repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
world-federation-of-advertisers/cross-media-measurement | src/test/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/DataProvidersServiceTest.kt | 1 | 8818 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.api.v2alpha
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.extensions.proto.ProtoTruth.assertThat
import com.google.protobuf.ByteString
import com.google.protobuf.kotlin.toByteString
import io.grpc.Status
import io.grpc.StatusRuntimeException
import java.security.cert.X509Certificate
import kotlin.test.assertFailsWith
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.kotlin.any
import org.wfanet.measurement.api.Version
import org.wfanet.measurement.api.v2alpha.dataProvider
import org.wfanet.measurement.api.v2alpha.getDataProviderRequest
import org.wfanet.measurement.api.v2alpha.signedData
import org.wfanet.measurement.api.v2alpha.testing.makeDataProvider
import org.wfanet.measurement.api.v2alpha.withDataProviderPrincipal
import org.wfanet.measurement.api.v2alpha.withMeasurementConsumerPrincipal
import org.wfanet.measurement.api.v2alpha.withModelProviderPrincipal
import org.wfanet.measurement.common.crypto.readCertificate
import org.wfanet.measurement.common.crypto.subjectKeyIdentifier
import org.wfanet.measurement.common.crypto.testing.FIXED_ENCRYPTION_PUBLIC_KEYSET
import org.wfanet.measurement.common.crypto.testing.FIXED_SERVER_CERT_PEM_FILE
import org.wfanet.measurement.common.crypto.tink.loadPublicKey
import org.wfanet.measurement.common.grpc.testing.GrpcTestServerRule
import org.wfanet.measurement.common.grpc.testing.mockService
import org.wfanet.measurement.common.testing.verifyProtoArgument
import org.wfanet.measurement.common.toProtoTime
import org.wfanet.measurement.consent.client.common.toEncryptionPublicKey
import org.wfanet.measurement.internal.kingdom.CertificateKt
import org.wfanet.measurement.internal.kingdom.DataProvider as InternalDataProvider
import org.wfanet.measurement.internal.kingdom.DataProviderKt.details
import org.wfanet.measurement.internal.kingdom.DataProvidersGrpcKt.DataProvidersCoroutineImplBase as InternalDataProvidersService
import org.wfanet.measurement.internal.kingdom.DataProvidersGrpcKt.DataProvidersCoroutineStub as InternalDataProvidersClient
import org.wfanet.measurement.internal.kingdom.certificate as internalCertificate
import org.wfanet.measurement.internal.kingdom.dataProvider as internalDataProvider
import org.wfanet.measurement.internal.kingdom.getDataProviderRequest as internalGetDataProviderRequest
private const val DATA_PROVIDER_ID = 123L
private const val DATA_PROVIDER_ID_2 = 124L
private const val CERTIFICATE_ID = 456L
private val DATA_PROVIDER_NAME = makeDataProvider(DATA_PROVIDER_ID)
private val DATA_PROVIDER_NAME_2 = makeDataProvider(DATA_PROVIDER_ID_2)
private val CERTIFICATE_NAME = "$DATA_PROVIDER_NAME/certificates/AAAAAAAAAcg"
private const val MEASUREMENT_CONSUMER_NAME = "measurementConsumers/AAAAAAAAAHs"
private const val MODEL_PROVIDER_NAME = "modelProviders/AAAAAAAAAHs"
@RunWith(JUnit4::class)
class DataProvidersServiceTest {
private val internalServiceMock: InternalDataProvidersService =
mockService() { onBlocking { getDataProvider(any()) }.thenReturn(INTERNAL_DATA_PROVIDER) }
@get:Rule val grpcTestServerRule = GrpcTestServerRule { addService(internalServiceMock) }
private lateinit var service: DataProvidersService
@Before
fun initService() {
service = DataProvidersService(InternalDataProvidersClient(grpcTestServerRule.channel))
}
@Test
fun `get with edp caller returns resource`() {
val dataProvider =
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking {
service.getDataProvider(getDataProviderRequest { name = DATA_PROVIDER_NAME })
}
}
val expectedDataProvider = dataProvider {
name = DATA_PROVIDER_NAME
certificate = CERTIFICATE_NAME
certificateDer = SERVER_CERTIFICATE_DER
publicKey = SIGNED_PUBLIC_KEY
}
assertThat(dataProvider).isEqualTo(expectedDataProvider)
verifyProtoArgument(internalServiceMock, InternalDataProvidersService::getDataProvider)
.isEqualTo(internalGetDataProviderRequest { externalDataProviderId = DATA_PROVIDER_ID })
}
@Test
fun `get with mc caller returns resource`() {
val dataProvider =
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking {
service.getDataProvider(getDataProviderRequest { name = DATA_PROVIDER_NAME })
}
}
val expectedDataProvider = dataProvider {
name = DATA_PROVIDER_NAME
certificate = CERTIFICATE_NAME
certificateDer = SERVER_CERTIFICATE_DER
publicKey = SIGNED_PUBLIC_KEY
}
assertThat(dataProvider).isEqualTo(expectedDataProvider)
verifyProtoArgument(internalServiceMock, InternalDataProvidersService::getDataProvider)
.isEqualTo(internalGetDataProviderRequest { externalDataProviderId = DATA_PROVIDER_ID })
}
@Test
fun `get throws UNAUTHENTICATED when no principal found`() {
val exception =
assertFailsWith<StatusRuntimeException> {
runBlocking {
service.getDataProvider(getDataProviderRequest { name = DATA_PROVIDER_NAME })
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.UNAUTHENTICATED)
}
@Test
fun `get throws PERMISSION_DENIED when edp caller doesn't match`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME_2) {
runBlocking {
service.getDataProvider(getDataProviderRequest { name = DATA_PROVIDER_NAME })
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `get throws PERMISSION_DENIED when principal with no authorization found`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withModelProviderPrincipal(MODEL_PROVIDER_NAME) {
runBlocking {
service.getDataProvider(getDataProviderRequest { name = DATA_PROVIDER_NAME })
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `get throws INVALID_ARGUMENT when name is missing`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking { service.getDataProvider(getDataProviderRequest {}) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `get throws INVALID_ARGUMENT when name is invalid`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking { service.getDataProvider(getDataProviderRequest { name = "foo" }) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
companion object {
private val serverCertificate: X509Certificate = readCertificate(FIXED_SERVER_CERT_PEM_FILE)
private val SERVER_CERTIFICATE_DER = serverCertificate.encoded.toByteString()
private val ENCRYPTION_PUBLIC_KEY =
loadPublicKey(FIXED_ENCRYPTION_PUBLIC_KEYSET).toEncryptionPublicKey()
private val SIGNED_PUBLIC_KEY = signedData {
data = ENCRYPTION_PUBLIC_KEY.toByteString()
signature = ByteString.copyFromUtf8("Fake signature of public key")
}
private val INTERNAL_DATA_PROVIDER: InternalDataProvider = internalDataProvider {
externalDataProviderId = DATA_PROVIDER_ID
details = details {
apiVersion = Version.V2_ALPHA.string
publicKey = SIGNED_PUBLIC_KEY.data
publicKeySignature = SIGNED_PUBLIC_KEY.signature
}
certificate = internalCertificate {
externalDataProviderId = DATA_PROVIDER_ID
externalCertificateId = CERTIFICATE_ID
subjectKeyIdentifier = serverCertificate.subjectKeyIdentifier!!
notValidBefore = serverCertificate.notBefore.toInstant().toProtoTime()
notValidAfter = serverCertificate.notAfter.toInstant().toProtoTime()
details = CertificateKt.details { x509Der = SERVER_CERTIFICATE_DER }
}
}
}
}
| apache-2.0 | d6ad9712c9edfc9dcc3bffbcb20033a7 | 40.990476 | 129 | 0.768315 | 4.636172 | false | true | false | false |
lllllT/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/presentation/internal/di/module/ApplicationModule.kt | 2 | 7411 | package com.bl_lia.kirakiratter.presentation.internal.di.module
import android.app.Application
import android.content.SharedPreferences
import android.preference.PreferenceManager
import com.bl_lia.kirakiratter.BuildConfig
import com.bl_lia.kirakiratter.R
import com.bl_lia.kirakiratter.data.cache.*
import com.bl_lia.kirakiratter.data.executor.JobExecutor
import com.bl_lia.kirakiratter.data.repository.*
import com.bl_lia.kirakiratter.data.type_adapter.AccountTypeAdapter
import com.bl_lia.kirakiratter.data.type_adapter.StatusTypeAdapter
import com.bl_lia.kirakiratter.domain.entity.Account
import com.bl_lia.kirakiratter.domain.entity.Status
import com.bl_lia.kirakiratter.domain.executor.PostExecutionThread
import com.bl_lia.kirakiratter.domain.executor.ThreadExecutor
import com.bl_lia.kirakiratter.domain.repository.*
import com.bl_lia.kirakiratter.presentation.UiThread
import com.facebook.stetho.okhttp3.StethoInterceptor
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import io.realm.RealmConfiguration
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Named
import javax.inject.Singleton
@Module
class ApplicationModule(
private val application: Application
) {
@Provides
@Singleton
internal fun provideApplication(): Application = application
@Provides
@Singleton
internal fun provideSharedPreferences(): SharedPreferences {
return PreferenceManager.getDefaultSharedPreferences(application)
}
@Provides
@Singleton
internal fun provideRetrofit(okHttpClient: OkHttpClient, gson: Gson): Retrofit =
Retrofit.Builder().apply {
baseUrl(BuildConfig.API_URL)
client(okHttpClient)
addConverterFactory(GsonConverterFactory.create(gson))
addCallAdapterFactory(RxJava2CallAdapterFactory.create())
}.build()
@Provides
@Singleton
@Named("PushRetrofit")
internal fun provideRetrofitForPush(okHttpClient: OkHttpClient): Retrofit =
Retrofit.Builder().apply {
client(okHttpClient)
baseUrl("http://example.com")
addConverterFactory(GsonConverterFactory.create())
addCallAdapterFactory(RxJava2CallAdapterFactory.create())
}.build()
@Provides
@Singleton
internal fun provideOkHttpClient(authInterceptor: Interceptor): OkHttpClient {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
return OkHttpClient.Builder().apply {
addInterceptor(authInterceptor)
if (BuildConfig.DEBUG) {
addInterceptor(interceptor)
addNetworkInterceptor(StethoInterceptor())
}
}.build()
}
@Provides
@Singleton
@Named("googleCloudClient")
internal fun provideGoogleCloudClient(): Retrofit =
Retrofit.Builder().apply {
baseUrl(BuildConfig.GOOGLE_TRANSLATE_API_URL)
addCallAdapterFactory(RxJava2CallAdapterFactory.create())
addConverterFactory(GsonConverterFactory.create())
client(OkHttpClient.Builder().apply {
addInterceptor(HttpLoggingInterceptor().apply {
level = if (BuildConfig.DEBUG) {
HttpLoggingInterceptor.Level.BODY
} else {
HttpLoggingInterceptor.Level.NONE
}
})
}.build())
}.build()
@Provides
@Singleton
internal fun provideAuthInterceptor(authCache: AuthCache): Interceptor {
return Interceptor { chain ->
val originalReq = chain.request()
val builder = originalReq.newBuilder()
val accessToken = authCache.accessToken()
if (accessToken != null) {
val value = "Bearer %s".format(accessToken.accessToken)
builder.header("Authorization", value)
}
val request = builder.build()
chain.proceed(request)
}
}
@Provides
@Singleton
fun provideGson(): Gson =
GsonBuilder().apply {
setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
registerTypeAdapter(Status::class.java, StatusTypeAdapter())
registerTypeAdapter(Account::class.java, AccountTypeAdapter())
}.create()
@Provides
@Singleton
fun provideThreadExecutor(executor: JobExecutor): ThreadExecutor = executor
@Provides
@Singleton
fun providePostExecutionThread(thread: UiThread): PostExecutionThread = thread
@Provides
@Singleton
internal fun provideAuthRepository(repository: AuthDataRepository): AuthRepository = repository
@Provides
@Singleton
internal fun provideTimelineRepository(repository: TimelineDataRepository): TimelineRepository = repository
@Provides
@Singleton
internal fun provideStatusRepository(repository: StatusDataRepository): StatusRepository = repository
@Provides
@Singleton
internal fun provideTranslationRepository(repository: TranslationDataRepository): TranslationRepository = repository
@Provides
@Singleton
internal fun provideNotificationRepository(repository: NotificationDataRepository): NotificationRepository = repository
@Provides
@Singleton
internal fun provideAccountRepository(repository: AccountDataRepository): AccountRepository = repository
@Provides
@Singleton
internal fun providePushNotificationRepository(repository: PushNotificationDataRepository): PushNotificationRepository = repository
@Provides
@Singleton
internal fun provideAuthCache(cache: SharedPrefAuthCache): AuthCache = cache
@Provides
@Singleton
internal fun provideTimelineCache(cache: SharedPrefTimelineCache): TimelineCache = cache
@Provides
@Singleton
internal fun provideAccountCache(cache: MemoryAccountCache): AccountCache = cache
@Provides
@Singleton
internal fun provideTimelineStatusCache(cache: RealmTimelineStatusCache): TimelineStatusCache = cache
@Provides
@Singleton
@Named("appName")
internal fun provideAppName(): String = application.getString(R.string.app_name)
@Provides
@Singleton
@Named("oauthRedirectUri")
internal fun provideOauthRedirectUri(): String {
return "%s://%s/".format(application.getString(R.string.oauth_scheme), application.getString(R.string.oauth_redirect_host))
}
@Provides
@Singleton
@Named("oauthScopes")
internal fun provideOauthScopes(): String = "read write follow"
@Provides
@Singleton
@Named("appWebsite")
internal fun provideAppWebsite(): String = application.getString(R.string.app_website)
@Provides
@Singleton
internal fun provideRealmConfiguration(): RealmConfiguration =
RealmConfiguration.Builder()
.deleteRealmIfMigrationNeeded()
.build()
} | mit | 55cc8d96e0aaef8933665e47ef927d26 | 34.127962 | 135 | 0.70085 | 5.433284 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/inspections/latex/typesetting/spacing/LatexMathOperatorEscapeInspection.kt | 1 | 4052 | package nl.hannahsten.texifyidea.inspections.latex.typesetting.spacing
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiRecursiveElementVisitor
import com.intellij.psi.util.PsiTreeUtil
import nl.hannahsten.texifyidea.inspections.InsightGroup
import nl.hannahsten.texifyidea.inspections.TexifyInspectionBase
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.psi.LatexMathContent
import nl.hannahsten.texifyidea.psi.LatexTypes
import nl.hannahsten.texifyidea.util.magic.CommandMagic
import org.jetbrains.annotations.Nls
/**
* Detects non-escaped common math functions like *sin*, *cos* and replaces them
* with `\sin`, `\cos`.
*
* @author Sten Wessel
*/
class LatexMathOperatorEscapeInspection : TexifyInspectionBase() {
override val inspectionGroup = InsightGroup.LATEX
@Nls
override fun getDisplayName() = "Non-escaped common math operators"
override val inspectionId = "MathOperatorEscape"
override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): List<ProblemDescriptor> {
val descriptors = descriptorList()
val pattern = PlatformPatterns.psiElement(LatexTypes.NORMAL_TEXT_WORD)
val envs = PsiTreeUtil.findChildrenOfType(file, LatexMathContent::class.java)
for (env in envs) {
env.acceptChildren(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
ProgressManager.checkCanceled()
if (pattern.accepts(element)) {
fun hasMathParentBeforeTextParent() = PsiTreeUtil.collectParents(
element,
LatexMathContent::class.java,
false
) { it is LatexCommands && it.name == "\\text" }.size > 0
fun descriptorAlreadyExists() = descriptors.firstOrNull {
it.psiElement == element && it.descriptionTemplate == "Non-escaped math operator"
} != null
if (element.text in SLASHLESS_MATH_OPERATORS && !descriptorAlreadyExists() && hasMathParentBeforeTextParent()) {
descriptors.add(
manager.createProblemDescriptor(
element,
"Non-escaped math operator",
EscapeMathOperatorFix(),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOntheFly
)
)
}
}
else super.visitElement(element)
}
})
}
return descriptors
}
/**
* @author Sten Wessel
*/
private class EscapeMathOperatorFix : LocalQuickFix {
@Nls
override fun getFamilyName(): String = "Escape math operator"
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement
val document = PsiDocumentManager.getInstance(project).getDocument(element.containingFile)
document?.insertString(element.textOffset, "\\")
}
}
companion object {
private val SLASHLESS_MATH_OPERATORS = CommandMagic.slashlessMathOperators.asSequence()
.map { it.command }
.toSet()
}
} | mit | d55d68538534546a1be025bdd987d85b | 40.357143 | 136 | 0.619694 | 5.612188 | false | false | false | false |
RoverPlatform/rover-android | experiences/src/main/kotlin/io/rover/sdk/experiences/assets/ImageDownloader.kt | 1 | 8621 | package io.rover.sdk.experiences.assets
import android.net.http.HttpResponseCache
import io.rover.sdk.core.data.http.AndroidHttpsUrlConnectionNetworkClient
import io.rover.sdk.experiences.logging.log
import io.rover.sdk.experiences.platform.debugExplanation
import org.reactivestreams.Publisher
import org.reactivestreams.Subscription
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.Executor
/**
* A simple HTTP downloader.
*/
internal class ImageDownloader(
private val ioExecutor: Executor
) {
/**
* Download the given URL as a stream. Supports HTTP and HTTPS, but only GET is supported.
*
* @return a async Publisher that yields a single [HttpClientResponse]. That response itself
* will contain a stream that can be read from until the connection completes.
*/
fun downloadStreamFromUrl(url: URL): Publisher<HttpClientResponse> {
// TODO: do the same global http cache check as the version in graphql API service is doing.
// TODO: also need some sort of interception support.
return Publisher { subscriber ->
var cancelled = false
var requested = false
val subscription = object : Subscription {
override fun request(n: Long) {
if (n != Long.MAX_VALUE) throw RuntimeException("Backpressure signalling not supported. Request Long.MAX_VALUE.")
if (requested) return
requested = true
ioExecutor.execute {
val connection = url
.openConnection() as HttpURLConnection
if (!connection.useCaches || HttpResponseCache.getInstalled() == null) {
// We expect the user to agree to and implement setting up a global
// HttpUrlConnection cache. While we would much prefer to maintain our own,
// however, the global-side-effect nature of the Android HttpClient API means
// that we won't be able to achieve that without just building our own cache
// regime rather than using the stock Android cache, so we'll stick with this
// approach for now.
//
// This is made even more unfortunate because it would have been to our
// advantage to set up parallel HttpClients with different caches in order to
// cache different request payloads separately: when the goal is to save
// perceptible delay for users small JSON payloads are more valuable to cache
// byte-for-byte compared with large bulky asset (say, images) payloads. Leaving
// them in the same LRU cache pool will mean that rotating through just a few
// large photos will cause the small payloads to be evicted even though their
// contribution to consumption of the cache is tiny.
AndroidHttpsUrlConnectionNetworkClient.emitMissingCacheWarning()
}
connection.apply {
requestMethod = "GET"
connectTimeout = 60000
readTimeout = 60000
}
val responseCode = try {
connection.connect()
connection.responseCode
} catch (e: IOException) {
// yield error to publisher.
log.w("$url -> connection failure: ${e.debugExplanation()}")
if (!cancelled) subscriber.onNext(
HttpClientResponse.ConnectionFailure(
e
)
)
if (!cancelled) subscriber.onComplete()
return@execute
}
log.v("$url -> HTTP $responseCode")
val result = when (responseCode) {
in 200..299, 304 -> {
try {
HttpClientResponse.Success(
CloseableBufferedInputStream(
connection.inputStream
) {
// when done reading the buffered stream, I can close out
// the connection (actually, the platform usually interprets
// this as returning it to the connection pool).
connection.disconnect()
}
)
} catch (e: IOException) {
HttpClientResponse.ConnectionFailure(
e
)
}
}
else -> {
// we don't support handling redirects as anything other than an onError for now.
try {
connection.errorStream.use { errorStream ->
val stream = BufferedInputStream(
errorStream
)
val result = HttpClientResponse.ApplicationError(
responseCode,
stream.reader(Charsets.UTF_8).readText()
)
stream.close()
connection.disconnect()
result
}
} catch (e: IOException) {
HttpClientResponse.ConnectionFailure(
e
)
}
}
}
if (!cancelled) {
subscriber.onNext(result)
subscriber.onComplete()
}
}
}
override fun cancel() {
// We're not going to attempt cancellation because we don't have a way yet
// of dispatching this on the thread in the ioExecutor the connection got
// scheduled on in the first place. Instead we'll just inhibit any more
// message deliveries.
cancelled = true
}
}
subscriber.onSubscribe(subscription)
}
}
sealed class HttpClientResponse {
class Success(
/**
* The HTTP request has gotten a successful reply, and now the server is streaming the
* response body to us.
*/
val bufferedInputStream: BufferedInputStream
) : HttpClientResponse()
/**
* A a session layer or below onError (HTTP protocol onError, network onError, and so on)
* occurred. Likely culprit is local connectivity issues or possibly even a Rover API outage.
*/
class ConnectionFailure(val reason: Throwable) : HttpClientResponse()
/**
* An application layer (HTTP) onError occurred (ie., a non-2xx status code).
*/
class ApplicationError(
val responseCode: Int,
val reportedReason: String
) : HttpClientResponse()
}
class CloseableBufferedInputStream(
input: InputStream,
private val onClose: () -> Unit
) : BufferedInputStream(input) {
override fun close() {
super.close()
onClose()
}
}
}
| apache-2.0 | e43182dfd90a4567e0d0ff5cd24c1bd0 | 46.10929 | 134 | 0.464911 | 6.930064 | false | false | false | false |
aaraashkhan/Runda | app/src/main/java/arash/sp/runda/view/fragments/RunningFragment.kt | 1 | 2020 | package arash.sp.runda.view.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import arash.sp.runda.R
import arash.sp.runda.presenters.RunningPresenter
import arash.sp.runda.rx.RunningObservable
import kotlinx.android.synthetic.main.fragment_running.*
/**
* Fragment to keep track of current workout
*/
class RunningFragment : Fragment() {
var mFragmentView: View? = null
lateinit var mObserver: RunningObservable
lateinit var mPresenter: RunningPresenter
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
if (mFragmentView == null) {
mFragmentView = inflater!!.inflate(R.layout.fragment_running, container, false)
}
mObserver = RunningObservable()
mPresenter = RunningPresenter(mObserver, this)
mObserver.setTextView(mFragmentView?.findViewById(R.id.counter))
mObserver.setStepsTextView(mFragmentView?.findViewById(R.id.steps))
mPresenter.onViewStarted()
return mFragmentView
}
fun decorateView() {
val start = mFragmentView?.findViewById<Button>(R.id.start)
val stop = mFragmentView?.findViewById<Button>(R.id.stop)
val counter = mFragmentView?.findViewById<TextView>(R.id.counter)
start?.setOnClickListener({
counter?.text = getString(R.string.title_counter_started)
start.isEnabled = false
mPresenter.startClicked()
})
stop?.setOnClickListener({
start?.isEnabled = true
counter?.text = getString(R.string.title_counter_stoped)
steps?.text = "Steps"
mPresenter.stopClicked()
})
}
override fun onDestroyView() {
super.onDestroyView()
mPresenter.onViewDestroyed()
}
}
| mit | e08039d9a8886d08927fcb07e3dca64c | 30.076923 | 91 | 0.681188 | 4.519016 | false | false | false | false |
GuiyeC/Aerlink-for-Android | wear/src/main/java/com/codegy/aerlink/extensions/BluetoothGatt+Extension.kt | 1 | 6131 | package com.codegy.aerlink.extensions
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattDescriptor
import android.util.Log
import com.codegy.aerlink.connection.CharacteristicIdentifier
import java.util.*
fun BluetoothGatt.getCharacteristic(characteristicIdentifier: CharacteristicIdentifier): BluetoothGattCharacteristic? {
return getCharacteristic(characteristicIdentifier.serviceUUID, characteristicIdentifier.characteristicUUID)
}
fun BluetoothGatt.getCharacteristic(serviceUUID: UUID, characteristicUUID: UUID): BluetoothGattCharacteristic? {
val service = getService(serviceUUID)
if (service == null) {
Log.e(this.javaClass.simpleName, "Service unavailable: $serviceUUID")
return null
}
val characteristic = service.getCharacteristic(characteristicUUID)
if (characteristic == null) {
Log.e(this.javaClass.simpleName, "Characteristic unavailable: $characteristicUUID")
return null
}
return characteristic
}
fun BluetoothGatt.subscribeToCharacteristic(characteristicIdentifier: CharacteristicIdentifier): Boolean {
val characteristic = getCharacteristic(characteristicIdentifier) ?: return false
val notificationsEnabledLocally = setCharacteristicNotification(characteristic, true)
if (!notificationsEnabledLocally) {
Log.e(this.javaClass.simpleName, "Failed to enable notifications locally on ${characteristicIdentifier.characteristicUUID}")
return false
}
// We write the configuration descriptor to enable notifications on the remote device
val configDescriptorUUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")
val descriptor = characteristic.getDescriptor(configDescriptorUUID)
if (descriptor == null) {
Log.e(this.javaClass.simpleName, "Descriptor unavailable to write on ${characteristicIdentifier.characteristicUUID}")
return false
}
descriptor.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
// descriptor.value = BluetoothGattDescriptor.ENABLE_INDICATION_VALUE
val notificationsEnabledRemotely = writeDescriptor(descriptor)
if (!notificationsEnabledRemotely) {
Log.e(this.javaClass.simpleName, "Failed to enable notifications remotely on ${characteristicIdentifier.characteristicUUID}")
return false
}
Log.d(this.javaClass.simpleName, "Started writing descriptor: ${characteristicIdentifier.characteristicUUID}")
return true
}
// Status: https://android.googlesource.com/platform/external/bluetooth/bluedroid/+/5738f83aeb59361a0a2eda2460113f6dc9194271/stack/include/gatt_api.h
fun stringFromConnectionError(error: Int): String {
when (error) {
BluetoothGatt.GATT_SUCCESS -> return "SUCCESS"
/** GATT CONN L2C FAILURE **/
0x01 -> return "GATT CONN L2C FAILURE: General L2CAP failure"
/** GATT_CONN_TIMEOUT **/
0x08 -> return "GATT CONN TIMEOUT: Connection timeout"
/** GATT CONN TERMINATE PEER USER **/
0x13 -> return "GATT CONN TERMINATE PEER USER: Connection terminated by peer user"
/** GATT CONN TERMINATE LOCAL HOST **/
0x16 -> return "GATT CONN TERMINATE LOCAL HOST: Connection terminated by local host"
/** GATT CONN FAIL ESTABLISH **/
0x3E -> return "GATT CONN FAIL ESTABLISH: Connection fail to establish"
/** GATT CONN LMP TIMEOUT **/
0x22 -> return "GATT CONN LMP TIMEOUT: Connection fail for LMP, response timed-out"
/** GATT CONN CANCEL **/
0x0100 -> return "GATT CONN CANCEL: L2CAP connection cancelled"
/** GATT ERROR **/
0x0085 -> return "GATT ERROR"
else -> return "UNKNOWN (0x${error.toString(16)})"
}
}
fun stringFromStatus(status: Int): String {
when (status) {
BluetoothGatt.GATT_SUCCESS -> return "SUCCESS"
0x0001 -> return "GATT INVALID HANDLE"
BluetoothGatt.GATT_READ_NOT_PERMITTED -> return "GATT READ NOT PERMITTED"
BluetoothGatt.GATT_WRITE_NOT_PERMITTED -> return "GATT WRITE NOT PERMITTED"
0x0004 -> return "GATT INVALID PDU"
BluetoothGatt.GATT_INSUFFICIENT_AUTHENTICATION -> return "GATT INSUFFICIENT AUTHENTICATION: Insufficient authentication for a given operation"
BluetoothGatt.GATT_REQUEST_NOT_SUPPORTED -> return "GATT REQUEST NOT SUPPORTED: The given request is not supported"
BluetoothGatt.GATT_INVALID_OFFSET -> return "GATT INVALID OFFSET: A read or write operation was requested with an invalid offset"
0x0008 -> return "GATT INSUFFICIENT AUTHORIZATION"
0x0009 -> return "GATT PREPARE Q FULL"
0x000a -> return "GATT NOT FOUND"
0x000b -> return "GATT NOT LONG"
0x000c -> return "GATT INSUFFICIENT KEY SIZE"
BluetoothGatt.GATT_INVALID_ATTRIBUTE_LENGTH -> return "GATT INVALID ATTRIBUTE LENGTH: A write operation exceeds the maximum length of the attribute"
0x000e -> return "GATT ERR UNLIKELY"
BluetoothGatt.GATT_INSUFFICIENT_ENCRYPTION -> return "GATT INSUFFICIENT ENCRYPTION: "
0x0010 -> return "GATT UNSUPPORTED GRP TYPE"
0x0011 -> return "GATT INSUFFICIENT RESOURCE"
0x0080 -> return "GATT NO RESOURCES"
0x0081 -> return "GATT INTERNAL ERROR"
0x0082 -> return "GATT WRONG STATE"
0x0083 -> return "GATT DB FULL"
0x0084 -> return "GATT BUSY"
0x0085 -> return "GATT ERROR"
0x0086 -> return "GATT CMD STARTED"
0x0087 -> return "GATT ILLEGAL PARAMETER"
0x0088 -> return "GATT PENDING"
0x0089 -> return "GATT AUTH FAIL"
0x008a -> return "GATT MORE"
0x008b -> return "GATT INVALID CFG"
0x008c -> return "GATT SERVICE STARTED"
0x008d -> return "GATT ENCRYPTED NO MITM"
0x008e -> return "GATT NOT ENCRYPTED"
BluetoothGatt.GATT_CONNECTION_CONGESTED -> return "GATT CONGESTED: A remote device connection is congested"
BluetoothGatt.GATT_FAILURE -> return "GATT FAILURE: A GATT operation failed"
else -> return "UNKNOWN (0x${status.toString(16)})"
}
}
| mit | 1cd360759c8280e432867ab6d322ac14 | 49.254098 | 156 | 0.714728 | 4.345145 | false | false | false | false |
googlesamples/mlkit | android/translate/app/src/main/java/com/google/mlkit/samples/nl/translate/kotlin/TranslateViewModel.kt | 1 | 8065 | /*
* Copyright 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mlkit.samples.nl.translate.kotlin
import android.app.Application
import android.util.LruCache
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
import com.google.mlkit.common.model.DownloadConditions
import com.google.mlkit.common.model.RemoteModelManager
import com.google.mlkit.nl.translate.TranslateLanguage
import com.google.mlkit.nl.translate.TranslateRemoteModel
import com.google.mlkit.nl.translate.Translation
import com.google.mlkit.nl.translate.Translator
import com.google.mlkit.nl.translate.TranslatorOptions
import com.google.mlkit.samples.nl.translate.R
import java.util.Locale
/**
* Model class for tracking available models and performing live translations
*/
class TranslateViewModel(application: Application) : AndroidViewModel(application) {
companion object {
// This specifies the number of translators instance we want to keep in our LRU cache.
// Each instance of the translator is built with different options based on the source
// language and the target language, and since we want to be able to manage the number of
// translator instances to keep around, an LRU cache is an easy way to achieve this.
private const val NUM_TRANSLATORS = 3
}
private val modelManager: RemoteModelManager = RemoteModelManager.getInstance()
private val pendingDownloads: HashMap<String, Task<Void>> = hashMapOf()
private val translators =
object : LruCache<TranslatorOptions, Translator>(NUM_TRANSLATORS) {
override fun create(options: TranslatorOptions): Translator {
return Translation.getClient(options)
}
override fun entryRemoved(
evicted: Boolean,
key: TranslatorOptions,
oldValue: Translator,
newValue: Translator?,
) {
oldValue.close()
}
}
val sourceLang = MutableLiveData<Language>()
val targetLang = MutableLiveData<Language>()
val sourceText = MutableLiveData<String>()
val translatedText = MediatorLiveData<ResultOrError>()
val availableModels = MutableLiveData<List<String>>()
// Gets a list of all available translation languages.
val availableLanguages: List<Language> = TranslateLanguage.getAllLanguages().map { Language(it) }
init {
// Create a translation result or error object.
val processTranslation =
OnCompleteListener<String> { task ->
if (task.isSuccessful) {
translatedText.value = ResultOrError(task.result, null)
} else {
translatedText.value = ResultOrError(null, task.exception)
}
// Update the list of downloaded models as more may have been
// automatically downloaded due to requested translation.
fetchDownloadedModels()
}
// Start translation if any of the following change: input text, source lang, target lang.
translatedText.addSource(sourceText) { translate().addOnCompleteListener(processTranslation) }
val languageObserver =
Observer<Language> { translate().addOnCompleteListener(processTranslation) }
translatedText.addSource(sourceLang, languageObserver)
translatedText.addSource(targetLang, languageObserver)
// Update the list of downloaded models.
fetchDownloadedModels()
}
private fun getModel(languageCode: String): TranslateRemoteModel {
return TranslateRemoteModel.Builder(languageCode).build()
}
// Updates the list of downloaded models available for local translation.
private fun fetchDownloadedModels() {
modelManager.getDownloadedModels(TranslateRemoteModel::class.java).addOnSuccessListener {
remoteModels ->
availableModels.value = remoteModels.sortedBy { it.language }.map { it.language }
}
}
// Starts downloading a remote model for local translation.
internal fun downloadLanguage(language: Language) {
val model = getModel(TranslateLanguage.fromLanguageTag(language.code)!!)
var downloadTask: Task<Void>?
if (pendingDownloads.containsKey(language.code)) {
downloadTask = pendingDownloads[language.code]
// found existing task. exiting
if (downloadTask != null && !downloadTask.isCanceled) {
return
}
}
downloadTask =
modelManager.download(model, DownloadConditions.Builder().build()).addOnCompleteListener {
pendingDownloads.remove(language.code)
fetchDownloadedModels()
}
pendingDownloads[language.code] = downloadTask
}
// Returns if a new model download task should be started.
fun requiresModelDownload(
lang: Language,
downloadedModels: List<String?>?,
): Boolean {
return if (downloadedModels == null) {
true
} else !downloadedModels.contains(lang.code) && !pendingDownloads.containsKey(lang.code)
}
// Deletes a locally stored translation model.
internal fun deleteLanguage(language: Language) {
val model = getModel(TranslateLanguage.fromLanguageTag(language.code)!!)
modelManager.deleteDownloadedModel(model).addOnCompleteListener { fetchDownloadedModels() }
pendingDownloads.remove(language.code)
}
fun translate(): Task<String> {
val text = sourceText.value
val source = sourceLang.value
val target = targetLang.value
if (source == null || target == null || text == null || text.isEmpty()) {
return Tasks.forResult("")
}
val sourceLangCode = TranslateLanguage.fromLanguageTag(source.code)!!
val targetLangCode = TranslateLanguage.fromLanguageTag(target.code)!!
val options =
TranslatorOptions.Builder()
.setSourceLanguage(sourceLangCode)
.setTargetLanguage(targetLangCode)
.build()
return translators[options].downloadModelIfNeeded().continueWithTask { task ->
if (task.isSuccessful) {
translators[options].translate(text)
} else {
Tasks.forException<String>(
task.exception
?: Exception(getApplication<Application>().getString(R.string.unknown_error))
)
}
}
}
/** Holds the result of the translation or any error. */
inner class ResultOrError(var result: String?, var error: Exception?)
/**
* Holds the language code (i.e. "en") and the corresponding localized full language name (i.e.
* "English")
*/
class Language(val code: String) : Comparable<Language> {
private val displayName: String
get() = Locale(code).displayName
override fun equals(other: Any?): Boolean {
if (other === this) {
return true
}
if (other !is Language) {
return false
}
val otherLang = other as Language?
return otherLang!!.code == code
}
override fun toString(): String {
return "$code - $displayName"
}
override fun compareTo(other: Language): Int {
return this.displayName.compareTo(other.displayName)
}
override fun hashCode(): Int {
return code.hashCode()
}
}
override fun onCleared() {
super.onCleared()
// Each new instance of a translator needs to be closed appropriately. Here we utilize the
// ViewModel's onCleared() to clear our LruCache and close each Translator instance when
// this ViewModel is no longer used and destroyed.
translators.evictAll()
}
}
| apache-2.0 | d03488f0b056ac4bfd3414f45288d70c | 35.826484 | 99 | 0.717917 | 4.680789 | false | false | false | false |
dafi/photoshelf | tumblr-ui-core/src/main/java/com/ternaryop/photoshelf/tumblr/ui/core/fragment/AbsPostsListFragment.kt | 1 | 17748 | package com.ternaryop.photoshelf.tumblr.ui.core.fragment
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.view.ActionMode
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.PopupMenu
import androidx.appcompat.widget.SearchView
import androidx.core.os.bundleOf
import androidx.core.view.MenuProvider
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.RecyclerView
import com.ternaryop.compat.os.getParcelableCompat
import com.ternaryop.photoshelf.EXTRA_POST
import com.ternaryop.photoshelf.activity.ImageViewerActivityStarter
import com.ternaryop.photoshelf.activity.ImageViewerData
import com.ternaryop.photoshelf.activity.TagPhotoBrowserData
import com.ternaryop.photoshelf.adapter.OnPhotoBrowseClickMultiChoice
import com.ternaryop.photoshelf.fragment.AbsPhotoShelfFragment
import com.ternaryop.photoshelf.fragment.BottomMenuSheetDialogFragment
import com.ternaryop.photoshelf.tumblr.dialog.EditPostEditorData
import com.ternaryop.photoshelf.tumblr.dialog.PostEditorActivityResultContracts
import com.ternaryop.photoshelf.tumblr.dialog.PostEditorResult
import com.ternaryop.photoshelf.tumblr.dialog.TumblrPostDialog
import com.ternaryop.photoshelf.tumblr.dialog.TumblrPostDialog.Companion.EXTRA_THUMBNAILS_ITEMS
import com.ternaryop.photoshelf.tumblr.ui.core.R
import com.ternaryop.photoshelf.tumblr.ui.core.adapter.PhotoShelfPost
import com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo.OnPhotoSwitchView
import com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo.PhotoAdapter
import com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo.PhotoAdapterGroup
import com.ternaryop.photoshelf.tumblr.ui.core.adapter.photo.PhotoAdapterSwitcher
import com.ternaryop.photoshelf.tumblr.ui.core.adapter.switcher.AdapterSwitcher
import com.ternaryop.photoshelf.tumblr.ui.core.adapter.switcher.AdapterSwitcherConfig
import com.ternaryop.photoshelf.tumblr.ui.core.postaction.OnPostActionListener
import com.ternaryop.photoshelf.tumblr.ui.core.postaction.PostAction
import com.ternaryop.photoshelf.tumblr.ui.core.postaction.PostActionColorItemDecoration
import com.ternaryop.photoshelf.tumblr.ui.core.postaction.PostActionExecutor
import com.ternaryop.photoshelf.tumblr.ui.core.postaction.PostActionResult
import com.ternaryop.photoshelf.tumblr.ui.core.postaction.errorList
import com.ternaryop.photoshelf.tumblr.ui.core.postaction.showConfirmDialog
import com.ternaryop.tumblr.TumblrAltSize.Companion.IMAGE_WIDTH_75
import com.ternaryop.tumblr.TumblrPhotoPost
import com.ternaryop.tumblr.android.finishActivity
import com.ternaryop.tumblr.android.viewPost
import com.ternaryop.utils.dialog.DialogUtils
import kotlinx.coroutines.launch
import javax.inject.Inject
private const val PHOTO_POST_ID = "photoPostId"
private const val QUICK_LIST_NAVIGATOR_DEFAULT_VISIBILITY_DURATION = 5000L
abstract class AbsPostsListFragment(
private val imageViewerActivityStarter: ImageViewerActivityStarter,
val tumblrPostDialog: TumblrPostDialog
) : AbsPhotoShelfFragment(),
OnPostActionListener,
OnPhotoBrowseClickMultiChoice,
SearchView.OnQueryTextListener,
ActionMode.Callback,
MenuProvider {
protected val photoAdapter: PhotoAdapter<out RecyclerView.ViewHolder>
get() {
return photoAdapterSwitcher.adapterGroup.adapter
}
protected lateinit var photoAdapterSwitcher: PhotoAdapterSwitcher
protected lateinit var recyclerView: RecyclerView
protected var searchView: SearchView? = null
protected var returnSelectedPost: Boolean = false
private var recyclerViewLayout: Parcelable? = null
val onConfirm: (PostAction) -> Unit = { postAction -> launch { postActionExecutor.execute(postAction) } }
private val activityResult = registerForActivityResult(PostEditorActivityResultContracts.Edit(tumblrPostDialog)) {
it?.also { onEdit(it) }
}
open val singleSelectionMenuIds: IntArray by lazy {
intArrayOf(R.id.post_edit, R.id.group_menu_image_dimension, R.id.show_post)
}
@Inject
lateinit var postActionExecutor: PostActionExecutor
private lateinit var postActionColorItemDecoration: PostActionColorItemDecoration
protected abstract val actionModeMenuId: Int
protected abstract val actionBarGroupMenuId: Int
abstract val adapterSwitcherConfig: AdapterSwitcherConfig
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_photo_list, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
postActionExecutor.onPostActionListener = this
postActionColorItemDecoration = PostActionColorItemDecoration(requireContext())
recyclerView = view.findViewById(R.id.list)
recyclerView.setHasFixedSize(true)
recyclerView.addItemDecoration(postActionColorItemDecoration)
view.findViewById<View>(R.id.scroll_buttons)?.also {
val visibilityDuration = arguments?.getLong(
ARG_QUICK_LIST_NAVIGATOR_VISIBILITY_DURATION, QUICK_LIST_NAVIGATOR_DEFAULT_VISIBILITY_DURATION
) ?: QUICK_LIST_NAVIGATOR_DEFAULT_VISIBILITY_DURATION
recyclerView.addOnScrollListener(QuickListNavigatorScrollListener(it, visibilityDuration))
}
photoAdapterSwitcher = AdapterSwitcher(
requireContext(),
PhotoAdapterGroup(adapterSwitcherConfig, recyclerView, this),
OnPhotoSwitchView()
)
photoAdapterSwitcher.switchView(photoAdapterSwitcher.viewType)
recyclerViewLayout = savedInstanceState?.getParcelableCompat(KEY_STATE_RECYCLER_VIEW_LAYOUT, Parcelable::class.java)
requireActivity().addMenuProvider(this, viewLifecycleOwner, Lifecycle.State.RESUMED)
}
override fun onAttach(context: Context) {
super.onAttach(context)
childFragmentManager.addFragmentOnAttachListener { _, childFragment ->
if (childFragment is BottomMenuSheetDialogFragment) {
childFragment.menuListener = when (childFragment.tag) {
FRAGMENT_IMAGE_BROWSER -> ImageBrowserBottomMenuListener(imageViewerActivityStarter)
else -> null
}
}
}
}
override fun onPrepareMenu(menu: Menu) {
menu.getItem(0)?.groupId?.also {
val isMenuVisible = !fragmentActivityStatus.isDrawerMenuOpen
menu.setGroupVisible(actionBarGroupMenuId, isMenuVisible)
}
setupSearchView(menu)
super.onPrepareMenu(menu)
}
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
mode.setTitle(R.string.select_posts)
mode.subtitle = resources.getQuantityString(R.plurals.selected_items, 1, 1)
val inflater = mode.menuInflater
inflater.inflate(actionModeMenuId, menu)
photoAdapter.isActionModeOn = true
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean = true
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
return handleMenuItem(item, photoAdapter.selectedPosts, mode)
}
override fun onDestroyActionMode(mode: ActionMode) {
this.actionMode = null
photoAdapter.selection.clear()
photoAdapter.isActionModeOn = false
}
private fun updateMenuItems() {
val selectCount = photoAdapter.selection.itemCount
val singleSelection = selectCount == 1
for (itemId in singleSelectionMenuIds) {
actionMode?.menu?.findItem(itemId)?.isVisible = singleSelection
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
saveRecyclerViewLayout(outState)
}
override fun refreshUI() {
updateTitleBar()
// use post() to resolve the following error:
// Cannot call this method in a scroll callback.
// Scroll callbacks might be run during a measure & layout pass where you cannot change theRecyclerView data.
// Any method call that might change the structure of the RecyclerView or the adapter contents
// should be postponed to the next frame.
recyclerView.post {
val itemAnimator = recyclerView.itemAnimator
if (itemAnimator == null) {
photoAdapter.notifyDataSetChanged()
} else {
// notifyDataSetChanged() can 'hide' the remove item animation started by notifyItemRemoved()
// so we wait for finished animations before call it
itemAnimator.isRunning {
photoAdapter.notifyDataSetChanged()
}
}
restoreRecyclerViewLayout()
}
}
protected open fun updateTitleBar() {
supportActionBar?.subtitle = resources.getQuantityString(
R.plurals.posts_count,
photoAdapter.itemCount,
photoAdapter.itemCount
)
}
override fun onTagClick(position: Int, clickedTag: String) {
requireContext().startActivity(
imageViewerActivityStarter.tagPhotoBrowserIntent(
requireContext(),
TagPhotoBrowserData(blogName, clickedTag, false)
)
)
}
override fun onThumbnailImageClick(position: Int) {
val post = photoAdapter.getItem(position)
val altSize = checkNotNull(post.firstPhotoAltSize)
imageViewerActivityStarter.startImageViewer(
requireContext(),
ImageViewerData(altSize[0].url, post.caption, post.firstTag)
)
}
override fun onOverflowClick(position: Int, view: View) {
val popupMenu = PopupMenu(requireContext(), view)
popupMenu.menuInflater.inflate(actionModeMenuId, popupMenu.menu)
popupMenu.setOnMenuItemClickListener { handleMenuItem(it, listOf(photoAdapter.getItem(position))) }
popupMenu.show()
}
override fun onItemClick(position: Int) {
if (actionMode == null) {
handleClickedThumbnail(position)
} else {
updateSelection(position)
}
}
override fun onItemLongClick(position: Int) {
if (actionMode == null) {
actionMode = requireActivity().startActionMode(this)
}
updateSelection(position)
}
private fun handleClickedThumbnail(position: Int) {
if (returnSelectedPost) {
photoAdapter.getItem(position).finishActivity(requireActivity(), EXTRA_POST)
} else {
return
// onThumbnailImageClick(position)
}
}
private fun updateSelection(position: Int) {
val selection = photoAdapter.selection
selection.toggle(position)
if (selection.itemCount == 0) {
actionMode?.finish()
} else {
updateMenuItems()
val selectionCount = selection.itemCount
actionMode?.subtitle = resources.getQuantityString(
R.plurals.selected_items,
selectionCount,
selectionCount
)
}
}
protected open fun handleMenuItem(
item: MenuItem,
postList: List<PhotoShelfPost>,
mode: ActionMode? = null
): Boolean {
val blogName = blogName ?: return false
return when (item.itemId) {
R.id.group_menu_image_dimension -> {
browseImageBySize(postList[0])
true
}
R.id.post_delete -> {
PostAction.Delete(blogName, postList).showConfirmDialog(requireContext(), onConfirm)
true
}
R.id.post_edit -> {
actionMode = mode
showEditDialog(postList[0])
true
}
R.id.show_post -> {
postList[0].viewPost(this)
true
}
else -> false
}
}
private fun browseImageBySize(photo: PhotoShelfPost) {
val title = getString(R.string.menu_header_show_image, photo.firstTag)
BottomMenuSheetDialogFragment()
.apply {
arguments = bundleOf(
BottomMenuSheetDialogFragment.ARG_TITLE to title,
BottomMenuSheetDialogFragment.ARG_SUBTITLE to photo.postId.toString(),
ImageBrowserBottomMenuListener.ARG_PHOTO_POST to photo
)
}
.show(childFragmentManager, FRAGMENT_IMAGE_BROWSER)
}
protected open fun setupSearchView(menu: Menu): SearchView? {
val searchMenu = menu.findItem(R.id.action_search)
if (searchMenu != null) {
searchView = (searchMenu.actionView as SearchView).also {
it.queryHint = getString(R.string.enter_tag_hint)
it.setOnQueryTextListener(this)
}
}
return searchView
}
override fun onQueryTextChange(newText: String): Boolean {
photoAdapter.filter.filter(newText)
return true
}
override fun onQueryTextSubmit(query: String): Boolean {
return true
}
override fun onStart(postAction: PostAction, executor: PostActionExecutor) {
postActionColorItemDecoration.setColor(postAction)
}
override fun onComplete(postAction: PostAction, executor: PostActionExecutor, resultList: List<PostActionResult>) {
refreshUI()
val errorList = resultList.errorList()
// all posts have been deleted so call actionMode.finish()
if (errorList.isEmpty()) {
if (actionMode != null) {
// when action mode is on the finish() method could be called
// while the item animation is running stopping it
// so we wait the animation is completed and then call finish()
recyclerView.post {
val itemAnimator = recyclerView.itemAnimator
if (itemAnimator == null) {
actionMode?.finish()
} else {
itemAnimator.isRunning {
actionMode?.finish()
}
}
}
}
return
}
selectPosts(errorList)
DialogUtils.showSimpleMessageDialog(
requireContext(),
R.string.generic_error,
requireContext().resources.getQuantityString(
R.plurals.general_posts_error,
errorList.size,
errorList[errorList.size - 1].error?.message,
errorList.size
)
)
}
private fun selectPosts(results: List<PostActionResult>) {
// select posts only if there is an action mode
if (actionMode == null) {
return
}
photoAdapter.selection.clear()
for (result in results) {
val position = photoAdapter.getPosition(result.post as PhotoShelfPost)
photoAdapter.selection.setSelected(position, true)
}
}
override fun onNext(postAction: PostAction, executor: PostActionExecutor, result: PostActionResult) {
when (postAction) {
is PostAction.SaveAsDraft,
is PostAction.Delete,
is PostAction.Publish -> {
if (!result.hasError() && result.post is PhotoShelfPost) {
photoAdapter.remove(result.post)
removeFromCache(result.post)
}
}
else -> {}
}
}
abstract fun removeFromCache(post: PhotoShelfPost)
private fun onEdit(postEditorResult: PostEditorResult) {
val postId = checkNotNull(postEditorResult.extras?.get(PHOTO_POST_ID) as Long)
val item = photoAdapter.findItem(postId) ?: return
launch {
with(postEditorResult) {
postActionExecutor.execute(PostAction.Edit(blogName, item, htmlTitle, tags))
}
}
}
private fun showEditDialog(item: TumblrPhotoPost) {
val data = EditPostEditorData(
item.blogName,
item.caption,
item.caption,
item.tags,
mapOf(
PHOTO_POST_ID to item.postId,
EXTRA_THUMBNAILS_ITEMS to listOf(item.getClosestPhotoByWidth(IMAGE_WIDTH_75)?.url)
)
)
activityResult.launch(data)
}
protected open fun restoreRecyclerViewLayout() {
recyclerViewLayout?.also {
recyclerView.layoutManager?.onRestoreInstanceState(recyclerViewLayout)
}
recyclerViewLayout = null
}
protected open fun saveRecyclerViewLayout(outState: Bundle) {
recyclerView.layoutManager?.onSaveInstanceState()?.also {
outState.putParcelable(KEY_STATE_RECYCLER_VIEW_LAYOUT, it)
}
}
override fun onMenuItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_switch_view -> {
photoAdapterSwitcher.toggleView()
true
}
else -> false
}
}
companion object {
const val KEY_STATE_RECYCLER_VIEW_LAYOUT = "recyclerViewLayout"
const val FRAGMENT_IMAGE_BROWSER = "imageBrowser"
const val ARG_QUICK_LIST_NAVIGATOR_VISIBILITY_DURATION = "quickListNavigatorVisibilityDuration"
}
}
| mit | fd421f0997c3536224cd03c7b370f862 | 37.004283 | 124 | 0.66616 | 5.052092 | false | false | false | false |
SpineEventEngine/core-java | buildSrc/src/main/kotlin/io/spine/internal/markup/MarkdownDocument.kt | 2 | 3510 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.markup
import java.io.File
/**
* A virtual document written in Markdown.
*
* After it's finished, end-users would typically write it to a [real file][writeToFile].
*/
@Suppress("TooManyFunctions")
class MarkdownDocument {
private val builder: StringBuilder = StringBuilder()
/**
* Appends the document with some plain text.
*/
fun text(value: String): MarkdownDocument {
builder.append(value)
return this
}
/**
* Appends the document with a new line symbol.
*/
fun nl(): MarkdownDocument = text(System.lineSeparator())
/**
* Appends the document with a single space.
*/
fun space(): MarkdownDocument = text(" ")
/**
* Appends the document with a number of space symbols.
*/
private fun space(count: Int): MarkdownDocument {
repeat(count) {
space()
}
return this
}
/**
* Appends the document with a space symbol.
*
* A DSL-style shortcut for [space].
*/
fun and(): MarkdownDocument = space()
/**
* Adds some text rendered in bold.
*/
fun bold(text: String): MarkdownDocument = text("**$text**")
/**
* Adds a heading of level 1.
*/
fun h1(text: String): MarkdownDocument = nl().text("# $text")
/**
* Adds a heading of level 2.
*/
fun h2(text: String): MarkdownDocument = nl().text("## $text")
/**
* Adds a link.
*/
fun link(text: String, url: String): MarkdownDocument = text("[$text](${url})")
/**
* Adds a link and uses the passed [url] value as both text and a navigation destination.
*/
fun link(url: String): MarkdownDocument = link(url, url)
/**
* Renders the item of an unordered list, also indenting it by the specified number of spaces.
*/
fun ul(indent: Int): MarkdownDocument = nl().space(indent).text("* ")
/**
* Renders the item of an ordered list.
*/
fun ol(): MarkdownDocument = nl().text("1. ")
/**
* Writes the content of this document to the passed file.
*
* If the file exists, it becomes overwritten.
*/
fun writeToFile(file: File) {
file.writeText(builder.toString())
}
}
| apache-2.0 | 5d5f47ce352f0c497f1b5c6bd14da6fb | 28.495798 | 98 | 0.648148 | 4.301471 | false | false | false | false |
AoEiuV020/PaNovel | app/src/main/java/cc/aoeiuv020/panovel/backup/BackupPresenter.kt | 1 | 8210 | package cc.aoeiuv020.panovel.backup
import android.net.Uri
import android.os.Build
import android.os.Environment
import cc.aoeiuv020.panovel.App
import cc.aoeiuv020.panovel.Presenter
import cc.aoeiuv020.panovel.R
import cc.aoeiuv020.panovel.backup.webdav.BackupWebDavHelper
import cc.aoeiuv020.panovel.report.Reporter
import cc.aoeiuv020.panovel.settings.LocationSettings
import cc.aoeiuv020.panovel.util.notNullOrReport
import cc.aoeiuv020.regex.pick
import org.jetbrains.anko.*
import java.io.File
import java.io.FileNotFoundException
import java.io.FilenameFilter
import java.io.IOException
import java.util.*
/**
* Created by AoEiuV020 on 2018.05.11-12:39:10.
*/
class BackupPresenter : Presenter<BackupActivity>(), AnkoLogger {
companion object {
const val NAME_FOLDER = "Backup"
private const val NAME_TEMPLATE = "PaNovel-Backup-##.zip"
val NAME_FORMAT = NAME_TEMPLATE.replace("##", "%d")
private val NAME_MATCHER = Regex(NAME_TEMPLATE.replace("##", "(\\d+)"))
val NAME_PATTERN = NAME_MATCHER.pattern
val FILENAME_FILTER = FilenameFilter { _, name ->
name.matches(NAME_MATCHER)
}
}
private val ctx = App.ctx
private val backupManager = BackupManager()
private val backupHelperMap: Map<Int, BackupHelper> = mapOf(R.id.rbDefaultWebDav to BackupWebDavHelper())
fun start() {
view?.doAsync({ e ->
val message = "寻找路径失败,"
Reporter.post(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
val baseFile = File(LocationSettings.backupLocation)
.apply { exists() || mkdirs() }
.takeIf { it.canWrite() }
?: ctx.filesDir
.resolve(NAME_FOLDER)
.apply { exists() || mkdirs() }
val indexList: List<Int> = baseFile.list(FILENAME_FILTER)
.map {
val (index) = it.pick(NAME_PATTERN)
index.toInt()
}.sorted()
val max = indexList.lastOrNull() ?: 1
val next = max + 1
val defaultOldName = String.format(Locale.ENGLISH, NAME_FORMAT, max)
val defaultOldUri = baseFile.resolve(defaultOldName).let { Uri.fromFile(it) }.toString()
val defaultNewName = String.format(Locale.ENGLISH, NAME_FORMAT, next)
val defaultNewUri = baseFile.resolve(defaultNewName).let { Uri.fromFile(it) }.toString()
uiThread {
view?.showDefaultPath(defaultOldUri, defaultNewUri)
}
val defaultOtherName = String.format(Locale.ENGLISH, NAME_FORMAT, 1)
val defaultOtherUri = Environment.getExternalStorageDirectory()
.resolve(defaultOtherName)
.let { Uri.fromFile(it) }
.toString()
uiThread {
view?.showOtherPath(defaultOtherUri)
}
backupHelperMap.forEach { entry ->
if (entry.value.ready()) {
view?.showBackupHint(entry.key, entry.value.configPreview())
}
}
}
}
fun import() {
view?.doAsync({ e ->
val message = "导入失败,"
error(message, e)
Reporter.post(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
val options = view.notNullOrReport().getCheckedOption()
val restore: (File) -> Unit = view.notNullOrReport().getSelectedId().let { backupHelperMap[it] }?.let { backupHelper ->
if (backupHelper.ready()) {
debug {
"import: ${backupHelper.type}"
}
backupHelper::restore
} else {
uiThread {
it.startConfig(backupHelper)
}
throw IllegalStateException("先前往配置")
}
} ?: run {
val uri: Uri = view.notNullOrReport().getSelectPath()
debug {
"import: $uri"
}
return@run { tempFile: File ->
try {
ctx.contentResolver.openInputStream(uri)
} catch (e: FileNotFoundException) {
if (e.message?.contains("Permission denied") == true
|| ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()))) {
uiThread {
it.requestPermissions()
}
throw IllegalStateException("没有权限,", e)
} else {
throw IOException("文件不存在或不可读", e)
}
}.notNullOrReport().use { input ->
debug { "开始导入," }
tempFile.outputStream().use { output ->
input.copyTo(output)
output.flush()
}
}
}
}
val result = backupManager.import(options, restore)
uiThread {
it.showImportSuccess(result)
}
}
}
fun export() {
view?.doAsync({ e ->
val message = "导出失败,"
error(message, e)
view?.runOnUiThread {
view?.showError(message, e)
}
}) {
val options = view.notNullOrReport().getCheckedOption()
val backup: (File) -> Unit = view.notNullOrReport().getSelectedId().let { backupHelperMap[it] }?.let { backupHelper ->
if (backupHelper.ready()) {
debug {
"export: ${backupHelper.type}"
}
backupHelper::backup
} else {
uiThread {
it.startConfig(backupHelper)
}
throw IllegalStateException("先前往配置")
}
} ?: run {
val uri: Uri = view.notNullOrReport().getSelectPath()
debug {
"export: $uri"
}
return@run { tempFile: File ->
try {
ctx.contentResolver.openOutputStream(uri)
} catch (e: FileNotFoundException) {
if (e.message?.contains("Permission denied") == true
|| ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()))) {
uiThread {
it.requestPermissions()
}
throw IllegalStateException("没有权限,", e)
} else {
throw IOException("文件不可写", e)
}
} catch (e: SecurityException) {
uiThread {
it.requestPermissions()
}
throw IllegalStateException("没有权限,", e)
}.notNullOrReport().use { output ->
// 这里貌似不会抛没权限的异常,
debug { "开始导出," }
tempFile.inputStream().use { input ->
input.copyTo(output)
output.flush()
}
}
}
}
val result = backupManager.export(options, backup)
uiThread {
it.showExportSuccess(result)
}
}
}
fun getHelper(id: Int): BackupHelper? {
return backupHelperMap[id]
}
} | gpl-3.0 | efa83e7a1e2120c288e2ea1e01ac273c | 37.89372 | 131 | 0.473292 | 5.220493 | false | false | false | false |
michaelgallacher/intellij-community | plugins/java-decompiler/plugin/src/org/jetbrains/java/decompiler/IdeaDecompiler.kt | 4 | 9797 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.java.decompiler
import com.intellij.execution.filters.LineNumbersMapping
import com.intellij.ide.highlighter.JavaFileType
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.intellij.openapi.fileTypes.StdFileTypes
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DefaultProjectFactory
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.newvfs.RefreshQueue
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.psi.PsiJavaModule
import com.intellij.psi.PsiPackage
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.psi.compiled.ClassFileDecompilers
import com.intellij.psi.impl.compiled.ClsFileImpl
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.java.decompiler.main.decompiler.BaseDecompiler
import org.jetbrains.java.decompiler.main.extern.IBytecodeProvider
import org.jetbrains.java.decompiler.main.extern.IFernflowerPreferences
import org.jetbrains.java.decompiler.main.extern.IResultSaver
import java.io.File
import java.util.*
import java.util.concurrent.Callable
import java.util.concurrent.Future
import java.util.jar.Manifest
class IdeaDecompiler : ClassFileDecompilers.Light() {
companion object {
const val BANNER = "//\n// Source code recreated from a .class file by IntelliJ IDEA\n// (powered by Fernflower decompiler)\n//\n\n"
private val LEGAL_NOTICE_KEY = "decompiler.legal.notice.accepted"
private fun getOptions(): Map<String, Any> {
val project = DefaultProjectFactory.getInstance().defaultProject
val options = CodeStyleSettingsManager.getInstance(project).currentSettings.getIndentOptions(JavaFileType.INSTANCE)
val indent = StringUtil.repeat(" ", options.INDENT_SIZE)
return mapOf(
IFernflowerPreferences.HIDE_DEFAULT_CONSTRUCTOR to "0",
IFernflowerPreferences.DECOMPILE_GENERIC_SIGNATURES to "1",
IFernflowerPreferences.REMOVE_SYNTHETIC to "1",
IFernflowerPreferences.REMOVE_BRIDGE to "1",
IFernflowerPreferences.LITERALS_AS_IS to "1",
IFernflowerPreferences.NEW_LINE_SEPARATOR to "1",
IFernflowerPreferences.BANNER to BANNER,
IFernflowerPreferences.MAX_PROCESSING_METHOD to 60,
IFernflowerPreferences.INDENT_STRING to indent,
IFernflowerPreferences.UNIT_TEST_MODE to if (ApplicationManager.getApplication().isUnitTestMode) "1" else "0")
}
}
private val myLogger = lazy { IdeaLogger() }
private val myOptions = lazy { getOptions() }
private val myProgress = ContainerUtil.newConcurrentMap<VirtualFile, ProgressIndicator>()
private val myFutures = ContainerUtil.newConcurrentMap<VirtualFile, Future<CharSequence>>()
@Volatile private var myLegalNoticeAccepted = false
init {
myLegalNoticeAccepted = ApplicationManager.getApplication().isUnitTestMode || PropertiesComponent.getInstance().isValueSet(LEGAL_NOTICE_KEY)
if (!myLegalNoticeAccepted) {
intercept()
}
}
private fun intercept() {
val app = ApplicationManager.getApplication()
val connection = app.messageBus.connect(app)
connection.subscribe(FileEditorManagerListener.Before.FILE_EDITOR_MANAGER, object : FileEditorManagerListener.Before.Adapter() {
override fun beforeFileOpened(source: FileEditorManager, file: VirtualFile) {
if (!myLegalNoticeAccepted && file.fileType === StdFileTypes.CLASS && ClassFileDecompilers.find(file) === this@IdeaDecompiler) {
myFutures.put(file, app.executeOnPooledThread(Callable<CharSequence> { decompile(file) }))
val dialog = LegalNoticeDialog(source.project, file)
dialog.show()
when (dialog.exitCode) {
DialogWrapper.OK_EXIT_CODE -> {
PropertiesComponent.getInstance().setValue(LEGAL_NOTICE_KEY, true)
myLegalNoticeAccepted = true
app.invokeLater({
RefreshQueue.getInstance().processSingleEvent(
VFileContentChangeEvent(this@IdeaDecompiler, file, file.modificationStamp, -1, false))
})
connection.disconnect()
}
LegalNoticeDialog.DECLINE_EXIT_CODE -> {
myFutures.remove(file)?.cancel(true)
PluginManagerCore.disablePlugin("org.jetbrains.java.decompiler")
ApplicationManagerEx.getApplicationEx().restart(true)
}
LegalNoticeDialog.POSTPONE_EXIT_CODE -> {
myFutures.remove(file)?.cancel(true)
}
}
}
}
})
}
override fun accepts(file: VirtualFile): Boolean = true
override fun getText(file: VirtualFile): CharSequence =
if (myLegalNoticeAccepted) myFutures.remove(file)?.get() ?: decompile(file)
else ClsFileImpl.decompile(file)
private fun decompile(file: VirtualFile): CharSequence {
if (PsiPackage.PACKAGE_INFO_CLS_FILE == file.name || PsiJavaModule.MODULE_INFO_CLS_FILE == file.name) {
return ClsFileImpl.decompile(file)
}
val indicator = ProgressManager.getInstance().progressIndicator
if (indicator != null) myProgress.put(file, indicator)
try {
val mask = "${file.nameWithoutExtension}$"
val files = mapOf(file.path to file) +
file.parent.children.filter { it.nameWithoutExtension.startsWith(mask) && it.fileType === StdFileTypes.CLASS }.map { it.path to it }
val options = HashMap(myOptions.value)
if (Registry.`is`("decompiler.use.line.mapping")) {
options.put(IFernflowerPreferences.BYTECODE_SOURCE_MAPPING, "1")
}
if (Registry.`is`("decompiler.dump.original.lines")) {
options.put(IFernflowerPreferences.DUMP_ORIGINAL_LINES, "1")
}
val provider = MyBytecodeProvider(files)
val saver = MyResultSaver()
val decompiler = BaseDecompiler(provider, saver, options, myLogger.value)
files.keys.forEach { path -> decompiler.addSpace(File(path), true) }
decompiler.decompileContext()
val mapping = saver.myMapping
if (mapping != null) {
file.putUserData(LineNumbersMapping.LINE_NUMBERS_MAPPING_KEY, ExactMatchLineNumbersMapping(mapping))
}
return saver.myResult
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Exception) {
if (ApplicationManager.getApplication().isUnitTestMode) {
throw AssertionError(file.url, e)
}
else {
throw ClassFileDecompilers.Light.CannotDecompileException(e)
}
}
finally {
myProgress.remove(file)
}
}
@TestOnly
fun getProgress(file: VirtualFile): ProgressIndicator? = myProgress[file]
private class MyBytecodeProvider(private val files: Map<String, VirtualFile>) : IBytecodeProvider {
override fun getBytecode(externalPath: String, internalPath: String?): ByteArray {
val path = FileUtil.toSystemIndependentName(externalPath)
val file = files[path] ?: throw AssertionError(path + " not in " + files.keys)
return file.contentsToByteArray(false)
}
}
private class MyResultSaver : IResultSaver {
var myResult = ""
var myMapping: IntArray? = null
override fun saveClassFile(path: String, qualifiedName: String, entryName: String, content: String, mapping: IntArray?) {
if (myResult.isEmpty()) {
myResult = content
myMapping = mapping
}
}
override fun saveFolder(path: String) { }
override fun copyFile(source: String, path: String, entryName: String) { }
override fun createArchive(path: String, archiveName: String, manifest: Manifest) { }
override fun saveDirEntry(path: String, archiveName: String, entryName: String) { }
override fun copyEntry(source: String, path: String, archiveName: String, entry: String) { }
override fun saveClassEntry(path: String, archiveName: String, qualifiedName: String, entryName: String, content: String) { }
override fun closeArchive(path: String, archiveName: String) { }
}
private class ExactMatchLineNumbersMapping(private val mapping: IntArray) : LineNumbersMapping {
override fun bytecodeToSource(line: Int): Int {
for (i in mapping.indices step 2) {
if (mapping[i] == line) {
return mapping[i + 1]
}
}
return -1
}
override fun sourceToBytecode(line: Int): Int {
for (i in mapping.indices step 2) {
if (mapping[i + 1] == line) {
return mapping[i]
}
}
return -1
}
}
} | apache-2.0 | 7665bef1a2e2fd4c53e7f971fcce6310 | 39.487603 | 144 | 0.717771 | 4.580178 | false | false | false | false |
mockk/mockk | modules/mockk/src/commonMain/kotlin/io/mockk/impl/stub/MockKStub.kt | 1 | 10399 | package io.mockk.impl.stub
import io.mockk.*
import io.mockk.impl.InternalPlatform
import io.mockk.impl.InternalPlatform.customComputeIfAbsent
import io.mockk.impl.log.Logger
import kotlin.reflect.KClass
open class MockKStub(
override val type: KClass<*>,
override val name: String,
val relaxed: Boolean = false,
val relaxUnitFun: Boolean = false,
val gatewayAccess: StubGatewayAccess,
val recordPrivateCalls: Boolean,
val mockType: MockType
) : Stub {
val log = gatewayAccess.safeToString(Logger<MockKStub>())
private val answers = InternalPlatform.synchronizedMutableList<InvocationAnswer>()
private val childs = InternalPlatform.synchronizedMutableMap<InvocationMatcher, Any>()
private val recordedCalls = InternalPlatform.synchronizedMutableList<Invocation>()
private val recordedCallsByMethod =
InternalPlatform.synchronizedMutableMap<MethodDescription, MutableList<Invocation>>()
private val exclusions = InternalPlatform.synchronizedMutableList<InvocationMatcher>()
private val verifiedCalls = InternalPlatform.synchronizedMutableList<Invocation>()
lateinit var hashCodeStr: String
var disposeRoutine: () -> Unit = {}
override fun addAnswer(matcher: InvocationMatcher, answer: Answer<*>) {
val invocationAnswer = InvocationAnswer(matcher, answer, 0)
answers.add(invocationAnswer)
}
override fun answer(invocation: Invocation): Any? {
val invocationAndMatcher = InternalPlatform.synchronized(answers) {
answers
.findLast { it.matcher.match(invocation) }
?.also { it.usageCount++ }
} ?: return defaultAnswer(invocation)
return with(invocationAndMatcher) {
matcher.captureAnswer(invocation)
val call = Call(
invocation.method.returnType,
invocation,
matcher,
invocation.fieldValueProvider
)
answer.answer(call)
}
}
protected inline fun stdObjectFunctions(
self: Any,
method: MethodDescription,
args: List<Any?>,
otherwise: () -> Any?
): Any? {
if (method.isToString()) {
return toStr()
} else if (method.isHashCode()) {
return InternalPlatformDsl.identityHashCode(self)
} else if (method.isEquals()) {
return self === args[0]
} else {
return otherwise()
}
}
override fun stdObjectAnswer(invocation: Invocation): Any? {
return stdObjectFunctions(invocation.self, invocation.method, invocation.args) {
throw MockKException("No other calls allowed in stdObjectAnswer than equals/hashCode/toString")
}
}
protected open fun defaultAnswer(invocation: Invocation): Any? {
return stdObjectFunctions(invocation.self, invocation.method, invocation.args) {
if (shouldRelax(invocation)) {
if (invocation.method.returnsUnit) return Unit
return gatewayAccess.anyValueGenerator().anyValue(
invocation.method.returnType,
invocation.method.returnTypeNullable
) {
childMockK(invocation.allEqMatcher(), invocation.method.returnType)
}
} else {
throw MockKException("no answer found for: ${gatewayAccess.safeToString.exec { invocation.toString() }}")
}
}
}
private fun shouldRelax(invocation: Invocation) = when {
relaxed -> true
relaxUnitFun &&
invocation.method.returnsUnit -> true
else -> false
}
override fun recordCall(invocation: Invocation) {
val record = when {
checkExcluded(invocation) -> {
log.debug { "Call excluded: $invocation" }
false
}
recordPrivateCalls -> true
else -> !invocation.method.privateCall
}
if (record) {
recordedCalls.add(invocation)
InternalPlatform.synchronized(recordedCallsByMethod) {
recordedCallsByMethod.getOrPut(invocation.method) { mutableListOf() }
.add(invocation)
}
gatewayAccess.stubRepository.notifyCallRecorded(this)
}
}
private fun checkExcluded(invocation: Invocation) = InternalPlatform.synchronized(exclusions) {
exclusions.any { it.match(invocation) }
}
override fun allRecordedCalls(): List<Invocation> {
InternalPlatform.synchronized(recordedCalls) {
return recordedCalls.toList()
}
}
override fun allRecordedCalls(method: MethodDescription): List<Invocation> {
InternalPlatform.synchronized(recordedCallsByMethod) {
return recordedCallsByMethod[method]?.toList() ?: listOf()
}
}
override fun excludeRecordedCalls(
params: MockKGateway.ExclusionParameters,
matcher: InvocationMatcher
) {
exclusions.add(matcher)
if (params.current) {
InternalPlatform.synchronized(recordedCalls) {
val callsToExclude = recordedCalls
.filter(matcher::match)
if (callsToExclude.isNotEmpty()) {
log.debug {
"Calls excluded: " + callsToExclude.joinToString(", ")
}
}
callsToExclude
.forEach { recordedCalls.remove(it) }
InternalPlatform.synchronized(recordedCallsByMethod) {
recordedCallsByMethod[matcher.method]?.apply {
filter(matcher::match)
.forEach { remove(it) }
}
}
InternalPlatform.synchronized(verifiedCalls) {
verifiedCalls
.filter(matcher::match)
.forEach { verifiedCalls.remove(it) }
}
}
}
}
override fun markCallVerified(invocation: Invocation) {
verifiedCalls.add(invocation)
}
override fun verifiedCalls(): List<Invocation> {
InternalPlatform.synchronized(verifiedCalls) {
return verifiedCalls.toList()
}
}
override fun matcherUsages(): Map<InvocationMatcher, Int> =
InternalPlatform.synchronized(answers) {
answers.associate { it.matcher to it.usageCount }
}
override fun toStr() = "${type.simpleName}($name)"
override fun childMockK(matcher: InvocationMatcher, childType: KClass<*>): Any {
return InternalPlatform.synchronized(childs) {
gatewayAccess.safeToString.exec {
childs.customComputeIfAbsent(matcher) {
gatewayAccess.mockFactory!!.mockk(
childType,
childName(this.name),
moreInterfaces = arrayOf(),
relaxed = relaxed,
relaxUnitFun = relaxUnitFun
)
}
}
}
}
private fun childName(name: String): String {
val result = childOfRegex.matchEntire(name)
return if (result != null) {
val group = result.groupValues[2]
val childN = if (group.isEmpty()) 1 else group.toInt()
"child^" + (childN + 1) + " of " + result.groupValues[3]
} else {
"child of " + name
}
}
override fun handleInvocation(
self: Any,
method: MethodDescription,
originalCall: () -> Any?,
args: Array<out Any?>,
fieldValueProvider: BackingFieldValueProvider
): Any? {
val originalPlusToString = {
if (method.isToString()) {
toStr()
} else {
originalCall()
}
}
fun List<StackElement>.cutMockKCallProxyCall(): List<StackElement> {
fun search(cls: String, mtd: String): Int? {
return indexOfFirst {
it.className == cls && it.methodName == mtd
}.let { if (it == -1) null else it }
}
val idx = search("io.mockk.proxy.MockKCallProxy", "call")
?: search("io.mockk.proxy.MockKProxyInterceptor", "intercept")
?: search("io.mockk.proxy.MockKProxyInterceptor", "interceptNoSuper")
?: return this
return this.drop(idx + 1)
}
val stackTraceHolder = InternalPlatform.captureStackTrace()
val invocation = Invocation(
self,
this,
method,
args.toList(),
InternalPlatform.time(),
{
stackTraceHolder()
.cutMockKCallProxyCall()
},
originalPlusToString,
fieldValueProvider
)
return gatewayAccess.callRecorder().call(invocation)
}
override fun clear(options: MockKGateway.ClearOptions) {
if (options.answers) {
this.answers.clear()
}
if (options.recordedCalls) {
this.recordedCalls.clear()
this.recordedCallsByMethod.clear()
}
if (options.childMocks) {
this.childs.clear()
}
if (options.verificationMarks) {
this.verifiedCalls.clear()
}
if (options.exclusionRules) {
this.exclusions.clear()
}
}
companion object {
val childOfRegex = Regex("child(\\^(\\d+))? of (.+)")
}
private data class InvocationAnswer(val matcher: InvocationMatcher, val answer: Answer<*>, var usageCount: Int)
protected fun Invocation.allEqMatcher() =
InvocationMatcher(
self,
method,
args.map {
if (it == null)
NullCheckMatcher<Any>()
else
EqMatcher(it)
}, false
)
override fun dispose() {
clear(
MockKGateway.ClearOptions(
true,
true,
true,
true,
true
)
)
disposeRoutine.invoke()
}
}
| apache-2.0 | 12e42d175007cad7c73b20ff7995d721 | 31.195046 | 121 | 0.563612 | 5.25999 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/ui/UIScrollable.kt | 1 | 11629 | package com.soywiz.korge.ui
import com.soywiz.kds.iterators.*
import com.soywiz.klock.*
import com.soywiz.kmem.*
import com.soywiz.korge.annotations.*
import com.soywiz.korge.component.*
import com.soywiz.korge.input.*
import com.soywiz.korge.internal.*
import com.soywiz.korge.render.*
import com.soywiz.korge.view.*
import com.soywiz.korim.bitmap.*
import com.soywiz.korim.color.*
import com.soywiz.korio.async.*
import com.soywiz.korma.interpolation.*
import kotlin.math.*
@KorgeExperimental
inline fun Container.uiScrollable(
width: Double = 256.0,
height: Double = 256.0,
config: UIScrollable.() -> Unit = {},
block: @ViewDslMarker Container.(UIScrollable) -> Unit = {}
): UIScrollable = UIScrollable(width, height)
.addTo(this).apply(config).also { block(it.container, it) }
// @TODO: Horizontal. And to be able to toggle vertical/horizontal
@KorgeExperimental
open class UIScrollable(width: Double, height: Double) : UIView(width, height) {
class MyScrollbarInfo(val scrollable: UIScrollable, val direction: UIDirection, val view: SolidRect) {
val isHorizontal get() = direction.isHorizontal
val isVertical get() = direction.isVertical
val container get() = scrollable.container
var scrollBarPos: Double by if (isHorizontal) view::x else view::y
var viewPos: Double by if (isHorizontal) view::x else view::y
//get() = if (isHorizontal) view.x else view.y
//set(value) = if (isHorizontal) view.x = value else view.y = value
var viewScaledSize: Double by if (isHorizontal) view::scaledWidth else view::scaledHeight
//get() = if (isHorizontal) view.scaledWidth else view.scaledHeight
//set(value: Double) = if (isHorizontal) view.scaledWidth = value else view.scaledHeight = value
val scrollRatio: Double get() = size / totalSize
val scrollbarSize: Double get() = size * scrollRatio
val scaledSize get() = if (isHorizontal) view.scaledWidth else view.scaledHeight
var containerPos: Double by if (isHorizontal) container::x else container::y
//get() = if (isHorizontal) container.x else container.y
//set(value) { if (isHorizontal) container.x = value else container.y = value }
val overflowPixelsBegin get() = if (isHorizontal) scrollable.overflowPixelsLeft else scrollable.overflowPixelsTop
val overflowPixelsEnd get() = if (isHorizontal) scrollable.overflowPixelsRight else scrollable.overflowPixelsBottom
val onScrollPosChange = Signal<UIScrollable>()
val size get() = if (isHorizontal) scrollable.width else scrollable.height
val shouldBeVisible get() = (size < totalSize)
val totalSize get() = (container.getLocalBoundsOptimized().let { if (isHorizontal) max(scrollable.width, it.right) else max(scrollable.height, it.bottom) })
//.also { println("totalSize=$it") }
val scrollArea get() = totalSize - size
var position: Double
get() = -containerPos
set(value) {
val oldValue = -containerPos
val newValue = -(value.clamp(-overflowPixelsBegin, scrollArea + overflowPixelsEnd))
if (newValue != oldValue) {
containerPos = newValue
onScrollPosChange(scrollable)
}
}
@KorgeInternal fun scrollBarPositionToScrollTopLeft(pos: Double): Double {
val d = size - scaledSize
if (d == 0.0) return 0.0
return (pos / d) * scrollArea
}
@KorgeInternal fun scrollTopLeftToScrollBarPosition(pos: Double): Double {
val d = scrollArea
if (d == 0.0) return 0.0
return (pos / d) * (size - scaledSize)
}
var positionRatio: Double
get() = position / scrollArea
set(value) {
position = scrollArea * value
}
var pixelSpeed = 0.0
var startScrollPos = 0.0
}
//private val background = solidRect(width, height, Colors["#161a1d"])
private val contentContainer = fixedSizeContainer(width, height, clip = true)
val container = contentContainer.container()
//private val verticalScrollBar = solidRect(10.0, height / 2, Colors["#57577a"])
//private val horizontalScrollBar = solidRect(width / 2, 10.0, Colors["#57577a"])
private val vertical = MyScrollbarInfo(this, UIDirection.VERTICAL, solidRect(10.0, height / 2, Colors["#57577a"]))
private val horizontal = MyScrollbarInfo(this, UIDirection.HORIZONTAL, solidRect(width / 2, 10.0, Colors["#57577a"]))
private val infos = arrayOf(horizontal, vertical)
private val totalHeight: Double get() = vertical.totalSize
private val totalWidth: Double get() = horizontal.totalSize
// HORIZONTAL SCROLLBAR
val onScrollLeftChange get() = horizontal.onScrollPosChange
val scrollWidth: Double get() = horizontal.totalSize
var scrollLeft: Double by horizontal::position
var scrollLeftRatio: Double by horizontal::positionRatio
// VERTICAL SCROLLBAR
val onScrollTopChange get() = vertical.onScrollPosChange
val scrollHeight: Double get() = vertical.totalSize
var scrollTop: Double by vertical::position
var scrollTopRatio: Double by vertical::positionRatio
var frictionRate = 0.75
var overflowRate = 0.1
val overflowPixelsVertical get() = height * overflowRate
val overflowPixelsHorizontal get() = width * overflowRate
val overflowPixelsTop get() = overflowPixelsVertical
val overflowPixelsBottom get() = overflowPixelsVertical
val overflowPixelsLeft get() = overflowPixelsHorizontal
val overflowPixelsRight get() = overflowPixelsHorizontal
var timeScrollBar = 0.seconds
var autohideScrollBar = false
var scrollBarAlpha = 0.75
var backgroundColor: RGBA = Colors["#161a1d"]
var mobileBehaviour = true
private fun showScrollBar() {
horizontal.view.alpha = scrollBarAlpha
vertical.view.alpha = scrollBarAlpha
timeScrollBar = 0.seconds
}
override fun renderInternal(ctx: RenderContext) {
ctx.useBatcher { batch ->
batch.drawQuad(ctx.getTex(Bitmaps.white), 0f, 0f, width.toFloat(), height.toFloat(), globalMatrix, colorMul = backgroundColor * renderColorMul)
}
super.renderInternal(ctx)
}
init {
container.y = 0.0
showScrollBar()
//onScrollTopChange.add { println(it.scrollRatio) }
onSizeChanged()
mouse {
scroll {
showScrollBar()
val info = when {
!horizontal.shouldBeVisible -> vertical
!vertical.shouldBeVisible -> horizontal
it.isAltDown -> horizontal
else -> vertical
}
//val infoAlt = if (it.isAltDown) vertical else horizontal
info.position = (info.position + it.scrollDeltaY * (info.size / 16.0))
//infoAlt.position = (info.position + it.scrollDeltaX * (info.size / 16.0))
if (it.scrollDeltaY != 0.0) info.pixelSpeed = 0.0
//if (it.scrollDeltaX != 0.0) infoAlt.pixelSpeed = 0.0
it.stopPropagation()
}
}
var dragging = false
for (info in infos) {
info.view.decorateOutOverAlphaSimple { if (it) 1.0 else scrollBarAlpha }
}
for (info in infos) {
var startScrollBarPos = 0.0
info.view.onMouseDrag {
if (!info.shouldBeVisible) return@onMouseDrag
val dxy = if (info.isHorizontal) it.localDX else it.localDY
if (it.start) {
startScrollBarPos = info.scrollBarPos
}
info.position =
info.scrollBarPositionToScrollTopLeft(startScrollBarPos + dxy).clamp(0.0, info.scrollArea)
}
}
contentContainer.onMouseDrag {
if (it.start) {
showScrollBar()
dragging = true
for (info in infos) {
if (!info.shouldBeVisible || !mobileBehaviour) continue
info.startScrollPos = info.position
info.pixelSpeed = 0.0
}
}
for (info in infos) {
if (!info.shouldBeVisible || !mobileBehaviour) continue
if (info.pixelSpeed.absoluteValue < 0.0001) {
info.pixelSpeed = 0.0
}
}
for (info in infos) {
if (!info.shouldBeVisible || !mobileBehaviour) continue
val localDXY = if (info.isHorizontal) it.localDX else it.localDY
info.position = info.startScrollPos - localDXY
if (it.end) {
dragging = false
info.pixelSpeed = 300.0
val elapsedTime = it.elapsed
info.pixelSpeed = -(localDXY * 1.1) / elapsedTime.seconds
}
}
}
addUpdater {
if (it.milliseconds == 0.0) return@addUpdater
//println("horizontal.scrollbarSize=${horizontal.scrollBarPos},${horizontal.scrollbarSize}(${horizontal.view.visible},${horizontal.view.alpha}), vertical.scrollbarSize=${vertical.scrollbarSize}")
infos.fastForEach { info ->
info.view.visible = info.shouldBeVisible
info.viewScaledSize = max(info.scrollbarSize, 10.0)
info.viewPos = info.scrollTopLeftToScrollBarPosition(info.position)
//verticalScrollBar.y = scrollTop
if (info.pixelSpeed.absoluteValue <= 1.0) {
info.pixelSpeed = 0.0
}
if (info.pixelSpeed != 0.0) {
val oldScrollPos = info.position
info.position += info.pixelSpeed * it.seconds
if (oldScrollPos == info.position) {
info.pixelSpeed = 0.0
}
} else {
//scrollTop = round(scrollTop)
if (!dragging && (info.position < 0.0 || info.position > info.scrollArea)) {
//println("scrollRatio=$scrollRatio, scrollTop=$scrollTop")
val destScrollPos = if (info.position < 0.0) 0.0 else info.scrollArea
if ((destScrollPos - info.position).absoluteValue < 0.1) {
info.position = destScrollPos
} else {
info.position = (0.5 * (it.seconds * 10.0)).interpolate(info.position, destScrollPos)
}
}
if (!dragging && autohideScrollBar) {
if (timeScrollBar >= 1.seconds) {
info.view.alpha *= 0.9
} else {
timeScrollBar += it
}
}
}
}
}
addFixedUpdater(0.1.seconds) {
//pixelSpeed *= 0.95
//pixelSpeed *= 0.75
infos.fastForEach { it.pixelSpeed *= frictionRate }
}
}
override fun onSizeChanged() {
contentContainer.size(this.width, this.height)
vertical.view.position(width - 10.0, 0.0)
horizontal.view.position(0.0, height - 10.0)
//background.size(width, height)
super.onSizeChanged()
}
}
| apache-2.0 | f2990c851236cb7c5bdfb7c2d1197d0f | 41.753676 | 207 | 0.590592 | 4.567557 | false | false | false | false |
Orchextra/orchextra-android-sdk | indoorpositioning/src/main/java/com/gigigo/orchextra/indoorpositioning/data/models/DbOxBeacon.kt | 1 | 1509 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gigigo.orchextra.indoorpositioning.data.models
import com.gigigo.orchextra.core.data.datasources.db.caching.strategy.ttl.TtlCachingObject
import com.j256.ormlite.field.DatabaseField
import com.j256.ormlite.table.DatabaseTable
@DatabaseTable(tableName = "trigger")
class DbOxBeacon : TtlCachingObject {
@DatabaseField(generatedId = true, columnName = "id")
var id: Int = 0
@DatabaseField(columnName = "value")
var value: String = ""
@DatabaseField
var type: Int = -1
@DatabaseField
var uuid: String = ""
@DatabaseField
var major: Int = -1
@DatabaseField
var minor: Int = -1
@DatabaseField
var namespaceId: String = ""
@DatabaseField
var instanceId: String = ""
@DatabaseField
var lastDetection: Long = 0
@DatabaseField
var dbPersistedTime: Long = 0
override fun getPersistedTime(): Long = dbPersistedTime
} | apache-2.0 | 3875b7213fdbbde3ed449de6821496e6 | 24.59322 | 90 | 0.734924 | 3.909326 | false | false | false | false |
pr0ves/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/util/data/ProfileData.kt | 2 | 1651 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.util.data
import ink.abb.pogo.api.PoGoApi
import java.util.concurrent.atomic.AtomicInteger
data class ProfileData(
var name: String? = null,
var level: Int? = null,
var exp: Long? = null,
var expToNextLevel: Long? = null,
var stardust: Int? = null,
var team: String? = null,
var pokebankLimit: Int? = null,
var pokebankUsage: Int? = null,
var backpackLimit: Int? = null,
var backpackUsage: Int? = null,
var coin: Int? = null
) {
fun buildFromApi(api: PoGoApi): ProfileData {
this.name = api.playerData.username
this.level = api.inventory.playerStats.level
this.exp = api.inventory.playerStats.experience
this.expToNextLevel = api.inventory.playerStats.nextLevelXp
this.stardust = api.inventory.currencies.getOrPut("STARDUST", { AtomicInteger(0) }).get()
this.team = api.playerData.team.name
this.pokebankLimit = api.playerData.maxPokemonStorage
this.pokebankUsage = api.inventory.pokemon.size
this.backpackLimit = api.playerData.maxItemStorage
this.backpackUsage = api.inventory.size
this.coin = api.inventory.currencies.getOrPut("POKECOIN", { AtomicInteger(0) }).get()
return this
}
}
| gpl-3.0 | 872a8729f3a94e9310f1cadf230f6df0 | 36.522727 | 97 | 0.67656 | 3.921615 | false | false | false | false |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/view/CardFormViewTest.kt | 1 | 14203 | package com.stripe.android.view
import android.content.Context
import android.view.View
import android.widget.LinearLayout
import androidx.core.view.isVisible
import androidx.test.core.app.ApplicationProvider
import com.google.android.material.textfield.TextInputLayout
import com.google.common.truth.Truth.assertThat
import com.stripe.android.ApiKeyFixtures
import com.stripe.android.CardNumberFixtures
import com.stripe.android.CardNumberFixtures.VISA_WITH_SPACES
import com.stripe.android.PaymentConfiguration
import com.stripe.android.R
import com.stripe.android.core.model.CountryCode
import com.stripe.android.databinding.StripeCardFormViewBinding
import com.stripe.android.model.Address
import com.stripe.android.model.CardBrand
import com.stripe.android.model.CardParams
import com.stripe.android.utils.TestUtils.idleLooper
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import java.util.Locale
@RunWith(RobolectricTestRunner::class)
class CardFormViewTest {
private val context: Context = ApplicationProvider.getApplicationContext()
private val activityScenarioFactory = ActivityScenarioFactory(context)
private val standardCardFormView: CardFormView by lazy {
activityScenarioFactory.createView {
CardFormView(it)
}
}
private val borderLessCardFormView: CardFormView by lazy {
activityScenarioFactory.createView {
CardFormView(
context = it,
attrs = Robolectric.buildAttributeSet()
.addAttribute(R.attr.cardFormStyle, "1")
.build()
)
}
}
private var standardBinding: StripeCardFormViewBinding? = null
private var borderlessBinding: StripeCardFormViewBinding? = null
@Before
fun setup() {
PaymentConfiguration.init(context, ApiKeyFixtures.FAKE_PUBLISHABLE_KEY)
standardBinding = StripeCardFormViewBinding.bind(standardCardFormView)
borderlessBinding = StripeCardFormViewBinding.bind(borderLessCardFormView)
}
@After
fun teardown() {
setLocale(Locale.US)
}
@Test
fun `when locale is US then country should be US and postal config should be US`() {
setLocale(Locale.US)
val binding = StripeCardFormViewBinding.bind(
activityScenarioFactory.createView {
CardFormView(it)
}
)
assertThat(
binding.countryLayout.countryAutocomplete.text.toString()
).isEqualTo("United States")
assertThat(
binding.postalCode.config
).isEqualTo(PostalCodeEditText.Config.US)
}
@Test
fun `when locale is not US then country should not be US and postal config should be Global`() {
setLocale(Locale.CANADA)
val binding = StripeCardFormViewBinding.bind(
activityScenarioFactory.createView {
CardFormView(it)
}
)
assertThat(
binding.countryLayout.countryAutocomplete.text.toString()
).isEqualTo("Canada")
assertThat(
binding.postalCode.config
).isEqualTo(PostalCodeEditText.Config.Global)
}
@Test
fun `when all fields are valid then cardParams should return correctly and errors is empty`() {
setValuesToStandardUI(VISA_WITH_SPACES, VALID_MONTH, VALID_YEAR, VALID_CVC, VALID_US_ZIP)
assertThat(standardCardFormView.cardParams)
.isEqualTo(
CardParams(
brand = CardBrand.Visa,
loggingTokens = setOf(CardFormView.CARD_FORM_VIEW),
number = CardNumberFixtures.VISA_NO_SPACES,
expMonth = 12,
expYear = 2050,
cvc = VALID_CVC,
address = Address.Builder()
.setCountryCode(CountryCode.US)
.setPostalCode(VALID_US_ZIP)
.build()
)
)
idleLooper()
standardBinding!!.let {
assertThat(it.errors.text).isEqualTo("")
assertThat(it.errors.isVisible).isFalse()
}
}
@Test
fun `when postal field is invalid then cardParams should return null and errors is not empty`() {
setValuesToStandardUI(VISA_WITH_SPACES, VALID_MONTH, VALID_YEAR, VALID_CVC, INVALID_US_ZIP)
assertThat(standardCardFormView.cardParams).isNull()
idleLooper()
standardBinding!!.let {
assertThat(it.errors.text).isEqualTo(context.getString(R.string.address_zip_invalid))
assertThat(it.errors.isVisible).isTrue()
}
}
@Test
fun `when card number is invalid then cardParams should return null and errors is not empty`() {
setValuesToStandardUI(INVALID_VISA, VALID_MONTH, VALID_YEAR, VALID_CVC, VALID_US_ZIP)
assertThat(standardCardFormView.cardParams).isNull()
idleLooper()
standardBinding!!.let {
assertThat(it.errors.text).isEqualTo(context.getString(R.string.invalid_card_number))
assertThat(it.errors.isVisible).isTrue()
}
}
@Test
fun `when expiration is invalid then cardParams should return null and errors is not empty`() {
setValuesToStandardUI(VISA_WITH_SPACES, VALID_MONTH, INVALID_YEAR, VALID_CVC, VALID_US_ZIP)
assertThat(standardCardFormView.cardParams).isNull()
idleLooper()
standardBinding!!.let {
assertThat(it.errors.text).isEqualTo(context.getString(R.string.invalid_expiry_year))
assertThat(it.errors.isVisible).isTrue()
}
}
@Test
fun `when cvc is invalid then cardParams should return null and errors is not empty`() {
setValuesToStandardUI(VISA_WITH_SPACES, VALID_MONTH, VALID_YEAR, INVALID_CVC, VALID_US_ZIP)
assertThat(standardCardFormView.cardParams).isNull()
idleLooper()
standardBinding!!.let {
assertThat(it.errors.text).isEqualTo(context.getString(R.string.invalid_cvc))
assertThat(it.errors.isVisible).isTrue()
}
}
@Test
fun `when cvc becomes valid then postal should get focus`() {
setValuesToStandardUI(VISA_WITH_SPACES, VALID_MONTH, VALID_YEAR, INVALID_CVC)
assertThat(standardBinding!!.postalCode.hasFocus()).isFalse()
standardBinding!!.cardMultilineWidget.cvcEditText.append("3")
assertThat(standardBinding!!.postalCode.hasFocus()).isTrue()
}
@Test
fun verifyStandardStyle() {
idleLooper()
standardBinding!!.let {
// 2 additional horizontal dividers added to card_multiline_widget.xml, now it has 4 child views
assertThat(it.cardMultilineWidget.childCount).isEqualTo(4)
// tl_card_number
assertThat(it.cardMultilineWidget.getChildAt(0)).isInstanceOf(
CardNumberTextInputLayout::class.java
)
// horizontal divider
assertThat(it.cardMultilineWidget.getChildAt(1)).isInstanceOf(
View::class.java
)
// second_row_layout
assertThat(it.cardMultilineWidget.getChildAt(2)).isInstanceOf(
LinearLayout::class.java
)
// horizontal divider
assertThat(it.cardMultilineWidget.getChildAt(3)).isInstanceOf(
View::class.java
)
// 1 vertical divider added between exp and cvc, now secondRowLayout has 4 child views
assertThat(it.cardMultilineWidget.secondRowLayout.childCount).isEqualTo(4)
// tl_expiry
assertThat(it.cardMultilineWidget.secondRowLayout.getChildAt(0)).isInstanceOf(
TextInputLayout::class.java
)
// vertical divider
assertThat(it.cardMultilineWidget.secondRowLayout.getChildAt(1)).isInstanceOf(
View::class.java
)
// tl_cvc
assertThat(it.cardMultilineWidget.secondRowLayout.getChildAt(2)).isInstanceOf(
TextInputLayout::class.java
)
// tl_postal_code(invisible)
assertThat(it.cardMultilineWidget.secondRowLayout.getChildAt(3)).isInstanceOf(
TextInputLayout::class.java
)
// divider with width=match_parent is visible
assertThat(it.countryPostalDivider.isVisible).isTrue()
}
}
@Test
fun verifyBorderlessStyle() {
idleLooper()
borderlessBinding?.let {
// no child views added to card_multiline_widget.xml, it still has 2 child views
assertThat(it.cardMultilineWidget.childCount).isEqualTo(2)
// tl_card_number
assertThat(it.cardMultilineWidget.getChildAt(0)).isInstanceOf(
CardNumberTextInputLayout::class.java
)
// second_row_layout
assertThat(it.cardMultilineWidget.getChildAt(1)).isInstanceOf(
LinearLayout::class.java
)
// 1 horizontal divider added to tl_card_number, now it has 2 child views
assertThat(it.cardMultilineWidget.cardNumberTextInputLayout.childCount).isEqualTo(
2
)
// no vertical divider added between exp and cvc, secondRowLayout still has 3 child views
assertThat(it.cardMultilineWidget.secondRowLayout.childCount).isEqualTo(
3
)
// 1 horizontal divider added below tl_expiry, now it has 2 child views
assertThat(it.cardMultilineWidget.expiryTextInputLayout.childCount).isEqualTo(
2
)
// 1 horizontal divider added below tl_cvc, now it has 2 child views
assertThat(it.cardMultilineWidget.cvcInputLayout.childCount).isEqualTo(2)
// 1 horizontal divider added below countryLayout, now it has 2 child views
assertThat(it.countryLayout.childCount).isEqualTo(2)
// divider with width=match_parent is invisible
assertThat(it.countryPostalDivider.isVisible).isFalse()
}
}
@Test
fun testCardValidCallback() {
standardBinding!!.let {
var currentIsValid = false
var currentInvalidFields = emptySet<CardValidCallback.Fields>()
standardCardFormView.setCardValidCallback { isValid, invalidFields ->
currentIsValid = isValid
currentInvalidFields = invalidFields
}
assertThat(currentIsValid)
.isFalse()
assertThat(currentInvalidFields)
.containsExactly(
CardValidCallback.Fields.Number,
CardValidCallback.Fields.Expiry,
CardValidCallback.Fields.Cvc,
CardValidCallback.Fields.Postal
)
it.cardMultilineWidget.cardNumberEditText.setText(VISA_WITH_SPACES)
assertThat(currentIsValid)
.isFalse()
assertThat(currentInvalidFields)
.containsExactly(
CardValidCallback.Fields.Expiry,
CardValidCallback.Fields.Cvc,
CardValidCallback.Fields.Postal
)
it.cardMultilineWidget.expiryDateEditText.append("12")
assertThat(currentIsValid)
.isFalse()
assertThat(currentInvalidFields)
.containsExactly(
CardValidCallback.Fields.Expiry,
CardValidCallback.Fields.Cvc,
CardValidCallback.Fields.Postal
)
it.cardMultilineWidget.expiryDateEditText.append("50")
assertThat(currentIsValid)
.isFalse()
assertThat(currentInvalidFields)
.containsExactly(
CardValidCallback.Fields.Cvc,
CardValidCallback.Fields.Postal
)
it.cardMultilineWidget.cvcEditText.append("12")
assertThat(currentIsValid)
.isFalse()
assertThat(currentInvalidFields)
.containsExactly(
CardValidCallback.Fields.Cvc,
CardValidCallback.Fields.Postal
)
it.cardMultilineWidget.cvcEditText.append("3")
assertThat(currentIsValid)
.isFalse()
assertThat(currentInvalidFields)
.containsExactly(
CardValidCallback.Fields.Postal
)
it.postalCode.setText(VALID_US_ZIP)
assertThat(currentIsValid)
.isTrue()
assertThat(currentInvalidFields)
.isEmpty()
}
}
private fun setValuesToStandardUI(
visa: String,
month: String,
year: String,
cvc: String,
zip: String? = null
) {
standardBinding!!.let {
it.cardMultilineWidget.cardNumberEditText.setText(visa)
it.cardMultilineWidget.expiryDateEditText.append(month)
it.cardMultilineWidget.expiryDateEditText.append(year)
it.cardMultilineWidget.cvcEditText.append(cvc)
zip?.let { zipString ->
it.postalCode.setText(zipString)
}
}
}
private fun setLocale(locale: Locale) {
Locale.setDefault(locale)
context.resources.configuration.let { config ->
config.setLocale(locale)
context.resources.updateConfiguration(config, context.resources.displayMetrics)
}
}
companion object {
const val VALID_MONTH = "12"
const val VALID_YEAR = "50"
const val INVALID_YEAR = "11"
const val VALID_CVC = "123"
const val INVALID_CVC = "12"
const val VALID_US_ZIP = "95051"
const val INVALID_US_ZIP = "9505"
const val INVALID_VISA = "1234 1234 1234 1234"
}
}
| mit | f6e281645db58eec422cc7e7e180d53e | 35.048223 | 108 | 0.620996 | 5.085213 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/OnnxOpDeclarations.kt | 1 | 52375 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions
import onnx.Onnx
import org.nd4j.ir.MapperNamespace
import org.nd4j.ir.OpNamespace
import org.nd4j.samediff.frameworkimport.ArgDescriptor
import org.nd4j.samediff.frameworkimport.onnx.*
import org.nd4j.samediff.frameworkimport.onnx.process.OnnxMappingProcess
import org.nd4j.samediff.frameworkimport.onnx.rule.tensor.NDArrayMappingRule
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.samediff.frameworkimport.registry.OpRegistryHolder
val onnxOpRegistry = OpMappingRegistry<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.TensorProto.DataType,Onnx.AttributeProto,Onnx.AttributeProto>("onnx",OpDescriptorLoaderHolder.nd4jOpDescriptor)
fun registry(): OpMappingRegistry<Onnx.GraphProto,Onnx.NodeProto,Onnx.NodeProto,Onnx.TensorProto,Onnx.TensorProto.DataType,Onnx.AttributeProto,Onnx.AttributeProto> {
return onnxOpRegistry
}
val names = mapOf(
"Acos" to "acos",
"Acosh" to "acosh",
"Asin" to "asin",
"Asinh" to "asinh",
"Atan" to "atan",
"Atanh" to "atanh",
"Cos" to "cos",
"Cosh" to "cosh",
"Erf" to "erf",
"Exp" to "exp",
"Identity" to "identity",
"Log" to "log",
"Sign" to "sign",
"Sin" to "sin",
"Sinh" to "sinh",
"Softsign" to "softsign",
"Tan" to "tan",
"Tanh" to "tanh"
)
val pairWiseNames = mapOf(
"And" to "boolean_and")
val equal = OnnxMappingProcess(
inputFrameworkOpName = "Equal",
opName = "equals",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
val sub = OnnxMappingProcess(
inputFrameworkOpName = "Sub",
opName = "subtract",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
val mul = OnnxMappingProcess(
inputFrameworkOpName = "Mul",
opName = "multiply",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
val lessEqual = OnnxMappingProcess(
inputFrameworkOpName = "LessOrEqual",
opName = "less_equal",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
val less = OnnxMappingProcess(
inputFrameworkOpName = "Less",
opName = "less",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
val greaterEqual = OnnxMappingProcess(
inputFrameworkOpName = "GreaterOrEqual",
opName = "greater_equal",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
val greater = OnnxMappingProcess(
inputFrameworkOpName = "Greater",
opName = "greater",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
val divide = OnnxMappingProcess(
inputFrameworkOpName = "Div",
opName = "divide",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
val add = OnnxMappingProcess(
inputFrameworkOpName = "Add",
opName = "add",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
//Adagrad
//Adam
//unmapped: select_last_index
val argMax = OnnxMappingProcess(
opName = "argmax",
inputFrameworkOpName = "ArgMax",
tensorMappingRules = listOf(NDArrayMappingRule(mappingNamesToPerform = mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(
invertBooleanNumber(mapOf("keepDims" to "keepdims")),
valueMappings(mutableMapOf("dimensions" to "axis"))),
opMappingRegistry = onnxOpRegistry
)
//unmapped: select_last_index
val argMin = OnnxMappingProcess(
opName = "argmin",
inputFrameworkOpName = "ArgMin",
tensorMappingRules = listOf(NDArrayMappingRule(mappingNamesToPerform = mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(
invertBooleanNumber(mapOf("keepDims" to "keepdims")),
valueMappings(mutableMapOf("dimensions" to "axis"))),
opMappingRegistry = onnxOpRegistry
)
//Note: weight formats are NCHW in ONNX
val avgPool = OnnxMappingProcess(
inputFrameworkOpName = "AveragePool",
opName = "avgpool2d",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X"))),
attributeMappingRules = listOf(
argDescriptorConstant(argDescriptorConstants = listOf(ArgDescriptor {
name = "isNCHW"
int64Value = 0
argIndex = 10
argType = OpNamespace.ArgDescriptor.ArgType.INT64
})),
intConstant(inputName = "dH",constantValue = 1,argumentIndex = 6)[0],
intConstant(inputName = "dW",constantValue = 1,argumentIndex = 7)[0],
intConstant(inputName = "extraParam0",constantValue = 0,argumentIndex = 9)[0],
stringContainsRule(outputAttribute = "isSameMode",inputFrameworkAttributeName = "auto_pad",valueToTest = "SAME",argumentIndex = 8),
listAttributeValueLookup(outputAttributeValue = "pH",inputAttributeValue = "pads",indexValue = 2,argumentIndex = 4, defaultValueIfNotFound = ArgDescriptor {
argIndex = 4
argType = OpNamespace.ArgDescriptor.ArgType.INT64
int64Value = 0
name = "pH"
}),
listAttributeValueLookup(outputAttributeValue = "pW",inputAttributeValue = "pads",indexValue = 3,argumentIndex = 5,defaultValueIfNotFound = ArgDescriptor {
argIndex = 5
argType = OpNamespace.ArgDescriptor.ArgType.INT64
int64Value = 0
name = "pW"
}),
listAttributeValueLookup(outputAttributeValue = "sH",inputAttributeValue = "strides",indexValue = 0,argumentIndex = 2,defaultValueIfNotFound = ArgDescriptor {
argIndex = 2
argType = OpNamespace.ArgDescriptor.ArgType.INT64
int64Value = 1
name = "sH"
}),
listAttributeValueLookup(outputAttributeValue = "sW",inputAttributeValue = "strides",indexValue = 1,argumentIndex = 3,defaultValueIfNotFound = ArgDescriptor {
argIndex = 3
argType = OpNamespace.ArgDescriptor.ArgType.INT64
int64Value = 1
name = "sW"
}),
listAttributeValueLookup(outputAttributeValue = "kW",inputAttributeValue = "kernel_shape",indexValue = 1,argumentIndex = 1),
listAttributeValueLookup(outputAttributeValue = "kH",inputAttributeValue = "kernel_shape",indexValue = 0,argumentIndex = 0)))
val aliasWithName = OnnxMappingProcess(
opName = "noop",
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "AliasWithName"
)
//note: this is handled by the batchnorm class now
val batchNorm = OnnxMappingProcess(
opName = "noop",
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "BatchNormalization"
)
//TODO: Binarizer
//TODO: Bitshift
//TODO: CastMap
//TODO: CategoryMapper
//TODO: Celu
//TODO: Compress
val concat = OnnxMappingProcess(
opName = "concat",
inputFrameworkOpName = "Concat",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "inputs"))),
attributeMappingRules = listOf(valueMappings(mapOf("concatDimension" to "axis")),
booleanConstant(inputName = "isDynamicAxis",constantValue = false,argumentIndex = 0)[0]),
variableResolutionType = MapperNamespace.VariableResolutionType.DIRECT
)
//TODO: ConcatFromSequence
//TODO: ConvInteger
//TODO: ConvTranspose
val cumSum = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "CumSum",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf()
)
val depthToSpace = OnnxMappingProcess(
opName = "depth_to_space",
inputFrameworkOpName = "DepthToSpace",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "input"))),
//note onnx is NCHW by default
attributeMappingRules = listOf(valueMappings(mapOf("block_size" to "blocksize")),
intConstant(inputName = "isNHWC",constantValue = 1,argumentIndex = 1)[0]),
opMappingRegistry = onnxOpRegistry
)
//TODO: DequantizeLinear
val determinant = OnnxMappingProcess(
opName = "matrix_determinant",
inputFrameworkOpName = "Det",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry
)
val floor = OnnxMappingProcess(
opName = "floor",
inputFrameworkOpName = "Floor",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry
)
val round = OnnxMappingProcess(
opName = "round",
inputFrameworkOpName = "Round",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry
)
val mod = OnnxMappingProcess(
opName = "mod",
inputFrameworkOpName = "Mod",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B"))),
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry
)
val sigmoid = OnnxMappingProcess(
opName = "sigmoid",
inputFrameworkOpName = "Sigmoid",
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X"))),
opMappingRegistry = onnxOpRegistry
)
val logSoftmax = OnnxMappingProcess(
opName = "log_softmax",
inputFrameworkOpName = "LogSoftmax",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "input"))),
attributeMappingRules = listOf(valueMappings(mutableMapOf("dimension" to "axis"))),
opMappingRegistry = onnxOpRegistry
)
val softmax = OnnxMappingProcess(
opName = "softmax",
inputFrameworkOpName = "Softmax",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "input"))),
attributeMappingRules = listOf(valueMappings(mutableMapOf("dimension" to "axis")),
booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0)[0]),
opMappingRegistry = onnxOpRegistry
)
val sequenceConstruct = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "SequenceConstruct",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf()
)
val sequenceAt = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "SequenceAt",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf()
)
val sequenceEmpty = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "SequenceEmpty",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf()
)
val sequenceErase = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "SequenceErase",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf()
)
val sequenceinsert = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "SequenceInsert",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf()
)
val sequenceRemove = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "SequenceRemove",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf()
)
val sequenceLength = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "SequenceLength",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf()
)
//TODO: DynamicQuantizeLinear
//TODO: Einsum
//TODO: EyeLike
//TODO: FeatureVectorizer
val gru = OnnxMappingProcess(
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "GRU",
opName = "gruCell",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf(
"input" to "X",
"Wru" to "R",
"Wc" to "W",
"bc" to "B",
"hLast" to "initial_h",
//TODO: erroneous mappings
"bru" to "B"))),
attributeMappingRules = listOf()
)
val gather = OnnxMappingProcess(
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "Gather",
opName = "gather",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("indices" to "indices","input" to "data"))),
attributeMappingRules = listOf(valueMappings(mapOf("dimensions" to "axis")),
booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0)[0])
)
//TODO: GatherElements
val gatherNd = OnnxMappingProcess(
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "GatherND",
opName = "gather_nd",
attributeMappingRules = booleanConstant(inputName = "checkIndices",constantValue = true,argumentIndex = 0),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("indices" to "indices","input" to "data")))
)
val ifOp = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "If",
opMappingRegistry = onnxOpRegistry
)
val loop = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Loop",
opMappingRegistry = onnxOpRegistry
)
val clip = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Clip",
opMappingRegistry = onnxOpRegistry
)
val roiAlign = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "RoiAlign",
opMappingRegistry = onnxOpRegistry
)
val nonZero = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "NonZero",
opMappingRegistry = onnxOpRegistry
)
//uses the Gemm Rule implementation instead
val gemm = OnnxMappingProcess(
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "Gemm",
opName = "noop")
//note: no ops are mostly just stubs for ops implemented as pre processors
//These are implemented using the PreImportHook found: https://github.com/eclipse/deeplearning4j/tree/master/nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations
val globalAveragePooling = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "GlobalAveragePool",
opMappingRegistry = onnxOpRegistry
)
//TODO: GlobalLpPool
val globalMaxPooling = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "GlobalMaxPool",
opMappingRegistry = onnxOpRegistry
)
val cast = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Cast",
opMappingRegistry = onnxOpRegistry
)
//TODO: DictVectorizer
//Dropout: Note https://github.com/eclipse/deeplearning4j/issues/5650
val dropout = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Dropout",
opMappingRegistry = onnxOpRegistry
)
val resize = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Resize",
opMappingRegistry = onnxOpRegistry
)
//pytorch op
val resizeNearest = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "ResizeNearest",
opMappingRegistry = onnxOpRegistry
)
val constantOfShape = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "ConstantOfShape",
opMappingRegistry = onnxOpRegistry
)
val unsqueeze = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Unsqueeze",
opMappingRegistry = onnxOpRegistry
)
val slice = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Slice",
opMappingRegistry = onnxOpRegistry
)
val expand = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Expand",
opMappingRegistry = onnxOpRegistry
)
val min = OnnxMappingProcess(
inputFrameworkOpName = "Min",
opName = "noop",
opMappingRegistry = onnxOpRegistry)
val max = OnnxMappingProcess(
inputFrameworkOpName = "Max",
opName = "noop",
opMappingRegistry = onnxOpRegistry)
//TODO: Gradient
//TODO: GraphCall
val hardSigmoid = OnnxMappingProcess(
opName = "hard_sigmoid",
inputFrameworkOpName = "HardSigmoid",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X")))
)
//TODO: map is-negative,is-positive
val isInf = OnnxMappingProcess(
opName = "isinf",
inputFrameworkOpName = "IsInf",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = booleanConstant(inputName = "inPlace", constantValue = false,argumentIndex = 0),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X")))
)
val or = OnnxMappingProcess(
opName = "or",
inputFrameworkOpName = "Or",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = listOf(
doubleConstant(inputName = "comparable", constantValue = 0.0,argumentIndex = 0)[0]),
tensorMappingRules = listOf(mappingNDArrayInputs((mutableMapOf("input" to "A","y" to "B"))))
)
val xor = OnnxMappingProcess(
opName = "bitwise_xor",
inputFrameworkOpName = "Xor",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = listOf(booleanConstant(inputName = "inPlace", constantValue = false,argumentIndex = 0)[0]),
tensorMappingRules = listOf(mappingNDArrayInputs((mutableMapOf("input" to "A","y" to "B"))))
)
//TODO: Hardmax
//TODO: Imputer
//TODO: InstanceNormalization
val lrn = OnnxMappingProcess(
opName = "lrn",
inputFrameworkOpName = "LRN",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X"))),
attributeMappingRules = listOf(valueMappings(mapOf("alpha" to "alpha","beta" to "beta","bias" to "bias","depth" to "size")),
booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0)[0])
)
//0=tanh, 1=relu, 2=sigmoid, 3=affine, 4=leaky relu, 5= thresholded relu, 6=scaled tanh, 7=hard sigmoid, 8=ELU, 9=softsign, 10=softplus
val lstmActivationMap = mapOf(
"Relu" to 1,
"Tanh" to 0,
"Sigmoid" to 2,
"Affine" to 3,
"LeakyRelu" to 4,
"ThresholdedRelu" to 5,
"ScaledTanh" to 6,
"HardSigmoid" to 7,
"Elu" to 8,
"Softsign" to 9,
"Softplus" to 10
)
val lstm = OnnxMappingProcess(
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "LSTM",
opName = "lstmLayer",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf(
"input" to "X",
"Wx" to "W",
"Wr" to "R",
"Wp" to "P",
"b" to "B",
"seqLen" to "sequence_lens",
"hI" to "initial_h",
"cI" to "initial_c"))),
attributeMappingRules = listOf(valueMappings(mapOf("cellClip" to "clip")),
stringToIndex(outputAttributeValue = "directionMode",
inputAttributeValue = "direction",
listOfValues = listOf("forward","reverse","bidirectional"),argumentIndex = 1),
intConstant(inputName = "dataFormat",constantValue = 0,argumentIndex = 0)[0],
booleanConstant(inputName = "hasBiases",constantValue = true,argumentIndex = 0)[0],
booleanConstant(inputName = "hasSeqLen",constantValue = true,argumentIndex = 1)[0],
booleanConstant(inputName = "hasInitH",constantValue = true,argumentIndex = 2)[0],
booleanConstant(inputName = "hasInitC",constantValue = true,argumentIndex = 3)[0],
booleanConstant(inputName = "hasPH",constantValue = true,argumentIndex = 4)[0],
booleanConstant(inputName = "retFullSeq",constantValue = true,argumentIndex = 5)[0],
booleanConstant(inputName = "retLastH",constantValue = true,argumentIndex = 6)[0],
booleanConstant(inputName = "retLastC",constantValue = true,argumentIndex = 7)[0],
listAttributeValueLookup(outputAttributeValue = "gateAlpha",inputAttributeValue = "activation_alpha",indexValue = 0,argumentIndex = 1),
listAttributeValueLookup(outputAttributeValue = "cellAlpha",inputAttributeValue = "activation_alpha",indexValue = 1,argumentIndex = 3),
listAttributeValueLookup(outputAttributeValue = "outAlpha",inputAttributeValue = "activation_alpha",indexValue = 2,argumentIndex = 5),
listAttributeValueLookup(outputAttributeValue = "gateBeta",inputAttributeValue = "activation_beta",indexValue = 0,argumentIndex = 2),
listAttributeValueLookup(outputAttributeValue = "cellBeta",inputAttributeValue = "activation_beta",indexValue = 1,argumentIndex = 4),
listAttributeValueLookup(outputAttributeValue = "outBeta",inputAttributeValue = "activation_beta",indexValue = 2,argumentIndex = 6),
mapStringToInt(outputAttributeValue = "gateAct",inputAttributeValue = "activations",argumentIndex = 2,mapOfValuesToInts = lstmActivationMap,lookupIndex = 0),
mapStringToInt(outputAttributeValue = "cellAct",inputAttributeValue = "activations",argumentIndex = 3,mapOfValuesToInts =lstmActivationMap,lookupIndex = 1),
mapStringToInt(outputAttributeValue = "outAct",inputAttributeValue = "activations",argumentIndex = 4,mapOfValuesToInts = lstmActivationMap,lookupIndex = 2))
)
//TODO: LabelEncoder
val leakyRelu = OnnxMappingProcess(
inputFrameworkOpName = "LeakyRelu",
opName = "leakyrelu",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X"))),
attributeMappingRules = listOf(valueMappings(mapOf("alpha" to "alpha")),
booleanConstant("inPlace",false,argumentIndex = 0)[0]),
opMappingRegistry = onnxOpRegistry
)
//TODO: LinearClassifier
//TODO: LinearRegressor
//TODO: Loop
//TODO: LpNormalization
//TODO: LpPool
val matMul = OnnxMappingProcess(
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "MatMul",
opName = "matmul",
attributeMappingRules = listOf(
booleanConstant(inputName = "transX",constantValue = false,argumentIndex = 0)[0],
booleanConstant(inputName = "transY",constantValue = false,argumentIndex = 1)[0],
booleanConstant(inputName = "transZ",constantValue = false,argumentIndex = 2)[0],
booleanConstant(inputName = "transposeX",constantValue = false,argumentIndex = 0)[0],
booleanConstant(inputName = "transposeY",constantValue = false,argumentIndex = 1)[0],
booleanConstant(inputName = "transposeZ",constantValue = false,argumentIndex = 2)[0],
doubleConstant(inputName = "alpha",constantValue = 0.0,argumentIndex = 0)[0],
doubleConstant(inputName = "beta",constantValue = 1.0,argumentIndex = 1)[0]),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "A","y" to "B")))
)
//TODO: MatMulInteger
//TODO: Max
val maxPool = OnnxMappingProcess(
inputFrameworkOpName = "MaxPool",
opName = "maxpool2d",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X"))),
attributeMappingRules = listOf(
argDescriptorConstant(argDescriptorConstants = listOf(ArgDescriptor {
name = "isNCHW"
int64Value = 0
argIndex = 10
argType = OpNamespace.ArgDescriptor.ArgType.INT64
})),
intConstant(inputName = "extraParam0",argumentIndex = 9,constantValue = 0)[0],
//note this parameter can be 0 for valid, 1 for same, 2 for causal
intConstant(inputName = "isSameMode",constantValue = 0,argumentIndex = 8)[0],
//stringContainsRule(outputAttribute = "isSameMode",inputFrameworkAttributeName = "auto_pad",valueToTest = "SAME",argumentIndex = 8),
listAttributeValueLookup(outputAttributeValue = "dH",inputAttributeValue = "dilations",indexValue = 0,argumentIndex = 6,defaultValueIfNotFound = ArgDescriptor {
int64Value = 1
name = "dH"
argIndex = 6
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "dW",inputAttributeValue = "dilations",indexValue = 1,argumentIndex = 7,
defaultValueIfNotFound = ArgDescriptor {
int64Value = 1
name = "dW"
argIndex = 7
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "pH",inputAttributeValue = "pads",indexValue = 2,argumentIndex = 4,defaultValueIfNotFound = ArgDescriptor {
int64Value = 0
name = "pads"
argIndex = 4
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "pW",inputAttributeValue = "pads",indexValue = 3,argumentIndex = 5,
defaultValueIfNotFound = ArgDescriptor {
int64Value = 0
name = "pads"
argIndex = 5
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "sH",inputAttributeValue = "strides",indexValue = 0,argumentIndex = 2,
defaultValueIfNotFound = ArgDescriptor {
int64Value = 1
name = "sH"
argIndex = 6
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "sW",inputAttributeValue = "strides",indexValue = 1,argumentIndex = 3,
defaultValueIfNotFound = ArgDescriptor {
int64Value = 1
name = "sW"
argIndex = 7
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "kH",inputAttributeValue = "kernel_shape",indexValue = 0,argumentIndex = 0),
listAttributeValueLookup(outputAttributeValue = "kW",inputAttributeValue = "kernel_shape",indexValue = 1,argumentIndex = 1)))
//TODO: MaxRoiPool
//TODO: MaxUnpool
//TODO: name: "MeanVarianceNormalization"
//todo: Momentum
//TODO: Multinomial
//TODO: NegativeLogLikelihoodLoss
val nonMaxSuppression = OnnxMappingProcess(
inputFrameworkOpName = "NonMaxSuppression",
opName = "non_max_suppression_v3",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = listOf(ndarrayToIntList(mutableMapOf("maxOutputSize" to "max_output_boxes_per_class"))),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf(
"boxes" to "boxes",
"scales" to "scores",
"maxOutSize" to "max_output_boxes_per_class",
"iouThreshold" to "iou_threshold",
"scoreThreshold" to "score_threshold")))
)
//TODO: NonZero PRIORITIZE
//TODO: Normalizer
//TODO: OneHot
//TODO: OneHotEncoder
//note: this is handled by the PRelu class now
val pRelu = OnnxMappingProcess(
inputFrameworkOpName = "PRelu",
opName = "noop",
opMappingRegistry = onnxOpRegistry
)
val pad = OnnxMappingProcess(
inputFrameworkOpName = "Pad",
opMappingRegistry = onnxOpRegistry,
opName = "pad",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data","paddings" to "pads"))),
attributeMappingRules = listOf(
stringToIndex(outputAttributeValue = "mode",inputAttributeValue = "mode",listOfValues = listOf("constant","reflect","edge"),argumentIndex = 0),
doubleConstant(inputName = "padValue",constantValue = 0.0,argumentIndex = 0)[0])
)
//TODO: QLinearConv
//TODO: QLinearMatMul
//TODO: QuantizeLinear
//TODO: RNN PRIORITIZE
val randomNormal = OnnxMappingProcess(
inputFrameworkOpName = "RandomNormal",
opName = "random_normal",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = listOf(listNumberToNDarray(outputAttributeValue = "input",inputAttributeValue = "shape"))
)
//TODO: RandomNormalLike
//TODO: Note that the attributes for random unifrom are wrong and needed to be discovered through other means.
//The combination of a lack of a java class + the c++ calling out to other functions which had the actual parameters
//names prevented resolution of the real parameter names. May have to look in to values that are passed inline in to functions and look up
//parameter names that way.
val randomUniform = OnnxMappingProcess(
inputFrameworkOpName = "RandomUniform",
opName = "randomuniform",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = listOf(
valueMappings(mapOf("min" to "low","max" to "high")),
intConstant(inputName = "seed",constantValue = 0,argumentIndex = 0)[0],
listNumberToNDarray(outputAttributeValue = "shape",
inputAttributeValue = "shape"))
)
//TODO: RandomUniformLike
val range = OnnxMappingProcess(
inputFrameworkOpName = "Range",
opName = "range",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("from" to "start","to" to "limit","step" to "delta"))),
attributeMappingRules = listOf(
convertNDArrayInputToScalarAttr(outputAttributeValue = "from",inputAttributeValue = "start"),
convertNDArrayInputToScalarAttr(outputAttributeValue = "to",inputAttributeValue = "limit"),
convertNDArrayInputToScalarAttr(outputAttributeValue = "step",inputAttributeValue = "delta"))
)
val neg = OnnxMappingProcess(
opName = "neg",
inputFrameworkOpName = "Neg",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X")))
)
val norm1 = OnnxMappingProcess(
inputFrameworkOpName = "ReduceL1",
opMappingRegistry = onnxOpRegistry,
opName = "reduce_norm1",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(invertBooleanNumber(mapOf("keepDims" to "keepdims")),
listNumberToListNumber(outputAttributeValue = "dimensions",inputAttributeValue = "axes"))
)
val norm2 = OnnxMappingProcess(
inputFrameworkOpName = "ReduceL2",
opMappingRegistry = onnxOpRegistry,
opName = "reduce_norm2",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(
invertBooleanNumber(mapOf("keepDims" to "keepdims")),
listNumberToListNumber(outputAttributeValue = "dimensions",inputAttributeValue = "axes"))
)
//TODO: ReduceLogSum
val reduceLogSumExp = OnnxMappingProcess(
inputFrameworkOpName = "ReduceLogSumExp",
opName = "reduce_logsumexp",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(
invertBooleanNumber(mutableMapOf("keepDims" to "keepdims")),
valueMappings(mutableMapOf("keepDims" to "keepdims")),
listNumberToListNumber(outputAttributeValue = "dimensions",inputAttributeValue = "axes")),
opMappingRegistry = onnxOpRegistry
)
val reduceMax = OnnxMappingProcess(
inputFrameworkOpName = "ReduceMax",
opName = "reduce_max",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(
invertBooleanNumber(mapOf("keepDims" to "keepdims")),
listNumberToListNumber(outputAttributeValue = "dimensions",inputAttributeValue = "axes")),
opMappingRegistry = onnxOpRegistry
)
val reduceMean = OnnxMappingProcess(
inputFrameworkOpName = "ReduceMean",
opName = "reduce_mean",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(
invertBooleanNumber(mapOf("keepDims" to "keepdims")),
listNumberToListNumber(outputAttributeValue = "dimensions",inputAttributeValue = "axes")),
opMappingRegistry = onnxOpRegistry
)
val reduceMin = OnnxMappingProcess(
inputFrameworkOpName = "ReduceMin",
opName = "reduce_min",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(
invertBooleanNumber(mapOf("keepDims" to "keepdims")),
listNumberToListNumber(outputAttributeValue = "dimensions",inputAttributeValue = "axes")),
opMappingRegistry = onnxOpRegistry
)
val reduceProd = OnnxMappingProcess(
inputFrameworkOpName = "ReduceProd",
opName = "reduce_prod",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(invertBooleanNumber(mapOf("keepDims" to "keepdims")),
listNumberToListNumber(outputAttributeValue = "dimensions",inputAttributeValue = "axes")),
opMappingRegistry = onnxOpRegistry
)
val reduceSum = OnnxMappingProcess(
inputFrameworkOpName = "ReduceSum",
opName = "reduce_sum",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(invertBooleanNumber(mapOf("keepDims" to "keepdims")),
ndarrayToIntList(mutableMapOf( "dimensions" to "axes"))),
opMappingRegistry = onnxOpRegistry
)
//flattenDims
val flatten = OnnxMappingProcess(
inputFrameworkOpName = "Flatten",
opName = "flatten_2d",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "input"))),
attributeMappingRules = listOf(valueMappings(mutableMapOf("dimensions" to "axis"))),
opMappingRegistry = onnxOpRegistry
)
//note this is implemented by Reshape.kt instead
val reshape = OnnxMappingProcess(
inputFrameworkOpName = "Reshape",
opName = "noop",
opMappingRegistry = onnxOpRegistry
)
//TODO: ReduceSumSquare
//for mapping indices see: https://github.com/eclipse/deeplearning4j/blob/228f6cda30e27999f0fea74badc8d98ee8fb0647/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/enums/ImageResizeMethod.java#L29
//TODO: ReverseSequence
//TODO: RoiAlign
//TODO: SVMClassifier
//TODO: SVMRegressor
//TODO: Scaler
//TODO: Scan
val scatter = OnnxMappingProcess(
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "ScatterElements",
opName = "scatter_update",
attributeMappingRules = listOf(),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("operand" to "data","updates" to "updates","indices" to "indices")))
)
val scatterNd = OnnxMappingProcess(inputFrameworkOpName ="ScatterND",
opName = "scatter_nd",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf(
"indices" to "indices",
"updates" to "updates","shape" to "data"))),
attributeMappingRules = listOf()
,opMappingRegistry = onnxOpRegistry)
//TODO: SequenceAt
//TODO: SequenceConstruct
//TODO: SequenceErase
//TODO: SequenceInsert
//TODO: SequenceLength
val shape = OnnxMappingProcess(
opName = "shape_of",
inputFrameworkOpName = "Shape",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
tensorMappingRules = listOf(mappingNDArrayInputs((mutableMapOf("input" to "data"))))
)
//TODO: Shrink
val not = OnnxMappingProcess(
opName = "not",
inputFrameworkOpName = "Not",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = doubleConstant(inputName = "comparable",constantValue = 0.0,argumentIndex = 0),
tensorMappingRules = listOf(mappingNDArrayInputs((mutableMapOf("input" to "X"))))
)
val pow = OnnxMappingProcess(
opName = "pow_pairwise",
inputFrameworkOpName = "Pow",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = listOf(
booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0)[0]),
tensorMappingRules = listOf(mappingNDArrayInputs((mutableMapOf("input" to "X","y" to "Y"))))
)
val size = OnnxMappingProcess(
opName = "size",
inputFrameworkOpName = "Size",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(mappingNDArrayInputs((mutableMapOf("input" to "data"))))
)
//TODO: SoftmaxCrossEntropyLoss
val spaceToDepth = OnnxMappingProcess(
opName = "space_to_depth",
inputFrameworkOpName = "SpaceToDepth",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "input"))),
attributeMappingRules = listOf(valueMappings(mapOf("block_size" to "blocksize")),
argDescriptorConstant(listOf(ArgDescriptor {
name = "isNHWC"
int64Value = 1
argIndex = 1
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}))),
opMappingRegistry = onnxOpRegistry
)
val split = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Split",
opMappingRegistry = onnxOpRegistry,
)
val transpose = OnnxMappingProcess(
opName = "noop",
inputFrameworkOpName = "Transpose",
opMappingRegistry = onnxOpRegistry
)
val sqrt = OnnxMappingProcess(
opName = "sqrt",
inputFrameworkOpName = "Sqrt",
opMappingRegistry = onnxOpRegistry,
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
tensorMappingRules = listOf(mappingNDArrayInputs((mutableMapOf("input" to "X"))))
)
val softplus = OnnxMappingProcess(
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "Softplus",
opName = "softplus",
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X")))
)
//TODO: SplitToSequence
val squeeze = OnnxMappingProcess(
opName = "squeeze",
inputFrameworkOpName = "Squeeze",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "data"))),
attributeMappingRules = listOf(ndarrayToIntList(mutableMapOf( "_a" to "axes")))
)
//TODO: StringNormalizer
//TODO: TfIdfVectorizer
//TODO: ThresholdedRelu
val tile = OnnxMappingProcess(
opMappingRegistry = onnxOpRegistry,
inputFrameworkOpName = "Tile",
opName = "tile",
attributeMappingRules = listOf(
booleanConstant(inputName = "is_static_reps",constantValue = true,argumentIndex = 0)[0],
intConstant(inputName = "dimensions",constantValue = 0,argumentIndex = 0)[0]),
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "input","reps_vector" to "repeats")))
)
val topK = OnnxMappingProcess(
opName = "top_k",
inputFrameworkOpName = "TopK",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("input" to "X"))),
attributeMappingRules = listOf(
invertBooleanNumber(mutableMapOf("needSort" to "sorted")),
convertNDArrayInputToScalarAttr(outputAttributeValue = "k",inputAttributeValue = "K")),
opMappingRegistry = onnxOpRegistry
)
val where = OnnxMappingProcess(
inputFrameworkOpName = "Where",
opName = "Where",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf("condition" to "condition","input" to "X","y" to "Y"))),
opMappingRegistry = onnxOpRegistry
)
val abs = OnnxMappingProcess(
opName = "abs", tensorMappingRules = listOf(NDArrayMappingRule(mappingNamesToPerform = mutableMapOf("input" to "X"))),
inputFrameworkOpName = "Abs",
inputFramework = "onnx",
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0),
opMappingRegistry = onnxOpRegistry)
val ceil = defOnnxSingleTransform(inputFrameworkOpName = "Ceil",opName = "ceil",inputFrameworkInput = "X",outputName = "input",
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0)
)
val const = OnnxMappingProcess(
inputFrameworkOpName = "Constant",
opName = "noop",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf())
//note: this is not a real onnx op and meant to be a dummy node to indicate placeholders
//samediff/tensorflow parlance
val placeHolder = OnnxMappingProcess(
inputFrameworkOpName = "Placeholder",
opName = "noop",
opMappingRegistry = onnxOpRegistry,
tensorMappingRules = listOf(),
attributeMappingRules = listOf())
val conv2d = OnnxMappingProcess(
inputFramework = "onnx",
inputFrameworkOpName = "Conv",
opName = "conv2d",
tensorMappingRules = listOf(mappingNDArrayInputs(mutableMapOf(
"input" to "X","weights" to "W","bias" to "B"))),
attributeMappingRules = listOf(
intConstant(inputName = "isNCHW",constantValue = 0,argumentIndex = 9)[0],
intConstant(inputName = "wFormat",constantValue = 1,argumentIndex = 10)[0],
stringEqualsRule(outputAttribute = "isSameMode",inputFrameworkAttributeName = "auto_pad",valueToTest = "SAME",argumentIndex = 8),
listAttributeValueLookup(outputAttributeValue = "dH",inputAttributeValue = "dilations",indexValue = 0,argumentIndex = 6,defaultValueIfNotFound = ArgDescriptor {
int64Value = 1
name = "dH"
argIndex = 6
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "dW",inputAttributeValue = "dilations",indexValue = 1,argumentIndex = 7,defaultValueIfNotFound = ArgDescriptor {
int64Value = 1
name = "dW"
argIndex = 7
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "pH",inputAttributeValue = "pads",indexValue = 0,argumentIndex = 4,
defaultValueIfNotFound = ArgDescriptor {
int64Value = 0
name = "padding"
argIndex = 4
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "pW",inputAttributeValue = "pads",indexValue = 1,argumentIndex = 5,
defaultValueIfNotFound = ArgDescriptor {
int64Value = 0
name = "padding"
argIndex = 5
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "sH",inputAttributeValue = "strides",indexValue = 0,argumentIndex = 2,
defaultValueIfNotFound = ArgDescriptor {
int64Value = 1
name = "strides"
argIndex = 2
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "sW",inputAttributeValue = "strides",indexValue = 1,argumentIndex = 3,
defaultValueIfNotFound = ArgDescriptor {
int64Value = 1
name = "strides"
argIndex = 3
argType = OpNamespace.ArgDescriptor.ArgType.INT64
}),
listAttributeValueLookup(outputAttributeValue = "kW",inputAttributeValue = "kernel_shape",indexValue = 1,argumentIndex = 0),
listAttributeValueLookup(outputAttributeValue = "kH",inputAttributeValue = "kernel_shape",indexValue = 0,argumentIndex = 1)
),opMappingRegistry = onnxOpRegistry)
val elu = defOnnxSingleTransform(opName = "elu",inputFrameworkOpName = "Elu",outputName = "input",inputFrameworkInput = "X",
attributeMappingRules = listOf(valueMappings(mutableMapOf("alpha" to "alpha"))))
val relu = defOnnxSingleTransform(inputFrameworkOpName = "Relu",opName = "relu",
inputFrameworkInput = "X",outputName = "input",
attributeMappingRules = listOf(
booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0)[0],
doubleConstant(inputName = "cutoff",constantValue = 0.0,argumentIndex = 0)[0]))
val isNan = defOnnxSingleTransform(inputFrameworkOpName = "IsNaN",opName = "isnan",inputFrameworkInput = "X",outputName = "input",
attributeMappingRules = booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0)
)
val selu = defOnnxSingleTransform(inputFrameworkOpName = "Selu",opName = "selu",inputFrameworkInput = "X",outputName = "input",attributeMappingRules =
booleanConstant(inputName = "inPlace",constantValue = false,argumentIndex = 0)
)
object OnnxOpDeclarations {
init {
val onnxops = OpDescriptorLoaderHolder.listForFramework<Onnx.NodeProto>("onnx")
val groupedOps = onnxops.values.groupBy { input -> input.name }
val singleGroupedOps = HashMap<String,Onnx.NodeProto>()
groupedOps.forEach { name,node ->
singleGroupedOps[name] = node[0]
}
OpRegistryHolder.registerOpList("onnx", singleGroupedOps)
names.forEach {
defineOnnxSingleTransform(inputFrameworkOpName = it.key,inputOpName = it.value)
} ?: "Error initializing single defined transforms in onnx."
pairWiseNames.forEach {
defineOnnxPairwiseTransforms(opName = it.value,inputFrameworkOpName = it.key)
} ?: "Error initializing pair wise transforms"
onnxops.values.forEach {
onnxOpRegistry.registerInputFrameworkOpDef(it.name,it)
}
OpDescriptorLoaderHolder.nd4jOpDescriptor.opListList.forEach {
onnxOpRegistry.registerNd4jOpDef(it.name,it)
}
OpRegistryHolder.registerOpMappingRegistry("onnx", onnxOpRegistry)
}
}
val declarations = OnnxOpDeclarations | apache-2.0 | 672dff5aa7f4d7bccd199645948d302a | 42.28595 | 233 | 0.64779 | 4.734249 | false | false | false | false |
mvarnagiris/expensius | models/src/test/kotlin/com/mvcoding/expensius/model/extensions/TagExtensions.kt | 1 | 1224 | /*
* 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.model.extensions
import com.mvcoding.expensius.model.*
fun aTagId() = TagId(aStringId())
fun aTitle() = Title(aString("title"))
fun aColor() = Color(anInt())
fun anOrder() = Order(anInt(100))
fun aCreateTag() = CreateTag(aTitle(), aColor(), anOrder())
fun someTags() = (0..anInt(5)).map { aTag() }.toSet()
fun someTagsIds() = (0..anInt(5)).map { aTagId() }.toSet()
fun aTag() = Tag(aTagId(), aModelState(), aTitle(), aColor(), anOrder())
fun Tag.withOrder(order: Int) = copy(order = Order(order))
fun Tag.withTitle(title: String) = copy(title = Title(title))
fun Tag.withModelState(modelState: ModelState) = copy(modelState = modelState)
| gpl-3.0 | ef10e55f1d1e4a6ad5a8df0b1df71a77 | 41.206897 | 78 | 0.718954 | 3.6 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/fixes/RemoveImportFix.kt | 2 | 1785 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.ide.intentions.RemoveCurlyBracesIntention
import org.rust.lang.core.psi.RsUseGroup
import org.rust.lang.core.psi.RsUseItem
import org.rust.lang.core.psi.RsUseSpeck
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.deleteWithSurroundingCommaAndWhitespace
import org.rust.lang.core.psi.ext.parentUseSpeck
/**
* Fix that removes a use speck or a whole use item.
*/
class RemoveImportFix(element: PsiElement) : LocalQuickFixOnPsiElement(element) {
override fun getText() = "Remove unused import"
override fun getFamilyName() = text
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
val element = startElement as? RsElement ?: return
deleteUseSpeckOrUseItem(element)
}
}
private fun deleteUseSpeckOrUseItem(element: RsElement) {
val parent = element.parent
element.deleteWithSurroundingCommaAndWhitespace()
if (parent is RsUseGroup) {
val parentSpeck = parent.parentUseSpeck
if (parent.useSpeckList.isEmpty()) {
deleteUseSpeck(parentSpeck)
} else {
val ctx = RemoveCurlyBracesIntention.createContextIfCompatible(parentSpeck) ?: return
RemoveCurlyBracesIntention.removeCurlyBracesFromUseSpeck(ctx)
}
}
}
fun deleteUseSpeck(useSpeck: RsUseSpeck) {
val element = (useSpeck.parent as? RsUseItem) ?: useSpeck
deleteUseSpeckOrUseItem(element)
}
| mit | 7dba1c2b76373aec4716011f503faa61 | 33.326923 | 108 | 0.753501 | 4.270335 | false | false | false | false |
bsmr-java/lwjgl3 | modules/generator/src/main/kotlin/org/lwjgl/generator/Structs.kt | 1 | 66879 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.generator
import java.io.PrintWriter
import java.util.*
private val STRUCT = "struct"
private val ANONYMOUS = "*" // very easy to introduce bugs, unless this is an invalid character in Java identifiers
open class StructMember(
val nativeType: NativeType,
val name: String,
val documentation: String
) : TemplateElement() {
init {
if ( nativeType is StructType && nativeType.includesPointer )
nativeType.definition.hasUsageInput()
}
internal val offsetField: String
get() = name.toUpperCase()
internal fun offsetField(parentField: String): String {
return if ( parentField.isEmpty() )
offsetField
else
"${parentField}_$offsetField"
}
internal fun field(parentMember: String) = if ( parentMember.isEmpty() )
if ( name == "class" ) "$name\$" else name // TODO: use a list of Java keywords here
else
"${parentMember}_$name"
var mutable = false
internal var links: String = ""
internal var linkMode: LinkMode = LinkMode.SINGLE
fun links(links: String, linkMode: LinkMode = LinkMode.SINGLE) {
this.links = links
this.linkMode = linkMode
}
}
private class StructMemberBuffer(
nativeType: StructType,
name: String,
documentation: String
) : StructMember(nativeType, name, documentation)
private open class StructMemberArray(
nativeType: NativeType,
name: String,
documentation: String,
/** Number of elements in the array. */
val size: String,
/** Number of pointer elements that must not be null. */
val validSize: String
) : StructMember(nativeType, name, documentation) {
val primitiveMapping: PrimitiveMapping get() = nativeType.let {
if ( it is PointerType ) PrimitiveMapping.POINTER else it.mapping as PrimitiveMapping
}
}
private class StructMemberCharArray(
nativeType: CharType,
name: String,
documentation: String,
size: String
) : StructMemberArray(nativeType, name, documentation, size, size)
private class StructMemberPadding(size: String, val condition: String?) : StructMemberArray(char, ANONYMOUS, "", size, size)
private enum class MultiSetterMode {
NORMAL,
ALTER
}
private enum class AccessMode(val indent: String) {
INSTANCE("\t"),
FLYWEIGHT("\t\t");
}
class Struct(
packageName: String,
className: String,
nativeSubPath: String = "",
/** The native struct name. May be different than className. */
val nativeName: String,
private val union: Boolean,
/** when true, a declaration is missing, we need to output one. */
private val virtual: Boolean,
/** when false, setters methods will not be generated. */
private val mutable: Boolean,
/** if specified, is the super-type of this struct. */
private val extends: Struct?,
/** when true, the struct layout will be built using native code. */
private val nativeLayout: Boolean
) : GeneratorTargetNative(packageName, className, nativeSubPath) {
companion object {
private val bufferMethodMap = mapOf(
"boolean" to "Byte",
"byte" to "Byte",
"char" to "Char",
"short" to "Short",
"int" to "Int",
"long" to "Long",
"float" to "Float",
"double" to "Double"
)
private val BUFFER_CAPACITY_PARAM = "capacity"
}
val nativeType: StructType get() = StructType(this)
/* Output parameter or function result by value */
private var usageOutput = false
fun hasUsageOutput() {
usageOutput = true
}
/* Input parameter */
private var usageInput = false
fun hasUsageInput() {
usageInput = true
}
/* Function result by reference */
private var usageResultPointer = false
fun hasUsageResultPointer() {
usageResultPointer = true
}
private var static: String? = null
fun static(expression: String) {
static = expression
}
private val members = ArrayList<StructMember>()
private val visibleMembers: Sequence<StructMember>
get() = members.asSequence().filter { it !is StructMemberPadding }
private val mutableMembers: Sequence<StructMember>
get() = visibleMembers.let {
if ( mutable ) it else it.filter { it -> it.mutable }
}
private val hasMutableMembers: Boolean get() = members.isNotEmpty() && (mutable || mutableMembers.any())
private fun add(member: StructMember): StructMember {
members.add(member)
return member
}
// Plain field
fun NativeType.member(name: String, documentation: String) = add(StructMember(this, name, documentation))
// Points to an array of structs, not a single struct
fun PointerType.buffer(name: String, documentation: String): StructMember {
if ( this !is StructType )
throw IllegalArgumentException()
return add(StructMemberBuffer(this, name, documentation))
}
// Array field
fun NativeType.array(name: String, documentation: String, size: Int, validSize: Int = size)
= array(name, documentation, size.toString(), validSize.toString())
fun NativeType.array(name: String, documentation: String, size: String, validSize: String = size)
= add(StructMemberArray(this, name, documentation, size, validSize))
// CharSequence special-case
fun CharType.array(name: String, documentation: String, size: Int) = array(name, documentation, size.toString())
fun CharType.array(name: String, documentation: String, size: String) = add(StructMemberCharArray(this, name, documentation, size))
fun padding(size: Int, condition: String? = null) = add(StructMemberPadding(size.toString(), condition))
/** Anonymous nested member struct definition. */
fun struct(init: Struct.() -> Unit): StructMember {
return struct(ANONYMOUS, ANONYMOUS, init)
}
/** Nested member struct definition. */
fun struct(name: String, documentation: String, init: Struct.() -> Unit): StructMember {
val struct = Struct(ANONYMOUS, ANONYMOUS, "", ANONYMOUS, false, false, true, null, false)
struct.init()
return StructType(struct).member(name, documentation)
}
/** Anonymous nested member union definition. */
fun union(init: Struct.() -> Unit): StructMember {
return union(ANONYMOUS, ANONYMOUS, init)
}
/** Nested member union definition. */
fun union(name: String, documentation: String, init: Struct.() -> Unit): StructMember {
val struct = Struct(ANONYMOUS, ANONYMOUS, "", ANONYMOUS, true, false, true, null, false)
struct.init()
return StructType(struct).member(name, documentation)
}
/** The nested struct's members are embedded in the parent struct. */
private val StructMember.isNestedStruct: Boolean
get() = nativeType is StructType && !nativeType.includesPointer && this !is StructMemberArray
/** The nested struct is not defined elsewhere, it's part of the parent struct's definition */
private val StructMember.isNestedStructDefinition: Boolean
get() = isNestedStruct && (nativeType as StructType).name === ANONYMOUS
private val StructMember.nestedMembers: Sequence<StructMember>
get() = (nativeType as StructType).definition.visibleMembers
private val containsUnion: Boolean get() =
union || members.any {
it.isNestedStruct && (it.nativeType as StructType).let {
if ( it.name === ANONYMOUS )
it.definition.containsUnion
else
it.definition.union
}
}
internal val validations: Sequence<String> by lazy {
if ( union )
return@lazy emptySequence<String>()
val validations = ArrayList<String>()
fun MutableList<String>.addPointer(m: StructMember) = this.add("\t\tlong ${m.name} = memGetAddress($STRUCT + $className.${m.offsetField});")
fun MutableList<String>.addCount(m: StructMember) = this.add("\t\t${m.nativeType.javaMethodType} ${m.name} = n${m.name}($STRUCT);")
fun validate(m: StructMember, indent: String, hasPointer: Boolean = false): String {
return if ( m.nativeType is StructType && m.nativeType.definition.validations.any() ) {
if ( m is StructMemberArray ) {
"""${if ( hasPointer ) "" else "${indent}long ${m.name} = $STRUCT + $className.${m.offsetField};\n"}${indent}for ( int i = 0; i < ${m.size}; i++ ) {
${ if ( m.validSize == m.size ) "$indent checkPointer(memGetAddress(${m.name}));" else
"""$indent if ( i < ${m.validSize} )
$indent checkPointer(memGetAddress(${m.name}));
$indent else if ( memGetAddress(${m.name}) == NULL )
$indent break;"""}
$indent ${m.nativeType.javaMethodType}.validate(${m.name});
$indent ${m.name} += POINTER_SIZE;
$indent}"""
} else {
"${if ( hasPointer ) "" else
"${indent}long ${m.name} = memGetAddress($STRUCT + $className.${m.offsetField});\n" +
"${indent}checkPointer(${m.name});\n"
}$indent${m.nativeType.javaMethodType}.validate(${m.name}${getReferenceMember(AutoSizeMember, m.name).let { if ( it != null ) ", ${it.name}" else "" }});"
}
} else
"${indent}checkPointer(memGetAddress($STRUCT + $className.${m.offsetField}));"
}
fun validationBlock(condition: String, validations: String): String = validations.contains('\n').let { needBraces ->
"\t\tif ( $condition )${if ( needBraces ) " {" else ""}\n$validations${if ( needBraces ) "\n\t\t}" else ""}"
}
mutableMembers.forEach { m ->
if ( m has AutoSizeMember ) {
m[AutoSizeMember].let { autoSize ->
val refs = autoSize.members(mutableMembers)
if ( autoSize.atLeastOne ) {
// TODO: There will be redundancy here when one of the refs is a validateable struct array. But we don't have a case for it yet.
validations.addCount(m)
// if m != 0, make sure one of the auto-sized members is not null
validations.add(
"\t\tif (${if ( autoSize.optional ) "\n\t\t\t${m.name} != 0 &&" else "\n\t\t\t${m.name} == 0 || ("}${
refs.map { "\n\t\t\tmemGetAddress($STRUCT + $className.${it.offsetField}) == NULL" }.joinToString(" &&")
}\n\t\t${if ( autoSize.optional ) "" else ")"}) {\n\t\t\tthrow new NullPointerException(\"At least one of ${refs.map { it.name }.joinToString()} must not be null\");\n\t\t}"
)
} else if ( autoSize.optional ) {
val refValidations = refs.filter { !it.has(nullable) }.map { ref ->
validate(ref, "\t\t\t")
}.joinToString("\n")
if ( refValidations.isEmpty() )
return@let
// if m != 0, make sure auto-sized members are not null
validations.add(
validationBlock("${if ( refValidations.contains(", ${m.name})") ) {
validations.addCount(m)
m.name
} else "n${m.name}($STRUCT)"} != 0", refValidations)
)
} else if ( refs.any { it.nativeType is StructType && it.nativeType.definition.validations.any() } )
validations.addCount(m)
}
} else if ( m.nativeType is PointerType && getReferenceMember(AutoSizeMember, m.name)?.get(AutoSizeMember).let { it == null || !it.optional } ) {
if ( m.nativeType is StructType && m.nativeType.definition.validations.any() ) {
validations.add(
if ( m.nativeType.includesPointer ) {
if ( m.has(nullable) ) {
validations.addPointer(m)
validationBlock("${m.name} != NULL", validate(m, "\t\t\t", hasPointer = true))
} else
validate(m, "\t\t")
} else
"\t\t${m.nativeType.javaMethodType}.validate($STRUCT + $className.${m.offsetField});"
)
} else if ( !m.has(nullable) && !(m.nativeType is StructType && !m.nativeType.includesPointer) ) {
validations.add(validate(m, "\t\t"))
}
}
}
validations.asSequence()
}
/** Returns a member that has the specified ReferenceModifier with the specified reference. Returns null if no such parameter exists. */
private fun getReferenceMember(modifierObject: ModifierKey<*>, reference: String) = members.firstOrNull {
it.hasRef(modifierObject, reference)
} // Assumes at most 1 parameter will be found that references the specified parameter
private fun PrintWriter.printDocumentation() {
val builder = StringBuilder()
val members = members.filter { it !is StructMemberPadding }
if ( documentation != null ) {
builder.append(documentation)
if ( members.isNotEmpty() )
builder.append("\n\n")
}
if ( members.isNotEmpty() ) {
val memberDoc = printMemberDocumentation()
if ( memberDoc.isNotEmpty() )
builder
.append("<h3>Member documentation</h3>\n\n")
.append(ul(*memberDoc.toTypedArray()))
.append("\n\n")
builder.append("<h3>Layout</h3>\n\n")
builder.append(codeBlock(printStructLayout()))
}
if ( builder.length != 0 )
println(processDocumentation(builder.toString()).toJavaDoc(indentation = ""))
}
private val nativeNameQualified: String get() {
val type = if ( union ) "union " else "struct "
return if ( nativeName.startsWith(type) )
nativeName
else if ( nativeName === ANONYMOUS )
type.substring(0, type.length - 1)
else
"$type$nativeName"
}
private fun Struct.printStructLayout(indentation: String = ""): String {
val memberIndentation = "$indentation "
return """$nativeNameQualified {
${members.map {
if ( it.isNestedStructDefinition )
"${(it.nativeType as StructType).definition.printStructLayout(memberIndentation)}${if ( it.name === ANONYMOUS ) "" else " ${it.name}"};"
else {
val nativeType = if ( it.nativeType is StructType && !it.nativeType.includesPointer )
"{@link ${it.nativeType.javaMethodType} ${it.nativeType.name}}"
else
it.nativeType.let {
if ( it is PointerType && !it.includesPointer )
"${it.name}${if ( !it.name.endsWith('*') ) " " else ""}*"
else
it.name
}
"${if (it has ConstMember) "const " else ""}$nativeType${if ( it.name === ANONYMOUS ) "" else " ${it.name}"}${if ( it is StructMemberArray ) "[${it.size}]" else ""};"
}
}.joinToString("\n$memberIndentation", prefix = memberIndentation)}
$indentation}"""
}
private fun Struct.printMemberDocumentation(prefix: String = "", documentation: MutableList<String> = ArrayList<String>()): List<String> {
members.forEach {
if ( it.isNestedStructDefinition )
(it.nativeType as StructType).definition.printMemberDocumentation(if (it.name === ANONYMOUS) prefix else "$prefix${it.name}.", documentation)
else if ( it.documentation.isNotEmpty() ) {
val doc = if ( it.links.isEmpty() )
it.documentation
else if ( it.links.any { it == '#' } )
it.linkMode.appendLinks(it.documentation, it.links)
else {
val regex = it.links.toRegex()
val tokens = Generator.tokens[packageName]!!.keys.filter { regex.matches(it) }
if ( tokens.isEmpty() )
throw IllegalStateException("Failed to match any tokens with regex: ${it.links}")
it.linkMode.appendLinks(it.documentation, tokens.sorted().joinToString(" #", prefix = "#"))
}
documentation.add("{@code $prefix${it.name}} – $doc")
}
}
return documentation
}
private fun StructMember.error(msg: String) {
throw IllegalArgumentException("$msg [${[email protected]}, member: $name]")
}
private fun validate() {
members.filter { it has AutoSizeMember }.forEach {
val autoSize = it[AutoSizeMember]
autoSize.references.forEachIndexed { i, reference ->
val bufferParam = members.firstOrNull { it.name == reference }
if ( bufferParam == null )
it.error("Reference does not exist: AutoSize($reference)")
else {
when {
bufferParam.nativeType !is PointerType
-> it.error("Reference must be a pointer type: AutoSize($reference)")
!bufferParam.nativeType.isPointerData -> it.error("Reference must not be a opaque pointer: AutoSize($reference)")
bufferParam.nativeType is StructType && !(bufferParam is StructMemberBuffer || bufferParam is StructMemberArray)
-> it.error("Reference must be a struct buffer: AutoSize($reference)")
autoSize.atLeastOne && !bufferParam.has(nullable)
-> it.error("The \"atLeastOne\" option requires references to be nullable: AutoSize($reference)")
}
}
}
}
}
override fun PrintWriter.generateJava() {
validate()
val nativeLayout = [email protected] || members.isEmpty()
if ( !nativeLayout && preamble.hasNativeDirectives )
kotlin.io.println("\tUnnecessary native directives in struct: $packageName.$className")
print(HEADER)
println("package $packageName;\n")
println("import java.nio.*;\n")
val mallocable = mutable || usageOutput || (usageInput && !usageResultPointer)
if ( mallocable || members.any { it.nativeType is PointerType && it.nativeType.mapping === PointerMapping.DATA_POINTER } )
println("import org.lwjgl.*;")
println("import org.lwjgl.system.*;\n")
fun Struct.hasChecks(): Boolean =
mutableMembers.any {
it is StructMemberArray ||
it.nativeType is CharSequenceType ||
(it.nativeType is PointerType && (!it.has(NullableMember) && (it.nativeType !is StructType || it.nativeType.includesPointer))) ||
(it.isNestedStructDefinition && (it.nativeType as StructType).definition.hasChecks())
}
if ( hasChecks() )
println("import static org.lwjgl.system.Checks.*;")
println("import static org.lwjgl.system.MemoryUtil.*;")
if ( nativeLayout || mallocable )
println("import static org.lwjgl.system.MemoryStack.*;")
println()
preamble.printJava(this)
printDocumentation()
print("${access.modifier}class $className extends ")
print(if (extends == null)
"Struct${if ( mallocable ) " implements NativeResource" else ""}"
else
extends.className
)
print(""" {
/** The struct size in bytes. */
public static final int SIZEOF;
public static final int ALIGNOF;
""")
if ( members.isNotEmpty() && (!nativeLayout || visibleMembers.any()) ) {
val memberCount = getMemberCount(members)
// Member offset fields
if ( visibleMembers.any() ) {
print("""
/** The struct member offsets. */
public static final int
""")
generateOffsetFields(visibleMembers)
println(";")
}
print("""
static {""")
if ( static != null )
print("""
$static
""")
// Member offset initialization
if ( nativeLayout ) {
print("""
try ( MemoryStack stack = stackPush() ) {
IntBuffer offsets = stack.mallocInt(${memberCount + 1});
SIZEOF = offsets(memAddress(offsets));
""")
generateOffsetInit(members, indentation = "\t\t\t")
println("""
ALIGNOF = offsets.get($memberCount);
}""")
} else {
print("""
Layout layout = """)
generateLayout(this@Struct)
print(""";
SIZEOF = layout.getSize();
ALIGNOF = layout.getAlignment();
""")
generateOffsetInit(members)
}
print("\t}")
} else {
print("""
static {""")
if (static != null)
print("""
$static
""")
print("""
try ( MemoryStack stack = stackPush() ) {
IntBuffer offsets = stack.mallocInt(1);
SIZEOF = offsets(memAddress(offsets));
ALIGNOF = offsets.get(0);
}
}""")
}
if ( nativeLayout )
print("""
private static native int offsets(long buffer);""")
print("""
$className(long address, ByteBuffer container) {
super(address, container);
}
/**
* Creates a {@link $className} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
* visible to the struct instance and vice versa.
*
* <p>The created instance holds a strong reference to the container object.</p>
*/
${access.modifier}$className(ByteBuffer container) {
this(memAddress(container), checkContainer(container, SIZEOF));
}
@Override
public int sizeof() { return SIZEOF; }
""")
val members = visibleMembers
if ( members.any() ) {
println()
generateGetters(AccessMode.INSTANCE, members)
if ( hasMutableMembers ) {
val mutableMembers = mutableMembers.filter { !it.has(AutoSizeMember) || it[AutoSizeMember].keepSetter(mutableMembers) }
println()
generateSetters(AccessMode.INSTANCE, mutableMembers)
if ( mutableMembers.singleOrNull() == null && !containsUnion ) {
val javadoc = "Initializes this struct with the specified values."
if ( generateAlternativeMultiSetter(mutableMembers) )
generateMultiSetter(javadoc, mutableMembers, Struct::generateAlternativeMultiSetterParameters, Struct::generateAlternativeMultiSetterSetters, MultiSetterMode.ALTER)
else
generateMultiSetter(javadoc, mutableMembers, Struct::generateMultiSetterParameters, Struct::generateMultiSetterSetters)
}
print("""
/** Unsafe version of {@link #set($className) set}. */${if (extends != null) """
@Override""" else ""}
public $className nset(long struct) {
memCopy(struct, $ADDRESS, SIZEOF);
return this;
}
/**
* Copies the specified struct data to this struct.
*
* @param src the source struct
*
* @return this struct
*/
public $className set($className src) {
return nset(src.$ADDRESS);
}
""")
}
}
print("""
// -----------------------------------
""")
// Factory constructors
if ( mallocable ) {
print("""
/** Returns a new {@link $className} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
public static $className malloc() {
return create(nmemAlloc(SIZEOF));
}
/** Returns a new {@link $className} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
public static $className calloc() {
return create(nmemCalloc(1, SIZEOF));
}
/** Returns a new {@link $className} instance allocated with {@link BufferUtils}. */
public static $className create() {
return new $className(BufferUtils.createByteBuffer(SIZEOF));
}
""")
}
print("""
/** Returns a new {@link $className} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
public static $className create(long address) {
return address == NULL ? null : new $className(address, null);
}
""")
if ( mallocable ) {
print("""
/**
* Returns a new {@link $className.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static Buffer malloc(int $BUFFER_CAPACITY_PARAM) {
return create(nmemAlloc($BUFFER_CAPACITY_PARAM * SIZEOF), $BUFFER_CAPACITY_PARAM);
}
/**
* Returns a new {@link $className.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static Buffer calloc(int $BUFFER_CAPACITY_PARAM) {
return create(nmemCalloc($BUFFER_CAPACITY_PARAM, SIZEOF), $BUFFER_CAPACITY_PARAM);
}
/**
* Returns a new {@link $className.Buffer} instance allocated with {@link BufferUtils}.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static Buffer create(int $BUFFER_CAPACITY_PARAM) {
return new Buffer(BufferUtils.createByteBuffer($BUFFER_CAPACITY_PARAM * SIZEOF));
}
""")
}
print("""
/**
* Create a {@link $className.Buffer} instance at the specified memory.
*
* @param address the memory address
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static Buffer create(long address, int $BUFFER_CAPACITY_PARAM) {
return address == NULL ? null : new Buffer(address, null, -1, 0, $BUFFER_CAPACITY_PARAM, $BUFFER_CAPACITY_PARAM);
}
""")
if ( mallocable ) {
print("""
// -----------------------------------
/** Returns a new {@link $className} instance allocated on the thread-local {@link MemoryStack}. */
public static $className mallocStack() {
return mallocStack(stackGet());
}
/** Returns a new {@link $className} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
public static $className callocStack() {
return callocStack(stackGet());
}
/**
* Returns a new {@link $className} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
*/
public static $className mallocStack(MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, SIZEOF));
}
/**
* Returns a new {@link $className} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
*/
public static $className callocStack(MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
}
/**
* Returns a new {@link $className.Buffer} instance allocated on the thread-local {@link MemoryStack}.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static Buffer mallocStack(int $BUFFER_CAPACITY_PARAM) {
return mallocStack($BUFFER_CAPACITY_PARAM, stackGet());
}
/**
* Returns a new {@link $className.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
*
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static Buffer callocStack(int $BUFFER_CAPACITY_PARAM) {
return callocStack($BUFFER_CAPACITY_PARAM, stackGet());
}
/**
* Returns a new {@link $className.Buffer} instance allocated on the specified {@link MemoryStack}.
*
* @param stack the stack from which to allocate
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static Buffer mallocStack(int $BUFFER_CAPACITY_PARAM, MemoryStack stack) {
return create(stack.nmalloc(ALIGNOF, $BUFFER_CAPACITY_PARAM * SIZEOF), $BUFFER_CAPACITY_PARAM);
}
/**
* Returns a new {@link $className.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
*
* @param stack the stack from which to allocate
* @param $BUFFER_CAPACITY_PARAM the buffer capacity
*/
public static Buffer callocStack(int $BUFFER_CAPACITY_PARAM, MemoryStack stack) {
return create(stack.ncalloc(ALIGNOF, $BUFFER_CAPACITY_PARAM, SIZEOF), $BUFFER_CAPACITY_PARAM);
}
""")
}
print("""
// -----------------------------------
""")
if ( members.any() ) {
generateStaticGetters(members)
println()
if ( hasMutableMembers ) {
generateStaticSetters(mutableMembers)
println()
if ( validations.any() ) {
println(
""" /**
* Validates pointer members that should not be $NULL.
*
* @param $STRUCT the struct to validate
*/
public static void validate(long $STRUCT) {
${validations.joinToString("\n")}
}
/**
* Calls {@link #validate(long)} for each struct contained in the specified struct array.
*
* @param array the struct array to validate
* @param count the number of structs in {@code array}
*/
public static void validate(long array, int count) {
for ( int i = 0; i < count; i++ )
validate(array + i * SIZEOF);
}
""")
}
}
}
println("\t// -----------------------------------")
print("""
/** An array of {@link $className} structs. */
public static class Buffer extends """)
print(if (extends == null)
"StructBuffer<$className, Buffer>${if (mallocable) " implements NativeResource" else ""}"
else
"${extends.className}.Buffer"
)
print(""" {
/**
* Creates a new {@link $className.Buffer} instance backed by the specified container.
*
* Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
* will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
* by {@link $className#SIZEOF}, and its mark will be undefined.
*
* <p>The created buffer instance holds a strong reference to the container object.</p>
*/""")
print(if (extends == null)
"""
public Buffer(ByteBuffer container) {
super(container, container.remaining() / SIZEOF);
}"""
else
"""
public Buffer(ByteBuffer container) {
this(container, container.remaining() / SIZEOF);
}
private Buffer(ByteBuffer container, int remaining) {
super(memAddress(container), container, -1, 0, remaining, remaining);
}""")
print("""
Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
super(address, container, mark, pos, lim, cap);
}
@Override
protected Buffer self() {
return this;
}
@Override
protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
return new Buffer(address, container, mark, pos, lim, cap);
}
@Override
protected $className newInstance(long address) {
return new $className(address, container);
}
@Override
protected int sizeof() {
return SIZEOF;
}
""")
if ( members.any() ) {
println()
generateGetters(AccessMode.FLYWEIGHT, members)
if ( hasMutableMembers ) {
println()
generateSetters(AccessMode.FLYWEIGHT, mutableMembers.filter { !it.has(AutoSizeMember) || it[AutoSizeMember].keepSetter(mutableMembers) })
}
}
print("""
}
}""")
}
private fun PrintWriter.generateOffsetFields(
members: Sequence<StructMember>,
indentation: String = "\t\t",
parentField: String = "",
more: Boolean = false
) {
members.forEachWithMore(more) { member, more ->
if ( member.name === ANONYMOUS && member.isNestedStruct ) {
generateOffsetFields(member.nestedMembers, indentation, parentField, more) // recursion
} else {
if ( more )
println(",")
val field = member.offsetField(parentField)
print("$indentation$field")
// Output nested field offsets
if ( member.isNestedStructDefinition )
generateOffsetFields(member.nestedMembers, "$indentation\t", field, true) // recursion
}
}
}
private fun getMemberCount(members: List<StructMember>): Int {
var count = members.size
for (member in members.asSequence().filter { it.isNestedStructDefinition })
count += getMemberCount((member.nativeType as StructType).definition.members) // recursion
return count
}
private fun PrintWriter.generateOffsetInit(
members: List<StructMember>,
indentation: String = "\t\t",
parentField: String = "",
offset: Int = 0
): Int {
var index = offset
members.forEach {
if ( it.name === ANONYMOUS && it.isNestedStruct ) {
index = generateOffsetInit((it.nativeType as StructType).definition.members, indentation, parentField, index + 1) // recursion
} else {
val field = it.offsetField(parentField)
try {
if ( it is StructMemberPadding )
return@forEach
println("$indentation$field = ${if ( nativeLayout ) "offsets.get" else "layout.offsetof"}($index);")
} finally {
index++
}
// Output nested fields
if ( it.isNestedStructDefinition )
index = generateOffsetInit((it.nativeType as StructType).definition.members, "$indentation\t", field, index) // recursion
}
}
return index
}
private fun PrintWriter.generateLayout(
struct: Struct,
indentation: String = "\t\t",
parentField: String = ""
) {
println("__${if ( struct.union ) "union" else "struct"}(")
struct.members.forEachWithMore { it, more ->
val field = it.offsetField(parentField)
if ( more )
println(",")
if ( it is StructMemberPadding ) {
print("$indentation\t__padding(${it.size}, ${it.condition ?: "true"})")
} else if ( it.isNestedStructDefinition ) {
print("$indentation\t")
generateLayout((it.nativeType as StructType).definition, "$indentation\t", field)
//print(")")
} else {
val size: String
val alignment: String
if ( it.nativeType is StructType && !it.nativeType.includesPointer ) {
size = "${it.nativeType.javaMethodType}.SIZEOF"
alignment = "${it.nativeType.javaMethodType}.ALIGNOF"
} else {
size = if ( it.nativeType is PointerType || it.nativeType.mapping === PrimitiveMapping.POINTER )
"POINTER_SIZE"
else
(it.nativeType.mapping as PrimitiveMapping).bytes.toString()
alignment = size
}
if ( it is StructMemberArray )
print("$indentation\t__array($size${if ( size != alignment ) ", $alignment" else ""}, ${it.size})")
else
print("$indentation\t__member($size${if ( size != alignment ) ", $alignment" else ""})")
}
}
print("\n$indentation)")
}
private fun PrintWriter.generateMultiSetter(
javaDoc: String,
members: Sequence<StructMember>,
generateParameters: (Struct, PrintWriter, Sequence<StructMember>, String, MultiSetterMode, Boolean) -> Unit,
generateSetters: (Struct, PrintWriter, Sequence<StructMember>, String, MultiSetterMode) -> Unit,
mode: MultiSetterMode = MultiSetterMode.NORMAL
) {
print("""
/** $javaDoc */
public $className set(
""")
generateParameters(this@Struct, this, members, "", mode, false)
println("""
) {""")
generateSetters(this@Struct, this, members, "", mode)
print("""
return this;
}
""")
}
private fun generateMultiSetterParameters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode, more: Boolean) {
writer.apply {
members.forEachWithMore(more) { it, more ->
val method = it.field(parentMember)
if ( it.isNestedStructDefinition ) {
generateMultiSetterParameters(writer, it.nestedMembers, method, mode, more) // recursion
return@forEachWithMore
}
if ( more )
println(",")
print("\t\t")
val param = it.field(parentMember)
print("${it.nativeType.javaMethodType} $param")
}
}
}
private fun generateMultiSetterSetters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode) {
writer.apply {
members.forEach {
val field = it.field(parentMember)
if ( it.isNestedStructDefinition )
generateMultiSetterSetters(writer, it.nestedMembers, field, mode) // recursion
else
println("\t\t$field($field);")
}
}
}
private fun generateAlternativeMultiSetter(members: Sequence<StructMember>): Boolean =
members.any {
if ( it.isNestedStructDefinition )
generateAlternativeMultiSetter(it.nestedMembers) // recursion
else
it is StructMemberArray || it.nativeType.isPointerData
}
private fun generateAlternativeMultiSetterParameters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode, more: Boolean) {
writer.apply {
members.forEachWithMore(more) { it, more ->
val method = it.field(parentMember)
if ( it.isNestedStructDefinition ) {
generateAlternativeMultiSetterParameters(writer, it.nestedMembers, method, mode, more) // recursion
return@forEachWithMore
}
if ( more )
println(",")
print("\t\t")
val param = it.field(parentMember)
print(
if (it is StructMemberArray) {
if ( it is StructMemberCharArray ) {
when ( mode ) {
MultiSetterMode.NORMAL,
MultiSetterMode.ALTER -> "ByteBuffer $param"
}
} else if ( it.nativeType is StructType ) {
if ( it.nativeType.includesPointer )
"PointerBuffer $param"
else
"${it.nativeType.javaMethodType}.Buffer $param"
} else
"${it.primitiveMapping.toPointer.javaMethodType.simpleName} $param"
} else if ( it.nativeType.isPointerData && it.nativeType is StructType ) {
val structType = it.nativeType.javaMethodType
if ( it is StructMemberBuffer )
"$structType.Buffer $param"
else
"$structType $param"
} else
"${it.nativeType.javaMethodType} $param"
)
}
}
}
private fun generateAlternativeMultiSetterSetters(writer: PrintWriter, members: Sequence<StructMember>, parentMember: String, mode: MultiSetterMode) {
writer.apply {
members.forEach {
val field = it.field(parentMember)
if ( it.isNestedStructDefinition )
generateAlternativeMultiSetterSetters(writer, it.nestedMembers, field, mode) // recursion
else
println("\t\t$field($field);")
}
}
}
private fun getFieldOffset(
m: StructMember,
parentStruct: Struct?,
parentField: String
) = if ( parentStruct == null || parentField.isEmpty() )
"$className.${m.offsetField}"
else if ( parentStruct.className === ANONYMOUS )
"${parentField}_${m.offsetField}"
else
throw IllegalStateException()
private val StructMember.pointerValue: String get() = if ( has(nullable) ) "value" else "checkPointer(value)"
private val StructMember.isNullable: Boolean
get() = has(nullable) ||
getReferenceMember(AutoSizeMember, name)?.get(AutoSizeMember)?.optional ?: false ||
(this is StructMemberArray && this.validSize < this.size)
private val StructMember.addressValue: String get() = if ( isNullable ) "addressSafe(value)" else "value.address()"
private val StructMember.memAddressValue: String get() = if ( isNullable ) "memAddressSafe(value)" else "memAddress(value)"
private val StructMember.autoSize: String get() = "n$name($STRUCT)"
.let {
val type = this.nativeType as IntegerType
if ( !type.unsigned )
it
else {
val mapping = type.mapping as PrimitiveMapping
when ( mapping.bytes ) {
1 -> "Byte.toUnsignedInt($it)"
2 -> "Short.toUnsignedInt($it)"
else -> it
}
}
}
.let {
val factor = this[AutoSizeMember].factor
if (factor != null)
"($it ${factor.expression()})"
else
it
}
.let { if (4 < (nativeType.mapping as PrimitiveMapping).bytes && !it.startsWith('(') ) "(int)$it" else it }
private fun PrintWriter.setRemaining(m: StructMember) {
// do not do this if the AutoSize parameter auto-sizes multiple members
val capacity = members.firstOrNull { it has AutoSizeMember && it[AutoSizeMember].let { it.atLeastOne || (it.dependent.isEmpty() && it.reference == m.name) } }
if ( capacity != null ) {
val autoSize = capacity[AutoSizeMember]
val autoSizeExpression = "value.remaining()"
.let {
if (autoSize.factor != null)
"($it ${autoSize.factor.expressionInv()})"
else
it
}
.let { if ((capacity.nativeType.mapping as PrimitiveMapping).bytes < 4) "(${capacity.nativeType.mapping.javaMethodType})$it" else it }
print(if ( m has nullable || autoSize.optional ) {
if ( autoSize.atLeastOne )
" if ( value != null ) n${capacity.name}($STRUCT, $autoSizeExpression);"
else if ( m has nullable && !autoSize.optional )
" if ( value != null ) n${capacity.name}($STRUCT, $autoSizeExpression);"
else
" n${capacity.name}($STRUCT, value == null ? 0 : $autoSizeExpression);"
} else
" n${capacity.name}($STRUCT, $autoSizeExpression);"
)
}
}
private fun PrintWriter.generateStaticSetters(
members: Sequence<StructMember>,
parentStruct: Struct? = null,
parentMember: String = "",
parentField: String = ""
) {
members.forEach {
val setter = it.field(parentMember)
val field = getFieldOffset(it, parentStruct, parentField)
if ( it.isNestedStruct ) {
val nestedStruct = (it.nativeType as StructType).definition
val structType = nestedStruct.className
if ( structType === ANONYMOUS )
generateStaticSetters(
it.nestedMembers, nestedStruct,
if ( it.name === ANONYMOUS ) parentMember else setter,
if ( it.name === ANONYMOUS ) parentField else field
)
else {
println("\t/** Unsafe version of {@link #$setter($structType) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, $structType value) { memCopy(value.$ADDRESS, $STRUCT + $field, $structType.SIZEOF); }")
}
} else {
// Setter
if ( it !is StructMemberArray && !it.nativeType.isPointerData ) {
if ( it.nativeType is CallbackType ) {
println("\t/** Unsafe version of {@link #$setter(${it.nativeType.javaMethodType}) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, long value) { memPutAddress($STRUCT + $field, ${it.pointerValue}); }")
} else {
val javaType = it.nativeType.nativeMethodType
val bufferMethod = getBufferMethod(it, javaType)
println(
if ( it has AutoSizeMember )
"\t/** Sets the specified value to the {@code ${it.name}} field of the specified {@code struct}. */"
else
"\t/** Unsafe version of {@link #$setter($javaType) $setter}. */"
)
print("\tpublic static void n$setter(long $STRUCT, $javaType value) { memPut$bufferMethod($STRUCT + $field, ")
if ( javaType == "boolean" )
print("value ? (byte)1 : (byte)0")
else if ( it.nativeType.mapping === PointerMapping.OPAQUE_POINTER )
print(it.pointerValue)
else
print("value")
println("); }")
}
}
// Alternative setters
if ( it is StructMemberArray ) {
if ( it.nativeType is StructType ) {
val structType = it.nativeType.javaMethodType
if ( it.nativeType.includesPointer ) {
println("\t/** Unsafe version of {@link #$setter(PointerBuffer) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, PointerBuffer value) {")
println("\t\tif ( CHECKS ) checkBufferGT(value, ${it.size});")
println("\t\tmemCopy(memAddress(value), $STRUCT + $field, value.remaining() * POINTER_SIZE);")
println("\t}")
println("\t/** Unsafe version of {@link #$setter(int, $structType) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, int index, $structType value) { memPutAddress($STRUCT + $field + index * POINTER_SIZE, ${it.addressValue}); }")
} else {
println("\t/** Unsafe version of {@link #$setter($structType.Buffer) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, $structType.Buffer value) {")
println("\t\tif ( CHECKS ) checkBufferGT(value, ${it.size});")
println("\t\tmemCopy(value.$ADDRESS, $STRUCT + $field, value.remaining() * $structType.SIZEOF);")
println("\t}")
println("\t/** Unsafe version of {@link #$setter(int, $structType) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, int index, $structType value) { memCopy(value.$ADDRESS, $STRUCT + $field + index * $structType.SIZEOF, $structType.SIZEOF); }")
}
} else if ( it is StructMemberCharArray ) {
val mapping = it.nativeType.mapping as PrimitiveMapping
val byteSize = if ( mapping.bytes == 1 ) it.size else "${it.size} * ${mapping.bytes}"
println("\t/** Unsafe version of {@link #$setter(ByteBuffer) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, ByteBuffer value) {")
println("\t\tif ( CHECKS ) {")
println("\t\t\tcheckNT${mapping.bytes}(value);")
println("\t\t\tcheckBufferGT(value, $byteSize);")
println("\t\t}")
println("\t\tmemCopy(memAddress(value), $STRUCT + $field, value.remaining());")
println("\t}")
} else {
val mapping = it.primitiveMapping
val bytesPerElement = if ( mapping === PrimitiveMapping.POINTER ) "POINTER_SIZE" else mapping.bytes.toString()
val bufferType = mapping.toPointer.javaMethodType.simpleName
println("\t/** Unsafe version of {@link #$setter($bufferType) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, $bufferType value) {")
println("\t\tif ( CHECKS ) checkBufferGT(value, ${it.size});")
println("\t\tmemCopy(memAddress(value), $STRUCT + $field, value.remaining() * $bytesPerElement);")
println("\t}")
println("\t/** Unsafe version of {@link #$setter(int, ${mapping.javaMethodType}) $setter}. */")
print("\tpublic static void n$setter(long $STRUCT, int index, ${mapping.javaMethodType} value) { ")
print(
when ( mapping ) {
PrimitiveMapping.POINTER -> "memPutAddress($STRUCT + $field + index * POINTER_SIZE, value);"
else -> "memPut${bufferMethodMap[mapping.javaMethodType.simpleName]}($STRUCT + $field + index * $bytesPerElement, value);"
}
)
println(" }")
}
} else if ( it.nativeType is CharSequenceType ) {
val mapping = it.nativeType.charMapping
println("\t/** Unsafe version of {@link #$setter(ByteBuffer) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, ByteBuffer value) { ")
println("\t\tif ( CHECKS ) checkNT${mapping.bytes}Safe(value); ")
println("\t\tmemPutAddress($STRUCT + $field, ${it.memAddressValue});")
println("\t}")
} else if ( it.nativeType.isPointerData ) {
if ( it.nativeType is StructType ) {
val structType = it.nativeType.javaMethodType
if ( it is StructMemberBuffer ) {
println("\t/** Unsafe version of {@link #$setter($structType.Buffer) $setter}. */")
print("\tpublic static void n$setter(long $STRUCT, $structType.Buffer value) { memPutAddress($STRUCT + $field, ${it.addressValue});")
setRemaining(it)
println(" }")
} else {
println("\t/** Unsafe version of {@link #$setter($structType) $setter}. */")
println("\tpublic static void n$setter(long $STRUCT, $structType value) { memPutAddress($STRUCT + $field, ${it.addressValue}); }")
}
} else {
val bufferType = it.nativeType.javaMethodType
println("\t/** Unsafe version of {@link #$setter($bufferType) $setter}. */")
print("\tpublic static void n$setter(long $STRUCT, $bufferType value) { memPutAddress($STRUCT + $field, ${it.memAddressValue});")
setRemaining(it)
println(" }")
}
}
}
}
}
private fun PrintWriter.generateSetters(
accessMode: AccessMode,
members: Sequence<StructMember>,
parentMember: String = ""
) {
val n = if ( accessMode === AccessMode.INSTANCE ) "n" else "$className.n"
members.forEach {
val setter = it.field(parentMember)
val field = it.name
val indent = accessMode.indent
val overrides = extends != null && extends.members.any { parentMember -> parentMember.name == it.name }
val returnType = if ( accessMode === AccessMode.INSTANCE )
className
else
"$className.Buffer"
if ( it.isNestedStruct ) {
val structType = it.nativeType.javaMethodType
if ( structType === ANONYMOUS )
generateSetters(accessMode, it.nestedMembers, if ( field === ANONYMOUS ) parentMember else field)
else {
println("$indent/** Copies the specified {@link $structType} to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter($structType value) { $n$setter($ADDRESS, value); return this; }")
}
} else {
// Setter
if ( it !is StructMemberArray && !it.nativeType.isPointerData ) {
if ( it.nativeType is CallbackType ) {
val callbackType = it.nativeType.javaMethodType
println("$indent/** Sets the address of the specified {@link $callbackType} to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter($callbackType value) { $n$setter($ADDRESS, addressSafe(value)); return this; }")
} else {
println("$indent/** Sets the specified value to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(${it.nativeType.javaMethodType} value) { $n$setter($ADDRESS, value${if ( it.nativeType.mapping === PrimitiveMapping.BOOLEAN4 ) " ? 1 : 0" else ""}); return this; }")
}
}
// Alternative setters
if ( it is StructMemberArray ) {
if ( it.nativeType is StructType ) {
val structType = it.nativeType.javaMethodType
if ( it.nativeType.includesPointer ) {
println("$indent/** Copies the specified {@link PointerBuffer} to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(PointerBuffer value) { $n$setter($ADDRESS, value); return this; }")
println("$indent/** Copies the address of the specified {@link $structType} at the specified index of the {@code $field} field. */")
} else {
println("$indent/** Copies the specified {@link $structType.Buffer} to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter($structType.Buffer value) { $n$setter($ADDRESS, value); return this; }")
println("$indent/** Copies the specified {@link $structType} at the specified index of the {@code $field} field. */")
}
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(int index, $structType value) { $n$setter($ADDRESS, index, value); return this; }")
} else if ( it is StructMemberCharArray ) {
println("$indent/** Copies the specified encoded string to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(ByteBuffer value) { $n$setter($ADDRESS, value); return this; }")
} else {
val bufferType = it.primitiveMapping.toPointer.javaMethodType.simpleName
println("$indent/** Copies the specified {@link $bufferType} to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter($bufferType value) { $n$setter($ADDRESS, value); return this; }")
println("$indent/** Sets the specified value at the specified index of the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(int index, ${it.nativeType.mapping.javaMethodType} value) { $n$setter($ADDRESS, index, value); return this; }")
}
} else if ( it.nativeType is CharSequenceType ) {
println("$indent/** Sets the address of the specified encoded string to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter(ByteBuffer value) { $n$setter($ADDRESS, value); return this; }")
} else if ( it.nativeType.isPointerData ) {
val pointerType = it.nativeType.javaMethodType
if ( it is StructMemberBuffer ) {
println("$indent/** Sets the address of the specified {@link $pointerType.Buffer} to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter($pointerType.Buffer value) { $n$setter($ADDRESS, value); return this; }")
} else {
println("$indent/** Sets the address of the specified {@link $pointerType} to the {@code $field} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $returnType $setter($pointerType value) { $n$setter($ADDRESS, value); return this; }")
}
}
}
}
}
private fun PrintWriter.generateStaticGetters(
members: Sequence<StructMember>,
parentStruct: Struct? = null,
parentMember: String = "",
parentField: String = ""
) {
members.forEach {
val getter = it.field(parentMember)
val field = getFieldOffset(it, parentStruct, parentField)
if ( it.isNestedStruct ) {
val nestedStruct = (it.nativeType as StructType).definition
val structType = nestedStruct.className
if ( structType === ANONYMOUS )
generateStaticGetters(
it.nestedMembers, nestedStruct,
if ( it.name === ANONYMOUS ) parentMember else getter,
if ( it.name === ANONYMOUS ) parentField else field
)
else {
println("\t/** Unsafe version of {@link #$getter}. */")
println("\tpublic static $structType n$getter(long $STRUCT) { return $structType.create($STRUCT + $field); }")
}
} else {
// Getter
if ( it !is StructMemberArray && !it.nativeType.isPointerData ) {
println("\t/** Unsafe version of {@link #$getter}. */")
if ( it.nativeType is CallbackType ) {
println("\tpublic static long n$getter(long $STRUCT) { return memGetAddress($STRUCT + $field); }")
} else {
val javaType = it.nativeType.nativeMethodType
val bufferMethod = getBufferMethod(it, javaType)
print("\tpublic static $javaType n$getter(long $STRUCT) { return memGet$bufferMethod($STRUCT + $field)")
if ( it.nativeType.mapping === PrimitiveMapping.BOOLEAN )
print(" != 0")
println("; }")
}
}
// Alternative getters
if ( it is StructMemberArray ) {
if ( it.nativeType is StructType ) {
val nestedStruct = it.nativeType.javaMethodType
if ( it.nativeType.includesPointer ) {
val capacity = getReferenceMember(AutoSizeMember, it.name)
println("\t/** Unsafe version of {@link #$getter}. */")
println("\tpublic static PointerBuffer n$getter(long $STRUCT) {")
println("\t\treturn memPointerBuffer($STRUCT + $field, ${if ( capacity == null ) it.size else capacity.autoSize});")
println("\t}")
println("\t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("\tpublic static $nestedStruct n$getter(long $STRUCT, int index) {")
println("\t\treturn $nestedStruct.create(memGetAddress($STRUCT + $field + index * POINTER_SIZE));")
println("\t}")
} else {
val capacity = getReferenceMember(AutoSizeMember, it.name)
println("\t/** Unsafe version of {@link #$getter}. */")
println("\tpublic static $nestedStruct.Buffer n$getter(long $STRUCT) {")
println("\t\treturn $nestedStruct.create($STRUCT + $field, ${if ( capacity == null ) it.size else capacity.autoSize});")
println("\t}")
println("\t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("\tpublic static $nestedStruct n$getter(long $STRUCT, int index) {")
println("\t\treturn $nestedStruct.create($STRUCT + $field + index * $nestedStruct.SIZEOF);")
println("\t}")
}
} else if ( it is StructMemberCharArray ) {
val mapping = it.nativeType.mapping as CharMapping
val byteSize = if ( mapping.bytes == 1 ) it.size else "${it.size} * ${mapping.bytes}"
println("\t/** Unsafe version of {@link #$getter}. */")
println("\tpublic static ByteBuffer n$getter(long $STRUCT) { return memByteBuffer($STRUCT + $field, $byteSize); }")
println("\t/** Unsafe version of {@link #${getter}String}. */")
println("\tpublic static String n${getter}String(long $STRUCT) { return mem${mapping.charset}($STRUCT + $field); }")
} else {
val mapping = it.primitiveMapping
val bufferType = mapping.toPointer.javaMethodType.simpleName
println("\t/** Unsafe version of {@link #$getter}. */")
println("\tpublic static $bufferType n$getter(long $STRUCT) {")
println("\t\treturn mem$bufferType($STRUCT + $field, ${it.size});")
println("\t}")
val javaType = mapping.javaMethodType.simpleName
val bufferMethod = getBufferMethod(it, javaType)
println("\t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("\tpublic static $javaType n$getter(long $STRUCT, int index) { return memGet$bufferMethod($STRUCT + $field + index * ${mapping.bytes}); }")
}
} else if ( it.nativeType is CharSequenceType ) {
val mapping = it.nativeType.charMapping
println("\t/** Unsafe version of {@link #$getter}. */")
println("\tpublic static ByteBuffer n$getter(long $STRUCT) { return memByteBufferNT${mapping.bytes}(memGetAddress($STRUCT + $field)); }")
println("\t/** Unsafe version of {@link #${getter}String}. */")
println("\tpublic static String n${getter}String(long $STRUCT) { return mem${mapping.charset}(memGetAddress($STRUCT + $field)); }")
} else if ( it.nativeType is StructType ) {
val structType = it.nativeType.javaMethodType
println("\t/** Unsafe version of {@link #$getter}. */")
println(if ( it is StructMemberBuffer ) {
val capacity = getReferenceMember(AutoSizeMember, it.name)
if ( capacity == null )
"\tpublic static $structType.Buffer n$getter(long $STRUCT, int $BUFFER_CAPACITY_PARAM) { return $structType.create(memGetAddress($STRUCT + $field), $BUFFER_CAPACITY_PARAM); }"
else
"\tpublic static $structType.Buffer n$getter(long $STRUCT) { return $structType.create(memGetAddress($STRUCT + $field), ${capacity.autoSize}); }"
} else
"\tpublic static $structType n$getter(long $STRUCT) { return $structType.create(memGetAddress($STRUCT + $field)); }"
)
} else if ( it.nativeType.isPointerData ) {
val bufferType = it.nativeType.javaMethodType
val capacity = getReferenceMember(AutoSizeMember, it.name)
if ( capacity == null ) {
println("\t/** Unsafe version of {@link #$getter(int) $getter}. */")
println("\tpublic static $bufferType n$getter(long $STRUCT, int $BUFFER_CAPACITY_PARAM) { return mem$bufferType(memGetAddress($STRUCT + $field), $BUFFER_CAPACITY_PARAM); }")
} else {
println("\t/** Unsafe version of {@link #$getter() $getter}. */")
println("\tpublic static $bufferType n$getter(long $STRUCT) { return mem$bufferType(memGetAddress($STRUCT + $field), ${capacity.autoSize}); }")
}
}
}
}
}
private fun PrintWriter.generateGetters(
accessMode: AccessMode,
members: Sequence<StructMember>,
parentMember: String = ""
) {
val n = if ( accessMode === AccessMode.INSTANCE ) "n" else "$className.n"
members.forEach {
val getter = it.field(parentMember)
val indent = accessMode.indent
val overrides = extends != null && extends.members.any { parentMember -> parentMember.name == it.name }
if ( it.isNestedStruct ) {
val nestedStruct = (it.nativeType as StructType).definition
val structType = nestedStruct.className
if ( structType === ANONYMOUS )
generateGetters(accessMode, it.nestedMembers, if ( it.name === ANONYMOUS ) parentMember else getter)
else {
println("$indent/** Returns a {@link $structType} view of the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $structType $getter() { return $n$getter($ADDRESS); }")
}
} else {
// Getter
if ( it !is StructMemberArray && !it.nativeType.isPointerData ) {
if ( it.nativeType is CallbackType ) {
val callbackType = it.nativeType.className
println("$indent/** Returns the {@code $callbackType} instance at the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $callbackType $getter() { return $callbackType.create($n$getter($ADDRESS)); }")
} else {
println("$indent/** Returns the value of the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public ${it.nativeType.javaMethodType} $getter() { return $n$getter($ADDRESS)${if ( it.nativeType.mapping === PrimitiveMapping.BOOLEAN4 ) " != 0" else ""}; }")
}
}
// Alternative getters
if ( it is StructMemberArray ) {
if ( it.nativeType is StructType ) {
val structType = it.nativeType.javaMethodType
if ( it.nativeType.includesPointer ) {
println("$indent/** Returns a {@link PointerBuffer} view of the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public PointerBuffer $getter() { return $n$getter($ADDRESS); }")
println("$indent/** Returns a {@link $structType} view of the pointer at the specified index of the {@code $getter}. */")
if (overrides) println("$indent@Override")
println("${indent}public $structType $getter(int index) { return $n$getter($ADDRESS, index); }")
} else {
println("$indent/** Returns a {@link $structType}.Buffer view of the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $structType.Buffer $getter() { return $n$getter($ADDRESS); }")
println("$indent/** Returns a {@link $structType} view of the struct at the specified index of the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $structType $getter(int index) { return $n$getter($ADDRESS, index); }")
}
} else if ( it is StructMemberCharArray ) {
println("$indent/** Returns a {@link ByteBuffer} view of the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public ByteBuffer $getter() { return $n$getter($ADDRESS); }")
println("$indent/** Decodes the null-terminated string stored in the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public String ${getter}String() { return $n${getter}String($ADDRESS); }")
} else {
val bufferType = it.primitiveMapping.toPointer.javaMethodType.simpleName
println("$indent/** Returns a {@link $bufferType} view of the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $bufferType $getter() { return $n$getter($ADDRESS); }")
println("$indent/** Returns the value at the specified index of the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public ${it.nativeType.javaMethodType} $getter(int index) { return $n$getter($ADDRESS, index); }")
}
} else if ( it.nativeType is CharSequenceType ) {
println("$indent/** Returns a {@link ByteBuffer} view of the null-terminated string pointed to by the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public ByteBuffer $getter() { return $n$getter($ADDRESS); }")
println("$indent/** Decodes the null-terminated string pointed to by the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public String ${getter}String() { return $n${getter}String($ADDRESS); }")
} else if ( it.nativeType is StructType ) {
val structType = it.nativeType.javaMethodType
if ( it is StructMemberBuffer ) {
if ( getReferenceMember(AutoSizeMember, it.name) == null ) {
println("""$indent/**
$indent * Returns a {@link $structType.Buffer} view of the struct array pointed to by the {@code $getter} field.
$indent *
$indent * @param $BUFFER_CAPACITY_PARAM the number of elements in the returned buffer
$indent */""")
if (overrides) println("$indent@Override")
println("${indent}public $structType.Buffer $getter(int $BUFFER_CAPACITY_PARAM) { return $n$getter($ADDRESS, $BUFFER_CAPACITY_PARAM); }")
} else {
println("$indent/** Returns a {@link $structType.Buffer} view of the struct array pointed to by the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $structType.Buffer $getter() { return $n$getter($ADDRESS); }")
}
} else {
println("$indent/** Returns a {@link $structType} view of the struct pointed to by the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $structType $getter() { return $n$getter($ADDRESS); }")
}
} else if ( it.nativeType.isPointerData ) {
val bufferType = it.nativeType.javaMethodType
if ( getReferenceMember(AutoSizeMember, it.name) == null ) {
println(
"""$indent/**
$indent * Returns a {@link $bufferType} view of the data pointed to by the {@code $getter} field.
$indent *
$indent * @param $BUFFER_CAPACITY_PARAM the number of elements in the returned buffer
$indent */""")
if (overrides) println("$indent@Override")
println("${indent}public $bufferType $getter(int $BUFFER_CAPACITY_PARAM) { return $n$getter($ADDRESS, $BUFFER_CAPACITY_PARAM); }")
} else {
println("$indent/** Returns a {@link $bufferType} view of the data pointed to by the {@code $getter} field. */")
if (overrides) println("$indent@Override")
println("${indent}public $bufferType $getter() { return $n$getter($ADDRESS); }")
}
}
}
}
}
private fun getBufferMethod(member: StructMember, javaType: String) = if ( member.nativeType.isPointer )
"Address"
else
bufferMethodMap[javaType] ?: throw UnsupportedOperationException("Unsupported struct member java type: $className.${member.name} ($javaType)")
override val skipNative: Boolean get() = !nativeLayout && members.isNotEmpty()
override fun PrintWriter.generateNative() {
print(HEADER)
nativeImport("<stddef.h>")
nativeDirective(
"""#ifdef LWJGL_WINDOWS
#define alignof __alignof
#else
#include <stdalign.h>
#endif""")
preamble.printNative(this)
println("""
EXTERN_C_EXIT
JNIEXPORT jint JNICALL Java_${nativeFileNameJNI}_offsets(JNIEnv *$JNIENV, jclass clazz, jlong bufferAddress) {
jint *buffer = (jint *)(intptr_t)bufferAddress;
UNUSED_PARAMS($JNIENV, clazz)
""")
if ( virtual ) {
// NOTE: Assumes a plain struct definition (no nested structs, no unions)
println("\ttypedef struct $nativeName {")
for (m in members) {
print("\t\t${m.nativeType.name}")
if ( m.nativeType is PointerType && !m.nativeType.includesPointer ) {
if ( !m.nativeType.name.endsWith('*') )
print(' ')
print('*')
}
println(" ${m.name};")
}
println("\t} $nativeName;\n")
}
var index = 0
if ( members.isNotEmpty() ) {
index = generateNativeMembers(members)
println()
}
println(
""" buffer[$index] = alignof($nativeName);
return sizeof($nativeName);
}
EXTERN_C_EXIT""")
}
private fun PrintWriter.generateNativeMembers(members: List<StructMember>, offset: Int = 0, prefix: String = ""): Int {
var index = offset
members.forEach {
if ( it.name === ANONYMOUS && it.isNestedStruct ) {
index = generateNativeMembers((it.nativeType as StructType).definition.members, index + 1, prefix) // recursion
} else {
println("\tbuffer[$index] = (jint)offsetof($nativeName, $prefix${it.name});")
index++
if ( it.isNestedStruct ) {
// Output nested structs
val structType = it.nativeType as StructType
if ( structType.name === ANONYMOUS )
index = generateNativeMembers(structType.definition.members, index, prefix = "$prefix${it.name}.") // recursion
}
}
}
return index
}
}
private val PointerType?.toStruct: Struct? get() = if (this == null)
null
else if (this is StructType)
this.definition
else {
this.elementType.let {
if (it !is PointerType)
throw IllegalStateException("Invalid struct parent type specified.")
it.toStruct
}
}
fun struct(
packageName: String,
className: String,
nativeSubPath: String = "",
nativeName: String = className,
virtual: Boolean = false,
mutable: Boolean = true,
extends: PointerType? = null,
nativeLayout: Boolean = false,
init: (Struct.() -> Unit)? = null
): StructType {
val struct = Struct(packageName, className, nativeSubPath, nativeName, false, virtual, mutable, extends.toStruct, nativeLayout)
if ( init != null ) {
struct.init()
Generator.register(struct)
}
return struct.nativeType
}
fun union(
packageName: String,
className: String,
nativeSubPath: String = "",
nativeName: String = className,
virtual: Boolean = false,
mutable: Boolean = true,
extends: PointerType? = null,
nativeLayout: Boolean = false,
init: (Struct.() -> Unit)? = null
): StructType {
val struct = Struct(packageName, className, nativeSubPath, nativeName, true, virtual, mutable, extends.toStruct, nativeLayout)
if ( init != null ) {
struct.init()
Generator.register(struct)
}
return struct.nativeType
} | bsd-3-clause | ad94e6afb913de4fc4a09605adc0d488 | 36.509815 | 216 | 0.664977 | 3.752399 | false | false | false | false |
codehz/container | app/src/main/java/one/codehz/container/widget/RecycleViewWithEmptySupport.kt | 1 | 2140 | package one.codehz.container.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import one.codehz.container.R
class RecycleViewWithEmptySupport @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defStyle: Int = 0)
: RecyclerView(context, attributeSet, defStyle) {
var emptyDrawable: Drawable = ColorDrawable(Color.RED)
private var isEmpty = false
init {
attributeSet?.let {
context.obtainStyledAttributes(it, R.styleable.RecycleViewWithEmptySupport).apply {
this.getResourceId(R.styleable.RecycleViewWithEmptySupport_emptyDrawable, 0).apply {
if (this != 0)
emptyDrawable = context.getDrawable(this)
}
}.recycle()
}
addOnLayoutChangeListener { view, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
emptyDrawable.setBounds(0, 0, right - left, bottom - top)
}
}
private val emptyObserver = object : AdapterDataObserver() {
override fun onChanged() {
isEmpty = adapter.itemCount == 0
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
isEmpty = false
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
isEmpty = adapter.itemCount == 0
}
}
override fun setAdapter(adapter: Adapter<*>?) {
super.setAdapter(adapter)
adapter?.apply {
try {
registerAdapterDataObserver(emptyObserver)
} catch (ignored: Exception) {
}
emptyObserver.onChanged()
}
}
override fun onDrawForeground(canvas: Canvas?) {
super.onDrawForeground(canvas)
}
override fun onDraw(c: Canvas) {
super.onDraw(c)
if (isEmpty) {
emptyDrawable.draw(c)
}
}
} | gpl-3.0 | 9c91a5cf2d4020e8b2854ff4f0205e93 | 30.955224 | 132 | 0.635047 | 4.930876 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/creator/exception/SetupException.kt | 1 | 1174 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.creator.exception
import javax.swing.JComponent
sealed class SetupException(val j: JComponent) : Exception() {
abstract val error: String
}
class EmptyFieldSetupException(j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>Please fill in all required fields</html>"
}
class BadListSetupException(j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>Please enter as a comma separated list</html>"
}
class EmptyInputSetupException(j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>Please fill in all required fields</html>"
}
class InvalidClassNameException(j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>Class Name must be a valid Java identifier and cannot be the default package</html>"
}
class OtherSetupException(private val msg: String, j: JComponent) : SetupException(j) {
override val error: String
get() = "<html>$msg</html>"
}
| mit | a33976771e134aad56e1c2b63d21f4b6 | 26.302326 | 107 | 0.70017 | 3.913333 | false | false | false | false |
elect86/helloTriangle | src/main/kotlin/gl4/helloTriangle.kt | 1 | 10137 | package gl4
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.KeyListener
import com.jogamp.newt.event.WindowAdapter
import com.jogamp.newt.event.WindowEvent
import com.jogamp.newt.opengl.GLWindow
import com.jogamp.opengl.*
import com.jogamp.opengl.GL2ES2.GL_DEBUG_SEVERITY_HIGH
import com.jogamp.opengl.GL2ES2.GL_DEBUG_SEVERITY_MEDIUM
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL4.GL_MAP_COHERENT_BIT
import com.jogamp.opengl.GL4.GL_MAP_PERSISTENT_BIT
import com.jogamp.opengl.util.Animator
import framework.Semantic
import glm.L
import glm.SIZE
import glm.f
import glm.glm
import glm.mat.Mat4
import glm.vec._2.Vec2
import glm.vec._3.Vec3
import uno.buffer.*
import uno.debug.GlDebugOutput
import uno.glsl.Program
import java.nio.ByteBuffer
import kotlin.properties.Delegates
/**
* Created by elect on 06/03/17.
*/
fun main(args: Array<String>) {
HelloTriangleK().setup()
}
class HelloTriangleK : GLEventListener, KeyListener {
var window by Delegates.notNull<GLWindow>()
val animator = Animator()
val vertexData = floatArrayOf(
-1f, -1f, 1f, 0f, 0f,
+0f, +2f, 0f, 0f, 1f,
+1f, -1f, 0f, 1f, 0f)
val elementData = shortArrayOf(0, 2, 1)
object Buffer {
val VERTEX = 0
val ELEMENT = 1
val GLOBAL_MATRICES = 2
val MODEL_MATRIX = 3
val MAX = 4
}
val bufferName = intBufferBig(Buffer.MAX)
val vertexArrayName = intBufferBig(1)
val clearColor = floatBufferBig(4)
val clearDepth = floatBufferBig(1)
val matBuffer = floatBufferBig(16)
var globalMatricesPointer by Delegates.notNull<ByteBuffer>()
var modelMatrixPointer by Delegates.notNull<ByteBuffer>()
// https://jogamp.org/bugzilla/show_bug.cgi?id=1287
val bug1287 = true
var program by Delegates.notNull<Program>()
var start = 0L
fun setup() {
val glProfile = GLProfile.get(GLProfile.GL3)
val glCapabilities = GLCapabilities(glProfile)
window = GLWindow.create(glCapabilities)
window.title = "Hello Triangle (enhanced)"
window.setSize(1024, 768)
window.contextCreationFlags = GLContext.CTX_OPTION_DEBUG
window.isVisible = true
window.addGLEventListener(this)
window.addKeyListener(this)
animator.add(window)
animator.start()
window.addWindowListener(object : WindowAdapter() {
override fun windowDestroyed(e: WindowEvent?) {
animator.stop(); System.exit(1); }
})
}
override fun init(drawable: GLAutoDrawable) {
val gl = drawable.gl.gL4
initDebug(gl)
initBuffers(gl)
initVertexArray(gl)
program = Program(gl, this::class.java, "shaders/gl4", "hello-triangle.vert", "hello-triangle.frag")
gl.glEnable(GL_DEPTH_TEST)
start = System.currentTimeMillis()
}
fun initDebug(gl: GL4) = with(gl) {
window.context.addGLDebugListener(GlDebugOutput())
// Turn off all the debug
glDebugMessageControl(
GL_DONT_CARE, // source
GL_DONT_CARE, // type
GL_DONT_CARE, // severity
0, null, // id
false)// count
// enabled
// Turn on all OpenGL Errors, shader compilation/linking errors, or highly-dangerous undefined behavior
glDebugMessageControl(
GL_DONT_CARE,
GL_DONT_CARE,
GL_DEBUG_SEVERITY_HIGH,
0, null,
true)
// Turn on all major performance warnings, shader compilation/linking warnings or the use of deprecated functions
glDebugMessageControl(
GL_DONT_CARE,
GL_DONT_CARE,
GL_DEBUG_SEVERITY_MEDIUM,
0, null,
true)
}
fun initBuffers(gl: GL4) = with(gl) {
val vertexBuffer = vertexData.toFloatBuffer()
val elementBuffer = elementData.toShortBuffer()
glCreateBuffers(Buffer.MAX, bufferName)
if (!bug1287) {
glNamedBufferStorage(bufferName[Buffer.VERTEX], vertexBuffer.SIZE.L, vertexBuffer, GL_STATIC_DRAW)
glNamedBufferStorage(bufferName[Buffer.ELEMENT], elementBuffer.SIZE.L, elementBuffer, GL_STATIC_DRAW)
glNamedBufferStorage(bufferName[Buffer.GLOBAL_MATRICES], Mat4.SIZE.L * 2, null, GL_MAP_WRITE_BIT)
glNamedBufferStorage(bufferName[Buffer.MODEL_MATRIX], Mat4.SIZE.L, null, GL_MAP_WRITE_BIT)
} else {
glBindBuffer(GL_ARRAY_BUFFER, bufferName[Buffer.VERTEX])
glBufferStorage(GL_ARRAY_BUFFER, vertexBuffer.SIZE.L, vertexBuffer, 0)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufferName[Buffer.ELEMENT])
glBufferStorage(GL_ELEMENT_ARRAY_BUFFER, elementBuffer.SIZE.L, elementBuffer, 0)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
val uniformBufferOffset = intBufferBig(1)
glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, uniformBufferOffset)
val globalBlockSize = glm.max(Mat4.SIZE * 2, uniformBufferOffset[0])
val modelBlockSize = glm.max(Mat4.SIZE, uniformBufferOffset[0])
glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.GLOBAL_MATRICES])
glBufferStorage(GL_UNIFORM_BUFFER, globalBlockSize.L, null, GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT)
glBindBuffer(GL_UNIFORM_BUFFER, 0)
glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.MODEL_MATRIX])
glBufferStorage(GL_UNIFORM_BUFFER, modelBlockSize.L, null, GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT)
glBindBuffer(GL_UNIFORM_BUFFER, 0)
uniformBufferOffset.destroy()
}
destroyBuffers(vertexBuffer, elementBuffer)
// map the transform buffers and keep them mapped
globalMatricesPointer = glMapNamedBufferRange(
bufferName[Buffer.GLOBAL_MATRICES], // buffer
0, // offset
Mat4.SIZE.L * 2, // size
GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT or GL_MAP_INVALIDATE_BUFFER_BIT) // flags
modelMatrixPointer = glMapNamedBufferRange(
bufferName[Buffer.MODEL_MATRIX],
0,
Mat4.SIZE.L,
GL_MAP_WRITE_BIT or GL_MAP_PERSISTENT_BIT or GL_MAP_COHERENT_BIT or GL_MAP_INVALIDATE_BUFFER_BIT)
}
fun initVertexArray(gl: GL4) = with(gl) {
glCreateVertexArrays(1, vertexArrayName)
glVertexArrayAttribBinding(vertexArrayName[0], Semantic.Attr.POSITION, Semantic.Stream.A)
glVertexArrayAttribBinding(vertexArrayName[0], Semantic.Attr.COLOR, Semantic.Stream.A)
glVertexArrayAttribFormat(vertexArrayName[0], Semantic.Attr.POSITION, Vec2.length, GL_FLOAT, false, 0)
glVertexArrayAttribFormat(vertexArrayName[0], Semantic.Attr.COLOR, Vec3.length, GL_FLOAT, false, Vec2.SIZE)
glEnableVertexArrayAttrib(vertexArrayName[0], Semantic.Attr.POSITION)
glEnableVertexArrayAttrib(vertexArrayName[0], Semantic.Attr.COLOR)
glVertexArrayElementBuffer(vertexArrayName[0], bufferName[Buffer.ELEMENT])
glVertexArrayVertexBuffer(vertexArrayName[0], Semantic.Stream.A, bufferName[Buffer.VERTEX], 0, Vec2.SIZE + Vec3.SIZE)
}
override fun display(drawable: GLAutoDrawable) = with(drawable.gl.gL4) {
// update view matrix
run {
val view = Mat4()
view.to(globalMatricesPointer, Mat4.SIZE)
}
glClearBufferfv(GL_COLOR, 0, clearColor.put(1f, .5f, 0f, 1f))
glClearBufferfv(GL_DEPTH, 0, clearDepth.put(0, 1f))
run {
// update model matrix based on time
val now = System.currentTimeMillis()
val diff = (now - start).f / 1_000f
// Here we build the matrix that will multiply our original vertex positions. We scale, half and rotate it.
val model = Mat4()
model
.scale_(0.5f)
.rotate_(diff, 0f, 0f, 1f)
.to(modelMatrixPointer)
}
glUseProgram(program.name)
glBindVertexArray(vertexArrayName[0])
glBindBufferBase(
GL_UNIFORM_BUFFER, // target
Semantic.Uniform.TRANSFORM0, // index
bufferName[Buffer.GLOBAL_MATRICES]) // buffer
glBindBufferBase(
GL_UNIFORM_BUFFER,
Semantic.Uniform.TRANSFORM1,
bufferName[Buffer.MODEL_MATRIX])
glDrawElements(
GL_TRIANGLES, // primitive mode
elementData.size, // element count
GL_UNSIGNED_SHORT, // element type
0) // element offset
glUseProgram(0)
glBindVertexArray(0)
}
override fun reshape(drawable: GLAutoDrawable, x: Int, y: Int, width: Int, height: Int) = with(drawable.gl.gL4) {
glm.ortho(-1f, 1f, -1f, 1f, 1f, -1f) to globalMatricesPointer
glViewport(x, y, width, height)
}
override fun dispose(drawable: GLAutoDrawable) = with(drawable.gl.gL4) {
glUnmapNamedBuffer(bufferName[Buffer.GLOBAL_MATRICES])
glUnmapNamedBuffer(bufferName[Buffer.MODEL_MATRIX])
glDeleteProgram(program.name)
glDeleteVertexArrays(1, vertexArrayName)
glDeleteBuffers(Buffer.MAX, bufferName)
destroyBuffers(vertexArrayName, bufferName, clearColor, clearDepth)
}
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_ESCAPE) {
/* Note: calling System.exit() synchronously inside the draw, reshape or init callbacks can lead to
deadlocks on certain platforms (in particular, X11) because the JAWT's locking routines cause a global
AWT lock to be grabbed. Run the exit routine in another thread. */
Thread { window.destroy() }.start()
}
}
override fun keyReleased(e: KeyEvent) {}
} | mit | e8cbe66112797cd07818f7f8f3d256b5 | 32.793333 | 137 | 0.640328 | 4.216722 | false | false | false | false |
adgvcxz/Diycode | app/src/main/java/com/adgvcxz/diycode/widget/MarkdownView.kt | 1 | 2614 | package com.adgvcxz.diycode.widget
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
/**
* zhaowei
* Created by zhaowei on 2017/4/10.
*/
class MarkdownView: WebView {
private val imageLinkPattern = "\\[(.*)!\\[(.*)\\]\\((.*)\\)(.*)\\]\\((.*)\\)"
private val imageLinkReplace = "<a href=\"$5\" >$1<img src=\"$3\" />$4</a>"
private val imagePattern = "!\\[(.*)\\]\\((.*)\\)"
private val imageReplace = "<img class=\"gcs-img-sign\" src=\"$2\" />"
var markdownText: String = ""
set(value) {
var text = value.replace(imageLinkPattern, imageLinkReplace).replace(imagePattern, imageReplace)
text = text.replace("\n", "\\\\n").replace("'", "\\\'").replace("\r", "")
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
field = "javascript:preview('$text')"
} else {
field = "preview('$text')"
}
invalidate()
}
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet?): super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context, attrs, defStyleAttr) {
init()
}
@SuppressLint("SetJavaScriptEnabled")
private fun init() {
if (isInEditMode) {
return
}
val settings = settings
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.databaseEnabled = true
loadUrl("file:///android_asset/html/preview.html")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
settings.allowUniversalAccessFromFileURLs = true
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
}
setWebChromeClient(object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
if (newProgress == 100) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
loadUrl(markdownText)
} else {
evaluateJavascript(markdownText, null)
}
}
}
})
}
} | apache-2.0 | 160630d09e309316a57f9aeafed065f2 | 32.101266 | 112 | 0.574981 | 4.51468 | false | false | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/editor/formatter/blocks/LuaTableBlock.kt | 2 | 2517 | /*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.editor.formatter.blocks
import com.intellij.formatting.Alignment
import com.intellij.formatting.ChildAttributes
import com.intellij.formatting.Indent
import com.intellij.formatting.Wrap
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.tang.intellij.lua.editor.formatter.LuaFormatContext
import com.tang.intellij.lua.psi.LuaTableExpr
import com.tang.intellij.lua.psi.LuaTableField
import com.tang.intellij.lua.psi.LuaTypes
class LuaTableBlock(psi: LuaTableExpr, wrap: Wrap?, alignment: Alignment?, indent: Indent, ctx: LuaFormatContext)
: LuaScriptBlock(psi, wrap, alignment, indent, ctx) {
private val childAlign = Alignment.createAlignment()
private val assignAlign:Alignment = Alignment.createAlignment(true)
override fun buildChild(child: PsiElement, indent: Indent?): LuaScriptBlock {
if (child is LuaTableField) {
return LuaTableFieldBlock(assignAlign, child, null, childAlign, Indent.getNormalIndent(), ctx)
} else if (child is PsiComment) {
return LuaScriptBlock(child, null, null, Indent.getNormalIndent(), ctx)
}
return super.buildChild(child, indent)
}
override fun getChildAttributes(newChildIndex: Int) =
ChildAttributes(Indent.getNormalIndent(), childAlign)
}
class LuaTableFieldBlock(private val assignAlign:Alignment, psi: LuaTableField, wrap: Wrap?, alignment: Alignment?, indent: Indent, ctx: LuaFormatContext)
: LuaScriptBlock(psi, wrap, alignment, indent, ctx) {
override fun buildChild(child: PsiElement, indent: Indent?): LuaScriptBlock {
if (ctx.luaSettings.ALIGN_TABLE_FIELD_ASSIGN) {
if (child.node.elementType == LuaTypes.ASSIGN) {
return createBlock(child, Indent.getNoneIndent(), assignAlign)
}
}
return super.buildChild(child, indent)
}
} | apache-2.0 | dfd4472204ad1023dc666db8be0e9266 | 39.612903 | 154 | 0.734207 | 4.079417 | false | false | false | false |
inorichi/tachiyomi-extensions | src/ru/risensteam/src/eu/kanade/tachiyomi/extension/ru/risensteam/RisensTeam.kt | 1 | 5064 | package eu.kanade.tachiyomi.extension.ru.risensteam
import com.github.salomonbrys.kotson.fromJson
import com.github.salomonbrys.kotson.get
import com.github.salomonbrys.kotson.int
import com.github.salomonbrys.kotson.nullString
import com.github.salomonbrys.kotson.string
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.network.asObservableSuccess
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.MangasPage
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import rx.Observable
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Locale
class RisensTeam : HttpSource() {
override val name = "Risens Team"
override val baseUrl = "https://risens.team"
override val lang = "ru"
override val supportsLatest = false
override val versionId: Int = 2
private val gson by lazy { Gson() }
// Popular (source only returns manga sorted by latest)
override fun popularMangaRequest(page: Int): Request {
return GET("https://risens.team/api/title/list?type=1", headers)
}
private fun mangaFromJson(json: JsonElement): SManga {
return SManga.create().apply {
url = "${json["id"].int}/${json["furl"].string}"
title = json["title"].string
thumbnail_url = baseUrl + json["poster"].string
description = json["description"].nullString
status = try { if (json["active"].int == 1) SManga.ONGOING else SManga.UNKNOWN } catch (_: Exception) { SManga.UNKNOWN }
}
}
override fun popularMangaParse(response: Response): MangasPage {
val mangas = gson.fromJson<JsonArray>(response.body!!.string())
.map { json -> mangaFromJson(json) }
return MangasPage(mangas, false)
}
// Latest
override fun latestUpdatesRequest(page: Int): Request = throw UnsupportedOperationException("Not used")
override fun latestUpdatesParse(response: Response): MangasPage = throw UnsupportedOperationException("Not used")
// Search
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val rbody =
"""{"queryString":"$query","limit":3}""".toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
return POST("$baseUrl/api/title/search", headers, rbody)
}
override fun searchMangaParse(response: Response): MangasPage = popularMangaParse(response)
// Details
override fun fetchMangaDetails(manga: SManga): Observable<SManga> {
return client.newCall(apiMangaDetailsRequest(manga))
.asObservableSuccess()
.map { response ->
mangaDetailsParse(response).apply { initialized = true }
}
}
private fun apiMangaDetailsRequest(manga: SManga): Request {
return GET("$baseUrl/api/title/show/${manga.url.substringBefore("/")}")
}
override fun mangaDetailsRequest(manga: SManga): Request {
return GET("$baseUrl/title/${manga.url}")
}
override fun mangaDetailsParse(response: Response): SManga {
return mangaFromJson(gson.fromJson<JsonObject>(response.body!!.string()))
}
// Chapters
override fun chapterListRequest(manga: SManga): Request = apiMangaDetailsRequest(manga)
override fun chapterListParse(response: Response): List<SChapter> {
return gson.fromJson<JsonObject>(response.body!!.string())["entities"].asJsonArray.map { json ->
SChapter.create().apply {
url = json["id"].int.toString()
name = listOfNotNull(json["label"].nullString, json["name"].nullString).joinToString(" - ")
date_upload = json["updated_at"].toDate()
}
}
}
private val simpleDateFormat by lazy {
SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
}
private fun JsonElement.toDate(): Long {
val date = this.nullString ?: return 0
return try {
simpleDateFormat.parse(date)?.time ?: 0
} catch (e: ParseException) {
0
}
}
// Pages
override fun pageListRequest(chapter: SChapter): Request {
return GET("$baseUrl/api/yandex/chapter/${chapter.url}", headers)
}
override fun pageListParse(response: Response): List<Page> {
return gson.fromJson<JsonArray>(response.body!!.string())
.mapIndexed { i, json -> Page(i, "", json.string) }
}
override fun imageUrlParse(response: Response): String = throw UnsupportedOperationException("Not used")
}
| apache-2.0 | 66e99e6b4b6db1069e2f6be4029ee446 | 34.412587 | 132 | 0.685427 | 4.607825 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/toilets_fee/AddToiletsFee.kt | 1 | 984 | package de.westnordost.streetcomplete.quests.toilets_fee
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
import de.westnordost.streetcomplete.quests.YesNoQuestAnswerFragment
class AddToiletsFee(o: OverpassMapDataDao) : SimpleOverpassQuestType<Boolean>(o) {
override val tagFilters = "nodes, ways with amenity = toilets and access !~ private|customers and !fee"
override val commitMessage = "Add toilets fee"
override val icon = R.drawable.ic_quest_toilet_fee
override fun getTitle(tags: Map<String, String>) = R.string.quest_toiletsFee_title
override fun createForm() = YesNoQuestAnswerFragment()
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.add("fee", if (answer) "yes" else "no")
}
}
| gpl-3.0 | 529c157fe017e37a64c6c783edb75068 | 43.727273 | 107 | 0.789634 | 4.513761 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/NotificationsActivity.kt | 1 | 15597 | package com.habitrpg.android.habitica.ui.activities
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RatingBar
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.databinding.ActivityNotificationsBinding
import com.habitrpg.android.habitica.extensions.fromHtml
import com.habitrpg.android.habitica.helpers.ExceptionHandler
import com.habitrpg.android.habitica.models.inventory.QuestContent
import com.habitrpg.android.habitica.ui.viewmodels.NotificationsViewModel
import com.habitrpg.common.habitica.models.Notification
import com.habitrpg.common.habitica.models.notifications.GroupTaskApprovedData
import com.habitrpg.common.habitica.models.notifications.GroupTaskNeedsWorkData
import com.habitrpg.common.habitica.models.notifications.GroupTaskRequiresApprovalData
import com.habitrpg.common.habitica.models.notifications.GuildInvitationData
import com.habitrpg.common.habitica.models.notifications.NewChatMessageData
import com.habitrpg.common.habitica.models.notifications.NewStuffData
import com.habitrpg.common.habitica.models.notifications.PartyInvitationData
import com.habitrpg.common.habitica.models.notifications.QuestInvitationData
import com.habitrpg.common.habitica.models.notifications.UnallocatedPointsData
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import javax.inject.Inject
class NotificationsActivity : BaseActivity(), androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener {
private lateinit var binding: ActivityNotificationsBinding
@Inject
lateinit var inventoryRepository: InventoryRepository
@Inject
lateinit var socialRepository: SocialRepository
val viewModel: NotificationsViewModel by viewModels()
var inflater: LayoutInflater? = null
override fun getLayoutResId(): Int = R.layout.activity_notifications
override fun getContentView(): View {
binding = ActivityNotificationsBinding.inflate(layoutInflater)
return binding.root
}
private var notifications: List<Notification> = emptyList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar(binding.toolbar)
inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as? LayoutInflater
compositeSubscription.add(
viewModel.getNotifications().subscribe(
{
this.setNotifications(it)
viewModel.markNotificationsAsSeen(it)
},
ExceptionHandler.rx()
)
)
binding.notificationsRefreshLayout.setOnRefreshListener(this)
}
override fun injectActivity(component: UserComponent?) {
component?.inject(this)
}
override fun onSupportNavigateUp(): Boolean {
if (supportFragmentManager.backStackEntryCount > 0) {
onBackPressed()
return true
}
return super.onSupportNavigateUp()
}
override fun onRefresh() {
binding.notificationsRefreshLayout.isRefreshing = true
lifecycleScope.launch(ExceptionHandler.coroutine()) {
viewModel.refreshNotifications()
binding.notificationsRefreshLayout.isRefreshing = false
}
}
private fun setNotifications(notifications: List<Notification>) {
this.notifications = notifications
binding.notificationItems.removeAllViewsInLayout()
if (notifications.isEmpty()) {
displayNoNotificationsView()
} else {
displayNotificationsListView(notifications)
}
}
private fun displayNoNotificationsView() {
binding.notificationItems.showDividers = LinearLayout.SHOW_DIVIDER_NONE
binding.notificationItems.addView(inflater?.inflate(R.layout.no_notifications, binding.notificationItems, false))
}
private fun displayNotificationsListView(notifications: List<Notification>) {
binding.notificationItems.showDividers = LinearLayout.SHOW_DIVIDER_MIDDLE or LinearLayout.SHOW_DIVIDER_END
binding.notificationItems.addView(
createNotificationsHeaderView(notifications.count())
)
notifications.map {
val item: View? = when (it.type) {
Notification.Type.NEW_CHAT_MESSAGE.type -> createNewChatMessageNotification(it)
Notification.Type.NEW_STUFF.type -> createNewStuffNotification(it)
Notification.Type.UNALLOCATED_STATS_POINTS.type -> createUnallocatedStatsNotification(it)
Notification.Type.NEW_MYSTERY_ITEMS.type -> createMysteryItemsNotification(it)
Notification.Type.GROUP_TASK_NEEDS_WORK.type -> createGroupTaskNeedsWorkNotification(it)
Notification.Type.GROUP_TASK_APPROVED.type -> createGroupTaskApprovedNotification(it)
Notification.Type.GROUP_TASK_REQUIRES_APPROVAL.type -> createGroupTaskNeedsApprovalNotification(it)
Notification.Type.PARTY_INVITATION.type -> createPartyInvitationNotification(it)
Notification.Type.GUILD_INVITATION.type -> createGuildInvitationNotification(it)
Notification.Type.QUEST_INVITATION.type -> createQuestInvitationNotification(it)
else -> null
}
if (item != null) {
binding.notificationItems.addView(item)
}
}
}
private fun createNotificationsHeaderView(notificationCount: Int): View? {
val header = inflater?.inflate(R.layout.notifications_header, binding.notificationItems, false)
val badge = header?.findViewById(R.id.notifications_title_badge) as? TextView
badge?.text = notificationCount.toString()
val dismissAllButton = header?.findViewById(R.id.dismiss_all_button) as? Button
dismissAllButton?.setOnClickListener { viewModel.dismissAllNotifications(notifications) }
return header
}
private fun createNewChatMessageNotification(notification: Notification): View? {
val data = notification.data as? NewChatMessageData
val stringId = if (viewModel.isPartyMessage(data)) R.string.new_msg_party else R.string.new_msg_guild
return createDismissableNotificationItem(
notification,
fromHtml(getString(stringId, data?.group?.name))
)
}
private fun createNewStuffNotification(notification: Notification): View? {
val data = notification.data as? NewStuffData
val text = if (data?.title != null) {
fromHtml("<b>" + getString(R.string.new_bailey_update) + "</b><br>" + data.title)
} else {
fromHtml("<b>" + getString(R.string.new_bailey_update) + "</b>")
}
return createDismissableNotificationItem(
notification,
text,
R.drawable.notifications_bailey
)
}
private fun createUnallocatedStatsNotification(notification: Notification): View? {
val data = notification.data as? UnallocatedPointsData
return createDismissableNotificationItem(
notification,
fromHtml(getString(R.string.unallocated_stats_points, data?.points.toString())),
R.drawable.notification_stat_sparkles
)
}
private fun createMysteryItemsNotification(notification: Notification): View? {
return createDismissableNotificationItem(
notification,
fromHtml(getString(R.string.new_subscriber_item)),
R.drawable.notification_mystery_item
)
}
private fun createGroupTaskNeedsWorkNotification(notification: Notification): View? {
val data = notification.data as? GroupTaskNeedsWorkData
val message = convertGroupMessageHtml(data?.message ?: "")
return createDismissableNotificationItem(
notification,
fromHtml(message),
null,
R.color.yellow_5
)
}
private fun createGroupTaskApprovedNotification(notification: Notification): View? {
val data = notification.data as? GroupTaskApprovedData
val message = convertGroupMessageHtml(data?.message ?: "")
return createDismissableNotificationItem(
notification,
fromHtml(message),
null,
R.color.green_10
)
}
private fun createGroupTaskNeedsApprovalNotification(notification: Notification): View? {
val data = notification.data as? GroupTaskRequiresApprovalData
val message = convertGroupMessageHtml(data?.message ?: "")
val item = createActionableNotificationItem(
notification,
fromHtml(message)
)
// Hide for now
item?.visibility = View.GONE
return item
}
/**
* Group task notifications have the message text in the notification data as HTML
* with <span class="notification-bold"> tags around emphasized words. So we just
* convert the span-tags to strong-tags to display correct parts as bold, since
* Html.fromHtml does not support CSS.
*/
private fun convertGroupMessageHtml(message: String): String {
// Using positive lookbehind to make sure "span" is preceded by "<" or "</"
val pattern = "(?<=</?)span".toRegex()
return message.replace(pattern, "strong")
}
private fun createDismissableNotificationItem(
notification: Notification,
messageText: CharSequence,
imageResourceId: Int? = null,
textColor: Int? = null
): View? {
val item = inflater?.inflate(R.layout.notification_item, binding.notificationItems, false)
val container = item?.findViewById(R.id.notification_item) as? View
container?.setOnClickListener {
val resultIntent = Intent()
resultIntent.putExtra("notificationId", notification.id)
setResult(Activity.RESULT_OK, resultIntent)
finish()
}
val dismissButton = item?.findViewById(R.id.dismiss_button) as? ImageView
dismissButton?.setOnClickListener { viewModel.dismissNotification(notification) }
val messageTextView = item?.findViewById(R.id.message_text) as? TextView
messageTextView?.text = messageText
if (imageResourceId != null) {
val notificationImage = item?.findViewById(R.id.notification_image) as? ImageView
notificationImage?.setImageResource(imageResourceId)
notificationImage?.visibility = View.VISIBLE
}
if (textColor != null) {
messageTextView?.setTextColor(ContextCompat.getColor(this, textColor))
}
return item
}
private fun createPartyInvitationNotification(notification: Notification): View? {
val data = notification.data as? PartyInvitationData
return createActionableNotificationItem(
notification,
fromHtml(getString(R.string.invited_to_party_notification, data?.invitation?.name))
)
}
private fun createGuildInvitationNotification(notification: Notification): View? {
val data = notification.data as? GuildInvitationData
val stringId = if (data?.invitation?.publicGuild == false) R.string.invited_to_private_guild else R.string.invited_to_public_guild
return createActionableNotificationItem(
notification,
fromHtml(getString(stringId, data?.invitation?.name)),
data?.invitation?.publicGuild == true
)
}
private fun createQuestInvitationNotification(notification: Notification): View? {
val data = notification.data as? QuestInvitationData
val view = createActionableNotificationItem(notification, "", true)
// hide view until we have loaded quest data and populated the values
view?.visibility = View.GONE
lifecycleScope.launch(ExceptionHandler.coroutine()) {
val questContent = inventoryRepository.getQuestContent(data?.questKey ?: "").firstOrNull()
if (questContent != null) {
updateQuestInvitationView(view, questContent)
}
}
return view
}
private fun updateQuestInvitationView(view: View?, questContent: QuestContent) {
val messageTextView = view?.findViewById(R.id.message_text) as? TextView
messageTextView?.text = fromHtml(getString(R.string.invited_to_quest, questContent.text))
val questObjectiveLabelView = view?.findViewById(R.id.quest_objective_label) as? TextView
val questObjectiveTextView = view?.findViewById(R.id.quest_objective_text) as? TextView
val questDifficultyLabelView = view?.findViewById(R.id.difficulty_label) as? TextView
questDifficultyLabelView?.text = getText(R.string.difficulty)
questDifficultyLabelView?.append(":")
val questDifficultyView = view?.findViewById(R.id.quest_difficulty) as? RatingBar
if (questContent.isBossQuest) {
questObjectiveLabelView?.text = getString(R.string.defeat)
questObjectiveTextView?.text = questContent.boss?.name
questDifficultyView?.rating = questContent.boss?.str ?: 1f
} else {
questObjectiveLabelView?.text = getString(R.string.collect)
val collectionList = questContent.collect?.map { it.count.toString() + " " + it.text }
questObjectiveTextView?.text = collectionList?.joinToString(", ")
questDifficultyView?.rating = 1f
}
questObjectiveLabelView?.append(":")
val questDetailView = view?.findViewById(R.id.quest_detail_view) as? View
questDetailView?.visibility = View.VISIBLE
view?.visibility = View.VISIBLE
}
private fun createActionableNotificationItem(
notification: Notification,
messageText: CharSequence,
openable: Boolean = false
): View? {
val item = inflater?.inflate(R.layout.notification_item_actionable, binding.notificationItems, false)
if (openable) {
val container = item?.findViewById(R.id.notification_item) as? View
container?.setOnClickListener {
val resultIntent = Intent()
resultIntent.putExtra("notificationId", notification.id)
setResult(Activity.RESULT_OK, resultIntent)
finish()
}
}
val acceptButton = item?.findViewById(R.id.accept_button) as? Button
acceptButton?.setOnClickListener {
viewModel.accept(notification.id)
}
val rejectButton = item?.findViewById(R.id.reject_button) as? Button
rejectButton?.setOnClickListener {
viewModel.reject(notification.id)
}
val messageTextView = item?.findViewById(R.id.message_text) as? TextView
messageTextView?.text = messageText
return item
}
private fun fromHtml(text: String): CharSequence {
return text.fromHtml()
}
}
| gpl-3.0 | 70d195716b14f17cea8487776ea32b25 | 38.788265 | 138 | 0.691607 | 5.090405 | false | false | false | false |
vmiklos/vmexam | osm/addr-osmify-kotlin/src/test/kotlin/MockUrlopen.kt | 1 | 578 | /*
* Copyright 2020 Miklos Vajna. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
package hu.vmiklos.addr_osmify
import hu.vmiklos.addr_osmify.App.Companion.urlopener
/**
* Sets and restores App.urlopener for testing.
*/
class MockUrlopen internal constructor(suffix: String) {
var old: Urlopener
fun destruct() {
urlopener = old
}
init {
old = urlopener
urlopener = MockUrlopener(suffix)
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
| mit | e761a72bf3fa8967e0c07e940000808b | 21.230769 | 73 | 0.681661 | 3.302857 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/core/presenters/NotificationListPresenter.kt | 2 | 14629 | package org.stepic.droid.core.presenters
import android.util.Patterns
import androidx.annotation.MainThread
import androidx.annotation.WorkerThread
import androidx.collection.ArraySet
import androidx.collection.LongSparseArray
import io.reactivex.Scheduler
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.Client
import org.stepic.droid.concurrency.MainHandler
import org.stepic.droid.configuration.EndpointResolver
import org.stepic.droid.core.internetstate.contract.InternetEnabledListener
import org.stepic.droid.core.presenters.contracts.NotificationListView
import org.stepic.droid.di.notifications.NotificationsScope
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepic.droid.model.NotificationCategory
import org.stepic.droid.notifications.badges.NotificationsBadgesManager
import org.stepic.droid.notifications.model.Notification
import org.stepic.droid.notifications.model.NotificationType
import org.stepic.droid.util.DateTimeHelper
import org.stepic.droid.util.not
import org.stepic.droid.util.substringOrNull
import org.stepik.android.data.user.source.UserRemoteDataSource
import org.stepik.android.domain.notification.repository.NotificationRepository
import timber.log.Timber
import java.util.ArrayList
import java.util.Calendar
import java.util.HashMap
import java.util.TimeZone
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
@NotificationsScope
class NotificationListPresenter
@Inject constructor(
private val threadPoolExecutor: ThreadPoolExecutor,
private val mainHandler: MainHandler,
private val notificationRepository: NotificationRepository,
private val userRemoteDataSource: UserRemoteDataSource,
@MainScheduler
private val mainScheduler: Scheduler,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
private val endpointResolver: EndpointResolver,
private val analytic: Analytic,
private val internetEnabledListenerClient: Client<InternetEnabledListener>,
private val notificationsBadgesManager: NotificationsBadgesManager
) : PresenterBase<NotificationListView>(), InternetEnabledListener {
private var notificationCategory: NotificationCategory? = null
val isLoading = AtomicBoolean(false)
val wasShown = AtomicBoolean(false)
val hasNextPage = AtomicBoolean(true)
private val page = AtomicInteger(1)
val notificationList: MutableList<Notification> = ArrayList()
val notificationMapIdToPosition: MutableMap<Long, Int> = HashMap()
private val compositeDisposable = CompositeDisposable()
/**
* return false if were cancelled
*/
@MainThread
fun init(notificationCategory: NotificationCategory): Boolean {
notificationsBadgesManager.syncCounter()
this.notificationCategory = notificationCategory
if (!isLoading && !wasShown) {
//it is not lock, it is just check, but we still can enter twice if we use it in multithreading way, but it is only for main thread.
isLoading.set(true)
view?.onLoading()
if (notificationList.isNotEmpty()) {
view?.onNeedShowNotifications(notificationList)
wasShown.set(true)
isLoading.set(false)
}
threadPoolExecutor.execute {
try {
val notifications = getNotificationFromOnePage(notificationCategory)
notifications.forEachIndexed { position, notification ->
notification.id?.let { notificationId ->
notificationMapIdToPosition[notificationId] = position
}
}
mainHandler.post {
notificationList.addAll(notifications)
resolveNotificationsDateGroup()
wasShown.set(true)
view?.onNeedShowNotifications(notificationList) ?: wasShown.set(false)
}
} catch (ex: Exception) {
mainHandler.post {
view?.onConnectionProblem()
}
} finally {
isLoading.set(false)
}
}
return false
} else {
if (!isLoading) {
view?.onNeedShowNotifications(notificationList)
}
//do nothing we loading or already loaded
return true
}
}
@WorkerThread
private fun getNotificationFromOnePage(notificationCategory: NotificationCategory): Iterable<Notification> {
Timber.d("loading from page %d", page.get())
val notifications = notificationRepository.getNotifications(notificationCategory, page.get()).blockingGet()
hasNextPage.set(notifications.hasNext)
page.set(notifications.page + 1)
val baseUrl = endpointResolver.getBaseUrl()
Timber.d("before filter size is %d", notifications.size)
val filteredNotifications = notifications
.filter {
it.htmlText?.isNotBlank() ?: false
}
val userIdToNotificationsIndexes = LongSparseArray<MutableList<Int>>() // userId -> notifications index where avatar should be set
val userIds = ArraySet<Long>()
filteredNotifications.forEachIndexed { index, notification ->
val notificationHtmlText = notification.htmlText ?: ""
val fixedHtml = notificationHtmlText.replace("href=\"/", "href=\"$baseUrl/")
notification.htmlText = fixedHtml
if (notification.type == NotificationType.comments) {
extractUserAvatarUrl(notification)?.let { userId ->
userIdToNotificationsIndexes.putIfAbsent(userId, ArrayList())
userIdToNotificationsIndexes[userId]?.add(index)
userIds.add(userId)
}
}
}
if (userIds.isNotEmpty()) {
userRemoteDataSource.getUsers(userIds.toList()).blockingGet().forEach {
val avatar = it.avatar
userIdToNotificationsIndexes[it.id]?.forEach { notificationIndex ->
notifications[notificationIndex].userAvatarUrl = avatar
}
}
}
Timber.d("after filter size is %d", notifications.size)
return notifications
}
@WorkerThread
private fun extractUserAvatarUrl(notification: Notification): Long? {
val matcher = Regex(Patterns.WEB_URL.pattern()) // used kotlin Regex instead of android Pattern due to unstable work of Pattern on different Android versions
notification.htmlText?.let { matcher.find(it) } ?.groupValues?.firstOrNull()?.let { userUrl ->
val start = userUrl.lastIndexOf('/')
return userUrl.substringOrNull(start + 1)?.toLongOrNull()
}
return null
}
fun loadMore() {
if (isLoading.get() || !hasNextPage) {
return
}
//if is not loading:
isLoading.set(true)
view?.onNeedShowLoadingFooter()
threadPoolExecutor.execute {
try {
notificationCategory?.let { category ->
val notifications = getNotificationFromOnePage(category)
val oldSize = notificationList.size
notifications.forEachIndexed { shift, notification ->
notification.id?.let { notificationId ->
notificationMapIdToPosition[notificationId] = shift + oldSize
}
}
mainHandler.post {
notificationList.addAll(notifications)
resolveNotificationsDateGroup()
view?.onNeedShowNotifications(notificationList)
}
}
} catch (ex: Exception) {
mainHandler.post {
view?.onConnectionProblem()
}
} finally {
isLoading.set(false)
}
}
}
fun markAsRead(id: Long) {
compositeDisposable += notificationRepository
.putNotifications(id, isRead = true)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onComplete = {
onNotificationShouldBeRead(id)
notificationsBadgesManager.syncCounter()
},
onError = {
val pos = notificationMapIdToPosition[id]
if (pos != null) {
view?.notCheckNotification(pos, id)
}
}
)
}
fun notificationIdIsNull() {
analytic.reportEvent(Analytic.Notification.ID_WAS_NULL)
}
fun onNotificationShouldBeRead(notificationId: Long) {
val position: Int = notificationMapIdToPosition[notificationId] ?: return
if (position >= 0 && position < notificationList.size) {
val notificationInList = notificationList[position]
if (notificationInList.isUnread ?: false) {
view?.markNotificationAsRead(position, notificationId)
}
}
}
@MainThread
fun markAllAsRead() {
val notificationCategoryLocal = notificationCategory
if (notificationCategoryLocal == null) {
analytic.reportEvent(Analytic.Notification.NOTIFICATION_NULL_POINTER)
} else {
analytic.reportEvent(Analytic.Notification.MARK_ALL_AS_READ)
view?.onLoadingMarkingAsRead()
threadPoolExecutor.execute {
try {
notificationRepository.markNotificationAsRead(notificationCategoryLocal).blockingAwait()
notificationsBadgesManager.syncCounter()
notificationList.forEach {
it.isUnread = false
}
mainHandler.post {
onMarkCategoryRead(notificationCategoryLocal)
view?.markAsReadSuccessfully()
}
} catch (exception: Exception) {
mainHandler.post {
view?.onConnectionProblemWhenMarkAllFail()
}
} finally {
mainHandler.post {
view?.makeEnableMarkAllButton()
}
}
}
}
}
@MainThread
fun onMarkCategoryRead(category: NotificationCategory) {
if (category == notificationCategory) {
//already mark
return
}
if (notificationCategory == null || (notificationCategory != NotificationCategory.all && category != NotificationCategory.all)) {
//if we update in not all and it is not all -> do not need extra check
return
}
threadPoolExecutor.execute {
val listForNotificationForUI = notificationList
.filter {
it.isUnread ?: false
}
.filter {
if (category == NotificationCategory.all) {
true
} else {
val notCategory: NotificationCategory = when (it.type) {
NotificationType.comments -> NotificationCategory.comments
NotificationType.other -> NotificationCategory.default
NotificationType.review -> NotificationCategory.review
NotificationType.teach -> NotificationCategory.teach
NotificationType.learn -> NotificationCategory.learn
null -> NotificationCategory.all
}
notCategory == category
}
}
val list: List<Pair<Int?, Long?>> = listForNotificationForUI.map {
val first = notificationMapIdToPosition[it.id]
Pair(first, it.id)
}
if (list.isNotEmpty()) {
mainHandler.post {
list.forEach {
if (it.first != null && it.second != null) {
view?.markNotificationAsRead(it.first!!, it.second!!)
}
}
}
}
}
}
private fun resolveNotificationsDateGroup() {
var groupId = -1
var groupDay = -1
var groupYear = -1
notificationList.forEach { notification ->
notification.time?.let { time ->
val date = DateTimeHelper.toCalendar(time)
date.timeZone = TimeZone.getDefault()
val day = date.get(Calendar.DAY_OF_YEAR)
val year = date.get(Calendar.YEAR)
if (day != groupDay || year != groupYear) {
groupDay = day
groupYear = year
groupId++
}
notification.dateGroup = groupId
}
}
}
override fun attachView(view: NotificationListView) {
super.attachView(view)
internetEnabledListenerClient.subscribe(this)
}
override fun detachView(view: NotificationListView) {
super.detachView(view)
internetEnabledListenerClient.unsubscribe(this)
compositeDisposable.clear()
}
override fun onInternetEnabled() {
val category = notificationCategory
if (notificationList.isEmpty() && category != null) {
init(category);
}
}
fun tryToOpenNotification(notification: Notification) {
analytic.reportEvent(Analytic.Notification.NOTIFICATION_CENTER_OPENED)
view?.openNotification(notification)
}
fun trackClickOnNotification(notification: Notification) {
analytic.reportEventWithIdName(Analytic.Notification.NOTIFICATION_CLICKED_IN_CENTER, notification.id.toString(), notification.type?.name ?: "")
}
} | apache-2.0 | e2d5507d48cf68baa07768eb2eda1b0f | 37.909574 | 165 | 0.597033 | 5.732367 | false | false | false | false |
huy-vuong/streamr | app/src/main/java/com/huyvuong/streamr/ui/component/subcomponent/ExifCardSubcomponent.kt | 1 | 12556 | package com.huyvuong.streamr.ui.component.subcomponent
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.support.v4.content.ContextCompat
import android.support.v7.widget.CardView
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import com.huyvuong.streamr.R
import com.huyvuong.streamr.model.view.Exif
import com.huyvuong.streamr.util.getCardHeaderDrawable
import org.jetbrains.anko.AnkoComponent
import org.jetbrains.anko.AnkoContext
import org.jetbrains.anko.bottomPadding
import org.jetbrains.anko.cardview.v7.cardView
import org.jetbrains.anko.dip
import org.jetbrains.anko.imageView
import org.jetbrains.anko.leftPadding
import org.jetbrains.anko.linearLayout
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.padding
import org.jetbrains.anko.sp
import org.jetbrains.anko.textView
import org.jetbrains.anko.topPadding
import org.jetbrains.anko.verticalLayout
import org.jetbrains.anko.wrapContent
import android.support.v7.appcompat.R as AppCompatR
class ExifCardSubcomponent : AnkoComponent<ViewGroup> {
private lateinit var exifCardView: CardView
private lateinit var exifHeaderTextView: TextView
private lateinit var cameraGroupLinearLayout: LinearLayout
private lateinit var modelTextView: TextView
private lateinit var makeTextView: TextView
private lateinit var lensGroupLinearLayout: LinearLayout
private lateinit var lensTextView: TextView
private lateinit var zoomTextView: TextView
private lateinit var exposureGroupLinearLayout: LinearLayout
private lateinit var exposureProgramTextView: TextView
private lateinit var apertureTextView: TextView
private lateinit var shutterSpeedTextView: TextView
private lateinit var isoTextView: TextView
private lateinit var exposureCompensationTextView: TextView
private lateinit var flashGroupLinearLayout: LinearLayout
private lateinit var flashTextView: TextView
override fun createView(ui: AnkoContext<ViewGroup>): CardView = with(ui.owner) {
cardView {
exifCardView = this
setCardBackgroundColor(ContextCompat.getColor(context, R.color.cardBackground))
radius = dip(2).toFloat()
elevation = 2.0F
visibility = View.GONE
verticalLayout {
lparams(width = matchParent, height = wrapContent)
verticalLayout {
lparams(width = matchParent, height = wrapContent)
padding = dip(16)
linearLayout {
lparams(width = matchParent, height = wrapContent)
bottomPadding = dip(16)
val cardPhotoDrawable =
ContextCompat.getDrawable(context, R.drawable.ic_card_exif)
cardPhotoDrawable?.colorFilter = PorterDuffColorFilter(
ContextCompat.getColor(context, R.color.cardHeaderIconColor),
PorterDuff.Mode.MULTIPLY)
imageView(getCardHeaderDrawable(context, R.drawable.ic_card_exif))
.lparams(width = dip(16), height = dip(16))
exifHeaderTextView = textView("Exif") {
leftPadding = dip(8)
textSize = sp(3.5F).toFloat()
}.lparams(width = matchParent, height = dip(16)) {
gravity = Gravity.CENTER_VERTICAL
}
}
cameraGroupLinearLayout = linearLayout {
lparams(width = matchParent, height = wrapContent)
topPadding = dip(16)
bottomPadding = dip(16)
imageView(R.drawable.ic_camera)
.lparams(width = dip(24), height = dip(24)) {
gravity = Gravity.CENTER_VERTICAL
}
verticalLayout {
lparams(width = matchParent, height = wrapContent)
leftPadding = dip(16)
modelTextView = textView {
setTextAppearance(AppCompatR.style.TextAppearance_AppCompat_Subhead)
}.lparams(width = matchParent, height = wrapContent, weight = 1.0F)
makeTextView = textView()
.lparams(
width = matchParent,
height = wrapContent,
weight = 1.0F)
}
}
lensGroupLinearLayout = linearLayout {
lparams(width = matchParent, height = wrapContent)
topPadding = dip(16)
bottomPadding = dip(16)
imageView(R.drawable.ic_lens)
.lparams(width = dip(24), height = dip(24)) {
gravity = Gravity.CENTER_VERTICAL
}
verticalLayout {
lparams(width = matchParent, height = wrapContent)
leftPadding = dip(16)
lensTextView = textView {
setTextAppearance(AppCompatR.style.TextAppearance_AppCompat_Subhead)
}.lparams(width = matchParent, height = wrapContent, weight = 1.0F)
zoomTextView = textView()
.lparams(
width = matchParent,
height = wrapContent,
weight = 1.0F)
}
}
exposureGroupLinearLayout = linearLayout {
lparams(width = matchParent, height = wrapContent)
topPadding = dip(16)
bottomPadding = dip(16)
imageView(R.drawable.ic_exposure)
.lparams(width = dip(24), height = dip(24)) {
gravity = Gravity.CENTER_VERTICAL
}
verticalLayout {
lparams(width = matchParent, height = wrapContent)
leftPadding = dip(16)
exposureProgramTextView = textView {
setTextAppearance(AppCompatR.style.TextAppearance_AppCompat_Subhead)
}.lparams(width = matchParent, height = wrapContent, weight = 1.0F)
linearLayout {
lparams(width = matchParent, height = wrapContent)
apertureTextView = textView {
textAlignment = TextView.TEXT_ALIGNMENT_TEXT_START
}.lparams(width = matchParent, height = wrapContent, weight = 1.0F)
shutterSpeedTextView = textView {
textAlignment = TextView.TEXT_ALIGNMENT_TEXT_START
}.lparams(width = matchParent, height = wrapContent, weight = 1.0F)
isoTextView = textView {
textAlignment = TextView.TEXT_ALIGNMENT_TEXT_END
}.lparams(width = matchParent, height = wrapContent, weight = 1.0F)
exposureCompensationTextView = textView {
textAlignment = TextView.TEXT_ALIGNMENT_TEXT_END
}.lparams(width = matchParent, height = wrapContent, weight = 1.0F)
}
}
}
flashGroupLinearLayout = linearLayout {
lparams(width = matchParent, height = wrapContent)
topPadding = dip(16)
bottomPadding = dip(16)
imageView(R.drawable.ic_flash)
.lparams(width = dip(24), height = dip(24)) {
gravity = Gravity.CENTER_VERTICAL
}
flashTextView = textView {
leftPadding = dip(16)
setTextAppearance(AppCompatR.style.TextAppearance_AppCompat_Subhead)
}.lparams(width = matchParent, height = wrapContent, weight = 1.0F)
}
}
}
}
}
fun bind(context: Context, exif: Exif?) {
// TODO Add "View EXIF" button to view all EXIF data.
if (exif == null) {
exifCardView.visibility = View.GONE
} else {
exifCardView.visibility = View.VISIBLE
if (exif.cameraMetadata == null) {
cameraGroupLinearLayout.visibility = View.GONE
} else {
cameraGroupLinearLayout.visibility = View.VISIBLE
modelTextView.text = exif.cameraMetadata.model
if (exif.cameraMetadata.model != null) {
makeTextView.visibility = View.VISIBLE
makeTextView.text = exif.cameraMetadata.make
} else {
makeTextView.visibility = View.GONE
}
}
if (exif.lensMetadata == null) {
lensGroupLinearLayout.visibility = View.GONE
} else {
lensGroupLinearLayout.visibility = View.VISIBLE
if (exif.lensMetadata.focalLength == null) {
zoomTextView.visibility = View.GONE
lensTextView.visibility = View.GONE
} else {
zoomTextView.visibility = View.VISIBLE
zoomTextView.text = "Taken at ${exif.lensMetadata.focalLength}"
if (exif.lensMetadata.model == null) {
lensTextView.visibility = View.GONE
zoomTextView.setTextAppearance(
AppCompatR.style.TextAppearance_AppCompat_Subhead)
} else {
lensTextView.visibility = View.VISIBLE
lensTextView.text = exif.lensMetadata.model
}
}
}
if (exif.exposureMetadata == null) {
exposureGroupLinearLayout.visibility = View.GONE
} else {
exposureGroupLinearLayout.visibility = View.VISIBLE
exposureProgramTextView.text =
exif.exposureMetadata.exposureProgram ?: "Unknown exposure mode"
val aperture = exif.exposureMetadata.aperture ?: "--"
apertureTextView.text = "\u0192/$aperture"
val shutterSpeed = exif.exposureMetadata.shutterSpeed ?: "--"
shutterSpeedTextView.text = shutterSpeed + " s"
val iso = exif.exposureMetadata.iso ?: "--"
isoTextView.text = "ISO $iso"
val exposureCompensation =
exif.exposureMetadata.run {
exposureCompensation ?: "--"
}
exposureCompensationTextView.text = "$exposureCompensation EV"
}
if (exif.flashMetadata == null) {
flashGroupLinearLayout.visibility = View.GONE
} else {
flashGroupLinearLayout.visibility = View.VISIBLE
flashTextView.text = exif.flashMetadata.flashStatus
}
val groups = listOf(
cameraGroupLinearLayout,
lensGroupLinearLayout,
exposureGroupLinearLayout,
flashGroupLinearLayout)
if (groups.all { it.visibility == View.GONE }) {
exifCardView.visibility = View.GONE
}
}
}
}
| gpl-3.0 | 131d321196bcbb4bc0f1b4ea7af110f5 | 43.211268 | 100 | 0.517999 | 6.0657 | false | false | false | false |
google/zsldemo | app/src/main/java/com/hadrosaur/zsldemo/AutoFitTextureView.kt | 1 | 2372 | /*
* 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
*
* 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.hadrosaur.zsldemo
import android.content.Context
import android.util.AttributeSet
import android.view.TextureView
import android.view.View
/**
* A [TextureView] that can be adjusted to a specified aspect ratio.
*/
class AutoFitTextureView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : TextureView(context, attrs, defStyle) {
private var ratioWidth = 0
private var ratioHeight = 0
/**
* Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
* calculated from the parameters. Note that the actual sizes of parameters don't matter, that
* is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
*
* @param width Relative horizontal size
* @param height Relative vertical size
*/
fun setAspectRatio(width: Int, height: Int) {
if (width < 0 || height < 0) {
throw IllegalArgumentException("Size cannot be negative.")
}
ratioWidth = width
ratioHeight = height
requestLayout()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = View.MeasureSpec.getSize(widthMeasureSpec)
val height = View.MeasureSpec.getSize(heightMeasureSpec)
if (ratioWidth == 0 || ratioHeight == 0) {
setMeasuredDimension(width, height)
} else {
if (width < height * ratioWidth / ratioHeight) {
setMeasuredDimension(width, width * ratioHeight / ratioWidth)
} else {
setMeasuredDimension(height * ratioWidth / ratioHeight, height)
}
}
}
} | apache-2.0 | b054cceca1e5da3271d6d3408b3a1040 | 34.41791 | 100 | 0.677066 | 4.65098 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/util/ImageUtil.kt | 2 | 1081 | package com.commit451.gitlab.util
import android.net.Uri
import com.commit451.gitlab.model.api.User
/**
* Utility for doing various image related things
*/
object ImageUtil {
fun getAvatarUrl(user: User?, size: Int): Uri {
if (user != null) {
if (user.avatarUrl != null) {
val avatarUrl = Uri.parse(user.avatarUrl)
if (avatarUrl != null && avatarUrl != Uri.EMPTY) {
return avatarUrl.buildUpon()
.appendQueryParameter("s", Integer.toString(size))
.build()
}
}
val email = user.email
if (email != null) {
return getAvatarUrl(email, size)
}
}
return getAvatarUrl(null as? String?, size)
}
fun getAvatarUrl(email: String?, size: Int): Uri {
return Gravatar
.init(email)
.ssl()
.size(size)
.defaultImage(Gravatar.DefaultImage.IDENTICON)
.build()
}
}
| apache-2.0 | 69558179bdade05a5ed3278567a0f994 | 26.717949 | 78 | 0.499537 | 4.639485 | false | false | false | false |
Tait4198/hi_pixiv | app/src/main/java/info/hzvtc/hipixiv/vm/fragment/TrendTagViewModel.kt | 1 | 2864 | package info.hzvtc.hipixiv.vm.fragment
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.util.Log
import info.hzvtc.hipixiv.R
import info.hzvtc.hipixiv.adapter.events.TrendTagItemClick
import info.hzvtc.hipixiv.adapter.TrendTagsAdapter
import info.hzvtc.hipixiv.databinding.FragmentListBinding
import info.hzvtc.hipixiv.pojo.trend.TrendTagsResponse
import info.hzvtc.hipixiv.view.SearchActivity
import info.hzvtc.hipixiv.view.fragment.BaseFragment
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class TrendTagViewModel @Inject constructor():
BaseFragmentViewModel<BaseFragment<FragmentListBinding>,FragmentListBinding>(),ViewModelData<TrendTagsResponse> {
var obsNewData : Observable<TrendTagsResponse>? = null
private lateinit var adapter: TrendTagsAdapter
override fun runView() {
getData(obsNewData)
}
override fun initViewModel() {
val layoutManger = GridLayoutManager(mView.context,3)
layoutManger.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup(){
override fun getSpanSize(pos: Int): Int = if(adapter.getFull(pos)) 1 else layoutManger.spanCount
}
mBind.recyclerView.layoutManager = layoutManger
adapter = TrendTagsAdapter(mView.context)
adapter.setTrendTagItemClick(object : TrendTagItemClick {
override fun itemClick(tag: String) {
if(mView.activity is SearchActivity){
(mView.activity as SearchActivity).searchByTrendTag(tag)
}
}
})
mBind.srLayout.setColorSchemeColors(ContextCompat.getColor(mView.context, R.color.primary))
mBind.srLayout.setOnRefreshListener({ getData(obsNewData) })
mBind.recyclerView.adapter = adapter
}
override fun getData(obs: Observable<TrendTagsResponse>?) {
if(obs != null){
Observable.just(obs)
.doOnNext({ if(obs != obsNewData) obsNewData = obs })
.doOnNext({ mBind.srLayout.isRefreshing = true })
.observeOn(Schedulers.io())
.flatMap({ obs -> obs })
.doOnNext({ response -> adapter.setNewData(response) })
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
_ -> adapter.updateUI(true)
},{
error ->
Log.e("Error",error.toString())
mBind.srLayout.isRefreshing = false
},{
mBind.srLayout.isRefreshing = false
})
}
}
override fun getMoreData() {
//
}
} | mit | 86e11a121cf5c5c6d819b43fb24dd335 | 38.791667 | 121 | 0.643156 | 5.123435 | false | false | false | false |
da1z/intellij-community | java/java-impl/src/com/intellij/lang/java/request/createMethodFromUsage.kt | 5 | 3419 | /*
* 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.
*/
@file:JvmName("CreateMethodFromUsage")
package com.intellij.lang.java.request
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.isValidMethodReference
import com.intellij.codeInsight.daemon.impl.quickfix.CreateMethodFromUsageFix.isMethodSignatureExists
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.lang.jvm.JvmClass
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.CreateMethodRequest
import com.intellij.lang.jvm.actions.EP_NAME
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiJavaCodeReferenceElement
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.util.PsiUtil.resolveClassInClassTypeOnly
import com.intellij.psi.util.parentOfType
fun generateActions(call: PsiMethodCallExpression): List<IntentionAction> {
if (!checkCall(call)) return emptyList()
val methodRequests = CreateMethodRequests(call).collectRequests()
val extensions = EP_NAME.extensions
return methodRequests.flatMap { (clazz, request) ->
extensions.flatMap { ext ->
ext.createAddMethodActions(clazz, request)
}
}
}
private fun checkCall(call: PsiMethodCallExpression): Boolean {
val ref = call.methodExpression
if (ref.referenceName == null) return false
if (isValidMethodReference(ref, call)) return false
return true
}
private class CreateMethodRequests(val myCall: PsiMethodCallExpression) {
private val myRequests = LinkedHashMap<JvmClass, CreateMethodRequest>()
fun collectRequests(): Map<JvmClass, CreateMethodRequest> {
doCollectRequests()
return myRequests
}
private fun doCollectRequests() {
val qualifier = myCall.methodExpression.qualifierExpression
if (qualifier != null) {
val instanceClass = resolveClassInClassTypeOnly(qualifier.type)
if (instanceClass != null) {
for (clazz in hierarchy(instanceClass)) {
processClass(clazz, false)
}
}
else {
val staticClass = (qualifier as? PsiJavaCodeReferenceElement)?.resolve() as? PsiClass
if (staticClass != null) {
processClass(staticClass, true)
}
}
}
else {
val inStaticContext = myCall.isInStaticContext()
for (outerClass in collectOuterClasses(myCall)) {
processClass(outerClass, inStaticContext)
}
}
}
private fun processClass(clazz: PsiClass, staticContext: Boolean) {
if (isMethodSignatureExists(myCall, clazz)) return // TODO generic check
val visibility = computeVisibility(myCall.project, myCall.parentOfType(), clazz)
val modifiers = mutableSetOf<JvmModifier>()
if (staticContext) modifiers += JvmModifier.STATIC
if (visibility != null) modifiers += visibility
myRequests[clazz] = CreateMethodFromJavaUsageRequest(myCall, modifiers)
}
}
| apache-2.0 | f59ceb9fc8f53b17a404cfd4be601fe6 | 35.763441 | 101 | 0.751097 | 4.576975 | false | false | false | false |
Adventech/sabbath-school-android-2 | common/storage/src/main/java/app/ss/storage/db/dao/BaseDao.kt | 1 | 655 | package app.ss.storage.db.dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Update
interface BaseDao<in T> {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(item: T?)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertItem(item: T?)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(items: List<T>)
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun update(item: T)
@Update(onConflict = OnConflictStrategy.REPLACE)
fun updateItem(item: T)
@Delete
suspend fun delete(item: T)
}
| mit | 1637cd03b4a98e9844c515c224c7678f | 23.259259 | 52 | 0.737405 | 4.14557 | false | false | false | false |
k9mail/k-9 | app/core/src/main/java/com/fsck/k9/controller/push/KoinModule.kt | 2 | 896 | package com.fsck.k9.controller.push
import org.koin.dsl.module
internal val controllerPushModule = module {
single { PushServiceManager(context = get()) }
single { BootCompleteManager(context = get()) }
single { AutoSyncManager(context = get()) }
single {
AccountPushControllerFactory(
backendManager = get(),
messagingController = get(),
folderRepository = get(),
preferences = get()
)
}
single {
PushController(
preferences = get(),
generalSettingsManager = get(),
backendManager = get(),
pushServiceManager = get(),
bootCompleteManager = get(),
autoSyncManager = get(),
pushNotificationManager = get(),
connectivityManager = get(),
accountPushControllerFactory = get()
)
}
}
| apache-2.0 | e5b7b8674ca6c81469155c43edc91caf | 28.866667 | 51 | 0.570313 | 5.430303 | false | false | false | false |
Maccimo/intellij-community | uast/uast-common/src/org/jetbrains/uast/internal/implementationUtils.kt | 4 | 3479 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.uast.internal
import com.intellij.diagnostic.AttachmentFactory
import com.intellij.openapi.diagnostic.Attachment
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.RecursionManager
import com.intellij.psi.PsiElement
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UastFacade
import org.jetbrains.uast.visitor.UastVisitor
fun List<UElement>.acceptList(visitor: UastVisitor) {
for (element in this) {
element.accept(visitor)
}
}
@Suppress("UnusedReceiverParameter")
inline fun <reified T : UElement> T.log(text: String = ""): String {
val className = T::class.java.simpleName
return if (text.isEmpty()) className else "$className ($text)"
}
fun <U : UElement> Array<out Class<out UElement>>.accommodate(vararg makers: UElementAlternative<out U>): Sequence<U> {
val makersSeq = makers.asSequence()
return this.asSequence()
.flatMap { requiredType -> makersSeq.filter { requiredType.isAssignableFrom(it.uType) } }
.distinct()
.mapNotNull { it.make.invoke() }
}
fun <U : UElement> Class<out UElement>.accommodate(a1: UElementAlternative<out U>, a2: UElementAlternative<out U>): U? {
return if (this.isAssignableFrom(a1.uType)) {
a1.make.invoke()
}
else if (this.isAssignableFrom(a2.uType)) {
a2.make.invoke()
}
else null
}
inline fun <reified U : UElement> alternative(noinline make: () -> U?) = UElementAlternative(U::class.java, make)
class UElementAlternative<U : UElement>(val uType: Class<U>, val make: () -> U?)
inline fun <reified T : UElement> convertOrReport(psiElement: PsiElement, parent: UElement): T? =
convertOrReport(psiElement, parent, T::class.java)
fun <T : UElement> convertOrReport(psiElement: PsiElement, parent: UElement, expectedType: Class<T>): T? {
fun UElement.safeToString(): String = RecursionManager.doPreventingRecursion(this, false) {
toString()
} ?: "<recursive `toString()` computation $javaClass>"
fun mkAttachments(): Array<Attachment> = ArrayList<Attachment>().also { result ->
result.add(Attachment("info.txt", buildString {
appendLine("context: ${parent.javaClass}")
appendLine("psiElement: ${psiElement.javaClass}")
appendLine("expectedType: $expectedType")
}))
result.add(Attachment("psiElementContent.txt", runCatching { psiElement.text ?: "<null>" }.getOrElse { it.stackTraceToString() }))
result.add(Attachment("uast-plugins.list", UastFacade.languagePlugins.joinToString("\n") { it.javaClass.toString() }))
result.add(runCatching { psiElement.containingFile }
.mapCatching { it.virtualFile }
.fold({ AttachmentFactory.createAttachment(it) }, { Attachment("containingFile-exception.txt", it.stackTraceToString()) }))
}.toTypedArray()
val plugin = parent.sourcePsi?.let { UastFacade.findPlugin(it) } ?: UastFacade.findPlugin(psiElement)
if (plugin == null) {
Logger.getInstance(parent.javaClass)
.error("cant get UAST plugin for ${parent.safeToString()} to convert element $psiElement", *mkAttachments())
return null
}
val result = expectedType.cast(plugin.convertElement(psiElement, parent, expectedType))
if (result == null) {
Logger.getInstance(parent.javaClass)
.error("failed to convert element $psiElement in ${parent.safeToString()}", *mkAttachments())
}
return result
} | apache-2.0 | bf6b6050bf340887ca6fb504f98e617c | 42.5 | 140 | 0.724346 | 4.122038 | false | false | false | false |
Maccimo/intellij-community | platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/zoomIndicator/AttachZoomIndicator.kt | 4 | 2645 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.fileEditor.impl.zoomIndicator
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.ui.awt.RelativePoint
import javax.swing.JComponent
class AttachZoomIndicator : EditorFactoryListener {
private fun service(project: Project) = project.service<ZoomIndicatorManager>()
private fun suppressZoomIndicator(editor: Editor) = editor.isDisposed || editor.getUserData(ZoomIndicatorManager.SUPPRESS_ZOOM_INDICATOR) == true
override fun editorCreated(event: EditorFactoryEvent) {
val editorEx = event.editor as? EditorImpl ?: return
val project = editorEx.project ?: return
if (project.isDisposed || suppressZoomIndicator(editorEx)) return
editorEx.addPropertyChangeListener {
if (it.propertyName != EditorEx.PROP_FONT_SIZE) return@addPropertyChangeListener
if (!ZoomIndicatorManager.isEnabled || suppressZoomIndicator(editorEx)) return@addPropertyChangeListener
invokeLater {
if (!editorEx.isDisposed) {
val balloon = service(project).createOrGetBalloon(editorEx)
balloon?.showInBottomCenterOf(getComponentToUse(project, editorEx))
}
}
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val editor = event.editor
val project = event.editor.project ?: return
if (editor.isDisposed || project.isDisposed) return
if (service(project).editor == editor) {
service(project).cancelCurrentPopup()
}
}
private fun getComponentToUse(project: Project, editorEx: EditorEx): JComponent {
return if (!EditorSettingsExternalizable.getInstance().isWheelFontChangePersistent) {
editorEx.component
}
else {
(FileEditorManager.getInstance(project) as? FileEditorManagerImpl)?.mainSplitters ?: editorEx.component
}
}
private fun Balloon.showInBottomCenterOf(component: JComponent) = show(RelativePoint.getSouthOf(component), Balloon.Position.below)
} | apache-2.0 | 41fb794f23913a78d77f257d06a44d63 | 44.62069 | 147 | 0.781474 | 4.624126 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/AbstractInspectionTest.kt | 3 | 7340 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.codeInsight
import com.intellij.codeInspection.ex.EntryPointsManagerBase
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiFile
import com.intellij.testFramework.TestLoggerFactory
import com.intellij.util.ThrowableRunnable
import org.jdom.Document
import org.jdom.input.SAXBuilder
import org.jetbrains.kotlin.formatter.FormatSettingsUtil
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.inspections.runInspection
import org.jetbrains.kotlin.idea.test.*
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import org.jetbrains.plugins.groovy.GroovyFileType
import org.junit.runner.Description
import java.io.File
abstract class AbstractInspectionTest : KotlinLightCodeInsightFixtureTestCase() {
companion object {
const val ENTRY_POINT_ANNOTATION = "test.anno.EntryPoint"
}
override fun setUp() {
try {
super.setUp()
EntryPointsManagerBase.getInstance(project).ADDITIONAL_ANNOTATIONS.add(ENTRY_POINT_ANNOTATION)
registerGradlPlugin()
} catch (e: Throwable) {
TestLoggerFactory.logTestFailure(e)
TestLoggerFactory.onTestFinished(false, Description.createTestDescription(javaClass, name))
throw e
}
}
protected open fun registerGradlPlugin() {
runWriteAction { FileTypeManager.getInstance().associateExtension(GroovyFileType.GROOVY_FILE_TYPE, "gradle") }
}
override fun tearDown() {
runAll(
ThrowableRunnable { EntryPointsManagerBase.getInstance(project).ADDITIONAL_ANNOTATIONS.remove(ENTRY_POINT_ANNOTATION) },
ThrowableRunnable { super.tearDown() }
)
}
protected open fun configExtra(psiFiles: List<PsiFile>, options: String) {
}
protected open val forceUsePackageFolder: Boolean = false //workaround for IDEA-176033
protected open fun inspectionClassDirective(): String = "// INSPECTION_CLASS: "
protected open fun doTest(path: String) {
val optionsFile = File(path)
val options = FileUtil.loadFile(optionsFile, true)
val inspectionClass = Class.forName(InTextDirectivesUtils.findStringWithPrefixes(options, inspectionClassDirective())!!)
val fixtureClasses = InTextDirectivesUtils.findListWithPrefixes(options, "// FIXTURE_CLASS: ")
withCustomCompilerOptions(options, project, module) {
val inspectionsTestDir = optionsFile.parentFile!!
val srcDir = inspectionsTestDir.parentFile!!
val settingsFile = File(inspectionsTestDir, "settings.xml")
val settingsElement = if (settingsFile.exists()) {
(SAXBuilder().build(settingsFile) as Document).rootElement
} else {
null
}
with(myFixture) {
testDataPath = srcDir.path
val afterFiles = srcDir.listFiles { it -> it.name == "inspectionData" }
?.single()
?.listFiles { it -> it.extension == "after" }
?: emptyArray()
val psiFiles = srcDir.walkTopDown().onEnter { it.name != "inspectionData" }.mapNotNull { file ->
when {
file.isDirectory -> null
file.extension == "kt" -> {
val text = FileUtil.loadFile(file, true)
val fileText =
if (text.lines().any { it.startsWith("package") })
text
else
"package ${file.nameWithoutExtension};$text"
if (forceUsePackageFolder) {
val packageName = fileText.substring(
"package".length,
fileText.indexOfAny(charArrayOf(';', '\n')),
).trim()
val projectFileName = packageName.replace('.', '/') + "/" + file.name
addFileToProject(projectFileName, fileText)
} else {
configureByText(file.name, fileText)!!
}
}
file.extension == "gradle" -> {
val text = FileUtil.loadFile(file, true)
val kgpArtifactVersion = KotlinPluginLayout.standaloneCompilerVersion.artifactVersion
val fileText = text.replace("\$PLUGIN_VERSION", kgpArtifactVersion)
configureByText(file.name, fileText)!!
}
else -> {
val filePath = file.relativeTo(srcDir).invariantSeparatorsPath
configureByFile(filePath)
}
}
}.toList()
configureCodeStyleAndRun(
project,
configurator = { FormatSettingsUtil.createConfigurator(options, it).configureSettings() }
) {
configureRegistryAndRun(options) {
try {
fixtureClasses.forEach { TestFixtureExtension.loadFixture(it, myFixture.module) }
configExtra(psiFiles, options)
val presentation = runInspection(
inspectionClass, project,
settings = settingsElement,
files = psiFiles.map { it.virtualFile!! }, withTestDir = inspectionsTestDir.path,
)
if (afterFiles.isNotEmpty()) {
presentation.problemDescriptors.forEach { problem ->
problem.fixes?.forEach { quickFix ->
project.executeWriteCommand(quickFix.name, quickFix.familyName) {
quickFix.applyFix(project, problem)
}
}
}
for (filePath in afterFiles) {
val kotlinFile = psiFiles.first { filePath.name == it.name + ".after" }
KotlinTestUtils.assertEqualsToFile(filePath, kotlinFile.text)
}
}
} finally {
fixtureClasses.forEach { TestFixtureExtension.unloadFixture(it) }
}
}
}
}
}
}
}
| apache-2.0 | 7c8979f6817b00561efe834eccdc3e1d | 44.308642 | 158 | 0.545777 | 6.061107 | false | true | false | false |
Maccimo/intellij-community | plugins/kotlin/native/src/org/jetbrains/kotlin/ide/konan/NativePlatformKindResolution.kt | 2 | 6713 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.ide.konan
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.analyzer.PlatformAnalysisParameters
import org.jetbrains.kotlin.analyzer.ResolverForModuleFactory
import org.jetbrains.kotlin.analyzer.ResolverForProject
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.builtins.functions.functionInterfacePackageFragmentProvider
import org.jetbrains.kotlin.builtins.konan.KonanBuiltIns
import org.jetbrains.kotlin.caches.resolve.IdePlatformKindResolution
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.CompositePackageFragmentProvider
import org.jetbrains.kotlin.descriptors.konan.DeserializedKlibModuleOrigin
import org.jetbrains.kotlin.ide.konan.analyzer.NativeResolverForModuleFactory
import org.jetbrains.kotlin.idea.base.projectStructure.IDELanguageSettingsProvider
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.IdeaModuleInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.NativeKlibLibraryInfo
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.SdkInfo
import org.jetbrains.kotlin.idea.caches.resolve.BuiltInsCacheKey
import org.jetbrains.kotlin.idea.klib.createKlibPackageFragmentProvider
import org.jetbrains.kotlin.incremental.components.LookupTracker
import org.jetbrains.kotlin.konan.util.KlibMetadataFactories
import org.jetbrains.kotlin.library.metadata.NullFlexibleTypeDeserializer
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.resolve.TargetEnvironment
import org.jetbrains.kotlin.serialization.konan.impl.KlibMetadataModuleDescriptorFactoryImpl
import org.jetbrains.kotlin.storage.StorageManager
class NativePlatformKindResolution : IdePlatformKindResolution {
override fun createKlibPackageFragmentProvider(
moduleInfo: ModuleInfo,
storageManager: StorageManager,
languageVersionSettings: LanguageVersionSettings,
moduleDescriptor: ModuleDescriptor
): PackageFragmentProvider? {
return (moduleInfo as? NativeKlibLibraryInfo)
?.resolvedKotlinLibrary
?.createKlibPackageFragmentProvider(
storageManager = storageManager,
metadataModuleDescriptorFactory = metadataFactories.DefaultDeserializedDescriptorFactory,
languageVersionSettings = languageVersionSettings,
moduleDescriptor = moduleDescriptor,
lookupTracker = LookupTracker.DO_NOTHING
)
}
override fun createResolverForModuleFactory(
settings: PlatformAnalysisParameters,
environment: TargetEnvironment,
platform: TargetPlatform
): ResolverForModuleFactory {
return NativeResolverForModuleFactory(settings, environment, platform)
}
override val kind get() = NativeIdePlatformKind
override fun getKeyForBuiltIns(moduleInfo: ModuleInfo, sdkInfo: SdkInfo?, stdlibInfo: LibraryInfo?): BuiltInsCacheKey = NativeBuiltInsCacheKey
override fun createBuiltIns(
moduleInfo: IdeaModuleInfo,
projectContext: ProjectContext,
resolverForProject: ResolverForProject<IdeaModuleInfo>,
sdkDependency: SdkInfo?,
stdlibDependency: LibraryInfo?,
) = createKotlinNativeBuiltIns(moduleInfo, projectContext)
private fun createKotlinNativeBuiltIns(moduleInfo: ModuleInfo, projectContext: ProjectContext): KotlinBuiltIns {
val stdlibInfo = moduleInfo.findNativeStdlib() ?: return DefaultBuiltIns.Instance
val project = projectContext.project
val storageManager = projectContext.storageManager
val builtInsModule = metadataFactories.DefaultDescriptorFactory.createDescriptorAndNewBuiltIns(
KotlinBuiltIns.BUILTINS_MODULE_NAME,
storageManager,
DeserializedKlibModuleOrigin(stdlibInfo.resolvedKotlinLibrary),
stdlibInfo.capabilities
)
val languageVersionSettings = IDELanguageSettingsProvider.getLanguageVersionSettings(
stdlibInfo,
project
)
val stdlibPackageFragmentProvider = createKlibPackageFragmentProvider(
stdlibInfo,
storageManager,
languageVersionSettings,
builtInsModule
) ?: return DefaultBuiltIns.Instance
builtInsModule.initialize(
CompositePackageFragmentProvider(
listOf(
stdlibPackageFragmentProvider,
functionInterfacePackageFragmentProvider(storageManager, builtInsModule),
(metadataFactories.DefaultDeserializedDescriptorFactory as KlibMetadataModuleDescriptorFactoryImpl)
.createForwardDeclarationHackPackagePartProvider(storageManager, builtInsModule)
),
"CompositeProvider@NativeBuiltins for $builtInsModule"
)
)
builtInsModule.setDependencies(listOf(builtInsModule))
return builtInsModule.builtIns
}
object NativeBuiltInsCacheKey : BuiltInsCacheKey
companion object {
private val metadataFactories = KlibMetadataFactories(::KonanBuiltIns, NullFlexibleTypeDeserializer)
private fun ModuleInfo.findNativeStdlib(): NativeKlibLibraryInfo? =
dependencies().lazyClosure { it.dependencies() }
.filterIsInstance<NativeKlibLibraryInfo>()
.firstOrNull { it.isStdlib && it.compatibilityInfo.isCompatible }
}
}
/**
* @see [org.jetbrains.kotlin.types.typeUtil.closure].
*/
private fun <T> Collection<T>.lazyClosure(f: (T) -> Collection<T>): Sequence<T> = sequence {
if (isEmpty()) return@sequence
var sizeBeforeIteration = 0
yieldAll(this@lazyClosure)
var yieldedCount = size
var elementsToCheck = this@lazyClosure
while (yieldedCount > sizeBeforeIteration) {
val toAdd = hashSetOf<T>()
elementsToCheck.forEach {
val neighbours = f(it)
yieldAll(neighbours)
yieldedCount += neighbours.size
toAdd.addAll(neighbours)
}
elementsToCheck = toAdd
sizeBeforeIteration = yieldedCount
}
}
| apache-2.0 | 96aa3a8c3a0921ab9bd5dc8b43692d97 | 43.164474 | 146 | 0.754655 | 5.898946 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/test/kotlin/com/acornui/DisposableBaseTest.kt | 1 | 1027 | /*
* Copyright 2020 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui
import kotlin.test.Test
import kotlin.test.assertTrue
class DisposableBaseTest {
@Test fun disposeRemovesOwnership() {
val a = D()
val b = D(a)
b.dispose()
a.dispose()
assertTrue(true)
}
@Test fun disposeOwnerDisposesOwned() {
val a = D()
val b = D(a)
a.dispose()
assertTrue(b.isDisposed)
}
}
private class D(owner: Owner? = null) : DisposableBase(owner), ManagedDisposable {
}
| apache-2.0 | 49d5154173b5effc02a16673c20c887d | 23.452381 | 82 | 0.714703 | 3.565972 | false | true | false | false |
AcornUI/Acorn | acornui-core/src/test/kotlin/com/acornui/asset/CacheImplTest.kt | 1 | 1513 | @file:Suppress("RemoveExplicitTypeArguments")
package com.acornui.asset
import com.acornui.async.delay
import com.acornui.di.ContextImpl
import com.acornui.test.initMockDom
import com.acornui.test.runTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.milliseconds
class CacheImplTest {
private val context = ContextImpl()
@BeforeTest
fun setup() {
initMockDom()
}
@Test fun testSet() {
val cache = CacheImpl(context)
val key = "key"
cache[key] = "Test"
assertEquals<String?>("Test", cache[key])
}
@Test fun testGc() = runTest {
val cache = CacheImpl(context, disposalTime = 10.milliseconds)
val key = "key"
cache[key] = "Test"
// Ensure keys with a reference are not discarded.
cache.refInc(key)
delay(20.milliseconds)
assertEquals<String?>("Test", cache[key])
// Ensure keys without a reference are discarded, but only after at least gcFrames.
cache.refDec(key)
delay(2.milliseconds)
assertEquals<String?>("Test", cache[key])
delay(50.milliseconds)
assertEquals<String?>(null, cache[key])
}
@Test fun testGc2() = runTest {
val cache = CacheImpl(context, disposalTime = 10.milliseconds)
val key = "key"
cache[key] = "Test"
// Ensure keys with no references are not immediately discarded.
cache.refInc(key)
cache.refDec(key)
delay(2.milliseconds)
assertEquals<String?>("Test", cache[key])
cache.refInc(key)
delay(20.milliseconds)
assertEquals<String?>("Test", cache[key])
}
} | apache-2.0 | b5407fe22d52d13f11774aa75da799d6 | 23.031746 | 85 | 0.722406 | 3.310722 | false | true | false | false |
JohnnyShieh/Gank | app/src/main/kotlin/com/johnny/gank/adapter/GankListAdapter.kt | 1 | 5059 | package com.johnny.gank.adapter
/*
* Copyright (C) 2016 Johnny Shieh 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.
*/
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.johnny.gank.R
import com.johnny.gank.model.ui.GankGirlImageItem
import com.johnny.gank.model.ui.GankHeaderItem
import com.johnny.gank.model.ui.GankItem
import com.johnny.gank.model.ui.GankNormalItem
import kotlinx.android.synthetic.main.recycler_item_category_title.view.*
import kotlinx.android.synthetic.main.recycler_item_gank.view.*
import kotlinx.android.synthetic.main.recycler_item_girl_imge.view.*
/**
* description
*
* @author Johnny Shieh ([email protected])
* @version 1.0
*/
class GankListAdapter(private val fragment: Fragment) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
const val VIEW_TYPE_NORMAL = 1
const val VIEW_TYPE_HEADER = 2
const val VIEW_TYPE_GIRL_IMAGE = 3
}
interface OnItemClickListener {
fun onClickNormalItem(view: View, normalItem: GankNormalItem)
fun onClickGirlItem(view: View, girlImageItem: GankGirlImageItem)
}
private val items = mutableListOf<GankItem>()
var onItemClickListener: OnItemClickListener? = null
fun swapData(list: List<GankItem>) {
items.clear()
items.addAll(list)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW_TYPE_HEADER -> CategoryHeaderViewHolder(
parent
)
VIEW_TYPE_GIRL_IMAGE -> GirlImageViewHolder(
parent
)
else -> NormalViewHolder(parent)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is CategoryHeaderViewHolder -> holder.itemView.category_title.text =
(items[position] as GankHeaderItem).name
is NormalViewHolder -> {
val normalItem = items[position] as GankNormalItem
holder.itemView.title.text = getGankTitleStr(
normalItem.gank.desc,
normalItem.gank.who
)
holder.itemView.title.setOnClickListener { view ->
onItemClickListener?.onClickNormalItem(
view,
normalItem
)
}
}
is GirlImageViewHolder -> {
val girlItem = items[position] as GankGirlImageItem
Glide.with(fragment)
.load(girlItem.imgUrl)
.apply(
RequestOptions()
.placeholder(R.color.imageColorPlaceholder)
.centerCrop()
).into(holder.itemView.girl_image)
holder.itemView.setOnClickListener { view ->
onItemClickListener?.onClickGirlItem(
view,
girlItem
)
}
}
}
}
override fun getItemViewType(position: Int): Int {
when (items[position]) {
is GankHeaderItem -> return VIEW_TYPE_HEADER
is GankGirlImageItem -> return VIEW_TYPE_GIRL_IMAGE
else -> return VIEW_TYPE_NORMAL
}
}
override fun getItemCount(): Int {
return items.size
}
class CategoryHeaderViewHolder(parent: ViewGroup) :
RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.recycler_item_category_title,
parent,
false
)
)
class NormalViewHolder(parent: ViewGroup) :
RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.recycler_item_gank,
parent,
false
)
)
class GirlImageViewHolder(parent: ViewGroup) :
RecyclerView.ViewHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.recycler_item_girl_imge,
parent,
false
)
)
}
| apache-2.0 | 25f386838b60d003c0d250a79862829e | 32.282895 | 96 | 0.606049 | 4.804368 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/layers/merge/biaffine/BiaffineLayerUtils.kt | 1 | 2350 | /* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.layers.merge.biaffine
import com.kotlinnlp.simplednn.core.arrays.AugmentedArray
import com.kotlinnlp.simplednn.core.functionalities.activations.Tanh
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.layers.models.merge.biaffine.BiaffineLayerParameters
import com.kotlinnlp.simplednn.core.layers.models.merge.biaffine.BiaffineLayer
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
/**
*
*/
internal object BiaffineLayerUtils {
/**
*
*/
fun buildLayer(): BiaffineLayer<DenseNDArray> = BiaffineLayer(
inputArray1 = AugmentedArray(values = DenseNDArrayFactory.arrayOf(doubleArrayOf(-0.8, -0.9))),
inputArray2 = AugmentedArray(values = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, -0.2, 0.6))),
inputType = LayerType.Input.Dense,
outputArray = AugmentedArray(size = 2),
params = buildParams(),
activationFunction = Tanh,
dropout = 0.0
)
/**
*
*/
fun buildParams() = BiaffineLayerParameters(inputSize1 = 2, inputSize2 = 3, outputSize = 2).apply {
w1.values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.3, 0.8),
doubleArrayOf(0.8, -0.7)
)))
w2.values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.6, 0.5, -0.9),
doubleArrayOf(0.3, -0.3, 0.3)
)))
b.values.assignValues(DenseNDArrayFactory.arrayOf(doubleArrayOf(0.5, -0.4)))
w[0].values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.4, 0.2),
doubleArrayOf(0.2, 0.4),
doubleArrayOf(0.0, 0.5)
)))
w[1].values.assignValues(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(-0.2, 0.9),
doubleArrayOf(0.5, 0.0),
doubleArrayOf(-0.1, -0.1)
)))
}
/**
*
*/
fun getOutputGold() = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.1, -0.3))
}
| mpl-2.0 | 6188aae7270231495a56ee2f349eb027 | 30.756757 | 102 | 0.673617 | 3.929766 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveTypeVarianceFix.kt | 1 | 2642 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtTypeParameter
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.Variance
class RemoveTypeVarianceFix(
typeParameter: KtTypeParameter,
private val variance: Variance,
private val type: String
) : KotlinQuickFixAction<KtTypeParameter>(typeParameter) {
override fun getText(): String = KotlinBundle.message("remove.0.variance.from.1", variance.label, type)
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val typeParameter = element ?: return
when (variance) {
Variance.IN_VARIANCE -> KtTokens.IN_KEYWORD
Variance.OUT_VARIANCE -> KtTokens.OUT_KEYWORD
else -> null
}?.let {
typeParameter.removeModifier(it)
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtTypeParameter>? {
val typeReference = diagnostic.psiElement.parent as? KtTypeReference ?: return null
val type = typeReference.analyze(BodyResolveMode.PARTIAL)[BindingContext.TYPE, typeReference] ?: return null
val descriptor = type.constructor.declarationDescriptor as? TypeParameterDescriptor ?: return null
val variance = descriptor.variance
if (variance == Variance.INVARIANT) return null
val typeParameter = DescriptorToSourceUtils.getSourceFromDescriptor(descriptor) as? KtTypeParameter ?: return null
return RemoveTypeVarianceFix(typeParameter, variance, IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type))
}
}
} | apache-2.0 | ef1f140630b017b1ae1e066e9771ad30 | 47.054545 | 158 | 0.761923 | 5.003788 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/HasExpectedMarker.kt | 1 | 2108 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.highlighter.markers
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.MemberDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.toDescriptor
import org.jetbrains.kotlin.idea.util.expectedDescriptors
import org.jetbrains.kotlin.idea.util.expectedDeclarationIfAny
import org.jetbrains.kotlin.psi.KtDeclaration
fun getExpectedDeclarationTooltip(declaration: KtDeclaration): String? {
val descriptor = declaration.toDescriptor() as? MemberDescriptor ?: return null
val expectDescriptors = descriptor.expectedDescriptors()
val modulesString = getModulesStringForExpectActualMarkerTooltip(expectDescriptors) ?: return null
return KotlinBundle.message(
"highlighter.tool.tip.has.expect.declaration.in", modulesString
)
}
fun KtDeclaration.allNavigatableExpectedDeclarations(): List<KtDeclaration> =
listOfNotNull(expectedDeclarationIfAny()) + findMarkerBoundDeclarations().mapNotNull { it.expectedDeclarationIfAny() }
@NlsContexts.PopupTitle
fun KtDeclaration.navigateToExpectedTitle() = KotlinBundle.message("highlighter.title.choose.expected.for", name.toString())
@NlsContexts.TabTitle
fun KtDeclaration.navigateToExpectedUsagesTitle() = KotlinBundle.message("highlighter.title.expected.for", name.toString())
fun buildNavigateToExpectedDeclarationsPopup(element: PsiElement?): NavigationPopupDescriptor? {
return element?.markerDeclaration?.let {
val navigatableExpectedDeclarations = it.allNavigatableExpectedDeclarations()
if (navigatableExpectedDeclarations.isEmpty()) return null
return NavigationPopupDescriptor(
navigatableExpectedDeclarations,
it.navigateToExpectedTitle(),
it.navigateToExpectedUsagesTitle(),
ActualExpectedPsiElementCellRenderer()
)
}
}
| apache-2.0 | 8b38938c1c356a669a558081060de22a | 46.909091 | 158 | 0.79649 | 4.995261 | false | false | false | false |
VTUZ-12IE1bzud/TruckMonitor-Android | app/src/main/kotlin/ru/annin/truckmonitor/presentation/ui/fragment/MapFragment.kt | 1 | 4186 | package ru.annin.truckmonitor.presentation.ui.fragment
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.arellomobile.mvp.MvpAppCompatFragment
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PolylineOptions
import ru.annin.truckmonitor.R
import ru.annin.truckmonitor.domain.model.CheckPoints
import ru.annin.truckmonitor.presentation.common.BaseViewDelegate
import ru.annin.truckmonitor.utils.safeLet
import ru.annin.truckmonitor.utils.toBitmap
/**
* Экран карты.
*
* @author Pavel Annin.
*/
class MapFragment : MvpAppCompatFragment(), OnMapReadyCallback {
companion object {
private const val ARG_CHECK_POINTS = "ru.annin.truckmonitor.arg.check_points"
@JvmStatic fun newInstance(contracts: List<CheckPoints>?) = MapFragment().apply {
arguments = Bundle().apply {
putSerializable(ARG_CHECK_POINTS, contracts?.let { ArrayList(it) })
}
}
}
// Component's
private lateinit var viewDelegate: ViewDelegate
private var map: GoogleMap? = null
// Data's
private var checkPoints: List<CheckPoints>? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_map, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Data's
checkPoints = arguments?.getSerializable(ARG_CHECK_POINTS) as ArrayList<CheckPoints>? ?: ArrayList()
viewDelegate = ViewDelegate(view).apply {
vMap.onCreate(null)
vMap.getMapAsync(this@MapFragment)
}
}
override fun onResume() {
super.onResume()
viewDelegate.vMap.onResume()
}
override fun onPause() {
super.onPause()
viewDelegate.vMap.onPause()
}
override fun onDestroy() {
viewDelegate.vMap.onDestroy()
super.onDestroy()
}
override fun onMapReady(googleMap: GoogleMap?) {
map = googleMap
map?.let {
it.uiSettings.isMyLocationButtonEnabled = true
it.isMyLocationEnabled = true
}
updateCheckPoints(checkPoints)
}
fun updateCheckPoints(checkPoints: List<CheckPoints>?) {
safeLet(map, checkPoints) { map, points ->
map.clear()
// Marker
points.forEach {
map.addMarker(MarkerOptions()
.position(LatLng(it.coordinate.latitude.toDouble(), it.coordinate.longitude.toDouble()))
.title(it.name)
.snippet(it.address)
.icon(BitmapDescriptorFactory.fromBitmap(if (it.fact.isNullOrBlank())
R.drawable.ic_marker.toBitmap(activity) else R.drawable.ic_marker_disable.toBitmap(activity)))
)
}
// Polyline
val poly = PolylineOptions()
.width(4f)
.color(Color.RED)
.geodesic(true)
points.indices
.filter { it <= points.size - 2 }
.forEach {
poly.add(LatLng(points[it].coordinate.latitude.toDouble(), points[it].coordinate.longitude.toDouble()),
LatLng(points[it + 1].coordinate.latitude.toDouble(), points[it + 1].coordinate.longitude.toDouble()))
}
map.addPolyline(poly)
}
}
private class ViewDelegate(vRoot: View) : BaseViewDelegate(vRoot) {
// View's
val vMap by findView<MapView>(R.id.v_map)
}
} | apache-2.0 | 9fa5e20eaf1966ae6de00d2384b179c3 | 33.237705 | 134 | 0.636255 | 4.60419 | false | false | false | false |
android/nowinandroid | core/database/src/main/java/com/google/samples/apps/nowinandroid/core/database/model/AuthorEntity.kt | 1 | 1511 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.database.model
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.samples.apps.nowinandroid.core.model.data.Author
/**
* Defines an author for [NewsResourceEntity].
* It has a many to many relationship with both entities
*/
@Entity(
tableName = "authors",
)
data class AuthorEntity(
@PrimaryKey
val id: String,
val name: String,
@ColumnInfo(name = "image_url")
val imageUrl: String,
@ColumnInfo(defaultValue = "")
val twitter: String,
@ColumnInfo(name = "medium_page", defaultValue = "")
val mediumPage: String,
@ColumnInfo(defaultValue = "")
val bio: String,
)
fun AuthorEntity.asExternalModel() = Author(
id = id,
name = name,
imageUrl = imageUrl,
twitter = twitter,
mediumPage = mediumPage,
bio = bio,
)
| apache-2.0 | fc2963fef8d7ecf284bfb86ab108455d | 28.057692 | 75 | 0.712773 | 4.029333 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/yargor/YarGorTrip.kt | 1 | 4321 | /*
* YarGorTrip.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.yargor
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.Localizer
import au.id.micolous.metrodroid.multi.Parcelize
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.TransitData
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.util.NumberUtils
import au.id.micolous.metrodroid.util.StationTableReader
import au.id.micolous.metrodroid.util.hexString
@Parcelize
data class YarGorTrip(
override val startTimestamp: TimestampFull,
private val mA: Int,
private val mRoute: Int,
private val mVehicle: Int,
private val mB: Int,
// sequential number of round trips that bus makes
private val mTrackNumber: Int) : Trip() {
override val fare: TransitCurrency?
get() = null
override val mode: Mode
get() = StationTableReader.getLineMode(YARGOR_STR, mRoute)
?: when(mRoute/100) {
0,20 -> Mode.BUS
1 -> Mode.TRAM
2,3 -> Mode.TROLLEYBUS
else -> Mode.OTHER
}
override fun getAgencyName(isShort: Boolean): FormattedString =
when (mode) {
Mode.TRAM -> Localizer.localizeFormatted(R.string.mode_tram)
Mode.TROLLEYBUS -> Localizer.localizeFormatted(R.string.mode_trolleybus)
Mode.BUS -> Localizer.localizeFormatted(R.string.mode_bus)
else -> Localizer.localizeFormatted(R.string.unknown_format, mRoute / 100)
}
override val routeName: FormattedString
get() = StationTableReader.getLineNameNoFallback(YARGOR_STR, mRoute) ?: FormattedString((mRoute % 100).toString())
override val vehicleID: String?
get() = mVehicle.toString()
override fun getRawFields(level: TransitData.RawLevel): String? =
"A=${mA.hexString}/B=${mB.hexString}" +
if (level == TransitData.RawLevel.ALL)
"/trackNumber=$mTrackNumber/route=$mRoute"
else ""
companion object {
private const val YARGOR_STR = "yargor"
private fun parseTimestampBCD(data: ImmutableByteArray, off: Int): TimestampFull =
TimestampFull(tz = YarGorTransitData.TZ,
year = 2000 + NumberUtils.convertBCDtoInteger(data[off].toInt() and 0xff),
month = NumberUtils.convertBCDtoInteger(data[off + 1].toInt() and 0xff) - 1,
day = NumberUtils.convertBCDtoInteger(data[off + 2].toInt() and 0xff),
hour = NumberUtils.convertBCDtoInteger(data[off + 3].toInt() and 0xff),
min = NumberUtils.convertBCDtoInteger(data[off + 4].toInt() and 0xff),
sec = NumberUtils.convertBCDtoInteger(data[off + 5].toInt() and 0xff))
fun parse(input: ImmutableByteArray): YarGorTrip? {
if (input[9] == 0.toByte())
return null
return YarGorTrip(startTimestamp = parseTimestampBCD(input, 9),
mVehicle = input.byteArrayToIntReversed(0, 2),
mA = input[2].toInt() and 0xff,
mRoute = input.byteArrayToIntReversed(3, 2),
mB = input.byteArrayToIntReversed(5, 2),
mTrackNumber = input.byteArrayToInt(7, 2))
}
}
}
| gpl-3.0 | 3b2fb400fc39f373548a9e86106c4ffb | 43.546392 | 122 | 0.647072 | 4.299502 | false | false | false | false |
Mystery00/JanYoShare | app/src/main/java/com/janyo/janyoshare/activity/RenameActivity.kt | 1 | 1376 | package com.janyo.janyoshare.activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.content.FileProvider
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.janyo.janyoshare.R
import vip.mystery0.tools.logs.Logs
import java.io.File
class RenameActivity : AppCompatActivity()
{
private val TAG = "RenameActivity"
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
val action = intent.action
val type = intent.type
if (action == Intent.ACTION_VIEW && type != null)
{
val uri = intent.data
val file = File(uri.path)
if (file.renameTo(File(file.parent + File.separator + file.nameWithoutExtension + ".apk")))
{
Logs.i(TAG, "onCreate: 重命名完成")
val intent = Intent(Intent.ACTION_VIEW)
val openFile = File(file.parent + File.separator + file.name + ".apk")
val openUri = if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M)
FileProvider.getUriForFile(this, getString(R.string.authorities), openFile)
else
Uri.fromFile(openFile)
intent.setDataAndType(openUri, "application/vnd.android.package-archive")
startActivity(intent)
}
else
{
Toast.makeText(this, R.string.hint_jys_rename_error, Toast.LENGTH_SHORT)
.show()
}
}
finish()
}
} | gpl-3.0 | 1bce14759c419210ec8b17e3b4ed0242 | 28.717391 | 94 | 0.728404 | 3.37284 | false | false | false | false |
ACRA/acra | acra-core/src/main/java/org/acra/data/CrashReportDataFactory.kt | 1 | 3994 | /*
* Copyright (c) 2017
*
* 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.acra.data
import android.content.Context
import org.acra.builder.ReportBuilder
import org.acra.collector.ApplicationStartupCollector
import org.acra.collector.Collector
import org.acra.collector.CollectorException
import org.acra.config.CoreConfiguration
import org.acra.log.debug
import org.acra.log.warn
import java.util.concurrent.ExecutionException
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
/**
* Responsible for collecting the CrashReportData for an Exception.
*
* @author F43nd1r
* @since 4.3.0
*/
class CrashReportDataFactory(private val context: Context, private val config: CoreConfiguration) {
private val collectors: List<Collector> = config.pluginLoader.loadEnabled(config, Collector::class.java).sortedBy { it.safeOrder }
private val Collector.safeOrder
get() = try {
order
} catch (t: Exception) {
Collector.Order.NORMAL
}
/**
* Collects crash data.
*
* @param builder ReportBuilder for whom to crete the crash report.
* @return CrashReportData identifying the current crash.
*/
fun createCrashData(builder: ReportBuilder): CrashReportData {
val executorService = if (config.parallel) Executors.newCachedThreadPool() else Executors.newSingleThreadExecutor()
val crashReportData = CrashReportData()
collectors.groupBy { it.safeOrder }.toSortedMap().forEach { (order, collectors) ->
debug { "Starting collectors with priority ${order.name}" }
collect(collectors, executorService, builder, crashReportData)
debug { "Finished collectors with priority ${order.name}" }
}
return crashReportData
}
private fun collect(collectors: List<Collector>, executorService: ExecutorService, builder: ReportBuilder, crashReportData: CrashReportData) {
val futures = collectors.map { collector ->
executorService.submit {
//catch absolutely everything possible here so no collector obstructs the others
try {
debug { "Calling collector ${collector.javaClass.name}" }
collector.collect(context, config, builder, crashReportData)
debug { "Collector ${collector.javaClass.name} completed" }
} catch (e: CollectorException) {
warn(e) { "" }
} catch (t: Throwable) {
warn(t) { "Error in collector ${collector.javaClass.simpleName}" }
}
}
}
for (future in futures) {
while (!future.isDone) {
try {
future.get()
} catch (ignored: InterruptedException) {
} catch (e: ExecutionException) {
break
}
}
}
}
fun collectStartUp() {
for (collector in collectors) {
if (collector is ApplicationStartupCollector) {
//catch absolutely everything possible here so no collector obstructs the others
try {
collector.collectApplicationStartUp(context, config)
} catch (t: Throwable) {
warn(t) { "${collector.javaClass.simpleName} failed to collect its startup data" }
}
}
}
}
} | apache-2.0 | 506b709dc26ea0046abf07076de28e84 | 37.786408 | 146 | 0.636955 | 4.870732 | false | true | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/util/ViewExtensions.kt | 1 | 665 | package org.thoughtcrime.securesms.util
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
var View.visible: Boolean
get() {
return this.visibility == View.VISIBLE
}
set(value) {
this.visibility = if (value) View.VISIBLE else View.GONE
}
fun View.padding(left: Int = paddingLeft, top: Int = paddingTop, right: Int = paddingRight, bottom: Int = paddingBottom) {
setPadding(left, top, right, bottom)
}
fun ConstraintLayout.changeConstraints(change: ConstraintSet.() -> Unit) {
val set = ConstraintSet()
set.clone(this)
set.change()
set.applyTo(this)
}
| gpl-3.0 | 748cb8f87588cc99a495cad5efaeadb8 | 26.708333 | 122 | 0.744361 | 3.911765 | false | false | false | false |
jk1/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/Row.kt | 3 | 2363 | // 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.ui.layout
import com.intellij.ui.components.Label
import com.intellij.util.ui.UIUtil.ComponentStyle
import com.intellij.util.ui.UIUtil.FontColor
import javax.swing.JComponent
abstract class Row : Cell() {
abstract var enabled: Boolean
abstract var visible: Boolean
abstract var subRowsEnabled: Boolean
abstract var subRowsVisible: Boolean
protected abstract val builder: LayoutBuilderImpl
// backward compatibility - return type should be void
fun label(text: String, gapLeft: Int = 0, style: ComponentStyle? = null, fontColor: FontColor? = null, bold: Boolean = false) {
val label = Label(text, style, fontColor, bold)
label(gapLeft = gapLeft)
}
/**
* Specifies the right alignment for the component if the cell is larger than the component plus its gaps.
*/
inline fun right(init: Row.() -> Unit) {
alignRight()
init()
}
@PublishedApi
internal abstract fun alignRight()
inline fun row(label: String, init: Row.() -> Unit): Row {
val row = createRow(label)
row.init()
return row
}
inline fun row(init: Row.() -> Unit): Row {
val row = createRow(null)
row.init()
return row
}
/**
* Shares cell between components.
*/
inline fun cell(isVerticalFlow: Boolean = false, init: Cell.() -> Unit) {
setCellMode(true, isVerticalFlow)
init()
setCellMode(false, isVerticalFlow)
}
@PublishedApi
internal abstract fun createRow(label: String?): Row
@PublishedApi
internal abstract fun setCellMode(value: Boolean, isVerticalFlow: Boolean)
// backward compatibility
@Deprecated(level = DeprecationLevel.HIDDEN, message = "deprecated")
operator fun JComponent.invoke(vararg constraints: CCFlags, gapLeft: Int = 0, growPolicy: GrowPolicy? = null) {
invoke(constraints = *constraints, gapLeft = gapLeft, growPolicy = growPolicy, comment = null)
}
@Deprecated(level = DeprecationLevel.ERROR, message = "Do not create standalone panel, if you want layout components in vertical flow mode, use cell(isVerticalFlow = true)")
fun panel(vararg constraints: LCFlags, title: String? = null, init: LayoutBuilder.() -> Unit) {
}
}
enum class GrowPolicy {
SHORT_TEXT, MEDIUM_TEXT
} | apache-2.0 | 226700444c2339bc29483a8fa5673563 | 29.701299 | 175 | 0.7135 | 4.204626 | false | false | false | false |
abertschi/ad-free | app/src/main/java/ch/abertschi/adfree/view/home/HomeActivity.kt | 1 | 3657 | /*
* Ad Free
* Copyright (c) 2017 by abertschi, www.abertschi.ch
* See the file "LICENSE" for the full license governing this code.
*/
package ch.abertschi.adfree.view.home
import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.support.v4.app.Fragment
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import ch.abertschi.adfree.R
import ch.abertschi.adfree.di.HomeModul
import ch.abertschi.adfree.presenter.HomePresenter
import ch.abertschi.adfree.view.ViewSettings
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.onClick
/**
* Created by abertschi on 15.04.17.
*/
class HomeActivity() : Fragment(), HomeView, AnkoLogger {
private lateinit var typeFace: Typeface
private lateinit var enjoySloganText: TextView
private lateinit var homePresenter: HomePresenter
private lateinit var updateMessageInfo: TextView
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.home_view, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
homePresenter = HomeModul(this.activity!!, this).provideSettingsPresenter()
typeFace = ViewSettings.instance(this.context!!).typeFace
enjoySloganText = view.findViewById(R.id.enjoy) as TextView
updateMessageInfo =
view.findViewById(R.id.version_update_reminder) as TextView
view.findViewById<TextView>(R.id.troubleshooting).onClick {
homePresenter.onTroubleshooting()
}
homePresenter.onCreate(this.context!!)
// TODO: this is debug code
// val r: Random = Random()
// val c: AdFreeApplication = globalContext.applicationContext as AdFreeApplication
// view.onTouch { view, motionEvent ->
// info { "AdFree event created" }
// when (r.nextBoolean()) {
// true -> c.adDetector.notifyObservers(AdEvent(EventType.IS_AD))
// else -> c.adDetector.notifyObservers(AdEvent(EventType.NO_AD))
// }
// true
// }
}
override fun showUpdateMessage(show: Boolean) {
if (show ){
updateMessageInfo.visibility = View.VISIBLE
updateMessageInfo.onClick {
homePresenter.onUpdateMessageClicked()
}
} else {
updateMessageInfo.visibility = View.GONE
}
}
override fun onResume() {
homePresenter.onResume(this.context!!)
super.onResume()
}
override fun showPermissionRequired() {
val text = "touch here to grant permission"
setSloganText(text)
enjoySloganText.setOnClickListener {
showNotificationPermissionSettings()
}
}
override fun showNotificationPermissionSettings() {
startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"))
}
private fun setSloganText(text: String) {
enjoySloganText.typeface = typeFace
enjoySloganText.text = Html.fromHtml(text)
}
override fun showEnjoyAdFree() {
val text = "<font color=#FFFFFF>enjoy</font> your <font color=#FFFFFF>ad-free</font> music experience."
setSloganText(text)
enjoySloganText.setOnClickListener(null)
}
// override fun setPowerState(state: Boolean) {
// powerButton.isChecked = state
// }
}
| apache-2.0 | 1528042e6eb96b07264d6dda257b1dcd | 31.078947 | 111 | 0.672136 | 4.411339 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/egl/src/templates/kotlin/egl/templates/ExtensionFlags.kt | 3 | 11119 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package egl.templates
import egl.*
import org.lwjgl.generator.*
val EXT = "EXT"
val KHR = "KHR"
val ANDROID = "ANDROID"
val ANGLE = "ANGLE"
val ARM = "ARM"
val HI = "HI"
val IMG = "IMG"
val MESA = "MESA"
val NOK = "NOK"
val NV = "NV"
val OVR = "OVR"
val TIZEN = "TIZEN"
val WL = "WL"
private val NativeClass.cap: String get() = "{@link #$capName $templateName}"
val EXT_client_extensions = EXT_FLAG.nativeClassEGL("EXT_client_extensions", postfix = EXT) {
documentation =
"""
When true, the $registryLink extension is supported.
This extension introduces the concept of *extension type*, requires that each EGL extension belong to exactly one type, and defines two types: display
and client. It also provides a method to query, without initializing a display, the set of supported client extensions.
A display extension adds functionality to an individual EGLDisplay. This type of extension has always existed but, until EGL_EXT_client_extensions,
lacked an identifying name.
A client extension adds functionality that is independent of any display. In other words, it adds functionality to the EGL client library itself. This
is a new type of extension defined by EGL_EXT_client_extensions. EGL_EXT_client_extensions is itself a client extension.
We suggest that each future extension clearly state its type by including the following toplevel section in its extension specification, preceding the
Dependencies section. For client extensions, this suggestion is a requirement.
${codeBlock("""
Extension Type
<Either "EGL display extension" or "EGL client extension" or
a future extension type.>""")}
By cleanly separating display extensions from client extensions, EGL_EXT_client_extensions solves a bootstrap problem for future EGL extensions that
will modify display initialization. To query for such extensions without EGL_EXT_client_extensions, an EGL client would need to initialize a throw-away
EGLDisplay solely to query its extension string. Initialization of the throw-away display may have undesired side-effects (discussed in the issues
section below) for EGL clients that wish to use the new methods of display initialization.
"""
}
val EXT_explicit_device = EXT_FLAG.nativeClassEGL("EXT_explicit_device", postfix = EXT) {
documentation =
"""
When true, the $registryLink extension is supported.
A system may support rendering with multiple devices for the same windowing system. In that case, an EGL implementation must select a default device
based on the native display.
This extension allows an application to explicitly request a device to use for rendering instead of the implementation's default.
This differs from ${EXT_platform_device.link} in that {@code EGL_EXT_platform_device} uses an {@code EGLDeviceEXT} instead of a native display. Thus,
{@code EGL_EXT_platform_device} allows offscreen rendering to a pbuffer or FBO, but it does not require or use a windowing system, and thus does not
allow pixmap or window surfaces.
Using {@code EGL_EXT_explicit_device} with {@code EGL_MESA_platform_surfaceless} is functionally identical to {@code EGL_EXT_platform_device}.
"""
}
val KHR_client_get_all_proc_addresses = EXT_FLAG.nativeClassEGL("KHR_client_get_all_proc_addresses", postfix = KHR) {
documentation =
"""
When true, the ${registryLink("KHR", "EGL_KHR_get_all_proc_addresses")} extension is supported.
eglGetProcAddress is currently defined to not support the querying of non-extension EGL or client API functions. Non-extension functions are expected
to be exposed as library symbols that can be resolved statically at link time, or dynamically at run time using OS-specific runtime linking mechanisms.
With the addition of OpenGL and OpenGL ES 3 support to EGL, the definition of a non-extension function becomes less clear. It is common for one OpenGL
library to implement many versions of OpenGL. The suggested library name for OpenGL ES 3 is the same as that of OpenGL ES 2. If OpenGL ES 3
applications linked statically to OpenGL ES 3 functions are run on a system with only OpenGL ES 2 support, they may fail to load. Similar problems
would be encountered by an application linking statically to various OpenGL functions.
To avoid requiring applications to fall back to OS-specific dynamic linking mechanisms, this extension drops the requirement that eglGetProcAddress
return only non-extension functions. If the extension string is present, applications can query all EGL and client API functions using
eglGetProcAddress.
To allow users to query this extension before initializing a display, and to also allow vendors to ship this extension without
EGL_EXT_client_extensions, two names are assigned to this extension: one a display extension and the other a client extension. Identical functionality
is exposed by each name, but users query each name using different methods. Users query EGL_KHR_get_all_proc_addresses in the usual way; that is, by
calling eglQueryString(dpy, EGL_EXTENSIONS) on an initialized display. To query EGL_KHR_client_get_all_proc_addresses, users must use a different
method which is described below in the section concerning EGL_EXT_client_extensions.
Requires ${EGL12.core}.
"""
}
val KHR_get_all_proc_addresses = EXT_FLAG.nativeClassEGL("KHR_get_all_proc_addresses", postfix = KHR) {
documentation =
"""
When true, the $registryLink extension is supported.
eglGetProcAddress is currently defined to not support the querying of non-extension EGL or client API functions. Non-extension functions are expected
to be exposed as library symbols that can be resolved statically at link time, or dynamically at run time using OS-specific runtime linking mechanisms.
With the addition of OpenGL and OpenGL ES 3 support to EGL, the definition of a non-extension function becomes less clear. It is common for one OpenGL
library to implement many versions of OpenGL. The suggested library name for OpenGL ES 3 is the same as that of OpenGL ES 2. If OpenGL ES 3
applications linked statically to OpenGL ES 3 functions are run on a system with only OpenGL ES 2 support, they may fail to load. Similar problems
would be encountered by an application linking statically to various OpenGL functions.
To avoid requiring applications to fall back to OS-specific dynamic linking mechanisms, this extension drops the requirement that eglGetProcAddress
return only non-extension functions. If the extension string is present, applications can query all EGL and client API functions using
eglGetProcAddress.
To allow users to query this extension before initializing a display, and to also allow vendors to ship this extension without
EGL_EXT_client_extensions, two names are assigned to this extension: one a display extension and the other a client extension. Identical functionality
is exposed by each name, but users query each name using different methods. Users query EGL_KHR_get_all_proc_addresses in the usual way; that is, by
calling eglQueryString(dpy, EGL_EXTENSIONS) on an initialized display. To query EGL_KHR_client_get_all_proc_addresses, users must use a different
method which is described below in the section concerning EGL_EXT_client_extensions.
Requires ${EGL12.core}.
"""
}
val KHR_stream_producer_aldatalocator = EXT_FLAG.nativeClassEGL("KHR_stream_producer_aldatalocator", postfix = KHR) {
documentation =
"""
When true, the $registryLink extension is supported.
This extension (in conjunction with the OpenMAX_AL_EGLStream_DataLocator extension to OpenMAX AL) allows an OpenMAX AL MediaPlayer object to be
connected as the producer of an EGLStream.
After the EGLStream is created and connected to a consumer, the OpenMAX AL MediaPlayer object is created by calling <pEngine>'s
CreateMediaPlayer() method. The <pImageVideoSnk> argument points to an XADataLocator_EGLStream containing the EGLStreamKHR handle of the stream.
The CreateMediaPlayer() method creates a MediaPlayer object and connects it as the producer of the EGLStream. (Note that the pFormat member of the
XADataSink structure is ignored in this case and may be #NULL.)
Once connected the MediaPlayer inserts image frames into the EGLStream.
Requires ${EGL12.core} and ${KHR_stream.link}. Requires OpenMAX AL 1.1 and OpenMAX_AL_EGLStream_DataLocator.
"""
}
val KHR_surfaceless_context = EXT_FLAG.nativeClassEGL("KHR_surfaceless_context", postfix = KHR) {
documentation =
"""
When true, the $registryLink extension is supported.
These extensions allows an application to make a context current by passing EGL_NO_SURFACE for the write and read surface in the call to
eglMakeCurrent. The motivation is that applications that only want to render to client API targets (such as OpenGL framebuffer objects) should not need
to create a throw-away EGL surface just to get a current context.
The state of an OpenGL ES context with no default framebuffer provided by EGL is the same as a context with an incomplete framebuffer object bound.
"""
}
val NV_post_convert_rounding = EXT_FLAG.nativeClassEGL("NV_post_convert_rounding", postfix = NV) {
documentation =
"""
When true, the $registryLink extension is supported.
This extension defines the conversions for posting operations when the destination's number of components or component sizes do not match the color
buffer. This extension supports posting a 24 bit (888) color buffer to a 16 bit (565) destination buffer, posting a 16 bit (565) color buffer to a 24
bit (888) destination buffer, and posting a component that is present in the source buffer, but not present in the destination buffer.
"""
}
val NV_stream_cross_object = EXT_FLAG.nativeClassEGL("NV_stream_cross_object", postfix = NV) { documentation = "See ${NV_stream_remote.link}." }
val NV_stream_cross_display = EXT_FLAG.nativeClassEGL("NV_stream_cross_display", postfix = NV) { documentation = "See ${NV_stream_remote.link}." }
val NV_stream_cross_process = EXT_FLAG.nativeClassEGL("NV_stream_cross_process", postfix = NV) { documentation = "See ${NV_stream_remote.link}." }
val NV_stream_cross_partition = EXT_FLAG.nativeClassEGL("NV_stream_cross_partition", postfix = NV) { documentation = "See ${NV_stream_remote.link}." }
val NV_stream_cross_system = EXT_FLAG.nativeClassEGL("NV_stream_cross_system", postfix = NV) { documentation = "See ${NV_stream_remote.link}." } | bsd-3-clause | df2c3f09180bcef4513b3c73297d9928 | 62.542857 | 159 | 0.737027 | 4.68563 | false | false | false | false |
ClearVolume/scenery | src/test/kotlin/graphics/scenery/tests/examples/advanced/ProceduralTextureExample.kt | 2 | 3890 | package graphics.scenery.tests.examples.advanced
import org.joml.Vector3f
import graphics.scenery.*
import graphics.scenery.backends.Renderer
import graphics.scenery.attribute.material.DefaultMaterial
import graphics.scenery.textures.Texture
import net.imglib2.type.numeric.integer.UnsignedByteType
import org.joml.Vector3i
import java.nio.ByteBuffer
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
/**
* Example demonstrating procedural texturing using [Texture].
*
* @author Ulrik Günther <[email protected]>
*/
class ProceduralTextureExample : SceneryBase("ProceduralTextureExample") {
override fun init() {
renderer = hub.add(Renderer.createRenderer(hub, applicationName, scene, 512, 512))
val boxmaterial = DefaultMaterial()
with(boxmaterial) {
ambient = Vector3f(1.0f, 0.0f, 0.0f)
diffuse = Vector3f(0.0f, 1.0f, 0.0f)
specular = Vector3f(1.0f, 1.0f, 1.0f)
}
val box = Box(Vector3f(1.0f, 1.0f, 1.0f))
box.name = "le box du procedurale"
with(box) {
setMaterial(boxmaterial)
scene.addChild(this)
}
val lights = (0..2).map {
PointLight(radius = 15.0f)
}
lights.mapIndexed { i, light ->
light.spatial {
position = Vector3f(2.0f * i, 2.0f * i, 2.0f * i)
}
light.emissionColor = Vector3f(1.0f, 1.0f, 1.0f)
light.intensity = 0.5f
scene.addChild(light)
}
val cam: Camera = DetachedHeadCamera()
with(cam) {
spatial {
position = Vector3f(0.0f, 0.0f, 3.0f)
}
perspectiveCamera(50.0f, windowWidth, windowHeight)
scene.addChild(this)
}
thread {
val imageSizeX = 256
val imageSizeY = 256
val imageChannels = 3
val textureBuffer = BufferUtils.allocateByte(imageSizeX * imageSizeY * imageChannels)
var ticks = 0L
while(true) {
if(box.lock.tryLock(2, TimeUnit.MILLISECONDS)) {
box.spatial {
rotation.rotateY(0.01f)
needsUpdate = true
}
textureBuffer.generateProceduralTextureAtTick(ticks,
imageSizeX, imageSizeY, imageChannels)
box.material {
textures.put("diffuse",
Texture(
Vector3i(imageSizeX, imageSizeY, 1),
channels = imageChannels, contents = textureBuffer,
type = UnsignedByteType()))
}
box.lock.unlock()
} else {
logger.debug("unsuccessful lock")
}
Thread.sleep(50)
ticks++
}
}
}
/**
* Generates a procedural texture inside the [ByteBuffer].
*
* @param[tick] The time parameter for the generated texture.
*/
private fun ByteBuffer.generateProceduralTextureAtTick(tick: Long, width: Int, height: Int, channels: Int) {
val b = this.duplicate()
val rgba = byteArrayOf(0, 0, 0, 255.toByte())
(0 until width * height).forEach {
val x = it % width
val y = it / height
val g = (255*Math.sin(0.1*x + 0.1*y + tick/10.0f)).toInt().toByte()
val m = (Math.sin(tick/100.0) * g).toInt().toByte()
rgba[0] = g
rgba[1] = m
rgba[2] = m
b.put(rgba.take(channels).toByteArray())
}
}
companion object {
@JvmStatic
fun main(args: Array<String>) {
ProceduralTextureExample().main()
}
}
}
| lgpl-3.0 | 04e46308ea01e1ad99d3163c10d7c820 | 29.622047 | 112 | 0.530985 | 4.168274 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/indicator/datasetindicatorengine/DataSetIndicatorEngineImpl.kt | 1 | 5731 | /*
* Copyright (c) 2004-2022, University of Oslo
* 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 the HISP project 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 OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.indicator.datasetindicatorengine
import dagger.Reusable
import io.reactivex.Single
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.db.stores.internal.LinkStore
import org.hisp.dhis.android.core.arch.helpers.UidsHelper.mapByUid
import org.hisp.dhis.android.core.constant.Constant
import org.hisp.dhis.android.core.constant.ConstantCollectionRepository
import org.hisp.dhis.android.core.datavalue.DataValue
import org.hisp.dhis.android.core.datavalue.DataValueCollectionRepository
import org.hisp.dhis.android.core.indicator.IndicatorCollectionRepository
import org.hisp.dhis.android.core.indicator.IndicatorTypeCollectionRepository
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitOrganisationUnitGroupLink
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitOrganisationUnitGroupLinkTableInfo
import org.hisp.dhis.android.core.parser.internal.service.dataobject.DimensionalItemObject
import org.hisp.dhis.android.core.parser.internal.service.utils.ExpressionHelper
import org.hisp.dhis.android.core.period.Period
import org.hisp.dhis.android.core.period.internal.PeriodHelper
@Reusable
internal class DataSetIndicatorEngineImpl @Inject constructor(
private val indicatorRepository: IndicatorCollectionRepository,
private val indicatorTypeRepository: IndicatorTypeCollectionRepository,
private val dataValueRepository: DataValueCollectionRepository,
private val constantRepository: ConstantCollectionRepository,
private val orgunitGroupLinkStore: LinkStore<OrganisationUnitOrganisationUnitGroupLink>,
private val periodHelper: PeriodHelper,
private val dataSetIndicatorEvaluator: DataSetIndicatorEvaluator
) : DataSetIndicatorEngine {
override fun evaluate(
indicatorUid: String,
dataSetUid: String,
periodId: String,
orgUnitUid: String,
attributeOptionComboUid: String
): Single<Double> {
return Single.fromCallable {
blockingEvaluate(indicatorUid, dataSetUid, periodId, orgUnitUid, attributeOptionComboUid)
}
}
override fun blockingEvaluate(
indicatorUid: String,
dataSetUid: String,
periodId: String,
orgUnitUid: String,
attributeOptionComboUid: String
): Double {
val indicator = indicatorRepository.uid(indicatorUid).blockingGet()
val indicatorType = indicatorTypeRepository.uid(indicator.indicatorType()?.uid()).blockingGet()
val valueMap = getValueMap(dataSetUid, attributeOptionComboUid, orgUnitUid, periodId)
val constantMap = getConstantMap()
val orgunitGroupCountMap = getOrgunitGroupMap()
val period = getPeriod(periodId)
return dataSetIndicatorEvaluator.evaluate(
indicator = indicator,
indicatorType = indicatorType,
valueMap = valueMap,
constantMap = constantMap,
orgUnitCountMap = orgunitGroupCountMap,
days = PeriodHelper.getDays(period)
)
}
private fun getValueMap(
dataSetUid: String,
attributeOptionComboUid: String,
orgUnitUid: String,
periodId: String
): Map<DimensionalItemObject, Double> {
val dataValues: List<DataValue> = dataValueRepository
.byDataSetUid(dataSetUid)
.byPeriod().eq(periodId)
.byOrganisationUnitUid().eq(orgUnitUid)
.byAttributeOptionComboUid().eq(attributeOptionComboUid)
.byDeleted().isFalse
.blockingGet()
return ExpressionHelper.getValueMap(dataValues)
}
private fun getConstantMap(): Map<String, Constant> {
val constants: List<Constant> = constantRepository.blockingGet()
return mapByUid(constants)
}
private fun getOrgunitGroupMap(): Map<String, Int> {
return orgunitGroupLinkStore.groupAndGetCountBy(
OrganisationUnitOrganisationUnitGroupLinkTableInfo.Columns.ORGANISATION_UNIT_GROUP
)
}
private fun getPeriod(periodId: String): Period {
return periodHelper.blockingGetPeriodForPeriodId(periodId)
}
}
| bsd-3-clause | 8e58f30fa108823eb45e27bdf03ae43e | 44.125984 | 103 | 0.751876 | 4.844463 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/DiscreteSeekBar.kt | 2 | 3402 | package org.wikipedia.views
import android.content.Context
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.core.content.withStyledAttributes
import androidx.core.graphics.withSave
import org.wikipedia.R
class DiscreteSeekBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
AppCompatSeekBar(context, attrs) {
private var minNumber = 0
private var tickDrawable: Drawable? = null
private var centerDrawable: Drawable? = null
private var isRtl = false
var value: Int
get() = progress + minNumber
set(value) {
progress = value - minNumber
}
init {
if (attrs != null) {
context.withStyledAttributes(attrs, R.styleable.DiscreteSeekBar) {
minNumber = getInteger(R.styleable.DiscreteSeekBar_min, 0)
max -= minNumber
val id = getResourceId(R.styleable.DiscreteSeekBar_tickDrawable, 0)
if (id != 0) {
tickDrawable = AppCompatResources.getDrawable(context, id)
}
val id2 = getResourceId(R.styleable.DiscreteSeekBar_centerDrawable, 0)
if (id2 != 0) {
centerDrawable = AppCompatResources.getDrawable(context, id2)
}
}
}
isRtl = resources.configuration.layoutDirection == LAYOUT_DIRECTION_RTL
// Set this to false to prevent the issue of canvas not drawing in init{}
setWillNotDraw(false)
}
@Synchronized
override fun onDraw(canvas: Canvas) {
if (value >= 0) {
drawTickMarks(canvas, drawCenter = true, drawOther = false)
super.onDraw(canvas)
drawTickMarks(canvas, drawCenter = false, drawOther = true)
} else {
super.onDraw(canvas)
drawTickMarks(canvas, drawCenter = true, drawOther = true)
}
}
private fun drawTickMarks(canvas: Canvas, drawCenter: Boolean, drawOther: Boolean) {
val maxNumber = max + minNumber
tickDrawable?.let {
val halfW = if (it.intrinsicWidth >= 0) it.intrinsicWidth / 2 else 1
val halfH = if (it.intrinsicHeight >= 0) it.intrinsicHeight / 2 else 1
it.setBounds(-halfW, -halfH, halfW, halfH)
}
centerDrawable?.let {
val halfW = if (it.intrinsicWidth >= 0) it.intrinsicWidth / 2 else 1
val halfH = if (it.intrinsicHeight >= 0) it.intrinsicHeight / 2 else 1
it.setBounds(-halfW, -halfH, halfW, halfH)
}
val tickSpacing = (width - paddingLeft - paddingRight).toFloat() / (maxNumber - minNumber).toFloat()
canvas.withSave {
if (isRtl) {
scale(-1f, 1f, (width / 2).toFloat(), (height / 2).toFloat())
}
translate(paddingLeft.toFloat(), (height / 2).toFloat())
for (i in minNumber..maxNumber) {
if (drawOther && i > value) {
tickDrawable?.draw(this)
}
if (drawCenter && i == 0) {
centerDrawable?.draw(this)
}
translate(tickSpacing, 0.0f)
}
}
}
}
| apache-2.0 | b1c6d792c019449ad9ec8cb1275c43ce | 37.659091 | 108 | 0.592299 | 4.50596 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/performance-tests/performance-test-utils/test/org/jetbrains/kotlin/idea/performance/tests/utils/project/gradleRoutines.kt | 8 | 3157 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.performance.tests.utils.project
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder
import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.externalSystem.util.ExternalSystemUtil
import com.intellij.openapi.project.Project
import org.gradle.util.GradleVersion
import org.jetbrains.kotlin.idea.performance.tests.utils.dispatchAllInvocationEvents
import org.jetbrains.plugins.gradle.service.project.open.setupGradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleConstants
import org.jetbrains.plugins.gradle.util.GradleLog
import org.jetbrains.plugins.gradle.util.suggestGradleVersion
import java.io.File
import java.nio.file.Paths
fun refreshGradleProject(projectPath: String, project: Project) {
_importProject(File(projectPath).absolutePath, project)
dispatchAllInvocationEvents()
}
const val GRADLE_JDK_NAME = "Gradle JDK"
/**
* inspired by org.jetbrains.plugins.gradle.service.project.open.importProject(projectDirectory, project)
*/
private fun _importProject(projectPath: String, project: Project) {
GradleLog.LOG.info("Import project at $projectPath")
val gradleProjectSettings = GradleProjectSettings()
val gradleVersion = suggestGradleVersion(project) ?: GradleVersion.current()
GradleSettings.getInstance(project).gradleVmOptions =
"-Xmx2048m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${System.getProperty("user.dir")}"
gradleProjectSettings.setupGradleProjectSettings(project, Paths.get(projectPath))
gradleProjectSettings.gradleJvm = GRADLE_JDK_NAME
GradleSettings.getInstance(project).getLinkedProjectSettings(projectPath)?.let { linkedProjectSettings ->
linkedProjectSettings.gradleJvm = GRADLE_JDK_NAME
}
_attachGradleProjectAndRefresh(gradleProjectSettings, project)
}
/**
* inspired by org.jetbrains.plugins.gradle.service.project.open.attachGradleProjectAndRefresh(gradleProjectSettings, project)
* except everything is MODAL_SYNC
*/
private fun _attachGradleProjectAndRefresh(
gradleProjectSettings: GradleProjectSettings,
project: Project
) {
val externalProjectPath = gradleProjectSettings.externalProjectPath
val settings = ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID)
if (settings.getLinkedProjectSettings(externalProjectPath) == null) {
settings.linkProject(gradleProjectSettings)
}
StatefulTestGradleProjectRefreshCallback(externalProjectPath, project).use { callback ->
ExternalSystemUtil.refreshProject(
externalProjectPath,
ImportSpecBuilder(project, GradleConstants.SYSTEM_ID)
.use(ProgressExecutionMode.MODAL_SYNC)
.callback(callback)
.build()
)
}
}
| apache-2.0 | f065626675ce872c6f86040fb699c540 | 42.847222 | 126 | 0.793475 | 4.940532 | false | false | false | false |
atfox7/KotlinSealedUnions | src/main/kotlin/io/andyfox/unions/Union7.kt | 1 | 4304 | /*
* Copyright (c) andyfox 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.andyfox.unions
sealed class Union7<out First, out Second, out Third, out Fourth, out Fifth, out Sixth, out Seventh> {
companion object {
@JvmStatic
fun <First> first(value: First): Union7<First, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing> = Union7First(value)
@JvmStatic
fun <Second> second(value: Second): Union7<Nothing, Second, Nothing, Nothing, Nothing, Nothing, Nothing> = Union7Second(value)
@JvmStatic
fun <Third> third(value: Third): Union7<Nothing, Nothing, Third, Nothing, Nothing, Nothing, Nothing> = Union7Third(value)
@JvmStatic
fun <Fourth> fourth(value: Fourth): Union7<Nothing, Nothing, Nothing, Fourth, Nothing, Nothing, Nothing> = Union7Fourth(value)
@JvmStatic
fun <Fifth> fifth(value: Fifth): Union7<Nothing, Nothing, Nothing, Nothing, Fifth, Nothing, Nothing> = Union7Fifth(value)
@JvmStatic
fun <Sixth> sixth(value: Sixth): Union7<Nothing, Nothing, Nothing, Nothing, Nothing, Sixth, Nothing> = Union7Sixth(value)
@JvmStatic
fun <Seventh> seventh(value: Seventh): Union7<Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Seventh> = Union7Seventh(value)
}
inline fun <R> join(mapFirst: (First) -> R,
mapSecond: (Second) -> R,
mapThird: (Third) -> R,
mapFourth: (Fourth) -> R,
mapFifth: (Fifth) -> R,
mapSixth: (Sixth) -> R,
mapSeventh: (Seventh) -> R): R =
when (this) {
is Union7First -> mapFirst(value)
is Union7Second -> mapSecond(value)
is Union7Third -> mapThird(value)
is Union7Fourth -> mapFourth(value)
is Union7Fifth -> mapFifth(value)
is Union7Sixth -> mapSixth(value)
is Union7Seventh -> mapSeventh(value)
}
inline fun continued(continuationFirst: (First) -> Unit,
continuationSecond: (Second) -> Unit,
continuationThird: (Third) -> Unit,
continuationFourth: (Fourth) -> Unit,
continuationFifth: (Fifth) -> Unit,
continuationSixth: (Sixth) -> Unit,
continuationSeventh: (Seventh) -> Unit) {
when (this) {
is Union7First -> continuationFirst(value)
is Union7Second -> continuationSecond(value)
is Union7Third -> continuationThird(value)
is Union7Fourth -> continuationFourth(value)
is Union7Fifth -> continuationFifth(value)
is Union7Sixth -> continuationSixth(value)
is Union7Seventh -> continuationSeventh(value)
}
}
data class Union7First<out First>(@PublishedApi internal val value: First) : Union7<First, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing>()
data class Union7Second<out Second>(@PublishedApi internal val value: Second) : Union7<Nothing, Second, Nothing, Nothing, Nothing, Nothing, Nothing>()
data class Union7Third<out Third>(@PublishedApi internal val value: Third) : Union7<Nothing, Nothing, Third, Nothing, Nothing, Nothing, Nothing>()
data class Union7Fourth<out Fourth>(@PublishedApi internal val value: Fourth) : Union7<Nothing, Nothing, Nothing, Fourth, Nothing, Nothing, Nothing>()
data class Union7Fifth<out Fifth>(@PublishedApi internal val value: Fifth) : Union7<Nothing, Nothing, Nothing, Nothing, Fifth, Nothing, Nothing>()
data class Union7Sixth< out Sixth>(@PublishedApi internal val value: Sixth) : Union7<Nothing, Nothing, Nothing, Nothing, Nothing, Sixth, Nothing>()
data class Union7Seventh<out Seventh>(@PublishedApi internal val value: Seventh) : Union7<Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Seventh>()
} | apache-2.0 | 2b290455be03dd021977b31906aba442 | 44.315789 | 156 | 0.669145 | 3.985185 | false | false | false | false |
mktiti/Battleship | src/main/java/hu/titi/battleship/activity/HostActivity.kt | 1 | 2285 | package hu.titi.battleship.activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.TextView
import hu.titi.battleship.R
import hu.titi.battleship.model.GameType
import hu.titi.battleship.net.GameHost
import hu.titi.battleship.net.NetHostService
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.textResource
import org.jetbrains.anko.uiThread
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import kotlin.concurrent.thread
private const val TAG = "host-activity"
class HostActivity : AppCompatActivity() {
private lateinit var ipShow: TextView
private lateinit var host: GameHost
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_host)
host = GameHost()
bindService(Intent(this@HostActivity, NetHostService::class.java), host, Context.BIND_AUTO_CREATE)
ipShow = findViewById(R.id.ip_view) as TextView
ipShow.textResource = R.string.waiting_for_ip
doAsync {
val ips = getIPAddress()
uiThread {
if (ips.isNotEmpty()) {
ipShow.text = getString(R.string.ip_is, ips[0].hostAddress)
}
}
}
}
override fun onStart() {
super.onStart()
Log.i(TAG, "start")
thread(name = "Host Close-Await") {
host.closeConnection()
if (host.startAndWait()) {
runOnUiThread {
startActivity<LocalGameActivity>("type" to GameType.REMOTE)
}
}
}
}
private fun getIPAddress(): List<InetAddress> =
NetworkInterface.getNetworkInterfaces().asSequence().flatMap {
it.inetAddresses.asSequence().filter { address ->
!address.isLoopbackAddress && address is Inet4Address
}
}.toList()
override fun onDestroy() {
doAsync {
host.closeConnection()
}
unbindService(host)
super.onDestroy()
}
}
| gpl-3.0 | 2ae61f34830e5266e53c9ee91d21396a | 28.294872 | 106 | 0.644639 | 4.402697 | false | false | false | false |
BreakOutEvent/breakout-backend | src/main/java/backend/view/sponsoring/DetailedSponsoringView.kt | 1 | 2387 | package backend.view.sponsoring
import backend.model.sponsoring.Sponsoring
import backend.view.MediaView
import backend.view.UnregisteredSponsorView
import javax.validation.Valid
import javax.validation.constraints.NotNull
class DetailedSponsoringView() {
var id: Long? = null
var eventId: Long? = null
var teamId: Long? = null
var team: String? = null
@NotNull
var amountPerKm: Double? = null
@NotNull
var limit: Double? = null
var sponsorId: Long? = null
var userId: Long? = null
var firstname: String? = null
var lastname: String? = null
var company: String? = null
var status: String? = null
var contract: MediaView? = null
@Valid
var unregisteredSponsor: UnregisteredSponsorView? = null
var sponsorIsHidden: Boolean = false
constructor(sponsoring: Sponsoring) : this() {
this.id = sponsoring.id
this.eventId = sponsoring.team?.event?.id
this.teamId = sponsoring.team?.id
this.team = sponsoring.team?.name
this.amountPerKm = sponsoring.amountPerKm.numberStripped.toDouble()
this.limit = sponsoring.limit.numberStripped.toDouble()
this.status = sponsoring.status.toString().toUpperCase()
this.contract = sponsoring.contract?.let(::MediaView)
// Add information about registered sponsor
// if he exists and isHidden is false
sponsoring.sponsor?.registeredSponsor?.isHidden?.let {
if (it) {
this.sponsorIsHidden = true
this.contract = null
} else {
this.userId = sponsoring.sponsor?.registeredSponsor?.account?.id
this.sponsorId = sponsoring.sponsor?.registeredSponsor?.id
this.firstname = sponsoring.sponsor?.firstname
this.lastname = sponsoring.sponsor?.lastname
this.company = sponsoring.sponsor?.company
}
}
// Add information about unregistered sponsor
// if he exists and isHidden is false
sponsoring.sponsor?.unregisteredSponsor?.isHidden?.let {
if (it) {
this.sponsorIsHidden = true
this.contract = null
} else {
this.unregisteredSponsor = UnregisteredSponsorView(sponsoring.sponsor?.unregisteredSponsor!!)
}
}
}
}
| agpl-3.0 | c7643bc3216c434875d08b8a7e77a3c9 | 27.759036 | 109 | 0.633012 | 4.891393 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ | src/main/kotlin/com/demonwav/mcdev/platform/mixin/inspection/MixinClassReferenceInspection.kt | 1 | 1781 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection
import com.demonwav.mcdev.platform.mixin.util.isAccessorMixin
import com.demonwav.mcdev.platform.mixin.util.isMixin
import com.demonwav.mcdev.util.findContainingClass
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiTypeElement
class MixinClassReferenceInspection : MixinInspection() {
override fun getStaticDescription() =
"A Mixin class doesn't exist at runtime, and thus cannot be referenced directly."
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitTypeElement(type: PsiTypeElement) {
val classType = type.type as? PsiClassType ?: return
val referencedClass = classType.resolve() ?: return
if (!referencedClass.isMixin) {
return
}
// Check if the the reference is a super Mixin
val psiClass = type.findContainingClass() ?: return
if (psiClass.isEquivalentTo(referencedClass) || psiClass.isInheritor(referencedClass, true)) {
// Mixin class is part of the hierarchy
return
}
// Check if the reference is an accessor Mixin
if (referencedClass.isAccessorMixin) {
return
}
holder.registerProblem(type, "Mixin class cannot be referenced directly")
}
}
}
| mit | b4e7a28c5b14054bdc04b0402a2fba5d | 31.981481 | 106 | 0.683885 | 5.19242 | false | false | false | false |
triarius/GenPass | app/src/main/kotlin/com/example/android/genpass/text/GraphemeLengthFilter.kt | 1 | 1870 | package com.example.android.genpass.text
import android.text.InputFilter
import android.text.Spanned
import com.ibm.icu.text.BreakIterator
import java.util.*
/**
* Created by narthana on 25/01/17.
*/
class GraphemeLengthFilter @JvmOverloads
constructor(val max: Int, private val locale: Locale = Locale.getDefault()): InputFilter {
/**
* We are replacing the range [dstart]...[dend] of [dest] with the range [start]...[end]
* of [source]. The return value is the replacement or null to use source unadulterated
*/
override fun filter(source: CharSequence, start: Int, end: Int,
dest: Spanned, dstart: Int, dend: Int): CharSequence? {
// keep = number of graphemes we must keep
val keep = max - (graphemeCount(dest, 0, dest.length) - graphemeCount(dest, dstart, dend))
return if (keep <= 0) ""
else if (keep >= graphemeCount(source, start, end)) null // keep original
else {
// 0 < keep < graphemeCount(source, start, end).
// so move as far into source as possible
BreakIterator.getCharacterInstance(locale).run {
setText(source.subSequence(start, end).toString())
// iterate though "keep" graphemes, noting the index at which we end up
val keepOffset = (1 .. keep).fold(0) { _, _ -> next() }
source.subSequence(start, start + keepOffset)
}
}
}
/**
* Counts the number of graphemes in [seq] from [beginIndex] to [endIndex]
*/
private fun graphemeCount(seq: CharSequence, beginIndex: Int, endIndex: Int): Int
= BreakIterator.getCharacterInstance(locale).run {
setText(seq.subSequence(beginIndex, endIndex).toString())
var count = 0
while (next() != BreakIterator.DONE) ++count
count
}
} | gpl-3.0 | d092a658ee498d1f8bc25075947f0fd5 | 38.808511 | 98 | 0.620856 | 4.030172 | false | false | false | false |
google/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/LibraryNameGenerator.kt | 5 | 2103 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryId
import com.intellij.workspaceModel.storage.bridgeEntities.api.LibraryTableId
import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer
object LibraryNameGenerator {
private const val UNIQUE_INDEX_LIBRARY_NAME_SUFFIX = "-d1a6f608-UNIQUE-INDEX-f29c-4df6-"
const val UNNAMED_LIBRARY_NAME_PREFIX = "#"
fun getLegacyLibraryName(libraryId: LibraryId): String? {
if (libraryId.name.startsWith(UNNAMED_LIBRARY_NAME_PREFIX)) return null
if (libraryId.name.contains(UNIQUE_INDEX_LIBRARY_NAME_SUFFIX)) return libraryId.name.substringBefore(UNIQUE_INDEX_LIBRARY_NAME_SUFFIX)
return libraryId.name
}
fun generateLibraryEntityName(legacyLibraryName: String?, exists: (String) -> Boolean): String {
if (legacyLibraryName == null) {
var index = 1
while (true) {
val candidate = "$UNNAMED_LIBRARY_NAME_PREFIX$index"
if (!exists(candidate)) {
return candidate
}
index++
}
@Suppress("UNREACHABLE_CODE")
error("Unable to suggest unique name for unnamed module library")
}
return generateUniqueLibraryName(legacyLibraryName, exists)
}
fun generateUniqueLibraryName(name: String, exists: (String) -> Boolean): String {
if (!exists(name)) return name
var index = 1
while (true) {
val candidate = "$name$UNIQUE_INDEX_LIBRARY_NAME_SUFFIX$index"
if (!exists(candidate)) {
return candidate
}
index++
}
}
fun getLibraryTableId(level: String): LibraryTableId = when (level) {
JpsLibraryTableSerializer.MODULE_LEVEL -> error("this method isn't supposed to be used for module-level libraries")
JpsLibraryTableSerializer.PROJECT_LEVEL -> LibraryTableId.ProjectLibraryTableId
else -> LibraryTableId.GlobalLibraryTableId(level)
}
}
| apache-2.0 | 13d8b34757538d26c4679543ea9df62f | 36.553571 | 158 | 0.726581 | 4.399582 | false | false | false | false |
dzharkov/intellij-markdown | src/org/intellij/markdown/flavours/gfm/GFMFlavourDescriptor.kt | 1 | 2628 | package org.intellij.markdown.flavours.gfm
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.ast.ASTNode
import org.intellij.markdown.ast.getTextInNode
import org.intellij.markdown.flavours.commonmark.CommonMarkFlavourDescriptor
import org.intellij.markdown.flavours.gfm.lexer._GFMLexer
import org.intellij.markdown.html.GeneratingProvider
import org.intellij.markdown.html.HtmlGenerator
import org.intellij.markdown.html.SimpleInlineTagProvider
import org.intellij.markdown.lexer.MarkdownLexer
import org.intellij.markdown.parser.LinkMap
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
import org.intellij.markdown.parser.sequentialparsers.SequentialParserManager
import org.intellij.markdown.parser.sequentialparsers.impl.*
import java.io.Reader
public class GFMFlavourDescriptor : CommonMarkFlavourDescriptor() {
override val markerProcessorFactory = GFMMarkerProcessor.Factory
override fun createInlinesLexer(): MarkdownLexer {
return MarkdownLexer(_GFMLexer(null as Reader?))
}
override val sequentialParserManager = object : SequentialParserManager() {
override fun getParserSequence(): List<SequentialParser> {
return listOf(AutolinkParser(listOf(MarkdownTokenTypes.AUTOLINK, GFMTokenTypes.GFM_AUTOLINK)),
BacktickParser(),
ImageParser(),
InlineLinkParser(),
ReferenceLinkParser(),
StrikeThroughParser(),
EmphStrongParser())
}
}
override fun createHtmlGeneratingProviders(linkMap: LinkMap): Map<IElementType, GeneratingProvider> {
return super.createHtmlGeneratingProviders(linkMap) + hashMapOf(
GFMElementTypes.STRIKETHROUGH to object: SimpleInlineTagProvider("span", 2, -2) {
override fun openTag(text: String, node: ASTNode): String {
return "<span class=\"user-del\">"
}
},
GFMTokenTypes.GFM_AUTOLINK to object : GeneratingProvider {
override fun processNode(visitor: HtmlGenerator.HtmlGeneratingVisitor, text: String, node: ASTNode) {
val linkDestination = node.getTextInNode(text)
visitor.consumeHtml("<a href=\"$linkDestination\">$linkDestination</a>")
}
},
MarkdownElementTypes.LIST_ITEM to CheckedListItemGeneratingProvider()
)
}
} | apache-2.0 | 89ce4da460465e8b7b212e93e924f1fd | 45.122807 | 121 | 0.697869 | 5.224652 | false | false | false | false |
indianpoptart/RadioControl | RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/receivers/ConnectivityReceiver.kt | 1 | 1733 | package com.nikhilparanjape.radiocontrol.receivers
import android.app.job.JobInfo
import android.app.job.JobScheduler
import android.content.ComponentName
import android.content.Context
import android.content.Context.JOB_SCHEDULER_SERVICE
import android.content.Intent
import android.util.Log
import androidx.legacy.content.WakefulBroadcastReceiver
import com.nikhilparanjape.radiocontrol.services.BackgroundJobService
@Suppress("DEPRECATION")
/**
* Created by Nikhil Paranjape on 11/8/2015.
*
* This uses some deprecated functions and may stop working :(
*
* This file is only here for backwards compatibility
*
* @author Nikhil Paranjape
*/
//This file is kept as a fallback
class ConnectivityReceiver : WakefulBroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
Log.d(TAG, "Get action-ConRec: " + intent.action!!)
val componentName = ComponentName(context, BackgroundJobService::class.java)
val jobInfo = JobInfo.Builder(12, componentName)
.setRequiresCharging(false)
.setOverrideDeadline(4000)
.setPersisted(true)
.build()
val jobScheduler = context.getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler?
val resultCode = jobScheduler!!.schedule(jobInfo)
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled!")
} else {
Log.d(TAG, "Job could not be scheduled")
}
}
interface ConnectivityReceiverListener
companion object {
private const val TAG = "RadioControl-CR"
}
}
| gpl-3.0 | 2635b39d04bad5419745529b342c6060 | 30.698113 | 91 | 0.684362 | 4.536649 | false | false | false | false |
thomasgalvin/Featherfall | src/main/kotlin/galvin/ff/demo/Setup.kt | 1 | 3611 | package galvin.ff.demo
import galvin.ff.*
import java.io.File
class Setup{
companion object {
private val timeProvider = DefaultTimeProvider()
fun createDefaultUsers(userDB: UserDB, accountRequestDB: AccountRequestDB){
val adminRole = Role( name = "Admin", permissions = listOf("Admin", "User") )
userDB.storeRole(adminRole)
val userRole = Role( name = "User", permissions = listOf("User") )
userDB.storeRole(userRole)
val adminUser = User(
login = "admin",
name = "Administrator",
displayName = "Administrator",
sortName = "Administrator",
created = timeProvider.now(),
active = false,
contact = listOf(
ContactInfo(
type = "Email",
description = "Email",
contact = "[email protected]",
primary = true
)
),
roles = listOf( adminRole.name, userRole.name )
)
val adminAccountRequest = AccountRequest(
user = adminUser,
password = "password",
confirmPassword = "password"
)
accountRequestDB.storeAccountRequest(adminAccountRequest)
accountRequestDB.approve( adminAccountRequest.uuid, "", timeProvider.now() )
val testUser = User(
login = "user",
name = "Joe User",
displayName = "Joe User",
sortName = "User, Joe",
created = timeProvider.now(),
active = false,
contact = listOf(
ContactInfo(
type = "Email",
description = "Email",
contact = "[email protected]",
primary = true
)
),
roles = listOf( userRole.name )
)
val userAccountRequest = AccountRequest(
user = testUser,
password = "password",
confirmPassword = "password"
)
accountRequestDB.storeAccountRequest(userAccountRequest)
accountRequestDB.approve( userAccountRequest.uuid, "", timeProvider.now() )
}
fun userDB(): UserDB {
val databaseFile = File( "target/ff_demo_users_" + uuid() )
return UserDB.SQLite(maxConnections = 1, databaseFile = databaseFile )
}
fun accountRequestDB( userDB: UserDB): AccountRequestDB {
val accountRequestDatabaseFile = File( "target/ff_demo_account_requests_" + uuid() )
val accountRequestUserDatabaseFile = File( "target/ff_demo_account_request_users_" + uuid() )
return AccountRequestDB.SQLite(
userDB = userDB,
maxConnections = 1,
databaseFile = accountRequestDatabaseFile,
userDatabaseFile = accountRequestUserDatabaseFile )
}
fun auditDB(): AuditDB {
val databaseFile = File( "target/ff_demo_audit_" + uuid() )
return AuditDB.SQLite(maxConnections = 1, databaseFile = databaseFile )
}
}
} | apache-2.0 | 41e207b757ff85d39c31a36820455ee2 | 38.692308 | 105 | 0.47383 | 5.740859 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/completion/impl-shared/src/org/jetbrains/kotlin/idea/completion/implCommon/AbstractCompletionDummyIdentifierProviderService.kt | 1 | 12103 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.completion.implCommon
import com.intellij.codeInsight.completion.CompletionInitializationContext
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.codeInsight.completion.CompletionUtil
import com.intellij.codeInsight.completion.CompletionUtilCore
import com.intellij.psi.*
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.idea.completion.api.CompletionDummyIdentifierProviderService
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import kotlin.math.max
@ApiStatus.Internal
abstract class AbstractCompletionDummyIdentifierProviderService : CompletionDummyIdentifierProviderService {
override fun correctPositionForStringTemplateEntry(context: CompletionInitializationContext): Boolean {
val offset = context.startOffset
val psiFile = context.file
val tokenBefore = psiFile.findElementAt(max(0, offset - 1))
if (offset > 0 && tokenBefore!!.node.elementType == KtTokens.REGULAR_STRING_PART && tokenBefore.text.startsWith(".")) {
val prev = tokenBefore.parent.prevSibling
if (prev != null && prev is KtSimpleNameStringTemplateEntry) {
val expression = prev.expression
if (expression != null) {
val prefix = tokenBefore.text.substring(0, offset - tokenBefore.startOffset)
context.dummyIdentifier = "{" + expression.text + prefix + CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "}"
context.offsetMap.addOffset(CompletionInitializationContext.START_OFFSET, expression.startOffset)
return true
}
}
}
return false
}
override fun provideDummyIdentifier(context: CompletionInitializationContext): String {
val psiFile = context.file
if (psiFile !is KtFile) {
error("CompletionDummyIdentifierProviderService.providerDummyIdentifier should not be called for non KtFile")
}
val offset = context.startOffset
val tokenBefore = psiFile.findElementAt(max(0, offset - 1))
return when {
context.completionType == CompletionType.SMART -> DEFAULT_DUMMY_IDENTIFIER
// TODO package completion
isInClassHeader(tokenBefore) -> CompletionUtilCore.DUMMY_IDENTIFIER // do not add '$' to not interrupt class declaration parsing
isInUnclosedSuperQualifier(tokenBefore) -> CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + ">"
isInSimpleStringTemplate(tokenBefore) -> CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED
else -> specialLambdaSignatureDummyIdentifier(tokenBefore)
?: specialExtensionReceiverDummyIdentifier(tokenBefore)
?: specialInTypeArgsDummyIdentifier(tokenBefore)
?: specialInArgumentListDummyIdentifier(tokenBefore)
?: specialInBinaryExpressionDummyIdentifier(tokenBefore)
?: isInValueOrTypeParametersList(tokenBefore)
?: handleDefaultCase(context)
?: DEFAULT_DUMMY_IDENTIFIER
}
}
protected open fun handleDefaultCase(context: CompletionInitializationContext): String? = null
private fun isInValueOrTypeParametersList(tokenBefore: PsiElement?): String? {
if (tokenBefore == null) return null
if (tokenBefore.parents.any { it is KtTypeParameterList || it is KtParameterList }) {
return CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED
}
return null
}
private fun specialLambdaSignatureDummyIdentifier(tokenBefore: PsiElement?): String? {
var leaf = tokenBefore
while (leaf is PsiWhiteSpace || leaf is PsiComment) {
leaf = leaf.prevLeaf(true)
}
val lambda = leaf?.parents?.firstOrNull { it is KtFunctionLiteral } ?: return null
val lambdaChild = leaf.parents.takeWhile { it != lambda }.lastOrNull()
return if (lambdaChild is KtParameterList)
CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED
else
null
}
private fun isInClassHeader(tokenBefore: PsiElement?): Boolean {
val classOrObject = tokenBefore?.parents?.firstIsInstanceOrNull<KtClassOrObject>() ?: return false
val name = classOrObject.nameIdentifier ?: return false
val headerEnd = classOrObject.body?.startOffset ?: classOrObject.endOffset
val offset = tokenBefore.startOffset
return name.endOffset <= offset && offset <= headerEnd
}
private fun specialInBinaryExpressionDummyIdentifier(tokenBefore: PsiElement?): String? {
if (tokenBefore.elementType == KtTokens.IDENTIFIER && tokenBefore?.context?.context is KtBinaryExpression)
return CompletionUtilCore.DUMMY_IDENTIFIER
return null
}
private fun isInUnclosedSuperQualifier(tokenBefore: PsiElement?): Boolean {
if (tokenBefore == null) return false
val tokensToSkip = TokenSet.orSet(TokenSet.create(KtTokens.IDENTIFIER, KtTokens.DOT), KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET)
val tokens = generateSequence(tokenBefore) { it.prevLeaf() }
val ltToken = tokens.firstOrNull { it.node.elementType !in tokensToSkip } ?: return false
if (ltToken.node.elementType != KtTokens.LT) return false
val superToken = ltToken.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment }
return superToken?.node?.elementType == KtTokens.SUPER_KEYWORD
}
private fun isInSimpleStringTemplate(tokenBefore: PsiElement?): Boolean {
return tokenBefore?.parents?.firstIsInstanceOrNull<KtStringTemplateExpression>()?.isPlain() ?: false
}
private fun specialExtensionReceiverDummyIdentifier(tokenBefore: PsiElement?): String? {
var token = tokenBefore ?: return null
var ltCount = 0
var gtCount = 0
val builder = StringBuilder()
while (true) {
val tokenType = token.node!!.elementType
if (tokenType in declarationKeywords) {
val balance = ltCount - gtCount
if (balance < 0) return null
builder.append(token.text!!.reversed())
builder.reverse()
var tail = "X" + ">".repeat(balance) + ".f"
if (tokenType == KtTokens.FUN_KEYWORD) {
tail += "()"
}
builder.append(tail)
val text = builder.toString()
val file = KtPsiFactory(tokenBefore.project).createFile(text)
val declaration = file.declarations.singleOrNull() ?: return null
if (declaration.textLength != text.length) return null
val containsErrorElement = !PsiTreeUtil.processElements(file) { it !is PsiErrorElement }
return if (containsErrorElement) null else "$tail$"
}
if (tokenType !in declarationTokens) return null
if (tokenType == KtTokens.LT) ltCount++
if (tokenType == KtTokens.GT) gtCount++
builder.append(token.text!!.reversed())
token = PsiTreeUtil.prevLeaf(token) ?: return null
}
}
private fun specialInTypeArgsDummyIdentifier(tokenBefore: PsiElement?): String? {
if (tokenBefore == null) return null
if (tokenBefore.getParentOfType<KtTypeArgumentList>(true) != null) { // already parsed inside type argument list
return CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED // do not insert '$' to not break type argument list parsing
}
val pair = unclosedTypeArgListNameAndBalance(tokenBefore) ?: return null
val (nameToken, balance) = pair
assert(balance > 0)
val nameRef = nameToken.parent as? KtNameReferenceExpression ?: return null
return if (allTargetsAreFunctionsOrClasses(nameRef)) {
CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + ">".repeat(balance) + "$"
} else {
null
}
}
protected abstract fun allTargetsAreFunctionsOrClasses(nameReferenceExpression: KtNameReferenceExpression): Boolean
private fun unclosedTypeArgListNameAndBalance(tokenBefore: PsiElement): Pair<PsiElement, Int>? {
val nameToken = findCallNameTokenIfInTypeArgs(tokenBefore) ?: return null
val pair = unclosedTypeArgListNameAndBalance(nameToken)
return if (pair == null) {
Pair(nameToken, 1)
} else {
Pair(pair.first, pair.second + 1)
}
}
private val callTypeArgsTokens = TokenSet.orSet(
TokenSet.create(
KtTokens.IDENTIFIER, KtTokens.LT, KtTokens.GT,
KtTokens.COMMA, KtTokens.DOT, KtTokens.QUEST, KtTokens.COLON,
KtTokens.LPAR, KtTokens.RPAR, KtTokens.ARROW
),
KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET
)
// if the leaf could be located inside type argument list of a call (if parsed properly)
// then it returns the call name reference this type argument list would belong to
private fun findCallNameTokenIfInTypeArgs(leaf: PsiElement): PsiElement? {
var current = leaf
while (true) {
val tokenType = current.node!!.elementType
if (tokenType !in callTypeArgsTokens) return null
if (tokenType == KtTokens.LT) {
val nameToken = current.prevLeaf(skipEmptyElements = true) ?: return null
if (nameToken.node!!.elementType != KtTokens.IDENTIFIER) return null
return nameToken
}
if (tokenType == KtTokens.GT) { // pass nested type argument list
val prev = current.prevLeaf(skipEmptyElements = true) ?: return null
val typeRef = findCallNameTokenIfInTypeArgs(prev) ?: return null
current = typeRef
continue
}
current = current.prevLeaf(skipEmptyElements = true) ?: return null
}
}
private fun specialInArgumentListDummyIdentifier(tokenBefore: PsiElement?): String? {
// If we insert `$` in the argument list of a delegation specifier, this will break parsing
// and the following block will not be attached as a body to the constructor. Therefore
// we need to use a regular identifier.
val argumentList = tokenBefore?.getNonStrictParentOfType<KtValueArgumentList>() ?: return null
if (argumentList.parent is KtConstructorDelegationCall) return CompletionUtil.DUMMY_IDENTIFIER_TRIMMED
// If there is = in the argument list after caret, then breaking parsing with just $ prevents K2 from resolving function call,
// i.e. `f ($ = )` is resolved to variable assignment and left part `f ($` is resolved to erroneous name reference,
// so we need to use `$,` to avoid resolving to variable assignment
return CompletionUtil.DUMMY_IDENTIFIER_TRIMMED + "$,"
}
private companion object {
private const val DEFAULT_DUMMY_IDENTIFIER: String =
CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + "$" // add '$' to ignore context after the caret
private val declarationKeywords = TokenSet.create(KtTokens.FUN_KEYWORD, KtTokens.VAL_KEYWORD, KtTokens.VAR_KEYWORD)
private val declarationTokens = TokenSet.orSet(
TokenSet.create(
KtTokens.IDENTIFIER, KtTokens.LT, KtTokens.GT,
KtTokens.COMMA, KtTokens.DOT, KtTokens.QUEST, KtTokens.COLON,
KtTokens.IN_KEYWORD, KtTokens.OUT_KEYWORD,
KtTokens.LPAR, KtTokens.RPAR, KtTokens.ARROW,
TokenType.ERROR_ELEMENT
),
KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET
)
}
}
| apache-2.0 | 85af503a30393df8987ae520c820445f | 46.093385 | 140 | 0.668347 | 5.106751 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/course_purchase/ui/dialog/CoursePurchaseBottomSheetDialogFragment.kt | 1 | 15494 | package org.stepik.android.view.course_purchase.ui.dialog
import android.os.Bundle
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.URLSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.text.buildSpannedString
import androidx.core.text.inSpans
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import by.kirich1409.viewbindingdelegate.viewBinding
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingFlowParams
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import org.stepic.droid.R
import org.stepic.droid.base.App
import org.stepic.droid.databinding.BottomSheetDialogCoursePurchaseBinding
import org.stepik.android.presentation.course_purchase.CoursePurchaseFeature
import org.stepik.android.presentation.course_purchase.CoursePurchaseViewModel
import org.stepik.android.presentation.course_purchase.model.CoursePurchaseData
import org.stepik.android.view.course.mapper.DisplayPriceMapper
import org.stepik.android.view.course.resolver.CoursePromoCodeResolver
import org.stepik.android.view.course_purchase.delegate.PromoCodeViewDelegate
import org.stepik.android.view.course_purchase.delegate.WishlistViewDelegate
import ru.nobird.app.presentation.redux.container.ReduxView
import ru.nobird.android.view.base.ui.extension.argument
import ru.nobird.android.view.redux.ui.extension.reduxViewModel
import javax.inject.Inject
import androidx.annotation.StringRes
import androidx.core.text.HtmlCompat
import androidx.core.text.getSpans
import androidx.core.text.toSpannable
import com.android.billingclient.api.Purchase
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.ktx.get
import org.stepic.droid.configuration.RemoteConfig
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment
import org.stepic.droid.util.DeviceInfoUtil
import org.stepic.droid.util.ProgressHelper
import org.stepic.droid.util.defaultLocale
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course_purchase.analytic.RestoreCoursePurchaseSource
import org.stepik.android.presentation.course.model.EnrollmentError
import org.stepik.android.presentation.wishlist.WishlistOperationFeature
import org.stepik.android.view.course_purchase.delegate.BuyActionViewDelegate
import org.stepik.android.view.in_app_web_view.ui.dialog.InAppWebViewDialogFragment
import ru.nobird.android.view.base.ui.extension.showIfNotExists
import ru.nobird.android.view.base.ui.extension.snackbar
class CoursePurchaseBottomSheetDialogFragment :
BottomSheetDialogFragment(),
ReduxView<CoursePurchaseFeature.State, CoursePurchaseFeature.Action.ViewAction> {
companion object {
const val TAG = "CoursePurchaseBottomSheetDialogFragment"
fun newInstance(coursePurchaseData: CoursePurchaseData, coursePurchaseSource: String, isNeedRestoreMessage: Boolean): DialogFragment =
CoursePurchaseBottomSheetDialogFragment().apply {
this.coursePurchaseData = coursePurchaseData
this.coursePurchaseSource = coursePurchaseSource
this.isNeedRestoreMessage = isNeedRestoreMessage
}
private const val RUSSIAN_LANGUAGE_CODE = "ru"
private const val BELARUSIAN_LANGUAGE_CODE = "be"
}
@Inject
internal lateinit var firebaseRemoteConfig: FirebaseRemoteConfig
@Inject
internal lateinit var screenManager: ScreenManager
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var displayPriceMapper: DisplayPriceMapper
@Inject
internal lateinit var coursePromoCodeResolver: CoursePromoCodeResolver
@Inject
internal lateinit var billingClient: BillingClient
private var coursePurchaseData: CoursePurchaseData by argument()
private var coursePurchaseSource: String by argument()
private var isNeedRestoreMessage: Boolean by argument()
private val coursePurchaseViewModel: CoursePurchaseViewModel by reduxViewModel(this) { viewModelFactory }
private val coursePurchaseBinding: BottomSheetDialogCoursePurchaseBinding by viewBinding(BottomSheetDialogCoursePurchaseBinding::bind)
private val progressDialogFragment: DialogFragment =
LoadingProgressDialogFragment.newInstance()
private lateinit var buyActionViewDelegate: BuyActionViewDelegate
private lateinit var promoCodeViewDelegate: PromoCodeViewDelegate
private lateinit var wishlistViewDelegate: WishlistViewDelegate
private fun injectComponent() {
App
.component()
.coursePurchaseComponentBuilder()
.build()
.inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectComponent()
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.TopCornersRoundedBottomSheetDialog)
coursePurchaseViewModel.onNewMessage(CoursePurchaseFeature.Message.InitMessage(coursePurchaseData, coursePurchaseSource))
when {
coursePurchaseData.purchaseState == Purchase.PurchaseState.PENDING -> {
coursePurchaseViewModel.onNewMessage(
CoursePurchaseFeature.Message.LaunchPendingPurchaseFlow
)
}
isNeedRestoreMessage || coursePurchaseData.purchaseState == Purchase.PurchaseState.PURCHASED -> {
coursePurchaseViewModel.onNewMessage(
CoursePurchaseFeature.Message.LaunchRestorePurchaseFlow(RestoreCoursePurchaseSource.COURSE_SCREEN)
)
}
}
}
override fun onStart() {
super.onStart()
(dialog as? BottomSheetDialog)?.behavior?.state = BottomSheetBehavior.STATE_EXPANDED
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.bottom_sheet_dialog_course_purchase, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
buyActionViewDelegate = BuyActionViewDelegate(coursePurchaseBinding, coursePurchaseData, displayPriceMapper,
launchPurchaseFlowAction = { coursePurchaseViewModel.onNewMessage(CoursePurchaseFeature.Message.LaunchPurchaseFlow) },
launchStartStudying = { coursePurchaseViewModel.onNewMessage(CoursePurchaseFeature.Message.StartLearningMessage) },
launchRestoreAction = {
coursePurchaseViewModel.onNewMessage(
CoursePurchaseFeature.Message.LaunchRestorePurchaseFlow(RestoreCoursePurchaseSource.BUY_COURSE_DIALOG)
)
},
closeDialog = { dismiss() }
)
promoCodeViewDelegate = PromoCodeViewDelegate(coursePurchaseBinding, coursePurchaseViewModel)
wishlistViewDelegate = WishlistViewDelegate(coursePurchaseBinding.coursePurchaseWishlistAction)
coursePurchaseBinding.coursePurchaseWishlistAction.setOnClickListener {
coursePurchaseViewModel.onNewMessage(
CoursePurchaseFeature.Message.WishlistMessage(
WishlistOperationFeature.Message.WishlistAddMessage(
coursePurchaseData.course,
CourseViewSource.CoursePurchase
)
)
)
}
coursePurchaseBinding.coursePurchaseCourseTitle.text = coursePurchaseData.course.title.orEmpty()
Glide
.with(requireContext())
.asBitmap()
.load(coursePurchaseData.course.cover)
.placeholder(R.drawable.general_placeholder)
.fitCenter()
.into(coursePurchaseBinding.coursePurchaseCourseIcon)
val supportSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
coursePurchaseViewModel.onNewMessage(
CoursePurchaseFeature.Message.SetupFeedback(
getString(R.string.feedback_subject),
DeviceInfoUtil.getInfosAboutDevice(requireContext(), "\n")
)
)
}
}
coursePurchaseBinding.coursePurchasePaymentFailureFeedback.text = buildSpannedString {
append(getString(R.string.course_purchase_payment_failure_body_part_1))
inSpans(supportSpan) {
append(getString(R.string.course_purchase_payment_failure_body_part_2))
}
append(getString(R.string.course_purchase_payment_failure_body_part_3))
}
coursePurchaseBinding.coursePurchasePaymentFailureFeedback.movementMethod = LinkMovementMethod.getInstance()
coursePurchaseBinding.coursePurchaseCommissionNotice.text = buildSpannedString {
append(resolveCommissionSpannedText())
}
coursePurchaseBinding.coursePurchaseCommissionNotice.movementMethod = LinkMovementMethod.getInstance()
}
override fun onAction(action: CoursePurchaseFeature.Action.ViewAction) {
when (action) {
is CoursePurchaseFeature.Action.ViewAction.LaunchPurchaseFlowBilling -> {
val billingFlowParams = BillingFlowParams
.newBuilder()
.setObfuscatedAccountId(action.obfuscatedParams.obfuscatedAccountId)
.setObfuscatedProfileId(action.obfuscatedParams.obfuscatedProfileId)
.setSkuDetails(action.skuDetails)
.build()
billingClient.launchBillingFlow(requireActivity(), billingFlowParams)
}
is CoursePurchaseFeature.Action.ViewAction.Error -> {
@StringRes
val errorMessage =
when (action.error) {
EnrollmentError.NO_CONNECTION ->
R.string.course_error_enroll
EnrollmentError.FORBIDDEN ->
R.string.join_course_web_exception
EnrollmentError.UNAUTHORIZED ->
R.string.unauthorization_detail
EnrollmentError.BILLING_ERROR ->
R.string.course_purchase_billing_error
EnrollmentError.BILLING_CANCELLED ->
R.string.course_purchase_billing_cancelled
EnrollmentError.BILLING_NOT_AVAILABLE ->
R.string.course_purchase_billing_not_available
EnrollmentError.COURSE_ALREADY_OWNED ->
R.string.course_purchase_already_owned
EnrollmentError.BILLING_NO_PURCHASES_TO_RESTORE ->
R.string.course_purchase_billing_no_purchases_to_restore
}
coursePurchaseBinding.coursePurchaseCoordinator.snackbar(messageRes = errorMessage)
}
is CoursePurchaseFeature.Action.ViewAction.ShowLoading ->
ProgressHelper.activate(progressDialogFragment, childFragmentManager, LoadingProgressDialogFragment.TAG)
is CoursePurchaseFeature.Action.ViewAction.ShowConsumeSuccess -> {
ProgressHelper.dismiss(childFragmentManager, LoadingProgressDialogFragment.TAG)
}
is CoursePurchaseFeature.Action.ViewAction.ShowConsumeFailure -> {
ProgressHelper.dismiss(childFragmentManager, LoadingProgressDialogFragment.TAG)
}
is CoursePurchaseFeature.Action.ViewAction.StartStudyAction -> {
(activity as? Callback ?: parentFragment as? Callback)?.continueLearning()
dismiss()
}
is CoursePurchaseFeature.Action.ViewAction.ShowContactSupport -> {
screenManager.openTextFeedBack(requireContext(), action.supportEmailData)
}
}
}
override fun render(state: CoursePurchaseFeature.State) {
if (state is CoursePurchaseFeature.State.Content) {
val isCancelable = state.paymentState is CoursePurchaseFeature.PaymentState.Idle ||
state.paymentState is CoursePurchaseFeature.PaymentState.PaymentFailure ||
state.paymentState is CoursePurchaseFeature.PaymentState.PaymentPending ||
state.paymentState is CoursePurchaseFeature.PaymentState.PaymentSuccess
this.isCancelable = isCancelable
buyActionViewDelegate.render(state)
if (state.paymentState is CoursePurchaseFeature.PaymentState.PaymentFailure ||
state.paymentState is CoursePurchaseFeature.PaymentState.PaymentPending ||
state.paymentState is CoursePurchaseFeature.PaymentState.PaymentSuccess
) {
promoCodeViewDelegate.setViewVisibility(isVisible = false)
wishlistViewDelegate.setViewVisibility(isVisible = false)
} else {
promoCodeViewDelegate.render(state.promoCodeState)
wishlistViewDelegate.setViewVisibility(isVisible = true)
wishlistViewDelegate.render(state.wishlistState, isCancelable)
}
coursePurchaseBinding.coursePurchaseBuyActionGreen.isEnabled = isCancelable
coursePurchaseBinding.coursePurchaseBuyActionViolet.isEnabled = isCancelable
}
}
private fun resolveCommissionSpannedText(): Spanned {
val userAgreementConfigKey =
when (resources.configuration.defaultLocale.language) {
RUSSIAN_LANGUAGE_CODE ->
RemoteConfig.PURCHASE_FLOW_DISCLAIMER_RU
BELARUSIAN_LANGUAGE_CODE ->
RemoteConfig.PURCHASE_FLOW_DISCLAIMER_BE
else ->
RemoteConfig.PURCHASE_FLOW_DISCLAIMER_EN
}
val userAgreementSpannedText = HtmlCompat.fromHtml(firebaseRemoteConfig[userAgreementConfigKey].asString(), HtmlCompat.FROM_HTML_MODE_COMPACT).toSpannable()
for (span in userAgreementSpannedText.getSpans<URLSpan>()) {
val start = userAgreementSpannedText.getSpanStart(span)
val end = userAgreementSpannedText.getSpanEnd(span)
val flags = userAgreementSpannedText.getSpanFlags(span)
val userAgreementLinkSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
InAppWebViewDialogFragment
.newInstance(getString(R.string.course_purchase_commission_web_view_title), span.url, isProvideAuth = false)
.showIfNotExists(childFragmentManager, InAppWebViewDialogFragment.TAG)
}
}
userAgreementSpannedText.removeSpan(span)
userAgreementSpannedText.setSpan(userAgreementLinkSpan, start, end, flags)
}
return userAgreementSpannedText
}
interface Callback {
fun continueLearning()
}
} | apache-2.0 | 00b876d1a1769f23e49f4e0dfbbfc167 | 45.671687 | 164 | 0.702659 | 5.449877 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/rx/SubjectsTest.kt | 1 | 4018 | package jetbrains.buildServer.dotnet.test.rx
import jetbrains.buildServer.rx.*
import org.testng.Assert
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
class SubjectsTest {
@DataProvider
fun subjectData(): Array<Array<out Any?>> {
return arrayOf(
arrayOf(
observableOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationCompleted.completed<Int>()),
listOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationCompleted.completed<Int>())),
arrayOf(
observableOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationCompleted.completed<Int>(), NotificationNext(4)),
listOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationCompleted.completed<Int>())),
arrayOf(
observableOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationError<Int>(error)),
listOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationError<Int>(error))),
arrayOf(
observableOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationError<Int>(error), NotificationNext(4)),
listOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationError<Int>(error))),
arrayOf(
emptyObservable<Int>(),
emptyList<Int>()))
}
@Test(dataProvider = "subjectData")
fun shouldProvideSubject(data: Observable<Notification<Int>>, expectedNotifications: List<Notification<Int>>) {
// Given
val subject = subjectOf<Int>()
val actualNotifications = mutableListOf<Notification<Int>>()
subject.materialize().subscribe { actualNotifications += it }.use {
// When
data.dematerialize().subscribe(subject)
// Then
Assert.assertEquals(
actualNotifications,
expectedNotifications)
}
}
@DataProvider
fun emptySubjectData(): Array<Array<out Any?>> {
return arrayOf(
arrayOf(
observableOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationCompleted.completed<Int>()),
emptyList<Notification<Int>>()),
arrayOf(
observableOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationCompleted.completed<Int>(), NotificationNext(4)),
emptyList<Notification<Int>>()),
arrayOf(
observableOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationError<Int>(error)),
emptyList<Notification<Int>>()),
arrayOf(
observableOf(NotificationNext(1), NotificationNext(2), NotificationNext(3), NotificationError<Int>(error), NotificationNext(4)),
emptyList<Notification<Int>>()),
arrayOf(
emptyObservable<Int>(),
emptyList<Int>()))
}
@Test(dataProvider = "emptySubjectData")
fun shouldProvideEmptySubject(data: Observable<Notification<Int>>, expectedNotifications: List<Notification<Int>>) {
// Given
val subject = emptySubject<Int>()
val actualNotifications = mutableListOf<Notification<Int>>()
subject.materialize().subscribe { actualNotifications += it }.use {
// When
data.dematerialize().subscribe(subject)
// Then
Assert.assertEquals(
actualNotifications,
expectedNotifications)
}
}
companion object {
private val error = Exception()
}
} | apache-2.0 | 1c223a13cfc056d2052a8808443253d2 | 46.282353 | 161 | 0.598805 | 5.526823 | false | true | false | false |
himaaaatti/spigot-plugins | helloworld/helloworld.kt | 1 | 2166 | package com.github.himaaaatti.spigot.plugin.helloworld
import org.bukkit.plugin.java.JavaPlugin
import org.bukkit.scheduler.BukkitRunnable
import org.bukkit.scheduler.BukkitTask
import org.bukkit.event.world.SpawnChangeEvent
import org.bukkit.World
import org.bukkit.Server
import org.bukkit.event.Listener
import org.bukkit.event.EventHandler
import org.bukkit.event.player.PlayerBedLeaveEvent
class HelloWorld: JavaPlugin() {
lateinit var world : World
lateinit var yoakeTask : BukkitTask
lateinit var yofukeTask: BukkitTask
override fun onEnable() {
world = getServer().getWorlds()[0]
createTasks()
getServer().getPluginManager().registerEvents(
object: Listener{
@EventHandler
fun onChangeSpawn(e: PlayerBedLeaveEvent) {
yoakeTask.cancel()
yofukeTask.cancel()
createTasks()
}
}, this
)
}
fun createTasks() {
val tick_of_day: Long = 24000
val current_time = getServer().getWorlds()[0].getTime()
val YOFUKE_TIME = 13000
val YOAKE_TIME = tick_of_day - 180
var delay_yoake :Long
var delay_fofuke :Long
if(current_time < YOFUKE_TIME) {
delay_fofuke = YOFUKE_TIME - current_time
}
else {
delay_fofuke = tick_of_day - current_time + YOFUKE_TIME
}
if(current_time < YOAKE_TIME) {
delay_yoake = YOAKE_TIME - current_time
}
else {
delay_yoake = tick_of_day - current_time + YOAKE_TIME
}
val server = getServer()
yofukeTask = object: BukkitRunnable() {
override fun run() {
server.broadcastMessage("日本の夜更けぜよ")
}
}.runTaskTimer(this, delay_fofuke, tick_of_day)
yoakeTask = object: BukkitRunnable() {
override fun run() {
server.broadcastMessage("日本の夜明けぜよ")
}
}.runTaskTimer(this, delay_yoake, tick_of_day)
}
}
| mit | 8eac2542ab595852ada6af3189ef3fea | 25.675 | 67 | 0.577788 | 3.996255 | false | false | false | false |
code-helix/slatekit | src/apps/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Example_Entities_Repo.kt | 1 | 5195 | /**
<slate_header>
author: Kishore Reddy
url: www.github.com/code-helix/slatekit
copyright: 2015 Kishore Reddy
license: www.github.com/code-helix/slatekit/blob/master/LICENSE.md
desc: A tool-kit, utility library and server-backend
usage: Please refer to license on github for more info.
</slate_header>
*/
package slatekit.examples
//<doc:import_required>
import slatekit.common.*
//</doc:import_required>
//<doc:import_examples>
import slatekit.db.Db
import slatekit.common.data.DbConString
import slatekit.entities.EntityWithId
import slatekit.entities.core.EntityInfo
import slatekit.entities.repos.InMemoryRepoWithLongId
import slatekit.meta.models.ModelMapper
import slatekit.orm.OrmMapper
import slatekit.orm.databases.vendors.MySqlConverter
import slatekit.orm.databases.vendors.MySqlRepo
import slatekit.results.Try
import slatekit.results.Success
//</doc:import_examples>
class Example_Entities_Repo : Command("entities") {
//<doc:setup>
// Example entity that the Repo with manage via CRUD operations
data class User(
override val id:Long = 0L,
@property:Field(required = true, length = 30)
val email:String = "",
@property:Field(required = true, length = 30)
val firstName:String = "",
@property:Field(required = true, length =30)
val lastName:String = "",
@property:Field(required = true)
val isMale:Boolean = false,
@property:Field(required = true)
val age:Int = 35
) : EntityWithId<Long> {
override fun isPersisted(): Boolean = id > 0
fun fullname():String = firstName + " " + lastName
override fun toString():String {
return "$email, $firstName, $lastName, $isMale, $age"
}
}
// CASE 1: In-memory ( non-persisted ) repository has limited functionality
// but is very useful for rapid prototyping of a data model when you are trying to
// figure out what fields/properties should exist on the model
val repo = InMemoryRepoWithLongId(User::class)
// CASE 2: My-sql ( persisted ) repository can be easily setup
// More examples of database setup/entity registration available in Setup/Registration docs.
// 1. First setup the database
val db = Db(DbConString("com.mysql.jdbc.Driver", "jdbc:mysql://localhost/user_db", "root", "abcdefghi"))
// 2. Setup the mapper
val model = ModelMapper.loadSchema(User::class)
val mapper: OrmMapper<Long, User> = OrmMapper(model, db, MySqlConverter(), Long::class, User::class)
// 3. Now create the repo with database and mapper
val entityInfo = EntityInfo(Long::class, slatekit.examples.common.User::class, "users")
val repoMySql = MySqlRepo(db, entityInfo, mapper)
// CASE 3: You can also extend from EntityRepositoryMySql
class UserRepository(db:Db, info:EntityInfo, mapper: OrmMapper<Long, User>) : MySqlRepo<Long, User>(db, info, mapper)
val userRepo = UserRepository(db, entityInfo, mapper)
//</doc:setup>
override protected fun execute(request: CommandRequest): Try<Any> {
//<doc:examples>
// CASE 1: Create 3-4 users for showing use-cases
repo.create(User(firstName ="john", lastName = "doe-01"))
repo.create(User(firstName ="jane", lastName = "doe-02"))
repo.create(User(firstName ="john", lastName = "doe-03"))
repo.create(User(firstName ="jane", lastName = "doe-04"))
// CASE 2: Get by id
printOne("2", repo.getById(2))
// CASE 3: Update
val item2 = repo.getById(2)
item2?.let { item ->
val updated = item.copy(firstName = "user_two")
repo.update(updated)
}
// CASE 4: Get all
printAll("all", repo.getAll())
// CASE 5: Get recent users ( 03, 04 )
printAll("recent", repo.recent(2))
// CASE 6: Get oldest users ( 01, 02 )
printAll("oldest", repo.oldest(2))
// CASE 7: Get first one ( oldest - 01 )
printOne("first", repo.first())
// CASE 8: Get last one ( recent - 04 )
printOne("last", repo.last())
// CASE 9: Delete by id
repo.deleteById(4)
// CASE 10: Get total ( 4 )
println(repo.count())
//</doc:examples>
return Success("")
}
fun printAll(tag: String, models: List<User>): Unit {
println()
println(tag.toUpperCase())
for (model in models)
printOne(null, model)
}
fun printOne(tag: String?, model: User?): Unit {
tag?.let { t ->
println()
println(t.toUpperCase())
}
model?.let { m ->
println("User: " + m.id + ", " + m.firstName + ", " + m.lastName)
}
}
/*
//<doc:output>
```bat
2
User: 2, jane, doe-02
ALL
User: 1, john, doe-01
User: 3, john, doe-03
User: 4, jane, doe-04
User: 2, user_two, doe-02
RECENT
User: 4, jane, doe-04
User: 3, john, doe-03
OLDEST
User: 1, john, doe-01
User: 2, user_two, doe-02
FIRST
User: 1, john, doe-01
LAST
User: 4, jane, doe-04
3
```
//</doc:output>
*/
}
| apache-2.0 | 501c948977d9985661d9af16fcd395bb | 25.505102 | 121 | 0.619057 | 3.767223 | false | false | false | false |
redism/rxtest | android/RxTest/app/src/test/java/me/snippex/rxtest/RxSimpleTest.kt | 1 | 3625 | package me.snippex.rxtest
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.schedulers.Schedulers
import org.junit.Assert.assertEquals
import org.junit.Test
import java.util.concurrent.CountDownLatch
class RxSimpleTest {
@Test
@Throws(Exception::class)
fun rxToBlockingShouldWork() {
assertEquals(Observable.just(1).blockingFirst(), 1)
}
@Test
fun addToAndCompositeDisposable() {
val disposeBag = CompositeDisposable()
Observable.just(10)
.subscribe()
.addTo(disposeBag) // TODO: addTo has been added?
}
@Test
@Throws(Exception::class)
fun rxObserveOnVsSubscribeOn() {
//
// observeOn 과 subscribeOn 과의 차이점을 설명합니다. 아래의 결과에서 볼 수 있는 것처럼 subscribeOn은 subscription 이 발생하는
// 스케줄러를 결정하고 observeOn은 이후의 스트림을 어떤 스케줄러에서 처리할 것인지를 결정한다.
//
// RESULTS
// =======
// [main] waiting stream to be completed.
// [RxNewThreadScheduler-1] createSimpleObservable, new subscriber found.
// [RxNewThreadScheduler-1] first doOnEach : OnNextNotification[10]
// [RxNewThreadScheduler-1] first doOnEach : OnCompleteNotification
// [RxComputationThreadPool-1] second doOnEach : OnNextNotification[10]
// [RxComputationThreadPool-1] value subscribed => 10
// [RxComputationThreadPool-1] second doOnEach : OnCompleteNotification
//
// 관전 포인트
// ========
// 각 출력이 발생한 쓰레드
// 각 출력이 발생한 순서 (실행할 때마다 순서가 바뀌기도 함)
//
fun createSimpleObservable(value: Int = 0): Observable<Int> {
return Observable.create<Int> { sub ->
pp(" createSimpleObservable, new subscriber found.") // Scheduler => Schedulers.newThread()
sub.onNext(value)
sub.onComplete()
}
}
val latch = CountDownLatch(1)
val disposeBag = CompositeDisposable()
createSimpleObservable(10)
.doOnEach { pp(" first doOnEach : $it") }
.subscribeOn(Schedulers.newThread())
.subscribeOn(Schedulers.io()) // subscribeOn 이 여러번 불려도 가장 앞의 것이 선택된다.
.observeOn(Schedulers.computation())
.doOnEach { pp(" second doOnEach : $it") }
.doOnComplete { latch.countDown() }
.subscribe { pp(" value subscribed => $it") }
.addTo(disposeBag)
pp(" waiting stream to be completed.")
latch.await() // 테스트는 main thread 를 기준으로 동작하므로 락을 걸지 않으면 파이프라인이 종료되기 전에 테스트가 끝나버린다.
disposeBag.dispose()
}
@Test
@Throws(Exception::class)
fun observableFrom() {
Observable.fromCallable { 100 }
.doOnEach { pp(" $it") }
.subscribe { pp(" $it") }
}
// http://reactivex.io/documentation/ko/single.html
@Test
fun rxSingle() {
// Single.just(10).compose { upstream: Single<Int> ->
//
// }
}
fun differenceBetweenObserveOnAndSubcribeOn() {
}
} | gpl-3.0 | 1f594c085f02ba872eeb721271bf050f | 31.444444 | 109 | 0.583619 | 3.678121 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/ranges/literal/progressionDownToMinValue.kt | 2 | 2325 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
// TODO: muted automatically, investigate should it be ran for NATIVE or not
// IGNORE_BACKEND: NATIVE
// Auto-generated by org.jetbrains.kotlin.generators.tests.GenerateRangesCodegenTestData. DO NOT EDIT!
// WITH_RUNTIME
import java.lang.Integer.MAX_VALUE as MaxI
import java.lang.Integer.MIN_VALUE as MinI
import java.lang.Byte.MAX_VALUE as MaxB
import java.lang.Byte.MIN_VALUE as MinB
import java.lang.Short.MAX_VALUE as MaxS
import java.lang.Short.MIN_VALUE as MinS
import java.lang.Long.MAX_VALUE as MaxL
import java.lang.Long.MIN_VALUE as MinL
import java.lang.Character.MAX_VALUE as MaxC
import java.lang.Character.MIN_VALUE as MinC
fun box(): String {
val list1 = ArrayList<Int>()
for (i in (MinI + 2) downTo MinI step 1) {
list1.add(i)
if (list1.size > 23) break
}
if (list1 != listOf<Int>(MinI + 2, MinI + 1, MinI)) {
return "Wrong elements for (MinI + 2) downTo MinI step 1: $list1"
}
val list2 = ArrayList<Int>()
for (i in (MinB + 2).toByte() downTo MinB step 1) {
list2.add(i)
if (list2.size > 23) break
}
if (list2 != listOf<Int>((MinB + 2).toInt(), (MinB + 1).toInt(), MinB.toInt())) {
return "Wrong elements for (MinB + 2).toByte() downTo MinB step 1: $list2"
}
val list3 = ArrayList<Int>()
for (i in (MinS + 2).toShort() downTo MinS step 1) {
list3.add(i)
if (list3.size > 23) break
}
if (list3 != listOf<Int>((MinS + 2).toInt(), (MinS + 1).toInt(), MinS.toInt())) {
return "Wrong elements for (MinS + 2).toShort() downTo MinS step 1: $list3"
}
val list4 = ArrayList<Long>()
for (i in (MinL + 2).toLong() downTo MinL step 1) {
list4.add(i)
if (list4.size > 23) break
}
if (list4 != listOf<Long>((MinL + 2).toLong(), (MinL + 1).toLong(), MinL)) {
return "Wrong elements for (MinL + 2).toLong() downTo MinL step 1: $list4"
}
val list5 = ArrayList<Char>()
for (i in (MinC + 2) downTo MinC step 1) {
list5.add(i)
if (list5.size > 23) break
}
if (list5 != listOf<Char>((MinC + 2), (MinC + 1), MinC)) {
return "Wrong elements for (MinC + 2) downTo MinC step 1: $list5"
}
return "OK"
}
| apache-2.0 | 2f97dbd32b33da7674d210cea5c00332 | 32.695652 | 102 | 0.618925 | 3.120805 | false | false | false | false |
smmribeiro/intellij-community | build/tasks/src/org/jetbrains/intellij/build/io/ZipFileWriter.kt | 1 | 9091 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.io
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.channels.FileChannel.MapMode
import java.nio.channels.WritableByteChannel
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.*
import java.util.zip.CRC32
import java.util.zip.Deflater
import java.util.zip.ZipEntry
import kotlin.math.min
// 1 MB
private const val largeFileThreshold = 1_048_576
private const val compressThreshold = 8 * 1024
// 8 MB (as JDK)
private const val mappedTransferSize = 8L * 1024L * 1024L
internal inline fun writeNewZip(file: Path, compress: Boolean = false, task: (ZipFileWriter) -> Unit) {
Files.createDirectories(file.parent)
ZipFileWriter(channel = FileChannel.open(file, W_CREATE_NEW),
deflater = if (compress) Deflater(Deflater.DEFAULT_COMPRESSION, true) else null).use {
task(it)
}
}
// you must pass SeekableByteChannel if files will be written (`file` method)
internal class ZipFileWriter(channel: WritableByteChannel, private val deflater: Deflater? = null) : AutoCloseable {
constructor(channel: WritableByteChannel, compress: Boolean)
: this(channel = channel, deflater = if (compress) Deflater(Deflater.DEFAULT_COMPRESSION, true) else null)
// size is written as part of optimized metadata - so, if compression is enabled, optimized metadata will be incorrect
val resultStream = ZipArchiveOutputStream(channel, withOptimizedMetadataEnabled = deflater == null)
private val crc32 = CRC32()
private val bufferAllocator = ByteBufferAllocator()
private val deflateBufferAllocator = if (deflater == null) null else ByteBufferAllocator()
@Suppress("DuplicatedCode")
fun file(nameString: String, file: Path) {
var isCompressed = deflater != null && !nameString.endsWith(".png")
val name = nameString.toByteArray()
val headerSize = 30 + name.size
crc32.reset()
val input: ByteBuffer
val size: Int
FileChannel.open(file, EnumSet.of(StandardOpenOption.READ)).use { channel ->
size = channel.size().toInt()
if (size == 0) {
writeEmptyFile(name, headerSize)
return
}
if (size < compressThreshold) {
isCompressed = false
}
if (size > largeFileThreshold || isCompressed) {
val headerPosition = resultStream.getChannelPositionAndAdd(headerSize)
var compressedSize = writeLargeFile(size.toLong(), channel, if (isCompressed) deflater else null).toInt()
val crc = crc32.value
val method: Int
if (compressedSize == -1) {
method = ZipEntry.STORED
compressedSize = size
}
else {
method = ZipEntry.DEFLATED
}
val buffer = bufferAllocator.allocate(headerSize)
writeLocalFileHeader(name = name, size = size, compressedSize = compressedSize, crc32 = crc, method = method, buffer = buffer)
buffer.position(0)
assert(buffer.remaining() == headerSize)
resultStream.writeEntryHeaderAt(name = name,
header = buffer,
position = headerPosition,
size = size,
compressedSize = compressedSize,
crc = crc,
method = method)
return
}
input = bufferAllocator.allocate(headerSize + size)
input.position(headerSize)
// set position to compute CRC
input.mark()
do {
channel.read(input)
}
while (input.hasRemaining())
input.reset()
crc32.update(input)
}
val crc = crc32.value
input.position(0)
writeLocalFileHeader(name, size, size, crc, ZipEntry.STORED, input)
input.position(0)
assert(input.remaining() == (size + headerSize))
resultStream.writeRawEntry(input, name, size, size, ZipEntry.STORED, crc, headerSize)
}
private fun writeLargeFile(fileSize: Long, channel: FileChannel, deflater: Deflater?): Long {
// channel.transferTo will use a slow path for untrusted (custom) WritableByteChannel implementations, so, duplicate what JDK does
// see FileChannelImpl.transferFromFileChannel
var remaining = fileSize
var position = 0L
var compressedSize = 0L
var effectiveDeflater = deflater
while (remaining > 0L) {
val size = min(remaining, mappedTransferSize)
val buffer = channel.map(MapMode.READ_ONLY, position, size)
remaining -= size
position += size
try {
buffer.mark()
crc32.update(buffer)
buffer.reset()
buffer.mark()
if (effectiveDeflater == null) {
resultStream.writeBuffer(buffer)
compressedSize = -1
}
else {
val output = deflateBufferAllocator!!.allocate(size.toInt() + 4096)
effectiveDeflater.setInput(buffer)
if (remaining <= 0) {
effectiveDeflater.finish()
}
do {
val n = effectiveDeflater.deflate(output, Deflater.SYNC_FLUSH)
assert(n != 0)
}
while (buffer.hasRemaining())
output.flip()
compressedSize += output.remaining()
if (position == 0L && compressedSize > size) {
// incompressible
effectiveDeflater = null
buffer.reset()
resultStream.writeBuffer(buffer)
compressedSize = -1
}
else {
resultStream.writeBuffer(output)
}
}
}
finally {
unmapBuffer(buffer)
}
}
effectiveDeflater?.reset()
return compressedSize
}
@Suppress("DuplicatedCode")
fun compressedData(nameString: String, data: ByteArray) {
val name = nameString.toByteArray()
val headerSize = 30 + name.size
val input = ByteBuffer.wrap(data)
val size = data.size
crc32.reset()
crc32.update(data)
val crc = crc32.value
input.position(0)
val output = deflateBufferAllocator!!.allocate(headerSize + size + 4096)
output.position(headerSize)
deflater!!.setInput(input)
deflater.finish()
do {
val n = deflater.deflate(output, Deflater.SYNC_FLUSH)
assert(n != 0)
}
while (input.hasRemaining())
deflater.reset()
output.limit(output.position())
output.position(0)
val compressedSize = output.remaining() - headerSize
writeLocalFileHeader(name, size, compressedSize, crc, ZipEntry.DEFLATED, output)
output.position(0)
assert(output.remaining() == (compressedSize + headerSize))
resultStream.writeRawEntry(output, name, size, compressedSize, ZipEntry.DEFLATED, crc, headerSize)
}
fun uncompressedData(nameString: String, data: String) {
uncompressedData(nameString, ByteBuffer.wrap(data.toByteArray()))
}
fun uncompressedData(nameString: String, data: ByteBuffer) {
val name = nameString.toByteArray()
val headerSize = 30 + name.size
if (!data.hasRemaining()) {
writeEmptyFile(name, headerSize)
return
}
data.mark()
crc32.reset()
crc32.update(data)
val crc = crc32.value
data.reset()
val size = data.remaining()
val header = bufferAllocator.allocate(headerSize)
writeLocalFileHeader(name, size, size, crc, ZipEntry.STORED, header)
header.position(0)
resultStream.writeRawEntry(header, data, name, size, size, ZipEntry.STORED, crc)
}
fun uncompressedData(nameString: String, maxSize: Int, dataWriter: (ByteBuffer) -> Unit) {
val name = nameString.toByteArray()
val headerSize = 30 + name.size
val output = bufferAllocator.allocate(headerSize + maxSize)
output.position(headerSize)
dataWriter(output)
output.limit(output.position())
output.position(headerSize)
val size = output.remaining()
crc32.reset()
crc32.update(output)
val crc = crc32.value
output.position(0)
writeLocalFileHeader(name, size, size, crc, ZipEntry.STORED, output)
output.position(0)
assert(output.remaining() == (size + headerSize))
resultStream.writeRawEntry(output, name, size, size, ZipEntry.STORED, crc, headerSize)
}
private fun writeEmptyFile(name: ByteArray, headerSize: Int) {
val input = bufferAllocator.allocate(headerSize)
writeLocalFileHeader(name, size = 0, compressedSize = 0, crc32 = 0, method = ZipEntry.STORED, buffer = input)
input.position(0)
input.limit(headerSize)
resultStream.writeRawEntry(input, name, 0, 0, ZipEntry.STORED, 0, headerSize)
}
fun dir(name: String) {
resultStream.addDirEntry(name)
}
override fun close() {
@Suppress("ConvertTryFinallyToUseCall")
try {
bufferAllocator.close()
deflateBufferAllocator?.close()
deflater?.end()
}
finally {
resultStream.close()
}
}
} | apache-2.0 | 292754edda49cf240743b6ee29b295f1 | 31.355872 | 158 | 0.653943 | 4.37488 | false | false | false | false |
cd1/motofretado | app/src/main/java/com/gmail/cristiandeives/motofretado/TrackBusPresenter.kt | 1 | 9392 | package com.gmail.cristiandeives.motofretado
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.os.Messenger
import android.preference.PreferenceManager
import android.support.annotation.UiThread
import android.util.Log
import com.gmail.cristiandeives.motofretado.http.Bus
import com.gmail.cristiandeives.motofretado.http.ModelListener
import java.lang.ref.WeakReference
@UiThread
internal class TrackBusPresenter(private val mContext: Context) : TrackBusMvp.Presenter {
companion object {
private val TAG = TrackBusPresenter::class.java.simpleName
private const val MOST_RECENT_TRACK_BUS_ID_PREF = "most_recent_track_bus_id"
}
private val mModel: TrackBusMvp.Model = TrackBusModel(mContext)
private var mView: TrackBusMvp.View? = null
private val mActivityDetectionServiceIntent: Intent
private val mUpdateLocationServiceIntent: Intent
private var mIsUpdateLocationServiceRunning: Boolean = false
private var mIsActivityDetectionServiceRunning: Boolean = false
private var mSelectedBusId: String? = null
private var mAvailableBuses: List<Bus>? = null
private var mBusErrorMessage: String? = null
init {
val messenger = Messenger(MyHandler(this))
mActivityDetectionServiceIntent = Intent(mContext, ActivityInVehicleFenceService::class.java).apply {
putExtra(ActivityInVehicleFenceService.EXTRA_MESSENGER, messenger)
}
mUpdateLocationServiceIntent = Intent(mContext, UpdateLocationService::class.java).apply {
putExtra(UpdateLocationService.EXTRA_MESSENGER, messenger)
}
mModel.readAllBuses(ReadAllBusesListener(null, true))
}
override fun onAttach(view: TrackBusMvp.View) {
mView = view
val errorMessage = mBusErrorMessage
if (errorMessage != null && errorMessage.isNotEmpty()) {
view.setBusError(errorMessage)
} else {
mAvailableBuses?.let { buses ->
view.apply {
setAvailableBuses(buses, mSelectedBusId)
enableBusId()
}
}
}
if (mIsUpdateLocationServiceRunning || mIsActivityDetectionServiceRunning) {
view.disableBusId()
}
if (!mIsActivityDetectionServiceRunning) {
view.uncheckSwitchDetectAutomatically()
}
}
override fun onDetach() {
mSelectedBusId = mView?.getBusId()
mView = null
}
override fun startLocationUpdate() {
mView?.let { view ->
val busId = view.getBusId()
Log.d(TAG, "starting service ${mUpdateLocationServiceIntent.component}")
mUpdateLocationServiceIntent.putExtra(UpdateLocationService.EXTRA_BUS_ID, busId)
mContext.startService(mUpdateLocationServiceIntent)
Log.d(TAG, "writing preference: $MOST_RECENT_TRACK_BUS_ID_PREF => $busId")
mContext.editSharedPreferences {
putString(MOST_RECENT_TRACK_BUS_ID_PREF, busId)
}
}
}
override fun stopLocationUpdate() {
if (mIsUpdateLocationServiceRunning) {
Log.d(TAG, "stopping service ${mUpdateLocationServiceIntent.component}")
mContext.stopService(mUpdateLocationServiceIntent)
}
}
override fun startActivityDetection() {
Log.d(TAG, "starting service ${mActivityDetectionServiceIntent.component}")
mContext.startService(mActivityDetectionServiceIntent)
}
override fun stopActivityDetection() {
if (mIsActivityDetectionServiceRunning) {
Log.d(TAG, "stopping service ${mActivityDetectionServiceIntent.component}")
mContext.stopService(mActivityDetectionServiceIntent)
}
}
override fun createBus(bus: Bus) {
Log.d(TAG, "creating bus: $bus")
mModel.createBus(bus, PostBusListener())
}
internal class MyHandler(presenter: TrackBusPresenter) : Handler() {
companion object {
const val MSG_DISPLAY_TOAST = 0
const val MSG_GMS_CONNECTION_FAILED = 1
const val MSG_UPDATE_LOCATION_SERVICE_CONNECTED = 2
const val MSG_UPDATE_LOCATION_SERVICE_DISCONNECTED = 3
const val MSG_ACTIVITY_DETECTION_SERVICE_CONNECTED = 4
const val MSG_ACTIVITY_DETECTION_SERVICE_DISCONNECTED = 5
const val MSG_USER_IS_ON_FOOT = 6
const val MSG_USER_IS_IN_VEHICLE = 7
}
private val mPresenterRef: WeakReference<TrackBusPresenter> = WeakReference(presenter)
override fun handleMessage(msg: Message) {
Log.v(TAG, "> handleMessage(msg=$msg)")
mPresenterRef.get()?.let { presenter ->
when (msg.what) {
MSG_DISPLAY_TOAST -> presenter.mView?.displayMessage(presenter.mContext.getString(msg.arg1))
MSG_GMS_CONNECTION_FAILED -> {
presenter.mView?.let { view ->
view.apply {
displayMessage(presenter.mContext.getString(R.string.gms_connection_failed))
uncheckSwitchDetectAutomatically()
}
}
}
MSG_UPDATE_LOCATION_SERVICE_DISCONNECTED -> {
presenter.apply {
mIsUpdateLocationServiceRunning = false
mView?.let { view ->
view.enableBusId()
view.uncheckSwitchDetectAutomatically()
}
mModel.cancelAllRequests()
}
}
MSG_UPDATE_LOCATION_SERVICE_CONNECTED -> {
presenter.apply {
mIsUpdateLocationServiceRunning = true
mView?.disableBusId()
}
}
MSG_ACTIVITY_DETECTION_SERVICE_CONNECTED -> {
presenter.apply {
mIsActivityDetectionServiceRunning = true
mView?.disableBusId()
}
}
MSG_ACTIVITY_DETECTION_SERVICE_DISCONNECTED -> presenter.apply {
mIsActivityDetectionServiceRunning = false
if (!mIsUpdateLocationServiceRunning) {
mView?.enableBusId()
}
}
MSG_USER_IS_ON_FOOT -> presenter.apply {
if (mIsUpdateLocationServiceRunning) {
stopLocationUpdate()
stopActivityDetection()
}
}
MSG_USER_IS_IN_VEHICLE -> presenter.apply {
if (!mIsUpdateLocationServiceRunning) {
startLocationUpdate()
}
}
else -> Log.wtf(TAG, "unexpected message code: ${msg.what}")
}
}
Log.v(TAG, "< handleMessage(msg=$msg)")
}
}
private inner class ReadAllBusesListener(private val mSelectedBusId: String?, private val mSelectDefaultFromPref: Boolean) : ModelListener<List<Bus>> {
override fun onSuccess(data: List<Bus>) {
mView?.let { view ->
if (!data.isEmpty()) {
val selectedBusId = if (mSelectDefaultFromPref) {
val busIdPref = PreferenceManager.getDefaultSharedPreferences(mContext)
.getString(MOST_RECENT_TRACK_BUS_ID_PREF, null)
Log.d(TAG, "preference read: $MOST_RECENT_TRACK_BUS_ID_PREF => $busIdPref")
busIdPref
} else if (!mSelectedBusId.isNullOrEmpty()) {
mSelectedBusId
} else {
null
}
view.enableBusId()
view.setAvailableBuses(data, selectedBusId)
mBusErrorMessage = null
mAvailableBuses = data
} else {
val errorMessage = mContext.getString(R.string.no_buses_available)
view.setBusError(errorMessage)
mBusErrorMessage = errorMessage
}
}
}
override fun onError(ex: Exception) {
Log.e(TAG, "could not read buses", ex)
val errorMessage = mContext.getString(R.string.read_buses_failed)
mView?.setBusError(errorMessage)
mBusErrorMessage = errorMessage
}
}
private inner class PostBusListener : ModelListener<Bus> {
override fun onSuccess(data: Bus) {
Log.d(TAG, "bus created successfully: $data")
mModel.readAllBuses(ReadAllBusesListener(data.id, false))
}
override fun onError(ex: Exception) {
Log.e(TAG, "could not create bus", ex)
mView?.displayMessage(mContext.getString(R.string.create_bus_failed))
}
}
} | gpl-3.0 | 35dc170a68cf2aa2858ade1bbd73b038 | 38.970213 | 155 | 0.567611 | 5.074014 | false | false | false | false |
CORDEA/ConviviumCalculator | android (kotlin)/app/src/main/kotlin/jp/cordea/conviviumcalculator/CsvIo.kt | 1 | 2032 | package jp.cordea.conviviumcalculator
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import io.realm.Realm
object CsvIo {
fun input(csv: String): Completable =
Single
.fromCallable {
Realm.getDefaultInstance().apply {
beginTransaction()
where(ListItem::class.java).findAll().deleteAllFromRealm()
}
}
.flatMapObservable { realm ->
Single.just(csv)
.flatMapObservable { Observable.fromIterable(it.split('\n')) }
.map { it.split(',').toTypedArray() }
.filter { it.isNotEmpty() }
.doOnNext {
it[1].toIntOrNull()?.let { price ->
val item = realm.createObject(ListItem::class.java, it[0])
item.price = price
item.isChecked = if (it.size > 2) it[2].toBoolean() else false
}
}
.doOnComplete {
realm.commitTransaction()
realm.close()
}
}
.ignoreElements()
fun output(): Single<String> =
Single
.fromCallable {
Realm.getDefaultInstance().run {
where(ListItem::class.java).findAll()
}
}
.flatMapObservable { Observable.fromIterable(it) }
.map { "%s,%d,%s".format(it.name, it.price, it.isChecked.toString()) }
.toList()
.map { it.joinToString("\n") }
}
| apache-2.0 | 68b9e4f91394077019bbf4d0968090fb | 41.333333 | 102 | 0.389764 | 6.43038 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt | 1 | 10850 | package info.nightscout.androidaps.plugins.general.automation
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import dagger.android.HasAndroidInjector
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.AutomationEventItemBinding
import info.nightscout.androidaps.databinding.AutomationFragmentBinding
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog
import info.nightscout.androidaps.plugins.general.automation.dragHelpers.ItemTouchHelperAdapter
import info.nightscout.androidaps.plugins.general.automation.dragHelpers.ItemTouchHelperViewHolder
import info.nightscout.androidaps.plugins.general.automation.dragHelpers.OnStartDragListener
import info.nightscout.androidaps.plugins.general.automation.dragHelpers.SimpleItemTouchHelperCallback
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationDataChanged
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation
import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import java.util.*
import javax.inject.Inject
class AutomationFragment : DaggerFragment(), OnStartDragListener {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var injector: HasAndroidInjector
private var disposable: CompositeDisposable = CompositeDisposable()
private lateinit var eventListAdapter: EventListAdapter
private var itemTouchHelper: ItemTouchHelper? = null
private var _binding: AutomationFragmentBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = AutomationFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
eventListAdapter = EventListAdapter()
binding.eventListView.layoutManager = LinearLayoutManager(context)
binding.eventListView.adapter = eventListAdapter
binding.logView.movementMethod = ScrollingMovementMethod()
binding.fabAddEvent.setOnClickListener {
val dialog = EditEventDialog()
val args = Bundle()
args.putString("event", AutomationEvent(injector).toJSON())
args.putInt("position", -1) // New event
dialog.arguments = args
dialog.show(childFragmentManager, "EditEventDialog")
}
val callback: ItemTouchHelper.Callback = SimpleItemTouchHelperCallback(eventListAdapter)
itemTouchHelper = ItemTouchHelper(callback)
itemTouchHelper?.attachToRecyclerView(binding.eventListView)
}
@Synchronized
override fun onResume() {
super.onResume()
disposable += rxBus
.toObservable(EventAutomationUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
updateGui()
}, { fabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventAutomationDataChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
eventListAdapter.notifyDataSetChanged()
}, { fabricPrivacy.logException(it) })
updateGui()
}
@Synchronized
override fun onPause() {
super.onPause()
disposable.clear()
}
@Synchronized
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
@Synchronized
private fun updateGui() {
if (_binding == null) return
eventListAdapter.notifyDataSetChanged()
val sb = StringBuilder()
for (l in automationPlugin.executionLog.reversed())
sb.append(l).append("<br>")
binding.logView.text = HtmlHelper.fromHtml(sb.toString())
}
override fun onStartDrag(viewHolder: RecyclerView.ViewHolder) {
itemTouchHelper?.startDrag(viewHolder)
}
fun fillIconSet(connector: TriggerConnector, set: HashSet<Int>) {
for (t in connector.list) {
if (t is TriggerConnector) {
fillIconSet(t, set)
} else {
val icon = t.icon()
if (icon.isPresent) {
set.add(icon.get()!!)
}
}
}
}
inner class EventListAdapter : RecyclerView.Adapter<EventListAdapter.ViewHolder>(), ItemTouchHelperAdapter {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.automation_event_item, parent, false)
return ViewHolder(v, parent.context)
}
private fun addImage(@DrawableRes res: Int, context: Context, layout: LinearLayout) {
val iv = ImageView(context)
iv.setImageResource(res)
iv.layoutParams = LinearLayout.LayoutParams(resourceHelper.dpToPx(24), resourceHelper.dpToPx(24))
layout.addView(iv)
}
@SuppressLint("ClickableViewAccessibility")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val event = automationPlugin.at(position)
holder.binding.eventTitle.text = event.title
holder.binding.enabled.isChecked = event.isEnabled
holder.binding.enabled.isEnabled = !event.readOnly
holder.binding.iconLayout.removeAllViews()
// trigger icons
val triggerIcons = HashSet<Int>()
fillIconSet(event.trigger as TriggerConnector, triggerIcons)
for (res in triggerIcons) {
addImage(res, holder.context, holder.binding.iconLayout)
}
// arrow icon
val iv = ImageView(holder.context)
iv.setImageResource(R.drawable.ic_arrow_forward_white_24dp)
iv.layoutParams = LinearLayout.LayoutParams(resourceHelper.dpToPx(24), resourceHelper.dpToPx(24))
iv.setPadding(resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4), 0)
holder.binding.iconLayout.addView(iv)
// action icons
val actionIcons = HashSet<Int>()
for (action in event.actions) {
actionIcons.add(action.icon())
}
for (res in actionIcons) {
addImage(res, holder.context, holder.binding.iconLayout)
}
// enabled event
holder.binding.enabled.setOnClickListener {
event.isEnabled = holder.binding.enabled.isChecked
rxBus.send(EventAutomationDataChanged())
}
// edit event
holder.binding.rootLayout.setOnClickListener {
val dialog = EditEventDialog()
val args = Bundle()
args.putString("event", event.toJSON())
args.putInt("position", position)
dialog.arguments = args
dialog.show(childFragmentManager, "EditEventDialog")
}
// Start a drag whenever the handle view it touched
holder.binding.iconSort.setOnTouchListener { v: View, motionEvent: MotionEvent ->
if (motionEvent.action == MotionEvent.ACTION_DOWN) {
[email protected](holder)
return@setOnTouchListener true
}
v.onTouchEvent(motionEvent)
}
// remove event
holder.binding.iconTrash.setOnClickListener {
showConfirmation(requireContext(), resourceHelper.gs(R.string.removerecord) + " " + automationPlugin.at(position).title,
Runnable {
automationPlugin.removeAt(position)
notifyItemRemoved(position)
}, Runnable {
rxBus.send(EventAutomationUpdateGui())
})
}
holder.binding.iconTrash.visibility = (!event.readOnly).toVisibility()
holder.binding.aapsLogo.visibility = (event.systemAction).toVisibility()
}
override fun getItemCount(): Int = automationPlugin.size()
override fun onItemMove(fromPosition: Int, toPosition: Int): Boolean {
automationPlugin.swap(fromPosition, toPosition)
notifyItemMoved(fromPosition, toPosition)
return true
}
override fun onItemDismiss(position: Int) {
activity?.let { activity ->
showConfirmation(activity, resourceHelper.gs(R.string.removerecord) + " " + automationPlugin.at(position).title,
Runnable {
automationPlugin.removeAt(position)
notifyItemRemoved(position)
rxBus.send(EventAutomationDataChanged())
}, Runnable { rxBus.send(EventAutomationUpdateGui()) })
}
}
inner class ViewHolder(view: View, val context: Context) : RecyclerView.ViewHolder(view), ItemTouchHelperViewHolder {
val binding = AutomationEventItemBinding.bind(view)
override fun onItemSelected() = itemView.setBackgroundColor(Color.LTGRAY)
override fun onItemClear() = itemView.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault))
}
}
}
| agpl-3.0 | ecf189fcd24573b2e54007c32d335628 | 41.885375 | 136 | 0.675945 | 5.350099 | false | false | false | false |
Flank/flank | test_runner/src/main/kotlin/ftl/client/RunShellCommand.kt | 1 | 1459 | package ftl.client
import flank.common.isWindows
import ftl.run.exception.FlankGeneralError
import ftl.util.failed
import ftl.util.waitForResult
sealed class ShellEnvironment(val execution: String) {
object Bash : ShellEnvironment("Bash.exe")
object BinBash : ShellEnvironment("/bin/bash")
object Cmd : ShellEnvironment("cmd.exe")
object Default : ShellEnvironment(if (isWindows) "cmd.exe" else "/bin/bash")
}
fun runShellCommand(
cmd: String,
additionalPath: List<Pair<String, String>>
): String {
val process = ProcessBuilder(shell.execution, command, cmd)
.appendAdditionalPaths(additionalPath)
.redirectOutput(ProcessBuilder.Redirect.PIPE)
.redirectError(ProcessBuilder.Redirect.PIPE)
.start()
val result = process.waitForResult()
if (process.failed()) {
System.err.println("Error: ${result.stderr}")
throw FlankGeneralError("Command failed: $cmd")
}
return result.stdout.trim() + result.stderr.trim()
}
private fun ProcessBuilder.appendAdditionalPaths(
additionalPath: List<Pair<String, String>>
) = apply {
val envs: MutableMap<String, String> = environment()
additionalPath.onEach { (key, value) -> envs[key] = value }
}
private val shell: ShellEnvironment by lazy {
when {
isWindows -> ShellEnvironment.Cmd
else -> ShellEnvironment.BinBash
}
}
private val command: String
get() = if (isWindows) "/c" else "-c"
| apache-2.0 | 1f3ab26c215819104d45c3cadd0faa8e | 28.18 | 80 | 0.697053 | 4.052778 | false | false | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/api/WykopImageFile.kt | 1 | 4182 | package io.github.feelfreelinux.wykopmobilny.api
import android.content.Context
import android.graphics.BitmapFactory
import android.net.Uri
import io.github.feelfreelinux.wykopmobilny.utils.FileUtils
import io.github.feelfreelinux.wykopmobilny.utils.printout
import io.github.feelfreelinux.wykopmobilny.utils.queryFileName
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import com.google.android.youtube.player.internal.y
import com.google.android.youtube.player.internal.x
import android.graphics.Bitmap
import android.R.attr.orientation
import android.graphics.Matrix
import android.media.ExifInterface
import android.util.Log
import com.evernote.android.job.JobProxy.Common
import com.google.android.youtube.player.internal.v
import io.github.feelfreelinux.wykopmobilny.R.id.imageView
import java.io.*
import android.os.Environment.getExternalStorageDirectory
class WykopImageFile(val uri: Uri, val context: Context) {
fun getFileMultipart(): MultipartBody.Part {
val contentResolver = context.contentResolver
val filename = uri.queryFileName(contentResolver)
var file: File?
try {
file = FileUtils.getFile(context, uri)
if (file == null) {
file = saveUri(uri, filename)
}
} catch (e: Throwable) {
file = saveUri(uri, filename)
}
var mimetype = contentResolver.getType(uri)
file?.let {
val opt = BitmapFactory.Options()
opt.inJustDecodeBounds = true
BitmapFactory.decodeFile(it.absolutePath, opt)
mimetype = opt.outMimeType
}
val rotatedFile = ensureRotation(file)
printout(rotatedFile!!.name!!)
return MultipartBody.Part.createFormData("embed", rotatedFile!!.name, RequestBody.create(MediaType.parse(mimetype), rotatedFile))
}
private fun saveUri(uri: Uri, filename: String): File? {
val inputStream = context.contentResolver.openInputStream(uri)
inputStream.use { input ->
val file = File.createTempFile(filename, "0", context.cacheDir)
val output = FileOutputStream(file)
try {
val buffer = ByteArray(4 * 1024) // or other buffer size
var read = input!!.read(buffer)
while (read != -1) {
output.write(buffer, 0, read)
read = input.read(buffer)
}
output.flush()
} finally {
output.close()
return file
}
}
return null
}
private fun ensureRotation(f: File?): File? {
try {
val exif = ExifInterface(f!!.getPath())
val orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL)
var angle = 0
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270
}
if (angle == 0) return f
val mat = Matrix()
mat.postRotate(angle.toFloat())
val options = BitmapFactory.Options()
options.inSampleSize = 2
val bmp = BitmapFactory.decodeStream(FileInputStream(f),
null, options)
val bitmap = Bitmap.createBitmap(bmp!!, 0, 0, bmp.width,
bmp.height, mat, true)
val file = File.createTempFile("rSaved", ".0", context.cacheDir)
val fileOutputStream = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream)
fileOutputStream.close()
return file
} catch (e: IOException) {
Log.w("TAG", "-- Error in setting image")
} catch (oom: OutOfMemoryError) {
Log.w("TAG", "-- OOM Error in setting image")
}
return f
}
} | mit | 36b1478a664cdee5eef9b75796932f92 | 33.286885 | 137 | 0.610952 | 4.806897 | false | false | false | false |
ncoe/rosetta | Remove_vowels_from_a_string/Kotlin/src/main/kotlin/RemoveVowels.kt | 1 | 407 | fun removeVowels(s: String): String {
val re = StringBuilder()
for (c in s) {
if (c != 'A' && c != 'a'
&& c != 'E' && c != 'e'
&& c != 'I' && c != 'i'
&& c != 'O' && c != 'o'
&& c != 'U' && c != 'u') {
re.append(c)
}
}
return re.toString()
}
fun main() {
println(removeVowels("Kotlin Programming Language"))
}
| mit | 82081c492de87c73709d6ee3871dce47 | 22.941176 | 56 | 0.371007 | 3.06015 | false | false | false | false |
kivensolo/UiUsingListView | module-Common/src/main/java/com/kingz/module/common/utils/ktx/SDKVersion.kt | 1 | 2470 | package com.kingz.module.common.utils.ktx
import android.annotation.SuppressLint
import android.os.Build
/**
* author:ZekeWang
* date:2021/1/4
* description:系统版本判断工具类
*/
@SuppressLint("ObsoleteSdkInt")
class SDKVersion {
companion object {
/** >=4.0 14 */
fun hasICS(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH
}
/**
* >= 4.1 16
*
* @return
*/
fun hasJellyBean(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
}
/** >= 4.2 17 */
fun hasJellyBeanMr1(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1
}
/** >= 4.3 18 */
fun hasJellyBeanMr2(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2
}
/** >=4.4 19 */
fun hasKitkat(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
}
/** >=4.4W 20 */
fun hasKitkatW(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH
}
/** >=5.0 21 */
fun afterLOLLIPOP(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
}
/** >=5.1 22 */
fun afterLOLLIPOPMR1(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1
}
/** >=6.0 23 */
fun afterMarshmallow(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
}
/** >=7.0 24 */
fun afterNougat(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
}
/** >=7.1.1 25 */
fun afterNougatMR1(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1
}
/** >=8.0 26 */
fun afterOreo(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
}
/** >=8.1 27 */
fun afterOreoMR1(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1
}
/** >=9.0 28 */
fun afterPie(): Boolean {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.P
}
fun getSDKVersionInt(): Int {
return Build.VERSION.SDK_INT
}
}
} | gpl-2.0 | 5d659b5d3ff729facd8c954d04a5c40d | 25.311828 | 82 | 0.522077 | 3.833856 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/source/online/YamlOnlineSourceMappings.kt | 1 | 5846 | @file:Suppress("UNCHECKED_CAST")
package eu.kanade.tachiyomi.data.source.online
import eu.kanade.tachiyomi.data.database.models.Manga
import okhttp3.FormBody
import okhttp3.RequestBody
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
private fun toMap(map: Any?) = map as? Map<String, Any?>
class YamlSourceNode(uncheckedMap: Map<*, *>) {
val map = toMap(uncheckedMap)!!
val id: String by map
val name: String by map
val host: String by map
val lang: String by map
val client: String?
get() = map["client"] as? String
val popular = PopularNode(toMap(map["popular"])!!)
val latestupdates = toMap(map["latest_updates"])?.let { LatestUpdatesNode(it) }
val search = SearchNode(toMap(map["search"])!!)
val manga = MangaNode(toMap(map["manga"])!!)
val chapters = ChaptersNode(toMap(map["chapters"])!!)
val pages = PagesNode(toMap(map["pages"])!!)
}
interface RequestableNode {
val map: Map<String, Any?>
val url: String
get() = map["url"] as String
val method: String?
get() = map["method"] as? String
val payload: Map<String, String>?
get() = map["payload"] as? Map<String, String>
fun createForm(): RequestBody {
return FormBody.Builder().apply {
payload?.let {
for ((key, value) in it) {
add(key, value)
}
}
}.build()
}
}
class PopularNode(override val map: Map<String, Any?>): RequestableNode {
val manga_css: String by map
val next_url_css: String?
get() = map["next_url_css"] as? String
}
class LatestUpdatesNode(override val map: Map<String, Any?>): RequestableNode {
val manga_css: String by map
val next_url_css: String?
get() = map["next_url_css"] as? String
}
class SearchNode(override val map: Map<String, Any?>): RequestableNode {
val manga_css: String by map
val next_url_css: String?
get() = map["next_url_css"] as? String
}
class MangaNode(private val map: Map<String, Any?>) {
val parts = CacheNode(toMap(map["parts"]) ?: emptyMap())
val artist = toMap(map["artist"])?.let { SelectableNode(it) }
val author = toMap(map["author"])?.let { SelectableNode(it) }
val summary = toMap(map["summary"])?.let { SelectableNode(it) }
val status = toMap(map["status"])?.let { StatusNode(it) }
val genres = toMap(map["genres"])?.let { SelectableNode(it) }
val cover = toMap(map["cover"])?.let { CoverNode(it) }
}
class ChaptersNode(private val map: Map<String, Any?>) {
val chapter_css: String by map
val title: String by map
val date = toMap(toMap(map["date"]))?.let { DateNode(it) }
}
class CacheNode(private val map: Map<String, Any?>) {
fun get(document: Document) = map.mapValues { document.select(it.value as String).first() }
}
open class SelectableNode(private val map: Map<String, Any?>) {
val select: String by map
val from: String?
get() = map["from"] as? String
open val attr: String?
get() = map["attr"] as? String
val capture: String?
get() = map["capture"] as? String
fun process(document: Element, cache: Map<String, Element>): String {
val parent = from?.let { cache[it] } ?: document
val node = parent.select(select).first()
var text = attr?.let { node.attr(it) } ?: node.text()
capture?.let {
text = Regex(it).find(text)?.groupValues?.get(1) ?: text
}
return text
}
}
class StatusNode(private val map: Map<String, Any?>) : SelectableNode(map) {
val complete: String?
get() = map["complete"] as? String
val ongoing: String?
get() = map["ongoing"] as? String
val licensed: String?
get() = map["licensed"] as? String
fun getStatus(document: Element, cache: Map<String, Element>): Int {
val text = process(document, cache)
complete?.let {
if (text.contains(it)) return Manga.COMPLETED
}
ongoing?.let {
if (text.contains(it)) return Manga.ONGOING
}
licensed?.let {
if (text.contains(it)) return Manga.LICENSED
}
return Manga.UNKNOWN
}
}
class CoverNode(private val map: Map<String, Any?>) : SelectableNode(map) {
override val attr: String?
get() = map["attr"] as? String ?: "src"
}
class DateNode(private val map: Map<String, Any?>) : SelectableNode(map) {
val format: String by map
fun getDate(document: Element, cache: Map<String, Element>, formatter: SimpleDateFormat): Date {
val text = process(document, cache)
try {
return formatter.parse(text)
} catch (exception: ParseException) {}
for (i in 0..7) {
(map["day$i"] as? List<String>)?.let {
it.find { it.toRegex().containsMatchIn(text) }?.let {
return Calendar.getInstance().apply { add(Calendar.DATE, -i) }.time
}
}
}
return Date(0)
}
}
class PagesNode(private val map: Map<String, Any?>) {
val pages_regex: String?
get() = map["pages_regex"] as? String
val pages_css: String?
get() = map["pages_css"] as? String
val pages_attr: String?
get() = map["pages_attr"] as? String ?: "value"
val replace: String?
get() = map["url_replace"] as? String
val replacement: String?
get() = map["url_replacement"] as? String
val image_regex: String?
get() = map["image_regex"] as? String
val image_css: String?
get() = map["image_css"] as? String
val image_attr: String
get() = map["image_attr"] as? String ?: "src"
} | gpl-3.0 | 082f39b852cc75a7b1d22b27eb40f58b | 23.987179 | 100 | 0.598358 | 3.740243 | false | false | false | false |
idea4bsd/idea4bsd | plugins/settings-repository/src/autoSync.kt | 3 | 5964 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.settingsRepository
import com.intellij.configurationStore.ComponentStoreImpl
import com.intellij.notification.Notification
import com.intellij.notification.Notifications
import com.intellij.notification.NotificationsAdapter
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ApplicationAdapter
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ShutDownTracker
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier
import java.util.concurrent.Future
internal class AutoSyncManager(private val icsManager: IcsManager) {
private @Volatile var autoSyncFuture: Future<*>? = null
@Volatile var enabled = true
fun waitAutoSync(indicator: ProgressIndicator) {
val autoFuture = autoSyncFuture
if (autoFuture != null) {
if (autoFuture.isDone) {
autoSyncFuture = null
}
else if (autoSyncFuture != null) {
LOG.info("Wait for auto sync future")
indicator.text = "Wait for auto sync completion"
while (!autoFuture.isDone) {
if (indicator.isCanceled) {
return
}
Thread.sleep(5)
}
}
}
}
fun registerListeners(application: Application) {
application.addApplicationListener(object : ApplicationAdapter() {
override fun applicationExiting() {
autoSync(true)
}
})
}
fun registerListeners(project: Project) {
project.messageBus.connect().subscribe(Notifications.TOPIC, object : NotificationsAdapter() {
override fun notify(notification: Notification) {
if (!icsManager.repositoryActive || project.isDisposed) {
return
}
if (when {
notification.groupId == VcsBalloonProblemNotifier.NOTIFICATION_GROUP.displayId -> {
val message = notification.content
message.startsWith("VCS Update Finished") ||
message == VcsBundle.message("message.text.file.is.up.to.date") ||
message == VcsBundle.message("message.text.all.files.are.up.to.date")
}
notification.groupId == VcsNotifier.NOTIFICATION_GROUP_ID.displayId && notification.title == "Push successful" -> true
else -> false
}) {
autoSync()
}
}
})
}
fun autoSync(onAppExit: Boolean = false, force: Boolean = false) {
if (!enabled || !icsManager.repositoryActive || (!force && !icsManager.settings.autoSync)) {
return
}
autoSyncFuture?.let {
if (!it.isDone) {
return
}
}
val app = ApplicationManagerEx.getApplicationEx() as ApplicationImpl
if (onAppExit) {
sync(app, onAppExit)
return
}
else if (app.isDisposeInProgress) {
// will be handled by applicationExiting listener
return
}
autoSyncFuture = app.executeOnPooledThread {
try {
// to ensure that repository will not be in uncompleted state and changes will be pushed
ShutDownTracker.getInstance().registerStopperThread(Thread.currentThread())
sync(app, onAppExit)
}
finally {
autoSyncFuture = null
ShutDownTracker.getInstance().unregisterStopperThread(Thread.currentThread())
}
}
}
private fun sync(app: ApplicationImpl, onAppExit: Boolean) {
catchAndLog {
icsManager.runInAutoCommitDisabledMode {
val repositoryManager = icsManager.repositoryManager
if (!repositoryManager.canCommit()) {
LOG.warn("Auto sync skipped: repository is not committable")
return@runInAutoCommitDisabledMode
}
// on app exit fetch and push only if there are commits to push
if (onAppExit && !repositoryManager.commit() && repositoryManager.getAheadCommitsCount() == 0) {
return@runInAutoCommitDisabledMode
}
val updater = repositoryManager.fetch()
// we merge in EDT non-modal to ensure that new settings will be properly applied
app.invokeAndWait({
catchAndLog {
val updateResult = updater.merge()
if (!onAppExit &&
!app.isDisposeInProgress &&
updateResult != null &&
updateStoragesFromStreamProvider(app.stateStore as ComponentStoreImpl, updateResult, app.messageBus)) {
// force to avoid saveAll & confirmation
app.exit(true, true, true)
}
}
}, ModalityState.NON_MODAL)
if (!updater.definitelySkipPush) {
repositoryManager.push()
}
}
}
}
}
inline internal fun catchAndLog(asWarning: Boolean = false, runnable: () -> Unit) {
try {
runnable()
}
catch (e: ProcessCanceledException) { }
catch (e: Throwable) {
if (asWarning || e is AuthenticationException || e is NoRemoteRepositoryException) {
LOG.warn(e)
}
else {
LOG.error(e)
}
}
} | apache-2.0 | b19e52d6317e559c20a47283f1be7056 | 32.324022 | 128 | 0.674715 | 4.840909 | false | false | false | false |
JetBrains/kotlin-native | build-tools/src/main/kotlin/org/jetbrains/kotlin/testing/native/GitDownloadTask.kt | 1 | 6189 | /*
* Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.testing.native
import org.gradle.api.DefaultTask
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.options.Option
import org.gradle.process.ExecResult
import org.gradle.process.ExecSpec
import org.jetbrains.kotlin.isNotEmpty
import java.io.File
import java.net.URL
import java.util.*
import javax.inject.Inject
/**
* Clones the given revision of the given Git repository to the given directory.
*/
@Suppress("UnstableApiUsage")
open class GitDownloadTask @Inject constructor(
val repositoryProvider: Provider<URL>,
val revisionProvider: Provider<String>,
val outputDirectoryProvider: Provider<File>
) : DefaultTask() {
private val repository: URL
get() = repositoryProvider.get()
private val revision: String
get() = revisionProvider.get()
private val outputDirectory: File
get() = outputDirectoryProvider.get()
@Option(option = "refresh",
description = "Fetch and checkout the revision even if the output directory already contains it. " +
"All changes in the output directory will be overwritten")
val refresh: Property<Boolean> = project.objects.property(Boolean::class.java).apply {
set(false)
}
private val upToDateChecker = UpToDateChecker()
init {
outputs.upToDateWhen { upToDateChecker.isUpToDate() }
}
private fun git(
vararg args: String,
ignoreExitValue: Boolean = false,
execConfiguration: ExecSpec.() -> Unit = {}
): ExecResult =
project.exec {
it.executable = "git"
it.args(*args)
it.isIgnoreExitValue = ignoreExitValue
it.execConfiguration()
}
private fun tryCloneBranch(): Boolean {
val execResult = git(
"clone", repository.toString(),
outputDirectory.absolutePath,
"--depth", "1",
"--branch", revision,
ignoreExitValue = true
)
return execResult.exitValue == 0
}
private fun fetchByHash() {
git("init", outputDirectory.absolutePath)
git("fetch", repository.toString(), "--depth", "1", revision) {
workingDir(outputDirectory)
}
git("reset", "--hard", revision) {
workingDir(outputDirectory)
}
}
@TaskAction
fun clone() {
// Gradle ignores outputs.upToDateWhen { ... } and reruns a task if the classpath of the task was changed
// So we have to perform the up-to-date check manually one more time in the task action.
if (upToDateChecker.isUpToDate()) {
logger.info("Skip cloning to avoid rewriting possible debug changes in ${outputDirectory.absolutePath}.")
return
}
project.delete {
it.delete(outputDirectory)
}
if (!tryCloneBranch()) {
logger.info("Cannot use the revision '$revision' to clone the repository. Trying to use init && fetch instead.")
fetchByHash()
}
// Store info about used revision for the manual up-to-date check.
upToDateChecker.storeRevisionInfo()
// Delete the .git directory of the cloned repo to avoid adding it to IDEA's VCS roots.
outputDirectory.resolve(".git").deleteRecursively()
}
/**
* This class performs manual UP-TO-DATE checking.
*
* We want to be able to edit downloaded sources for debug purposes. Thus this task should not rewrite changes in
* the output directory.
*
* Gradle does allow us to provide a custom logic to determine if task outputs are UP-TO-DATE or not (see
* Task.outputs.upToDateWhen). But Gradle still reruns a task if its classpath was changed. This may lead
* to rewriting our manual debug changes in downloaded sources if there are some changes in the
* `build-tools` project.
*
* So we have to manually check up-to-dateness in upToDateWhen and as a first step of the task action.
*/
private inner class UpToDateChecker() {
private val revisionInfoFile: File
get() = outputDirectory.resolve(".revision")
/**
* The download task should be executed in the following cases:
*
* - The output directory doesn't exist or is empty;
* - Repository or revision was changed since the last execution;
* - A user forced rerunning this tasks manually (see [GitDownloadTask.refresh]).
*
* In all other cases we consider the task UP-TO-DATE.
*/
fun isUpToDate(): Boolean {
return !refresh.get() &&
outputDirectory.let { it.exists() && project.fileTree(it).isNotEmpty } &&
noRevisionChanges()
}
private fun noRevisionChanges(): Boolean =
revisionInfoFile.exists() && loadRevisionInfo() == RevisionInfo(repository, revision)
fun storeRevisionInfo() {
val properties = Properties()
properties["repository"] = repository.toString()
properties["revision"] = revision
revisionInfoFile.bufferedWriter().use {
properties.store(it, null)
}
}
private fun loadRevisionInfo(): RevisionInfo? {
return try {
val properties = Properties()
revisionInfoFile.bufferedReader().use {
properties.load(it)
}
RevisionInfo(properties.getProperty("repository"), properties.getProperty("revision"))
} catch (_ : Exception) {
null
}
}
}
private data class RevisionInfo(val repository: String, val revision: String) {
constructor(repository: URL, revision: String): this(repository.toString(), revision)
}
}
| apache-2.0 | 033b6a2d242258b29fb35686fce1be23 | 34.774566 | 124 | 0.62094 | 4.89249 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/misc/extension/recyclerview/BindingAdapter.kt | 1 | 1744 | package taiwan.no1.app.ssfm.misc.extension.recyclerview
import android.databinding.BindingAdapter
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
/**
* @author jieyi
* @since 10/1/17
*/
@BindingAdapter("android:layoutManager",
"android:adapter",
"android:itemDecoration",
requireAll = false)
fun RecyclerView.setAdapter(layoutManager: RecyclerView.LayoutManager?,
adapter: RecyclerView.Adapter<*>?,
itemDecoration: RecyclerView.ItemDecoration?) {
layoutManager?.let { this.layoutManager = it }
adapter?.let { this.adapter = it }
itemDecoration?.let { addItemDecoration(it) }
}
// OPTIMIZE(jieyi): 10/2/17 Help want! I might instead an anonymous variable method for loading more.
interface RecyclerViewScrollCallback {
fun loadMoreEvent(recyclerView: RecyclerView, total: Int)
}
@BindingAdapter("android:loadMore")
fun RecyclerView.setOnScrollListener(callback: RecyclerViewScrollCallback?) =
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
(recyclerView.layoutManager as LinearLayoutManager).let {
val visibleItems = it.childCount
val totalItems = it.itemCount
val pastVisibleItems = it.findFirstVisibleItemPosition()
if (visibleItems + pastVisibleItems >= totalItems) {
callback?.loadMoreEvent(recyclerView, totalItems)
}
}
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
}
})
| apache-2.0 | 01087cda639f658584e0e3c5bd204da7 | 38.636364 | 101 | 0.668005 | 5.237237 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/processor/UpsertionMethodProcessor.kt | 3 | 3779 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.processor
import androidx.room.Upsert
import androidx.room.compiler.processing.XMethodElement
import androidx.room.compiler.processing.XType
import androidx.room.vo.UpsertionMethod
import androidx.room.vo.findFieldByColumnName
class UpsertionMethodProcessor(
baseContext: Context,
val containing: XType,
val executableElement: XMethodElement
) {
val context = baseContext.fork(executableElement)
fun process(): UpsertionMethod {
val delegate = ShortcutMethodProcessor(context, containing, executableElement)
val annotation = delegate.extractAnnotation(
Upsert::class,
ProcessorErrors.MISSING_UPSERT_ANNOTATION
)
val returnType = delegate.extractReturnType()
context.checker.notUnbound(
returnType, executableElement,
ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_UPSERTION_METHODS
)
val (entities, params) = delegate.extractParams(
targetEntityType = annotation?.getAsType("entity"),
missingParamError = ProcessorErrors.UPSERTION_DOES_NOT_HAVE_ANY_PARAMETERS_TO_UPSERT,
onValidatePartialEntity = { entity, pojo ->
val missingPrimaryKeys = entity.primaryKey.fields.any {
pojo.findFieldByColumnName(it.columnName) == null
}
context.checker.check(
entity.primaryKey.autoGenerateId || !missingPrimaryKeys,
executableElement,
ProcessorErrors.missingPrimaryKeysInPartialEntityForUpsert(
partialEntityName = pojo.typeName.toString(context.codeLanguage),
primaryKeyNames = entity.primaryKey.fields.columnNames
)
)
// Verify all non null columns without a default value are in the POJO otherwise
// the UPSERT will fail with a NOT NULL constraint.
val missingRequiredFields = (entity.fields - entity.primaryKey.fields).filter {
it.nonNull && it.defaultValue == null &&
pojo.findFieldByColumnName(it.columnName) == null
}
context.checker.check(
missingRequiredFields.isEmpty(),
executableElement,
ProcessorErrors.missingRequiredColumnsInPartialEntity(
partialEntityName = pojo.typeName.toString(context.codeLanguage),
missingColumnNames = missingRequiredFields.map { it.columnName }
)
)
}
)
val methodBinder = delegate.findUpsertMethodBinder(returnType, params)
context.checker.check(
methodBinder.adapter != null,
executableElement,
ProcessorErrors.CANNOT_FIND_UPSERT_RESULT_ADAPTER
)
return UpsertionMethod(
element = executableElement,
returnType = returnType,
entities = entities,
parameters = params,
methodBinder = methodBinder
)
}
} | apache-2.0 | de2b3fd220de79a4326d23094e36e87e | 38.789474 | 97 | 0.636412 | 5.315049 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/objectExpression/object.kt | 4 | 246 | <warning descr="SSR">fun a() = object {
val c = 1
}</warning>
class A() {
<warning descr="SSR">private fun b() = object {
val c = 1
}</warning>
<warning descr="SSR">fun c() = object {
val c = 1
}</warning>
} | apache-2.0 | f15f4c5f7de3f4ef42fe4c19f7c49baa | 16.642857 | 51 | 0.504065 | 3.28 | false | false | false | false |
jwren/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/LibraryLicense.kt | 1 | 6044 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build
import com.intellij.util.containers.ContainerUtil
/**
* Describes a library which is included into distribution of an IntelliJ-based IDE. This information is used to show list of Third-party
* software in About popup and on the product download page.
*/
data class LibraryLicense(
/**
* Presentable full name of the library. If {@code null} {@link #libraryName} will be used instead.
*/
val name: String? = null,
/**
* URL of the library site, may be {@code null} if the library doesn't have a site
*/
val url: String? = null,
/**
* Version of the library. If {@link #libraryName} points to a Maven library version is taken from the library configuration so it must
* not be specified explicitly.
*/
val version: String? = null,
/**
* Name of the library in IDEA Project Configuration (for unnamed module libraries it's a name of its JAR file). May be {@code null} if
* the library isn't explicitly added to dependencies of a module, in that case {@link #attachedTo} must be specified instead. This property
* is used to automatically generate list of libraries used in a particular project.
*/
val libraryName: String? = null,
/**
* Names of additional libraries in IDEA Project Configuration which are associated with the given library. It makes sense to use this
* property only for unnamed module library consisting of several JAR files, but even in such cases consider merging such JARs into a single
* module library and giving it a name.
*/
val additionalLibraryNames: List<String> = emptyList(),
/**
* Specifies name of the module in IDEA Project configuration the library is implicitly attached to. It makes sense to use this property
* only for libraries which cannot be added to a module dependencies as a regular dependency (e.g. if it isn't a Java library). For regular
* cases specify {@link #libraryName} instead.
*/
val attachedTo: String? = null,
/**
* Set to {@code true} if this entry describes license for a transitive dependency included into the library specified by {@link #libraryName}
*/
val transitiveDependency: Boolean = false,
/**
* Type of a license (e.g. {@code 'Apache 2.0'})
*/
val license: String? = null,
/**
* URL of a page on the library site (or a generic site) containing the license text, may be {@code null} for standard licenses
* (see {@link #PREDEFINED_LICENSE_URLS}) or if there is no such page.
*/
val licenseUrl: String? = null,
) {
init {
require(name != null || libraryName != null) { "name or libraryName must be set" }
}
companion object {
private const val APACHE_LICENSE_URL = "https://www.apache.org/licenses/LICENSE-2.0"
private val PREDEFINED_LICENSE_URLS: Map<String, String> = mapOf("Apache 2.0" to APACHE_LICENSE_URL)
@JvmStatic
val JETBRAINS_OWN = "JetBrains"
/**
* Denotes version of library built from custom revision
*/
const val CUSTOM_REVISION = "custom revision"
/**
* Use this method only for JetBrains's own libraries which are available as part of IntelliJ-based IDEs only so there is no way to
* give link to their sites. For other libraries please fill all necessary fields of {@link LibraryLicense} instead of using this method.
*/
@JvmStatic
fun jetbrainsLibrary(libraryName: String): LibraryLicense =
LibraryLicense(
libraryName = libraryName,
license = JETBRAINS_OWN,
)
}
fun getLibraryNames(): List<String> =
ContainerUtil.createMaybeSingletonList(libraryName) + additionalLibraryNames
val presentableName: String
get() = name ?: libraryName!!
fun getLibraryLicenseUrl(): String? = licenseUrl ?: PREDEFINED_LICENSE_URLS[license]
fun apache(): LibraryLicense {
require(license == null) { "No need to specify 'license' for Apache 2.0" }
require(licenseUrl?.contains("apache.org/licenses") != true) { "No need to specify default 'licenseUrl' for Apache 2.0" }
return copy(
license = "Apache 2.0",
licenseUrl = licenseUrl ?: APACHE_LICENSE_URL,
)
}
fun simplifiedBsd(): LibraryLicense {
require(license == null) { "No need to specify 'license' for Simplified BSD" }
require(licenseUrl?.contains("opensource.org/licenses") != true) { "No need to specify default 'licenseUrl' for Simplified BSD" }
return copy(
license = "BSD 2-Clause",
licenseUrl = licenseUrl ?: "https://opensource.org/licenses/BSD-2-Clause",
)
}
fun newBsd(): LibraryLicense {
require(license == null) { "No need to specify 'license' for New BSD" }
require(licenseUrl?.contains("opensource.org/licenses") != true) { "No need to specify default 'licenseUrl' for New BSD" }
return copy(
license = "BSD 3-Clause",
licenseUrl = licenseUrl ?: "https://opensource.org/licenses/BSD-3-Clause",
)
}
fun mit(): LibraryLicense {
require(license == null) { "No need to specify 'license' for MIT" }
require(licenseUrl?.contains("opensource.org/licenses") != true) { "No need to specify default 'licenseUrl' for MIT" }
return copy(
license = "MIT",
licenseUrl = licenseUrl ?: "https://opensource.org/licenses/MIT",
)
}
fun eplV1(): LibraryLicense = epl(1)
fun eplV2(): LibraryLicense = epl(2)
private fun epl(v: Int): LibraryLicense {
require(v == 1 || v == 2) { "Version must be either 1 or 2 for Eclipse Public License" }
require(license == null) { "No need to specify 'license' for Eclipse Public License" }
require(licenseUrl?.contains("eclipse.org") != true) { "No need to specify default 'licenseUrl' for Eclipse Public License" }
return copy(
license = "Eclipse Public License $v.0",
licenseUrl = licenseUrl ?: (if (v == 1) "https://www.eclipse.org/org/documents/epl-v10.html" else "https://www.eclipse.org/legal/epl-2.0")
)
}
}
| apache-2.0 | eec63a22898b8d264ece2a75b8b44370 | 40.115646 | 144 | 0.688617 | 4.208914 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/inspections/AbstractHighLevelApiBasedInspection.kt | 1 | 3789 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.inspections
import com.intellij.codeInspection.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession
import org.jetbrains.kotlin.idea.frontend.api.analyzeWithReadAction
import org.jetbrains.kotlin.idea.frontend.api.computation.ApplicableComputation
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.findExistingEditor
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtVisitorVoid
abstract class AbstractHighLevelApiBasedInspection<ELEMENT : KtElement, DATA : Any>(
val elementType: Class<ELEMENT>
) : AbstractKotlinInspection() {
final override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) =
object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
super.visitKtElement(element)
if (!elementType.isInstance(element) || element.textLength == 0) return
@Suppress("UNCHECKED_CAST")
visitTargetElement(element as ELEMENT, holder, isOnTheFly)
}
}
protected fun visitTargetElement(element: ELEMENT, holder: ProblemsHolder, isOnTheFly: Boolean) {
if (!isApplicableByPsi(element)) return
if (analyzeWithReadAction(element) { analyzeAndGetData(element) == null }) return
holder.registerProblemWithoutOfflineInformation(
element,
inspectionText(element),
isOnTheFly,
inspectionHighlightType(element),
inspectionHighlightRangeInElement(element),
LocalFix(fixText(element))
)
}
open fun inspectionHighlightRangeInElement(element: ELEMENT): TextRange? = null
open fun inspectionHighlightType(element: ELEMENT): ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING
abstract fun inspectionText(element: ELEMENT): String
abstract val defaultFixText: String
open fun fixText(element: ELEMENT) = defaultFixText
abstract fun isApplicableByPsi(element: ELEMENT): Boolean
abstract fun KtAnalysisSession.analyzeAndGetData(element: ELEMENT): DATA?
abstract fun applyTo(element: ELEMENT, data: DATA, project: Project = element.project, editor: Editor? = null)
private inner class LocalFix(@Nls val text: String) : LocalQuickFix {
override fun startInWriteAction() = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
@Suppress("UNCHECKED_CAST")
val element = descriptor.psiElement as ELEMENT
if (!isApplicableByPsi(element)) return
ApplicationManager.getApplication().executeOnPooledThread {
val computation = ApplicableComputation(
computation = { analyzeAndGetData(it) },
application = { element, data ->
applyTo(element, data, project, element.findExistingEditor())
},
psiChecker = ::isApplicableByPsi,
computationTitle = fixText(element)
)
computation.computeAndApply(element)
}
}
override fun getFamilyName() = defaultFixText
override fun getName() = text
}
} | apache-2.0 | 033aad005feaad8ef14d789d2be1dc36 | 40.195652 | 124 | 0.702032 | 5.405136 | false | false | false | false |
Bluexin/mek-re | src/main/java/be/bluexin/mekre/blocks/MachineBlock.kt | 1 | 3695 | package be.bluexin.mekre.blocks
import be.bluexin.mekre.MachineType
import be.bluexin.mekre.blocks.states.BSMachine
import be.bluexin.mekre.containers.OperatingTEContainer
import be.bluexin.mekre.tiles.EnergeticTE
import be.bluexin.mekre.tiles.OperatingTE
import com.teamwizardry.librarianlib.common.container.GuiHandler
import com.teamwizardry.librarianlib.common.util.getTileEntitySafely
import net.minecraft.block.Block
import net.minecraft.block.material.Material
import net.minecraft.block.properties.PropertyEnum
import net.minecraft.block.state.IBlockState
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.world.IBlockAccess
import net.minecraft.world.World
import net.minecraftforge.fml.relauncher.ReflectionHelper
/**
* Part of mek_re by Bluexin, released under GNU GPLv3.
*
* @author Bluexin
*/
class MachineBlock(val subID: Int) : MVariantBlockContainer<MachineType>("machineBlock$subID", Material.IRON, hardness = 3.5F, resistance = 16F) {
// TODO: when implementing the TEs, the facing will have to be propagated
// About TE sync: https://gist.github.com/williewillus/7945c4959b1142ece9828706b527c5a4
// https://github.com/Growlith1223/ArsMagica2/commit/cc3e11e14983abfe00889892ce26cbf442d940e8
// https://github.com/TehNut/LendingLibrary/blob/1.11/src/main/java/tehnut/lib/mc/tile/TileBase.java
init {
ReflectionHelper.setPrivateValue(Block::class.java, this, this.createBlockState(), "blockState", "field_176227_L")
this.defaultState = blockState.baseState
}
override val variants: Array<MachineType> = MachineType.values().filter { it.ordinal >= subID * 16 && it.ordinal < (subID + 1) * 16 }.toTypedArray()
override val variantsAll: Array<MachineType>
get() = MachineType.values()
override fun createBlockState() = BSMachine(this)
override fun onBlockPlacedBy(worldIn: World, pos: BlockPos, state: IBlockState, placer: EntityLivingBase, stack: ItemStack) {
(worldIn.getTileEntity(pos) as EnergeticTE).facing = placer.horizontalFacing.opposite
}
override fun getStateFromMeta(meta: Int) = MachineBlocksHolder[subID][variants[meta % 16]]
override lateinit var typeProperty: PropertyEnum<MachineType>
override fun isOpaqueCube(state: IBlockState) = state.getValue(this.typeProperty).opaque
override fun createTileEntity(world: World, state: IBlockState) = state.getValue(this.typeProperty).te!!.invoke()
override fun hasTileEntity(state: IBlockState) = state.getValue(this.typeProperty).te != null
override fun getActualState(state: IBlockState, worldIn: IBlockAccess, pos: BlockPos): IBlockState? {
val te = worldIn.getTileEntitySafely(pos) as? OperatingTE
return super.getActualState(state, worldIn, pos)
.withProperty(BSMachine.activeProperty, te?.operates ?: false)
.withProperty(BSMachine.facingProperty, te?.facing ?: EnumFacing.NORTH)
}
override fun onBlockActivated(worldIn: World, pos: BlockPos, state: IBlockState, playerIn: EntityPlayer, hand: EnumHand, heldItem: ItemStack?, side: EnumFacing, hitX: Float, hitY: Float, hitZ: Float): Boolean {
return if (hasTileEntity(state)) {
GuiHandler.open(OperatingTEContainer.NAME, playerIn, pos)
true
} else false
}
}
object MachineBlocksHolder : IManyBlocksHolder<MachineBlock, MachineType> {
override val blocks: Array<MachineBlock> = (0..MachineType.values().size / 16).map(::MachineBlock).toTypedArray()
}
| gpl-3.0 | 6b5449fb1f16e0f3a001c83e6fe5f6ef | 46.371795 | 214 | 0.763735 | 3.832988 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequest.kt | 7 | 13607 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api
import com.fasterxml.jackson.databind.JsonNode
import com.intellij.collaboration.api.dto.GraphQLRequestDTO
import com.intellij.collaboration.api.dto.GraphQLResponseDTO
import com.intellij.util.ThrowableConvertor
import org.jetbrains.plugins.github.api.data.GithubResponsePage
import org.jetbrains.plugins.github.api.data.GithubSearchResult
import org.jetbrains.plugins.github.api.data.graphql.GHGQLError
import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException
import org.jetbrains.plugins.github.exceptions.GithubConfusingException
import org.jetbrains.plugins.github.exceptions.GithubJsonException
import java.io.IOException
/**
* Represents an API request with strictly defined response type
*/
sealed class GithubApiRequest<out T>(val url: String) {
var operationName: String? = null
abstract val acceptMimeType: String?
protected val headers = mutableMapOf<String, String>()
val additionalHeaders: Map<String, String>
get() = headers
@Throws(IOException::class)
abstract fun extractResult(response: GithubApiResponse): T
fun withOperationName(name: String): GithubApiRequest<T> {
operationName = name
return this
}
abstract class Get<T> @JvmOverloads constructor(url: String,
override val acceptMimeType: String? = null) : GithubApiRequest<T>(url) {
abstract class Optional<T> @JvmOverloads constructor(url: String,
acceptMimeType: String? = null) : Get<T?>(url, acceptMimeType) {
companion object {
inline fun <reified T> json(url: String, acceptMimeType: String? = null): Optional<T> =
Json(url, T::class.java, acceptMimeType)
}
open class Json<T>(url: String, private val clazz: Class<T>, acceptMimeType: String? = GithubApiContentHelper.V3_JSON_MIME_TYPE)
: Optional<T>(url, acceptMimeType) {
override fun extractResult(response: GithubApiResponse): T = parseJsonObject(response, clazz)
}
}
companion object {
inline fun <reified T> json(url: String, acceptMimeType: String? = null): Get<T> =
Json(url, T::class.java, acceptMimeType)
inline fun <reified T> jsonPage(url: String, acceptMimeType: String? = null): Get<GithubResponsePage<T>> =
JsonPage(url, T::class.java, acceptMimeType)
inline fun <reified T> jsonSearchPage(url: String, acceptMimeType: String? = null): Get<GithubResponsePage<T>> =
JsonSearchPage(url, T::class.java, acceptMimeType)
}
open class Json<T>(url: String, private val clazz: Class<T>, acceptMimeType: String? = GithubApiContentHelper.V3_JSON_MIME_TYPE)
: Get<T>(url, acceptMimeType) {
override fun extractResult(response: GithubApiResponse): T = parseJsonObject(response, clazz)
}
open class JsonList<T>(url: String, private val clazz: Class<T>, acceptMimeType: String? = GithubApiContentHelper.V3_JSON_MIME_TYPE)
: Get<List<T>>(url, acceptMimeType) {
override fun extractResult(response: GithubApiResponse): List<T> = parseJsonList(response, clazz)
}
open class JsonPage<T>(url: String, private val clazz: Class<T>, acceptMimeType: String? = GithubApiContentHelper.V3_JSON_MIME_TYPE)
: Get<GithubResponsePage<T>>(url, acceptMimeType) {
override fun extractResult(response: GithubApiResponse): GithubResponsePage<T> {
return GithubResponsePage.parseFromHeader(parseJsonList(response, clazz),
response.findHeader(GithubResponsePage.HEADER_NAME))
}
}
open class JsonSearchPage<T>(url: String,
private val clazz: Class<T>,
acceptMimeType: String? = GithubApiContentHelper.V3_JSON_MIME_TYPE)
: Get<GithubResponsePage<T>>(url, acceptMimeType) {
override fun extractResult(response: GithubApiResponse): GithubResponsePage<T> {
return GithubResponsePage.parseFromHeader(parseJsonSearchPage(response, clazz).items,
response.findHeader(GithubResponsePage.HEADER_NAME))
}
}
}
abstract class Head<T> @JvmOverloads constructor(url: String,
override val acceptMimeType: String? = null) : GithubApiRequest<T>(url)
abstract class WithBody<out T>(url: String) : GithubApiRequest<T>(url) {
abstract val body: String?
abstract val bodyMimeType: String
}
abstract class Post<out T> @JvmOverloads constructor(override val bodyMimeType: String,
url: String,
override var acceptMimeType: String? = null) : GithubApiRequest.WithBody<T>(url) {
companion object {
inline fun <reified T> json(url: String, body: Any, acceptMimeType: String? = null): Post<T> =
Json(url, body, T::class.java, acceptMimeType)
}
open class Json<T>(url: String, private val bodyObject: Any, private val clazz: Class<T>,
acceptMimeType: String? = GithubApiContentHelper.V3_JSON_MIME_TYPE)
: Post<T>(GithubApiContentHelper.JSON_MIME_TYPE, url, acceptMimeType) {
override val body: String
get() = GithubApiContentHelper.toJson(bodyObject)
override fun extractResult(response: GithubApiResponse): T = parseJsonObject(response, clazz)
}
abstract class GQLQuery<out T>(url: String,
private val queryName: String,
private val variablesObject: Any)
: Post<T>(GithubApiContentHelper.JSON_MIME_TYPE, url) {
override val body: String
get() {
val query = GHGQLQueryLoader.loadQuery(queryName)
val request = GraphQLRequestDTO(query, variablesObject)
return GithubApiContentHelper.toJson(request, true)
}
protected fun throwException(errors: List<GHGQLError>): Nothing {
if (errors.any { it.type.equals("INSUFFICIENT_SCOPES", true) })
throw GithubAuthenticationException("Access token has not been granted the required scopes.")
if (errors.size == 1) throw GithubConfusingException(errors.single().toString())
throw GithubConfusingException(errors.toString())
}
class Parsed<out T>(url: String,
requestFilePath: String,
variablesObject: Any,
private val clazz: Class<T>)
: GQLQuery<T>(url, requestFilePath, variablesObject) {
override fun extractResult(response: GithubApiResponse): T {
val result: GraphQLResponseDTO<out T, GHGQLError> = parseGQLResponse(response, clazz)
val data = result.data
if (data != null) return data
val errors = result.errors
if (errors == null) error("Undefined request state - both result and errors are null")
else throwException(errors)
}
}
class TraversedParsed<out T : Any>(url: String,
requestFilePath: String,
variablesObject: Any,
private val clazz: Class<out T>,
private vararg val pathFromData: String)
: GQLQuery<T>(url, requestFilePath, variablesObject) {
override fun extractResult(response: GithubApiResponse): T {
return parseResponse(response, clazz, pathFromData)
?: throw GithubJsonException("Non-nullable entity is null or entity path is invalid")
}
}
class OptionalTraversedParsed<T>(url: String,
requestFilePath: String,
variablesObject: Any,
private val clazz: Class<T>,
private vararg val pathFromData: String)
: GQLQuery<T?>(url, requestFilePath, variablesObject) {
override fun extractResult(response: GithubApiResponse): T? {
return parseResponse(response, clazz, pathFromData)
}
}
internal fun <T> parseResponse(response: GithubApiResponse,
clazz: Class<T>,
pathFromData: Array<out String>): T? {
val result: GraphQLResponseDTO<out JsonNode, GHGQLError> = parseGQLResponse(response, JsonNode::class.java)
val data = result.data
if (data != null && !data.isNull) {
var node: JsonNode = data
for (path in pathFromData) {
node = node[path] ?: break
}
if (!node.isNull) return GithubApiContentHelper.fromJson(node.toString(), clazz, true)
}
val errors = result.errors
if (errors == null) return null
else throwException(errors)
}
}
}
abstract class Put<T> @JvmOverloads constructor(override val bodyMimeType: String,
url: String,
override val acceptMimeType: String? = null) : GithubApiRequest.WithBody<T>(url) {
companion object {
inline fun <reified T> json(url: String, body: Any? = null): Put<T> = Json(url, body, T::class.java)
inline fun <reified T> jsonList(url: String, body: Any): Put<List<T>> = JsonList(url, body, T::class.java)
}
open class Json<T>(url: String, private val bodyObject: Any?, private val clazz: Class<T>)
: Put<T>(GithubApiContentHelper.JSON_MIME_TYPE, url, GithubApiContentHelper.V3_JSON_MIME_TYPE) {
init {
if (bodyObject == null) headers["Content-Length"] = "0"
}
override val body: String?
get() = bodyObject?.let { GithubApiContentHelper.toJson(it) }
override fun extractResult(response: GithubApiResponse): T = parseJsonObject(response, clazz)
}
open class JsonList<T>(url: String, private val bodyObject: Any?, private val clazz: Class<T>)
: Put<List<T>>(GithubApiContentHelper.JSON_MIME_TYPE, url, GithubApiContentHelper.V3_JSON_MIME_TYPE) {
init {
if (bodyObject == null) headers["Content-Length"] = "0"
}
override val body: String?
get() = bodyObject?.let { GithubApiContentHelper.toJson(it) }
override fun extractResult(response: GithubApiResponse): List<T> = parseJsonList(response, clazz)
}
}
abstract class Patch<T> @JvmOverloads constructor(override val bodyMimeType: String,
url: String,
override var acceptMimeType: String? = null) : Post<T>(bodyMimeType,
url,
acceptMimeType) {
companion object {
inline fun <reified T> json(url: String, body: Any): Post<T> = Json(url, body, T::class.java)
}
open class Json<T>(url: String, bodyObject: Any, clazz: Class<T>) : Post.Json<T>(url, bodyObject, clazz)
}
abstract class Delete<T> @JvmOverloads constructor(override val bodyMimeType: String,
url: String,
override val acceptMimeType: String? = null) : GithubApiRequest.WithBody<T>(url) {
companion object {
inline fun <reified T> json(url: String, body: Any? = null): Delete<T> = Json(url, body, T::class.java)
}
open class Json<T>(url: String, private val bodyObject: Any? = null, private val clazz: Class<T>)
: Delete<T>(GithubApiContentHelper.JSON_MIME_TYPE, url, GithubApiContentHelper.V3_JSON_MIME_TYPE) {
init {
if (bodyObject == null) headers["Content-Length"] = "0"
}
override val body: String?
get() = bodyObject?.let { GithubApiContentHelper.toJson(it) }
override fun extractResult(response: GithubApiResponse): T = parseJsonObject(response, clazz)
}
}
companion object {
private fun <T> parseJsonObject(response: GithubApiResponse, clazz: Class<T>): T {
return response.readBody(ThrowableConvertor { GithubApiContentHelper.readJsonObject(it, clazz) })
}
private fun <T> parseJsonList(response: GithubApiResponse, clazz: Class<T>): List<T> {
return response.readBody(ThrowableConvertor { GithubApiContentHelper.readJsonList(it, clazz) })
}
private fun <T> parseJsonSearchPage(response: GithubApiResponse, clazz: Class<T>): GithubSearchResult<T> {
return response.readBody(ThrowableConvertor {
@Suppress("UNCHECKED_CAST")
GithubApiContentHelper.readJsonObject(it, GithubSearchResult::class.java, clazz) as GithubSearchResult<T>
})
}
private fun <T> parseGQLResponse(response: GithubApiResponse, dataClass: Class<out T>): GraphQLResponseDTO<out T, GHGQLError> {
return response.readBody(ThrowableConvertor {
@Suppress("UNCHECKED_CAST")
GithubApiContentHelper.readJsonObject(it, GraphQLResponseDTO::class.java, dataClass, GHGQLError::class.java,
gqlNaming = true) as GraphQLResponseDTO<T, GHGQLError>
})
}
}
} | apache-2.0 | 92460225a8d65af36a68a87f79a4c59b | 45.762887 | 140 | 0.622547 | 4.786141 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/GradleScriptNotificationProvider.kt | 1 | 11125 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleJava.scripting
import com.intellij.icons.AllIcons
import com.intellij.ide.actions.ImportModuleAction
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.externalSystem.service.project.wizard.AbstractExternalProjectImportProvider
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.projectImport.ProjectImportProvider
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotificationProvider
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.configuration.GRADLE_SYSTEM_ID
import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle
import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle
import org.jetbrains.kotlin.idea.gradleJava.scripting.legacy.GradleStandaloneScriptActionsManager
import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsLocator
import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsLocator.NotificationKind.*
import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager
import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.Imported
import java.io.File
import java.util.function.Function
import javax.swing.JComponent
internal class GradleScriptNotificationProvider : EditorNotificationProvider {
override fun collectNotificationData(
project: Project,
file: VirtualFile,
): Function<in FileEditor, out JComponent?> {
if (!isGradleKotlinScript(file)
|| !FileTypeRegistry.getInstance().isFileOfType(file, KotlinFileType.INSTANCE)
) {
return EditorNotificationProvider.CONST_NULL
}
val standaloneScriptActions = GradleStandaloneScriptActionsManager.getInstance(project)
val rootsManager = GradleBuildRootsManager.getInstance(project)
val scriptUnderRoot = rootsManager?.findScriptBuildRoot(file) ?: return EditorNotificationProvider.CONST_NULL
// todo: this actions will be usefull only when gradle fix https://github.com/gradle/gradle/issues/12640
fun EditorNotificationPanel.showActionsToFixNotEvaluated() {
// suggest to reimport project if something changed after import
val build: Imported = scriptUnderRoot.nearest as? Imported ?: return
val importTs = build.data.importTs
if (!build.areRelatedFilesChangedBefore(file, importTs)) {
createActionLabel(getConfigurationsActionText()) {
rootsManager.updateStandaloneScripts {
runPartialGradleImport(project, build)
}
}
}
// suggest to choose new gradle project
createActionLabel(KotlinIdeaGradleBundle.message("notification.outsideAnything.linkAction")) {
linkProject(project, scriptUnderRoot)
}
}
return Function { fileEditor ->
when (scriptUnderRoot.notificationKind) {
dontCare -> null
legacy -> {
val actions = standaloneScriptActions[file]
if (actions == null) null
else {
object : EditorNotificationPanel(fileEditor) {
val contextHelp = KotlinIdeaGradleBundle.message("notification.gradle.legacy.firstLoad.info")
init {
if (actions.isFirstLoad) {
text(KotlinIdeaGradleBundle.message("notification.gradle.legacy.firstLoad"))
toolTipText = contextHelp
} else {
text(KotlinIdeaGradleBundle.message("notification.text.script.configuration.has.been.changed"))
}
createActionLabel(KotlinIdeaCoreBundle.message("notification.action.text.load.script.configuration")) {
actions.reload()
}
createActionLabel(KotlinIdeaCoreBundle.message("notification.action.text.enable.auto.reload")) {
actions.enableAutoReload()
}
if (actions.isFirstLoad) {
contextHelp(contextHelp)
}
}
}
}
}
legacyOutside -> EditorNotificationPanel(fileEditor).apply {
text(KotlinIdeaGradleBundle.message("notification.gradle.legacy.outsideProject"))
createActionLabel(KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.addAsStandaloneAction")) {
rootsManager.updateStandaloneScripts {
addStandaloneScript(file.path)
}
}
contextHelp(KotlinIdeaGradleBundle.message("notification.gradle.legacy.outsideProject.addToStandaloneHelp"))
}
outsideAnything -> EditorNotificationPanel(fileEditor).apply {
text(KotlinIdeaGradleBundle.message("notification.outsideAnything.text"))
createActionLabel(KotlinIdeaGradleBundle.message("notification.outsideAnything.linkAction")) {
linkProject(project, scriptUnderRoot)
}
}
wasNotImportedAfterCreation -> EditorNotificationPanel(fileEditor).apply {
text(configurationsAreMissingRequestNeeded())
createActionLabel(getConfigurationsActionText()) {
val root = scriptUnderRoot.nearest
if (root != null) {
runPartialGradleImport(project, root)
}
}
val help = configurationsAreMissingRequestNeededHelp()
contextHelp(help)
}
notEvaluatedInLastImport -> EditorNotificationPanel(fileEditor).apply {
text(configurationsAreMissingAfterRequest())
// todo: this actions will be usefull only when gradle fix https://github.com/gradle/gradle/issues/12640
// showActionsToFixNotEvaluated()
createActionLabel(KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.addAsStandaloneAction")) {
rootsManager.updateStandaloneScripts {
addStandaloneScript(file.path)
}
}
contextHelp(KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.info"))
}
standalone, standaloneLegacy -> EditorNotificationPanel(fileEditor).apply {
val actions = standaloneScriptActions[file]
if (actions != null) {
text(
KotlinIdeaGradleBundle.message("notification.standalone.text") +
". " +
KotlinIdeaGradleBundle.message("notification.text.script.configuration.has.been.changed")
)
createActionLabel(KotlinIdeaCoreBundle.message("notification.action.text.load.script.configuration")) {
actions.reload()
}
createActionLabel(KotlinIdeaCoreBundle.message("notification.action.text.enable.auto.reload")) {
actions.enableAutoReload()
}
} else {
text(KotlinIdeaGradleBundle.message("notification.standalone.text"))
}
createActionLabel(KotlinIdeaGradleBundle.message("notification.standalone.disableScriptAction")) {
rootsManager.updateStandaloneScripts {
removeStandaloneScript(file.path)
}
}
if (scriptUnderRoot.notificationKind == standaloneLegacy) {
contextHelp(KotlinIdeaGradleBundle.message("notification.gradle.legacy.standalone.info"))
} else {
contextHelp(KotlinIdeaGradleBundle.message("notification.standalone.info"))
}
}
}
}
}
private fun linkProject(
project: Project,
scriptUnderRoot: GradleBuildRootsLocator.ScriptUnderRoot,
) {
val settingsFile: File? = tryFindGradleSettings(scriptUnderRoot)
// from AttachExternalProjectAction
val manager = ExternalSystemApiUtil.getManager(GRADLE_SYSTEM_ID) ?: return
val provider = ProjectImportProvider.PROJECT_IMPORT_PROVIDER.extensions.find {
it is AbstractExternalProjectImportProvider && GRADLE_SYSTEM_ID == it.externalSystemId
} ?: return
val projectImportProviders = arrayOf(provider)
if (settingsFile != null) {
PropertiesComponent.getInstance().setValue(
"last.imported.location",
settingsFile.canonicalPath
)
}
val wizard = ImportModuleAction.selectFileAndCreateWizard(
project,
null,
manager.externalProjectDescriptor,
projectImportProviders
) ?: return
if (wizard.stepCount <= 0 || wizard.showAndGet()) {
ImportModuleAction.createFromWizard(project, wizard)
}
}
private fun tryFindGradleSettings(scriptUnderRoot: GradleBuildRootsLocator.ScriptUnderRoot): File? {
try {
var parent = File(scriptUnderRoot.filePath).canonicalFile.parentFile
while (parent.isDirectory) {
listOf("settings.gradle", "settings.gradle.kts").forEach {
val settings = parent.resolve(it)
if (settings.isFile) {
return settings
}
}
parent = parent.parentFile
}
} catch (t: Throwable) {
// ignore
}
return null
}
private fun EditorNotificationPanel.contextHelp(@Nls text: String) {
val helpIcon = createActionLabel("") {}
helpIcon.icon = AllIcons.General.ContextHelp
helpIcon.setUseIconAsLink(true)
helpIcon.toolTipText = text
}
}
| apache-2.0 | 782bc49adb4acfd5968b08c8437cc09c | 46.542735 | 135 | 0.601258 | 6.335421 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/check/HelpCheck.kt | 1 | 3103 | package com.cognifide.gradle.aem.common.instance.check
import com.cognifide.gradle.aem.common.instance.InstanceSync
import com.cognifide.gradle.aem.common.instance.service.osgi.Bundle
import com.cognifide.gradle.common.CommonException
import java.util.concurrent.TimeUnit
class HelpCheck(group: CheckGroup) : DefaultCheck(group) {
/**
* After longer inactivity time, try helping instance going back to healthy state.
*/
val stateTime = aem.obj.long { convention(TimeUnit.MINUTES.toMillis(8)) }
/**
* Bundle with these states are considered for forcing start.
*/
val bundleStartStates = aem.obj.strings {
convention(listOf(
Bundle.STATE_RESOLVED,
Bundle.STATE_INSTALLED
))
}
/**
* Repeat bundle starting few times (brute-forcing).
*/
var bundleStartRetry = common.retry { afterSquaredSecond(3) }
/**
* Time to wait after starting bundles.
*/
val bundleStartDelay = aem.obj.long { convention(TimeUnit.SECONDS.toMillis(3)) }
override fun check() {
if (progress.stateTime >= stateTime.get()) {
progress.stateData.getOrPut(STATE_HELPED) {
help()
true
}
}
}
private fun help() = sync {
startBundles()
}
private fun InstanceSync.startBundles() {
logger.info("Trying to start OSGi bundles on $instance")
var startable = listOf<Bundle>()
try {
bundleStartRetry.withCountdown<Unit, CommonException>("start bundles on '${instance.name}'") {
startable = startableBundles()
if (startable.isNotEmpty()) {
startBundles(startable)
startable = startableBundles()
if (startable.isNotEmpty()) {
throw HelpException("Starting bundles to be repeated on $instance!")
}
}
}
} catch (e: HelpException) {
logger.warn("Bundles (${startable.size}) cannot be started automatically on $instance:\n" +
startable.joinToString("\n"))
}
}
private fun ignoredBundles() = group.checks.filterIsInstance<BundlesCheck>()
.firstOrNull()?.symbolicNamesIgnored?.get()
?: listOf<String>()
private fun InstanceSync.startableBundles(): List<Bundle> = osgi.bundles.asSequence()
.filter { !ignoredBundles().contains(it.symbolicName) }
.filter { !it.fragment && bundleStartStates.get().contains(it.state) }
.toList()
private fun InstanceSync.startBundles(bundles: List<Bundle>) {
common.parallel.poolEach(bundles) { startBundle(it) }
Thread.sleep(bundleStartDelay.get())
}
private fun InstanceSync.startBundle(bundle: Bundle) = try {
osgi.startBundle(bundle.symbolicName)
} catch (e: CommonException) {
logger.debug("Cannot start bundle on $instance!", e)
}
companion object {
private const val STATE_HELPED = "helped"
}
}
| apache-2.0 | 69038812c5ce989731f7fe1592197b94 | 32.728261 | 106 | 0.608443 | 4.445559 | false | false | false | false |
AMARJITVS/NoteDirector | app/src/main/kotlin/com/amar/notesapp/helpers/Constants.kt | 1 | 2939 | package com.amar.NoteDirector.helpers
// shared preferences
val SORT_ORDER = "sort_order"
val DIRECTORY_SORT_ORDER = "directory_sort_order"
val SORT_FOLDER_PREFIX = "sort_folder_"
val SHOW_HIDDEN_MEDIA = "show_hidden_media"
val TEMPORARILY_SHOW_HIDDEN = "temporarily_show_hidden"
val IS_THIRD_PARTY_INTENT = "is_third_party_intent"
val AUTOPLAY_VIDEOS = "autoplay_videos"
val LOOP_VIDEOS = "loop_videos"
val ANIMATE_GIFS = "animate_gifs"
val MAX_BRIGHTNESS = "max_brightness"
val CROP_THUMBNAILS = "crop_thumbnails"
val SCREEN_ROTATION = "screen_rotation"
val DISPLAY_FILE_NAMES = "display_file_names"
val DARK_BACKGROUND = "dark_background"
val PINNED_FOLDERS = "pinned_folders"
val FILTER_MEDIA = "filter_media"
val DIR_COLUMN_CNT = "dir_column_cnt"
val DIR_LANDSCAPE_COLUMN_CNT = "dir_landscape_column_cnt"
val DIR_HORIZONTAL_COLUMN_CNT = "dir_horizontal_column_cnt"
val DIR_LANDSCAPE_HORIZONTAL_COLUMN_CNT = "dir_landscape_horizontal_column_cnt"
val MEDIA_COLUMN_CNT = "media_column_cnt"
val MEDIA_LANDSCAPE_COLUMN_CNT = "media_landscape_column_cnt"
val MEDIA_HORIZONTAL_COLUMN_CNT = "media_horizontal_column_cnt"
val MEDIA_LANDSCAPE_HORIZONTAL_COLUMN_CNT = "media_landscape_horizontal_column_cnt"
val SHOW_ALL = "show_all" // display images and videos from all folders together
val SAVE_FOLDER_PREFIX = "folder2_"
val HIDE_FOLDER_TOOLTIP_SHOWN = "hide_folder_tooltip_shown"
val EXCLUDED_FOLDERS = "excluded_folders"
val INCLUDED_FOLDERS = "included_folders"
val ALBUM_COVERS = "album_covers"
val SCROLL_HORIZONTALLY = "scroll_horizontally"
val HIDE_SYSTEM_UI = "hide_system_ui"
val REPLACE_SHARE_WITH_ROTATE = "replace_share_with_rotate"
val DELETE_EMPTY_FOLDERS = "delete_empty_folders"
val ALLOW_VIDEO_GESTURES = "allow_video_gestures"
val TEMP_FOLDER_PATH = "temp_folder_path"
// slideshow
val SLIDESHOW_INTERVAL = "slideshow_interval"
val SLIDESHOW_INCLUDE_PHOTOS = "slideshow_include_photos"
val SLIDESHOW_INCLUDE_VIDEOS = "slideshow_include_videos"
val SLIDESHOW_INCLUDE_GIFS = "slideshow_include_gifs"
val SLIDESHOW_RANDOM_ORDER = "slideshow_random_order"
val SLIDESHOW_USE_FADE = "slideshow_use_fade"
val SLIDESHOW_MOVE_BACKWARDS = "slideshow_move_backwards"
val SLIDESHOW_LOOP = "loop_slideshow"
val SLIDESHOW_DEFAULT_INTERVAL = 5
val SLIDESHOW_SCROLL_DURATION = 500L
val NOMEDIA = ".nomedia"
val DIRECTORY = "directory"
val MEDIUM = "medium"
val GET_IMAGE_INTENT = "get_image_intent"
val GET_VIDEO_INTENT = "get_video_intent"
val GET_ANY_INTENT = "get_any_intent"
val SET_WALLPAPER_INTENT = "set_wallpaper_intent"
val DIRECTORIES = "directories2"
val IS_VIEW_INTENT = "is_view_intent"
val REQUEST_EDIT_IMAGE = 1
val REQUEST_SET_AS = 2
// rotations
val ROTATE_BY_SYSTEM_SETTING = 0
val ROTATE_BY_DEVICE_ROTATION = 1
val ROTATE_BY_ASPECT_RATIO = 2
val ORIENT_PORTRAIT = 0
val ORIENT_LANDSCAPE_LEFT = 1
val ORIENT_LANDSCAPE_RIGHT = 2
// filter media
val IMAGES = 1
val VIDEOS = 2
val GIFS = 4
| apache-2.0 | 700d915fe7f55d73e3b47513ec85e40a | 36.202532 | 106 | 0.758421 | 3.194565 | false | false | false | false |
hsz/idea-gitignore | src/main/kotlin/mobi/hsz/idea/gitignore/util/Utils.kt | 1 | 5245 | // Copyright 2000-2021 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 mobi.hsz.idea.gitignore.util
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.colors.EditorColors
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import mobi.hsz.idea.gitignore.IgnoreBundle
import mobi.hsz.idea.gitignore.IgnoreBundle.obtainLanguage
import mobi.hsz.idea.gitignore.file.type.IgnoreFileType
/**
* [Utils] class that contains various methods.
*/
object Utils {
/**
* Gets relative path of given @{link VirtualFile} and root directory.
*
* @param directory root directory
* @param file file to get it's path
* @return relative path
*/
fun getRelativePath(directory: VirtualFile, file: VirtualFile) =
VfsUtilCore.getRelativePath(file, directory, '/')?.let {
it + ('/'.takeIf { file.isDirectory } ?: "")
}
/**
* Finds [PsiFile] for the given [VirtualFile] instance. If file is outside current project,
* it's required to create new [PsiFile] manually.
*
* @param project current project
* @param virtualFile to handle
* @return [PsiFile] instance
*/
fun getPsiFile(project: Project, virtualFile: VirtualFile) =
PsiManager.getInstance(project).run {
findFile(virtualFile) ?: findViewProvider(virtualFile)?.let {
obtainLanguage(virtualFile)?.createFile(it)
}
}
/**
* Opens given file in editor.
*
* @param project current project
* @param file file to open
*/
fun openFile(project: Project, file: PsiFile) {
FileEditorManager.getInstance(project).openFile(file.virtualFile, true)
}
/**
* Checks if given directory is VCS directory.
*
* @param directory to check
* @return given file is VCS directory
*/
fun isVcsDirectory(directory: VirtualFile) = when {
!directory.isDirectory -> false
else -> IgnoreBundle.VCS_LANGUAGES.find {
directory.name == it.vcsDirectory && IgnoreBundle.ENABLED_LANGUAGES[it.fileType] ?: false
} != null
}
/**
* Gets list of words for given [String] excluding special characters.
*
* @param filter input string
* @return list of words without special characters
*/
fun getWords(filter: String) = filter.toLowerCase().split("\\W+").filter(String::isNotEmpty)
/**
* Checks if lists are equal.
*
* @param l1 first list
* @param l2 second list
* @return lists are equal
*/
fun equalLists(l1: List<*>, l2: List<*>) = l1.size == l2.size && l1.containsAll(l2) && l2.containsAll(l1)
/**
* Searches for the module in the project that contains given file.
*
* @param file file
* @param project project
* @return module containing passed file or null
*/
fun getModuleForFile(file: VirtualFile, project: Project): Module? =
ModuleManager.getInstance(project).modules.find { it.moduleContentScope.contains(file) }
fun getModuleRootForFile(file: VirtualFile, project: Project) = getModuleForFile(file, project)?.let { module ->
ModuleRootManager.getInstance(module).contentRoots.first()?.takeIf { it.isDirectory }
}
/**
* Checks if file is in project directory.
*
* @param file file
* @param project project
* @return file is under directory
*/
fun isInProject(file: VirtualFile, project: Project) =
getModuleForFile(file, project) != null || StringUtil.startsWith(file.url, "temp://")
/**
* Creates and configures template preview editor.
*
* @param document virtual editor document
* @param project current project
* @return editor
*/
fun createPreviewEditor(document: Document, project: Project?, isViewer: Boolean): Editor =
EditorFactory.getInstance().createEditor(
document,
project,
IgnoreFileType.INSTANCE,
isViewer
).apply {
(this as EditorEx).setCaretEnabled(!isViewer)
settings.apply {
isLineNumbersShown = false
additionalColumnsCount = 1
additionalLinesCount = 0
isRightMarginShown = false
isFoldingOutlineShown = false
isLineMarkerAreaShown = false
isIndentGuidesShown = false
isVirtualSpace = false
isWheelFontChangeEnabled = false
}
colorsScheme.setColor(EditorColors.CARET_ROW_COLOR, null)
}
}
| mit | c4edddc783ef4893384c078b90dd4273 | 34.439189 | 140 | 0.656435 | 4.588801 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/service/ResourceDepManageService.kt | 1 | 58742 | package org.evomaster.core.problem.rest.service
import com.google.inject.Inject
import org.evomaster.client.java.controller.api.dto.TestResultsDto
import org.evomaster.client.java.controller.api.dto.database.execution.ExecutionDto
import org.evomaster.core.EMConfig
import org.evomaster.core.Lazy
import org.evomaster.core.database.DbAction
import org.evomaster.core.database.DbActionUtils
import org.evomaster.core.database.schema.Table
import org.evomaster.core.problem.rest.HttpVerb
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.problem.rest.RestIndividual
import org.evomaster.core.problem.rest.param.BodyParam
import org.evomaster.core.problem.rest.resource.ExcludedResourceNode
import org.evomaster.core.problem.rest.resource.ResourceCluster
import org.evomaster.core.problem.rest.resource.RestResourceCalls
import org.evomaster.core.problem.rest.resource.dependency.MutualResourcesRelations
import org.evomaster.core.problem.rest.resource.dependency.ResourceRelatedToResources
import org.evomaster.core.problem.rest.resource.dependency.ResourceRelatedToTable
import org.evomaster.core.problem.rest.resource.dependency.SelfResourcesRelation
import org.evomaster.core.problem.util.inference.SimpleDeriveResourceBinding
import org.evomaster.core.problem.util.inference.model.ParamGeneBindMap
import org.evomaster.core.problem.util.StringSimilarityComparator
import org.evomaster.core.search.ActionFilter
import org.evomaster.core.search.ActionFilter.*
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.service.AdaptiveParameterControl
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.EvaluatedMutation
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.nio.file.Files
import java.nio.file.Paths
import kotlin.math.max
/**
* this class is used to manage dependency among resources
*/
class ResourceDepManageService {
@Inject
private lateinit var rm: ResourceManageService
@Inject
private lateinit var randomness: Randomness
@Inject
private lateinit var config: EMConfig
@Inject
private lateinit var apc: AdaptiveParameterControl
companion object{
private const val DERIVE_RELATED = 1.0
val log: Logger = LoggerFactory.getLogger(ResourceDepManageService::class.java)
}
/**
* key is either a path of one resource, or a list of paths of resources
* value is a list of related to resources
*/
private val dependencies: MutableMap<String, MutableList<ResourceRelatedToResources>> = mutableMapOf()
/**
* key is a path of an resource
* value is a set of resources that is not related to the key, i.e., the key does not rely on
*/
private val uncorrelated: MutableMap<String, MutableSet<String>> = mutableMapOf()
//private val inference = SimpleDeriveResourceBinding()
/************************ manage relationship between resource and tables ***********************************/
/**
* update relationship between resource and tables.
* Note that the entry point is on the rest fitness.
*/
fun updateResourceTables(restIndividual: RestIndividual, dto: TestResultsDto) {
val tables = rm.getTableInfo()
/*
TODO how to decide to remove relationship between resource and table
*/
val addedMap = mutableMapOf<String, MutableSet<String>>()
val removedMap = mutableMapOf<String, MutableSet<String>>()
restIndividual.seeMainExecutableActions().forEachIndexed { index, action ->
if (config.doesApplyNameMatching) updateParamInfo(action as RestCallAction, tables)
// size of extraHeuristics might be less than size of action due to failure of handling rest action
if (index < dto.extraHeuristics.size) {
val dbDto = dto.extraHeuristics[index].databaseExecutionDto
if (dbDto != null)
updateResourceToTable(action as RestCallAction, dbDto, tables, addedMap, removedMap)
}
}
if (addedMap.isNotEmpty() || removedMap.isNotEmpty())
updateDependencyOnceResourceTableUpdate(addedMap, removedMap)
}
private fun updateParamInfo(action: RestCallAction, tables: Map<String, Table>) {
val r = rm.getResourceNodeFromCluster(action.path.toString())
// skip resource if it is ExcludedResourceNode
if (r is ExcludedResourceNode) return
val additionalInfo = r.updateAdditionalParams(action)
if (!additionalInfo.isNullOrEmpty()) {
SimpleDeriveResourceBinding.deriveParamsToTable(additionalInfo, r, allTables = tables)
}
}
/**
* TODO remove false-derived dependencies based on feedback from evomaster driver
*/
private fun updateDependencyOnceResourceTableUpdate(addedMap: MutableMap<String, MutableSet<String>>, removedMap: MutableMap<String, MutableSet<String>>) {
val groupTable = addedMap.flatMap { it.value }.toHashSet()
groupTable.forEach { table ->
val newRelatedResource = addedMap.filter { it.value.contains(table) }.keys
val previousResourcesWithTable = dependencies.values.flatMap { l -> l.filter { d->d is MutualResourcesRelations && d.referredTables.contains(table) }.flatMap { it.targets }}.toHashSet()
var find = false
dependencies.values.forEach { rlist ->
rlist.forEach { mu ->
if (mu is MutualResourcesRelations && mu.targets.containsAll(newRelatedResource.plus(previousResourcesWithTable).toHashSet())) {
mu.referredTables.add(table)
find = true
}
}
}
if (!find) {
//update existing dependency with new related resources if it refers to the table
val updateToAddNewResource = mutableMapOf<String, MutableList<MutualResourcesRelations>>()
dependencies.forEach { (k, d) ->
d.filter { r -> r is MutualResourcesRelations && r.referredTables.contains(table) }.forEach { r->
updateToAddNewResource.getOrPut(k){ mutableListOf()}.add(r as MutualResourcesRelations)
}
}
updateToAddNewResource.forEach { (t, u) ->
dependencies.getValue(t).removeAll(u)
u.forEach { m->
val newTargets = m.targets.plus(newRelatedResource).toHashSet()
val newTables = m.referredTables.plus(table).toHashSet()
val newMut = MutualResourcesRelations(newTargets.toList(), DERIVE_RELATED, newTables)
dependencies.getValue(t).add(newMut)
}
}
//add new dependency for new RelatedResources with table
newRelatedResource.forEach {nr->
dependencies.getOrPut(nr) { mutableListOf() }
val append = dependencies.getValue(nr).filter { it is MutualResourcesRelations && newRelatedResource.plus(previousResourcesWithTable).toHashSet().containsAll(it.targets) }
if (append.isNotEmpty()){
append.forEach { a->
dependencies.getValue(nr).remove(a)
val newTargets = a.targets.plus(newRelatedResource).plus(previousResourcesWithTable).toHashSet()
val newTables = (a as MutualResourcesRelations).referredTables.plus(table).toHashSet()
val newMut = MutualResourcesRelations(newTargets.toList(), DERIVE_RELATED, newTables)
dependencies.getValue(nr).add(newMut)
}
}else{
val newMut = MutualResourcesRelations(newRelatedResource.plus(previousResourcesWithTable).toHashSet().toList(), DERIVE_RELATED, mutableSetOf(table))
dependencies.getValue(nr).add(newMut)
}
}
}
}
}
private fun updateResourceToTable(action: RestCallAction, updated: Map<String, MutableSet<String>>, matchedWithVerb: Boolean, tables: Map<String, Table>,
addedMap: MutableMap<String, MutableSet<String>>, removedMap: MutableMap<String, MutableSet<String>>) {
val ar = rm.getResourceNodeFromCluster(action.path.toString())
val rToTable = ar.resourceToTable
if (updated.isNotEmpty() && matchedWithVerb) {
val derivedTables = rToTable.getTablesInDerivedMap()
updated.forEach { (t, u) ->
if (derivedTables.any { it.equals(t, ignoreCase = true) }) {
if (action.parameters.isNotEmpty() && u.isNotEmpty() && u.none { it == "*" }) {
action.parameters.forEach { p ->
val paramId = ar.getParamId(action.parameters, p)
ar.resourceToTable.paramToTable[paramId]?.let { paramToTable ->
paramToTable.getRelatedColumn(t)?.apply {
paramToTable.confirmedColumn.addAll(this.intersect(u))
}
}
}
}
} else {
val matchedInfo = ResourceRelatedToTable.generateFromDtoMatchedInfo(t.toLowerCase())
ar.resourceToTable.derivedMap.put(t, mutableListOf(matchedInfo))
action.parameters.forEach { p ->
val paramId = ar.getParamId(action.parameters, p)
val paramInfo = ar.paramsInfo[paramId].run {
this ?: ar.updateAdditionalParam(action, p).also {
SimpleDeriveResourceBinding.deriveParamsToTable(paramId, it, ar, tables)
}
}
// ?:throw IllegalArgumentException("cannot find the param Id $paramId in the rest resource ${referResource.getName()}")
val hasMatchedParam = SimpleDeriveResourceBinding.deriveRelatedTable(ar, paramId, paramInfo, mutableSetOf(t), p is BodyParam, -1, alltables = tables)
ar.resourceToTable.paramToTable[paramId]?.let { paramToTable ->
paramToTable.getRelatedColumn(t)?.apply {
paramToTable.confirmedColumn.addAll(this.intersect(u.filter { it != "*" }))
}
}
}
addedMap.getOrPut(ar.getName()) { mutableSetOf() }.add(t)
}
rToTable.confirmedSet.getOrPut(t) { true }
rToTable.confirmedSet[t] = true
}
} else {
updated.keys.forEach { t ->
rToTable.confirmedSet.getOrPut(t) { false }
}
}
}
private fun updateResourceToTable(action: RestCallAction, dto: ExecutionDto, tables: Map<String, Table>,
addedMap: MutableMap<String, MutableSet<String>>, removedMap: MutableMap<String, MutableSet<String>>) {
dto.insertedData.filter { u -> tables.any { it.key.toLowerCase() == u.key } }.let { added ->
updateResourceToTable(action, added, (action.verb == HttpVerb.POST || action.verb == HttpVerb.PUT), tables, addedMap, removedMap)
}
dto.updatedData.filter { u -> tables.any { it.key.toLowerCase() == u.key } }.let { updated ->
updateResourceToTable(action, updated, (action.verb == HttpVerb.PATCH || action.verb == HttpVerb.PUT), tables, addedMap, removedMap)
}
dto.deletedData.filter { u -> tables.any { it.key.toLowerCase() == u } }.let { del ->
updateResourceToTable(action, del.map { Pair(it, mutableSetOf<String>()) }.toMap(), (action.verb == HttpVerb.PATCH || action.verb == HttpVerb.PUT), tables, addedMap, removedMap)
}
dto.queriedData.filter { u -> tables.any { it.key.toLowerCase() == u.key } }.let { get ->
updateResourceToTable(action, get, true, tables, addedMap, removedMap)
}
rm.getResourceNodeFromCluster(action.path.toString()).resourceToTable.updateActionRelatedToTable(action.verb.toString(), dto, tables.keys)
}
/************************ derive dependency using parser ***********************************/
/**
* init dependencies between [resourceCluster] and [tables]
*/
fun initDependencyBasedOnDerivedTables(resourceCluster: ResourceCluster) {
resourceCluster.getTableInfo().keys.forEach { table ->
val mutualResources = resourceCluster.getCluster().values.filter { r -> r.getDerivedTables().any { e -> e.equals(table, ignoreCase = true) } }.map { it.getName() }.toList()
if (mutualResources.isNotEmpty() && mutualResources.size > 1) {
val mutualRelation = MutualResourcesRelations(mutualResources, StringSimilarityComparator.SimilarityThreshold, mutableSetOf(table))
mutualResources.forEach { res ->
val relations = dependencies.getOrPut(res) { mutableListOf() }
relations.find { r -> r is MutualResourcesRelations && r.targets.containsAll(mutualRelation.targets) }.let {
if (it == null)
relations.add(mutualRelation)
else
(it as MutualResourcesRelations).referredTables.add(table.toLowerCase())
}
}
}
}
}
/**
* to derive dependency based on schema, i.e., description of each action if exists.
*
* If a description of a Post action includes some tokens (the token must be some "object") that is related to other rest action,
* we create a "possible dependency" between the actions.
*/
fun deriveDependencyBasedOnSchema(resourceCluster: ResourceCluster) {
resourceCluster.getCluster().values
.filter { it.actions.filter { it.verb == HttpVerb.POST }.isNotEmpty() }
.forEach { r ->
/*
TODO Man should only apply on POST Action? how about others?
*/
val post = r.actions.first { it.verb == HttpVerb.POST }
post.tokens.forEach { _, u ->
resourceCluster.getCluster().values.forEach { or ->
if (or != r) {
or.actions
.flatMap { it.tokens.values.filter { t -> t.fromDefinition && t.isDirect && t.isType } }
.filter { ot ->
StringSimilarityComparator.isSimilar(u.getKey(), ot.getKey())
}.let {
if (it.isNotEmpty()) {
val addInfo = it.map { t -> t.getKey() }.joinToString(";")
updateDependencies(or.getName(), mutableListOf(r.getName()), addInfo, StringSimilarityComparator.SimilarityThreshold)
updateDependencies(r.getName(), mutableListOf(or.getName()), addInfo, StringSimilarityComparator.SimilarityThreshold)
}
}
}
}
}
}
}
/************************ utility ***********************************/
private fun compare(actionName: String, eviA: EvaluatedIndividual<RestIndividual>, eviB: EvaluatedIndividual<RestIndividual>): Int {
val actionAs = mutableListOf<Int>()
val actionBs = mutableListOf<Int>()
eviA.individual.seeAllActions().forEachIndexed { index, action ->
if (action.getName() == actionName)
actionAs.add(index)
}
eviB.individual.seeAllActions().forEachIndexed { index, action ->
if (action.getName() == actionName)
actionBs.add(index)
}
return compare(actionAs, eviA, actionBs, eviB)
}
/**
* is the performance of [actionA] better than the performance [actionB]?
*/
private fun compare(actionA: Int, eviA: EvaluatedIndividual<RestIndividual>, actionB: Int, eviB: EvaluatedIndividual<RestIndividual>): Int {
return compare(mutableListOf(actionA), eviA, mutableListOf(actionB), eviB)
}
private fun compare(actionA: MutableList<Int>, eviA: EvaluatedIndividual<RestIndividual>, actionB: MutableList<Int>, eviB: EvaluatedIndividual<RestIndividual>): Int {
val alistHeuristics = eviA.fitness.getViewOfData().filter { actionA.contains(it.value.actionIndex) }
val blistHeuristics = eviB.fitness.getViewOfData().filter { actionB.contains(it.value.actionIndex) }
//whether actionA reach more
if (alistHeuristics.size > blistHeuristics.size) return 1
else if (alistHeuristics.size < blistHeuristics.size) return -1
//whether actionA reach new
if (alistHeuristics.filter { !blistHeuristics.containsKey(it.key) }.isNotEmpty()) return 1
else if (blistHeuristics.filter { !alistHeuristics.containsKey(it.key) }.isNotEmpty()) return -1
val targets = alistHeuristics.keys.plus(blistHeuristics.keys).toHashSet()
targets.forEach { t ->
val ta = alistHeuristics[t]
val tb = blistHeuristics[t]
if (ta != null && tb != null) {
if (ta.distance > tb.distance)
return 1
else if (ta.distance < tb.distance)
return -1
}
}
return 0
}
/**
* update dependencies based on derived info
* [additionalInfo] is structure mutator in this context
*/
private fun updateDependencies(key: String, target: MutableList<String>, additionalInfo: String, probability: Double = DERIVE_RELATED) {
val relation = if (target.size == 1 && target[0] == key) SelfResourcesRelation(key, probability, additionalInfo)
else ResourceRelatedToResources(listOf(key), target, probability, info = additionalInfo)
updateDependencies(relation, additionalInfo)
}
private fun updateDependencies(relation: ResourceRelatedToResources, additionalInfo: String) {
val found = dependencies.getOrPut(relation.originalKey()) { mutableListOf() }.find { it.targets.containsAll(relation.targets) }
if (found == null) dependencies[relation.originalKey()]!!.add(relation)
else {
/*
TODO Man a strategy to manipulate the probability
*/
found.probability = max(found.probability, relation.probability)
if (found.additionalInfo.isBlank())
found.additionalInfo = additionalInfo
else if (!found.additionalInfo.contains(additionalInfo))
found.additionalInfo += ";$additionalInfo"
}
}
/**
* return all calls of [ind] which are related to [call] with a probability that is more than [minProbability] and not more than [maxProbability]
*/
private fun findDependentResources(ind: RestIndividual, call: RestResourceCalls, minProbability: Double = 0.0, maxProbability: Double = 1.0): MutableList<RestResourceCalls> {
return ind.getResourceCalls().filter { other ->
(other != call) && dependencies[call.getResourceNodeKey()]?.any { r -> r.targets.contains(other.getResourceNodeKey()) && r.probability >= minProbability && r.probability <= maxProbability } ?:false
}.toMutableList()
}
private fun findNonDependentResources(ind: RestIndividual, call: RestResourceCalls): MutableList<RestResourceCalls> {
return ind.getResourceCalls().filter { other ->
(other != call) && uncorrelated[call.getResourceNodeKey()]?.contains(other.getResourceNodeKey()) ?: false
}.toMutableList()
}
/**
* [call] is related to any resource which exists in [ind] with a probability that is more than [minProbability] and not more than [maxProbability]
*/
private fun existsDependentResources(ind: RestIndividual, call: RestResourceCalls, minProbability: Double = 0.0, maxProbability: Double = 1.0): Boolean {
return ind.getResourceCalls().any { other ->
(other != call) && dependencies[call.getResourceNodeKey()]?.any { r -> r.targets.contains(other.getResourceNodeKey()) && r.probability >= minProbability && r.probability <= maxProbability }?:false
}
}
private fun isNonDepResources(ind: RestIndividual, call: RestResourceCalls): Boolean {
return ind.getResourceCalls().find { other ->
(other != call) && uncorrelated[other.getResourceNodeKey()]?.contains(call.getResourceNodeKey()) ?: false
} != null
}
/************************ detect dependency based on fitness ***********************************/
/**
* detect possible dependencies by comparing a mutated (i.e., swap) individual with its previous regarding fitness
*/
private fun detectAfterSwap(previous: EvaluatedIndividual<RestIndividual>, current: EvaluatedIndividual<RestIndividual>, isBetter: EvaluatedMutation) {
val seqPre = previous.individual.getResourceCalls()
val seqCur = current.individual.getResourceCalls()
/*
For instance, ABCDEFG, if we swap B and F, become AFCDEBG, then check FCDE (do not include B!).
if F is worse, F may rely on {C, D, E, B}
if C is worse, C rely on B; else if C is better, C rely on F; else C may not rely on B and F
there is another case regarding duplicated resources calls (i.e., same resource and same actions) in a test,
for instance, ABCDB*B**EF, swap B and F, become AFCDB*B**EB, in this case,
B* probability become better, B** is same, B probability become worse
*/
/**
* collect elements is not in the same position
*/
val swapsloc = mutableListOf<Int>()
seqCur.forEachIndexed { index, restResourceCalls ->
if (restResourceCalls.getResolvedKey() != seqPre[index].getResolvedKey())
swapsloc.add(index)
}
if (swapsloc.size != 2) throw IllegalArgumentException("detect wrong mutator!")
val swapF = seqCur.getOrNull(swapsloc[0])
?: throw IllegalArgumentException("detect wrong mutator!")
val swapB = seqCur.getOrNull(swapsloc[1])
?: throw IllegalArgumentException("detect wrong mutator!")
if (isBetter != EvaluatedMutation.EQUAL_WITH) {
val locOfF = swapsloc[0]
val distance = swapF.seeActionSize(ActionFilter.NO_SQL) - swapB.seeActionSize(ActionFilter.NO_SQL)
//check F
val middles = seqCur.subList(swapsloc[0] + 1, swapsloc[1] + 1).map { it.getResourceNodeKey() }
if (compare(swapsloc[0], current, swapsloc[1], previous) != 0) {
middles.forEach {
updateDependencies(swapF.getResourceNodeKey(), mutableListOf(it), RestResourceStructureMutator.MutationType.SWAP.toString(), (1.0 / middles.size))
}
} else {
uncorrelated.getOrPut(swapF.getResourceNodeKey()) { mutableSetOf() }.apply {
addAll(middles.toHashSet())
}
}
//check FCDE
var actionIndex = seqCur.mapIndexed { index, restResourceCalls ->
if (index <= locOfF) restResourceCalls.seeActionSize(ActionFilter.NO_SQL)
else 0
}.sum()
((locOfF + 1) until swapsloc[1]).forEach { indexOfCalls ->
var isAnyChange = false
var changeDegree = 0
seqCur[indexOfCalls].seeActions(NO_SQL).forEach { curAction ->
val actionA = actionIndex - distance
val compareResult = swapF.seeActions(NO_SQL).plus(swapB.seeActions(NO_SQL)).find { it.getName() == curAction.getName() }.run {
if (this == null) compare(actionIndex, current, actionA, previous)
else compare(this.getName(), current, previous)
}.also { r -> changeDegree += r }
isAnyChange = isAnyChange || compareResult != 0
actionIndex += 1
//isAnyChange = isAnyChange || compare(actionA, current, actionIndex, previous).also { r-> changeDegree += r } !=0
}
val seqKey = seqCur[indexOfCalls].getResourceNodeKey()
if (isAnyChange) {
val relyOn = if (changeDegree > 0) {
mutableListOf(swapF.getResourceNodeKey())
} else if (changeDegree < 0) {
mutableListOf(swapB.getResourceNodeKey())
} else
mutableListOf(swapB.getResourceNodeKey(), swapF.getResourceNodeKey())
updateDependencies(seqKey, relyOn, RestResourceStructureMutator.MutationType.SWAP.toString())
} else {
uncorrelated.getOrPut(seqKey) { mutableSetOf() }.apply {
add(swapB.getResourceNodeKey())
add(swapF.getResourceNodeKey())
}
}
}
val before = seqCur.subList(swapsloc[0], swapsloc[1]).map { it.getResourceNodeKey() }
if (compare(swapsloc[1], current, swapsloc[0], previous) != 0) {
middles.forEach {
updateDependencies(swapB.getResourceNodeKey(), mutableListOf(it), RestResourceStructureMutator.MutationType.SWAP.toString(), (1.0 / before.size))
}
} else {
uncorrelated.getOrPut(swapB.getResourceNodeKey()) { mutableSetOf() }.addAll(before)
}
//TODO check G, a bit complicated,
} else {
/*
For instance, ABCDEFG, if we swap B and F, become AFCDEBG.
if there is no any impact on fitness,
1) it probably means {C,D,E} does not rely on B and F
2) F does not rely on {C, D, E}
3) F does not rely on B
*/
val middles = seqCur.subList(swapsloc[0] + 1, swapsloc[1] + 1).map { it.getResourceNodeKey() }
middles.forEach { c ->
uncorrelated.getOrPut(c) { mutableSetOf() }.apply {
add(swapB.getResourceNodeKey())
add(swapF.getResourceNodeKey())
}
uncorrelated.getOrPut(swapF.getResourceNodeKey()) { mutableSetOf() }.add(c)
}
uncorrelated.getOrPut(swapF.getResourceNodeKey()) { mutableSetOf() }.add(swapB.getResourceNodeKey())
}
}
/**
* detect possible dependencies by comparing a mutated (i.e., modify) individual with its previous regarding fitness
*/
private fun detectAfterModify(previous: EvaluatedIndividual<RestIndividual>, current: EvaluatedIndividual<RestIndividual>, isBetter: EvaluatedMutation) {
val seqPre = previous.individual.getResourceCalls()
val seqCur = current.individual.getResourceCalls()
/*
For instance, ABCDEFG, if we replace B with another resource instance, then check CDEFG.
if C is worse/better, C rely on B, else C may not rely on B, i.e., the changes of B cannot affect C.
*/
if (isBetter != EvaluatedMutation.EQUAL_WITH) {
val locOfModified = (0 until seqCur.size).find { seqPre[it].template!!.template != seqCur[it].template!!.template }
?: return
//throw IllegalArgumentException("mutator does not change anything.")
val modified = seqCur[locOfModified]
val distance = seqCur[locOfModified].seeActionSize(NO_SQL) - seqPre[locOfModified].seeActionSize(NO_SQL)
var actionIndex = seqCur.mapIndexed { index, restResourceCalls ->
if (index <= locOfModified) restResourceCalls.seeActionSize(NO_SQL)
else 0
}.sum()
((locOfModified + 1) until seqCur.size).forEach { indexOfCalls ->
var isAnyChange = false
seqCur[indexOfCalls].seeActions(NO_SQL).forEach {
val actionA = actionIndex - distance
isAnyChange = isAnyChange || compare(actionIndex, current, actionA, previous) != 0
actionIndex += 1
}
if (isAnyChange) {
val seqKey = seqCur[indexOfCalls].getResourceNodeKey()
updateDependencies(seqKey, mutableListOf(modified.getResourceNodeKey()), RestResourceStructureMutator.MutationType.MODIFY.toString())
}
}
}
}
/**
* detect possible dependencies by comparing a mutated (i.e., replace) individual with its previous regarding fitness
*/
private fun detectAfterReplace(previous: EvaluatedIndividual<RestIndividual>, current: EvaluatedIndividual<RestIndividual>, isBetter: EvaluatedMutation) {
val seqPre = previous.individual.getResourceCalls()
val seqCur = current.individual.getResourceCalls()
/*
For instance, ABCDEFG, if we replace B with H become AHCDEFG, then check CDEFG.
if C is worse, C rely on B; else if C is better, C rely on H; else C may not rely on B and H
*/
val mutatedIndex = (0 until seqCur.size).find { seqCur[it].getResolvedKey() != seqPre[it].getResolvedKey() }!!
val replaced = seqCur[mutatedIndex]
val replace = seqPre[mutatedIndex]
if (isBetter != EvaluatedMutation.EQUAL_WITH) {
val locOfReplaced = seqCur.indexOf(replaced)
val distance = locOfReplaced - seqPre.indexOf(replace)
var actionIndex = seqCur.mapIndexed { index, restResourceCalls ->
if (index <= locOfReplaced) restResourceCalls.seeActionSize(NO_SQL)
else 0
}.sum()
((locOfReplaced + 1) until seqCur.size).forEach { indexOfCalls ->
var isAnyChange = false
var changeDegree = 0
seqCur[indexOfCalls].seeActions(NO_SQL).forEach { curAction ->
val actionA = actionIndex - distance
val compareResult = replaced.seeActions(NO_SQL).plus(replace.seeActions(NO_SQL)).find { it.getName() == curAction.getName() }.run {
if (this == null) compare(actionIndex, current, actionA, previous)
else compare(this.getName(), current, previous)
}.also { r -> changeDegree += r }
isAnyChange = isAnyChange || compareResult != 0
actionIndex += 1
//isAnyChange = isAnyChange || compare(actionA, current, actionIndex, previous).also { r-> changeDegree += r } !=0
}
val seqKey = seqCur[indexOfCalls].getResourceNodeKey()
if (isAnyChange) {
val relyOn = if (changeDegree > 0) {
mutableListOf(replaced.getResourceNodeKey())
} else if (changeDegree < 0) {
mutableListOf(replace.getResourceNodeKey())
} else
mutableListOf(replaced.getResourceNodeKey(), replace.getResourceNodeKey())
updateDependencies(seqKey, relyOn, RestResourceStructureMutator.MutationType.REPLACE.toString())
} else {
uncorrelated.getOrPut(seqKey) { mutableSetOf() }.apply {
add(replaced.getResourceNodeKey())
add(replace.getResourceNodeKey())
}
}
}
} else {
/*
For instance, ABCDEFG, if we replace B with H become AHCDEFG, then check CDEFG.
if there is no any impact on fitness, it probably means {C, D, E, F, G} does not rely on B and H
*/
((mutatedIndex + 1) until seqCur.size).forEach {
val non = seqCur[it].getResourceNodeKey()
uncorrelated.getOrPut(non) { mutableSetOf() }.apply {
add(replaced.getResourceNodeKey())
add(replace.getResourceNodeKey())
}
}
}
}
/**
* detect possible dependencies by comparing a mutated (i.e., add) individual with its previous regarding fitness
*/
private fun detectAfterAdd(previous: EvaluatedIndividual<RestIndividual>, current: EvaluatedIndividual<RestIndividual>, isBetter: EvaluatedMutation) {
val seqPre = previous.individual.getResourceCalls()
val seqCur = current.individual.getResourceCalls()
/*
For instance, ABCDEFG, if we add H at 3nd position, become ABHCDEFG, then check CDEFG.
if C is better, C rely on H; else if C is worse, C rely on H ? ;else C may not rely on H
*/
val added = seqCur.find { cur -> seqPre.find { pre -> pre.getResolvedKey() == cur.getResolvedKey() } == null }
?: return
val addedKey = added.getResourceNodeKey()
val locOfAdded = seqCur.indexOf(added)
if (isBetter != EvaluatedMutation.EQUAL_WITH) {
var actionIndex = seqCur.mapIndexed { index, restResourceCalls ->
if (index <= locOfAdded) restResourceCalls.seeActionSize(NO_SQL)
else 0
}.sum()
val distance = added.seeActionSize(NO_SQL)
(locOfAdded + 1 until seqCur.size).forEach { indexOfCalls ->
var isAnyChange = false
seqCur[indexOfCalls].seeActions(NO_SQL).forEach { curAction ->
val actionA = actionIndex - distance
val compareResult = added.seeActions(NO_SQL).find { it.getName() == curAction.getName() }.run {
if (this == null) compare(actionIndex, current, actionA, previous)
else compare(this.getName(), current, previous)
}
isAnyChange = isAnyChange || compareResult != 0
actionIndex += 1 //actionB
}
val seqKey = seqCur[indexOfCalls].getResourceNodeKey()
if (isAnyChange) {
updateDependencies(seqKey, mutableListOf(addedKey), RestResourceStructureMutator.MutationType.ADD.toString())
} else {
uncorrelated.getOrPut(seqKey) { mutableSetOf() }.add(addedKey)
}
}
} else {
/*
For instance, ABCDEFG, if we add H at 3nd position, become ABHCDEFG.
if there is no any impact on fitness, it probably means {C, D, E, F, G} does not rely on H
*/
(locOfAdded + 1 until seqCur.size).forEach {
val non = seqCur[it].getResourceNodeKey()
uncorrelated.getOrPut(non) { mutableSetOf() }.add(addedKey)
}
}
}
/**
* detect possible dependencies by comparing a mutated (i.e., delete) individual with its previous regarding fitness
*/
private fun detectAfterDelete(previous: EvaluatedIndividual<RestIndividual>, current: EvaluatedIndividual<RestIndividual>, isBetter: EvaluatedMutation) {
val seqPre = previous.individual.getResourceCalls()
val seqCur = current.individual.getResourceCalls()
/*
For instance, ABCDEFG, if B is deleted, become ACDEFG, then check CDEFG.
if C is worse, C rely on B;
else if C is better, C rely one B ?;
else C may not rely on B.
there is another case regarding duplicated resources calls (i.e., same resource and same actions) in a test, for instance, ABCB* (B* denotes the 2nd B), if B is deleted, become ACB*, then check CB* as before,
when comparing B*, B* probability achieves better performance by taking target from previous first B, so we need to compare with merged targets, i.e., B and B*.
*/
val delete = seqPre.find { pre -> seqCur.find { cur -> pre.getResolvedKey() == cur.getResolvedKey() } == null }
?: return
val deleteKey = delete.getResourceNodeKey()
val locOfDelete = seqPre.indexOf(delete)
if (isBetter != EvaluatedMutation.EQUAL_WITH) {
var actionIndex = seqPre.mapIndexed { index, restResourceCalls ->
if (index < locOfDelete) restResourceCalls.seeActionSize(NO_SQL)
else 0
}.sum()
val distance = 0 - delete.seeActionSize(NO_SQL)
(locOfDelete until seqCur.size).forEach { indexOfCalls ->
var isAnyChange = false
seqCur[indexOfCalls].seeActions(NO_SQL).forEach { curAction ->
val actionA = actionIndex - distance
val compareResult = delete.seeActions(NO_SQL).find { it.getName() == curAction.getName() }.run {
if (this == null) compare(actionIndex, current, actionA, previous)
else compare(this.getName(), current, previous)
}
isAnyChange = isAnyChange || compareResult != 0
actionIndex += 1 //actionB
}
val seqKey = seqCur[indexOfCalls].getResourceNodeKey()
if (isAnyChange) {
updateDependencies(seqKey, mutableListOf(deleteKey), RestResourceStructureMutator.MutationType.DELETE.toString())
} else {
uncorrelated.getOrPut(seqKey) { mutableSetOf() }.add(deleteKey)
}
}
} else {
/*
For instance, ABCDEFG, if B is deleted, become ACDEFG, then check CDEFG.
if there is no impact on fitness, it probably means {C, D, E, F, G} does not rely on B
*/
(locOfDelete until seqCur.size).forEach {
val non = seqCur[it].getResourceNodeKey()
uncorrelated.getOrPut(non) { mutableSetOf() }.add(deleteKey)
}
}
}
/**
* detect possible dependency among resources,
* the entry is structure mutation
*
* [isBetter] 1 means current is better than previous, 0 means that they are equal, and -1 means current is worse than previous
*/
fun detectDependencyAfterStructureMutation(previous: EvaluatedIndividual<RestIndividual>, current: EvaluatedIndividual<RestIndividual>, isBetter: EvaluatedMutation) {
val seqPre = previous.individual.getResourceCalls()
val seqCur = current.individual.getResourceCalls()
when (seqCur.size - seqPre.size) {
0 -> {
if (seqPre.map { it.getResourceNodeKey() }.toList() == seqCur.map { it.getResourceNodeKey() }.toList()) {
//Modify
detectAfterModify(previous, current, isBetter)
} else if (seqCur.size > 1
&& seqCur
.filterIndexed { index, restResourceCalls -> restResourceCalls.getResolvedKey() != seqPre[index].getResolvedKey() }.size == 2) {
//SWAP
detectAfterSwap(previous, current, isBetter)
} else {
//REPLACE
detectAfterReplace(previous, current, isBetter)
}
}
1 -> detectAfterAdd(previous, current, isBetter)
-1 -> detectAfterDelete(previous, current, isBetter)
else -> {
throw IllegalArgumentException("apply undefined structure mutator that changed the size of resources from ${seqPre.size} to ${seqCur.size}")
}
}
}
fun isDependencyNotEmpty(): Boolean {
return dependencies.isNotEmpty()
}
/************************ manage to resource call regarding dependency ***********************************/
/**
* handle to select an resource call for adding in [ind], and the resource should (probably) depend on one of resource in [ind].
* @return pair, first is an existing resource call in [ind], and second is a newly created resource call that is related to the first
* null, all resources are checked, and none of resource is related to other
*/
fun handleAddDepResource(ind: RestIndividual, maxTestSize: Int, candidates: MutableList<RestResourceCalls> = mutableListOf()): Pair<RestResourceCalls?, RestResourceCalls>? {
val options = mutableListOf(0, 1)
while (options.isNotEmpty()) {
val option = randomness.choose(options)
val pair = when (option) {
0 -> handleAddNewDepResource(if (candidates.isEmpty()) ind.getResourceCalls().toMutableList() else candidates, maxTestSize)
1 -> {
handleAddNotCheckedDepResource(ind, maxTestSize)?:handleAddNewDepResource(if (candidates.isEmpty()) ind.getResourceCalls().toMutableList() else candidates, maxTestSize)
}
else -> null
}
if (pair != null) return pair
options.remove(option)
}
return null
}
/**
* @return pair, first is an existing resource call in [sequence], and second is a newly created resource call that is related to the first
*/
private fun handleAddNewDepResource(sequence: MutableList<RestResourceCalls>, maxTestSize: Int): Pair<RestResourceCalls?, RestResourceCalls>? {
val existingRs = sequence.map { it.getResourceNodeKey() }
val candidates = sequence
.filter {
dependencies[it.getResourceNodeKey()] != null &&
dependencies[it.getResourceNodeKey()]!!.any { dep ->
dep.targets.any { t -> existingRs.none { e -> e == t } } ||
(dep is SelfResourcesRelation && existingRs.count { e -> e == it.getResourceNodeKey() } == 1)
}
}
if (candidates.isNotEmpty()) {
val first = randomness.choose(candidates)
/*
add self relation with a relative low probability, i.e., 20%
*/
dependencies[first.getResourceNodeKey()]!!.flatMap { dep ->
if (dep !is SelfResourcesRelation)
dep.getDependentResources(first.getResourceNodeKey(), exclude = existingRs)
else if (randomness.nextBoolean(0.2)) dep.targets else mutableListOf()
}.let { templates ->
if (templates.isNotEmpty()) {
rm.getResourceNodeFromCluster(randomness.choose(templates)).sampleAnyRestResourceCalls(randomness, maxTestSize, prioriDependent = true).let { second ->
return Pair(first, second)
}
}
}
}
return null
}
private fun handleAddNotCheckedDepResource(ind: RestIndividual, maxTestSize: Int): Pair<RestResourceCalls?, RestResourceCalls>? {
val checked = ind.getResourceCalls().flatMap { cur ->
findDependentResources(ind, cur).plus(findNonDependentResources(ind, cur))
}.map { it.getResourceNodeKey() }.toHashSet()
rm.getResourceCluster().keys.filter { !checked.contains(it) }.let { keys ->
if (keys.isNotEmpty()) {
rm.getResourceNodeFromCluster(randomness.choose(keys)).sampleAnyRestResourceCalls(randomness, maxTestSize, prioriDependent = true).let { second ->
return Pair(null, second)
}
}
}
return null
}
/**
* handle to select an non-dependent resource for deletion
* @return a candidate, if none of a resource is deletable, return null
*/
fun handleDelNonDepResource(ind: RestIndividual): RestResourceCalls {
val candidates = identifyDelNonDepResource(ind)
Lazy.assert { candidates.isNotEmpty() }
return randomness.choose(candidates)
}
/**
* identify a set of non-dependent resource for deletion in [ind]
*/
fun identifyDelNonDepResource(ind: RestIndividual): List<RestResourceCalls> {
val candidates = ind.getResourceCalls().filter { it.isDeletable }.filter { cur ->
!existsDependentResources(ind, cur)
}
if (candidates.isEmpty()) return ind.getResourceCalls().filter(RestResourceCalls::isDeletable)
val nodep = candidates.filter { isNonDepResources(ind, it)}
if (nodep.isNotEmpty()) return nodep
return candidates
}
/**
* handle to select two related resources for swap
* @return a pair of position to swap, if none of a pair resource is movable, return null
*/
fun handleSwapDepResource(ind: RestIndividual, candidates: Map<Int, Set<Int>>): Pair<Int, Int>? {
if (candidates.isEmpty()) return null
val options = mutableListOf(1, 2, 3)
while (options.isNotEmpty()) {
val option = randomness.choose(options)
val pair = when (option) {
1 -> adjustDepResource(ind, candidates)
2 -> {
swapNotConfirmedDepResource(ind, candidates)?:adjustDepResource(ind, candidates)
}
3 -> {
swapNotCheckedResource(ind, candidates)?:adjustDepResource(ind, candidates)
}
else -> null
}
if (pair != null) return pair
options.remove(option)
}
return null
}
private fun adjustDepResource(ind: RestIndividual, all : Map<Int, Set<Int>>): Pair<Int, Int>? {
val candidates = mutableMapOf<Int, MutableSet<Int>>()
ind.getResourceCalls().forEachIndexed { index, cur ->
findDependentResources(ind, cur, minProbability = StringSimilarityComparator.SimilarityThreshold).map { ind.getResourceCalls().indexOf(it) }.filter { second -> index < second }.apply {
if (isNotEmpty()) candidates.getOrPut(index) { mutableSetOf() }.addAll(this.toHashSet())
}
}
return selectSwap(candidates, all)
}
private fun selectSwap(candidates: Map<Int, Set<Int>>, all: Map<Int, Set<Int>>) : Pair<Int, Int>?{
val valid = candidates.filter { e->
all.containsKey(e.key) && e.value.any { all[e.key]!!.contains(it) }
}
if (valid.isNotEmpty()) {
val select = randomness.choose(valid.keys)
val ex = valid.getValue(select).filter { v-> all[select]!!.contains(v) }
return select to randomness.choose(ex)
}
return null
}
private fun swapNotConfirmedDepResource(ind: RestIndividual, all : Map<Int, Set<Int>>): Pair<Int, Int>? {
val probCandidates = ind.getResourceCalls().filter {
existsDependentResources(ind, it, maxProbability = StringSimilarityComparator.SimilarityThreshold) }
if (probCandidates.isEmpty()) return null
val valid = probCandidates.map { ind.getResourceCalls().indexOf(it) }.filter { all.containsKey(it) }
if (valid.isEmpty()) return null
val select = randomness.choose(valid)
val ex = findDependentResources(ind, ind.getResourceCalls()[select], maxProbability = StringSimilarityComparator.SimilarityThreshold)
val validEx = ex.map { ind.getResourceCalls().indexOf(it) }.filter { all[select]!!.contains(it) }
if (validEx.isNotEmpty())
return select to randomness.choose(validEx)
return null
}
private fun swapNotCheckedResource(ind: RestIndividual, all : Map<Int, Set<Int>>): Pair<Int, Int>? {
val candidates = mutableMapOf<Int, MutableSet<Int>>()
ind.getResourceCalls().forEachIndexed { index, cur ->
val checked = findDependentResources(ind, cur).plus(findNonDependentResources(ind, cur))
ind.getResourceCalls().filter { it != cur && !checked.contains(it) }.map { ind.getResourceCalls().indexOf(it) }.apply {
if (isNotEmpty()) candidates.getOrPut(index) { mutableSetOf() }.addAll(this)
}
}
return selectSwap(candidates, all)
}
/**
* @return a list of db actions of [ind] which are possibly not related to rest actions of [ind]
*/
fun unRelatedSQL(ind: RestIndividual, candidates: List<DbAction>?) : List<DbAction>{
val allrelated = getAllRelatedTables(ind)
return (candidates?:ind.seeInitializingActions().filterIsInstance<DbAction>().filterNot { it.representExistingData }).filterNot { allrelated.any { r-> r.equals(it.table.name, ignoreCase = true) } }
}
fun identifyUnRelatedSqlTable(ind: RestIndividual, candidates: List<DbAction>?) : List<String>{
val actions = unRelatedSQL(ind, candidates)
return if (actions.isNotEmpty()) actions.map { it.table.name } else ind.seeInitializingActions().filterIsInstance<DbAction>().filterNot { it.representExistingData }.map { it.table.name }
}
/**
* add [num] related resources into [ind] with SQL
* @param probability represent a probability of using identified dependent tables, otherwise employ the tables which are
* not part of the current dbInitialization
*
* Man: shall we set probability 1.0? because the related tables for the resource might be determinate based on
* tracking of SQL execution.
*/
fun addRelatedSQL(ind: RestIndividual, num: Int, probability: Double = 1.0) : List<List<DbAction>>{
val other = randomness.choose(identifyRelatedSQL(ind, probability))
return createDbActions(other, num)
}
/**
* @param probability represent a probability of using identified dependent tables, otherwise employ the tables which are
* not part of the current dbInitialization
*/
fun identifyRelatedSQL(ind: RestIndividual, probability: Double = 1.0): Set<String>{
val allrelated = getAllRelatedTables(ind)
if (allrelated.isNotEmpty() && randomness.nextBoolean(probability)){
val notincluded = allrelated.filterNot {
ind.seeInitializingActions().filterIsInstance<DbAction>().any { d-> it.equals(d.table.name, ignoreCase = true) }
}
//prioritize notincluded related ones with a probability 0.8
return if (notincluded.isNotEmpty() && randomness.nextBoolean(0.8)){
notincluded.toSet()
}else allrelated
}else{
val left = rm.getTableInfo().keys.filterNot {
ind.seeInitializingActions().filterIsInstance<DbAction>().any { d-> it.equals(d.table.name, ignoreCase = true) }
}
return if (left.isNotEmpty() && randomness.nextBoolean()) left.toSet()
else rm.getTableInfo().keys
}
}
fun createDbActions(name : String, num : Int) : List<List<DbAction>>{
rm.getSqlBuilder() ?:throw IllegalStateException("attempt to create resource with SQL but the sqlBuilder is null")
if (num <= 0)
throw IllegalArgumentException("invalid num (i.e.,$num) for creating resource")
val extraConstraints = randomness.nextBoolean(apc.getExtraSqlDbConstraintsProbability())
val list= (0 until num)
.map { rm.getSqlBuilder()!!.createSqlInsertionAction(name, setOf(), mutableListOf(),true, extraConstraints) }
.toMutableList()
if (log.isTraceEnabled){
log.trace("at createDbActions, {} insertions are added, and they are {}", list.size,
list.flatten().joinToString(",") {
it.getResolvedName()
})
}
DbActionUtils.randomizeDbActionGenes(list.flatten(), randomness)
DbActionUtils.repairBrokenDbActionsList(list.flatten().toMutableList(), randomness)
return list
}
/************************ sample resource individual regarding dependency ***********************************/
/**
* sample an individual which contains related resources
*/
fun sampleRelatedResources(calls: MutableList<RestResourceCalls>, sizeOfResource: Int, maxSize: Int) {
val start = -calls.sumBy { it.seeActionSize(NO_SQL) }
val first = randomness.choose(dependencies.keys)
rm.sampleCall(first, true, calls, maxSize)
var size = calls.sumBy { it.seeActionSize(NO_SQL) } + start
val excluded = mutableListOf<String>()
val relatedResources = mutableListOf<RestResourceCalls>()
excluded.add(first)
relatedResources.add(calls.last())
while (relatedResources.size < sizeOfResource && size < maxSize) {
val notRelated = rm.getResourceCluster().keys.filter { r-> (dependencies[first]?.none { t -> t.targets.contains(r)}?:true) && !excluded.contains(r) }
val candidates = dependencies[first]!!.flatMap { it.getDependentResources(first, exclude = excluded) }
/*
if there is no valid candidate, prefer not related resource
*/
val related = if (candidates.isNotEmpty()) randomness.choose(candidates) else if(notRelated.isNotEmpty()) randomness.choose(notRelated) else break
excluded.add(related)
rm.sampleCall(related, true, calls, size, false, if (related.isEmpty()) null else relatedResources)
// calls.last().verifyBindingGenes(calls)
relatedResources.add(calls.last())
size = calls.sumBy { it.seeActionSize(NO_SQL) } + start
}
}
/**
* add related resource with SQL as its initialization of [ind], i.e., [RestIndividual.dbInitialization]
* @param ind to be handled by adding resources in its initialization with sql
* @param maxPerResource is a maximum resources to be added per resource
*/
fun sampleResourceWithRelatedDbActions(ind: RestIndividual, maxPerResource : Int) {
if (maxPerResource == 0) return
rm.getSqlBuilder()?:return
val relatedTables = getAllRelatedTables(ind).flatMap { t-> (0 until randomness.nextInt(1, maxPerResource)).map { t } }
val extraConstraints = randomness.nextBoolean(apc.getExtraSqlDbConstraintsProbability())
val added = rm.cluster.createSqlAction(
relatedTables,
rm.getSqlBuilder()!!,
mutableListOf(),
false,
true,
randomness,
useExtraSqlDbConstraints = extraConstraints)
DbActionUtils.repairBrokenDbActionsList(added,randomness)
ind.addInitializingDbActions(actions = added)
}
private fun getAllRelatedTables(ind: RestIndividual) : Set<String>{
return ind.getResourceCalls().flatMap { c->
extractRelatedTablesForCall(c, withSql = c.is2POST).values.flatMap { it.map { g->g.tableName } }.toSet()
}.toSet()
}
/**************************************** apply parser to derive ************************************************************************/
/**
* check if the [call] has related tables
*/
fun checkIfDeriveTable(call: RestResourceCalls): Boolean {
if (!call.template!!.independent) return false
call.seeActions(NO_SQL).first().apply {
if (this is RestCallAction) {
if (this.parameters.isNotEmpty()) return true
}
}
return false
}
/**
* @return extracted related tables for [call] regarding [dbActions]
* if [dbActions] is not empty, return related table from tables in [dbActions]
* if [dbActions] is empty, return all derived related table
*/
fun extractRelatedTablesForCall(call: RestResourceCalls, dbActions: MutableList<DbAction> = mutableListOf(), withSql : Boolean): MutableMap<RestCallAction, MutableList<ParamGeneBindMap>> {
val paramsInfo = call.getResourceNode().getPossiblyBoundParams(call.getRestTemplate(), withSql)
return SimpleDeriveResourceBinding.generateRelatedTables(paramsInfo, call, dbActions)
}
/**
* @return whether all resources in SUT are independent
*/
fun onlyIndependentResource(): Boolean {
return rm.getResourceCluster().values.none { r -> !r.isIndependent() }
}
/**
* @return whether the [ind] can be mutated with resource-based solution
* e.g., the [ind] does not have any related resource, then the resource-based solution will not be employed
*/
fun canMutateResource(ind: RestIndividual) : Boolean{
return ind.getResourceCalls().size > 1 ||
getAllRelatedTables(ind).isNotEmpty() ||
(
rm.getResourceCluster().values.filter { r->
!r.isIndependent() && ind.getResourceCalls().any { i->
i.getResourceNode().getName().equals(r.getName(), ignoreCase = true)
}
}.size > 1)
}
/**
* @return related resource of [resource]
*/
fun getRelatedResource(resource : String) : Set<String> = dependencies[resource]?.flatMap { it.targets }?.toSet()?: setOf()
/**
* export derived dependency info as outputs of EM
*/
fun exportDependencies(){
val path = Paths.get(config.dependencyFile)
Files.createDirectories(path.parent)
if (dependencies.isNotEmpty()){
val header = mutableListOf("key").plus(dependencies.values.first().first().toCSVHeader()).joinToString(",")
val content = mutableListOf<String>()
dependencies.forEach { (t, u) ->
u.forEachIndexed { index, resourceRelatedToResources ->
val row = mutableListOf(if (index == 0) t else "").plus(resourceRelatedToResources.exportCSV())
content.add(row.joinToString(","))
}
}
Files.write(path, listOf(header).plus(content))
}
}
} | lgpl-3.0 | 36c3d6a16b39f2ef3831277aabb728ee | 47.588089 | 217 | 0.602312 | 4.851904 | false | false | false | false |
EMResearch/EvoMaster | core/src/test/kotlin/org/evomaster/core/search/gene/ChoiceGeneTest.kt | 1 | 2220 | package org.evomaster.core.search.gene
import org.evomaster.core.search.gene.numeric.IntegerGene
import org.evomaster.core.search.gene.optional.ChoiceGene
import org.evomaster.core.search.gene.string.StringGene
import org.evomaster.core.search.service.Randomness
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
class ChoiceGeneTest {
@Test
fun testOneElement() {
ChoiceGene("choice",listOf(
IntegerGene("a",0,10)
))
}
@Test
fun testInvalidChildren() {
assertThrows<IllegalStateException> {
ChoiceGene("choice",listOf())
}
}
@Test
fun testInvalidNegativeActiveChoice() {
assertThrows<IllegalArgumentException> {
ChoiceGene("choice",listOf(IntegerGene("a",0,10)), activeChoice = -1)
}
}
@Test
fun testInvalidActiveChoice() {
assertThrows<IllegalArgumentException> {
ChoiceGene("choice",listOf(IntegerGene("a",0,10)), activeChoice = 1)
}
}
val rand = Randomness().apply { updateSeed(42) }
@Test
fun testRadomize() {
val gene = ChoiceGene("choice",listOf(
IntegerGene("a",0,10)
))
gene.doInitialize(rand)
(gene.getViewOfChildren()[0] as IntegerGene).value = 0
assertEquals("0", gene.getValueAsPrintableString())
}
@Test
fun testRadomizeTwoChoices() {
val gene = ChoiceGene("choice",listOf(
IntegerGene("a",0,10),
StringGene("b","foo")
))
gene.doInitialize(rand)
repeat (100) {
gene.randomize(rand,true)
(gene.getViewOfChildren()[0] as IntegerGene).value = 1
(gene.getViewOfChildren()[1] as StringGene).value = "bar"
val value = gene.getValueAsPrintableString()
assertTrue(0 <= gene.activeGeneIndex && gene.activeGeneIndex <=1)
if (gene.activeGeneIndex == 0) {
assertEquals("1", value)
} else {
assertEquals("\"bar\"", value)
}
}
}
} | lgpl-3.0 | 8fc05c0ed6e945acd55e1378c66c9405 | 28.223684 | 81 | 0.607658 | 4.503043 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.