repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
googleapis/gax-kotlin
examples-android/app/src/main/java/com/google/api/kgax/examples/grpc/LanguageRetryActivity.kt
1
2969
/* * Copyright 2018 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.api.kgax.examples.grpc import android.os.Bundle import android.support.test.espresso.idling.CountingIdlingResource import android.util.Log import com.google.api.kgax.Retry import com.google.api.kgax.RetryContext import com.google.api.kgax.grpc.StubFactory import com.google.cloud.language.v1.AnalyzeEntitiesRequest import com.google.cloud.language.v1.Document import com.google.cloud.language.v1.LanguageServiceGrpc import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlin.coroutines.CoroutineContext /** * Kotlin example showcasing client side retries using KGax with gRPC and the * Google Natural Language API. */ class LanguageRetryActivity : AbstractExampleActivity<LanguageServiceGrpc.LanguageServiceFutureStub>( CountingIdlingResource("LanguageRetry") ) { lateinit var job: Job override val coroutineContext: CoroutineContext get() = Dispatchers.Main + job override val factory = StubFactory( LanguageServiceGrpc.LanguageServiceFutureStub::class, "language.googleapis.com", 443 ) override val stub by lazy { applicationContext.resources.openRawResource(R.raw.sa).use { factory.fromServiceAccount( it, listOf("https://www.googleapis.com/auth/cloud-platform") ) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) job = Job() // call the api launch(Dispatchers.Main) { val response = stub.prepare { withRetry(RetryForever) }.execute { it -> it.analyzeEntities( AnalyzeEntitiesRequest.newBuilder().apply { document = Document.newBuilder().apply { content = "Hi there Joe" type = Document.Type.PLAIN_TEXT }.build() }.build() ) } updateUIWithExampleResult(response.toString()) } } } object RetryForever : Retry { override fun retryAfter(error: Throwable, context: RetryContext): Long? { Log.i("Retry", "Will attempt retry #${context.numberOfAttempts}") // retry after a 500 ms delay return 500 } }
apache-2.0
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/tmdb/movie/get/MovieGetProductionCompany.kt
1
806
package uk.co.ourfriendirony.medianotifier.clients.tmdb.movie.get import com.fasterxml.jackson.annotation.* @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder("id", "logo_path", "name", "origin_country") class MovieGetProductionCompany { @get:JsonProperty("id") @set:JsonProperty("id") @JsonProperty("id") var id: Int? = null @get:JsonProperty("logo_path") @set:JsonProperty("logo_path") @JsonProperty("logo_path") var logoPath: String? = null @get:JsonProperty("name") @set:JsonProperty("name") @JsonProperty("name") var name: String? = null @get:JsonProperty("origin_country") @set:JsonProperty("origin_country") @JsonProperty("origin_country") var originCountry: String? = null }
apache-2.0
noties/Markwon
app-sample/src/main/java/io/noties/markwon/app/samples/html/InspectHtmlTextSample.kt
1
1742
package io.noties.markwon.app.samples.html import android.text.style.URLSpan import io.noties.markwon.Markwon import io.noties.markwon.MarkwonVisitor import io.noties.markwon.app.sample.ui.MarkwonTextViewSample import io.noties.markwon.html.HtmlPlugin import io.noties.markwon.html.HtmlTag import io.noties.markwon.html.MarkwonHtmlRenderer import io.noties.markwon.html.TagHandler import io.noties.markwon.sample.annotations.MarkwonArtifact import io.noties.markwon.sample.annotations.MarkwonSampleInfo import io.noties.markwon.sample.annotations.Tag @MarkwonSampleInfo( id = "20210201140501", title = "Inspect text", description = "Inspect text content of a `HTML` node", artifacts = [MarkwonArtifact.HTML], tags = [Tag.html] ) class InspectHtmlTextSample : MarkwonTextViewSample() { override fun render() { val md = """ <p>lorem ipsum</p> <div class="custom-youtube-player">https://www.youtube.com/watch?v=abcdefgh</div> """.trimIndent() val markwon = Markwon.builder(context) .usePlugin(HtmlPlugin.create { it.addHandler(DivHandler()) }) .build() markwon.setMarkdown(textView, md) } class DivHandler : TagHandler() { override fun handle(visitor: MarkwonVisitor, renderer: MarkwonHtmlRenderer, tag: HtmlTag) { val attr = tag.attributes()["class"] ?: return if (attr.contains(CUSTOM_CLASS)) { val text = visitor.builder().substring(tag.start(), tag.end()) visitor.builder().setSpan( URLSpan(text), tag.start(), tag.end() ) } } override fun supportedTags(): Collection<String> = setOf("div") companion object { const val CUSTOM_CLASS = "custom-youtube-player" } } }
apache-2.0
quarkusio/quarkus
integration-tests/hibernate-orm-panache-kotlin/src/main/kotlin/io/quarkus/it/panache/kotlin/TestEndpoint.kt
1
42770
package io.quarkus.it.panache.kotlin import io.quarkus.hibernate.orm.panache.kotlin.PanacheQuery import io.quarkus.panache.common.Page import io.quarkus.panache.common.Parameters import io.quarkus.panache.common.Sort import io.quarkus.panache.common.exception.PanacheQueryException import org.hibernate.engine.spi.SelfDirtinessTracker import org.hibernate.jpa.QueryHints import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.fail import java.lang.UnsupportedOperationException import java.lang.reflect.Field import java.lang.reflect.Method import java.util.UUID import java.util.stream.Collectors import java.util.stream.Stream import javax.inject.Inject import javax.persistence.LockModeType import javax.persistence.NoResultException import javax.persistence.NonUniqueResultException import javax.persistence.PersistenceException import javax.transaction.Transactional import javax.ws.rs.GET import javax.ws.rs.Path import javax.ws.rs.Produces import javax.ws.rs.core.MediaType import javax.xml.bind.annotation.XmlAttribute import javax.xml.bind.annotation.XmlElements import javax.xml.bind.annotation.XmlTransient /** * Various tests covering Panache functionality. All tests should work in both standard JVM and in native mode. */ @Path("test") class TestEndpoint { @GET @Path("model") @Transactional fun testModel(): String { Person.flush() Assertions.assertNotNull(Person.getEntityManager()) Assertions.assertDoesNotThrow { Person.findById(Long.MIN_VALUE) } Assertions.assertDoesNotThrow { Person.find("name = ?1", UUID.randomUUID().toString()).firstResult() } Assertions.assertThrows(NoResultException::class.java, { Person.find("name = ?1", UUID.randomUUID().toString()).singleResult() }) var persons: List<Person> = Person.findAll().list() Assertions.assertEquals(0, persons.size) persons = Person.listAll() Assertions.assertEquals(0, persons.size) var personStream = Person.findAll().stream() Assertions.assertEquals(0, personStream.count()) personStream = Person.streamAll() Assertions.assertEquals(0, personStream.count()) try { Person.findAll().singleResult() Assertions.fail<Any>("singleResult should have thrown") } catch (x: NoResultException) { } Assertions.assertNull(Person.findAll().firstResult()) var person: Person = makeSavedPerson() Assertions.assertNotNull(person.id) Assertions.assertEquals(1, Person.count()) Assertions.assertEquals(1, Person.count("name = ?1", "stef")) Assertions.assertEquals(1, Person.count("name = :name", Parameters.with("name", "stef").map())) Assertions.assertEquals(1, Person.count("name = :name", Parameters.with("name", "stef"))) Assertions.assertEquals(1, Person.count("name", "stef")) Assertions.assertEquals(1, Dog.count()) Assertions.assertEquals(1, person.dogs.size) persons = Person.findAll().list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = Person.listAll() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) personStream = Person.findAll().stream() Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = Person.streamAll() Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) Assertions.assertEquals(person, Person.findAll().firstResult()) Assertions.assertEquals(person, Person.findAll().singleResult()) persons = Person.find("name = ?1", "stef").list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = Person.find("name = ?1", "stef").withLock(LockModeType.PESSIMISTIC_READ).list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) // next calls to this query will be cached persons = Person.find("name = ?1", "stef").withHint(QueryHints.HINT_CACHEABLE, "true").list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = Person.list("name = ?1", "stef") Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = Person.find("name = :name", Parameters.with("name", "stef").map()).list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = Person.find("name = :name", Parameters.with("name", "stef")).list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = Person.list("name = :name", Parameters.with("name", "stef").map()) Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = Person.list("name = :name", Parameters.with("name", "stef")) Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = Person.find("name", "stef").list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) personStream = Person.find("name = ?1", "stef").stream() Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = Person.stream("name = ?1", "stef") Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = Person.stream("name = :name", Parameters.with("name", "stef").map()) Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = Person.stream("name = :name", Parameters.with("name", "stef")) Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = Person.find("name", "stef").stream() Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) Assertions.assertEquals(person, Person.find("name", "stef").firstResult()) Assertions.assertEquals(person, Person.find("name", "stef").singleResult()) var byId: Person? = person.id?.let { Person.findById(it) } Assertions.assertEquals(person, byId) Assertions.assertEquals("Person(id=${person.id}, name=${person.name}, status=${person.status})", byId.toString()) byId = person.id?.let { Person.findById(it, LockModeType.PESSIMISTIC_READ) } Assertions.assertEquals(person, byId) Assertions.assertEquals("Person(id=${person.id}, name=${person.name}, status=${person.status})", byId.toString()) Assertions.assertNotNull(person.dogs.toString()) person.delete() Assertions.assertEquals(0, Person.count()) person = makeSavedPerson() Assertions.assertEquals(1, Person.count()) Assertions.assertEquals(0, Person.delete("name = ?1", "emmanuel")) Assertions.assertEquals(1, Dog.delete("owner = ?1", person)) Assertions.assertEquals(1, Person.delete("name", "stef")) person = makeSavedPerson() Assertions.assertEquals(1, Dog.delete("owner = :owner", Parameters.with("owner", person).map())) Assertions.assertEquals(1, Person.delete("name", "stef")) person = makeSavedPerson() Assertions.assertEquals(1, Dog.delete("owner = :owner", Parameters.with("owner", person))) Assertions.assertEquals(1, Person.delete("name", "stef")) Assertions.assertEquals(0, Person.deleteAll()) makeSavedPerson() Assertions.assertEquals(1, Dog.deleteAll()) Assertions.assertEquals(1, Person.deleteAll()) testPersist(PersistTest.Iterable) testPersist(PersistTest.Stream) testPersist(PersistTest.Variadic) Assertions.assertEquals(6, Person.deleteAll()) testSorting() // paging for (i in 0..6) { makeSavedPerson(i.toString()) } testPaging(Person.findAll()) testPaging(Person.find("ORDER BY name")) try { Person.findAll().singleResult() Assertions.fail<Any>("singleResult should have thrown") } catch (x: NonUniqueResultException) { } Assertions.assertNotNull(Person.findAll().firstResult()) Assertions.assertEquals(7, Person.deleteAll()) testUpdate() // persistAndFlush val person1 = Person() person1.name = "testFLush1" person1.uniqueName = "unique" person1.persist() val person2 = Person() person2.name = "testFLush2" person2.uniqueName = "unique" try { person2.persistAndFlush() Assertions.fail<Any>() } catch (pe: PersistenceException) { // this is expected } return "OK" } private fun testUpdate() { makeSavedPerson("p1") makeSavedPerson("p2") var updateByIndexParameter: Int = Person.update("update from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1") Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") var updateByNamedParameter: Int = Person.update( "update from Person2 p set p.name = 'stefNEW' where p.name = :pName", Parameters.with("pName", "stefp2").map() ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, Person.deleteAll()) makeSavedPerson("p1") makeSavedPerson("p2") updateByIndexParameter = Person.update("from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1") Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") updateByNamedParameter = Person.update( "from Person2 p set p.name = 'stefNEW' where p.name = :pName", Parameters.with("pName", "stefp2").map() ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, Person.deleteAll()) makeSavedPerson("p1") makeSavedPerson("p2") updateByIndexParameter = Person.update("set name = 'stefNEW' where name = ?1", "stefp1") Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") updateByNamedParameter = Person.update( "set name = 'stefNEW' where name = :pName", Parameters.with("pName", "stefp2").map() ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, Person.deleteAll()) makeSavedPerson("p1") makeSavedPerson("p2") updateByIndexParameter = Person.update("name = 'stefNEW' where name = ?1", "stefp1") Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") updateByNamedParameter = Person.update( "name = 'stefNEW' where name = :pName", Parameters.with("pName", "stefp2").map() ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, Person.deleteAll()) makeSavedPerson("p1") makeSavedPerson("p2") updateByIndexParameter = Person.update("name = 'stefNEW' where name = ?1", "stefp1") Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") updateByNamedParameter = Person.update( "name = 'stefNEW' where name = :pName", Parameters.with("pName", "stefp2") ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, Person.deleteAll()) // Assertions.assertThrows(PanacheQueryException::class.java, { Person.update(null) }, // "PanacheQueryException should have thrown") Assertions.assertThrows( PanacheQueryException::class.java, { Person.update(" ") }, "PanacheQueryException should have thrown" ) } private fun testUpdateDAO() { makeSavedPerson("p1") makeSavedPerson("p2") var updateByIndexParameter: Int = personRepository.update( "update from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1" ) Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") var updateByNamedParameter: Int = personRepository.update( "update from Person2 p set p.name = 'stefNEW' where p.name = :pName", Parameters.with("pName", "stefp2").map() ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, personRepository.deleteAll()) makeSavedPerson("p1") makeSavedPerson("p2") updateByIndexParameter = personRepository.update("from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1") Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") updateByNamedParameter = personRepository.update( "from Person2 p set p.name = 'stefNEW' where p.name = :pName", Parameters.with("pName", "stefp2").map() ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, personRepository.deleteAll()) makeSavedPerson("p1") makeSavedPerson("p2") updateByIndexParameter = personRepository.update("set name = 'stefNEW' where name = ?1", "stefp1") Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") updateByNamedParameter = personRepository.update( "set name = 'stefNEW' where name = :pName", Parameters.with("pName", "stefp2").map() ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, personRepository.deleteAll()) makeSavedPerson("p1") makeSavedPerson("p2") updateByIndexParameter = personRepository.update("name = 'stefNEW' where name = ?1", "stefp1") Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") updateByNamedParameter = personRepository.update( "name = 'stefNEW' where name = :pName", Parameters.with("pName", "stefp2").map() ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, personRepository.deleteAll()) makeSavedPerson("p1") makeSavedPerson("p2") updateByIndexParameter = personRepository.update("name = 'stefNEW' where name = ?1", "stefp1") Assertions.assertEquals(1, updateByIndexParameter, "More than one Person updated") updateByNamedParameter = personRepository.update( "name = 'stefNEW' where name = :pName", Parameters.with("pName", "stefp2") ) Assertions.assertEquals(1, updateByNamedParameter, "More than one Person updated") Assertions.assertEquals(2, personRepository.deleteAll()) // Assertions.assertThrows(PanacheQueryException::class.java, { personDao.update(null) }, // "PanacheQueryException should have thrown") Assertions.assertThrows( PanacheQueryException::class.java, { personRepository.update(" ") }, "PanacheQueryException should have thrown" ) } private fun testSorting() { val person1 = Person() person1.name = "stef" person1.status = Status.LIVING person1.persist() val person2 = Person() person2.name = "stef" person2.status = Status.DECEASED person2.persist() val person3 = Person() person3.name = "emmanuel" person3.status = Status.LIVING person3.persist() val sort1 = Sort.by("name", "status") val order1: List<Person> = listOf(person3, person2, person1) var list: List<Person?> = Person.findAll(sort1).list() Assertions.assertEquals(order1, list) list = Person.listAll(sort1) Assertions.assertEquals(order1, list) list = Person.streamAll(sort1).collect(Collectors.toList()) Assertions.assertEquals(order1, list) val sort2 = Sort.descending("name", "status") val order2: List<Person> = listOf(person1, person2) list = Person.find("name", sort2, "stef").list() Assertions.assertEquals(order2, list) list = Person.list("name", sort2, "stef") Assertions.assertEquals(order2, list) list = Person.stream("name", sort2, "stef").collect(Collectors.toList()) Assertions.assertEquals(order2, list) list = Person.find("name = :name", sort2, Parameters.with("name", "stef").map()).list() Assertions.assertEquals(order2, list) list = Person.list("name = :name", sort2, Parameters.with("name", "stef").map()) Assertions.assertEquals(order2, list) list = Person.stream("name = :name", sort2, Parameters.with("name", "stef").map()) .collect(Collectors.toList()) Assertions.assertEquals(order2, list) list = Person.find("name = :name", sort2, Parameters.with("name", "stef")).list() Assertions.assertEquals(order2, list) list = Person.list("name = :name", sort2, Parameters.with("name", "stef")) Assertions.assertEquals(order2, list) list = Person.stream("name = :name", sort2, Parameters.with("name", "stef")).collect(Collectors.toList()) Assertions.assertEquals(order2, list) Assertions.assertEquals(3, Person.deleteAll()) } private fun makeSavedPerson(suffix: String): Person { val person = Person() person.name = "stef$suffix" person.status = Status.LIVING person.address = Address("stef street") person.address?.persist() person.persist() return person } private fun makeSavedPerson(): Person { val person: Person = makeSavedPerson("") val dog = Dog("octave", "dalmatian") dog.owner = person person.dogs.add(dog) dog.persist() return person } private fun testPersist(persistTest: PersistTest) { val person1 = Person() person1.name = "stef1" val person2 = Person() person2.name = "stef2" Assertions.assertFalse(person1.isPersistent()) Assertions.assertFalse(person2.isPersistent()) when (persistTest) { PersistTest.Iterable -> Person.persist(listOf(person1, person2)) PersistTest.Stream -> Person.persist(Stream.of(person1, person2)) PersistTest.Variadic -> Person.persist(person1, person2) } Assertions.assertTrue(person1.isPersistent()) Assertions.assertTrue(person2.isPersistent()) } @Inject lateinit var personRepository: PersonRepository @Inject lateinit var dogDao: DogDao @Inject lateinit var addressDao: AddressDao @GET @Path("model-dao") @Transactional fun testModelDao(): String { personRepository.flush() Assertions.assertNotNull(personRepository.getEntityManager()) var persons = personRepository.findAll().list() Assertions.assertEquals(0, persons.size) var personStream = personRepository.findAll().stream() Assertions.assertEquals(0, personStream.count()) try { personRepository.findAll().singleResult() Assertions.fail<Any>("singleResult should have thrown") } catch (x: NoResultException) { } Assertions.assertNull(personRepository.findAll().firstResult()) var person: Person = makeSavedPersonDao() Assertions.assertNotNull(person.id) Assertions.assertEquals(1, personRepository.count()) Assertions.assertEquals(1, personRepository.count("name = ?1", "stef")) Assertions.assertEquals(1, personRepository.count("name = :name", Parameters.with("name", "stef").map())) Assertions.assertEquals(1, personRepository.count("name = :name", Parameters.with("name", "stef"))) Assertions.assertEquals(1, personRepository.count("name", "stef")) Assertions.assertEquals(1, dogDao.count()) Assertions.assertEquals(1, person.dogs.size) persons = personRepository.findAll().list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = personRepository.listAll() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) personStream = personRepository.findAll().stream() Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = personRepository.streamAll() Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) Assertions.assertEquals(person, personRepository.findAll().firstResult()) Assertions.assertEquals(person, personRepository.findAll().singleResult()) persons = personRepository.find("name = ?1", "stef").list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = personRepository.find("name = ?1", "stef").withLock(LockModeType.PESSIMISTIC_READ).list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = personRepository.list("name = ?1", "stef") Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = personRepository.find("name = :name", Parameters.with("name", "stef").map()).list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = personRepository.find("name = :name", Parameters.with("name", "stef")).list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = personRepository.list("name = :name", Parameters.with("name", "stef").map()) Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = personRepository.list("name = :name", Parameters.with("name", "stef")) Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) persons = personRepository.find("name", "stef").list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals(person, persons[0]) personStream = personRepository.find("name = ?1", "stef").stream() Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = personRepository.stream("name = ?1", "stef") Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = personRepository.stream("name = :name", Parameters.with("name", "stef").map()) Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = personRepository.stream("name = :name", Parameters.with("name", "stef")) Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) personStream = personRepository.find("name", "stef").stream() Assertions.assertEquals(persons, personStream.collect(Collectors.toList())) Assertions.assertEquals(person, personRepository.find("name", "stef").firstResult()) Assertions.assertEquals(person, personRepository.find("name", "stef").singleResult()) var byId = person.id?.let { personRepository.findById(it) } Assertions.assertEquals(person, byId) byId = person.id?.let { personRepository.findById(it, LockModeType.PESSIMISTIC_READ) } Assertions.assertEquals(person, byId) personRepository.delete(person) Assertions.assertEquals(0, personRepository.count()) person = makeSavedPersonDao() Assertions.assertEquals(1, personRepository.count()) Assertions.assertEquals(0, personRepository.delete("name = ?1", "emmanuel")) Assertions.assertEquals(1, dogDao.delete("owner = ?1", person)) Assertions.assertEquals(1, personRepository.delete("name", "stef")) person = makeSavedPerson() Assertions.assertEquals(1, dogDao.delete("owner = :owner", Parameters.with("owner", person).map())) Assertions.assertEquals(1, personRepository.delete("name", "stef")) person = makeSavedPerson() Assertions.assertEquals(1, dogDao.delete("owner = :owner", Parameters.with("owner", person))) Assertions.assertEquals(1, personRepository.delete("name", "stef")) Assertions.assertEquals(0, personRepository.deleteAll()) makeSavedPersonDao() Assertions.assertEquals(1, dogDao.deleteAll()) Assertions.assertEquals(1, personRepository.deleteAll()) testPersistDao(PersistTest.Iterable) testPersistDao(PersistTest.Stream) testPersistDao(PersistTest.Variadic) Assertions.assertEquals(6, personRepository.deleteAll()) testSortingDao() // paging for (i in 0..6) { makeSavedPersonDao(i.toString()) } testPaging(personRepository.findAll()) testPaging(personRepository.find("ORDER BY name")) try { personRepository.findAll().singleResult() Assertions.fail<Any>("singleResult should have thrown") } catch (x: NonUniqueResultException) { } Assertions.assertNotNull(personRepository.findAll().firstResult()) Assertions.assertEquals(7, personRepository.deleteAll()) testUpdateDAO() // flush val person1 = Person() person1.name = "testFlush1" person1.uniqueName = "unique" personRepository.persist(person1) val person2 = Person() person2.name = "testFlush2" person2.uniqueName = "unique" try { personRepository.persistAndFlush(person2) Assertions.fail<Any>() } catch (pe: PersistenceException) { // this is expected } return "OK" } private fun testSortingDao() { val person1 = Person() person1.name = "stef" person1.status = Status.LIVING personRepository.persist(person1) val person2 = Person() person2.name = "stef" person2.status = Status.DECEASED personRepository.persist(person2) val person3 = Person() person3.name = "emmanuel" person3.status = Status.LIVING personRepository.persist(person3) val sort1 = Sort.by("name", "status") val order1: List<Person> = listOf(person3, person2, person1) var list = personRepository.findAll(sort1).list() Assertions.assertEquals(order1, list) list = personRepository.listAll(sort1) Assertions.assertEquals(order1, list) list = personRepository.streamAll(sort1).collect(Collectors.toList()) Assertions.assertEquals(order1, list) val sort2 = Sort.descending("name", "status") val order2: List<Person> = listOf(person1, person2) list = personRepository.find("name", sort2, "stef").list() Assertions.assertEquals(order2, list) list = personRepository.list("name", sort2, "stef") Assertions.assertEquals(order2, list) list = personRepository.stream("name", sort2, "stef").collect(Collectors.toList()) Assertions.assertEquals(order2, list) list = personRepository.find("name = :name", sort2, Parameters.with("name", "stef").map()).list() Assertions.assertEquals(order2, list) list = personRepository.list("name = :name", sort2, Parameters.with("name", "stef").map()) Assertions.assertEquals(order2, list) list = personRepository.stream("name = :name", sort2, Parameters.with("name", "stef").map()).collect(Collectors.toList()) Assertions.assertEquals(order2, list) list = personRepository.find("name = :name", sort2, Parameters.with("name", "stef")).list() Assertions.assertEquals(order2, list) list = personRepository.list("name = :name", sort2, Parameters.with("name", "stef")) Assertions.assertEquals(order2, list) list = personRepository.stream("name = :name", sort2, Parameters.with("name", "stef")).collect(Collectors.toList()) Assertions.assertEquals(order2, list) Assertions.assertEquals(3, Person.deleteAll()) } internal enum class PersistTest { Iterable, Variadic, Stream } private fun testPersistDao(persistTest: PersistTest) { val person1 = Person() person1.name = "stef1" val person2 = Person() person2.name = "stef2" Assertions.assertFalse(person1.isPersistent()) Assertions.assertFalse(person2.isPersistent()) when (persistTest) { PersistTest.Iterable -> personRepository.persist(listOf(person1, person2)) PersistTest.Stream -> personRepository.persist(Stream.of(person1, person2)) PersistTest.Variadic -> personRepository.persist(person1, person2) } Assertions.assertTrue(person1.isPersistent()) Assertions.assertTrue(person2.isPersistent()) } private fun makeSavedPersonDao(suffix: String): Person { val person = Person() person.name = "stef$suffix" person.status = Status.LIVING person.address = Address("stef street") addressDao.persist(person.address!!) personRepository.persist(person) return person } private fun makeSavedPersonDao(): Person { val person: Person = makeSavedPersonDao("") val dog = Dog("octave", "dalmatian") dog.owner = person person.dogs.add(dog) dogDao.persist(dog) return person } private fun testPaging(query: PanacheQuery<Person>) { // ints var persons: List<Person> = query.page(0, 3).list() Assertions.assertEquals(3, persons.size) Assertions.assertEquals("stef0", persons[0].name) Assertions.assertEquals("stef1", persons[1].name) Assertions.assertEquals("stef2", persons[2].name) persons = query.page(1, 3).list() Assertions.assertEquals(3, persons.size) Assertions.assertEquals("stef3", persons[0].name) Assertions.assertEquals("stef4", persons[1].name) Assertions.assertEquals("stef5", persons[2].name) persons = query.page(2, 3).list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals("stef6", persons[0].name) persons = query.page(2, 4).list() Assertions.assertEquals(0, persons.size) // page var page = Page(3) persons = query.page(page).list() Assertions.assertEquals(3, persons.size) Assertions.assertEquals("stef0", persons[0].name) Assertions.assertEquals("stef1", persons[1].name) Assertions.assertEquals("stef2", persons[2].name) page = page.next() persons = query.page(page).list() Assertions.assertEquals(3, persons.size) Assertions.assertEquals("stef3", persons[0].name) Assertions.assertEquals("stef4", persons[1].name) Assertions.assertEquals("stef5", persons[2].name) page = page.next() persons = query.page(page).list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals("stef6", persons[0].name) page = page.next() persons = query.page(page).list() Assertions.assertEquals(0, persons.size) // query paging page = Page(3) persons = query.page(page).list() Assertions.assertEquals(3, persons.size) Assertions.assertEquals("stef0", persons[0].name) Assertions.assertEquals("stef1", persons[1].name) Assertions.assertEquals("stef2", persons[2].name) Assertions.assertTrue(query.hasNextPage()) Assertions.assertFalse(query.hasPreviousPage()) persons = query.nextPage().list() Assertions.assertEquals(1, query.page().index) Assertions.assertEquals(3, query.page().size) Assertions.assertEquals(3, persons.size) Assertions.assertEquals("stef3", persons[0].name) Assertions.assertEquals("stef4", persons[1].name) Assertions.assertEquals("stef5", persons[2].name) Assertions.assertTrue(query.hasNextPage()) Assertions.assertTrue(query.hasPreviousPage()) persons = query.nextPage().list() Assertions.assertEquals(1, persons.size) Assertions.assertEquals("stef6", persons[0].name) Assertions.assertFalse(query.hasNextPage()) Assertions.assertTrue(query.hasPreviousPage()) persons = query.nextPage().list() Assertions.assertEquals(0, persons.size) Assertions.assertEquals(7, query.count()) Assertions.assertEquals(3, query.pageCount()) } @GET @Path("accessors") @Throws(NoSuchMethodException::class, SecurityException::class) fun testAccessors(): String { checkMethod(AccessorEntity::class.java, "getString", String::class.java) checkMethod(AccessorEntity::class.java, "getBool", Boolean::class.javaPrimitiveType) checkMethod(AccessorEntity::class.java, "getB", Byte::class.javaPrimitiveType) checkMethod(AccessorEntity::class.java, "getC", Char::class.javaPrimitiveType) checkMethod(AccessorEntity::class.java, "getS", Short::class.javaPrimitiveType) checkMethod(AccessorEntity::class.java, "getI", Int::class.javaPrimitiveType) checkMethod(AccessorEntity::class.java, "getL", Long::class.javaPrimitiveType) checkMethod(AccessorEntity::class.java, "getF", Float::class.javaPrimitiveType) checkMethod(AccessorEntity::class.java, "getD", Double::class.javaPrimitiveType) checkMethod(AccessorEntity::class.java, "getT", Any::class.java) checkMethod(AccessorEntity::class.java, "getT2", Any::class.java) checkMethod(AccessorEntity::class.java, "setString", Void.TYPE, String::class.java) checkMethod(AccessorEntity::class.java, "setBool", Void.TYPE, Boolean::class.javaPrimitiveType!!) checkMethod(AccessorEntity::class.java, "setC", Void.TYPE, Char::class.javaPrimitiveType!!) checkMethod(AccessorEntity::class.java, "setS", Void.TYPE, Short::class.javaPrimitiveType!!) checkMethod(AccessorEntity::class.java, "setI", Void.TYPE, Int::class.javaPrimitiveType!!) checkMethod(AccessorEntity::class.java, "setL", Void.TYPE, Long::class.javaPrimitiveType!!) checkMethod(AccessorEntity::class.java, "setF", Void.TYPE, Float::class.javaPrimitiveType!!) checkMethod(AccessorEntity::class.java, "setD", Void.TYPE, Double::class.javaPrimitiveType!!) checkMethod(AccessorEntity::class.java, "setT", Void.TYPE, Any::class.java) checkMethod(AccessorEntity::class.java, "setT2", Void.TYPE, Any::class.java) // Now check that accessors are called val entity = AccessorEntity() val b: Byte = entity.b Assertions.assertEquals(1, entity.getBCalls) entity.i = 2 Assertions.assertEquals(1, entity.setICalls) // accessors inside the entity itself entity.method() Assertions.assertEquals(2, entity.getBCalls) Assertions.assertEquals(2, entity.setICalls) Assertions.assertThrows(UnsupportedOperationException::class.java) { entity.l } Assertions.assertThrows(UnsupportedOperationException::class.java) { entity.l = 42 } return "OK" } private fun checkMethod(klass: Class<*>, name: String, returnType: Class<*>?, vararg params: Class<*>) { val method = klass.getMethod(name, *params) Assertions.assertEquals(returnType, method.returnType) } @GET @Path("model1") @Transactional fun testModel1(): String { Person.deleteAll() Assertions.assertEquals(0, Person.count()) val person: Person = makeSavedPerson("") val trackingPerson = person as SelfDirtinessTracker var dirtyAttributes = trackingPerson.`$$_hibernate_getDirtyAttributes`() Assertions.assertEquals(0, dirtyAttributes.size) person.name = "1" dirtyAttributes = trackingPerson.`$$_hibernate_getDirtyAttributes`() Assertions.assertEquals(1, dirtyAttributes.size) Assertions.assertEquals(1, Person.count()) return "OK" } @GET @Path("model2") @Transactional fun testModel2(): String { Assertions.assertEquals(1, Person.count()) val person = Person.findAll().firstResult() Assertions.assertEquals("1", person?.name) if (person != null) { person.name = "2" } return "OK" } @GET @Path("model3") @Transactional fun testModel3(): String { Assertions.assertEquals(1, Person.count()) val person = Person.findAll().firstResult() Assertions.assertEquals("2", person?.name) Dog.deleteAll() Person.deleteAll() Address.deleteAll() Assertions.assertEquals(0, Person.count()) return "OK" } @Produces(MediaType.APPLICATION_XML) @GET @Path("ignored-properties") fun ignoredProperties(): Person { Person::class.java.getMethod("\$\$_hibernate_read_id") Person::class.java.getMethod("\$\$_hibernate_read_name") try { Person::class.java.getMethod("\$\$_hibernate_read_persistent") Assertions.fail<Any>() } catch (e: NoSuchMethodException) { } // no need to persist it, we can fake it val person = Person() person.id = 666L person.name = "Eddie" person.status = Status.DECEASED return person } @Inject lateinit var bug5274EntityRepository: Bug5274EntityRepository @GET @Path("5274") @Transactional fun testBug5274(): String { bug5274EntityRepository.count() return "OK" } @Inject lateinit var bug5885EntityRepository: Bug5885EntityRepository @GET @Path("5885") @Transactional fun testBug5885(): String { bug5885EntityRepository.findById(1L) return "OK" } @GET @Path("testJaxbAnnotationTransfer") fun testJaxbAnnotationTransfer(): String { // Test for fix to this bug: https://github.com/quarkusio/quarkus/issues/6021 // Ensure that any JAX-B annotations are properly moved to generated getters var m: Method = JAXBEntity::class.java.getMethod("getNamedAnnotatedProp") var annotation = m.getAnnotation(XmlAttribute::class.java) Assertions.assertNotNull(annotation) Assertions.assertEquals("Named", annotation.name) Assertions.assertNull(m.getAnnotation(XmlTransient::class.java)) m = JAXBEntity::class.java.getMethod("getDefaultAnnotatedProp") annotation = m.getAnnotation(XmlAttribute::class.java) Assertions.assertNotNull(annotation) Assertions.assertEquals("##default", annotation.name) Assertions.assertNull(m.getAnnotation(XmlTransient::class.java)) m = JAXBEntity::class.java.getMethod("getUnAnnotatedProp") Assertions.assertNull(m.getAnnotation(XmlAttribute::class.java)) Assertions.assertNull(m.getAnnotation(XmlTransient::class.java)) m = JAXBEntity::class.java.getMethod("getTransientProp") Assertions.assertNull(m.getAnnotation(XmlAttribute::class.java)) Assertions.assertNotNull(m.getAnnotation(XmlTransient::class.java)) m = JAXBEntity::class.java.getMethod("getArrayAnnotatedProp") Assertions.assertNull(m.getAnnotation(XmlTransient::class.java)) val elementsAnnotation = m.getAnnotation(XmlElements::class.java) Assertions.assertNotNull(elementsAnnotation) Assertions.assertNotNull(elementsAnnotation.value) Assertions.assertEquals(2, elementsAnnotation.value.size) Assertions.assertEquals("array1", elementsAnnotation.value[0].name) Assertions.assertEquals("array2", elementsAnnotation.value[1].name) // Ensure that all original fields were labeled @XmlTransient and had their original JAX-B annotations removed ensureFieldSanitized("namedAnnotatedProp") ensureFieldSanitized("transientProp") ensureFieldSanitized("defaultAnnotatedProp") ensureFieldSanitized("unAnnotatedProp") ensureFieldSanitized("arrayAnnotatedProp") return "OK" } private fun ensureFieldSanitized(fieldName: String) { val f: Field = JAXBEntity::class.java.getField(fieldName) Assertions.assertNull(f.getAnnotation(XmlAttribute::class.java)) Assertions.assertNotNull(f.getAnnotation(XmlTransient::class.java)) } @GET @Path("9036") @Transactional fun testBug9036(): String { Person.deleteAll() val emptyPerson = Person() emptyPerson.persist() val deadPerson = Person() deadPerson.name = "Stef" deadPerson.status = Status.DECEASED deadPerson.persist() val livePerson = Person() livePerson.name = "Stef" livePerson.status = Status.LIVING livePerson.persist() Assertions.assertEquals(3, Person.count()) Assertions.assertEquals(3, Person.listAll().size) // should be filtered val query = Person.findAll(Sort.by("id")) .filter("Person.isAlive") .filter("Person.hasName", Parameters.with("name", "Stef")) Assertions.assertEquals(1, query.count()) Assertions.assertEquals(1, query.list().size) Assertions.assertEquals(livePerson, query.list()[0]) Assertions.assertEquals(1, query.stream().count()) Assertions.assertEquals(livePerson, query.firstResult()) Assertions.assertEquals(livePerson, query.singleResult()) // these should be unaffected Assertions.assertEquals(3, Person.count()) Assertions.assertEquals(3, Person.listAll().size) Person.deleteAll() return "OK" } }
apache-2.0
quarkusio/quarkus
integration-tests/mongodb-panache-kotlin/src/main/kotlin/io/quarkus/it/mongodb/panache/bugs/LinkedEntity.kt
1
372
package io.quarkus.it.mongodb.panache.bugs import io.quarkus.mongodb.panache.kotlin.PanacheMongoCompanion import io.quarkus.mongodb.panache.kotlin.PanacheMongoEntity import org.bson.types.ObjectId class LinkedEntity : PanacheMongoEntity() { companion object : PanacheMongoCompanion<LinkedEntity> var name: String? = null var myForeignId: ObjectId? = null }
apache-2.0
google/prefab
api/src/main/kotlin/com/google/prefab/api/PrebuiltLibrary.kt
1
1520
/* * 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 java.nio.file.Path /** * A platform-specific library file in a module. * * @property[path] The path to the library file on disk. * @property[module]: The module associated with this library. * @property[platform] The [platform-specific data][PlatformDataInterface] * describing the library. */ data class PrebuiltLibrary( val path: Path, val module: Module, val platform: PlatformDataInterface, ) { /** * The platform-specific library directory containing the library file. */ val directory: Path = path.parent /** * The path to the headers on disk. * * This is the path to the platform-specific include path if it exists. * Otherwise this is the path to the module's include path. */ val includePath: Path = directory.resolve("include").takeIf { it.toFile().exists() } ?: module.includePath }
apache-2.0
MyDogTom/detekt
detekt-sample-extensions/src/main/kotlin/io/gitlab/arturbosch/detekt/sample/extensions/reports/QualifiedNamesOutputReport.kt
1
430
package io.gitlab.arturbosch.detekt.sample.extensions.reports import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.OutputReport /** * @author Artur Bosch */ class QualifiedNamesOutputReport : OutputReport() { override var fileName: String = "fqNames" override val ending: String = "txt" override fun render(detektion: Detektion): String? { return qualifiedNamesReport(detektion) } }
apache-2.0
daemontus/glucose
core/src/main/java/com/glucose/util/RxUtils.kt
2
417
package com.glucose.util import com.github.daemontus.Result import com.github.daemontus.asError import com.github.daemontus.asOk import rx.Observable /** * Create an observable that will not throw an error, instead it will propagate it in form of * result object. */ fun <R> Observable<R>.asResult(): Observable<Result<R, Throwable>> = this.map { it.asOk<R, Throwable>() }.onErrorReturn { it.asError() }
mit
rei-m/android_hyakuninisshu
state/src/main/java/me/rei_m/hyakuninisshu/state/exam/action/FetchAllExamResultAction.kt
1
1277
/* * Copyright (c) 2020. Rei Matsushita * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package me.rei_m.hyakuninisshu.state.exam.action import me.rei_m.hyakuninisshu.state.core.Action import me.rei_m.hyakuninisshu.state.exam.model.ExamResult /** * 力試しの結果をすべて取得するアクション. */ sealed class FetchAllExamResultAction(override val error: Throwable? = null) : Action { class Success( val examResultList: List<ExamResult> ) : FetchAllExamResultAction() { override fun toString() = "$name(examResultList=$examResultList)" } class Failure(error: Throwable) : FetchAllExamResultAction(error) { override fun toString() = "$name(error=$error)" } override val name = "FetchAllExamResultAction" }
apache-2.0
RettyEng/redux-kt
redux-kt-core/src/main/kotlin/me/retty/reduxkt/Reducer.kt
1
376
package me.retty.reduxkt import me.retty.reduxkt.internal.utils.comp import me.retty.reduxkt.internal.utils.curry /** * Created by yusaka on 3/14/17. */ typealias Reducer<StateType> = (Action, StateType) -> StateType infix fun <T> Reducer<T>.compose(reducer: Reducer<T>): Reducer<T> = { action, state -> ((this curry action) comp (reducer curry (action)))(state) }
mit
pnemonic78/RemoveDuplicates
duplicates-android/app/src/main/java/com/github/duplicates/alarm/AlarmItem.kt
1
1619
/* * Copyright 2016, Moshe Waisberg * * 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.github.duplicates.alarm import com.github.duplicates.DaysOfWeek import com.github.duplicates.DuplicateItem import com.github.duplicates.DuplicateItemType /** * Duplicate alarm item. * * @author moshe.w */ class AlarmItem : DuplicateItem(DuplicateItemType.ALARM) { var activate: Int = 0 var alarmTime: Int = 0 var alertTime: Long = 0 var createTime: Long = 0 var isDailyBriefing: Boolean = false var name: String? = null var notificationType: Int = 0 var repeat: DaysOfWeek? = null var isSnoozeActivate: Boolean = false var snoozeDoneCount: Int = 0 var snoozeDuration: Int = 0 var snoozeRepeat: Int = 0 var soundTone: Int = 0 var soundType: Int = 0 var soundUri: String? = null var isSubdueActivate: Boolean = false var subdueDuration: Int = 0 var subdueTone: Int = 0 var subdueUri: Int = 0 var volume: Int = 0 override fun contains(s: CharSequence): Boolean { return name?.contains(s, true) ?: false } }
apache-2.0
rossdanderson/stateless4j
examples/kotlin/src/main/kotlin/com/github/rossdanderson/stateless4k/examples/State.kt
2
195
package com.github.rossdanderson.stateless4k.examples enum class State { OnHook, OffHook, AwaitingNumberInput, WithDialTone, Ringing, Connected, OnHold, Invalid }
apache-2.0
alashow/music-android
modules/base-android/src/main/java/tm/alashow/base/ui/utils/extensions/ActivityExtensions.kt
1
545
/* * Copyright (C) 2018, Alashov Berkeli * All rights reserved. */ package tm.alashow.base.ui.utils.extensions import android.app.Activity.RESULT_OK import android.content.Context import android.content.Intent import androidx.activity.result.contract.ActivityResultContract class CompleteTask : ActivityResultContract<Intent, Boolean>() { override fun createIntent(context: Context, input: Intent): Intent { return input } override fun parseResult(resultCode: Int, intent: Intent?): Boolean = resultCode == RESULT_OK }
apache-2.0
vilnius/tvarkau-vilniu
app/src/main/java/lt/vilnius/tvarkau/fragments/interactors/MultipleReportsMapInteractor.kt
1
241
package lt.vilnius.tvarkau.fragments.interactors import io.reactivex.Single import lt.vilnius.tvarkau.entity.Problem /** * @author Martynas Jurkus */ interface MultipleReportsMapInteractor { fun getReports(): Single<List<Problem>> }
mit
icanit/mangafeed
app/src/main/java/eu/kanade/tachiyomi/widget/preference/LoginPreference.kt
1
975
package eu.kanade.tachiyomi.widget.preference import android.content.Context import android.support.v4.content.ContextCompat import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceViewHolder import android.util.AttributeSet import eu.kanade.tachiyomi.R import kotlinx.android.synthetic.main.preference_widget_imageview.view.* class LoginPreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : Preference(context, attrs) { init { widgetLayoutResource = R.layout.preference_widget_imageview } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) holder.itemView.image_view.setImageResource(if (getPersistedString("").isNullOrEmpty()) android.R.color.transparent else R.drawable.ic_done_green_24dp) } override public fun notifyChanged() { super.notifyChanged() } }
apache-2.0
NooAn/bytheway
app/src/test/java/ru/a1024bits/bytheway/TranslationTest.kt
1
1315
package ru.a1024bits.bytheway import junit.framework.Assert import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import ru.a1024bits.bytheway.util.Translit /** * Created by Andrei_Gusenkov on 3/16/2018. */ @RunWith(JUnit4::class) class TranslationTest { @Test @Throws(Exception::class) fun testCitySlate() { val t = Translit() val s = "Рига" val s1 = "Riga" Assert.assertTrue(s1.toLowerCase().compareTo(t.cyr2lat(s).toLowerCase()) == 0) } @Test @Throws(Exception::class) fun testCitySlate2() { val t = Translit() val s = "Москва" val s1 = "Moskva" Assert.assertTrue(s1.toLowerCase().compareTo(t.cyr2lat(s).toLowerCase()) == 0) } @Test @Throws(Exception::class) fun testCitySlate3() { val t = Translit() val s = "Санкт" val s1 = "Sankt" Assert.assertTrue(s1.toLowerCase().compareTo(t.cyr2lat(s).toLowerCase()) == 0) } @Test @Throws(Exception::class) fun testCitySlate4() { val t = Translit() val s = "Хельсинки" val s1 = "Helsinki" // Assert.assertEquals(s1, t.cyr2lat(s)) //Assert.assertTrue(s1.toLowerCase().compareTo(t.cyr2lat(s).toLowerCase())) } }
mit
Aidanvii7/Toolbox
delegates-observable-rxjava/src/test/java/com/aidanvii/toolbox/delegates/observable/rxjava/RxFilterDecoratorTest.kt
1
4199
package com.aidanvii.toolbox.delegates.observable.rxjava import com.aidanvii.toolbox.assignedButNeverAccessed import com.aidanvii.toolbox.delegates.observable.doOnNext import com.aidanvii.toolbox.delegates.observable.filter import com.aidanvii.toolbox.delegates.observable.filterNotNull import com.aidanvii.toolbox.delegates.observable.filterNotNullWith import com.aidanvii.toolbox.delegates.observable.observable import com.aidanvii.toolbox.unusedValue import com.aidanvii.toolbox.unusedVariable import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import com.nhaarman.mockito_kotlin.verifyZeroInteractions import com.nhaarman.mockito_kotlin.whenever import org.amshove.kluent.mock import org.junit.Test @Suppress(assignedButNeverAccessed, unusedValue, unusedVariable) class RxFilterDecoratorTest { val mockPredicate = mock<(Int) -> Boolean>() val mockDoOnNext = mock<(propertyEvent: Int) -> Unit>() @Test fun `propagates values downstream when predicate returns true`() { whenever(mockPredicate(any())).thenReturn(true) val givenInitial = 1 val givenNext = 2 var property by observable(givenInitial) .toRx() .filter(mockPredicate) .doOnNext(mockDoOnNext) property = givenNext verify(mockDoOnNext).invoke(givenNext) verifyNoMoreInteractions(mockDoOnNext) } @Test fun `does not propagate values downstream when predicate returns false`() { whenever(mockPredicate(any())).thenReturn(false) val given = 1 var property by observable(given) .toRx() .filter(mockPredicate) .doOnNext(mockDoOnNext) property = given verifyZeroInteractions(mockDoOnNext) } @Test fun `propagates values downstream when given value is not null`() { val givenNull = null val givenNotNull = 2 var property by observable<Int?>(givenNull) .toRx() .filterNotNull() .doOnNext(mockDoOnNext) property = givenNotNull verify(mockDoOnNext).invoke(givenNotNull) verifyNoMoreInteractions(mockDoOnNext) } @Test fun `does not propagate values downstream when next given value is null`() { val givenNull = null var property by observable<Int?>(givenNull) .toRx() .filterNotNull() .doOnNext(mockDoOnNext) property = givenNull verifyZeroInteractions(mockDoOnNext) } @Test fun `propagates values downstream when given value is not null and predicate returns true`() { whenever(mockPredicate(any())).thenReturn(true) val givenNull = null val givenNotNull = 2 var property by observable<Int?>(givenNull) .toRx() .filterNotNullWith(mockPredicate) .doOnNext(mockDoOnNext) property = givenNotNull verify(mockPredicate).invoke(givenNotNull) verify(mockDoOnNext).invoke(givenNotNull) verifyNoMoreInteractions(mockDoOnNext) } @Test fun `does not propagate values downstream when given value is not null and predicate returns false`() { whenever(mockPredicate(any())).thenReturn(false) val givenNull = null val givenNotNull = 2 var property by observable<Int?>(givenNull) .toRx() .filterNotNullWith(mockPredicate) .doOnNext(mockDoOnNext) property = givenNotNull verify(mockPredicate).invoke(givenNotNull) verifyZeroInteractions(mockDoOnNext) } @Test fun `does not propagate values downstream when given value is null`() { whenever(mockPredicate(any())).thenReturn(true) val givenNull = null var property by observable<Int?>(givenNull) .toRx() .filterNotNullWith(mockPredicate) .doOnNext(mockDoOnNext) property = givenNull verifyZeroInteractions(mockDoOnNext, mockPredicate) } }
apache-2.0
dennism1997/BeachVolleyballWeather
app/src/main/java/com/moumou/beachvolleyballweather/SharedPreferencesHandler.kt
1
1447
package com.moumou.beachvolleyballweather import android.content.Context import android.support.v7.app.AlertDialog import android.support.v7.preference.PreferenceManager import com.google.gson.Gson import com.google.gson.JsonSyntaxException import com.google.gson.reflect.TypeToken import com.moumou.beachvolleyballweather.weather.WeatherLocation object SharedPreferencesHandler { val KEY_WEATHER_LOCATIONS = "WEATHERLOCATIONS" fun storeLocations(c : Context, l : ArrayList<WeatherLocation>) { val sharedPref = PreferenceManager.getDefaultSharedPreferences(c) val editor = sharedPref.edit() editor.putString(KEY_WEATHER_LOCATIONS, Gson().toJson(l)) editor.apply() } fun getLocations(c : Context) : ArrayList<WeatherLocation> { val sharedPref = PreferenceManager.getDefaultSharedPreferences(c) val s = sharedPref.getString(KEY_WEATHER_LOCATIONS, "") val type = object : TypeToken<ArrayList<WeatherLocation>>() {}.type if (s != "") { try { return Gson().fromJson<ArrayList<WeatherLocation>>(s, type) } catch (e : JsonSyntaxException) { AlertDialog.Builder(c).setMessage(c.getString(R.string.storage_parsing_error)).setPositiveButton( R.string.ok) { dialog, _ -> dialog.dismiss() }.show() } } return ArrayList() } }
mit
cicada-kt/cicada-jdbc-kt
src/main/kotlin/cn/org/cicada/jdbc/kt/dao/DaoProvider.kt
1
188
package cn.org.cicada.jdbc.kt.dao interface DaoProvider { fun update(sql: String, vararg params: Any?) fun <T> query(type: Class<T>, sql: String, vararg params: Any?) : List<T> }
mit
SchoolPower/SchoolPower-Android
app/src/main/java/com/carbonylgroup/schoolpower/data/Subject.kt
1
6721
/** * Copyright (C) 2019 SchoolPower Studio */ package com.carbonylgroup.schoolpower.data import com.carbonylgroup.schoolpower.utils.Utils import org.json.JSONObject import java.io.Serializable import java.util.* /* Sample: { "assignments": [ (AssignmentItem)... ], "expression": "1(A-E)", "startDate": "2017-08-31T16:00:00.000Z", "endDate": "2018-01-21T16:00:00.000Z", "finalGrades": { "X1": { "percent": "0.0", "letter": "--", "comment": null, "eval": "--", "startDate": 1515945600, "endDate": 1515945600 }, "T2": { "percent": "92.0", "letter": "A", "comment": "Some comments", "eval": "M", "startDate": 1510502400, "endDate": 1510502400 }, "T1": { "percent": "90.0", "letter": "A", "comment": "Some comments", "eval": "M", "startDate": 1504195200, "endDate": 1504195200 }, "S1": { "percent": "91.0", "letter": "A", "comment": null, "eval": "M", "startDate": 1504195200, "endDate": 1504195200 } }, "name": "Course Name", "roomName": "100", "teacher": { "firstName": "John", "lastName": "Doe", "email": null, "schoolPhone": null } } */ class Subject(json: JSONObject, utils: Utils) : Serializable { val name: String = json.getString("name") val teacherName: String = json.getJSONObject("teacher").let { obj -> obj.getString("firstName") + " " + obj.getString("lastName") } val teacherEmail: String = json.getJSONObject("teacher").optString("email") val blockLetter: String // init in code val roomNumber: String = json.getString("roomName") val assignments: ArrayList<AssignmentItem> = arrayListOf() val grades: HashMap<String, Grade> = hashMapOf() val startDate: Long val endDate: Long var margin = 0 private fun getAdjustedExpression(utils: Utils, blockLetterRaw: String): String { // Smart block display if (!utils.getPreferences().getBoolean("list_preference_even_odd_filter", false) || blockLetterRaw == "") return blockLetterRaw val blockStartIndex = blockLetterRaw.indexOf('(') val currentWeekIsEven = utils.getPreferences().getBoolean("list_preference_is_even_week", false) val blocksToDisplay = arrayListOf<String>() var oddEvenWeekFeatureEnabled = false // e.g. 1(A-J), 2(B-C,F,H) for (block in blockLetterRaw.substring(blockStartIndex + 1, blockLetterRaw.length - 1) .split(",")) { // A, B, C, D, E val odd = block.indexOf('A') != -1 || block.indexOf('B') != -1 || block.indexOf('C') != -1 || block.indexOf('D') != -1 || block.indexOf('E') != -1 // F, G, H, I, J val even = block.indexOf('F') != -1 || block.indexOf('G') != -1 || block.indexOf('H') != -1 || block.indexOf('I') != -1 || block.indexOf('J') != -1 if (even) oddEvenWeekFeatureEnabled = true if ((even && currentWeekIsEven) || (odd && !currentWeekIsEven)) blocksToDisplay.add(block) } if (oddEvenWeekFeatureEnabled) { return blockLetterRaw.substring(0, blockStartIndex + 1) + blocksToDisplay.joinToString(",") + ")" } else { return blockLetterRaw } } init { if (!json.isNull("assignments")) { val jsonAssignments = json.getJSONArray("assignments") (0 until jsonAssignments.length()).mapTo(assignments) { AssignmentItem(jsonAssignments.getJSONObject(it)) } } val categoriesWeights = CategoryWeightData(utils) if (!json.isNull("finalGrades")) { val finalGrades = json.getJSONObject("finalGrades") for (key in finalGrades.keys()) { val grade = finalGrades.getJSONObject(key) grades[key] = Grade(grade.getString("percent").toDouble().toInt().toString(), grade.getString("letter"), grade.getString("comment"), grade.getString("eval"), CalculatedGrade(this, key, categoriesWeights)) } } startDate = Utils.convertDateToTimestamp(json.getString("startDate")) endDate = Utils.convertDateToTimestamp(json.getString("endDate")) val blockLetterRaw = json.getString("expression") blockLetter = try { getAdjustedExpression(utils, blockLetterRaw) } catch (e: Exception) { blockLetterRaw } } // Call it when weights of categories have been changed. fun recalculateGrades(weights: CategoryWeightData) { for ((name, grade) in grades) { grade.calculatedGrade = CalculatedGrade(this, name, weights) } } // Compare `oldSubject` with this one and mark changed assignments fun markNewAssignments(oldSubject: Subject, utils: Utils) { // Mark new or changed assignments val newAssignmentListCollection = assignments val oldAssignmentListCollection = oldSubject.assignments for (item in newAssignmentListCollection) { // if no item in oldAssignmentListCollection has the same title, score and date as those of the new one, then the assignment should be marked. val found = oldAssignmentListCollection.any { it.title == item.title && it.score == item.score && it.date == item.date && !it.isNew } if (!found) { item.isNew = true margin = 0 val oldPercent = utils.getLatestTermGrade(oldSubject)?.getGrade() ?: continue val newPercent = utils.getLatestTermGrade(this)?.getGrade() ?: continue if (oldPercent != newPercent) margin = newPercent - oldPercent } } } fun getShortName() = Utils.getShortName(name) fun getLatestTermName(utils: Utils): String? = utils.getLatestTermName(this.grades) fun getLatestTermGrade(utils: Utils) = utils.getLatestTermGrade(this) }
gpl-3.0
SpryServers/sprycloud-android
src/main/java/com/nextcloud/client/logger/ui/LogsEmailSender.kt
2
3734
/* * Nextcloud Android client application * * @author Chris Narkiewicz * Copyright (C) 2019 Chris Narkiewicz <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.nextcloud.client.logger.ui import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.widget.Toast import androidx.core.content.FileProvider import com.nextcloud.client.core.AsyncRunner import com.nextcloud.client.core.Cancellable import com.nextcloud.client.core.Clock import com.nextcloud.client.logger.LogEntry import com.owncloud.android.R import java.io.File import java.io.FileWriter import java.util.TimeZone class LogsEmailSender(private val context: Context, private val clock: Clock, private val runner: AsyncRunner) { private companion object { const val LOGS_MIME_TYPE = "text/plain" } private class Task( private val context: Context, private val logs: List<LogEntry>, private val file: File, private val tz: TimeZone ) : Function0<Uri?> { override fun invoke(): Uri? { file.parentFile.mkdirs() val fo = FileWriter(file, false) logs.forEach { fo.write(it.toString(tz)) fo.write("\n") } fo.close() return FileProvider.getUriForFile(context, context.getString(R.string.file_provider_authority), file) } } private var task: Cancellable? = null fun send(logs: List<LogEntry>) { if (task == null) { val outFile = File(context.cacheDir, "attachments/logs.txt") task = runner.post(Task(context, logs, outFile, clock.tz), onResult = { task = null; send(it) }) } } fun stop() { if (task != null) { task?.cancel() task = null } } private fun send(uri: Uri?) { task = null val intent = Intent(Intent.ACTION_SEND_MULTIPLE) intent.putExtra(Intent.EXTRA_EMAIL, context.getString(R.string.mail_logger)) val subject = context.getString(R.string.log_send_mail_subject).format(context.getString(R.string.app_name)) intent.putExtra(Intent.EXTRA_SUBJECT, subject) intent.putExtra(Intent.EXTRA_TEXT, getPhoneInfo()) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK intent.type = LOGS_MIME_TYPE intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayListOf(uri)) try { context.startActivity(intent) } catch (ex: ActivityNotFoundException) { Toast.makeText(context, R.string.log_send_no_mail_app, Toast.LENGTH_SHORT).show() } } private fun getPhoneInfo(): String { return "Model: " + Build.MODEL + "\n" + "Brand: " + Build.BRAND + "\n" + "Product: " + Build.PRODUCT + "\n" + "Device: " + Build.DEVICE + "\n" + "Version-Codename: " + Build.VERSION.CODENAME + "\n" + "Version-Release: " + Build.VERSION.RELEASE } }
gpl-2.0
magnusja/libaums
libaums/src/main/java/me/jahnen/libaums/core/partition/PartitionTypes.kt
2
336
package me.jahnen.libaums.core.partition /** * Created by magnusja on 28/02/17. */ object PartitionTypes { const val UNKNOWN = -1 const val FAT12 = 0 const val FAT16 = 1 const val FAT32 = 2 const val LINUX_EXT = 3 const val APPLE_HFS_HFS_PLUS = 4 const val ISO9660 = 5 const val NTFS_EXFAT = 6 }
apache-2.0
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/quests/fixme_show/ShowFixme.kt
1
1645
package de.westnordost.streetcomplete.quests.fixme_show import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement class ShowFixme() : OsmFilterQuestType<List<String>>() { override val elementFilter = "nodes, ways, relations with fixme and fixme!=continue and highway!=proposed and railway!=proposed" + " and !fixme:requires_aerial_image " + " and !fixme:use_better_tagging_scheme " + " and !fixme:3d_tagging " override val commitMessage = "Handle fixme tag" override val icon = R.drawable.ic_quest_power override val isSplitWayEnabled = true override fun getTitle(tags: Map<String, String>) = R.string.quest_show_fixme override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>): Array<String> { val name = tags["fixme"] return if (name != null) arrayOf(name) else arrayOf() } override fun createForm() = ShowFixmeForm() override fun applyAnswerTo(answer: List<String>, changes: StringMapChangesBuilder) { val value = answer.first() if ("fixme:solved" == value) { //TODO: handle it without magic values changes.delete("fixme") } else { changes.add(value, "yes") } } override val wikiLink = "Key:fixme" override val questTypeAchievements: List<QuestTypeAchievement> get() = listOf() }
gpl-3.0
naosim/rtmjava
src/main/java/com/naosim/rtm/domain/repository/RtmAuthRepository.kt
1
373
package com.naosim.rtm.domain.repository import com.naosim.rtm.domain.model.auth.GetTokenResponse import com.naosim.rtm.domain.model.auth.* import java.util.* interface RtmAuthRepository { fun getFrob(): FrobUnAuthed fun getAuthUrl(frob: Frob): String fun getToken(frob: FrobAuthed): GetTokenResponse fun checkToken(token: Token): Optional<CheckedToken> }
mit
sephiroth74/android-target-tooltip
app/src/main/java/it/sephiroth/android/library/tooltip_demo/MainApplication.kt
1
850
package it.sephiroth.android.library.tooltip_demo import android.app.Application import timber.log.Timber // // ADOBE CONFIDENTIAL // __________________ // // Copyright 2017 Adobe // All Rights Reserved. // // NOTICE: All information contained herein is, and remains // the property of Adobe and its suppliers, if any. The intellectual // and technical concepts contained herein are proprietary to Adobe // and its suppliers and are protected by all applicable intellectual // property laws, including trade secret and copyright laws. // Dissemination of this information or reproduction of this material // is strictly forbidden unless prior written permission is obtained // from Adobe. // class MainApplication : Application() { override fun onCreate() { super.onCreate() Timber.plant(Timber.DebugTree()) } }
mit
stealthcode/RxJava
language-adaptors/rxjava-kotlin/src/test/kotlin/rx/lang/kotlin/BasicKotlinTests.kt
2
11680
/** * Copyright 2013 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.lang.kotlin import rx.Observable import org.junit.Test import rx.subscriptions.Subscriptions import org.mockito.Mockito.* import org.mockito.Matchers.* import rx.Observer import org.junit.Assert.* import rx.Notification import rx.Subscription import kotlin.concurrent.thread import rx.Observable.OnSubscribeFunc import rx.lang.kotlin.BasicKotlinTests.AsyncObservable import rx.Observable.OnSubscribe import rx.Subscriber /** * This class use plain Kotlin without extensions from the language adaptor */ public class BasicKotlinTests : KotlinTests() { [Test] public fun testCreate() { Observable.create(object:OnSubscribe<String> { override fun call(subscriber: Subscriber<in String>?) { subscriber!!.onNext("Hello") subscriber.onCompleted() } })!!.subscribe { result -> a!!.received(result) } verify(a, times(1))!!.received("Hello") } [Test] public fun testFilter() { Observable.from(listOf(1, 2, 3))!!.filter { it!! >= 2 }!!.subscribe(received()) verify(a, times(0))!!.received(1); verify(a, times(1))!!.received(2); verify(a, times(1))!!.received(3); } [Test] public fun testLast() { assertEquals("three", Observable.from(listOf("one", "two", "three"))!!.toBlockingObservable()!!.last()) } [Test] public fun testLastWithPredicate() { assertEquals("two", Observable.from(listOf("one", "two", "three"))!!.toBlockingObservable()!!.last { x -> x!!.length == 3 }) } [Test] public fun testMap1() { Observable.from(1)!!.map { v -> "hello_$v" }!!.subscribe(received()) verify(a, times(1))!!.received("hello_1") } [Test] public fun testMap2() { Observable.from(listOf(1, 2, 3))!!.map { v -> "hello_$v" }!!.subscribe((received())) verify(a, times(1))!!.received("hello_1") verify(a, times(1))!!.received("hello_2") verify(a, times(1))!!.received("hello_3") } [Test] public fun testMaterialize() { Observable.from(listOf(1, 2, 3))!!.materialize()!!.subscribe((received())) verify(a, times(4))!!.received(any(javaClass<Notification<Int>>())) verify(a, times(0))!!.error(any(javaClass<Exception>())) } [Test] public fun testMergeDelayError() { Observable.mergeDelayError( Observable.from(listOf(1, 2, 3)), Observable.merge( Observable.from(6), Observable.error(NullPointerException()), Observable.from(7) ), Observable.from(listOf(4, 5)) )!!.subscribe(received(), { e -> a!!.error(e) }) verify(a, times(1))!!.received(1) verify(a, times(1))!!.received(2) verify(a, times(1))!!.received(3) verify(a, times(1))!!.received(4) verify(a, times(1))!!.received(5) verify(a, times(1))!!.received(6) verify(a, times(0))!!.received(7) verify(a, times(1))!!.error(any(javaClass<NullPointerException>())) } [Test] public fun testMerge() { Observable.merge( Observable.from(listOf(1, 2, 3)), Observable.merge( Observable.from(6), Observable.error(NullPointerException()), Observable.from(7) ), Observable.from(listOf(4, 5)) )!!.subscribe(received(), { e -> a!!.error(e) }) verify(a, times(1))!!.received(1) verify(a, times(1))!!.received(2) verify(a, times(1))!!.received(3) verify(a, times(0))!!.received(4) verify(a, times(0))!!.received(5) verify(a, times(1))!!.received(6) verify(a, times(0))!!.received(7) verify(a, times(1))!!.error(any(javaClass<NullPointerException>())) } [Test] public fun testScriptWithMaterialize() { TestFactory().observable.materialize()!!.subscribe((received())) verify(a, times(2))!!.received(any(javaClass<Notification<Int>>())) } [Test] public fun testScriptWithMerge() { val factory = TestFactory() Observable.merge(factory.observable, factory.observable)!!.subscribe((received())) verify(a, times(1))!!.received("hello_1") verify(a, times(1))!!.received("hello_2") } [Test] public fun testFromWithIterable() { val list = listOf(1, 2, 3, 4, 5) assertEquals(5, Observable.from(list)!!.count()!!.toBlockingObservable()!!.single()) } [Test] public fun testFromWithObjects() { val list = listOf(1, 2, 3, 4, 5) assertEquals(2, Observable.from(listOf(list, 6))!!.count()!!.toBlockingObservable()!!.single()) } [Test] public fun testStartWith() { val list = listOf(10, 11, 12, 13, 14) val startList = listOf(1, 2, 3, 4, 5) assertEquals(6, Observable.from(list)!!.startWith(0)!!.count()!!.toBlockingObservable()!!.single()) assertEquals(10, Observable.from(list)!!.startWith(startList)!!.count()!!.toBlockingObservable()!!.single()) } [Test] public fun testScriptWithOnNext() { TestFactory().observable.subscribe((received())) verify(a, times(1))!!.received("hello_1") } [Test] public fun testSkipTake() { Observable.from(listOf(1, 2, 3))!!.skip(1)!!.take(1)!!.subscribe(received()) verify(a, times(0))!!.received(1) verify(a, times(1))!!.received(2) verify(a, times(0))!!.received(3) } [Test] public fun testSkip() { Observable.from(listOf(1, 2, 3))!!.skip(2)!!.subscribe(received()) verify(a, times(0))!!.received(1) verify(a, times(0))!!.received(2) verify(a, times(1))!!.received(3) } [Test] public fun testTake() { Observable.from(listOf(1, 2, 3))!!.take(2)!!.subscribe(received()) verify(a, times(1))!!.received(1) verify(a, times(1))!!.received(2) verify(a, times(0))!!.received(3) } [Test] public fun testTakeLast() { TestFactory().observable.takeLast(1)!!.subscribe((received())) verify(a, times(1))!!.received("hello_1") } [Test] public fun testTakeWhile() { Observable.from(listOf(1, 2, 3))!!.takeWhile { x -> x!! < 3 }!!.subscribe(received()) verify(a, times(1))!!.received(1) verify(a, times(1))!!.received(2) verify(a, times(0))!!.received(3) } [Test] public fun testTakeWhileWithIndex() { Observable.from(listOf(1, 2, 3))!!.takeWhileWithIndex { x, i -> i!! < 2 }!!.subscribe(received()) verify(a, times(1))!!.received(1) verify(a, times(1))!!.received(2) verify(a, times(0))!!.received(3) } [Test] public fun testToSortedList() { TestFactory().numbers.toSortedList()!!.subscribe(received()) verify(a, times(1))!!.received(listOf(1, 2, 3, 4, 5)) } [Test] public fun testForEach() { Observable.create(AsyncObservable())!!.toBlockingObservable()!!.forEach(received()) verify(a, times(1))!!.received(1) verify(a, times(1))!!.received(2) verify(a, times(1))!!.received(3) } [Test(expected = javaClass<RuntimeException>())] public fun testForEachWithError() { Observable.create(AsyncObservable())!!.toBlockingObservable()!!.forEach { throw RuntimeException("err") } fail("we expect an exception to be thrown") } [Test] public fun testLastOrDefault() { assertEquals("two", Observable.from(listOf("one", "two"))!!.toBlockingObservable()!!.lastOrDefault("default") { x -> x!!.length == 3 }) assertEquals("default", Observable.from(listOf("one", "two"))!!.toBlockingObservable()!!.lastOrDefault("default") { x -> x!!.length > 3 }) } [Test(expected = javaClass<IllegalArgumentException>())] public fun testSingle() { assertEquals("one", Observable.from("one")!!.toBlockingObservable()!!.single { x -> x!!.length == 3 }) Observable.from(listOf("one", "two"))!!.toBlockingObservable()!!.single { x -> x!!.length == 3 } fail() } [Test] public fun testDefer() { Observable.defer { Observable.from(listOf(1, 2)) }!!.subscribe(received()) verify(a, times(1))!!.received(1) verify(a, times(1))!!.received(2) } [Test] public fun testAll() { Observable.from(listOf(1, 2, 3))!!.all { x -> x!! > 0 }!!.subscribe(received()) verify(a, times(1))!!.received(true) } [Test] public fun testZip() { val o1 = Observable.from(listOf(1, 2, 3))!! val o2 = Observable.from(listOf(4, 5, 6))!! val o3 = Observable.from(listOf(7, 8, 9))!! val values = Observable.zip(o1, o2, o3) { a, b, c -> listOf(a, b, c) }!!.toList()!!.toBlockingObservable()!!.single()!! assertEquals(listOf(1, 4, 7), values[0]) assertEquals(listOf(2, 5, 8), values[1]) assertEquals(listOf(3, 6, 9), values[2]) } [Test] public fun testZipWithIterable() { val o1 = Observable.from(listOf(1, 2, 3))!! val o2 = Observable.from(listOf(4, 5, 6))!! val o3 = Observable.from(listOf(7, 8, 9))!! val values = Observable.zip(listOf(o1, o2, o3)) { args -> listOf(*args) }!!.toList()!!.toBlockingObservable()!!.single()!! assertEquals(listOf(1, 4, 7), values[0]) assertEquals(listOf(2, 5, 8), values[1]) assertEquals(listOf(3, 6, 9), values[2]) } [Test] public fun testGroupBy() { var count = 0 Observable.from(listOf("one", "two", "three", "four", "five", "six"))!! .groupBy { s -> s!!.length }!! .flatMap { groupObervable -> groupObervable!!.map { s -> "Value: $s Group ${groupObervable.getKey()}" } }!!.toBlockingObservable()!!.forEach { s -> println(s) count++ } assertEquals(6, count) } public class TestFactory() { var counter = 1 val numbers: Observable<Int> get(){ return Observable.from(listOf(1, 3, 2, 5, 4))!! } val onSubscribe: TestOnSubscribe get(){ return TestOnSubscribe(counter++) } val observable: Observable<String> get(){ return Observable.create(onSubscribe)!! } } class AsyncObservable : OnSubscribe<Int> { override fun call(op: Subscriber<in Int>?) { thread { Thread.sleep(50) op!!.onNext(1) op.onNext(2) op.onNext(3) op.onCompleted() } } } class TestOnSubscribe(val count: Int) : OnSubscribe<String> { override fun call(op: Subscriber<in String>?) { op!!.onNext("hello_$count") op.onCompleted() } } }
apache-2.0
Kotlin/kotlinx.serialization
core/commonTest/src/kotlinx/serialization/SerializersLookupInterfaceTest.kt
1
1639
package kotlinx.serialization import kotlinx.serialization.test.* import kotlin.test.* class SerializersLookupInterfaceTest { interface I @Polymorphic interface I2 @Suppress("SERIALIZER_TYPE_INCOMPATIBLE") @Serializable(PolymorphicSerializer::class) interface I3 @Serializable @SerialName("S") sealed interface S // TODO: not working because (see #1207, plugin does not produce companion object for interfaces) // We even have #1853 with tests for that // @Serializable(ExternalSerializer::class) // interface External @Test fun testSealedInterfaceLookup() { if (currentPlatform == Platform.JS_LEGACY) return val serializer = serializer<S>() assertTrue(serializer is SealedClassSerializer) assertEquals("S", serializer.descriptor.serialName) } @Test fun testInterfaceLookup() { // Native does not have KClass.isInterface if (currentPlatform == Platform.NATIVE || currentPlatform == Platform.JS_LEGACY) return val serializer1 = serializer<I>() assertTrue(serializer1 is PolymorphicSerializer) assertEquals("kotlinx.serialization.Polymorphic<I>", serializer1.descriptor.serialName) val serializer2 = serializer<I2>() assertTrue(serializer2 is PolymorphicSerializer) assertEquals("kotlinx.serialization.Polymorphic<I2>", serializer2.descriptor.serialName) val serializer3 = serializer<I3>() assertTrue(serializer3 is PolymorphicSerializer) assertEquals("kotlinx.serialization.Polymorphic<I3>", serializer3.descriptor.serialName) } }
apache-2.0
yifeidesu/Bitty
app/src/main/java/com/robyn/bitty/utils/tweetUtils/playerUtils.kt
1
2767
package com.robyn.bitty.utils.tweetUtils import android.content.Context import android.net.Uri import android.view.View import com.google.android.exoplayer2.ExoPlayerFactory import com.google.android.exoplayer2.SimpleExoPlayer import com.google.android.exoplayer2.trackselection.DefaultTrackSelector import com.google.android.exoplayer2.ui.SimpleExoPlayerView import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter import com.google.android.exoplayer2.source.ExtractorMediaSource import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory import com.google.android.exoplayer2.util.Util import com.twitter.sdk.android.core.models.Tweet /** * Methods to play a video contained in a Tweet * * todo: replace by glide!? * * Created by yifei on 12/4/2017. */ /** * Create a [SimpleExoPlayer], set [uri] as data source to it, and return it. */ fun getPlayer(context: Context, uri: Uri): SimpleExoPlayer { // Create the player with all default params val bandwidthMeter = DefaultBandwidthMeter() val trackSelector = DefaultTrackSelector(bandwidthMeter) val player = ExoPlayerFactory.newSimpleInstance(context, trackSelector) // Get data source from uri val dataSourceFactory = DefaultDataSourceFactory(context, Util.getUserAgent(context, "videodemoapp"), bandwidthMeter) val extractorsFactory = DefaultExtractorsFactory() val videoSource = ExtractorMediaSource(uri, dataSourceFactory, extractorsFactory, null, null) // Set the data source to the player player.prepare(videoSource) return player } /** * This method decides if the [tweet] has video url. * If it does, it has a player to player the video on the url * * Currently works only for some types, mp4, gif ... */ fun playVideo(tweet: Tweet, context: Context, playerView: SimpleExoPlayerView) { with(getVideoUrl(tweet)) { if (this!=null) { playerView.player = getPlayer(context, this) playerView.visibility = View.VISIBLE }else{ playerView.visibility = View.GONE } } } /** * Returns the [tweet]'s 1st video url, if it has any. */ fun getVideoUrl(tweet: Tweet): Uri? { var uri: Uri? = null // rewrite logic tweet.extendedEntities?.apply { if (!this.media.isEmpty()) { with(tweet.extendedEntities.media.get(0).videoInfo) { this?.apply { if (!this.variants.isEmpty()) { this.variants[0].url.apply { uri = Uri.parse(this) } } } } } } return uri }
apache-2.0
jcam3ron/cassandra-migration
src/test/java/com/builtamont/cassandra/migration/internal/info/MigrationInfoSpec.kt
1
2671
/** * File : MigrationInfoSpec.kt * License : * Original - Copyright (c) 2015 - 2016 Contrast Security * Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd * * 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.builtamont.cassandra.migration.internal.info import com.builtamont.cassandra.migration.api.MigrationType import com.builtamont.cassandra.migration.api.MigrationVersion import com.builtamont.cassandra.migration.api.resolver.ResolvedMigration import com.builtamont.cassandra.migration.internal.metadatatable.AppliedMigration import com.builtamont.cassandra.migration.internal.resolver.ResolvedMigrationImpl import io.kotlintest.matchers.have import io.kotlintest.specs.FreeSpec /** * MigrationInfoSpec unit tests. */ class MigrationInfoSpec : FreeSpec() { val version = MigrationVersion.fromVersion("1") val description = "test" val type = MigrationType.CQL /** * Creates a new resolved migration. * * @return The resolved migration. */ fun createResolvedMigration(): ResolvedMigration { val resolvedMigration = ResolvedMigrationImpl() resolvedMigration.version = version resolvedMigration.description = description resolvedMigration.type = type resolvedMigration.checksum = 456 return resolvedMigration } /** * Creates a new applied migration. * * @return The applied migration. */ fun createAppliedMigration(): AppliedMigration { return AppliedMigration(version, description, type, null, 123, "testUser", 0, success = true) } init { "MigrationInfo" - { "should be able to validate migrations info" { val migrationInfo = MigrationInfoImpl( createResolvedMigration(), createAppliedMigration(), MigrationInfoContext() ) val message = migrationInfo.validate() message!! should have substring "123" message!! should have substring "456" } } } }
apache-2.0
ziggy42/Blum
app/src/main/java/com/andreapivetta/blu/ui/timeline/holders/StatusViewHolder.kt
1
2739
package com.andreapivetta.blu.ui.timeline.holders import android.support.annotation.CallSuper import android.view.View import android.widget.TextView import com.andreapivetta.blu.R import com.andreapivetta.blu.common.utils.Utils import com.andreapivetta.blu.common.utils.loadAvatar import com.andreapivetta.blu.common.utils.visible import com.andreapivetta.blu.data.model.Tweet import com.andreapivetta.blu.ui.timeline.InteractionListener import kotlinx.android.synthetic.main.tweet_basic.view.* open class StatusViewHolder(container: View, listener: InteractionListener) : BaseViewHolder(container, listener) { protected var retweetTextView: TextView = container.retweetTextView @CallSuper override fun setup(tweet: Tweet) { val currentTweet: Tweet if (tweet.retweet) { currentTweet = tweet.getRetweetedTweet() retweetTextView.visible() retweetTextView.text = container.context.getString( R.string.retweeted_by, tweet.user.screenName) } else { currentTweet = tweet retweetTextView.visible(false) } val currentUser = currentTweet.user userNameTextView.text = currentUser.name userScreenNameTextView.text = "@${currentUser.screenName}" timeTextView.text = " • ${Utils.formatDate(currentTweet.timeStamp)}" userProfilePicImageView.loadAvatar(currentUser.biggerProfileImageURL) if (currentTweet.favorited) favouriteImageButton.setImageResource(R.drawable.ic_favorite_red) else favouriteImageButton.setImageResource(R.drawable.ic_favorite) if (currentTweet.retweeted) retweetImageButton.setImageResource(R.drawable.ic_repeat_green) else retweetImageButton.setImageResource(R.drawable.ic_repeat) favouritesStatsTextView.text = "${tweet.favoriteCount}" retweetsStatsTextView.text = "${tweet.retweetCount}" statusTextView.text = currentTweet.getTextWithoutMediaURLs() userProfilePicImageView.setOnClickListener { listener.showUser(currentUser) } favouriteImageButton.setOnClickListener { if (currentTweet.favorited) listener.unfavorite(currentTweet) else listener.favorite(currentTweet) } retweetImageButton.setOnClickListener { if (currentTweet.retweeted) listener.unretweet(currentTweet) else listener.retweet(currentTweet) } respondImageButton.setOnClickListener { listener.reply(currentTweet, currentUser) } container.setOnClickListener { listener.openTweet(currentTweet) } } }
apache-2.0
Ruben-Sten/TeXiFy-IDEA
test/nl/hannahsten/texifyidea/completion/LatexCompletionTest.kt
1
4864
package nl.hannahsten.texifyidea.completion import com.intellij.codeInsight.completion.CompletionType import com.intellij.testFramework.fixtures.BasePlatformTestCase import nl.hannahsten.texifyidea.file.LatexFileType import org.junit.Test class LatexCompletionTest : BasePlatformTestCase() { @Throws(Exception::class) override fun setUp() { super.setUp() } @Test fun testCompleteLatexReferences() { // given myFixture.configureByText(LatexFileType, """\ap<caret>""") // when val result = myFixture.complete(CompletionType.BASIC) // then assertTrue("LaTeX autocompletion should be available", result.any { it.lookupString.startsWith("appendix") }) } @Test fun testCompleteCustomCommandReferences() { // given myFixture.configureByText( LatexFileType, """ \newcommand{\hi}{hi} \h<caret> """.trimIndent() ) // when val result = myFixture.complete(CompletionType.BASIC) // then assertTrue("LaTeX autocompletion of custom commands should be available", result.any { it.lookupString == "hi" }) } fun testCompleteCustomColorDefinitions() { myFixture.configureByText( LatexFileType, """ \colorlet{fadedred}{red!70!} \color{r<caret>} """.trimIndent() ) val result = myFixture.complete(CompletionType.BASIC) assertTrue("fadedred should be available", result.any { it.lookupString == "fadedred" }) } fun testCompletionInCustomArgument() { myFixture.configureByText( LatexFileType, """ \newcommand{\hello}[1]{hello #1} \hello{\te<caret>} """.trimIndent() ) val result = myFixture.complete(CompletionType.BASIC) assertTrue(result.any { it.lookupString.startsWith("textbf") }) } // fun testCustomCommandAliasCompletion() { // myFixture.configureByText(LatexFileType, """ // \begin{thebibliography}{9} // \bibitem{testkey} // Reference. // \end{thebibliography} // // \newcommand{\mycite}[1]{\cite{#1}} // // \mycite{<caret>} // """.trimIndent()) // CommandManager.updateAliases(setOf("\\cite"), project) // val result = myFixture.complete(CompletionType.BASIC) // // assertTrue(result.any { it.lookupString == "testkey" }) // } // Test doesn't work // fun testTwoLevelCustomCommandAliasCompletion() { // myFixture.configureByText(LatexFileType, """ // \begin{thebibliography}{9} // \bibitem{testkey} // Reference. // \end{thebibliography} // // \newcommand{\mycite}[1]{\cite{#1}} // <caret> // """.trimIndent()) // // // For n-level autocompletion, the autocompletion needs to run n times (but only runs when the number of indexed // // newcommands changes) // CommandManager.updateAliases(setOf("\\cite"), project) // CommandManager.updateAliases(setOf("\\cite"), project) // // myFixture.complete(CompletionType.BASIC) // myFixture.type("""\newcommand{\myothercite}[1]{\mycite{#1}}""") // myFixture.type("""\myother""") // myFixture.complete(CompletionType.BASIC) // val result = myFixture.complete(CompletionType.BASIC, 2) // // assertTrue(result.any { it.lookupString == "testkey" }) // } fun testCustomLabelAliasCompletion() { myFixture.configureByText( LatexFileType, """ \newcommand{\mylabel}[1]{\label{#1}} \mylabel{label1} \label{label2} ~\ref{la<caret>} """.trimIndent() ) val result = myFixture.complete(CompletionType.BASIC) assertTrue(result.any { it.lookupString == "label1" }) } // Test only works when no other tests are run // fun testCustomLabelPositionAliasCompletion() { // myFixture.configureByText(LatexFileType, """ // \newcommand{\mylabel}[2]{\section{#1}\label{sec:#2}} // // \mylabel{section1}{label1} // \label{label2} // // ~\ref{<caret>} // """.trimIndent()) // // CommandManager.updateAliases(Magic.Command.labelDefinition, project) // val result = myFixture.complete(CompletionType.BASIC) // // assertEquals(2, result.size) // assertTrue(result.any { it.lookupString == "label1" }) // assertFalse(result.any { it.lookupString == "section1" }) // assertFalse(result.any { it.lookupString == "sec:#2" }) // } }
mit
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/people/SyncPersonBackdrop.kt
1
2347
/* * Copyright (C) 2016 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.actions.people import android.content.ContentValues import android.content.Context import com.uwetrottmann.tmdb2.entities.TaggedImagesResultsPage import com.uwetrottmann.tmdb2.services.PeopleService import net.simonvt.cathode.actions.TmdbCallAction import net.simonvt.cathode.actions.people.SyncPersonBackdrop.Params import net.simonvt.cathode.images.ImageType import net.simonvt.cathode.images.ImageUri import net.simonvt.cathode.provider.DatabaseContract.PersonColumns import net.simonvt.cathode.provider.ProviderSchematic.People import net.simonvt.cathode.provider.helper.PersonDatabaseHelper import net.simonvt.cathode.provider.update import retrofit2.Call import javax.inject.Inject class SyncPersonBackdrop @Inject constructor( private val context: Context, private val personHelper: PersonDatabaseHelper, private val peopleService: PeopleService ) : TmdbCallAction<Params, TaggedImagesResultsPage>() { override fun key(params: Params): String = "SyncPersonBackdrop&tmdbId=${params.tmdbId}" override fun getCall(params: Params): Call<TaggedImagesResultsPage> = peopleService.taggedImages(params.tmdbId, 1, "en") override suspend fun handleResponse(params: Params, response: TaggedImagesResultsPage) { val personId = personHelper.getIdFromTmdb(params.tmdbId) val values = ContentValues() if (response.results!!.size > 0) { val taggedImage = response.results!![0] val path = ImageUri.create(ImageType.STILL, taggedImage.file_path) values.put(PersonColumns.SCREENSHOT, path) } else { values.putNull(PersonColumns.SCREENSHOT) } context.contentResolver.update(People.withId(personId), values) } data class Params(val tmdbId: Int) }
apache-2.0
SimonVT/cathode
cathode/src/main/java/net/simonvt/cathode/entitymapper/EpisodeMapper.kt
1
5151
/* * Copyright (C) 2018 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.entitymapper import android.database.Cursor import net.simonvt.cathode.common.data.MappedCursorLiveData import net.simonvt.cathode.common.database.getBoolean import net.simonvt.cathode.common.database.getFloat import net.simonvt.cathode.common.database.getInt import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.common.database.getStringOrNull import net.simonvt.cathode.entity.Episode import net.simonvt.cathode.provider.DatabaseContract.EpisodeColumns import net.simonvt.cathode.provider.util.DataHelper object EpisodeMapper : MappedCursorLiveData.CursorMapper<Episode> { override fun map(cursor: Cursor): Episode? { return if (cursor.moveToFirst()) mapEpisode(cursor) else null } fun mapEpisode(cursor: Cursor): Episode { val id = cursor.getLong(EpisodeColumns.ID) val showId = cursor.getLong(EpisodeColumns.SHOW_ID) val seasonId = cursor.getLong(EpisodeColumns.SEASON_ID) val season = cursor.getInt(EpisodeColumns.SEASON) val episode = cursor.getInt(EpisodeColumns.EPISODE) val numberAbs = cursor.getInt(EpisodeColumns.NUMBER_ABS) val title = cursor.getStringOrNull(EpisodeColumns.TITLE) val overview = cursor.getStringOrNull(EpisodeColumns.OVERVIEW) val traktId = cursor.getLong(EpisodeColumns.TRAKT_ID) val imdbId = cursor.getStringOrNull(EpisodeColumns.IMDB_ID) val tvdbId = cursor.getInt(EpisodeColumns.TVDB_ID) val tmdbId = cursor.getInt(EpisodeColumns.TMDB_ID) val tvrageId = cursor.getLong(EpisodeColumns.TVRAGE_ID) var firstAired = cursor.getLong(EpisodeColumns.FIRST_AIRED) if (firstAired != 0L) { firstAired = DataHelper.getFirstAired(firstAired) } val updatedAt = cursor.getLong(EpisodeColumns.UPDATED_AT) val userRating = cursor.getInt(EpisodeColumns.USER_RATING) val ratedAt = cursor.getLong(EpisodeColumns.RATED_AT) val rating = cursor.getFloat(EpisodeColumns.RATING) val votes = cursor.getInt(EpisodeColumns.VOTES) val plays = cursor.getInt(EpisodeColumns.PLAYS) val watched = cursor.getBoolean(EpisodeColumns.WATCHED) val watchedAt = cursor.getLong(EpisodeColumns.LAST_WATCHED_AT) val inCollection = cursor.getBoolean(EpisodeColumns.IN_COLLECTION) val collectedAt = cursor.getLong(EpisodeColumns.COLLECTED_AT) val inWatchlist = cursor.getBoolean(EpisodeColumns.IN_WATCHLIST) val watchlistedAt = cursor.getLong(EpisodeColumns.LISTED_AT) val watching = cursor.getBoolean(EpisodeColumns.WATCHING) val checkedIn = cursor.getBoolean(EpisodeColumns.CHECKED_IN) val checkinStartedAt = cursor.getLong(EpisodeColumns.STARTED_AT) val checkinExpiresAt = cursor.getLong(EpisodeColumns.EXPIRES_AT) val lastCommentSync = cursor.getLong(EpisodeColumns.LAST_COMMENT_SYNC) val notificationDismissed = cursor.getBoolean(EpisodeColumns.NOTIFICATION_DISMISSED) val showTitle = cursor.getStringOrNull(EpisodeColumns.SHOW_TITLE) return Episode( id, showId, seasonId, season, episode, numberAbs, title, overview, traktId, imdbId, tvdbId, tmdbId, tvrageId, firstAired, updatedAt, userRating, ratedAt, rating, votes, plays, watched, watchedAt, inCollection, collectedAt, inWatchlist, watchlistedAt, watching, checkedIn, checkinStartedAt, checkinExpiresAt, lastCommentSync, notificationDismissed, showTitle ) } @JvmField val projection = arrayOf( EpisodeColumns.ID, EpisodeColumns.SHOW_ID, EpisodeColumns.SEASON_ID, EpisodeColumns.SEASON, EpisodeColumns.EPISODE, EpisodeColumns.NUMBER_ABS, EpisodeColumns.TITLE, EpisodeColumns.OVERVIEW, EpisodeColumns.TRAKT_ID, EpisodeColumns.TVDB_ID, EpisodeColumns.TMDB_ID, EpisodeColumns.TVRAGE_ID, EpisodeColumns.FIRST_AIRED, EpisodeColumns.UPDATED_AT, EpisodeColumns.USER_RATING, EpisodeColumns.RATED_AT, EpisodeColumns.RATING, EpisodeColumns.VOTES, EpisodeColumns.PLAYS, EpisodeColumns.WATCHED, EpisodeColumns.LAST_WATCHED_AT, EpisodeColumns.IN_COLLECTION, EpisodeColumns.COLLECTED_AT, EpisodeColumns.IN_WATCHLIST, EpisodeColumns.LISTED_AT, EpisodeColumns.WATCHING, EpisodeColumns.CHECKED_IN, EpisodeColumns.STARTED_AT, EpisodeColumns.EXPIRES_AT, EpisodeColumns.LAST_COMMENT_SYNC, EpisodeColumns.NOTIFICATION_DISMISSED, EpisodeColumns.SHOW_TITLE ) }
apache-2.0
android/android-studio-poet
aspoet-input/src/main/kotlin/com/google/androidstudiopoet/input/ResourcesConfig.kt
1
743
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.androidstudiopoet.input data class ResourcesConfig(val stringCount: Int?, val imageCount: Int?, val layoutCount: Int?)
apache-2.0
Countly/countly-sdk-android
app/src/main/java/ly/count/android/demo/ActivityExampleKotlin.kt
1
1137
package ly.count.android.demo import android.content.res.Configuration import androidx.appcompat.app.AppCompatActivity import ly.count.android.sdk.Countly class ActivityExampleKotlin : AppCompatActivity() { override fun onStart() { super.onStart() Countly.sharedInstance().onStart(this); Countly.sharedInstance().apm().startTrace("fff"); Countly.sharedInstance().consent().checkAllConsent(); Countly.sharedInstance().crashes().addCrashBreadcrumb("ddd"); Countly.sharedInstance().events().recordEvent("ddd"); val count: Int = Countly.sharedInstance().ratings().getAutomaticStarRatingSessionLimit(); Countly.sharedInstance().remoteConfig().allValues; Countly.sharedInstance().sessions().beginSession() Countly.sharedInstance().views().isAutomaticViewTrackingEnabled; val id = Countly.sharedInstance().deviceId().id; } override fun onStop() { Countly.sharedInstance().onStop(); super.onStop() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) Countly.sharedInstance().onConfigurationChanged(newConfig); } }
mit
Flank/simple-flank
src/test/kotlin/SigningValidationTest.kt
1
2720
import java.io.File import org.junit.Test import strikt.api.expectThat import strikt.assertions.contains class SigningValidationTest : GradleTest() { @Test fun warnIfDefaultSigning() { projectFromResources("app") val build = gradleRunner("flankRunDebug").forwardOutput().build() expectThat(build.output) { contains("Warning: The debug keystore should be set") } } @Test fun failIfDefaultSigningAndHermeticTests() { projectFromResources("app") File(testProjectDir.root, "build.gradle.kts") .appendText( """ simpleFlank { hermeticTests.set(true) } """.trimIndent()) gradleRunner("flankRunDebug").forwardOutput().buildAndFail() } @Test fun failIfNoSigningAndHermeticTests() { projectFromResources("app") File(testProjectDir.root, "build.gradle.kts") .appendText( """ android { testBuildType = "beta" buildTypes { create("beta") } } simpleFlank { hermeticTests.set(true) } """.trimIndent()) gradleRunner("flankRunDebug").forwardOutput().buildAndFail() } @Test fun workFineIfCustomSigning() { projectFromResources("app") File(testProjectDir.root, "build.gradle.kts") .appendText( """ android { signingConfigs { named("debug") { storeFile = File(projectDir, "someKeystore") keyAlias = "debugKey" keyPassword = "debugKeystore" storePassword = "debugKeystore" } } buildTypes { getByName("debug") { signingConfig = signingConfigs.getByName("debug") } } } simpleFlank { hermeticTests.set(true) } """.trimIndent()) val build = gradleRunner("flankRunDebug").forwardOutput().build() expectThat(build.output) { not { contains("The debug keystore should be set") } } } @Test fun workFineNotOnlyWithDebugSigningConfig() { projectFromResources("app") File(testProjectDir.root, "build.gradle.kts") .appendText( """ android { signingConfigs { create("mySigning") { storeFile = File(projectDir, "someKeystore") keyAlias = "debugKey" keyPassword = "debugKeystore" storePassword = "debugKeystore" } } buildTypes { getByName("debug") { signingConfig = signingConfigs.getByName("mySigning") } } } simpleFlank { hermeticTests.set(true) } """.trimIndent()) gradleRunner("flankRunDebug").forwardOutput().build() } }
apache-2.0
FHannes/intellij-community
uast/uast-java/src/org/jetbrains/uast/java/controlStructures/JavaUForExpression.kt
8
1517
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.java import com.intellij.psi.PsiForStatement import com.intellij.psi.impl.source.tree.ChildRole import org.jetbrains.uast.UElement import org.jetbrains.uast.UForExpression import org.jetbrains.uast.UIdentifier class JavaUForExpression( override val psi: PsiForStatement, override val uastParent: UElement? ) : JavaAbstractUExpression(), UForExpression { override val declaration by lz { psi.initialization?.let { JavaConverter.convertStatement(it, { this }) } } override val condition by lz { psi.condition?.let { JavaConverter.convertExpression(it, { this }) } } override val update by lz { psi.update?.let { JavaConverter.convertStatement(it, { this }) } } override val body by lz { JavaConverter.convertOrEmpty(psi.body, this) } override val forIdentifier: UIdentifier get() = UIdentifier(psi.getChildByRole(ChildRole.FOR_KEYWORD), this) }
apache-2.0
NextFaze/dev-fun
devfun-compiler/src/main/java/com/nextfaze/devfun/compiler/processing/KElements.kt
1
3741
package com.nextfaze.devfun.compiler.processing import com.nextfaze.devfun.compiler.get import com.nextfaze.devfun.compiler.isClassPublic import com.nextfaze.devfun.compiler.toKClassBlock import com.nextfaze.devfun.compiler.toTypeName import com.squareup.kotlinpoet.CodeBlock import kotlinx.metadata.ClassName import kotlinx.metadata.Flag import kotlinx.metadata.Flags import kotlinx.metadata.KmClassVisitor import kotlinx.metadata.jvm.KotlinClassHeader import kotlinx.metadata.jvm.KotlinClassMetadata import javax.inject.Inject import javax.inject.Singleton import javax.lang.model.element.Name import javax.lang.model.element.TypeElement import javax.lang.model.type.DeclaredType import javax.lang.model.type.TypeMirror import javax.lang.model.util.Elements import javax.lang.model.util.Types @Singleton internal class KElements @Inject constructor( private val elements: Elements, private val types: Types ) { private val typeElementMap = mutableMapOf<Name, ClassElement>() private val metaDataElement: DeclaredType = types.getDeclaredType(elements.getTypeElement("kotlin.Metadata")) operator fun get(typeElement: TypeElement) = with(typeElement) { typeElementMap.getOrPut(qualifiedName) { ClassElement(this) } } inner class ClassElement(val element: TypeElement) : TypeElement by element { private val metaDataAnnotation by lazy { element.annotationMirrors.firstOrNull { types.isSameType(it.annotationType, metaDataElement) } } val isInterface = element.kind.isInterface private val isClass = element.kind.isClass val simpleName = element.simpleName.toString() override fun toString() = element.toString() val isPublic by lazy { element.isClassPublic } val type: TypeMirror by lazy { element.asType() } val typeName by lazy { type.toTypeName() } val typeBlock: CodeBlock by lazy { CodeBlock.of("%T", typeName) } val klassBlock: CodeBlock by lazy { type.toKClassBlock(elements = elements) } val isKtFile by lazy { isClass && metaDataAnnotation?.get<Int>("k") == KotlinClassHeader.FILE_FACADE_KIND } private val header: KotlinClassHeader? by lazy { val annotation = metaDataAnnotation ?: return@lazy null KotlinClassHeader( kind = annotation["k"], metadataVersion = annotation["mv"], bytecodeVersion = annotation["bv"], data1 = annotation["d1"], data2 = annotation["d2"], extraString = annotation["xs"], packageName = annotation["pn"], extraInt = annotation["xi"] ) } private val metadata by lazy { header?.let { KotlinClassMetadata.read(it) } } val isKObject by lazy { var flag = false val metadata = metadata if (isClass && !isKtFile && metadata is KotlinClassMetadata.Class) { metadata.accept(object : KmClassVisitor() { override fun visit(flags: Flags, name: ClassName) { flag = Flag.Class.IS_OBJECT(flags) } }) } return@lazy flag } val isCompanionObject by lazy { var flag = false val metadata = metadata if (isClass && !isKtFile && metadata is KotlinClassMetadata.Class) { metadata.accept(object : KmClassVisitor() { override fun visit(flags: Flags, name: ClassName) { flag = Flag.Class.IS_COMPANION_OBJECT(flags) } }) } return@lazy flag } } }
apache-2.0
JurajBegovac/RxKotlinTraits
rxkotlin-traits/src/main/kotlin/com/jurajbegovac/rxkotlin/traits/shared_sequence/SharedSequence+Operators.kt
1
5556
package com.jurajbegovac.rxkotlin.traits.shared_sequence import com.jurajbegovac.rxkotlin.traits.observable.debug /** Created by juraj begovac on 13/06/2017. */ fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.debug( id: String, logger: (String) -> Unit): SharedSequence<SharingStrategy, Element> = SharedSequence(source.debug(id, logger), sharingStrategy) fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.map( errorValue: Result? = null, func: (Element) -> Result): SharedSequence<SharingStrategy, Result> { val errorStream = if (errorValue != null) sharingStrategy.just(errorValue) else sharingStrategy.empty() return flatMap(errorStream, { element -> try { val result = func(element) sharingStrategy.just(result) } catch (e: Throwable) { reportError(e) errorStream } }) } fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.filter( errorValue: Boolean = false, predicate: (Element) -> Boolean): SharedSequence<SharingStrategy, Element> { val source = this.source .filter { try { predicate(it) } catch (e: Throwable) { reportError(e) errorValue } } return SharedSequence(source, this.sharingStrategy) } fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.flatMap( errorValue: SharedSequence<SharingStrategy, Result> = this.sharingStrategy.empty(), func: (Element) -> SharedSequence<SharingStrategy, Result>): SharedSequence<SharingStrategy, Result> { val source = this.source .flatMap { try { func(it).source } catch (e: Throwable) { reportError(e) errorValue.source } } return SharedSequence(source, this.sharingStrategy) } fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.switchMap( errorValue: SharedSequence<SharingStrategy, Result> = this.sharingStrategy.empty(), func: (Element) -> SharedSequence<SharingStrategy, Result>): SharedSequence<SharingStrategy, Result> { val source = this.source .switchMap { try { func(it).source } catch (e: Throwable) { reportError(e) errorValue.source } } return SharedSequence(source, this.sharingStrategy) } fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.flatMapIterable( errorValue: Iterable<Result> = emptyList<Result>(), func: (Element) -> Iterable<Result>): SharedSequence<SharingStrategy, Result> { val source = this.source .flatMapIterable { try { func(it) } catch (e: Throwable) { reportError(e) errorValue } } return SharedSequence(source, this.sharingStrategy) } fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.distinctUntilChanged(): SharedSequence<SharingStrategy, Element> = SharedSequence(this.source.distinctUntilChanged(), this.sharingStrategy) fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.distinctUntilChanged( errorValue: Boolean = false, comparator: (Element, Element) -> Boolean): SharedSequence<SharingStrategy, Element> { val source = this.source .distinctUntilChanged { e1, e2 -> try { comparator(e1, e2) } catch (e: Throwable) { reportError(e) errorValue } } return SharedSequence(source, this.sharingStrategy) } fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.distinctUntilChanged( errorValue: Boolean = false, keySelector: (Element) -> Result): SharedSequence<SharingStrategy, Element> { val source = this.source .distinctUntilChanged { e -> try { keySelector(e) } catch (e: Throwable) { reportError(e) errorValue } } return SharedSequence(source, this.sharingStrategy) } fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.startWith( item: Element): SharedSequence<SharingStrategy, Element> = SharedSequence(this.source.startWith(item), this.sharingStrategy) fun <Element, SharingStrategy : SharingStrategyProtocol, Result> SharedSequence<SharingStrategy, Element>.scan( errorValue: Result, initialValue: Result, accumulator: (Result, Element) -> Result): SharedSequence<SharingStrategy, Result> { val source = this.source .scan(initialValue) { r, t -> try { accumulator(r, t) } catch (e: Throwable) { reportError(e) errorValue } } return SharedSequence(source, this.sharingStrategy) } fun <Element, SharingStrategy : SharingStrategyProtocol> SharedSequence<SharingStrategy, Element>.doOnNext( onNext: (Element) -> Unit): SharedSequence<SharingStrategy, Element> { val source = this.source .doOnNext { try { onNext(it) } catch (e: Throwable) { reportError(e) } } return SharedSequence(source, this.sharingStrategy) }
mit
ExMCL/ExMCL
ExMCL API/src/main/kotlin/com/n9mtq4/exmcl/api/tabs/creators/LowLevelTabCreator.kt
1
2741
/* * MIT License * * Copyright (c) 2016 Will (n9Mtq4) Bresnahan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.n9mtq4.exmcl.api.tabs.creators import com.n9mtq4.exmcl.api.hooks.events.PreDefinedSwingComponent import com.n9mtq4.exmcl.api.hooks.events.PreDefinedSwingHookEvent import com.n9mtq4.exmcl.api.tabs.events.LowLevelCreateTabEvent import com.n9mtq4.exmcl.api.tabs.events.SafeForLowLevelTabCreationEvent import com.n9mtq4.logwindow.BaseConsole import com.n9mtq4.logwindow.annotation.ListensFor import com.n9mtq4.logwindow.listener.GenericListener import net.minecraft.launcher.ui.tabs.LauncherTabPanel import java.awt.Component /** * Created by will on 2/13/16 at 12:32 AM. * * @author Will "n9Mtq4" Bresnahan */ class LowLevelTabCreator : GenericListener, TabCreator { private var tabPanel: Any? = null @Suppress("unused", "UNUSED_PARAMETER") @ListensFor(LowLevelCreateTabEvent::class) fun listenForLLTabCreation(e: LowLevelCreateTabEvent, baseConsole: BaseConsole) { tryCreatingTab(e, baseConsole) } @Suppress("unused", "UNUSED_PARAMETER") @ListensFor(PreDefinedSwingHookEvent::class) fun listenForSwingHook(e: PreDefinedSwingHookEvent, baseConsole: BaseConsole) { if (e.type == PreDefinedSwingComponent.LAUNCHER_TAB_PANEL) { tabPanel = e.component baseConsole.pushEvent(SafeForLowLevelTabCreationEvent(baseConsole)) } } override fun addTab(title: String, tab: Component) { (tabPanel as LauncherTabPanel).addTab(title, tab) } private fun tryCreatingTab(e: LowLevelCreateTabEvent, baseConsole: BaseConsole) { addTab(e.title, e.component) baseConsole.println("Added tab name: ${e.title}, an instance of ${e.component.javaClass.name}") } }
mit
ashdavies/data-binding
mobile/src/main/kotlin/io/ashdavies/playground/navigation/ChannelNavDirector.kt
1
604
package io.ashdavies.playground.navigation import androidx.navigation.NavDirections import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel.Factory.CONFLATED import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow internal class ChannelNavDirector : NavDirector { private val _directions: Channel<NavDirections> = Channel(CONFLATED) override val directions: Flow<NavDirections> = flow { for (it: NavDirections in _directions) { emit(it) } } override fun navigate(directions: NavDirections) { _directions.offer(directions) } }
apache-2.0
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/timer_recordings/TimerRecordingListFragment.kt
1
11042
package org.tvheadend.tvhclient.ui.features.dvr.timer_recordings import android.os.Bundle import android.view.* import android.widget.Filter import androidx.appcompat.widget.PopupMenu import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import org.tvheadend.data.entity.TimerRecording import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.RecyclerviewFragmentBinding import org.tvheadend.tvhclient.ui.base.BaseFragment import org.tvheadend.tvhclient.ui.common.* import org.tvheadend.tvhclient.ui.common.interfaces.RecyclerViewClickInterface import org.tvheadend.tvhclient.ui.common.interfaces.SearchRequestInterface import org.tvheadend.tvhclient.util.extensions.gone import org.tvheadend.tvhclient.util.extensions.visible import org.tvheadend.tvhclient.util.extensions.visibleOrGone import timber.log.Timber import java.util.concurrent.CopyOnWriteArrayList class TimerRecordingListFragment : BaseFragment(), RecyclerViewClickInterface, SearchRequestInterface, Filter.FilterListener { private lateinit var binding: RecyclerviewFragmentBinding private lateinit var timerRecordingViewModel: TimerRecordingViewModel private lateinit var recyclerViewAdapter: TimerRecordingRecyclerViewAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = RecyclerviewFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) timerRecordingViewModel = ViewModelProvider(requireActivity())[TimerRecordingViewModel::class.java] arguments?.let { timerRecordingViewModel.selectedListPosition = it.getInt("listPosition") } recyclerViewAdapter = TimerRecordingRecyclerViewAdapter(isDualPane, this, htspVersion) binding.recyclerView.layoutManager = LinearLayoutManager(activity) binding.recyclerView.adapter = recyclerViewAdapter binding.recyclerView.gone() binding.searchProgress.visibleOrGone(baseViewModel.isSearchActive) timerRecordingViewModel.recordings.observe(viewLifecycleOwner, { recordings -> if (recordings != null) { recyclerViewAdapter.addItems(recordings) observeSearchQuery() } binding.recyclerView.visible() showStatusInToolbar() activity?.invalidateOptionsMenu() if (isDualPane && recyclerViewAdapter.itemCount > 0) { showRecordingDetails(timerRecordingViewModel.selectedListPosition) } }) } private fun observeSearchQuery() { Timber.d("Observing search query") baseViewModel.searchQueryLiveData.observe(viewLifecycleOwner, { query -> if (query.isNotEmpty()) { Timber.d("View model returned search query '$query'") onSearchRequested(query) } else { Timber.d("View model returned empty search query") onSearchResultsCleared() } }) } private fun showStatusInToolbar() { context?.let { if (!baseViewModel.isSearchActive) { toolbarInterface.setTitle(getString(R.string.timer_recordings)) toolbarInterface.setSubtitle(it.resources.getQuantityString(R.plurals.items, recyclerViewAdapter.itemCount, recyclerViewAdapter.itemCount)) } else { toolbarInterface.setTitle(getString(R.string.search_results)) toolbarInterface.setSubtitle(it.resources.getQuantityString(R.plurals.timer_recordings, recyclerViewAdapter.itemCount, recyclerViewAdapter.itemCount)) } } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val ctx = context ?: return super.onOptionsItemSelected(item) return when (item.itemId) { R.id.menu_add_recording -> return addNewTimerRecording(requireActivity()) R.id.menu_remove_all_recordings -> showConfirmationToRemoveAllTimerRecordings(ctx, CopyOnWriteArrayList(recyclerViewAdapter.items)) else -> super.onOptionsItemSelected(item) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.recording_list_options_menu, menu) } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) // Enable the remove all recordings menu if there are at least 2 recordings available if (sharedPreferences.getBoolean("delete_all_recordings_menu_enabled", resources.getBoolean(R.bool.pref_default_delete_all_recordings_menu_enabled)) && recyclerViewAdapter.itemCount > 1 && isConnectionToServerAvailable) { menu.findItem(R.id.menu_remove_all_recordings)?.isVisible = true } menu.findItem(R.id.menu_add_recording)?.isVisible = isConnectionToServerAvailable menu.findItem(R.id.menu_search)?.isVisible = recyclerViewAdapter.itemCount > 0 menu.findItem(R.id.media_route_menu_item)?.isVisible = false } private fun showRecordingDetails(position: Int) { timerRecordingViewModel.selectedListPosition = position recyclerViewAdapter.setPosition(position) val recording = recyclerViewAdapter.getItem(position) if (recording == null || !isVisible) { return } val fm = activity?.supportFragmentManager if (!isDualPane) { val fragment = TimerRecordingDetailsFragment.newInstance(recording.id) fm?.beginTransaction()?.also { it.replace(R.id.main, fragment) it.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) it.addToBackStack(null) it.commit() } } else { var fragment = activity?.supportFragmentManager?.findFragmentById(R.id.details) if (fragment !is TimerRecordingDetailsFragment) { fragment = TimerRecordingDetailsFragment.newInstance(recording.id) // Check the lifecycle state to avoid committing the transaction // after the onSaveInstance method was already called which would // trigger an illegal state exception. if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) { fm?.beginTransaction()?.also { it.replace(R.id.details, fragment) it.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) it.commit() } } } else if (timerRecordingViewModel.currentIdLiveData.value != recording.id) { timerRecordingViewModel.currentIdLiveData.value = recording.id } } } private fun showPopupMenu(view: View, position: Int) { val ctx = context ?: return val timerRecording = recyclerViewAdapter.getItem(position) ?: return val popupMenu = PopupMenu(ctx, view) popupMenu.menuInflater.inflate(R.menu.timer_recordings_popup_menu, popupMenu.menu) popupMenu.menuInflater.inflate(R.menu.external_search_options_menu, popupMenu.menu) preparePopupOrToolbarSearchMenu(popupMenu.menu, timerRecording.title, isConnectionToServerAvailable) popupMenu.menu.findItem(R.id.menu_disable_recording)?.isVisible = htspVersion >= 19 && timerRecording.isEnabled popupMenu.menu.findItem(R.id.menu_enable_recording)?.isVisible = htspVersion >= 19 && !timerRecording.isEnabled popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.menu_edit_recording -> return@setOnMenuItemClickListener editSelectedTimerRecording(requireActivity(), timerRecording.id) R.id.menu_remove_recording -> return@setOnMenuItemClickListener showConfirmationToRemoveSelectedTimerRecording(ctx, timerRecording, null) R.id.menu_disable_recording -> return@setOnMenuItemClickListener enableTimerRecording(timerRecording, false) R.id.menu_enable_recording -> return@setOnMenuItemClickListener enableTimerRecording(timerRecording, true) R.id.menu_search_imdb -> return@setOnMenuItemClickListener searchTitleOnImdbWebsite(ctx, timerRecording.title) R.id.menu_search_fileaffinity -> return@setOnMenuItemClickListener searchTitleOnFileAffinityWebsite(ctx, timerRecording.title) R.id.menu_search_youtube -> return@setOnMenuItemClickListener searchTitleOnYoutube(ctx, timerRecording.title) R.id.menu_search_google -> return@setOnMenuItemClickListener searchTitleOnGoogle(ctx, timerRecording.title) R.id.menu_search_epg -> return@setOnMenuItemClickListener searchTitleInTheLocalDatabase(requireActivity(), baseViewModel, timerRecording.title) else -> return@setOnMenuItemClickListener false } } popupMenu.show() } private fun enableTimerRecording(timerRecording: TimerRecording, enabled: Boolean): Boolean { val intent = timerRecordingViewModel.getIntentData(requireContext(), timerRecording) intent.action = "updateTimerecEntry" intent.putExtra("id", timerRecording.id) intent.putExtra("enabled", if (enabled) 1 else 0) activity?.startService(intent) return true } override fun onClick(view: View, position: Int) { showRecordingDetails(position) } override fun onLongClick(view: View, position: Int): Boolean { showPopupMenu(view, position) return true } override fun onFilterComplete(i: Int) { binding.searchProgress.gone() showStatusInToolbar() // Preselect the first result item in the details screen if (isDualPane) { when { recyclerViewAdapter.itemCount > timerRecordingViewModel.selectedListPosition -> { showRecordingDetails(timerRecordingViewModel.selectedListPosition) } recyclerViewAdapter.itemCount <= timerRecordingViewModel.selectedListPosition -> { showRecordingDetails(0) } recyclerViewAdapter.itemCount == 0 -> { removeDetailsFragment() } } } } override fun onSearchRequested(query: String) { recyclerViewAdapter.filter.filter(query, this) } override fun onSearchResultsCleared() { recyclerViewAdapter.filter.filter("", this) } override fun getQueryHint(): String { return getString(R.string.search_timer_recordings) } }
gpl-3.0
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/epg/EpgViewPagerFragment.kt
1
9084
package org.tvheadend.tvhclient.ui.features.epg import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.constraintlayout.widget.ConstraintSet import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.SCROLL_STATE_IDLE import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.EpgViewpagerFragmentBinding import org.tvheadend.tvhclient.util.extensions.visibleOrGone import timber.log.Timber import java.util.* class EpgViewPagerFragment : Fragment(), EpgScrollInterface { private lateinit var epgViewModel: EpgViewModel private lateinit var recyclerViewAdapter: EpgVerticalRecyclerViewAdapter /** * Defines if the current time indication (vertical line) shall be shown. * The indication shall only be shown for the first fragment. */ private val showTimeIndication: Boolean get() { return fragmentId == 0 } private var updateViewHandler = Handler(Looper.getMainLooper()) private var updateViewTask: Runnable? = null private var updateTimeIndicationHandler = Handler(Looper.getMainLooper()) private var updateTimeIndicationTask: Runnable? = null private lateinit var constraintSet: ConstraintSet private lateinit var binding: EpgViewpagerFragmentBinding private var recyclerViewLinearLayoutManager: LinearLayoutManager? = null private var enableScrolling = false private var fragmentId = 0 override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = DataBindingUtil.inflate(inflater, R.layout.epg_viewpager_fragment, container, false) return binding.root } override fun onDestroy() { super.onDestroy() if (showTimeIndication) { updateViewTask?.let { updateViewHandler.removeCallbacks(it) } updateTimeIndicationTask?.let { updateTimeIndicationHandler.removeCallbacks(it) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Timber.d("Initializing") epgViewModel = ViewModelProvider(requireActivity())[EpgViewModel::class.java] // Required to show the vertical current time indication constraintSet = ConstraintSet() constraintSet.clone(binding.constraintLayout) // Get the id that defines the position of the fragment in the viewpager fragmentId = arguments?.getInt("fragmentId") ?: 0 binding.startTime = epgViewModel.getStartTime(fragmentId) binding.endTime = epgViewModel.getEndTime(fragmentId) recyclerViewAdapter = EpgVerticalRecyclerViewAdapter(requireActivity(), epgViewModel, fragmentId, viewLifecycleOwner) recyclerViewLinearLayoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) binding.viewpagerRecyclerView.layoutManager = recyclerViewLinearLayoutManager binding.viewpagerRecyclerView.setHasFixedSize(true) binding.viewpagerRecyclerView.adapter = recyclerViewAdapter binding.viewpagerRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState != SCROLL_STATE_IDLE) { enableScrolling = true } else if (enableScrolling) { enableScrolling = false activity?.let { val fragment = it.supportFragmentManager.findFragmentById(R.id.main) if (fragment is EpgScrollInterface) { (fragment as EpgScrollInterface).onScrollStateChanged() } } } } override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (enableScrolling) { activity?.let { val position = recyclerViewLinearLayoutManager?.findFirstVisibleItemPosition() ?: -1 val childView = recyclerViewLinearLayoutManager?.getChildAt(0) val offset = if (childView == null) 0 else childView.top - recyclerView.paddingTop val fragment = it.supportFragmentManager.findFragmentById(R.id.main) if (fragment is EpgScrollInterface && position >= 0) { (fragment as EpgScrollInterface).onScroll(position, offset) } } } } }) // In case the channels and hours and days to show have changed invalidate // the adapter so that the UI can be updated with the new data Timber.d("Observing trigger to reload epg data") epgViewModel.viewAndEpgDataIsInvalid.observe(viewLifecycleOwner, { reload -> Timber.d("Trigger to reload epg data has changed to $reload") if (reload) { recyclerViewAdapter.loadProgramData() } }) binding.currentTime.visibleOrGone(showTimeIndication) if (showTimeIndication) { // Create the handler and the timer task that will update the // entire view every 30 minutes if the first screen is visible. // This prevents the time indication from moving to far to the right updateViewTask = object : Runnable { override fun run() { recyclerViewAdapter.notifyDataSetChanged() updateViewHandler.postDelayed(this, 1200000) } } // Create the handler and the timer task that will update the current // time indication every minute. updateTimeIndicationTask = object : Runnable { override fun run() { setCurrentTimeIndication() updateTimeIndicationHandler.postDelayed(this, 60000) } } updateViewTask?.let { updateViewHandler.postDelayed(it, 60000) } updateTimeIndicationTask?.let { updateTimeIndicationHandler.post(it) } } // The program data needs to be loaded when the fragment is created recyclerViewAdapter.loadProgramData() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) recyclerViewLinearLayoutManager?.let { outState.putParcelable("layout", it.onSaveInstanceState()) } } /** * Shows a vertical line in the program guide to indicate the current time. * It is only visible in the first screen. This method is called every minute. */ private fun setCurrentTimeIndication() { // Get the difference between the current time and the given start time. Calculate // from this value in minutes the width in pixels. This will be horizontal offset // for the time indication. If channel icons are shown then we need to add a // the icon width to the offset. val currentTime = Calendar.getInstance().timeInMillis val durationTime = (currentTime - epgViewModel.getStartTime(fragmentId)) / 1000 / 60 val offset = (durationTime * epgViewModel.pixelsPerMinute).toInt() Timber.d("Fragment id: $fragmentId, current time: $currentTime, start time: ${epgViewModel.getStartTime(fragmentId)}, offset: $offset, durationTime: $durationTime, pixelsPerMinute: ${epgViewModel.pixelsPerMinute}") // Set the left constraint of the time indication so it shows the actual time binding.currentTime.let { constraintSet.connect(it.id, ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT, offset) constraintSet.connect(it.id, ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, offset) constraintSet.applyTo(binding.constraintLayout) } } override fun onScroll(position: Int, offset: Int) { recyclerViewLinearLayoutManager?.scrollToPositionWithOffset(position, offset) } override fun onScrollStateChanged() { // NOP } companion object { fun newInstance(fragmentId: Int): EpgViewPagerFragment { val fragment = EpgViewPagerFragment() val bundle = Bundle() bundle.putInt("fragmentId", fragmentId) fragment.arguments = bundle return fragment } } }
gpl-3.0
SeunAdelekan/Kanary
src/main/com/iyanuadelekan/kanary/app/Extensions.kt
1
887
package com.iyanuadelekan.kanary.app import com.fasterxml.jackson.databind.ObjectMapper import com.iyanuadelekan.kanary.exceptions.InvalidResponseEntityException import javax.servlet.http.HttpServletResponse /** * @author Iyanu Adelekan on 24/11/2018. */ fun HttpServletResponse.withStatus(statusCode: Int): HttpServletResponse { status = statusCode return this } @Throws(InvalidResponseEntityException::class) fun <T : Any> HttpServletResponse.send(data: T) { val isValidResponseEntity = data.javaClass.getAnnotation(ResponseEntity::class.java) != null if (isValidResponseEntity) { val mapper = ObjectMapper() val json = mapper.writeValueAsString(data) contentType = "application/json" writer.print(json) println(json) // TODO remove this line. return } throw InvalidResponseEntityException() }
apache-2.0
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/service/GraphQLServiceImpl.kt
1
1924
package net.nemerosa.ontrack.graphql.service import graphql.ExecutionInput import graphql.ExecutionResult import graphql.GraphQL import graphql.execution.ExecutionStrategy import net.nemerosa.ontrack.graphql.schema.GraphqlSchemaService import net.nemerosa.ontrack.tx.TransactionService import org.springframework.beans.factory.annotation.Qualifier import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class GraphQLServiceImpl( private val graphqlSchemaService: GraphqlSchemaService, private val graphQLExceptionHandlers: List<GraphQLExceptionHandler>, @Qualifier("queryExecutionStrategy") private val queryExecutionStrategy: ExecutionStrategy, @Qualifier("queryExecutionStrategy") private val mutationExecutionStrategy: ExecutionStrategy, private val transactionService: TransactionService ) : GraphQLService { private val graphQL: GraphQL by lazy { GraphQL.newGraphQL(graphqlSchemaService.schema) .queryExecutionStrategy(queryExecutionStrategy) .mutationExecutionStrategy(mutationExecutionStrategy) .build() } override fun execute( query: String, variables: Map<String, Any>, operationName: String?, ): ExecutionResult { val result: ExecutionResult = transactionService.doInTransaction { graphQL.execute( ExecutionInput.newExecutionInput() .query(query) .operationName(operationName) .variables(variables) .build() ) } if (result.errors != null && result.errors.isNotEmpty()) { result.errors.forEach { error -> graphQLExceptionHandlers.forEach { it.handle(error) } } } return result } }
mit
kotlin-graphics/uno-sdk
vk/src/main/kotlin/uno/vk/glfw vk.kt
1
1166
package uno.vk import kool.adr import kool.mInt import org.lwjgl.glfw.GLFWVulkan import org.lwjgl.system.MemoryUtil.* import uno.glfw.GlfwWindow import uno.glfw.glfw import uno.glfw.stak import vkk.VK_CHECK_RESULT import vkk.entities.VkSurfaceKHR import vkk.identifiers.Instance // --- [ glfwVulkanSupported ] --- val glfw.vulkanSupported: Boolean get() = GLFWVulkan.glfwVulkanSupported() // --- [ glfwGetRequiredInstanceExtensions ] --- val glfw.requiredInstanceExtensions: ArrayList<String> get() = stak { val pCount = it.mInt() val ppNames = GLFWVulkan.nglfwGetRequiredInstanceExtensions(pCount.adr) val count = pCount[0] if (count == 0) arrayListOf() else { val pNames = memPointerBuffer(ppNames, count) val res = ArrayList<String>(count) for (i in 0 until count) res += memASCII(pNames[i]) res } } // --- [ glfwCreateWindowSurface ] --- infix fun Instance.createSurface(window: GlfwWindow): VkSurfaceKHR = VkSurfaceKHR(stak.longAdr { VK_CHECK_RESULT(GLFWVulkan.nglfwCreateWindowSurface(adr, window.handle.value, NULL, it)) })
mit
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/data/local/dao/AlbumDao.kt
1
952
package be.florien.anyflow.data.local.dao import androidx.lifecycle.LiveData import androidx.paging.DataSource import androidx.room.Dao import androidx.room.Query import be.florien.anyflow.data.local.model.DbAlbum import be.florien.anyflow.data.local.model.DbAlbumDisplay @Dao interface AlbumDao : BaseDao<DbAlbum> { @Query("SELECT * FROM album ORDER BY name COLLATE UNICODE") fun orderByName(): DataSource.Factory<Int, DbAlbumDisplay> @Query("SELECT * FROM album WHERE album.name LIKE :filter ORDER BY name COLLATE UNICODE") fun orderByNameFiltered(filter: String): DataSource.Factory<Int, DbAlbumDisplay> @Query("SELECT * FROM album WHERE album.name LIKE :filter ORDER BY name COLLATE UNICODE") suspend fun orderByNameFilteredList(filter: String): List<DbAlbumDisplay> @Query("UPDATE Album SET artistId = :id, artistName = :name WHERE id = :albumId") fun updateAlbumArtist(albumId: Long, id: Long, name: String) }
gpl-3.0
olonho/carkot
kotstd/kt/ByteArray.kt
1
3003
package kotlin external fun malloc_array(size: Int): Int external fun kotlinclib_byte_array_get_ix(dataRawPtr: Int, index: Int): Byte external fun kotlinclib_byte_array_set_ix(dataRawPtr: Int, index: Int, value: Byte) external fun kotlinclib_byte_size(): Int class ByteArray(var size: Int) { val dataRawPtr: Int /** Returns the number of elements in the array. */ //size: Int init { this.dataRawPtr = malloc_array(kotlinclib_byte_size() * this.size) var index = 0 while (index < this.size) { set(index, 0) index = index + 1 } } /** Returns the array element at the given [index]. This method can be called using the index operator. */ operator fun get(index: Int): Byte { return kotlinclib_byte_array_get_ix(this.dataRawPtr, index) } /** Sets the element at the given [index] to the given [value]. This method can be called using the index operator. */ operator fun set(index: Int, value: Byte) { kotlinclib_byte_array_set_ix(this.dataRawPtr, index, value) } fun clone(): ByteArray { val newInstance = ByteArray(this.size) var index = 0 while (index < this.size) { val value = this.get(index) newInstance.set(index, value) index = index + 1 } return newInstance } } fun ByteArray.print() { var index = 0 print('[') while (index < size) { print(get(index)) index++ if (index < size) { print(';') print(' ') } } print(']') } fun ByteArray.println() { this.print() //println() } fun ByteArray.copyOf(newSize: Int): ByteArray { val newInstance = ByteArray(newSize) var index = 0 val end = if (newSize > this.size) this.size else newSize while (index < end) { val value = this.get(index) newInstance.set(index, value) index = index + 1 } while (index < newSize) { newInstance.set(index, 0) index = index + 1 } return newInstance } fun ByteArray.copyOfRange(fromIndex: Int, toIndex: Int): ByteArray { val newInstance = ByteArray(toIndex - fromIndex) var index = fromIndex while (index < toIndex) { val value = this.get(index) newInstance.set(index - fromIndex, value) index = index + 1 } return newInstance } operator fun ByteArray.plus(element: Byte): ByteArray { val index = size val result = this.copyOf(index + 1) result[index] = element return result } operator fun ByteArray.plus(elements: ByteArray): ByteArray { val thisSize = size val arraySize = elements.size val resultSize = thisSize + arraySize val newInstance = this.copyOf(resultSize) var index = thisSize while (index < resultSize) { val value = elements.get(index - thisSize) newInstance.set(index, value) index = index + 1 } return newInstance }
mit
d9n/intellij-rust
debugger/src/main/kotlin/org/rust/debugger/lang/RsDebuggerTypesHelper.kt
1
1946
package org.rust.debugger.lang import com.intellij.psi.PsiElement import com.intellij.xdebugger.XSourcePosition import com.jetbrains.cidr.execution.debugger.CidrDebugProcess import com.jetbrains.cidr.execution.debugger.backend.LLValue import com.jetbrains.cidr.execution.debugger.evaluation.CidrDebuggerTypesHelper import com.jetbrains.cidr.execution.debugger.evaluation.CidrMemberValue import org.rust.lang.core.psi.RsCodeFragmentFactory import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.ext.RsCompositeElement import org.rust.lang.core.psi.ext.getNextNonCommentSibling import org.rust.lang.core.psi.ext.parentOfType class RsDebuggerTypesHelper(process: CidrDebugProcess) : CidrDebuggerTypesHelper(process) { override fun computeSourcePosition(value: CidrMemberValue): XSourcePosition? = null override fun isImplicitContextVariable(position: XSourcePosition, `var`: LLValue): Boolean? = false override fun resolveProperty(value: CidrMemberValue, dynamicTypeName: String?): XSourcePosition? = null override fun resolveToDeclaration(position: XSourcePosition, `var`: LLValue): PsiElement? { if (!isRust(position)) return delegate?.resolveToDeclaration(position, `var`) val context = getContextElement(position) return resolveToDeclaration(context, `var`.name) } private val delegate: CidrDebuggerTypesHelper? = RsDebuggerLanguageSupportFactory.DELEGATE?.createTypesHelper(process) private fun isRust(position: XSourcePosition): Boolean = getContextElement(position).containingFile is RsFile } private fun resolveToDeclaration(ctx: PsiElement?, name: String): PsiElement? { val composite = ctx?.getNextNonCommentSibling()?.parentOfType<RsCompositeElement>(strict = false) ?: return null val path = RsCodeFragmentFactory(composite.project).createLocalVariable(name, composite) ?: return null return path.reference.resolve() }
mit
goodwinnk/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/util/scenarios/ProjectStructureDialogModel.kt
1
3888
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.util.scenarios import com.intellij.testGuiFramework.fixtures.JDialogFixture import com.intellij.testGuiFramework.framework.Timeouts.defaultTimeout import com.intellij.testGuiFramework.impl.GuiTestCase import com.intellij.testGuiFramework.impl.button import com.intellij.testGuiFramework.impl.jList import com.intellij.testGuiFramework.impl.testTreeItemExist import com.intellij.testGuiFramework.util.logUIStep import com.intellij.testGuiFramework.util.scenarios.ProjectStructureDialogModel.Constants.buttonCancel import com.intellij.testGuiFramework.util.scenarios.ProjectStructureDialogModel.Constants.itemLibrary import com.intellij.testGuiFramework.util.scenarios.ProjectStructureDialogModel.Constants.menuArtifacts import com.intellij.testGuiFramework.util.scenarios.ProjectStructureDialogModel.Constants.menuFacets import com.intellij.testGuiFramework.util.scenarios.ProjectStructureDialogModel.Constants.menuLibraries import com.intellij.testGuiFramework.util.scenarios.ProjectStructureDialogModel.Constants.menuModules import com.intellij.testGuiFramework.util.scenarios.ProjectStructureDialogModel.Constants.menuSDKs import com.intellij.testGuiFramework.util.scenarios.ProjectStructureDialogModel.Constants.projectStructureTitle import com.intellij.testGuiFramework.utils.TestUtilsClass import com.intellij.testGuiFramework.utils.TestUtilsClassCompanion class ProjectStructureDialogModel(val testCase: GuiTestCase) : TestUtilsClass(testCase) { companion object : TestUtilsClassCompanion<ProjectStructureDialogModel>( { ProjectStructureDialogModel(it) } ) object Constants{ const val projectStructureTitle = "Project Structure" const val menuProject = "Project" const val menuModules = "Modules" const val menuLibraries = "Libraries" const val itemLibrary = "Library" const val menuFacets = "Facets" const val itemFacet = "Facet" const val menuArtifacts = "Artifacts" const val itemArtifact = "Artifact" const val menuSDKs = "SDKs" const val itemSDK = "SDK" const val menuGlobalLibraries = "Global Libraries" const val menuProblems = "Problems" const val buttonCancel = "Cancel" } } val GuiTestCase.projectStructureDialogModel by ProjectStructureDialogModel fun ProjectStructureDialogModel.connectDialog(): JDialogFixture = testCase.dialog(projectStructureTitle, true, defaultTimeout) fun ProjectStructureDialogModel.checkInProjectStructure(actions: GuiTestCase.()->Unit){ with(guiTestCase){ val dialog = connectDialog() try { this.actions() } finally { logUIStep("Close '$projectStructureTitle' dialog with Cancel") dialog.button(buttonCancel).click() } } } fun ProjectStructureDialogModel.checkLibraryPresent(vararg library: String){ with(guiTestCase){ val dialog = connectDialog() with(dialog){ val tabs = jList(menuLibraries) logUIStep("Click '$menuLibraries'") tabs.clickItem(menuLibraries) testTreeItemExist(itemLibrary, *library) } } } private fun ProjectStructureDialogModel.checkPage(page: String, checks: JDialogFixture.()->Unit){ with(guiTestCase){ logUIStep("Click $page") val dialog = connectDialog() dialog.jList(page).clickItem(page) dialog.checks() } } fun ProjectStructureDialogModel.checkModule(checks: JDialogFixture.()->Unit){ checkPage(menuModules, checks) } fun ProjectStructureDialogModel.checkArtifact(checks: JDialogFixture.()->Unit){ checkPage(menuArtifacts, checks) } fun ProjectStructureDialogModel.checkSDK(checks: JDialogFixture.()->Unit){ checkPage(menuSDKs, checks) } fun ProjectStructureDialogModel.checkFacet(checks: JDialogFixture.()->Unit){ checkPage(menuFacets, checks) }
apache-2.0
goodwinnk/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/RepositoryBrowser.kt
1
7752
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vcs.impl import com.intellij.ide.impl.ContentManagerWatcher import com.intellij.ide.util.treeView.AbstractTreeBuilder import com.intellij.ide.util.treeView.AbstractTreeStructure import com.intellij.ide.util.treeView.NodeDescriptor import com.intellij.openapi.actionSystem.* import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.fileChooser.ex.FileSystemTreeImpl import com.intellij.openapi.fileChooser.ex.RootFileElement import com.intellij.openapi.fileChooser.impl.FileTreeBuilder import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.fileEditor.impl.LoadTextUtil import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.RemoteFilePath import com.intellij.openapi.vcs.actions.VcsContextFactory import com.intellij.openapi.vcs.changes.ByteBackedContentRevision import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.ContentRevision import com.intellij.openapi.vcs.changes.CurrentContentRevision import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction import com.intellij.openapi.vcs.history.VcsRevisionNumber import com.intellij.openapi.vcs.vfs.AbstractVcsVirtualFile import com.intellij.openapi.vcs.vfs.VcsVirtualFile import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowAnchor import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.content.ContentFactory import com.intellij.util.PlatformIcons import java.awt.BorderLayout import java.io.File import java.util.* import javax.swing.Icon import javax.swing.JPanel import javax.swing.JTree import javax.swing.tree.DefaultTreeModel const val TOOLWINDOW_ID = "Repositories" fun showRepositoryBrowser(project: Project, root: AbstractVcsVirtualFile, localRoot: VirtualFile, title: String) { val toolWindowManager = ToolWindowManager.getInstance(project) val repoToolWindow = toolWindowManager.getToolWindow(TOOLWINDOW_ID) ?: registerRepositoriesToolWindow(toolWindowManager) for (content in repoToolWindow.contentManager.contents) { val component = content.component as? RepositoryBrowserPanel ?: continue if (component.root == root) { repoToolWindow.contentManager.setSelectedContent(content) return } } val contentPanel = RepositoryBrowserPanel(project, root, localRoot) val content = ContentFactory.SERVICE.getInstance().createContent(contentPanel, title, true) repoToolWindow.contentManager.addContent(content) repoToolWindow.contentManager.setSelectedContent(content, true) repoToolWindow.activate(null) } private fun registerRepositoriesToolWindow(toolWindowManager: ToolWindowManager): ToolWindow { val toolWindow = toolWindowManager.registerToolWindow(TOOLWINDOW_ID, true, ToolWindowAnchor.LEFT) ContentManagerWatcher(toolWindow, toolWindow.contentManager) return toolWindow } val REPOSITORY_BROWSER_DATA_KEY = DataKey.create<RepositoryBrowserPanel>("com.intellij.openapi.vcs.impl.RepositoryBrowserPanel") class RepositoryBrowserPanel( val project: Project, val root: AbstractVcsVirtualFile, val localRoot: VirtualFile ) : JPanel(BorderLayout()), DataProvider { private val fileSystemTree: FileSystemTreeImpl init { val fileChooserDescriptor = object : FileChooserDescriptor(true, false, false, false, false, true) { override fun getRoots(): List<VirtualFile> = listOf(root) override fun getIcon(file: VirtualFile): Icon? { if (file.isDirectory) { return PlatformIcons.FOLDER_ICON } return FileTypeManager.getInstance().getFileTypeByFileName(file.name).icon } } fileSystemTree = object : FileSystemTreeImpl(project, fileChooserDescriptor) { override fun createTreeBuilder(tree: JTree?, treeModel: DefaultTreeModel?, treeStructure: AbstractTreeStructure?, comparator: Comparator<NodeDescriptor<Any>>?, descriptor: FileChooserDescriptor?, onInitialized: Runnable?): AbstractTreeBuilder { return object : FileTreeBuilder(tree, treeModel, treeStructure, comparator, descriptor, onInitialized) { override fun isAutoExpandNode(nodeDescriptor: NodeDescriptor<*>): Boolean { return nodeDescriptor.element is RootFileElement } } } } fileSystemTree.addOkAction { val files = fileSystemTree.selectedFiles for (file in files) { FileEditorManager.getInstance(project).openFile(file, true) } } val actionGroup = DefaultActionGroup() actionGroup.add(ActionManager.getInstance().getAction(IdeActions.ACTION_EDIT_SOURCE)) actionGroup.add(ActionManager.getInstance().getAction("Vcs.ShowDiffWithLocal")) fileSystemTree.registerMouseListener(actionGroup) val scrollPane = ScrollPaneFactory.createScrollPane(fileSystemTree.tree) add(scrollPane, BorderLayout.CENTER) } override fun getData(dataId: String): Any? { return when { CommonDataKeys.VIRTUAL_FILE_ARRAY.`is`(dataId) -> fileSystemTree.selectedFiles CommonDataKeys.NAVIGATABLE_ARRAY.`is`(dataId) -> fileSystemTree.selectedFiles .filter { !it.isDirectory } .map { OpenFileDescriptor(project, it) } .toTypedArray() REPOSITORY_BROWSER_DATA_KEY.`is`(dataId) -> this else -> null } } fun hasSelectedFiles() = fileSystemTree.selectedFiles.any { it is VcsVirtualFile } fun getSelectionAsChanges(): List<Change> { return fileSystemTree.selectedFiles .filterIsInstance<VcsVirtualFile>() .map { createChangeVsLocal(it) } } private fun createChangeVsLocal(file: VcsVirtualFile): Change { val repoRevision = VcsVirtualFileContentRevision(file) val localPath = File(localRoot.path, file.path) val localRevision = CurrentContentRevision(VcsContextFactory.SERVICE.getInstance().createFilePathOn(localPath)) return Change(repoRevision, localRevision) } } class DiffRepoWithLocalAction : AnActionExtensionProvider { override fun isActive(e: AnActionEvent): Boolean { return e.getData(REPOSITORY_BROWSER_DATA_KEY) != null } override fun update(e: AnActionEvent) { val repoBrowser = e.getData(REPOSITORY_BROWSER_DATA_KEY) ?: return e.presentation.isEnabled = repoBrowser.hasSelectedFiles() } override fun actionPerformed(e: AnActionEvent) { val repoBrowser = e.getData(REPOSITORY_BROWSER_DATA_KEY) ?: return val changes = repoBrowser.getSelectionAsChanges() ShowDiffAction.showDiffForChange(repoBrowser.project, changes) } } class VcsVirtualFileContentRevision(private val vcsVirtualFile: VcsVirtualFile) : ContentRevision, ByteBackedContentRevision { override fun getContent(): String? { return contentAsBytes?.let { LoadTextUtil.getTextByBinaryPresentation(it, vcsVirtualFile).toString() } } override fun getContentAsBytes(): ByteArray? { return vcsVirtualFile.fileRevision?.loadContent() } override fun getFile(): FilePath { return RemoteFilePath(vcsVirtualFile.path, vcsVirtualFile.isDirectory) } override fun getRevisionNumber(): VcsRevisionNumber { return vcsVirtualFile.fileRevision?.revisionNumber ?: VcsRevisionNumber.NULL } }
apache-2.0
drakeet/MultiType
library/src/main/kotlin/com/drakeet/multitype/DelegateNotFoundException.kt
1
823
/* * Copyright (c) 2016-present. Drakeet Xu * * 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.drakeet.multitype /** * @author Drakeet Xu */ internal class DelegateNotFoundException(clazz: Class<*>) : RuntimeException( "Have you registered the ${clazz.name} type and its delegate or binder?" )
apache-2.0
MiloszKrajewski/stateful4k
src/main/java/org/softpark/stateful4k/config/states/StateConfiguration.kt
1
812
package org.softpark.stateful4k.config.states internal class StateConfiguration<C, S, E, AS: S>( override val stateType: Class<AS>): IStateConfiguration<C, S, E> { override var alias: String? = null override var onEnter: ((C, S) -> Unit)? = null override var onExit: ((C, S) -> Unit)? = null constructor(other: StateConfiguration<C, S, E, AS>): this(other.stateType) { alias = other.alias onEnter = other.onEnter onExit = other.onExit } override fun freeze(): IStateConfiguration<C, S, E> = StateConfiguration(this) override fun toString(): String = "StateConfiguration(" + "stateType:${stateType.name},alias:'$alias'," + "enter:${onEnter != null},exit:${onExit != null})" }
bsd-3-clause
jeksor/Language-Detector
app/src/main/java/com/esorokin/lantector/model/service/DetectLanguageService.kt
1
1801
package com.esorokin.lantector.model.service import com.esorokin.lantector.model.ModelWrapper import com.esorokin.lantector.model.data.DetectedLanguageText import com.esorokin.lantector.model.mapper.DetectLanguageTextMapper import com.esorokin.lantector.model.network.api.WatsonPlatformApi import com.esorokin.lantector.model.storage.Database import com.esorokin.lantector.utils.ext.subscribeIgnoreResult import com.esorokin.lantector.utils.ext.transitSuccessToEmitter import io.reactivex.Observable import io.reactivex.Single import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import javax.inject.Inject import javax.inject.Singleton @Singleton class DetectLanguageService @Inject constructor() { @Inject internal lateinit var watsonPlatformApi: WatsonPlatformApi @Inject internal lateinit var detectedTextMapper: DetectLanguageTextMapper @Inject internal lateinit var database: Database private val historyEmitter: Subject<ModelWrapper<List<DetectedLanguageText>>> = PublishSubject.create() fun historyEmitter(): Observable<ModelWrapper<List<DetectedLanguageText>>> = historyEmitter fun requestHistory() { getHistory().subscribeIgnoreResult() } fun getHistory(): Single<List<DetectedLanguageText>> { return database.getAllDetectedResults() .map { it.sortedByDescending { it.date } } .transitSuccessToEmitter(historyEmitter) } fun detectLanguage(text: String): Single<DetectedLanguageText> = watsonPlatformApi.detectLanguage(text) .map { detectedTextMapper.invoke(it, text) } .doOnSuccess { database.addDetectedResult(it) .subscribeIgnoreResult() requestHistory() } }
mit
kiruto/kotlin-android-mahjong
mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/rules/yaku/yakuimpl/33_大三元.kt
1
1684
/* * The MIT License (MIT) * * Copyright (c) 2016 yuriel<[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package dev.yuriel.kotmahjan.rules.yaku.yakuimpl import dev.yuriel.kotmahjan.models.isSanGen import dev.yuriel.kotmahjan.rules.MentsuSupport /** * Created by yuriel on 7/24/16. * 大三元判定 * 白・發・中の3種類をすべて刻子または槓子にして和了した場合に成立 */ fun 大三元Impl(s: MentsuSupport): Boolean { var sangenCount = 0 for (kotsu in s.getKotsuList()) { if (isSanGen(kotsu.getHai())) { sangenCount++ } } return sangenCount == 3 }
mit
Setekh/Gleipnir-Graphics
src/main/kotlin/eu/corvus/corax/scene/pool/ObjectPoolImpl.kt
1
1848
/** * Copyright (c) 2013-2019 Corvus Corax Entertainment * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * - Neither the name of Corvus Corax Entertainment nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package eu.corvus.corax.scene.pool import eu.corvus.corax.scene.Object /** * @author Vlad Ravenholm on 12/15/2019 */ class ObjectPoolImpl: ObjectPool { override fun create(): Int { return 0 } override fun free(obj: Object) { } }
bsd-3-clause
MimiReader/mimi-reader
mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/extensions/BoardExtension.kt
1
382
package com.emogoth.android.phone.mimi.db.extensions import com.emogoth.android.phone.mimi.db.models.Board import com.mimireader.chanlib.models.ChanBoard fun List<Board>.toChanBoards(boards: List<Board>): List<ChanBoard> { val chanBoards = ArrayList<ChanBoard>(boards.size) for (board in boards) { chanBoards.add(board.toChanBoard()) } return chanBoards }
apache-2.0
Ztiany/Repository
Kotlin/Kotlin-coroutinelite/src/main/java/com/bennyhuo/coroutines/lite/Deferred.kt
2
1022
package com.bennyhuo.coroutines.lite import kotlin.coroutines.experimental.CoroutineContext import kotlin.coroutines.experimental.suspendCoroutine /** * Created by benny on 2018/5/20. */ class Deferred<T>(context: CoroutineContext, block: suspend () -> T) : AbstractCoroutine<T>(context, block) { suspend fun await(): T { val currentState = state.get() return when (currentState) { is State.InComplete -> awaitSuspend() is State.Complete<*> -> (currentState.value as T?) ?: throw currentState.exception!! else -> throw IllegalStateException("Invalid State: $currentState") } } private suspend fun awaitSuspend() = suspendCoroutine<T> { continuation -> doOnCompleted { t, throwable -> when { t != null -> continuation.resume(t) throwable != null -> continuation.resumeWithException(throwable) else -> throw IllegalStateException("Won't happen.") } } } }
apache-2.0
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/animation/RxAbstractPathAnimator.kt
1
4579
/* * Copyright (C) 2015 tyrantgit * * 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.tamsiree.rxui.animation import android.content.res.TypedArray import android.graphics.Path import android.view.View import android.view.ViewGroup import com.tamsiree.rxui.R import java.util.* import java.util.concurrent.atomic.AtomicInteger /** * @author tamsiree */ abstract class RxAbstractPathAnimator(protected val mConfig: Config) { private val mRandom: Random = Random() fun randomRotation(): Float { return mRandom.nextFloat() * 28.6f - 14.3f } fun createPath(counter: AtomicInteger, view: View, factor: Int): Path { var factor = factor val r = mRandom var x = r.nextInt(mConfig.xRand) var x2 = r.nextInt(mConfig.xRand) val y = view.height - mConfig.initY var y2: Int = counter.toInt() * 15 + mConfig.animLength * factor + r.nextInt(mConfig.animLengthRand) factor = y2 / mConfig.bezierFactor x += mConfig.xPointFactor x2 += mConfig.xPointFactor val y3 = y - y2 y2 = y - y2 / 2 val p = Path() p.moveTo(mConfig.initX.toFloat(), y.toFloat()) p.cubicTo(mConfig.initX.toFloat(), y - factor.toFloat(), x.toFloat(), y2 + factor.toFloat(), x.toFloat(), y2.toFloat()) p.moveTo(x.toFloat(), y2.toFloat()) p.cubicTo(x.toFloat(), y2 - factor.toFloat(), x2.toFloat(), y3 + factor.toFloat(), x2.toFloat(), y3.toFloat()) return p } abstract fun start(child: View, parent: ViewGroup?) class Config { var initX = 0 var initY = 0 var xRand = 0 var animLengthRand = 0 var bezierFactor = 0 var xPointFactor = 0 var animLength = 0 @JvmField var heartWidth = 0 @JvmField var heartHeight = 0 @JvmField var animDuration = 0 companion object { @JvmStatic fun fromTypeArray(typedArray: TypedArray): Config { val config = Config() val res = typedArray.resources config.initX = typedArray.getDimension(R.styleable.RxHeartLayout_initX, res.getDimensionPixelOffset(R.dimen.heart_anim_init_x).toFloat()).toInt() config.initY = typedArray.getDimension(R.styleable.RxHeartLayout_initY, res.getDimensionPixelOffset(R.dimen.heart_anim_init_y).toFloat()).toInt() config.xRand = typedArray.getDimension(R.styleable.RxHeartLayout_xRand, res.getDimensionPixelOffset(R.dimen.heart_anim_bezier_x_rand).toFloat()).toInt() config.animLength = typedArray.getDimension(R.styleable.RxHeartLayout_animLength, res.getDimensionPixelOffset(R.dimen.heart_anim_length).toFloat()).toInt() config.animLengthRand = typedArray.getDimension(R.styleable.RxHeartLayout_animLengthRand, res.getDimensionPixelOffset(R.dimen.heart_anim_length_rand).toFloat()).toInt() config.bezierFactor = typedArray.getInteger(R.styleable.RxHeartLayout_bezierFactor, res.getInteger(R.integer.heart_anim_bezier_factor)) config.xPointFactor = typedArray.getDimension(R.styleable.RxHeartLayout_xPointFactor, res.getDimensionPixelOffset(R.dimen.heart_anim_x_point_factor).toFloat()).toInt() config.heartWidth = typedArray.getDimension(R.styleable.RxHeartLayout_heart_width, res.getDimensionPixelOffset(R.dimen.heart_size_width).toFloat()).toInt() config.heartHeight = typedArray.getDimension(R.styleable.RxHeartLayout_heart_height, res.getDimensionPixelOffset(R.dimen.heart_size_height).toFloat()).toInt() config.animDuration = typedArray.getInteger(R.styleable.RxHeartLayout_anim_duration, res.getInteger(R.integer.anim_duration)) return config } } } }
apache-2.0
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/feed/configure/ConfigureActivity.kt
1
677
package org.wikipedia.feed.configure import android.content.Context import android.content.Intent import org.wikipedia.Constants import org.wikipedia.activity.SingleFragmentActivity import org.wikipedia.feed.configure.ConfigureFragment.Companion.newInstance class ConfigureActivity : SingleFragmentActivity<ConfigureFragment>() { override fun createFragment(): ConfigureFragment { return newInstance() } companion object { fun newIntent(context: Context, invokeSource: Int): Intent { return Intent(context, ConfigureActivity::class.java) .putExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, invokeSource) } } }
apache-2.0
tbrooks8/quasar
quasar-kotlin/src/test/kotlin/co/paralleluniverse/kotlin/actors/PingPong.kt
1
3443
/* * Quasar: lightweight threads and actors for the JVM. * Copyright (c) 2015, Parallel Universe Software Co. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 3.0 * as published by the Free Software Foundation. */ package actors import co.paralleluniverse.actors.* import co.paralleluniverse.actors.behaviors.BehaviorActor import co.paralleluniverse.actors.behaviors.ProxyServerActor import co.paralleluniverse.actors.behaviors.Supervisor import co.paralleluniverse.actors.behaviors.Supervisor.* import co.paralleluniverse.actors.behaviors.Supervisor.ChildMode import co.paralleluniverse.actors.behaviors.Supervisor.ChildMode.* import co.paralleluniverse.actors.behaviors.SupervisorActor import co.paralleluniverse.actors.behaviors.SupervisorActor.* import co.paralleluniverse.actors.behaviors.SupervisorActor.RestartStrategy.* import co.paralleluniverse.fibers.Suspendable import org.junit.Test import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.* import co.paralleluniverse.kotlin.Actor import co.paralleluniverse.kotlin.Actor.Companion.Timeout import co.paralleluniverse.kotlin.* /** * @author circlespainter * @author pron */ // This example is meant to be a translation of the canonical // Erlang [ping-pong example](http://www.erlang.org/doc/getting_started/conc_prog.html#id67347). data class Msg(val txt: String, val from: ActorRef<Any?>) class Ping(val n: Int) : Actor() { @Suspendable override fun doRun() { val pong: ActorRef<Any> = ActorRegistry.getActor("pong") for(i in 1..n) { pong.send(Msg("ping", self())) // Fiber-blocking receive { // Fiber-blocking, always consume the message when (it) { "pong" -> println("Ping received pong") else -> null // Discard } } } pong.send("finished") // Fiber-blocking println("Ping exiting") } } class Pong() : Actor() { @Suspendable override fun doRun() { while (true) { // snippet Kotlin Actors example receive(1000, TimeUnit.MILLISECONDS) { // Fiber-blocking when (it) { is Msg -> { if (it.txt == "ping") it.from.send("pong") // Fiber-blocking } "finished" -> { println("Pong received 'finished', exiting") return // Non-local return, exit actor } is Timeout -> { println("Pong timeout in 'receive', exiting") return // Non-local return, exit actor } else -> defer() } } // end of snippet } } } public class KotlinPingPongActorTest { @Test public fun testActors() { val pong = spawn(register("pong", Pong())) val ping = spawn(Ping(3)) LocalActor.join(pong) LocalActor.join(ping) } }
gpl-3.0
SchibstedSpain/Leku
leku/src/main/java/com/schibstedspain/leku/locale/DefaultCountryLocaleRect.kt
1
5194
package com.schibstedspain.leku.locale import com.google.android.gms.maps.model.LatLng import java.util.Locale @SuppressWarnings("MagicNumber") internal object DefaultCountryLocaleRect { private val US_LOWER_LEFT = LatLng(16.132785, -168.372760) private val US_UPPER_RIGHT = LatLng(72.344643, -47.598995) private val UK_LOWER_LEFT = LatLng(49.495463, -8.392245) private val UK_UPPER_RIGHT = LatLng(59.409006, 2.652597) private val FRANCE_LOWER_LEFT = LatLng(42.278589, -5.631326) private val FRANCE_UPPER_RIGHT = LatLng(51.419246, 9.419559) private val ITALY_LOWER_LEFT = LatLng(36.072602, 6.344287) private val ITALY_UPPER_RIGHT = LatLng(47.255500, 19.209133) private val GERMANY_LOWER_LEFT = LatLng(47.103880, 5.556203) private val GERMANY_UPPER_RIGHT = LatLng(55.204320, 15.453816) private val GERMAN_LOWER_LEFT = LatLng(45.875834, 6.235783) // DACH Region private val GERMAN_UPPER_RIGHT = LatLng(55.130976, 16.922589) // DACH Region private val UAE_LOWER_LEFT = LatLng(22.523123, 51.513718) // United Arab Emirates private val UAE_UPPER_RIGHT = LatLng(26.188523, 56.568692) // United Arab Emirates private const val UAE_COUNTRY_CODE = "ar_ae" private val INDIA_LOWER_LEFT = LatLng(5.445640, 67.487799) private val INDIA_UPPER_RIGHT = LatLng(37.691225, 90.413055) private const val INDIA_COUNTRY_CODE = "en_in" private val SPAIN_LOWER_LEFT = LatLng(26.525467, -18.910366) private val SPAIN_UPPER_RIGHT = LatLng(43.906271, 5.394197) private const val SPAIN_COUNTRY_CODE = "es_es" private val PAKISTAN_LOWER_LEFT = LatLng(22.895428, 60.201233) private val PAKISTAN_UPPER_RIGHT = LatLng(37.228272, 76.918031) private const val PAKISTAN_COUNTRY_CODE = "en_pk" private val VIETNAM_LOWER_LEFT = LatLng(6.997486, 101.612789) private val VIETNAM_UPPER_RIGHT = LatLng(24.151926, 110.665524) private const val VIETNAM_COUNTRY_CODE = "vi_VN" private val HK_LOWER_LEFT = LatLng(22.153611, 113.835000) // Hong Kong private val HK_UPPER_RIGHT = LatLng(22.563333, 114.441389) // Hong Kong private const val HK_COUNTRY_CODE = "zh_HK" private val BRAZIL_LOWER_LEFT = LatLng(-34.990322, -75.004705) // Brazil private val BRAZIL_UPPER_RIGHT = LatLng(10.236344, -30.084353) // Brazil private const val BRAZIL_COUNTRY_CODE = "pt_BR" private val IRELAND_LOWER_LEFT = LatLng(51.304344, -10.763079) private val IRELAND_UPPER_RIGHT = LatLng(55.367338, -6.294837) private const val IRELAND_COUNTRY_CODE = "en_IE" val defaultLowerLeft: LatLng? get() = getLowerLeftFromZone(Locale.getDefault()) val defaultUpperRight: LatLng? get() = getUpperRightFromZone(Locale.getDefault()) fun getLowerLeftFromZone(locale: Locale): LatLng? { return when { Locale.US == locale -> US_LOWER_LEFT Locale.UK == locale -> UK_LOWER_LEFT Locale.FRANCE == locale -> FRANCE_LOWER_LEFT Locale.ITALY == locale -> ITALY_LOWER_LEFT Locale.GERMANY == locale -> GERMANY_LOWER_LEFT Locale.GERMAN == locale -> GERMAN_LOWER_LEFT locale.toString().equals(UAE_COUNTRY_CODE, ignoreCase = true) -> UAE_LOWER_LEFT locale.toString().equals(INDIA_COUNTRY_CODE, ignoreCase = true) -> INDIA_LOWER_LEFT locale.toString().equals(SPAIN_COUNTRY_CODE, ignoreCase = true) -> SPAIN_LOWER_LEFT locale.toString().equals(PAKISTAN_COUNTRY_CODE, ignoreCase = true) -> PAKISTAN_LOWER_LEFT locale.toString().equals(VIETNAM_COUNTRY_CODE, ignoreCase = true) -> VIETNAM_LOWER_LEFT locale.toString().equals(HK_COUNTRY_CODE, ignoreCase = true) -> HK_LOWER_LEFT locale.toString().equals(BRAZIL_COUNTRY_CODE, ignoreCase = true) -> BRAZIL_LOWER_LEFT locale.toString().equals(IRELAND_COUNTRY_CODE, ignoreCase = true) -> IRELAND_LOWER_LEFT else -> null } } fun getUpperRightFromZone(locale: Locale): LatLng? { return when { Locale.US == locale -> US_UPPER_RIGHT Locale.UK == locale -> UK_UPPER_RIGHT Locale.FRANCE == locale -> FRANCE_UPPER_RIGHT Locale.ITALY == locale -> ITALY_UPPER_RIGHT Locale.GERMANY == locale -> GERMANY_UPPER_RIGHT Locale.GERMAN == locale -> GERMAN_UPPER_RIGHT locale.toString().equals(UAE_COUNTRY_CODE, ignoreCase = true) -> UAE_UPPER_RIGHT locale.toString().equals(INDIA_COUNTRY_CODE, ignoreCase = true) -> INDIA_UPPER_RIGHT locale.toString().equals(SPAIN_COUNTRY_CODE, ignoreCase = true) -> SPAIN_UPPER_RIGHT locale.toString().equals(PAKISTAN_COUNTRY_CODE, ignoreCase = true) -> PAKISTAN_UPPER_RIGHT locale.toString().equals(VIETNAM_COUNTRY_CODE, ignoreCase = true) -> VIETNAM_UPPER_RIGHT locale.toString().equals(HK_COUNTRY_CODE, ignoreCase = true) -> HK_UPPER_RIGHT locale.toString().equals(BRAZIL_COUNTRY_CODE, ignoreCase = true) -> BRAZIL_UPPER_RIGHT locale.toString().equals(IRELAND_COUNTRY_CODE, ignoreCase = true) -> IRELAND_UPPER_RIGHT else -> null } } }
apache-2.0
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/login/LoginResetPasswordResult.kt
1
260
package org.wikipedia.login import org.wikipedia.dataclient.WikiSite internal class LoginResetPasswordResult(site: WikiSite, status: String, userName: String?, password: String?, message: String?) : LoginResult(site, status, userName, password, message)
apache-2.0
matejdro/WearMusicCenter
mobile/src/main/java/com/matejdro/wearmusiccenter/view/mainactivity/MainActivityViewModel.kt
1
285
package com.matejdro.wearmusiccenter.view.mainactivity import androidx.lifecycle.ViewModel import com.matejdro.wearmusiccenter.config.WatchInfoProvider import javax.inject.Inject class MainActivityViewModel @Inject constructor(val watchInfoProvider: WatchInfoProvider) : ViewModel()
gpl-3.0
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/view/Bank.kt
1
158
package com.stripe.android.view internal interface Bank { val id: String val code: String val displayName: String val brandIconResId: Int? }
mit
stripe/stripe-android
paymentsheet/src/test/java/com/stripe/android/paymentsheet/flowcontroller/DefaultFlowControllerInitializerTest.kt
1
19507
package com.stripe.android.paymentsheet.flowcontroller import android.app.Application import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.stripe.android.core.Logger import com.stripe.android.core.model.CountryCode import com.stripe.android.googlepaylauncher.GooglePayRepository import com.stripe.android.model.PaymentIntent import com.stripe.android.model.PaymentIntentFixtures import com.stripe.android.model.PaymentMethod import com.stripe.android.model.PaymentMethodFixtures import com.stripe.android.model.StripeIntent import com.stripe.android.paymentsheet.FakePrefsRepository import com.stripe.android.paymentsheet.PaymentSheet import com.stripe.android.paymentsheet.PaymentSheetFixtures import com.stripe.android.paymentsheet.analytics.EventReporter import com.stripe.android.paymentsheet.model.PaymentSelection import com.stripe.android.paymentsheet.model.SavedSelection import com.stripe.android.paymentsheet.model.StripeIntentValidator import com.stripe.android.paymentsheet.repositories.CustomerRepository import com.stripe.android.paymentsheet.repositories.StripeIntentRepository import com.stripe.android.ui.core.forms.resources.LpmRepository import com.stripe.android.ui.core.forms.resources.StaticLpmResourceRepository import com.stripe.android.utils.FakeCustomerRepository import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.runner.RunWith import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.MockitoAnnotations import org.mockito.kotlin.any import org.mockito.kotlin.capture import org.mockito.kotlin.mock import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import kotlin.test.BeforeTest import kotlin.test.Test @ExperimentalCoroutinesApi @RunWith(RobolectricTestRunner::class) internal class DefaultFlowControllerInitializerTest { private val testDispatcher = UnconfinedTestDispatcher() private val eventReporter = mock<EventReporter>() private val stripeIntentRepository = StripeIntentRepository.Static(PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD) private val customerRepository = FakeCustomerRepository(PAYMENT_METHODS) private val lpmResourceRepository = StaticLpmResourceRepository( LpmRepository( LpmRepository.LpmRepositoryArguments(ApplicationProvider.getApplicationContext<Application>().resources) ).apply { this.forceUpdate(listOf(PaymentMethod.Type.Card.code, PaymentMethod.Type.USBankAccount.code), null) } ) private val prefsRepository = FakePrefsRepository() private val initializer = createInitializer() @Captor private lateinit var paymentMethodTypeCaptor: ArgumentCaptor<List<PaymentMethod.Type>> private val readyGooglePayRepository = mock<GooglePayRepository>() private val unreadyGooglePayRepository = mock<GooglePayRepository>() @BeforeTest fun setup() { MockitoAnnotations.openMocks(this) whenever(readyGooglePayRepository.isReady()).thenReturn( flow { emit(true) } ) whenever(unreadyGooglePayRepository.isReady()).thenReturn( flow { emit(false) } ) } @Test fun `init without configuration should return expected result`() = runTest { assertThat( initializer.init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET ) ).isEqualTo( FlowControllerInitializer.InitResult.Success( InitData( null, PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD, emptyList(), SavedSelection.None, isGooglePayReady = false ) ) ) } @Test fun `init with configuration should return expected result`() = runTest { prefsRepository.savePaymentSelection( PaymentSelection.Saved(PaymentMethodFixtures.CARD_PAYMENT_METHOD) ) assertThat( initializer.init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY ) ).isEqualTo( FlowControllerInitializer.InitResult.Success( InitData( PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY, PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD, PAYMENT_METHODS, SavedSelection.PaymentMethod( id = "pm_123456789" ), isGooglePayReady = true ) ) ) } @Test fun `init() with no customer, and google pay ready should default saved selection to google pay`() = runTest { prefsRepository.savePaymentSelection(null) val initializer = createInitializer() assertThat( initializer.init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_GOOGLEPAY ) ).isEqualTo( FlowControllerInitializer.InitResult.Success( InitData( PaymentSheetFixtures.CONFIG_GOOGLEPAY, PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD, emptyList(), SavedSelection.GooglePay, isGooglePayReady = true ) ) ) } @Test fun `init() with no customer, and google pay not ready should default saved selection to none`() = runTest { prefsRepository.savePaymentSelection(null) val initializer = createInitializer(isGooglePayReady = false) assertThat( initializer.init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_GOOGLEPAY ) ).isEqualTo( FlowControllerInitializer.InitResult.Success( InitData( PaymentSheetFixtures.CONFIG_GOOGLEPAY, PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD, emptyList(), SavedSelection.None, isGooglePayReady = false ) ) ) } @Test fun `init() with customer payment methods, and google pay ready should default saved selection to last payment method`() = runTest { prefsRepository.savePaymentSelection(null) val initializer = createInitializer() assertThat( initializer.init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY ) ).isEqualTo( FlowControllerInitializer.InitResult.Success( InitData( PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY, PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD, PAYMENT_METHODS, SavedSelection.PaymentMethod("pm_123456789"), isGooglePayReady = true ) ) ) assertThat(prefsRepository.getSavedSelection(true, true)) .isEqualTo( SavedSelection.PaymentMethod( id = "pm_123456789" ) ) } @Test fun `init() with customer, no methods, and google pay not ready, should set first payment method as google pay`() = runTest { prefsRepository.savePaymentSelection(null) val initializer = createInitializer( isGooglePayReady = false, customerRepo = FakeCustomerRepository(emptyList()) ) assertThat( initializer.init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY ) ).isEqualTo( FlowControllerInitializer.InitResult.Success( InitData( PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY, PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD, emptyList(), SavedSelection.None, isGooglePayReady = false ) ) ) assertThat(prefsRepository.getSavedSelection(true, true)) .isEqualTo(SavedSelection.None) } @Test fun `init() with customer, no methods, and google pay ready, should set first payment method as none`() = runTest { prefsRepository.savePaymentSelection(null) val initializer = createInitializer( customerRepo = FakeCustomerRepository(emptyList()) ) assertThat( initializer.init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY ) ).isEqualTo( FlowControllerInitializer.InitResult.Success( InitData( PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY, PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD, emptyList(), SavedSelection.GooglePay, isGooglePayReady = true ) ) ) assertThat(prefsRepository.getSavedSelection(true, true)) .isEqualTo(SavedSelection.GooglePay) } @Test fun `init() with customer should fetch only supported payment method types`() = runTest { val customerRepository = mock<CustomerRepository> { whenever(it.getPaymentMethods(any(), any())).thenReturn(emptyList()) } val paymentMethodTypes = listOf( "card", // valid and supported "fpx", // valid but not supported "invalid_type" // unknown type ) val initializer = createInitializer( stripeIntentRepo = StripeIntentRepository.Static( PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD.copy( paymentMethodTypes = paymentMethodTypes ) ), customerRepo = customerRepository ) initializer.init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY ) verify(customerRepository).getPaymentMethods( any(), capture(paymentMethodTypeCaptor) ) assertThat(paymentMethodTypeCaptor.allValues.flatten()) .containsExactly(PaymentMethod.Type.Card) } @Test fun `when allowsDelayedPaymentMethods is false then delayed payment methods are filtered out`() = runTest { val customerRepository = mock<CustomerRepository> { whenever(it.getPaymentMethods(any(), any())).thenReturn(emptyList()) } val initializer = createInitializer( stripeIntentRepo = StripeIntentRepository.Static( PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD.copy( paymentMethodTypes = listOf( PaymentMethod.Type.Card.code, PaymentMethod.Type.SepaDebit.code, PaymentMethod.Type.AuBecsDebit.code ) ) ), customerRepo = customerRepository ) initializer.init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY ) verify(customerRepository).getPaymentMethods( any(), capture(paymentMethodTypeCaptor) ) assertThat(paymentMethodTypeCaptor.value) .containsExactly(PaymentMethod.Type.Card) } @Test fun `init() with customer should filter out invalid payment method types`() = runTest { val initResult = createInitializer( stripeIntentRepo = StripeIntentRepository.Static( PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD ), customerRepo = FakeCustomerRepository( listOf( PaymentMethodFixtures.CARD_PAYMENT_METHOD.copy(card = null), // invalid PaymentMethodFixtures.CARD_PAYMENT_METHOD ) ) ).init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY ) as FlowControllerInitializer.InitResult.Success assertThat(initResult.initData.paymentMethods) .containsExactly(PaymentMethodFixtures.CARD_PAYMENT_METHOD) } @Test fun `init() when PaymentIntent has invalid status should return null`() = runTest { val result = createInitializer( stripeIntentRepo = StripeIntentRepository.Static( PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD.copy( status = StripeIntent.Status.Succeeded ) ) ).init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, PaymentSheetFixtures.CONFIG_CUSTOMER_WITH_GOOGLEPAY ) assertThat(result) .isInstanceOf(FlowControllerInitializer.InitResult::class.java) } @Test fun `init() when PaymentIntent has invalid confirmationMethod should return null`() = runTest { val result = createInitializer( stripeIntentRepo = StripeIntentRepository.Static( PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD.copy( confirmationMethod = PaymentIntent.ConfirmationMethod.Manual ) ) ).init( PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET ) assertThat(result) .isInstanceOf(FlowControllerInitializer.InitResult::class.java) } @Test fun `Defaults to Google Play for guests if Link is not enabled`() = runTest { val result = createInitializer( stripeIntentRepo = StripeIntentRepository.Static( PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD ) ).init( clientSecret = PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, paymentSheetConfiguration = mockConfiguration() ) as FlowControllerInitializer.InitResult.Success assertThat(result.initData.savedSelection).isEqualTo(SavedSelection.GooglePay) } @Test fun `Defaults to Link for guests if available`() = runTest { val result = createInitializer( stripeIntentRepo = StripeIntentRepository.Static( PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD ), isLinkEnabled = true ).init( clientSecret = PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, // The mock configuration is necessary to enable Google Pay. We want to do that, // so that we can check that Link is preferred. paymentSheetConfiguration = mockConfiguration() ) as FlowControllerInitializer.InitResult.Success assertThat(result.initData.savedSelection).isEqualTo(SavedSelection.Link) } @Test fun `Defaults to first existing payment method for known customer`() = runTest { val result = createInitializer( stripeIntentRepo = StripeIntentRepository.Static( PaymentIntentFixtures.PI_REQUIRES_PAYMENT_METHOD ), customerRepo = FakeCustomerRepository(paymentMethods = PAYMENT_METHODS) ).init( clientSecret = PaymentSheetFixtures.PAYMENT_INTENT_CLIENT_SECRET, paymentSheetConfiguration = mockConfiguration( customer = PaymentSheet.CustomerConfiguration( id = "some_id", ephemeralKeySecret = "some_key" ) ) ) as FlowControllerInitializer.InitResult.Success val expectedPaymentMethodId = requireNotNull(PAYMENT_METHODS.first().id) assertThat(result.initData.savedSelection).isEqualTo(SavedSelection.PaymentMethod(id = expectedPaymentMethodId)) } private fun createInitializer( isGooglePayReady: Boolean = true, isLinkEnabled: Boolean = false, stripeIntentRepo: StripeIntentRepository = stripeIntentRepository, customerRepo: CustomerRepository = customerRepository ): FlowControllerInitializer { return DefaultFlowControllerInitializer( { prefsRepository }, { if (isGooglePayReady) readyGooglePayRepository else unreadyGooglePayRepository }, stripeIntentRepo, StripeIntentValidator(), customerRepo, lpmResourceRepository, Logger.noop(), eventReporter, testDispatcher, isLinkEnabled ) } private fun mockConfiguration( customer: PaymentSheet.CustomerConfiguration? = null, isGooglePayEnabled: Boolean = true ): PaymentSheet.Configuration { return PaymentSheet.Configuration( merchantDisplayName = "Merchant", customer = customer, googlePay = PaymentSheet.GooglePayConfiguration( environment = PaymentSheet.GooglePayConfiguration.Environment.Test, countryCode = CountryCode.US.value ).takeIf { isGooglePayEnabled } ) } private companion object { private val PAYMENT_METHODS = listOf(PaymentMethodFixtures.CARD_PAYMENT_METHOD) + PaymentMethodFixtures.createCards(5) } }
mit
noloman/keddit
app/src/main/java/me/manulorenzo/keddit/network/RedditRestApiImpl.kt
1
432
package me.manulorenzo.keddit.network import com.droidcba.kedditbysteps.api.RedditNewsResponse import retrofit2.Call import javax.inject.Inject /** * Created by Manuel Lorenzo on 07/11/2016. */ class RedditRestApiImpl @Inject constructor(val redditApi: RedditApi) : RedditRestApiInterface { override fun getNews(after: String, limit: String): Call<RedditNewsResponse> { return redditApi.getTop(after, limit) } }
mit
dantman/gradle-mdicons
src/main/kotlin/com.tmiyamon.mdicons/ext/Util.kt
1
1392
package com.tmiyamon.mdicons.ext import com.tmiyamon.mdicons import com.tmiyamon.mdicons.Extension import com.tmiyamon.mdicons.MaterialDesignIconsPlugin import org.gradle.api.Project import org.gradle.api.Task import java.io.FileFilter fun getExtensionOf(project: Project): mdicons.Extension { return project.getExtensions().getByType(javaClass<Extension>()) } fun <T: Task> Project.taskOf(taskClass: Class<T>): Task { return task(mapOf( "type" to taskClass, "group" to "MaterialDesignIcons" ), "${MaterialDesignIconsPlugin.NAME}${taskClass.getSimpleName()}") } fun compose<A, B, C>(f: (B) -> C, g: (A) -> B): (A) -> C { return { x -> f(g(x)) } } fun composeFileFilter(vararg filters: FileFilter): FileFilter { return FileFilter { file -> filters.fold(true) { acc, f -> acc && f.accept(file) } } } fun trace(vararg s: Any) { MaterialDesignIconsPlugin.logger.trace(s.map { it.toString() }.join(" ")) } fun debug(vararg s: Any) { MaterialDesignIconsPlugin.logger.debug(s.map { it.toString() }.join(" ")) } fun info(vararg s: Any) { MaterialDesignIconsPlugin.logger.info(s.map { it.toString() }.join(" ")) } fun warn(vararg s: Any) { MaterialDesignIconsPlugin.logger.warn(s.map { it.toString() }.join(" ")) } fun error(vararg s: Any) { MaterialDesignIconsPlugin.logger.error(s.map { it.toString() }.join(" ")) }
apache-2.0
stripe/stripe-android
link/src/test/java/com/stripe/android/link/ui/inline/InlineSignupViewModelTest.kt
1
13210
package com.stripe.android.link.ui.inline import com.google.common.truth.Truth.assertThat import com.stripe.android.core.Logger import com.stripe.android.core.exception.APIConnectionException import com.stripe.android.core.model.CountryCode import com.stripe.android.link.LinkPaymentLauncher import com.stripe.android.link.account.LinkAccountManager import com.stripe.android.link.analytics.LinkEventsReporter import com.stripe.android.link.model.LinkAccount import com.stripe.android.link.ui.signup.SignUpState import com.stripe.android.link.ui.signup.SignUpViewModel import com.stripe.android.model.ConsumerSession import com.stripe.android.model.PaymentIntent import com.stripe.android.ui.core.elements.PhoneNumberController import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.advanceTimeBy import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import kotlin.test.AfterTest import kotlin.test.BeforeTest @ExperimentalCoroutinesApi @RunWith(RobolectricTestRunner::class) class InlineSignupViewModelTest { private val linkAccountManager = mock<LinkAccountManager>() private val linkEventsReporter = mock<LinkEventsReporter>() @BeforeTest fun setUp() { Dispatchers.setMain(UnconfinedTestDispatcher()) } @AfterTest fun tearDown() { Dispatchers.resetMain() } @Test fun `When email is provided it should not trigger lookup and should collect phone number`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel(prefilledEmail = CUSTOMER_EMAIL) viewModel.toggleExpanded() assertThat(viewModel.viewState.value.signUpState).isEqualTo(SignUpState.InputtingPhoneOrName) verify(linkAccountManager, times(0)).lookupConsumer(any(), any()) } @Test fun `When email and phone are provided it should prefill all values`() = runTest(UnconfinedTestDispatcher()) { val viewModel = InlineSignupViewModel( config = LinkPaymentLauncher.Configuration( stripeIntent = mockStripeIntent(), merchantName = MERCHANT_NAME, customerEmail = CUSTOMER_EMAIL, customerPhone = CUSTOMER_PHONE, customerName = CUSTOMER_NAME, customerBillingCountryCode = CUSTOMER_BILLING_COUNTRY_CODE, shippingValues = null, ), linkAccountManager = linkAccountManager, linkEventsReporter = linkEventsReporter, logger = Logger.noop() ) viewModel.toggleExpanded() assertThat(viewModel.viewState.value.signUpState).isEqualTo(SignUpState.InputtingPhoneOrName) assertThat(viewModel.phoneController.initialPhoneNumber).isEqualTo(CUSTOMER_PHONE) verify(linkAccountManager, times(0)).lookupConsumer(any(), any()) } @Test fun `When email lookup call fails then useLink is false`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.toggleExpanded() viewModel.emailController.onRawValueChange("[email protected]") whenever(linkAccountManager.lookupConsumer(any(), any())) .thenReturn(Result.failure(APIConnectionException())) // Advance past lookup debounce delay advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100) assertThat(viewModel.viewState.value.useLink).isEqualTo(false) whenever(linkAccountManager.lookupConsumer(any(), any())) .thenReturn(Result.success(mock())) viewModel.emailController.onRawValueChange("[email protected]") // Advance past lookup debounce delay advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100) assertThat(viewModel.viewState.value.useLink).isEqualTo(true) } @Test fun `When entered existing account then it emits user input`() = runTest(UnconfinedTestDispatcher()) { val email = "[email protected]" val viewModel = createViewModel() viewModel.toggleExpanded() viewModel.emailController.onRawValueChange(email) val linkAccount = LinkAccount( mockConsumerSessionWithVerificationSession( ConsumerSession.VerificationSession.SessionType.Sms, ConsumerSession.VerificationSession.SessionState.Started ) ) whenever(linkAccountManager.lookupConsumer(any(), any())) .thenReturn(Result.success(linkAccount)) // Advance past lookup debounce delay advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100) assertThat(viewModel.viewState.value.userInput).isEqualTo(UserInput.SignIn(email)) } @Test fun `When entered non-existing account then it collects phone number`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.toggleExpanded() viewModel.emailController.onRawValueChange("[email protected]") whenever(linkAccountManager.lookupConsumer(any(), any())) .thenReturn(Result.success(null)) // Advance past lookup debounce delay advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100) assertThat(viewModel.viewState.value.userInput).isNull() assertThat(viewModel.viewState.value.signUpState).isEqualTo(SignUpState.InputtingPhoneOrName) } @Test fun `When user input becomes invalid then it emits null user input`() = runTest(UnconfinedTestDispatcher()) { val email = "[email protected]" val viewModel = createViewModel() viewModel.toggleExpanded() viewModel.emailController.onRawValueChange(email) assertThat(viewModel.viewState.value.userInput).isNull() whenever(linkAccountManager.lookupConsumer(any(), any())) .thenReturn(Result.success(null)) // Advance past lookup debounce delay advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100) assertThat(viewModel.viewState.value.userInput).isNull() val phone = "1234567890" viewModel.phoneController.onRawValueChange(phone) assertThat(viewModel.viewState.value.userInput) .isEqualTo(UserInput.SignUp(email, "+1$phone", "US", name = null)) viewModel.phoneController.onRawValueChange("") assertThat(viewModel.viewState.value.userInput).isNull() } @Test fun `When user checks box then analytics event is sent`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.toggleExpanded() verify(linkEventsReporter).onInlineSignupCheckboxChecked() } @Test fun `When signup starts then analytics event is sent`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel() viewModel.toggleExpanded() viewModel.emailController.onRawValueChange("[email protected]") whenever(linkAccountManager.lookupConsumer(any(), any())) .thenReturn(Result.success(null)) // Advance past lookup debounce delay advanceTimeBy(SignUpViewModel.LOOKUP_DEBOUNCE_MS + 100) assertThat(viewModel.viewState.value.signUpState).isEqualTo(SignUpState.InputtingPhoneOrName) verify(linkEventsReporter).onSignupStarted(true) } @Test fun `User input is valid without name for US users`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel(countryCode = CountryCode.US) viewModel.toggleExpanded() viewModel.emailController.onRawValueChange("[email protected]") viewModel.phoneController.onRawValueChange("1234567890") assertThat(viewModel.viewState.value.userInput).isEqualTo( UserInput.SignUp( email = "[email protected]", phone = "+11234567890", country = CountryCode.US.value, name = null ) ) } @Test fun `User input is only valid with name for non-US users`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel(countryCode = CountryCode.CA) viewModel.toggleExpanded() viewModel.emailController.onRawValueChange("[email protected]") viewModel.phoneController.selectCanadianPhoneNumber() viewModel.phoneController.onRawValueChange("1234567890") assertThat(viewModel.viewState.value.userInput).isNull() viewModel.nameController.onRawValueChange("Someone from Canada") assertThat(viewModel.viewState.value.userInput).isEqualTo( UserInput.SignUp( email = "[email protected]", phone = "+11234567890", country = CountryCode.CA.value, name = "Someone from Canada" ) ) } @Test fun `Prefilled values are handled correctly`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel( countryCode = CountryCode.GB, prefilledEmail = CUSTOMER_EMAIL, prefilledName = CUSTOMER_NAME, prefilledPhone = "+44$CUSTOMER_PHONE" ) viewModel.toggleExpanded() val expectedInput = UserInput.SignUp( email = CUSTOMER_EMAIL, phone = "+44$CUSTOMER_PHONE", country = CountryCode.GB.value, name = CUSTOMER_NAME ) assertThat(viewModel.viewState.value.userInput).isEqualTo(expectedInput) } @Test fun `E-mail is required for user input to be valid`() = runTest(UnconfinedTestDispatcher()) { val viewModel = createViewModel( countryCode = CountryCode.GB, prefilledName = CUSTOMER_NAME, prefilledPhone = "+44$CUSTOMER_PHONE" ) viewModel.toggleExpanded() assertThat(viewModel.viewState.value.userInput).isNull() viewModel.emailController.onRawValueChange("[email protected]") assertThat(viewModel.viewState.value.userInput).isNotNull() } private fun createViewModel( countryCode: CountryCode = CountryCode.US, prefilledEmail: String? = null, prefilledName: String? = null, prefilledPhone: String? = null ) = InlineSignupViewModel( config = LinkPaymentLauncher.Configuration( stripeIntent = mockStripeIntent(countryCode), merchantName = MERCHANT_NAME, customerEmail = prefilledEmail, customerName = prefilledName, customerPhone = prefilledPhone, customerBillingCountryCode = null, shippingValues = null, ), linkAccountManager = linkAccountManager, linkEventsReporter = linkEventsReporter, logger = Logger.noop() ) private fun mockConsumerSessionWithVerificationSession( type: ConsumerSession.VerificationSession.SessionType, state: ConsumerSession.VerificationSession.SessionState ): ConsumerSession { val verificationSession = mock<ConsumerSession.VerificationSession>() whenever(verificationSession.type).thenReturn(type) whenever(verificationSession.state).thenReturn(state) val verificationSessions = listOf(verificationSession) val consumerSession = mock<ConsumerSession>() whenever(consumerSession.verificationSessions).thenReturn(verificationSessions) whenever(consumerSession.clientSecret).thenReturn("secret") whenever(consumerSession.emailAddress).thenReturn("email") return consumerSession } private fun mockStripeIntent( countryCode: CountryCode = CountryCode.US ): PaymentIntent = mock { on { this.countryCode } doReturn countryCode.value } private fun PhoneNumberController.selectCanadianPhoneNumber() { val canada = countryDropdownController.displayItems.indexOfFirst { it.contains("Canada") } onSelectedCountryIndex(canada) } private companion object { const val MERCHANT_NAME = "merchantName" const val CUSTOMER_EMAIL = "[email protected]" const val CUSTOMER_PHONE = "1234567890" const val CUSTOMER_NAME = "Customer" const val CUSTOMER_BILLING_COUNTRY_CODE = "US" } }
mit
andimage/PCBridge
src/main/kotlin/com/projectcitybuild/repositories/PlayerConfigRepository.kt
1
2223
package com.projectcitybuild.repositories import com.projectcitybuild.core.infrastructure.database.DataSource import com.projectcitybuild.entities.PlayerConfig import com.projectcitybuild.modules.playercache.PlayerConfigCache import java.time.LocalDateTime import java.util.UUID import javax.inject.Inject class PlayerConfigRepository @Inject constructor( private val cache: PlayerConfigCache, private val dataSource: DataSource ) { fun get(uuid: UUID): PlayerConfig? { val cachedPlayer = cache.get(uuid) if (cachedPlayer != null) { return cachedPlayer } val row = dataSource.database().getFirstRow( "SELECT * FROM players WHERE `uuid`=(?) LIMIT 1", uuid.toString() ) if (row != null) { val deserializedPlayer = PlayerConfig( id = row.get("id"), uuid = UUID.fromString(row.get("uuid")), isMuted = row.get("is_muted"), isAllowingTPs = row.get("is_allowing_tp"), firstSeen = row.get("first_seen"), ) cache.put(uuid, deserializedPlayer) return deserializedPlayer } return null } fun add(uuid: UUID, isMuted: Boolean, isAllowingTPs: Boolean, firstSeen: LocalDateTime): PlayerConfig { val lastInsertedId = dataSource.database().executeInsert( "INSERT INTO players VALUES (NULL, ?, ?, ?, ?)", uuid.toString(), isMuted, isAllowingTPs, firstSeen, ) val playerConfig = PlayerConfig( id = lastInsertedId, uuid, isMuted, isAllowingTPs, firstSeen, ) cache.put(uuid, playerConfig) return playerConfig } fun save(player: PlayerConfig) { cache.put(player.uuid, player) dataSource.database().executeUpdate( "UPDATE players SET `uuid` = ?, `is_muted` = ?, `is_allowing_tp` = ?, `first_seen` = ? WHERE `id`= ?", player.uuid.toString(), player.isMuted, player.isAllowingTPs, player.firstSeen, player.id, ) } }
mit
AndroidX/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/ColorLightTokens.kt
3
2144
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // VERSION: v0_103 // GENERATED CODE - DO NOT MODIFY BY HAND package androidx.compose.material3.tokens internal object ColorLightTokens { val Background = PaletteTokens.Neutral99 val Error = PaletteTokens.Error40 val ErrorContainer = PaletteTokens.Error90 val InverseOnSurface = PaletteTokens.Neutral95 val InversePrimary = PaletteTokens.Primary80 val InverseSurface = PaletteTokens.Neutral20 val OnBackground = PaletteTokens.Neutral10 val OnError = PaletteTokens.Error100 val OnErrorContainer = PaletteTokens.Error10 val OnPrimary = PaletteTokens.Primary100 val OnPrimaryContainer = PaletteTokens.Primary10 val OnSecondary = PaletteTokens.Secondary100 val OnSecondaryContainer = PaletteTokens.Secondary10 val OnSurface = PaletteTokens.Neutral10 val OnSurfaceVariant = PaletteTokens.NeutralVariant30 val OnTertiary = PaletteTokens.Tertiary100 val OnTertiaryContainer = PaletteTokens.Tertiary10 val Outline = PaletteTokens.NeutralVariant50 val OutlineVariant = PaletteTokens.NeutralVariant80 val Primary = PaletteTokens.Primary40 val PrimaryContainer = PaletteTokens.Primary90 val Scrim = PaletteTokens.Neutral0 val Secondary = PaletteTokens.Secondary40 val SecondaryContainer = PaletteTokens.Secondary90 val Surface = PaletteTokens.Neutral99 val SurfaceTint = Primary val SurfaceVariant = PaletteTokens.NeutralVariant90 val Tertiary = PaletteTokens.Tertiary40 val TertiaryContainer = PaletteTokens.Tertiary90 }
apache-2.0
AndroidX/androidx
tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/grid/LazySemantics.kt
3
7482
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.foundation.lazy.grid import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.gestures.animateScrollBy import androidx.compose.foundation.lazy.layout.LazyLayoutItemProvider import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.CollectionInfo import androidx.compose.ui.semantics.ScrollAxisRange import androidx.compose.ui.semantics.collectionInfo import androidx.compose.ui.semantics.horizontalScrollAxisRange import androidx.compose.ui.semantics.indexForKey import androidx.compose.ui.semantics.scrollBy import androidx.compose.ui.semantics.scrollToIndex import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.verticalScrollAxisRange import androidx.tv.foundation.lazy.layout.LazyLayoutSemanticState import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @OptIn(ExperimentalFoundationApi::class) @Composable internal fun rememberLazyGridSemanticState( state: TvLazyGridState, itemProvider: LazyLayoutItemProvider, reverseScrolling: Boolean ): LazyLayoutSemanticState = remember(state, itemProvider, reverseScrolling) { object : LazyLayoutSemanticState { override fun scrollAxisRange(): ScrollAxisRange = ScrollAxisRange( value = { // This is a simple way of representing the current position without // needing any lazy items to be measured. It's good enough so far, because // screen-readers care mostly about whether scroll position changed or not // rather than the actual offset in pixels. state.firstVisibleItemIndex + state.firstVisibleItemScrollOffset / 100_000f }, maxValue = { if (state.canScrollForward) { // If we can scroll further, we don't know the end yet, // but it's upper bounded by #items + 1 itemProvider.itemCount + 1f } else { // If we can't scroll further, the current value is the max state.firstVisibleItemIndex + state.firstVisibleItemScrollOffset / 100_000f } }, reverseScrolling = reverseScrolling ) override suspend fun animateScrollBy(delta: Float) { state.animateScrollBy(delta) } override suspend fun scrollToItem(index: Int) { state.scrollToItem(index) } // TODO(popam): check if this is correct - it would be nice to provide correct columns override fun collectionInfo(): CollectionInfo = CollectionInfo(rowCount = -1, columnCount = -1) } } @OptIn(ExperimentalFoundationApi::class) @Suppress("ComposableModifierFactory", "ModifierInspectorInfo") @Composable internal fun Modifier.lazyGridSemantics( itemProvider: LazyGridItemProvider, state: TvLazyGridState, coroutineScope: CoroutineScope, isVertical: Boolean, reverseScrolling: Boolean, userScrollEnabled: Boolean ) = this.then( remember( itemProvider, state, isVertical, reverseScrolling, userScrollEnabled ) { val indexForKeyMapping: (Any) -> Int = { needle -> val key = itemProvider::getKey var result = -1 for (index in 0 until itemProvider.itemCount) { if (key(index) == needle) { result = index break } } result } val accessibilityScrollState = ScrollAxisRange( value = { // This is a simple way of representing the current position without // needing any lazy items to be measured. It's good enough so far, because // screen-readers care mostly about whether scroll position changed or not // rather than the actual offset in pixels. state.firstVisibleItemIndex + state.firstVisibleItemScrollOffset / 100_000f }, maxValue = { if (state.canScrollForward) { // If we can scroll further, we don't know the end yet, // but it's upper bounded by #items + 1 itemProvider.itemCount + 1f } else { // If we can't scroll further, the current value is the max state.firstVisibleItemIndex + state.firstVisibleItemScrollOffset / 100_000f } }, reverseScrolling = reverseScrolling ) val scrollByAction: ((x: Float, y: Float) -> Boolean)? = if (userScrollEnabled) { { x, y -> val delta = if (isVertical) { y } else { x } coroutineScope.launch { (state as ScrollableState).animateScrollBy(delta) } // TODO(aelias): is it important to return false if we know in advance we cannot scroll? true } } else { null } val scrollToIndexAction: ((Int) -> Boolean)? = if (userScrollEnabled) { { index -> require(index >= 0 && index < state.layoutInfo.totalItemsCount) { "Can't scroll to index $index, it is out of " + "bounds [0, ${state.layoutInfo.totalItemsCount})" } coroutineScope.launch { state.scrollToItem(index) } true } } else { null } // TODO(popam): check if this is correct - it would be nice to provide correct columns here val collectionInfo = CollectionInfo(rowCount = -1, columnCount = -1) Modifier.semantics { indexForKey(indexForKeyMapping) if (isVertical) { verticalScrollAxisRange = accessibilityScrollState } else { horizontalScrollAxisRange = accessibilityScrollState } if (scrollByAction != null) { scrollBy(action = scrollByAction) } if (scrollToIndexAction != null) { scrollToIndex(action = scrollToIndexAction) } this.collectionInfo = collectionInfo } } )
apache-2.0
Heapy/Heap
backend-store-postgres/src/main/kotlin/io/heapy/crm/komodo/store/postgres/indexes/Indexes.kt
1
634
/* * This file is generated by jOOQ. */ package io.heapy.crm.komodo.store.postgres.indexes import io.heapy.crm.komodo.store.postgres.tables.FlywaySchemaHistory import org.jooq.Index import org.jooq.impl.DSL import org.jooq.impl.Internal // ------------------------------------------------------------------------- // INDEX definitions // ------------------------------------------------------------------------- val FLYWAY_SCHEMA_HISTORY_S_IDX: Index = Internal.createIndex(DSL.name("flyway_schema_history_s_idx"), FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY, arrayOf(FlywaySchemaHistory.FLYWAY_SCHEMA_HISTORY.SUCCESS), false)
gpl-3.0
ioc1778/incubator
incubator-etc/src/main/java/com/riaektiv/guice/EventHandler.kt
2
204
package com.riaektiv.guice /** * Coding With Passion Since 1991 * Created: 4/30/2017, 8:03 PM Eastern Time * @author Sergey Chuykov */ interface EventHandler<E : Event> { fun handle(event: E) }
bsd-3-clause
Undin/intellij-rust
src/test/kotlin/org/rust/ide/formatter/RsAutoIndentMacrosTest.kt
3
9684
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.formatter import org.rust.ide.typing.RsTypingTestBase class RsAutoIndentMacrosTest : RsTypingTestBase() { fun `test macro call argument one line braces`() = doTestByText(""" foo! {/*caret*/} """, """ foo! { /*caret*/ } """) fun `test macro call argument one line parens`() = doTestByText(""" foo! (/*caret*/); """, """ foo! ( /*caret*/ ); """) fun `test macro call argument one line brackets`() = doTestByText(""" foo! [/*caret*/]; """, """ foo! [ /*caret*/ ]; """) fun `test macro call argument two lines`() = doTestByText(""" foo! {/*caret*/ } """, """ foo! { /*caret*/ } """) fun `test macro call argument one line with extra token`() = doTestByText(""" foo! {/*caret*/foo} """, """ foo! { /*caret*/foo} """) fun `test macro call argument tt one line braces`() = doTestByText(""" foo! { {/*caret*/} } """, """ foo! { { /*caret*/ } } """) fun `test macro call argument tt one line parens`() = doTestByText(""" foo! { (/*caret*/) } """, """ foo! { ( /*caret*/ ) } """) fun `test macro call argument tt one line brackets`() = doTestByText(""" foo! { [/*caret*/] } """, """ foo! { [ /*caret*/ ] } """) fun `test macro call argument tt one line with extra token`() = doTestByText(""" foo! { {/*caret*/foo} } """, """ foo! { { /*caret*/foo} } """) fun `test macro definition body one line braces`() = doTestByText(""" macro_rules! foo {/*caret*/} """, """ macro_rules! foo { /*caret*/ } """) fun `test macro definition body one line parens`() = doTestByText(""" macro_rules! foo (/*caret*/); """, """ macro_rules! foo ( /*caret*/ ); """) fun `test macro definition body one line brackets`() = doTestByText(""" macro_rules! foo [/*caret*/]; """, """ macro_rules! foo [ /*caret*/ ]; """) fun `test macro definition body two lines`() = doTestByText(""" macro_rules! foo {/*caret*/ } """, """ macro_rules! foo { /*caret*/ } """) fun `test macro definition body one line with extra tokens`() = doTestByText(""" macro_rules! foo {/*caret*/() => {}} """, """ macro_rules! foo { /*caret*/() => {}} """) fun `test macro definition case pattern one line parens`() = doTestByText(""" macro_rules! foo { (/*caret*/) => {} } """, """ macro_rules! foo { ( /*caret*/ ) => {} } """) fun `test macro definition case pattern one line braces`() = doTestByText(""" macro_rules! foo { {/*caret*/} => {} } """, """ macro_rules! foo { { /*caret*/ } => {} } """) fun `test macro definition case pattern one line brackets`() = doTestByText(""" macro_rules! foo { [/*caret*/] => {} } """, """ macro_rules! foo { [ /*caret*/ ] => {} } """) fun `test macro definition case pattern one line with extra token`() = doTestByText(""" macro_rules! foo { (/*caret*/foo) => {} } """, """ macro_rules! foo { ( /*caret*/foo) => {} } """) fun `test macro definition case body one line braces`() = doTestByText(""" macro_rules! foo { () => {/*caret*/} } """, """ macro_rules! foo { () => { /*caret*/ } } """) fun `test macro definition case body one line parens`() = doTestByText(""" macro_rules! foo { () => (/*caret*/) } """, """ macro_rules! foo { () => ( /*caret*/ ) } """) fun `test macro definition case body one line brackets`() = doTestByText(""" macro_rules! foo { () => [/*caret*/] } """, """ macro_rules! foo { () => [ /*caret*/ ] } """) fun `test macro definition case body one line with extra token`() = doTestByText(""" macro_rules! foo { () => {/*caret*/foo} } """, """ macro_rules! foo { () => { /*caret*/foo} } """) fun `test macro definition case body tt one line braces`() = doTestByText(""" macro_rules! foo { () => { {/*caret*/} } } """, """ macro_rules! foo { () => { { /*caret*/ } } } """) fun `test macro definition case body tt one line parens`() = doTestByText(""" macro_rules! foo { () => { (/*caret*/) } } """, """ macro_rules! foo { () => { ( /*caret*/ ) } } """) fun `test macro definition case body tt one line brackets`() = doTestByText(""" macro_rules! foo { () => { [/*caret*/] } } """, """ macro_rules! foo { () => { [ /*caret*/ ] } } """) fun `test macro definition case body tt one line with extra token`() = doTestByText(""" macro_rules! foo { () => { {/*caret*/foo} } } """, """ macro_rules! foo { () => { { /*caret*/foo} } } """) fun `test macro definition case body tt 2 one line braces`() = doTestByText(""" macro_rules! foo { () => { { {/*caret*/} } } } """, """ macro_rules! foo { () => { { { /*caret*/ } } } } """) fun `test macro definition case body tt 2 one line parens`() = doTestByText(""" macro_rules! foo { () => { { (/*caret*/) } } } """, """ macro_rules! foo { () => { { ( /*caret*/ ) } } } """) fun `test macro definition case body tt 2 one line brackets`() = doTestByText(""" macro_rules! foo { () => { { [/*caret*/] } } } """, """ macro_rules! foo { () => { { [ /*caret*/ ] } } } """) fun `test macro definition case body tt 2 one line with extra token`() = doTestByText(""" macro_rules! foo { () => { { {/*caret*/foo} } } } """, """ macro_rules! foo { () => { { { /*caret*/foo} } } } """) fun `test macro definition case pattern between tokens 1`() = doTestByText(""" macro_rules! foo { ( foo/*caret*/ bar ) => {} } """, """ macro_rules! foo { ( foo /*caret*/ bar ) => {} } """) fun `test macro definition case pattern between tokens 2`() = doTestByText(""" macro_rules! foo { ( foo/*caret*/bar baz ) => {} } """, """ macro_rules! foo { ( foo /*caret*/bar baz ) => {} } """) fun `test macro definition case body between tokens 1`() = doTestByText(""" macro_rules! foo { () => { foo/*caret*/ bar } } """, """ macro_rules! foo { () => { foo /*caret*/ bar } } """) fun `test macro definition case body between tokens 2`() = doTestByText(""" macro_rules! foo { () => { foo/*caret*/bar baz } } """, """ macro_rules! foo { () => { foo /*caret*/bar baz } } """) }
mit
mvarnagiris/expensius
app/src/main/kotlin/com/mvcoding/expensius/feature/settings/SettingsModule.kt
1
1972
/* * Copyright (C) 2017 Mantas Varnagiris. * * 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. */ package com.mvcoding.expensius.feature.settings import android.app.Activity import com.memoizrlabs.Scope import com.memoizrlabs.Shank import com.memoizrlabs.ShankModule import com.memoizrlabs.shankkotlin.provideSingletonFor import com.memoizrlabs.shankkotlin.registerFactory import com.mvcoding.expensius.feature.currency.provideCurrenciesSource import com.mvcoding.expensius.model.ReportSettings import com.mvcoding.expensius.provideAppUserSource import com.mvcoding.expensius.provideRxSchedulers import memoizrlabs.com.shankandroid.withThisScope class SettingsModule : ShankModule { override fun registerFactories() { settingsPresenter() reportSettingsSource() } private fun settingsPresenter() = registerFactory(SettingsPresenter::class) { -> SettingsPresenter(provideAppUserSource(), provideAppUserSource(), provideCurrenciesSource(), provideRxSchedulers()) } private fun reportSettingsSource() = registerFactory(ReportSettingsSource::class) { -> val appUserSource = provideAppUserSource() ReportSettingsSource { appUserSource.data().map { ReportSettings(it.settings.reportPeriod, it.settings.reportGroup, it.settings.mainCurrency) } } } } fun Activity.provideSettingsPresenter() = withThisScope.provideSingletonFor<SettingsPresenter>() fun provideReportSettingsSource(scope: Scope) = Shank.with(scope).provideSingletonFor<ReportSettingsSource>()
gpl-3.0
google/dokka
runners/gradle-integration-tests/src/test/kotlin/org/jetbrains/dokka/gradle/AbstractDokkaGradleTest.kt
2
4472
package org.jetbrains.dokka.gradle import com.intellij.rt.execution.junit.FileComparisonFailure import org.gradle.testkit.runner.GradleRunner import org.junit.Rule import org.junit.rules.TemporaryFolder import java.io.File import java.nio.file.Files import java.nio.file.Paths val testDataFolder = Paths.get("testData") val pluginClasspathData = Paths.get("build", "createClasspathManifest", "dokka-plugin-classpath.txt") val androidPluginClasspathData = pluginClasspathData.resolveSibling("android-dokka-plugin-classpath.txt") val dokkaFatJarPathData = pluginClasspathData.resolveSibling("fatjar.txt") val androidLocalProperties = testDataFolder.resolve("android.local.properties").let { if (Files.exists(it)) it else null } abstract class AbstractDokkaGradleTest { @get:Rule val testProjectDir = TemporaryFolder() open val pluginClasspath: List<File> = pluginClasspathData.toFile().readLines().map { File(it) } fun checkOutputStructure(expected: String, actualSubpath: String) { val expectedPath = testDataFolder.resolve(expected) val actualPath = testProjectDir.root.toPath().resolve(actualSubpath).normalize() assertEqualsIgnoringSeparators(expectedPath.toFile(), buildString { actualPath.toFile().writeStructure(this, File(actualPath.toFile(), ".")) }) } fun checkNoErrorClasses(actualSubpath: String, extension: String = "html", errorClassMarker: String = "ERROR CLASS") { val actualPath = testProjectDir.root.toPath().resolve(actualSubpath).normalize() var checked = 0 Files.walk(actualPath).filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".$extension") }.forEach { val text = it.toFile().readText() val noErrorClasses = text.replace(errorClassMarker, "?!") if (noErrorClasses != text) { throw FileComparisonFailure("", noErrorClasses, text, null) } checked++ } println("$checked files checked for error classes") } fun checkNoUnresolvedLinks(actualSubpath: String, extension: String = "html", marker: Regex = "[\"']#[\"']".toRegex()) { val actualPath = testProjectDir.root.toPath().resolve(actualSubpath).normalize() var checked = 0 Files.walk(actualPath).filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".$extension") }.forEach { val text = it.toFile().readText() val noErrorClasses = text.replace(marker, "?!") if (noErrorClasses != text) { throw FileComparisonFailure("", noErrorClasses, text, null) } checked++ } println("$checked files checked for unresolved links") } fun checkExternalLink(actualSubpath: String, linkBody: String, fullLink: String, extension: String = "html") { val match = "!!match!!" val notMatch = "!!not-match!!" val actualPath = testProjectDir.root.toPath().resolve(actualSubpath).normalize() var checked = 0 var totalEntries = 0 Files.walk(actualPath).filter { Files.isRegularFile(it) && it.fileName.toString().endsWith(".$extension") }.forEach { val text = it.toFile().readText() val textWithoutMatches = text.replace(fullLink, match) val textWithoutNonMatches = textWithoutMatches.replace(linkBody, notMatch) if (textWithoutNonMatches != textWithoutMatches) { val expected = textWithoutNonMatches.replace(notMatch, fullLink).replace(match, fullLink) val actual = textWithoutMatches.replace(match, fullLink) throw FileComparisonFailure("", expected, actual, null) } if (text != textWithoutMatches) totalEntries++ checked++ } println("$checked files checked for valid external links '$linkBody', found $totalEntries links") } fun configure(gradleVersion: String = "3.5", kotlinVersion: String = "1.1.2", arguments: Array<String>): GradleRunner { val fatjar = dokkaFatJarPathData.toFile().readText() return GradleRunner.create().withProjectDir(testProjectDir.root) .withArguments("-Pdokka_fatjar=$fatjar", "-Ptest_kotlin_version=$kotlinVersion", *arguments) .withPluginClasspath(pluginClasspath) .withGradleVersion(gradleVersion) .withDebug(true) } }
apache-2.0
deva666/anko
anko/library/static/supportV4/src/SupportContextUtils.kt
2
1087
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package org.jetbrains.anko.support.v4 import android.app.Activity import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import android.support.v4.app.Fragment inline val Fragment.defaultSharedPreferences: SharedPreferences get() = PreferenceManager.getDefaultSharedPreferences(activity) inline val Fragment.act: Activity get() = activity inline val Fragment.ctx: Context get() = activity
apache-2.0
google/dokka
core/src/main/kotlin/Utilities/SamplesPathsToURLs.kt
2
1780
/* * 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 org.jetbrains.dokka.Utilities //HashMap of all filepaths to the URLs that should be downloaded to that filepath val filepathsToUrls: HashMap<String, String> = hashMapOf( "./samples/development/samples/ApiDemos" to "https://android.googlesource.com/platform/development/+archive/refs/heads/master/samples/ApiDemos.tar.gz", "./samples/development/samples/NotePad" to "https://android.googlesource.com/platform/development/+archive/refs/heads/master/samples/NotePad.tar.gz", "./samples/external/icu/android_icu4j/src/samples/java/android/icu/samples/text" to "https://android.googlesource.com/platform/external/icu/+archive/refs/heads/master/android_icu4j/src/samples/java/android/icu/samples/text.tar.gz", "./samples/frameworks/base/core/java/android/content" to "https://android.googlesource.com/platform/frameworks/base/+archive/refs/heads/master/core/java/android/content.tar.gz", "./samples/frameworks/base/tests/appwidgets/AppWidgetHostTest/src/com/android/tests/appwidgethost" to "https://android.googlesource.com/platform/frameworks/base/+archive/refs/heads/master/tests/appwidgets/AppWidgetHostTest/src/com/android/tests/appwidgethost.tar.gz" )
apache-2.0
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacBasicAnnotationProcessor.kt
3
3065
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.javac import androidx.room.compiler.processing.CommonProcessorDelegate import androidx.room.compiler.processing.XBasicAnnotationProcessor import androidx.room.compiler.processing.XProcessingEnv import androidx.room.compiler.processing.XProcessingEnvConfig import javax.annotation.processing.AbstractProcessor import javax.annotation.processing.ProcessingEnvironment import javax.annotation.processing.RoundEnvironment import javax.lang.model.element.TypeElement /** * Javac implementation of a [XBasicAnnotationProcessor] with built-in support for validating and * deferring elements. */ abstract class JavacBasicAnnotationProcessor @JvmOverloads constructor( configureEnv: (Map<String, String>) -> XProcessingEnvConfig = { XProcessingEnvConfig.DEFAULT } ) : AbstractProcessor(), XBasicAnnotationProcessor { constructor(config: XProcessingEnvConfig) : this({ config }) private val xEnv: JavacProcessingEnv by lazy { JavacProcessingEnv(processingEnv, configureEnv(processingEnv.options)) } // Cache and lazily get steps during the initial process() so steps initialization is done once. private val steps by lazy { processingSteps().toList() } private val commonDelegate by lazy { CommonProcessorDelegate(this.javaClass, xEnv, steps) } final override val xProcessingEnv: XProcessingEnv get() = xEnv final override fun init(processingEnv: ProcessingEnvironment?) { super.init(processingEnv) initialize(xEnv) } final override fun getSupportedAnnotationTypes() = steps.flatMap { it.annotations() }.toSet() final override fun process( annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment ): Boolean { val xRoundEnv = JavacRoundEnv(xEnv, roundEnv) if (roundEnv.processingOver()) { val missingElements = commonDelegate.processLastRound() postRound(xEnv, xRoundEnv) if (!xProcessingEnv.config.disableAnnotatedElementValidation && !roundEnv.errorRaised() ) { // Report missing elements if no error was raised to avoid being noisy. commonDelegate.reportMissingElements(missingElements) } } else { commonDelegate.processRound(xRoundEnv) postRound(xEnv, xRoundEnv) xEnv.clearCache() } return false } }
apache-2.0
pyamsoft/power-manager
powermanager/src/main/java/com/pyamsoft/powermanager/uicore/WatchedDialog.kt
1
973
/* * Copyright 2017 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.powermanager.uicore import android.support.annotation.CallSuper import com.pyamsoft.powermanager.PowerManager import com.pyamsoft.pydroid.ui.app.fragment.DialogFragmentBase abstract class WatchedDialog : DialogFragmentBase() { @CallSuper override fun onDestroy() { super.onDestroy() PowerManager.getRefWatcher(this).watch(this) } }
apache-2.0
hkokocin/google-android-architecture-sample
app/src/main/java/com/example/hkokocin/gaa/users/UserWidget.kt
1
1002
package com.example.hkokocin.gaa.users import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.support.constraint.ConstraintLayout import android.widget.ImageView import android.widget.TextView import com.bumptech.glide.Glide import com.example.hkokocin.gaa.R import com.example.hkokocin.gaa.adapter.Widget import com.example.hkokocin.gaa.data.GitHubUser class UserWidget( val activity: Activity ) : Widget<GitHubUser>(R.layout.user_item) { private val ivAvatar: ImageView by viewId(R.id.iv_avatar) private val tvName: TextView by viewId(R.id.tv_name) private val clContainer: ConstraintLayout by viewId(R.id.cl_container) override fun setData(data: GitHubUser) { Glide.with(ivAvatar).load(data.avatarUrl).into(ivAvatar) tvName.text = data.name clContainer.setOnClickListener { activity.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(data.url))) } } }
mit
raxden/square
sample/src/main/java/com/raxdenstudios/square/sample/commons/InjectFragmentActivity.kt
2
2081
package com.raxdenstudios.square.sample.commons import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import com.raxdenstudios.square.interceptor.Interceptor import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.AutoInflateLayoutInterceptor import com.raxdenstudios.square.interceptor.commons.autoinflatelayout.HasAutoInflateLayoutInterceptor import com.raxdenstudios.square.interceptor.commons.injectfragment.HasInjectFragmentInterceptor import com.raxdenstudios.square.interceptor.commons.injectfragment.InjectFragmentInterceptor import kotlinx.android.synthetic.main.inject_fragment_activity.* class InjectFragmentActivity : AppCompatActivity(), HasAutoInflateLayoutInterceptor, HasInjectFragmentInterceptor<InjectedFragment> { private lateinit var mAutoInflateLayoutInterceptor: AutoInflateLayoutInterceptor private lateinit var mInjectFragmentInterceptor: InjectFragmentInterceptor var mContentView: View? = null var mInjectedFragment: InjectedFragment? = null // ======== HasInflateLayoutInterceptor ======================================================== override fun onContentViewCreated(view: View) { mContentView = view } // ======== HasInjectFragmentInterceptor ======================================================= override fun onLoadFragmentContainer(): View = container_view override fun onCreateFragment(): InjectedFragment = InjectedFragment.newInstance(Bundle().apply { putString("title", "Fragment 1") }) override fun onFragmentLoaded(fragment: InjectedFragment) { mInjectedFragment = fragment } // ============================================================================================= override fun onInterceptorCreated(interceptor: Interceptor) { when(interceptor) { is AutoInflateLayoutInterceptor -> mAutoInflateLayoutInterceptor = interceptor is InjectFragmentInterceptor -> mInjectFragmentInterceptor = interceptor } } }
apache-2.0
inorichi/tachiyomi-extensions
multisrc/overrides/mangacatalog/readvinlandsagamangaonline/src/ReadVinlandSagaMangaOnline.kt
1
626
package eu.kanade.tachiyomi.extension.en.readvinlandsagamangaonline import eu.kanade.tachiyomi.multisrc.mangacatalog.MangaCatalog import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.util.asJsoup class ReadVinlandSagaMangaOnline : MangaCatalog("Read Vinland Saga Manga Online", "https://ww1.readvinlandsaga.com", "en") { override val sourceList = listOf( Pair("Vinland Saga", "$baseUrl/manga/vinland-saga/"), Pair("Fan Colored", "$baseUrl/manga/vinland-saga-colored/"), Pair("Planetes", "$baseUrl/manga/planetes/"), ).sortedBy { it.first }.distinctBy { it.second } }
apache-2.0
teobaranga/T-Tasks
t-tasks/src/main/java/com/teo/ttasks/ui/activities/edit_task/EditTaskActivity.kt
1
10919
package com.teo.ttasks.ui.activities.edit_task import android.app.DatePickerDialog import android.app.Dialog import android.app.TimePickerDialog import android.content.Context import android.content.Intent import android.os.Bundle import android.text.format.DateFormat import android.view.Menu import android.view.MenuItem import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.DatePicker import android.widget.LinearLayout import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.fragment.app.DialogFragment import com.teo.ttasks.R import com.teo.ttasks.data.TaskListsAdapter import com.teo.ttasks.data.model.Task import com.teo.ttasks.data.model.TaskList import com.teo.ttasks.databinding.ActivityEditTaskBinding import com.teo.ttasks.util.DateUtils import com.teo.ttasks.util.toastShort import org.koin.androidx.scope.lifecycleScope import org.threeten.bp.LocalDateTime import org.threeten.bp.LocalTime import org.threeten.bp.ZoneId import java.util.* class EditTaskActivity : AppCompatActivity(), EditTaskView { class DatePickerFragment : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { // Use the current date as the default date in the picker val c = Calendar.getInstance() val year = c.get(Calendar.YEAR) val month = c.get(Calendar.MONTH) val day = c.get(Calendar.DAY_OF_MONTH) // Create a new instance of DatePickerDialog and return it return DatePickerDialog(requireContext(), activity as EditTaskActivity, year, month, day) } } private val editTaskPresenter: EditTaskPresenter by lifecycleScope.inject() private lateinit var editTaskBinding: ActivityEditTaskBinding private lateinit var taskListsAdapter: TaskListsAdapter private lateinit var taskListId: String private var datePickerFragment: DatePickerFragment? = null /** * Flag indicating that the reminder time has been clicked. * Used to differentiate between the reminder time and the due time. */ private var reminderTimeClicked: Boolean = false /** Listener invoked when the reminder time has been selected */ private val reminderTimeSetListener: TimePickerDialog.OnTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hourOfDay, minute -> val localTime = LocalTime.of(hourOfDay, minute) val formattedTime = localTime.format(DateUtils.formatterTime) if (reminderTimeClicked) { editTaskBinding.reminder.text = formattedTime editTaskPresenter.setReminderTime(localTime) reminderTimeClicked = false } else { // editTaskBinding.dueDate.text = DateUtils.formatDate(this, time) editTaskBinding.dueTime.text = formattedTime editTaskPresenter.setDueTime(localTime) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) editTaskBinding = DataBindingUtil.setContentView(this, R.layout.activity_edit_task) editTaskBinding.view = this editTaskPresenter.bindView(this) val taskId = intent.getStringExtra(EXTRA_TASK_ID)?.trim() taskListId = checkNotNull(intent.getStringExtra(EXTRA_TASK_LIST_ID)?.trim()) supportActionBar!!.setDisplayHomeAsUpEnabled(true) taskListsAdapter = TaskListsAdapter(this).apply { setDropDownViewResource(R.layout.spinner_item_task_list_edit_dropdown) editTaskBinding.taskLists.adapter = this } if (taskId.isNullOrBlank()) { // Update the toolbar title supportActionBar!!.setTitle(R.string.title_activity_new_task) // Show the keyboard editTaskBinding.taskTitle.requestFocus() } // Load the available task lists and the task, if available editTaskPresenter.loadTask(taskListId, taskId) } override fun onDestroy() { editTaskPresenter.unbindView(this) super.onDestroy() } override fun onTaskLoaded(task: Task) { editTaskBinding.task = task } override fun onTaskListsLoaded(taskLists: List<TaskList>) { with(taskListsAdapter) { clear() addAll(taskLists) } if (taskLists.isNotEmpty()) { editTaskBinding.taskLists.setSelection( taskLists .indexOfFirst { taskList -> taskList.id == taskListId } .coerceAtLeast(0)) } } override fun onTaskLoadError() { toastShort(R.string.error_task_loading) finish() } override fun onTaskSaved() { onBackPressed() } override fun onTaskSaveError() { // TODO: 2016-07-24 implement } /** * Reset the due time * * @return true if the due time was reset, false otherwise */ override fun onDueTimeLongClicked(v: View): Boolean { // TODO: 2016-05-18 return false if the due time is already reset editTaskBinding.dueTime.setText(R.string.due_time_all_day) return true } override fun onTitleChanged(title: CharSequence, start: Int, before: Int, count: Int) { editTaskPresenter.setTaskTitle(title.toString()) // Clear the error editTaskBinding.taskTitle.error = null } override fun onNotesChanged(notes: CharSequence, start: Int, before: Int, count: Int) { editTaskPresenter.setTaskNotes(notes.toString()) } override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int, dayOfMonth: Int) { val dateTime = LocalDateTime.of(year, monthOfYear + 1, dayOfMonth, 0, 0) .atZone(ZoneId.systemDefault()) editTaskPresenter.dueDate = dateTime // Display the date after being processed by the presenter editTaskBinding.dueDate.text = dateTime.format(DateUtils.formatterDate) } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_edit_task, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } R.id.done -> { if (editTaskBinding.taskTitle.length() == 0) { editTaskBinding.taskTitle.error = getString(R.string.error_no_title) editTaskBinding.taskTitle.requestFocus() return true } editTaskPresenter.finishTask() return true } } return super.onOptionsItemSelected(item) } @Suppress("UNUSED_PARAMETER") fun onDueDateClicked(v: View) { hideKeyboard() if (editTaskPresenter.hasDueDate()) { val dialog = AlertDialog.Builder(this) .setView(R.layout.dialog_remove_change) .show() dialog.findViewById<LinearLayout>(R.id.remove)!!.setOnClickListener { // Reset the due date & reminder editTaskPresenter.removeDueDate() editTaskPresenter.removeReminder() editTaskBinding.dueDate.text = null editTaskBinding.reminder.text = null dialog.dismiss() } dialog.findViewById<LinearLayout>(R.id.change)!!.setOnClickListener { datePickerFragment = (datePickerFragment ?: DatePickerFragment()).apply { show(supportFragmentManager, "datePicker") } dialog.dismiss() } } else { datePickerFragment = (datePickerFragment ?: DatePickerFragment()).apply { show(supportFragmentManager, "datePicker") } } } @Suppress("UNUSED_PARAMETER") fun onDueTimeClicked(v: View) { hideKeyboard() showReminderTimePickerDialog() } @Suppress("UNUSED_PARAMETER") fun onReminderClicked(v: View) { hideKeyboard() if (!editTaskPresenter.hasDueDate()) { toastShort("You need to set a due date before adding a reminder") return } if (editTaskPresenter.hasReminder()) { val dialog = AlertDialog.Builder(this) .setView(R.layout.dialog_remove_change) .show() dialog.findViewById<LinearLayout>(R.id.remove)!!.setOnClickListener { editTaskPresenter.removeReminder() editTaskBinding.reminder.text = null dialog.dismiss() } dialog.findViewById<LinearLayout>(R.id.change)!!.setOnClickListener { reminderTimeClicked = true showReminderTimePickerDialog() dialog.dismiss() } } else { reminderTimeClicked = true showReminderTimePickerDialog() } } /** * Show the picker for the task reminder time */ private fun showReminderTimePickerDialog() { // Use the current time as the default values for the picker val c = Calendar.getInstance() val hour = c.get(Calendar.HOUR_OF_DAY) val minute = c.get(Calendar.MINUTE) // Create a new instance of TimePickerDialog and return it TimePickerDialog( this, reminderTimeSetListener, hour, minute, DateFormat.is24HourFormat(this) ).show() } private fun hideKeyboard() { currentFocus?.windowToken?.let { val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(it, 0) } } companion object { private const val EXTRA_TASK_ID = "taskId" private const val EXTRA_TASK_LIST_ID = "taskListId" fun startEdit(context: Context, taskId: String, taskListId: String, bundle: Bundle?) { context.startActivity(getTaskCreateIntent(context, taskListId).apply { putExtra(EXTRA_TASK_ID, taskId) }, bundle) } fun startCreate(context: Context, taskListId: String, bundle: Bundle?) { context.startActivity(getTaskCreateIntent(context, taskListId), bundle) } /** * Used when starting this activity from the widget */ fun getTaskCreateIntent(context: Context, taskListId: String): Intent { return Intent(context, EditTaskActivity::class.java).apply { putExtra(EXTRA_TASK_LIST_ID, taskListId) } } } }
apache-2.0
depoll/bindroid
bindroid-test/src/com/bindroid/test/kotlin/CompiledPropertyTest.kt
1
1394
package com.bindroid.test.kotlin import com.bindroid.utils.CompiledProperty import com.bindroid.utils.weakBind import junit.framework.TestCase import org.junit.Assert class CompiledPropertyTest : TestCase() { var prop: String? = null val readOnlyProp: String? get() = prop fun testReadWriteCompiledProperty() { prop = "Hello" val property = CompiledProperty({ ::prop }) Assert.assertEquals("Hello", property.value) property.value = "Goodbye" Assert.assertEquals("Goodbye", prop) Assert.assertEquals("Goodbye", property.value) } fun testReadOnlyCompiledProperty() { prop = "Hello" val property = CompiledProperty({ ::readOnlyProp }) Assert.assertEquals("Hello", property.value) var threw = true try { property.value = "Goodbye" threw = false } catch (e: Exception) { } Assert.assertTrue(threw) } private class TestObj { var myProp: String? = null } fun testWeakCompiledProperty() { var obj = TestObj() obj.myProp = "Hello" val property = CompiledProperty(obj weakBind { ::myProp }) Assert.assertEquals("Hello", property.value) @Suppress("UNUSED_VALUE") obj = TestObj() Runtime.getRuntime().gc() Assert.assertNull(property.value) } }
mit
saki4510t/libcommon
common/src/main/java/com/serenegiant/widget/GLView.kt
1
9541
package com.serenegiant.widget /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2022 saki [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context import android.opengl.GLES20 import android.opengl.Matrix import android.os.Handler import android.util.AttributeSet import android.util.Log import android.view.Choreographer import android.view.SurfaceHolder import android.view.SurfaceView import android.view.View import androidx.annotation.AnyThread import androidx.annotation.CallSuper import androidx.annotation.Size import androidx.annotation.WorkerThread import com.serenegiant.gl.GLContext import com.serenegiant.gl.GLManager import com.serenegiant.gl.ISurface /** * SurfaceViewのSurfaceへOpenGL|ESで描画するためのヘルパークラス * SurfaceViewを継承 */ open class GLView @JvmOverloads constructor( context: Context?, attrs: AttributeSet? = null, defStyle: Int = 0) : SurfaceView(context, attrs, defStyle), IGLTransformView { /** * GLスレッド上での処理 */ interface GLRenderer { /** * Surfaceが生成された時 * EGL/GLコンテキストを保持しているワーカースレッド上で実行される */ @WorkerThread fun onSurfaceCreated() /** * Surfaceのサイズが変更された * EGL/GLコンテキストを保持しているワーカースレッド上で実行される */ @WorkerThread fun onSurfaceChanged(format: Int, width: Int, height: Int) /** * トランスフォームマトリックスを適用 */ @WorkerThread fun applyTransformMatrix(@Size(min=16) transform: FloatArray) /** * 描画イベント * EGL/GLコンテキストを保持しているワーカースレッド上で実行される */ @WorkerThread fun drawFrame() /** * Surfaceが破棄された * EGL/GLコンテキストを保持しているワーカースレッド上で実行される */ @WorkerThread fun onSurfaceDestroyed() } private val mGLManager: GLManager private val mGLContext: GLContext private val mGLHandler: Handler @Volatile private var mHasSurface: Boolean = false /** * SurfaceViewのSurfaceへOpenGL|ESで描画するためのISurfaceインスタンス */ private var mTarget: ISurface? = null private val mMatrix: FloatArray = FloatArray(16) private var mMatrixChanged = false private var mGLRenderer: GLRenderer? = null init { if (DEBUG) Log.v(TAG, "コンストラクタ:") mGLManager = GLManager() mGLContext = mGLManager.glContext mGLHandler = mGLManager.glHandler Matrix.setIdentityM(mMatrix, 0) holder.addCallback(object : SurfaceHolder.Callback { override fun surfaceCreated(holder: SurfaceHolder) { if (DEBUG) Log.v(TAG, "surfaceCreated:") if ((width > 0) && (height > 0)) { mHasSurface = true mMatrixChanged = true queueEvent { onSurfaceCreated() } } } override fun surfaceChanged (holder: SurfaceHolder, format: Int, width: Int, height: Int) { if (DEBUG) Log.v(TAG, "surfaceChanged:(${width}x${height})") queueEvent { onSurfaceChanged(format, width, height) } } override fun surfaceDestroyed(holder: SurfaceHolder) { if (DEBUG) Log.v(TAG, "surfaceDestroyed:") mHasSurface = false queueEvent { onSurfaceDestroyed() } } }) } override fun onDetachedFromWindow() { mGLManager.release() super.onDetachedFromWindow() } /** * OpenGL|ES3.xが使用可能かどうかを取得 */ @AnyThread fun isGLES3() : Boolean { return mGLContext.isGLES3 } @AnyThread fun isOES3Supported() : Boolean { return mGLContext.isOES3Supported } /** * 内部使用のGLManagerインスタンスを取得 */ @AnyThread fun getGLManager() : GLManager { return mGLManager } /** * 内部使用のGLContextを取得 */ @AnyThread fun getGLContext() : GLContext { return mGLContext } /** * GLRendererをセット */ @AnyThread fun setRenderer(renderer: GLRenderer?) { queueEvent { mGLRenderer = renderer } } /** * Viewportを設定 * @param x * @param y * @param width * @param height */ @AnyThread fun setViewport(x: Int, y: Int, width: Int, height: Int) { queueEvent { if (mTarget != null) { mTarget!!.setViewPort(x, y, width, height) } } } /** * EGL/GLコンテキストを保持しているワーカースレッド上で実行要求する */ @AnyThread fun queueEvent(task: Runnable) { mGLHandler.post(task) } /** * EGL/GLコンテキストを保持しているワーカースレッド上で実行要求する */ @AnyThread fun queueEvent(task: Runnable, delayMs: Long) { if (delayMs > 0) { mGLHandler.postDelayed(task, delayMs) } else { mGLHandler.post(task) } } /** * EGL/GLコンテキストを保持しているワーカースレッド上で実行待ちしていれば実行待ちを解除する */ @AnyThread fun removeEvent(task: Runnable) { mGLHandler.removeCallbacks(task) } //-------------------------------------------------------------------------------- /** * IGLTransformViewの実装 */ @AnyThread override fun setTransform(@Size(min=16) transform: FloatArray?) { synchronized(mMatrix) { if (transform != null) { System.arraycopy(transform, 0, mMatrix, 0, 16) } else { Matrix.setIdentityM(mMatrix, 0) } mMatrixChanged = true } } /** * IGLTransformViewの実装 */ @AnyThread override fun getTransform(@Size(min=16) transform: FloatArray?): FloatArray { var result = transform if (result == null) { result = FloatArray(16) } synchronized(mMatrix) { System.arraycopy(mMatrix, 0, result, 0, 16) } return result } /** * IGLTransformViewの実装 */ @AnyThread override fun getView(): View { return this } //-------------------------------------------------------------------------------- /** * デフォルトのレンダリングコンテキストへ切り返る * Surfaceが有効であればそのサーフェースへの描画コンテキスト * Surfaceが無効であればEGL/GLコンテキスト保持用のオフスクリーンへの描画コンテキストになる */ @WorkerThread protected fun makeDefault() { if (mTarget != null) { mTarget!!.makeCurrent() } else { mGLContext.makeDefault() } } /** * Choreographerを使ったvsync同期用描画のFrameCallback実装 */ private var mChoreographerCallback = object : Choreographer.FrameCallback { override fun doFrame(frameTimeNanos: Long) { if (mHasSurface) { mGLManager.postFrameCallbackDelayed(this, 0) makeDefault() synchronized(mMatrix) { if (mMatrixChanged) { applyTransformMatrix(mMatrix) mMatrixChanged = false } } drawFrame() mTarget?.swap() } } } /** * Surfaceが生成された時 * EGL/GLコンテキストを保持しているワーカースレッド上で実行される */ @WorkerThread @CallSuper protected fun onSurfaceCreated() { if (DEBUG) Log.v(TAG, "onSurfaceCreated:") mTarget = mGLContext.egl.createFromSurface(holder.surface) // 画面全体へ描画するためにビューポートを設定する mTarget?.setViewPort(0, 0, width, height) mGLManager.postFrameCallbackDelayed(mChoreographerCallback, 0) mGLRenderer?.onSurfaceCreated() } /** * Surfaceのサイズが変更された * EGL/GLコンテキストを保持しているワーカースレッド上で実行される */ @WorkerThread @CallSuper protected fun onSurfaceChanged( format: Int, width: Int, height: Int) { if (DEBUG) Log.v(TAG, "onSurfaceChanged:(${width}x${height})") // 画面全体へ描画するためにビューポートを設定する mTarget?.setViewPort(0, 0, width, height) mGLRenderer?.onSurfaceChanged(format, width, height) } /** * 描画イベント * EGL/GLコンテキストを保持しているワーカースレッド上で実行される */ @WorkerThread protected fun drawFrame() { if (mHasSurface) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) mGLRenderer?.drawFrame() } } /** * Surfaceが破棄された * EGL/GLコンテキストを保持しているワーカースレッド上で実行される */ @WorkerThread @CallSuper protected fun onSurfaceDestroyed() { if (DEBUG) Log.v(TAG, "onSurfaceDestroyed:") if (mGLManager.isValid) { mGLManager.removeFrameCallback(mChoreographerCallback) mGLHandler.removeCallbacksAndMessages(null) } mGLRenderer?.onSurfaceDestroyed() if (mTarget != null) { mTarget!!.release() mTarget = null } } /** * トランスフォームマトリックスを適用 */ @WorkerThread @CallSuper protected fun applyTransformMatrix(@Size(min=16) transform: FloatArray) { if (DEBUG) Log.v(TAG, "applyTransformMatrix:") mGLRenderer?.applyTransformMatrix(transform) } companion object { private const val DEBUG = false // TODO set false on release private val TAG = GLView::class.java.simpleName } }
apache-2.0
bogerchan/National-Geography
app/src/main/java/me/boger/geographic/biz/common/FavoriteNGDataSupplier.kt
1
3940
package me.boger.geographic.biz.common import android.content.Context import android.content.Intent import android.text.TextUtils import com.google.gson.reflect.TypeToken import me.boger.geographic.R import me.boger.geographic.core.NGRumtime import me.boger.geographic.biz.detailpage.DetailPageData import me.boger.geographic.biz.detailpage.DetailPagePictureData import me.boger.geographic.biz.selectpage.SelectPageAlbumData import me.boger.geographic.core.NGBroadcastManager import me.boger.geographic.core.NGConstants import me.boger.geographic.util.Timber import java.util.* /** * Created by BogerChan on 2017/7/10. */ class FavoriteNGDataSupplier(ctx: Context) { companion object { val KEY_FAVORITE_NG_DETAIL_DATA = "fav_ng_detail_data" } private var mDetailPageData: DetailPageData = DetailPageData("0", ArrayList<DetailPagePictureData>(0)) private var mSP = ctx.getSharedPreferences(ctx.packageName, Context.MODE_PRIVATE) init { val jsonDetailPageData = mSP.getString(KEY_FAVORITE_NG_DETAIL_DATA, null) if (!TextUtils.isEmpty(jsonDetailPageData)) { val list = NGRumtime.gson.fromJson<MutableList<DetailPagePictureData>>( jsonDetailPageData, object : TypeToken<MutableList<DetailPagePictureData>>() {}.type) mDetailPageData.counttotal = list.size.toString() mDetailPageData.picture = list } } fun addDetailPageDataToFavorite(data: DetailPagePictureData): Boolean { try { if (mDetailPageData.picture.contains(data)) { return true } mDetailPageData.picture.add(data) mSP.edit() .putString(KEY_FAVORITE_NG_DETAIL_DATA, NGRumtime.gson.toJson(mDetailPageData.picture)) .apply() } catch (e: Exception) { Timber.e(e) mDetailPageData.picture.remove(data) return false } NGBroadcastManager.sendLocalBroadcast(Intent(NGConstants.ACTION_FAVORITE_DATA_CHANGED)) return true } fun removeDetailPageDataToFavorite(data: DetailPagePictureData): Boolean { try { if (!mDetailPageData.picture.contains(data)) { return true } mDetailPageData.picture.remove(data) mSP.edit() .putString(KEY_FAVORITE_NG_DETAIL_DATA, NGRumtime.gson.toJson(mDetailPageData.picture)) .apply() } catch (e: Exception) { Timber.e(e) mDetailPageData.picture.add(data) return false } NGBroadcastManager.sendLocalBroadcast(Intent(NGConstants.ACTION_FAVORITE_DATA_CHANGED)) return true } fun getDetailPageData(): DetailPageData { mDetailPageData.picture.forEach { it.clearLocale() } return mDetailPageData.copy(picture = mDetailPageData.picture.toMutableList()) } private fun getLastCoverUrl(): String { return if (mDetailPageData.picture.size > 0) mDetailPageData.picture.last().url else "" } private fun getImageCount() = mDetailPageData.picture.size fun syncFavoriteState(data: DetailPageData) { val favoriteIdSet = mutableSetOf<String>() mDetailPageData.picture.forEach { favoriteIdSet.add(it.id) } data.picture.forEach { it.favorite = favoriteIdSet.contains(it.id) } } fun getFavoriteAlbumData(): SelectPageAlbumData { return SelectPageAlbumData( "unset", String.format(Locale.getDefault(), NGRumtime.application.getString(R.string.text_favorite_item_title), getImageCount()), getLastCoverUrl(), "unset", "unset", "unset", "unset", "unset", "unset", "unset", "unset", "unset") } }
apache-2.0
czyzby/ktx
math/src/main/kotlin/ktx/math/ranges.kt
2
6361
package ktx.math import com.badlogic.gdx.math.Interpolation import com.badlogic.gdx.math.MathUtils /** * Creates a range defined with the given inclusive [tolerance] above and below this center value. */ infix fun Int.amid(tolerance: Int) = (this - tolerance)..(this + tolerance) /** * Returns a random element from this range using the specified source of randomness. * * This overload allows passing a [java.util.Random] instance so, for instance, [MathUtils.random] may be used. Results * are undefined for an empty range, and there is no error checking. */ fun IntRange.random(random: java.util.Random) = random.nextInt(1 + last - first) + first /** * Creates a range by scaling this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * the [multiplier]. */ operator fun IntRange.times(multiplier: Int) = (first * multiplier)..(last * multiplier) /** * Creates a range by scaling the [range]'s [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * this multiplier. */ operator fun Int.times(range: IntRange) = (this * range.first)..(this * range.last) /** * Creates a range by scaling this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * the [divisor]. */ operator fun IntRange.div(divisor: Int) = (first / divisor)..(last / divisor) /** * Creates a range by shifting this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * the [addend]. */ operator fun IntRange.plus(addend: Int) = (first + addend)..(last + addend) /** * Creates a range by shifting this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * the [subtrahend]. */ operator fun IntRange.minus(subtrahend: Int) = (start - subtrahend)..(endInclusive - subtrahend) /** * Creates a range defined with the given [tolerance] above and below this center value. */ infix fun Float.amid(tolerance: Float) = (this - tolerance)..(this + tolerance) /** * Creates a range by scaling this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * the [multiplier]. */ operator fun ClosedRange<Float>.times(multiplier: Float) = (start * multiplier)..(endInclusive * multiplier) /** * Creates a range by scaling the [range]'s [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * this multiplier. */ operator fun Float.times(range: ClosedRange<Float>) = (this * range.start)..(this * range.endInclusive) /** * Creates a range by scaling this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * the [denominator]. */ operator fun ClosedRange<Float>.div(denominator: Float) = (start / denominator)..(endInclusive / denominator) /** * Creates a range by shifting this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * the [addend]. */ operator fun ClosedRange<Float>.plus(addend: Float) = (start + addend)..(endInclusive + addend) /** * Creates a range by shifting this range's [start][ClosedRange.start] and [endInclusive][ClosedRange.endInclusive] by * the [subtrahend]. */ operator fun ClosedRange<Float>.minus(subtrahend: Float) = (start - subtrahend)..(endInclusive - subtrahend) /** * Returns a pseudo-random, uniformly distributed [Float] value from [MathUtils.random]'s sequence, bounded by * this range. * * Results are undefined for an empty range, and there is no error checking. Note that * [endInclusive][ClosedRange.endInclusive] is treated as exclusive as it is not practical to keep it inclusive. */ fun ClosedRange<Float>.random() = MathUtils.random.nextFloat() * (endInclusive - start) + start /** * Returns a pseudo-random, standard Gaussian distributed [Float] value from [MathUtils.random]'s sequence. The * distribution is centered to this range's center and is scaled so this range is six standard deviations wide. * * Results are undefined for an empty range, and there is no error checking. * * @param clamped If true (the default), values outside the range are clamped to the range. */ fun ClosedRange<Float>.randomGaussian(clamped: Boolean = true) = ((MathUtils.random.nextGaussian() / 6.0 + 0.5).toFloat() * (endInclusive - start) + start).let { if (clamped) it.coerceIn(this) else it } /** * Returns a triangularly distributed random number in this range, with the *mode* centered in this range, giving a * symmetric distribution. * * This function uses [MathUtils.randomTriangular]. Note that [endInclusive][ClosedRange.endInclusive] is treated as * exclusive as it is not practical to keep it inclusive. Results are undefined for an empty range, and there is no * error checking. */ fun ClosedRange<Float>.randomTriangular() = MathUtils.randomTriangular(start, endInclusive) /** * Returns a triangularly distributed random number in this range, where values around the *mode* are more likely. * [normalizedMode] must be a value in the range 0.0..1.0 and represents the fractional position of the mode across the * range. * * This function uses `MathUtils.randomTriangular(min, max, mode)`. Note that [endInclusive][ClosedRange.endInclusive] * is treated as exclusive as it is not practical to keep it inclusive. Results are undefined for an empty range, and * there is no error checking. */ fun ClosedRange<Float>.randomTriangular(normalizedMode: Float): Float = MathUtils.randomTriangular( start, endInclusive, normalizedMode * (endInclusive - start) + start ) /** * Linearly interpolate between the start and end of this range. * * @param progress The position to interpolate, where 0 corresponds with [ClosedRange.start] and 1 corresponds with * [ClosedRange.endInclusive]. * @return The interpolated value. */ fun ClosedRange<Float>.lerp(progress: Float): Float = progress * (endInclusive - start) + start /** * Interpolate between the start and end of this range. * * @param progress The position to interpolate, where 0 corresponds with [ClosedRange.start] and 1 corresponds with * [ClosedRange.endInclusive]. * @param interpolation The function to interpolate with. * @return The interpolated value. */ fun ClosedRange<Float>.interpolate(progress: Float, interpolation: Interpolation): Float = interpolation.apply(progress) * (endInclusive - start) + start
cc0-1.0
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/data/osm/osmquest/OsmQuest.kt
1
2627
package de.westnordost.streetcomplete.data.osm.osmquest import java.util.Date import de.westnordost.streetcomplete.data.quest.Quest import de.westnordost.streetcomplete.data.quest.QuestStatus import de.westnordost.streetcomplete.data.osm.changes.StringMapChanges import de.westnordost.streetcomplete.data.quest.QuestType import de.westnordost.osmapi.map.data.Element import de.westnordost.osmapi.map.data.LatLon import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementGeometry import de.westnordost.streetcomplete.data.osm.elementgeometry.ElementPolylinesGeometry import de.westnordost.streetcomplete.data.osm.upload.HasElementTagChanges import de.westnordost.streetcomplete.data.osm.upload.UploadableInChangeset import de.westnordost.streetcomplete.util.measuredLength import de.westnordost.streetcomplete.util.pointOnPolylineFromEnd import de.westnordost.streetcomplete.util.pointOnPolylineFromStart /** Represents one task for the user to complete/correct the data based on one OSM element */ data class OsmQuest( override var id: Long?, override val osmElementQuestType: OsmElementQuestType<*>, // underlying OSM data override val elementType: Element.Type, override val elementId: Long, override var status: QuestStatus, override var changes: StringMapChanges?, var changesSource: String?, override var lastUpdate: Date, override val geometry: ElementGeometry ) : Quest, UploadableInChangeset, HasElementTagChanges { constructor(type: OsmElementQuestType<*>, elementType: Element.Type, elementId: Long, geometry: ElementGeometry) : this(null, type, elementType, elementId, QuestStatus.NEW, null, null, Date(), geometry) override val center: LatLon get() = geometry.center override val type: QuestType<*> get() = osmElementQuestType override val position: LatLon get() = center override val markerLocations: Collection<LatLon> get() { if (osmElementQuestType.hasMarkersAtEnds && geometry is ElementPolylinesGeometry) { val polyline = geometry.polylines[0] val length = polyline.measuredLength() if (length > 15 * 4) { return listOf( polyline.pointOnPolylineFromStart(15.0)!!, polyline.pointOnPolylineFromEnd(15.0)!! ) } } return listOf(center) } override fun isApplicableTo(element: Element) = osmElementQuestType.isApplicableTo(element) /* --------------------------- UploadableInChangeset --------------------------- */ override val source: String get() = changesSource!! }
gpl-3.0
fredyw/leetcode
src/main/kotlin/leetcode/Problem1968.kt
1
658
package leetcode /** * https://leetcode.com/problems/array-with-elements-not-equal-to-average-of-neighbors/ */ class Problem1968 { fun rearrangeArray(nums: IntArray): IntArray { nums.sort() val mid = nums.size / 2 val answer = IntArray(nums.size) var i = 0 var j = 0 while (i <= mid && j < nums.size) { answer[j] = nums[i] i++ j += 2 } i = if (nums.size % 2 == 0) mid else mid + 1 j = 1 while (i < nums.size && j < nums.size) { answer[j] = nums[i] i++ j += 2 } return answer } }
mit
rhdunn/xquery-intellij-plugin
src/main/java/uk/co/reecedunn/intellij/plugin/xquery/codeInspection/xqst/XQST0047.kt
1
3258
/* * Copyright (C) 2017-2019 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.codeInspection.xqst import com.intellij.codeInspection.InspectionManager import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.psi.PsiFile import com.intellij.util.SmartList import uk.co.reecedunn.intellij.plugin.core.codeInspection.Inspection import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.intellij.resources.XQueryPluginBundle import uk.co.reecedunn.intellij.plugin.xdm.types.element import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XpmNamespaceDeclaration import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModuleImport import uk.co.reecedunn.intellij.plugin.xquery.model.XQueryPrologResolver class XQST0047 : Inspection("xqst/XQST0047.md", XQST0047::class.java.classLoader) { override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? { if (file !is XQueryModule) return null val descriptors = SmartList<ProblemDescriptor>() file.children().forEach { module -> val uris = HashMap<String, XpmNamespaceDeclaration>() val prolog = (module as? XQueryPrologResolver)?.prolog?.firstOrNull() prolog?.children()?.filterIsInstance<XQueryModuleImport>()?.forEach(fun(child) { val ns = child as? XpmNamespaceDeclaration val uri = ns?.namespaceUri?.data // NOTE: A ModuleImport without a namespace prefix can import // additional definitions into the namespace. if (ns == null || uri == null || ns.namespacePrefix?.data.isNullOrBlank()) return val duplicate: XpmNamespaceDeclaration? = uris[uri] if (duplicate != null) { val description = XQueryPluginBundle.message("inspection.XQST0047.duplicate-namespace-uri.message", uri) descriptors.add( manager.createProblemDescriptor( ns.namespaceUri?.element!!, description, null as LocalQuickFix?, ProblemHighlightType.GENERIC_ERROR, isOnTheFly ) ) } uris[uri] = ns }) } return descriptors.toTypedArray() } }
apache-2.0
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/max_speed/AddMaxSpeed.kt
1
2600
package de.westnordost.streetcomplete.quests.max_speed import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.meta.OsmTaggings import de.westnordost.streetcomplete.data.osm.Countries import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao class AddMaxSpeed(o: OverpassMapDataDao) : SimpleOverpassQuestType<MaxSpeedAnswer>(o) { override val tagFilters = """ ways with highway ~ motorway|trunk|primary|secondary|tertiary|unclassified|residential and !maxspeed and !maxspeed:forward and !maxspeed:backward and !source:maxspeed and !zone:maxspeed and !maxspeed:type and !zone:traffic and surface !~ ${OsmTaggings.ANYTHING_UNPAVED.joinToString("|")} and motor_vehicle !~ private|no and vehicle !~ private|no and (access !~ private|no or (foot and foot !~ private|no)) and area != yes """ override val commitMessage = "Add speed limits" override val icon = R.drawable.ic_quest_max_speed override val hasMarkersAtEnds = true // see #813: US has different rules for each different state which need to be respected override val enabledForCountries = Countries.allExcept("US") override val defaultDisabledMessage = R.string.default_disabled_msg_maxspeed override fun getTitle(tags: Map<String, String>) = if (tags.containsKey("name")) R.string.quest_maxspeed_name_title2 else R.string.quest_maxspeed_title_short2 override fun createForm() = AddMaxSpeedForm() override fun applyAnswerTo(answer: MaxSpeedAnswer, changes: StringMapChangesBuilder) { when(answer) { is MaxSpeedSign -> { changes.add("maxspeed", answer.value) changes.add("maxspeed:type", "sign") } is MaxSpeedZone -> { changes.add("maxspeed", answer.value) changes.add("maxspeed:type", answer.countryCode + ":" + answer.roadType) } is AdvisorySpeedSign -> { changes.add("maxspeed:advisory", answer.value) changes.add("maxspeed:type:advisory", "sign") } is IsLivingStreet -> { changes.modify("highway", "living_street") } is ImplicitMaxSpeed -> { changes.add("maxspeed:type", answer.countryCode + ":" + answer.roadType) } } } }
gpl-3.0
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/xquery/XQueryWindowStartCondition.kt
1
814
/* * Copyright (C) 2016 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.ast.xquery import com.intellij.psi.PsiElement /** * An XQuery 3.0 `WindowStartCondition` node in the XQuery AST. */ interface XQueryWindowStartCondition : PsiElement
apache-2.0
HabitRPG/habitica-android
shared/src/commonMain/kotlin/com/habitrpg/shared/habitica/models/responses/MaintenanceResponse.kt
1
264
package com.habitrpg.shared.habitica.models.responses class MaintenanceResponse { var activeMaintenance: Boolean? = null var minBuild: Int? = null var title: String? = null var imageUrl: String? = null var description: String? = null }
gpl-3.0
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/plugin/PluginEmptySequenceTypePsiImpl.kt
1
2065
/* * Copyright (C) 2019, 2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xpath.psi.impl.plugin import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.util.elementType import uk.co.reecedunn.intellij.plugin.intellij.lang.* import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType import uk.co.reecedunn.intellij.plugin.xpath.ast.plugin.PluginEmptySequenceType import xqt.platform.intellij.xpath.XPathTokenProvider private val XQUERY10_REC_EMPTY: List<Version> = listOf( XQuerySpec.REC_1_0_20070123, EXistDB.VERSION_4_0 ) private val XQUERY10_WD_EMPTY: List<Version> = listOf( XQuerySpec.WD_1_0_20030502, XQuerySpec.MARKLOGIC_0_9, until(EXistDB.VERSION_4_0) ) class PluginEmptySequenceTypePsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), PluginEmptySequenceType, VersionConformance { // region XdmSequenceType override val typeName: String = "empty-sequence()" override val itemType: XdmItemType? get() = null override val lowerBound: Int = 0 override val upperBound: Int = 0 // endregion // region VersionConformance override val requiresConformance: List<Version> get() = when (conformanceElement.elementType) { XPathTokenProvider.KEmpty -> XQUERY10_WD_EMPTY else -> XQUERY10_REC_EMPTY } override val conformanceElement: PsiElement get() = firstChild // endregion }
apache-2.0
elect86/jAssimp
src/test/kotlin/assimp/md5/boarMan.kt
2
4070
package assimp.md5 import assimp.* import glm_.mat4x4.Mat4 import glm_.vec3.Vec3 import io.kotest.matchers.shouldBe object boarMan { operator fun invoke(fileName: String) { Importer().testURLs(getResource(fileName)) { flags shouldBe 0 with(rootNode) { name shouldBe "<MD5_Root>" transformation shouldBe Mat4( 1f, 0f, 0f, 0f, 0f, 0f, -1f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 0f, 1f) parent shouldBe null numChildren shouldBe 2 with(children[0]) { name shouldBe "<MD5_Mesh>" transformation shouldBe Mat4() (parent === rootNode) shouldBe true numChildren shouldBe 0 numMeshes shouldBe 1 meshes[0] shouldBe 0 } with(children[1]) { name shouldBe "<MD5_Hierarchy>" transformation shouldBe Mat4() (parent === rootNode) shouldBe true numChildren shouldBe 1 with(children[0]) { name shouldBe "Bone" transformation shouldBe Mat4( 1.00000000f, -0.000000000f, 0.000000000f, 0.000000000f, 0.000000000f, -5.96046448e-07f, 1.00000000f, 0.000000000f, -0.000000000f, -1.00000000f, -5.96046448e-07f, 0.000000000f, 0.000000000f, 0.000000000f, 0.000000000f, 1.00000000f ) (parent === rootNode.children[1]) shouldBe true numChildren shouldBe 0 numMeshes shouldBe 0 } numMeshes shouldBe 0 } numMeshes shouldBe 0 } with(meshes[0]) { primitiveTypes shouldBe 4 numVertices shouldBe 8436 numFaces shouldBe 2812 vertices[0] shouldBe Vec3(2.81622696f, 0.415550232f, 24.7310295f) vertices[4217] shouldBe Vec3(7.40894270f, 2.25090504f, 23.1958885f) vertices[8435] shouldBe Vec3(1.2144182f, -3.79157066f, 25.3626385f) textureCoords[0][0][0] shouldBe 0.704056978f textureCoords[0][0][1] shouldBe 0.896108985f textureCoords[0][4217][0] shouldBe 1.852235f textureCoords[0][4217][1] shouldBe 0.437269986f textureCoords[0][8435][0] shouldBe 0.303604007f textureCoords[0][8435][1] shouldBe 1.94788897f faces.asSequence().filterIndexed { i, _ -> i in 0..7 }.forEachIndexed { i, f -> val idx = i * 3 f shouldBe mutableListOf(idx + 1, idx + 2, idx) } faces[1407] shouldBe mutableListOf(4708, 4707, 4706) faces[2811] shouldBe mutableListOf(8435, 8434, 8433) numBones shouldBe 1 with(bones[0]) { name shouldBe "Bone" numWeights shouldBe 8436 weights.forEachIndexed { i, w -> w.vertexId shouldBe i; w.weight shouldBe 1f } offsetMatrix shouldBe Mat4( 1.00000000f, -0.000000000f, 0.000000000f, -0.000000000f, -0.000000000f, -5.96046448e-07f, -1.00000000f, 0.000000000f, 0.000000000f, 1.00000000f, -5.96046448e-07f, -0.000000000f, -0.000000000f, 0.000000000f, -0.000000000f, 1.00000000f) } materialIndex shouldBe 0 name.isEmpty() shouldBe true } numMaterials shouldBe 1 with(materials[0]) { textures[0].file shouldBe "" } } } }
mit
bugsnag/bugsnag-js
test/react-native/features/fixtures/reactnative/scenarios/UserNativeClientScenario.kt
1
353
package com.reactnative.scenarios import android.content.Context import com.bugsnag.android.Bugsnag import com.facebook.react.bridge.Promise class UserNativeClientScenario(context: Context): Scenario(context) { override fun run(promise: Promise) { Bugsnag.setUser("123", "[email protected]", "Bug Snag") throw generateException() } }
mit
matija94/show-me-the-code
java/Android-projects/Keddit/app/src/main/java/com/example/matija/keddit/MainActivity.kt
1
1690
package com.example.matija.keddit import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) if (savedInstanceState == null) { changeFragment(NewsFragment()) } } fun changeFragment(f: Fragment, cleanStack: Boolean = false) { val ft = supportFragmentManager.beginTransaction() if(cleanStack) { clearBackStack() } ft.setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_fade_out, R.anim.abc_popup_enter, R.anim.abc_popup_exit) ft.replace(R.id.activity_base_content, f) ft.addToBackStack(null) ft.commit() } fun clearBackStack() { val manager = supportFragmentManager if (manager.backStackEntryCount > 0) { val first = manager.getBackStackEntryAt(0) manager.popBackStack(first.id, FragmentManager.POP_BACK_STACK_INCLUSIVE) } } /** * Finish activity when reaching the last fragment. */ override fun onBackPressed() { val fragmentManager = supportFragmentManager if (fragmentManager.backStackEntryCount > 1) { fragmentManager.popBackStack() } else { finish() } } }
mit
MarkNKamau/JustJava-Android
app/src/main/java/com/marknkamau/justjava/data/db/DbRepositoryImpl.kt
1
1699
package com.marknkamau.justjava.data.db import com.marknkamau.justjava.data.models.AppProduct import com.marknkamau.justjava.data.models.CartItem import com.marknkamau.justjava.data.models.CartOptionEntity import com.marknkamau.justjava.data.models.CartProductEntity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class DbRepositoryImpl(private val cartDao: CartDao) : DbRepository { override suspend fun saveItemToCart(product: AppProduct, quantity: Int) = withContext(Dispatchers.IO) { val cartProductId = cartDao.addItem( CartProductEntity( 0, product.id, product.name, product.price, product.calculateTotal(quantity), quantity ) ) product.choices?.forEach { choice -> choice.options.filter { it.isChecked }.forEach { option -> val optionEntity = CartOptionEntity( 0, choice.id.toLong(), choice.name, option.id.toLong(), option.name, option.price, cartProductId ) cartDao.addItem(optionEntity) } } Unit } override suspend fun getCartItems(): List<CartItem> = withContext(Dispatchers.IO) { cartDao.getAllWithOptions() } override suspend fun deleteItemFromCart(item: CartItem) = withContext(Dispatchers.IO) { cartDao.deleteItem(item.cartItem) } override suspend fun clearCart() = withContext(Dispatchers.IO) { cartDao.deleteAll() } }
apache-2.0