content
stringlengths
0
13M
contentHash
stringlengths
1
10
path
stringlengths
4
297
package com.cognifide.gradle.aem.instance.tasks import com.cognifide.gradle.aem.common.instance.action.AwaitUpAction import com.cognifide.gradle.aem.common.instance.action.ReloadAction import com.cognifide.gradle.aem.common.instance.names import com.cognifide.gradle.aem.common.tasks.Instance import org.gradle.api.tasks.TaskAction open class InstanceReload : Instance() { private var reloadOptions: ReloadAction.() -> Unit = {} fun reload(options: ReloadAction.() -> Unit) { this.reloadOptions = options } private var awaitUpOptions: AwaitUpAction.() -> Unit = {} fun awaitUp(options: AwaitUpAction.() -> Unit) { this.awaitUpOptions = options } @TaskAction fun reload() { instanceManager.awaitReloaded(anyInstances, reloadOptions, awaitUpOptions) common.notifier.lifecycle("Instance(s) reloaded", "Which: ${anyInstances.names}") } init { description = "Reloads all AEM instance(s)." } companion object { const val NAME = "instanceReload" } }
2860077243
src/main/kotlin/com/cognifide/gradle/aem/instance/tasks/InstanceReload.kt
/* * * * Apache License * * * * Copyright [2017] Sinyuk * * * * 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.sinyuk.fanfou.ui.status import android.os.Build import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentPagerAdapter import android.text.Editable import android.text.TextWatcher import android.view.View import android.view.ViewTreeObserver import cn.dreamtobe.kpswitch.util.KeyboardUtil import com.linkedin.android.spyglass.suggestions.SuggestionsResult import com.linkedin.android.spyglass.suggestions.interfaces.Suggestible import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsResultListener import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsVisibilityManager import com.linkedin.android.spyglass.tokenization.QueryToken import com.linkedin.android.spyglass.tokenization.impl.WordTokenizer import com.linkedin.android.spyglass.tokenization.impl.WordTokenizerConfig import com.linkedin.android.spyglass.tokenization.interfaces.QueryTokenReceiver import com.sinyuk.fanfou.R import com.sinyuk.fanfou.base.AbstractActivity import com.sinyuk.fanfou.base.AbstractFragment import com.sinyuk.fanfou.di.Injectable import com.sinyuk.fanfou.domain.DO.Player import com.sinyuk.fanfou.domain.DO.Status import com.sinyuk.fanfou.domain.STATUS_LIMIT import com.sinyuk.fanfou.domain.StatusCreation import com.sinyuk.fanfou.domain.TIMELINE_CONTEXT import com.sinyuk.fanfou.ui.editor.EditorView import com.sinyuk.fanfou.ui.editor.MentionListView import com.sinyuk.fanfou.ui.timeline.TimelineView import com.sinyuk.fanfou.util.obtainViewModelFromActivity import com.sinyuk.fanfou.viewmodel.FanfouViewModelFactory import com.sinyuk.fanfou.viewmodel.PlayerViewModel import kotlinx.android.synthetic.main.status_view.* import kotlinx.android.synthetic.main.status_view_footer.* import kotlinx.android.synthetic.main.status_view_reply_actionbar.* import javax.inject.Inject /** * Created by sinyuk on 2018/1/12. * */ class StatusView : AbstractFragment(), Injectable, QueryTokenReceiver, SuggestionsResultListener, SuggestionsVisibilityManager { companion object { fun newInstance(status: Status, photoExtra: Bundle? = null) = StatusView().apply { arguments = Bundle().apply { putParcelable("status", status) putBundle("photoExtra", photoExtra) } } } override fun layoutId() = R.layout.status_view @Inject lateinit var factory: FanfouViewModelFactory private val playerViewModel by lazy { obtainViewModelFromActivity(factory, PlayerViewModel::class.java) } override fun onEnterAnimationEnd(savedInstanceState: Bundle?) { super.onEnterAnimationEnd(savedInstanceState) navBack.setOnClickListener { onBackPressedSupport() } setupEditor() setupKeyboard() onTextChanged(0) setupViewPager() val status = arguments!!.getParcelable<Status>("status") fullscreenButton.setOnClickListener { (activity as AbstractActivity).start(EditorView.newInstance(status.id, replyEt.mentionsText, StatusCreation.REPOST_STATUS)) replyEt.text = null } } private fun setupViewPager() { val status = arguments!!.getParcelable<Status>("status") val bundle = arguments!!.getBundle("photoExtra") val fragments: List<Fragment> = if (findChildFragment(TimelineView::class.java) == null) { val mentionView = MentionListView() mentionView.onItemClickListener = onSuggestionSelectListener mutableListOf(TimelineView.contextTimeline(TIMELINE_CONTEXT, status, bundle), mentionView) } else { mutableListOf(findChildFragment(TimelineView::class.java), MentionListView()) } viewPager.setPagingEnabled(false) viewPager.offscreenPageLimit = 1 viewPager.adapter = object : FragmentPagerAdapter(childFragmentManager) { override fun getItem(position: Int) = fragments[position] override fun getCount() = fragments.size } } private var keyboardListener: ViewTreeObserver.OnGlobalLayoutListener? = null private fun setupKeyboard() { keyboardListener = KeyboardUtil.attach(activity, panelRoot, { // TODO: how comes the Exception: panelRootContainer must not be null panelRootContainer?.visibility = if (it) { if (replyEt.requestFocus()) replyEt.setSelection(replyEt.text.length) View.VISIBLE } else { replyEt.clearFocus() View.GONE } }) } private val config = WordTokenizerConfig.Builder() .setExplicitChars("@") .setThreshold(3) .setMaxNumKeywords(5) .setWordBreakChars(" ").build() private fun setupEditor() { replyEt.tokenizer = WordTokenizer(config) replyEt.setAvoidPrefixOnTap(true) replyEt.setQueryTokenReceiver(this) replyEt.setSuggestionsVisibilityManager(this) replyEt.setAvoidPrefixOnTap(true) replyCommitButton.setOnClickListener { } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) textCountProgress.min = 0 textCountProgress.max = STATUS_LIMIT replyEt.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { onTextChanged(s?.length ?: 0) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { } }) } /** * @param count 字数 */ private fun onTextChanged(count: Int) { textCountProgress.progress = count replyCommitButton.isEnabled = count in 1..STATUS_LIMIT } private val onSuggestionSelectListener = object : MentionListView.OnItemClickListener { override fun onItemClick(position: Int, item: Suggestible) { (item as Player).let { replyEt.insertMention(it) displaySuggestions(false) playerViewModel.updateMentionedAt(it) // onTextChanged(replyEt.text.length) replyEt.requestFocus() replyEt.setSelection(replyEt.text.length) } } } @Suppress("PrivatePropertyName") private val BUCKET = "player-mentioned" override fun onQueryReceived(queryToken: QueryToken): MutableList<String> { val data = playerViewModel.filter(queryToken.keywords) onReceiveSuggestionsResult(SuggestionsResult(queryToken, data), BUCKET) return arrayOf(BUCKET).toMutableList() } override fun onReceiveSuggestionsResult(result: SuggestionsResult, bucket: String) { val data = result.suggestions if (data?.isEmpty() != false) return displaySuggestions(true) findChildFragment(MentionListView::class.java).setData(data) } override fun displaySuggestions(display: Boolean) { viewPager.setCurrentItem(if (display) 1 else 0, true) } override fun isDisplayingSuggestions() = viewPager.currentItem == 1 override fun onBackPressedSupport(): Boolean { when { panelRootContainer.visibility == View.VISIBLE -> KeyboardUtil.hideKeyboard(panelRootContainer) isDisplayingSuggestions -> displaySuggestions(false) else -> pop() } return true } override fun onDestroy() { keyboardListener?.let { KeyboardUtil.detach(activity, it) } activity?.currentFocus?.let { KeyboardUtil.hideKeyboard(it) } super.onDestroy() } }
1441581882
presentation/src/main/java/com/sinyuk/fanfou/ui/status/StatusView.kt
package com.timepath.vfs.provider.jdbc import com.timepath.vfs.MockFile import com.timepath.vfs.SimpleVFile import com.timepath.vfs.provider.ProviderStub import org.jetbrains.annotations.NonNls import java.sql.SQLException import java.text.MessageFormat import java.util.LinkedList import java.util.logging.Level /** * @author TimePath */ class JDBCTable(private val jdbcProvider: JDBCProvider, name: String) : ProviderStub(name) { override fun get(NonNls name: String) = list().firstOrNull { name == it.name } SuppressWarnings("NestedTryStatement") override fun list(): Collection<SimpleVFile> { val rows = LinkedList<MockFile>() try { jdbcProvider.conn.prepareStatement("SELECT * FROM ${name}").let { st -> st.executeQuery().let { rs -> val len = rs.getMetaData().getColumnCount() while (rs.next()) { val sb = StringBuilder() for (i in 0..len - 1) { sb.append('\t').append(rs.getString(i + 1)) } rows.add(MockFile(rs.getString(1), sb.substring(1))) } } } } catch (e: SQLException) { JDBCProvider.LOG.log(Level.SEVERE, MessageFormat.format("Reading from table {0}", name), e) } return rows } }
3486848447
src/main/kotlin/com/timepath/vfs/provider/jdbc/JDBCTable.kt
/* * Copyright 2017-2022 Adobe. * * 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.adobe.testing.s3mock.its import com.adobe.testing.s3mock.util.DigestUtil import com.amazonaws.services.s3.model.AmazonS3Exception import com.amazonaws.services.s3.model.CopyObjectRequest import com.amazonaws.services.s3.model.MetadataDirective import com.amazonaws.services.s3.model.ObjectMetadata import com.amazonaws.services.s3.model.PutObjectRequest import com.amazonaws.services.s3.model.SSEAwsKeyManagementParams import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInfo import java.io.File import java.io.FileInputStream import java.io.InputStream import java.util.UUID /** * Test the application using the AmazonS3 SDK V1. */ internal class CopyObjectV1IT : S3TestBase() { /** * Puts an Object; Copies that object to a new bucket; Downloads the object from the new bucket; * compares checksums of original and copied object. */ @Test fun shouldCopyObject(testInfo: TestInfo) { val sourceKey = UPLOAD_FILE_NAME val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey) val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/$sourceKey" val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) s3Client.copyObject(copyObjectRequest) val copiedObject = s3Client.getObject(destinationBucketName, destinationKey) val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent) copiedObject.close() assertThat(copiedDigest) .`as`("Source file and copied File should have same digests") .isEqualTo(putObjectResult.eTag) } @Test fun testCopyObject_successMatch(testInfo: TestInfo) { val sourceKey = UPLOAD_FILE_NAME val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey) val matchingEtag = "\"${putObjectResult.eTag}\"" val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/$sourceKey" val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) .withMatchingETagConstraint(matchingEtag) s3Client.copyObject(copyObjectRequest) val copiedObject = s3Client.getObject(destinationBucketName, destinationKey) val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent) copiedObject.close() assertThat(copiedDigest) .`as`("Source file and copied File should have same digests") .isEqualTo(putObjectResult.eTag) } @Test fun testCopyObject_successNoneMatch(testInfo: TestInfo) { val sourceKey = UPLOAD_FILE_NAME val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey) val nonMatchingEtag = "\"${randomName}\"" val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/$sourceKey" val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) .withNonmatchingETagConstraint(nonMatchingEtag) s3Client.copyObject(copyObjectRequest) val copiedObject = s3Client.getObject(destinationBucketName, destinationKey) val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent) copiedObject.close() assertThat(copiedDigest) .`as`("Source file and copied File should have same digests") .isEqualTo(putObjectResult.eTag) } @Test fun testCopyObject_failureMatch(testInfo: TestInfo) { val sourceKey = UPLOAD_FILE_NAME val (bucketName, _) = givenBucketAndObjectV1(testInfo, sourceKey) val nonMatchingEtag = "\"${randomName}\"" val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/$sourceKey" val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) .withMatchingETagConstraint(nonMatchingEtag) s3Client.copyObject(copyObjectRequest) assertThatThrownBy { s3Client.getObject(destinationBucketName, destinationKey) } .isInstanceOf(AmazonS3Exception::class.java) .hasMessageContaining("Service: Amazon S3; Status Code: 404; Error Code: NoSuchKey;") .hasMessageContaining("The specified key does not exist.") } @Test fun testCopyObject_failureNoneMatch(testInfo: TestInfo) { val sourceKey = UPLOAD_FILE_NAME val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey) val matchingEtag = "\"${putObjectResult.eTag}\"" val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/$sourceKey" val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) .withNonmatchingETagConstraint(matchingEtag) s3Client.copyObject(copyObjectRequest) assertThatThrownBy { s3Client.getObject(destinationBucketName, destinationKey) } .isInstanceOf(AmazonS3Exception::class.java) .hasMessageContaining("Service: Amazon S3; Status Code: 404; Error Code: NoSuchKey;") .hasMessageContaining("The specified key does not exist.") } /** * Puts an Object; Copies that object to the same bucket and the same key; * Downloads the object; compares checksums of original and copied object. */ @Test fun shouldCopyObjectToSameKey(testInfo: TestInfo) { val bucketName = givenBucketV1(testInfo) val uploadFile = File(UPLOAD_FILE_NAME) val sourceKey = UPLOAD_FILE_NAME val objectMetadata = ObjectMetadata() objectMetadata.userMetadata = mapOf("test-key" to "test-value") val putObjectRequest = PutObjectRequest(bucketName, sourceKey, uploadFile).withMetadata(objectMetadata) val putObjectResult = s3Client.putObject(putObjectRequest) //TODO: this is actually illegal on S3. when copying to the same key like this, S3 will throw: // This copy request is illegal because it is trying to copy an object to itself without // changing the object's metadata, storage class, website redirect location or encryption attributes. val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, bucketName, sourceKey) s3Client.copyObject(copyObjectRequest) val copiedObject = s3Client.getObject(bucketName, sourceKey) val copiedObjectMetadata = copiedObject.objectMetadata assertThat(copiedObjectMetadata.userMetadata["test-key"]).isEqualTo("test-value") val objectContent = copiedObject.objectContent val copiedDigest = DigestUtil.hexDigest(objectContent) copiedObject.close() assertThat(copiedDigest) .`as`("Source file and copied File should have same digests") .isEqualTo(putObjectResult.eTag) } /** * Puts an Object; Copies that object with REPLACE directive to the same bucket and the same key; * Downloads the object; compares checksums of original and copied object. */ @Test fun shouldCopyObjectWithReplaceToSameKey(testInfo: TestInfo) { val bucketName = givenBucketV1(testInfo) val uploadFile = File(UPLOAD_FILE_NAME) val sourceKey = UPLOAD_FILE_NAME val objectMetadata = ObjectMetadata() objectMetadata.userMetadata = mapOf("test-key" to "test-value") val putObjectRequest = PutObjectRequest(bucketName, sourceKey, uploadFile).withMetadata(objectMetadata) val putObjectResult = s3Client.putObject(putObjectRequest) val replaceObjectMetadata = ObjectMetadata() replaceObjectMetadata.userMetadata = mapOf("test-key2" to "test-value2") val copyObjectRequest = CopyObjectRequest() .withSourceBucketName(bucketName) .withSourceKey(sourceKey) .withDestinationBucketName(bucketName) .withDestinationKey(sourceKey) .withMetadataDirective(MetadataDirective.REPLACE) .withNewObjectMetadata(replaceObjectMetadata) s3Client.copyObject(copyObjectRequest) val copiedObject = s3Client.getObject(bucketName, sourceKey) val copiedObjectMetadata = copiedObject.objectMetadata assertThat(copiedObjectMetadata.userMetadata["test-key"]) .`as`("Original userMetadata must have been replaced.") .isNullOrEmpty() assertThat(copiedObjectMetadata.userMetadata["test-key2"]).isEqualTo("test-value2") val objectContent = copiedObject.objectContent val copiedDigest = DigestUtil.hexDigest(objectContent) copiedObject.close() assertThat(copiedDigest) .`as`("Source file and copied File should have same digests") .isEqualTo(putObjectResult.eTag) } /** * Puts an Object; Copies that object to a new bucket with new user metadata; Downloads the * object from the new bucket; * compares checksums of original and copied object; compares copied object user metadata with * the new user metadata specified during copy request. */ @Test fun shouldCopyObjectWithNewUserMetadata(testInfo: TestInfo) { val sourceKey = UPLOAD_FILE_NAME val (bucketName, putObjectResult) = givenBucketAndObjectV1(testInfo, sourceKey) val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/$sourceKey/withNewUserMetadata" val objectMetadata = ObjectMetadata() objectMetadata.addUserMetadata("key", "value") val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) copyObjectRequest.newObjectMetadata = objectMetadata s3Client.copyObject(copyObjectRequest) val copiedObject = s3Client.getObject(destinationBucketName, destinationKey) val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent) copiedObject.close() assertThat(copiedDigest) .`as`("Source file and copied File should have same digests") .isEqualTo(putObjectResult.eTag) assertThat(copiedObject.objectMetadata.userMetadata) .`as`("User metadata should be identical!") .isEqualTo(objectMetadata.userMetadata) } /** * Puts an Object with some user metadata; Copies that object to a new bucket. * Downloads the object from the new bucket; * compares checksums of original and copied object; compares copied object user metadata with * the source object user metadata; */ @Test fun shouldCopyObjectWithSourceUserMetadata(testInfo: TestInfo) { val bucketName = givenBucketV1(testInfo) val uploadFile = File(UPLOAD_FILE_NAME) val sourceKey = UPLOAD_FILE_NAME val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/$sourceKey/withSourceObjectUserMetadata" val sourceObjectMetadata = ObjectMetadata() sourceObjectMetadata.addUserMetadata("key", "value") val putObjectRequest = PutObjectRequest(bucketName, sourceKey, uploadFile) putObjectRequest.metadata = sourceObjectMetadata val putObjectResult = s3Client.putObject(putObjectRequest) val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) s3Client.copyObject(copyObjectRequest) val copiedObject = s3Client.getObject(destinationBucketName, destinationKey) val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent) copiedObject.close() assertThat(copiedDigest) .`as`("Source file and copied File should have same digests") .isEqualTo(putObjectResult.eTag) assertThat(copiedObject.objectMetadata.userMetadata) .`as`("User metadata should be identical!") .isEqualTo(sourceObjectMetadata.userMetadata) } /** * Copy an object to a key needing URL escaping. * * @see .shouldCopyObject */ @Test fun shouldCopyObjectToKeyNeedingEscaping(testInfo: TestInfo) { val bucketName = givenBucketV1(testInfo) val uploadFile = File(UPLOAD_FILE_NAME) val sourceKey = UPLOAD_FILE_NAME val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/some escape-worthy characters %$@ $sourceKey" val putObjectResult = s3Client.putObject(PutObjectRequest(bucketName, sourceKey, uploadFile)) val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) s3Client.copyObject(copyObjectRequest) val copiedObject = s3Client.getObject(destinationBucketName, destinationKey) val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent) copiedObject.close() assertThat(copiedDigest) .`as`("Source file and copied File should have same digests") .isEqualTo(putObjectResult.eTag) } /** * Copy an object from a key needing URL escaping. * * @see .shouldCopyObject */ @Test fun shouldCopyObjectFromKeyNeedingEscaping(testInfo: TestInfo) { val bucketName = givenBucketV1(testInfo) val uploadFile = File(UPLOAD_FILE_NAME) val sourceKey = "some escape-worthy characters %$@ $UPLOAD_FILE_NAME" val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/$sourceKey" val putObjectResult = s3Client.putObject(PutObjectRequest(bucketName, sourceKey, uploadFile)) val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) s3Client.copyObject(copyObjectRequest) val copiedObject = s3Client.getObject(destinationBucketName, destinationKey) val copiedDigest = DigestUtil.hexDigest(copiedObject.objectContent) copiedObject.close() assertThat(copiedDigest) .`as`("Source file and copied File should have same digests") .isEqualTo(putObjectResult.eTag) } /** * Puts an Object; Copies that object to a new bucket; Downloads the object from the new bucket; * compares checksums of original and copied object. */ @Test @Throws(Exception::class) fun shouldCopyObjectEncrypted(testInfo: TestInfo) { val bucketName = givenBucketV1(testInfo) val uploadFile = File(UPLOAD_FILE_NAME) val sourceKey = UPLOAD_FILE_NAME s3Client.putObject(PutObjectRequest(bucketName, sourceKey, uploadFile)) val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf/$sourceKey" val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) copyObjectRequest.sseAwsKeyManagementParams = SSEAwsKeyManagementParams(TEST_ENC_KEY_ID) val copyObjectResult = s3Client.copyObject(copyObjectRequest) val metadata = s3Client.getObjectMetadata(destinationBucketName, destinationKey) val uploadFileIs: InputStream = FileInputStream(uploadFile) val uploadDigest = DigestUtil.hexDigest(TEST_ENC_KEY_ID, uploadFileIs) assertThat(copyObjectResult.eTag) .`as`("ETag should match") .isEqualTo(uploadDigest) assertThat(metadata.contentLength) .`as`("Files should have the same length") .isEqualTo(uploadFile.length()) } /** * Tests that an object won't be copied with wrong encryption Key. */ @Test fun shouldNotObjectCopyWithWrongEncryptionKey(testInfo: TestInfo) { val sourceKey = UPLOAD_FILE_NAME val (bucketName, _) = givenBucketAndObjectV1(testInfo, sourceKey) val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf$sourceKey" val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) copyObjectRequest.sseAwsKeyManagementParams = SSEAwsKeyManagementParams(TEST_WRONG_KEY_ID) assertThatThrownBy { s3Client.copyObject(copyObjectRequest) } .isInstanceOf(AmazonS3Exception::class.java) .hasMessageContaining("Status Code: 400; Error Code: KMS.NotFoundException") } /** * Tests that a copy request for a non-existing object throws the correct error. */ @Test fun shouldThrowNoSuchKeyOnCopyForNonExistingKey(testInfo: TestInfo) { val bucketName = givenBucketV1(testInfo) val sourceKey = randomName val destinationBucketName = givenRandomBucketV1() val destinationKey = "copyOf$sourceKey" val copyObjectRequest = CopyObjectRequest(bucketName, sourceKey, destinationBucketName, destinationKey) assertThatThrownBy { s3Client.copyObject(copyObjectRequest) } .isInstanceOf(AmazonS3Exception::class.java) .hasMessageContaining("Status Code: 404; Error Code: NoSuchKey") } @Test fun multipartCopy() { //content larger than default part threshold of 5MiB val contentLen = 10 * _1MB val objectMetadata = ObjectMetadata() objectMetadata.contentLength = contentLen.toLong() val assumedSourceKey = UUID.randomUUID().toString() val sourceBucket = givenRandomBucketV1() val targetBucket = givenRandomBucketV1() val transferManager = createTransferManager() val upload = transferManager .upload( sourceBucket, assumedSourceKey, randomInputStream(contentLen), objectMetadata ) val uploadResult = upload.waitForUploadResult() assertThat(uploadResult.key).isEqualTo(assumedSourceKey) val assumedDestinationKey = UUID.randomUUID().toString() val copy = transferManager.copy( sourceBucket, assumedSourceKey, targetBucket, assumedDestinationKey ) val copyResult = copy.waitForCopyResult() assertThat(copyResult.destinationKey).isEqualTo(assumedDestinationKey) assertThat(uploadResult.eTag) .`as`("Hashes for source and target S3Object do not match.") .isEqualTo(copyResult.eTag) } }
3285210315
integration-tests/src/test/kotlin/com/adobe/testing/s3mock/its/CopyObjectV1IT.kt
// GENERATED package com.fkorotkov.kubernetes import io.fabric8.kubernetes.api.model.CSIPersistentVolumeSource as model_CSIPersistentVolumeSource import io.fabric8.kubernetes.api.model.CSIVolumeSource as model_CSIVolumeSource import io.fabric8.kubernetes.api.model.LocalObjectReference as model_LocalObjectReference import io.fabric8.kubernetes.api.model.SecretReference as model_SecretReference fun model_CSIPersistentVolumeSource.`nodePublishSecretRef`(block: model_SecretReference.() -> Unit = {}) { if(this.`nodePublishSecretRef` == null) { this.`nodePublishSecretRef` = model_SecretReference() } this.`nodePublishSecretRef`.block() } fun model_CSIVolumeSource.`nodePublishSecretRef`(block: model_LocalObjectReference.() -> Unit = {}) { if(this.`nodePublishSecretRef` == null) { this.`nodePublishSecretRef` = model_LocalObjectReference() } this.`nodePublishSecretRef`.block() }
1284884984
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/nodePublishSecretRef.kt
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.preference import android.content.Context import android.util.AttributeSet import im.vector.util.VectorUtils import org.matrix.androidsdk.MXSession import org.matrix.androidsdk.data.Room /** * Specialized class to target a Room avatar preference. * Based don the avatar preference class it redefines refreshAvatar() and * add the new method setConfiguration(). */ class RoomAvatarPreference : UserAvatarPreference { private var mRoom: Room? = null constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) override fun refreshAvatar() { if (null != mAvatarView && null != mRoom) { VectorUtils.loadRoomAvatar(context, mSession, mAvatarView, mRoom) } } fun setConfiguration(aSession: MXSession, aRoom: Room) { mSession = aSession mRoom = aRoom refreshAvatar() } }
1537895136
vector/src/main/java/im/vector/preference/RoomAvatarPreference.kt
package com.mikepenz.materialdrawer.model import android.view.View import android.widget.CompoundButton import android.widget.ToggleButton import androidx.annotation.LayoutRes import com.mikepenz.materialdrawer.R import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener import com.mikepenz.materialdrawer.model.interfaces.Checkable import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem /** * An abstract [IDrawerItem] implementation describing a drawerItem with support for a toggle */ open class AbstractToggleableDrawerItem<Item : AbstractToggleableDrawerItem<Item>> : Checkable, BaseDescribeableDrawerItem<Item, AbstractToggleableDrawerItem.ViewHolder>() { var isToggleEnabled = true override var isChecked = false var onCheckedChangeListener: OnCheckedChangeListener? = null override val type: Int get() = R.id.material_drawer_item_primary_toggle override val layoutRes: Int @LayoutRes get() = R.layout.material_drawer_item_toggle private val checkedChangeListener = object : CompoundButton.OnCheckedChangeListener { override fun onCheckedChanged(buttonView: CompoundButton, ic: Boolean) { if (isEnabled) { isChecked = ic onCheckedChangeListener?.onCheckedChanged(this@AbstractToggleableDrawerItem, buttonView, ic) } else { buttonView.setOnCheckedChangeListener(null) buttonView.isChecked = !ic buttonView.setOnCheckedChangeListener(this) } } } @Deprecated("Please consider to replace with the actual property setter") fun withToggleEnabled(toggleEnabled: Boolean): Item { this.isToggleEnabled = toggleEnabled return this as Item } @Deprecated("Please consider to replace with the actual property setter") fun withOnCheckedChangeListener(onCheckedChangeListener: OnCheckedChangeListener): Item { this.onCheckedChangeListener = onCheckedChangeListener return this as Item } override fun bindView(holder: ViewHolder, payloads: List<Any>) { super.bindView(holder, payloads) //bind the basic view parts bindViewHelper(holder) //handle the toggle holder.toggle.setOnCheckedChangeListener(null) holder.toggle.isChecked = isChecked holder.toggle.setOnCheckedChangeListener(checkedChangeListener) holder.toggle.isEnabled = isToggleEnabled //add a onDrawerItemClickListener here to be able to check / uncheck if the drawerItem can't be selected withOnDrawerItemClickListener { v, item, position -> if (!isSelectable) { isChecked = !isChecked holder.toggle.isChecked = isChecked } false } //call the onPostBindView method to trigger post bind view actions (like the listener to modify the item if required) onPostBindView(this, holder.itemView) } override fun getViewHolder(v: View): ViewHolder { return ViewHolder(v) } open class ViewHolder internal constructor(view: View) : BaseViewHolder(view) { internal val toggle: ToggleButton = view.findViewById<ToggleButton>(R.id.material_drawer_toggle) } }
738839465
materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/AbstractToggleableDrawerItem.kt
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.processor import COMMON import androidx.room.ColumnInfo import androidx.room.Dao import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.Query import androidx.room.RawQuery import androidx.room.ext.PagingTypeNames import androidx.room.ext.SupportDbTypeNames import androidx.room.ext.hasAnnotation import androidx.room.ext.typeName import androidx.room.processor.ProcessorErrors.RAW_QUERY_STRING_PARAMETER_REMOVED import androidx.room.testing.TestInvocation import androidx.room.testing.TestProcessor import androidx.room.vo.RawQueryMethod import com.google.auto.common.MoreElements import com.google.auto.common.MoreTypes import com.google.common.truth.Truth import com.google.testing.compile.CompileTester import com.google.testing.compile.JavaFileObjects import com.google.testing.compile.JavaSourcesSubjectFactory import com.squareup.javapoet.ArrayTypeName import com.squareup.javapoet.ClassName import com.squareup.javapoet.TypeName import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class RawQueryMethodProcessorTest { @Test fun supportRawQuery() { singleQueryMethod( """ @RawQuery abstract public int[] foo(SupportSQLiteQuery query); """) { query, _ -> assertThat(query.name, `is`("foo")) assertThat(query.runtimeQueryParam, `is`( RawQueryMethod.RuntimeQueryParameter( paramName = "query", type = SupportDbTypeNames.QUERY ) )) assertThat(query.returnType.typeName(), `is`(ArrayTypeName.of(TypeName.INT) as TypeName)) }.compilesWithoutError() } @Test fun stringRawQuery() { singleQueryMethod( """ @RawQuery abstract public int[] foo(String query); """) { _, _ -> }.failsToCompile().withErrorContaining(RAW_QUERY_STRING_PARAMETER_REMOVED) } @Test fun withObservedEntities() { singleQueryMethod( """ @RawQuery(observedEntities = User.class) abstract public LiveData<User> foo(SupportSQLiteQuery query); """) { query, _ -> assertThat(query.name, `is`("foo")) assertThat(query.runtimeQueryParam, `is`( RawQueryMethod.RuntimeQueryParameter( paramName = "query", type = SupportDbTypeNames.QUERY ) )) assertThat(query.observedTableNames.size, `is`(1)) assertThat(query.observedTableNames, `is`(setOf("User"))) }.compilesWithoutError() } @Test fun observableWithoutEntities() { singleQueryMethod( """ @RawQuery(observedEntities = {}) abstract public LiveData<User> foo(SupportSQLiteQuery query); """) { query, _ -> assertThat(query.name, `is`("foo")) assertThat(query.runtimeQueryParam, `is`( RawQueryMethod.RuntimeQueryParameter( paramName = "query", type = SupportDbTypeNames.QUERY ) )) assertThat(query.observedTableNames, `is`(emptySet())) }.failsToCompile() .withErrorContaining(ProcessorErrors.OBSERVABLE_QUERY_NOTHING_TO_OBSERVE) } @Test fun observableWithoutEntities_dataSourceFactory() { singleQueryMethod( """ @RawQuery abstract public ${PagingTypeNames.DATA_SOURCE_FACTORY}<Integer, User> getOne(); """) { _, _ -> // do nothing }.failsToCompile() .withErrorContaining(ProcessorErrors.OBSERVABLE_QUERY_NOTHING_TO_OBSERVE) } @Test fun observableWithoutEntities_positionalDataSource() { singleQueryMethod( """ @RawQuery abstract public ${PagingTypeNames.POSITIONAL_DATA_SOURCE}<User> getOne(); """) { _, _ -> // do nothing }.failsToCompile() .withErrorContaining(ProcessorErrors.OBSERVABLE_QUERY_NOTHING_TO_OBSERVE) } @Test fun positionalDataSource() { singleQueryMethod( """ @RawQuery(observedEntities = {User.class}) abstract public ${PagingTypeNames.POSITIONAL_DATA_SOURCE}<User> getOne( SupportSQLiteQuery query); """) { _, _ -> // do nothing }.compilesWithoutError() } @Test fun pojo() { val pojo: TypeName = ClassName.get("foo.bar.MyClass", "MyPojo") singleQueryMethod( """ public class MyPojo { public String foo; public String bar; } @RawQuery abstract public MyPojo foo(SupportSQLiteQuery query); """) { query, _ -> assertThat(query.name, `is`("foo")) assertThat(query.runtimeQueryParam, `is`( RawQueryMethod.RuntimeQueryParameter( paramName = "query", type = SupportDbTypeNames.QUERY ) )) assertThat(query.returnType.typeName(), `is`(pojo)) assertThat(query.observedTableNames, `is`(emptySet())) }.compilesWithoutError() } @Test fun void() { singleQueryMethod( """ @RawQuery abstract public void foo(SupportSQLiteQuery query); """) { _, _ -> }.failsToCompile().withErrorContaining( ProcessorErrors.RAW_QUERY_BAD_RETURN_TYPE ) } @Test fun noArgs() { singleQueryMethod( """ @RawQuery abstract public int[] foo(); """) { _, _ -> }.failsToCompile().withErrorContaining( ProcessorErrors.RAW_QUERY_BAD_PARAMS ) } @Test fun tooManyArgs() { singleQueryMethod( """ @RawQuery abstract public int[] foo(SupportSQLiteQuery query, SupportSQLiteQuery query2); """) { _, _ -> }.failsToCompile().withErrorContaining( ProcessorErrors.RAW_QUERY_BAD_PARAMS ) } @Test fun varargs() { singleQueryMethod( """ @RawQuery abstract public int[] foo(SupportSQLiteQuery... query); """) { _, _ -> }.failsToCompile().withErrorContaining( ProcessorErrors.RAW_QUERY_BAD_PARAMS ) } @Test fun observed_notAnEntity() { singleQueryMethod( """ @RawQuery(observedEntities = {${COMMON.NOT_AN_ENTITY_TYPE_NAME}.class}) abstract public int[] foo(SupportSQLiteQuery query); """) { _, _ -> }.failsToCompile().withErrorContaining( ProcessorErrors.rawQueryBadEntity(COMMON.NOT_AN_ENTITY_TYPE_NAME) ) } @Test fun observed_relationPojo() { singleQueryMethod( """ public static class MyPojo { public String foo; @Relation( parentColumn = "foo", entityColumn = "name" ) public java.util.List<User> users; } @RawQuery(observedEntities = MyPojo.class) abstract public int[] foo(SupportSQLiteQuery query); """) { method, _ -> assertThat(method.observedTableNames, `is`(setOf("User"))) }.compilesWithoutError() } @Test fun observed_embedded() { singleQueryMethod( """ public static class MyPojo { public String foo; @Embedded public User users; } @RawQuery(observedEntities = MyPojo.class) abstract public int[] foo(SupportSQLiteQuery query); """) { method, _ -> assertThat(method.observedTableNames, `is`(setOf("User"))) }.compilesWithoutError() } private fun singleQueryMethod( vararg input: String, handler: (RawQueryMethod, TestInvocation) -> Unit ): CompileTester { return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources()) .that(listOf(JavaFileObjects.forSourceString("foo.bar.MyClass", DAO_PREFIX + input.joinToString("\n") + DAO_SUFFIX ), COMMON.LIVE_DATA, COMMON.COMPUTABLE_LIVE_DATA, COMMON.USER, COMMON.DATA_SOURCE_FACTORY, COMMON.POSITIONAL_DATA_SOURCE, COMMON.NOT_AN_ENTITY)) .processedWith(TestProcessor.builder() .forAnnotations(Query::class, Dao::class, ColumnInfo::class, Entity::class, PrimaryKey::class, RawQuery::class) .nextRunHandler { invocation -> val (owner, methods) = invocation.roundEnv .getElementsAnnotatedWith(Dao::class.java) .map { Pair(it, invocation.processingEnv.elementUtils .getAllMembers(MoreElements.asType(it)) .filter { it.hasAnnotation(RawQuery::class) } ) }.first { it.second.isNotEmpty() } val parser = RawQueryMethodProcessor( baseContext = invocation.context, containing = MoreTypes.asDeclared(owner.asType()), executableElement = MoreElements.asExecutable(methods.first())) val parsedQuery = parser.process() handler(parsedQuery, invocation) true } .build()) } companion object { private const val DAO_PREFIX = """ package foo.bar; import androidx.annotation.NonNull; import androidx.room.*; import androidx.sqlite.db.SupportSQLiteQuery; import androidx.lifecycle.LiveData; @Dao abstract class MyClass { """ private const val DAO_SUFFIX = "}" } }
4214973657
room/compiler/src/test/kotlin/androidx/room/processor/RawQueryMethodProcessorTest.kt
package com.ivanovsky.passnotes.presentation.note_editor.view enum class TextInputLines { SINGLE_LINE, MULTIPLE_LINES }
2602981785
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/note_editor/view/TextInputLines.kt
package com.ivanovsky.passnotes.domain.interactor.filepicker import com.ivanovsky.passnotes.data.entity.FileDescriptor import com.ivanovsky.passnotes.data.entity.OperationResult import com.ivanovsky.passnotes.data.repository.file.FileSystemResolver class FilePickerInteractor(private val fileSystemResolver: FileSystemResolver) { fun getFileList(dir: FileDescriptor): OperationResult<List<FileDescriptor>> { return fileSystemResolver.resolveProvider(dir.fsAuthority).listFiles(dir) } fun getParent(file: FileDescriptor): OperationResult<FileDescriptor> { return fileSystemResolver.resolveProvider(file.fsAuthority).getParent(file) } }
1170112905
app/src/main/kotlin/com/ivanovsky/passnotes/domain/interactor/filepicker/FilePickerInteractor.kt
package nl.deltadak.plep.ui.taskcell import javafx.geometry.Pos import javafx.scene.control.CheckBox import javafx.scene.control.ComboBox import javafx.scene.control.Label import javafx.scene.control.TreeItem import javafx.scene.layout.HBox import javafx.scene.layout.Priority import javafx.scene.layout.Region import javafx.scene.text.TextAlignment import nl.deltadak.plep.HomeworkTask import nl.deltadak.plep.database.tables.Colors import nl.deltadak.plep.ui.taskcell.components.textlabel.TextLabelStyle import nl.deltadak.plep.ui.taskcell.util.blockerlisteners.ChangeListenerWithBlocker import nl.deltadak.plep.ui.taskcell.util.blockerlisteners.InvalidationListenerWithBlocker import nl.deltadak.plep.ui.util.LABEL_MAGIK /** * Manages the layout of a TreeCell. Always contains a CheckBox and a Label (text). Also contains a ComboBox (dropdown menu) if the Cell is the root of a task. * The given components are updated with the correct layout. * * @property taskCell Cell to set layout on. * @property doneChangeListener Should provide the ability to temporarily block the listener of the checkbox. * @property checkBox Checkbox of the task. * @property label Text of the task. * @property labelChangeListener Should provide the ability to temporarily block the listener of the combobox. * @property root Root item of the TreeView in which the task is. * @property comboBox Combobox of the task. */ class TaskLayout(private val taskCell: TaskCell, private val doneChangeListener: ChangeListenerWithBlocker<Boolean>, private val checkBox: CheckBox, val label: Label, private val labelChangeListener: InvalidationListenerWithBlocker, val root: TreeItem<HomeworkTask>, private val comboBox: ComboBox<String>) { /** * Updates the layout. * The homeworktask could be null, since updating is initiated by JavaFX. * * @param homeworkTask The Homework task to be displayed in the Cell. */ fun update(homeworkTask: HomeworkTask?) { if (taskCell.isEmpty) { taskCell.graphic = null taskCell.text = null } else { if (homeworkTask != null) { setLayout(homeworkTask) } } } private fun setLayout(homeworkTask: HomeworkTask) { // Create the container for components. val cellBox = HBox(10.0) cellBox.alignment = Pos.CENTER_LEFT setCheckBox(homeworkTask) setTextLabel(homeworkTask) // Get style from the database and apply to the item. val color = Colors.get(homeworkTask.colorID) taskCell.style = "-fx-control-inner-background: #$color" TextLabelStyle().setDoneStyle(homeworkTask.done, label, comboBox) // If the item is top level, a parent task, it has to show a course label (ComboBox), and it has to have a context menu. if (taskCell.treeItem.parent == root) { val region = setComboBox(homeworkTask) cellBox.children.addAll(checkBox, label, region, comboBox) taskCell.graphic = cellBox taskCell.text = null } else { // Set up subtask, with context menu disabled. with(taskCell) { contextMenu = null graphic = cellBox.apply { children.addAll(checkBox, label) } text = null } } } /** * Setup checkbox. */ private fun setCheckBox(homeworkTask: HomeworkTask) { // Block the listener on the checkbox when we manually toggle it, so it corresponds to the value in the database. doneChangeListener.block = true val done = homeworkTask.done // Manually toggle, if necessary. checkBox.isSelected = done doneChangeListener.block = false } /** * Setup text label. */ private fun setTextLabel(homeworkTask: HomeworkTask) { with(label) { text = homeworkTask.text prefWidthProperty().bind(taskCell.treeView.widthProperty().subtract(LABEL_MAGIK)) isWrapText = true textAlignment = TextAlignment.JUSTIFY } } /** * Setup combobox. */ private fun setComboBox(homeworkTask: HomeworkTask): Region { // Before setting value, we need to temporarily disable the listener, otherwise it fires and goes unnecessarily updating the database, which takes a lot of time. labelChangeListener.block = true comboBox.value = homeworkTask.label labelChangeListener.block = false // Create a region to make sure that the ComboBox is aligned on the right. val region = Region() HBox.setHgrow(region, Priority.ALWAYS) return region } }
2527412726
src/main/kotlin/nl/deltadak/plep/ui/taskcell/TaskLayout.kt
package com.orgzly.android.query class QueryTokenizer(val str: String, private val groupOpen: String, private val groupClose: String) { val tokens = tokanize(str) var nextToken = 0 fun hasMoreTokens(): Boolean = nextToken < tokens.size fun nextToken() = tokens[nextToken++] private fun tokanize(str: String): List<String> { return tokenRegex.findAll(str).map { it.value }.toList() } companion object { val TAG: String = QueryTokenizer::class.java.name private const val char = """[^")(\s]""" private const val doubleQuoted = """"[^"\\]*(?:\\.[^"\\]*)*"""" private const val doubleQuotedWithPrefix = """$char*$doubleQuoted""" private const val groupOpener = """\(""" private const val groupCloser = """\)""" private const val rest = """$char+""" private val tokenRegex = listOf(doubleQuotedWithPrefix, groupOpener, groupCloser, rest) .joinToString("|").toRegex() fun unquote(s: String): String { if (s.length < 2) { return s } val first = s[0] val last = s[s.length - 1] if (first != last || first != '"') { return s } val b = StringBuilder(s.length - 2) var quote = false for (i in 1 until s.length - 1) { val c = s[i] if (c == '\\' && !quote) { quote = true continue } quote = false b.append(c) } return b.toString() } fun quote(s: String, delim: String): String { if (s.isEmpty()) { return "\"\"" } for (element in s) { if (element == '"' || element == '\\' || delim.indexOf(element) >= 0) { return quoteUnconditionally(s) } } return s } fun quoteUnconditionally(s: String): String { val builder = StringBuilder(s.length + 8) builder.append('"') for (element in s) { if (element == '"') { builder.append('\\') } builder.append(element) continue } builder.append('"') return builder.toString() } } }
1169657403
app/src/main/java/com/orgzly/android/query/QueryTokenizer.kt
package com.orgzly.android.ui.drawer import android.content.Intent import android.content.res.Resources import android.view.Menu import androidx.lifecycle.Observer import com.google.android.material.navigation.NavigationView import com.orgzly.BuildConfig import com.orgzly.R import com.orgzly.android.AppIntent import com.orgzly.android.db.entity.BookAction import com.orgzly.android.db.entity.BookView import com.orgzly.android.db.entity.SavedSearch import com.orgzly.android.ui.books.BooksFragment import com.orgzly.android.ui.main.MainActivity import com.orgzly.android.ui.main.MainActivityViewModel import com.orgzly.android.ui.notes.book.BookFragment import com.orgzly.android.ui.notes.query.QueryFragment import com.orgzly.android.ui.savedsearches.SavedSearchesFragment import com.orgzly.android.util.LogUtils import java.util.* internal class DrawerNavigationView( private val activity: MainActivity, viewModel: MainActivityViewModel, navView: NavigationView) { private val menu: Menu = navView.menu private val menuItemIdMap = hashMapOf<String, Int>() private var activeFragmentTag: String? = null init { // Add mapping for groups menuItemIdMap[BooksFragment.drawerItemId] = R.id.books menuItemIdMap[SavedSearchesFragment.getDrawerItemId()] = R.id.searches // Setup intents menu.findItem(R.id.searches).intent = Intent(AppIntent.ACTION_OPEN_SAVED_SEARCHES) menu.findItem(R.id.books).intent = Intent(AppIntent.ACTION_OPEN_BOOKS) menu.findItem(R.id.settings).intent = Intent(AppIntent.ACTION_OPEN_SETTINGS) viewModel.books().observe(activity, Observer { refreshFromBooks(it) }) viewModel.savedSearches().observe(activity, Observer { refreshFromSavedSearches(it) }) } fun updateActiveFragment(fragmentTag: String) { this.activeFragmentTag = fragmentTag setActiveItem(fragmentTag) } private fun setActiveItem(fragmentTag: String) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, fragmentTag) this.activeFragmentTag = fragmentTag val fragment = activity.supportFragmentManager.findFragmentByTag(activeFragmentTag) // Uncheck all for (i in 0 until menu.size()) { menu.getItem(i).isChecked = false } if (fragment != null && fragment is DrawerItem) { val fragmentMenuItemId = fragment.getCurrentDrawerItemId() val itemId = menuItemIdMap[fragmentMenuItemId] if (itemId != null) { menu.findItem(itemId)?.isChecked = true } } } private fun refreshFromSavedSearches(savedSearches: List<SavedSearch>) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, savedSearches.size) removeItemsWithOrder(1) savedSearches.forEach { savedSearch -> val intent = Intent(AppIntent.ACTION_OPEN_QUERY) intent.putExtra(AppIntent.EXTRA_QUERY_STRING, savedSearch.query) val id = generateRandomUniqueId() val item = menu.add(R.id.drawer_group, id, 1, savedSearch.name) menuItemIdMap[QueryFragment.getDrawerItemId(savedSearch.query)] = id item.intent = intent item.isCheckable = true } activeFragmentTag?.let { setActiveItem(it) } } private fun refreshFromBooks(books: List<BookView>) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, books.size) removeItemsWithOrder(3) books.forEach { book -> val intent = Intent(AppIntent.ACTION_OPEN_BOOK) intent.putExtra(AppIntent.EXTRA_BOOK_ID, book.book.id) val id = generateRandomUniqueId() val name = book.book.run { title ?: name } val item = menu.add(R.id.drawer_group, id, 3, name) item.isEnabled = !book.book.isDummy item.intent = intent item.isCheckable = true if (book.book.lastAction?.type == BookAction.Type.ERROR) { item.setActionView(R.layout.drawer_item_sync_failed) } else if (book.isOutOfSync()) { item.setActionView(R.layout.drawer_item_sync_needed) } menuItemIdMap[BookFragment.getDrawerItemId(book.book.id)] = id } activeFragmentTag?.let { setActiveItem(it) } } private fun generateRandomUniqueId(): Int { val rand = Random() while (true) { val id = rand.nextInt(Integer.MAX_VALUE) + 1 try { activity.resources.getResourceName(id) } catch (e: Resources.NotFoundException) { return id } } } private fun removeItemsWithOrder(orderToDelete: Int) { val itemIdsToRemove = HashSet<Int>() var i = 0 while (true) { val item = menu.getItem(i++) ?: break val order = item.order if (order > orderToDelete) { break } else if (order == orderToDelete) { itemIdsToRemove.add(item.itemId) } } for (id in itemIdsToRemove) { menu.removeItem(id) } } companion object { private val TAG = DrawerNavigationView::class.java.name } }
18121676
app/src/main/java/com/orgzly/android/ui/drawer/DrawerNavigationView.kt
package com.piticlistudio.playednext.data.entity.mapper.datasources.image import com.piticlistudio.playednext.data.entity.giantbomb.GiantbombGameImage import com.piticlistudio.playednext.test.factory.DataFactory import com.piticlistudio.playednext.test.factory.GameImageFactory.Factory.makeGiantbombGameImage import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test /** * Test cases for [GiantbombImageMapper] * Created by e-jegi on 3/26/2018. */ internal class GiantbombImageMapperTest { private val mapper = GiantbombImageMapper() @Nested @DisplayName("When we call mapFromDataLayer") inner class MapFromModel { @Test fun `then should map into GameImage with medium url values`() { val response = makeGiantbombGameImage() val result = mapper.mapFromDataLayer(response) assertNotNull(result) with(result) { assertEquals(response.medium_url, result?.url) } } @Test fun `then should map into GameImage with screen_url value when medium_url is null`() { val response = GiantbombGameImage(icon_url = DataFactory.randomString(), medium_url = null, original_url = DataFactory.randomString(), screen_large_url = DataFactory.randomString(), screen_url = DataFactory.randomString(), small_url = DataFactory.randomString(), super_url = DataFactory.randomString(), thumb_url = DataFactory.randomString(), tiny_url = DataFactory.randomString()) val result = mapper.mapFromDataLayer(response) assertNotNull(result) with(result) { assertEquals(response.screen_url, result?.url) } } @Test fun `then should map into GameImage with screen_large_url value when medium_url and screen_url are null`() { val response = GiantbombGameImage(icon_url = DataFactory.randomString(), medium_url = null, original_url = DataFactory.randomString(), screen_large_url = DataFactory.randomString(), screen_url = null, small_url = DataFactory.randomString(), super_url = DataFactory.randomString(), thumb_url = DataFactory.randomString(), tiny_url = DataFactory.randomString()) val result = mapper.mapFromDataLayer(response) assertNotNull(result) with(result) { assertEquals(response.screen_large_url, result?.url) } } @Test fun `then should map into GameImage with small_url value when medium_url, screen_url and screen_large_url are null`() { val response = GiantbombGameImage(icon_url = DataFactory.randomString(), medium_url = null, original_url = DataFactory.randomString(), screen_large_url = null, screen_url = null, small_url = DataFactory.randomString(), super_url = DataFactory.randomString(), thumb_url = DataFactory.randomString(), tiny_url = DataFactory.randomString()) val result = mapper.mapFromDataLayer(response) assertNotNull(result) with(result) { assertEquals(response.small_url, result?.url) } } @Test fun `then should map into GameImage with original_url value when medium_url, screen_url, screen_large_url and small_url are null`() { val response = GiantbombGameImage(icon_url = DataFactory.randomString(), medium_url = null, original_url = DataFactory.randomString(), screen_large_url = null, screen_url = null, small_url = null, super_url = DataFactory.randomString(), thumb_url = DataFactory.randomString(), tiny_url = DataFactory.randomString()) val result = mapper.mapFromDataLayer(response) assertNotNull(result) with(result) { assertEquals(response.original_url, result?.url) } } @Test fun `then should return null if no available url to map from`() { val response = GiantbombGameImage(icon_url = DataFactory.randomString(), medium_url = null, original_url = null, screen_large_url = null, screen_url = null, small_url = null, super_url = DataFactory.randomString(), thumb_url = DataFactory.randomString(), tiny_url = DataFactory.randomString()) val result = mapper.mapFromDataLayer(response) assertNull(result) } } }
1290271119
app/src/test/java/com/piticlistudio/playednext/data/entity/mapper/datasources/image/GiantbombImageMapperTest.kt
package fr.free.nrw.commons import android.content.ContentProviderClient import android.content.Context import android.content.SharedPreferences import android.support.v4.util.LruCache import com.nhaarman.mockito_kotlin.mock import com.squareup.leakcanary.RefWatcher import fr.free.nrw.commons.auth.AccountUtil import fr.free.nrw.commons.auth.SessionManager import fr.free.nrw.commons.data.DBOpenHelper import fr.free.nrw.commons.di.CommonsApplicationComponent import fr.free.nrw.commons.di.CommonsApplicationModule import fr.free.nrw.commons.di.DaggerCommonsApplicationComponent import fr.free.nrw.commons.location.LocationServiceManager import fr.free.nrw.commons.mwapi.MediaWikiApi import fr.free.nrw.commons.nearby.NearbyPlaces import fr.free.nrw.commons.upload.UploadController class TestCommonsApplication : CommonsApplication() { private var mockApplicationComponent: CommonsApplicationComponent? = null override fun onCreate() { if (mockApplicationComponent == null) { mockApplicationComponent = DaggerCommonsApplicationComponent.builder() .appModule(MockCommonsApplicationModule(this)).build() } super.onCreate() } // No leakcanary in unit tests. override fun setupLeakCanary(): RefWatcher = RefWatcher.DISABLED } @Suppress("MemberVisibilityCanBePrivate") class MockCommonsApplicationModule(appContext: Context) : CommonsApplicationModule(appContext) { val accountUtil: AccountUtil = mock() val appSharedPreferences: SharedPreferences = mock() val defaultSharedPreferences: SharedPreferences = mock() val otherSharedPreferences: SharedPreferences = mock() val uploadController: UploadController = mock() val mockSessionManager: SessionManager = mock() val locationServiceManager: LocationServiceManager = mock() val mockDbOpenHelper: DBOpenHelper = mock() val nearbyPlaces: NearbyPlaces = mock() val lruCache: LruCache<String, String> = mock() val categoryClient: ContentProviderClient = mock() val contributionClient: ContentProviderClient = mock() val modificationClient: ContentProviderClient = mock() val uploadPrefs: SharedPreferences = mock() override fun provideCategoryContentProviderClient(context: Context?): ContentProviderClient = categoryClient override fun provideContributionContentProviderClient(context: Context?): ContentProviderClient = contributionClient override fun provideModificationContentProviderClient(context: Context?): ContentProviderClient = modificationClient override fun providesDirectNearbyUploadPreferences(context: Context?): SharedPreferences = uploadPrefs override fun providesAccountUtil(context: Context): AccountUtil = accountUtil override fun providesApplicationSharedPreferences(context: Context): SharedPreferences = appSharedPreferences override fun providesDefaultSharedPreferences(context: Context): SharedPreferences = defaultSharedPreferences override fun providesOtherSharedPreferences(context: Context): SharedPreferences = otherSharedPreferences override fun providesUploadController(sessionManager: SessionManager, sharedPreferences: SharedPreferences, context: Context): UploadController = uploadController override fun providesSessionManager(context: Context, mediaWikiApi: MediaWikiApi, sharedPreferences: SharedPreferences): SessionManager = mockSessionManager override fun provideLocationServiceManager(context: Context): LocationServiceManager = locationServiceManager override fun provideDBOpenHelper(context: Context): DBOpenHelper = mockDbOpenHelper override fun provideNearbyPlaces(): NearbyPlaces = nearbyPlaces override fun provideLruCache(): LruCache<String, String> = lruCache }
2577388714
app/src/test/kotlin/fr/free/nrw/commons/TestCommonsApplication.kt
package io.sonatalang.snc.frontend.domain.token object NewLineToken : BasicToken(false), TokenFactory<NewLineToken> { override fun with(character: Char) = this override fun toString() = "\n" override fun isSuitable(character: Char) = character == '\n' override fun create(character: Char) = NewLineToken }
3518168341
frontend/src/main/kotlin/io/sonatalang/snc/frontend/domain/token/NewLineToken.kt
package com.openconference.sessiondetails.presentationmodel import com.openconference.model.Session import org.threeten.bp.LocalDateTime import org.threeten.bp.ZoneId import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.format.FormatStyle import java.util.* /** * Responsible to transform a Session to [SessionDetailItem] * * @author Hannes Dorfmann */ interface SessionDetailsPresentationModelTransformer { fun transform(session: Session): SessionDetail } /** * Phone Session Details Presentation Model Transformer * @author Hannes Dorfmann */ // TODO Tablet class PhoneSessionDetailsPresentationModelTransformer : SessionDetailsPresentationModelTransformer { private val dateFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) override fun transform(session: Session): SessionDetail { val items = ArrayList<SessionDetailItem>() // TODO use settings for time zone (users preferences) val zoneId = ZoneId.systemDefault() val start = session.startTime() val localStart = if (start == null) null else LocalDateTime.ofInstant(start, zoneId) val end = session.endTime() val localEnd = if (end == null) null else LocalDateTime.ofInstant(end, zoneId) if (start != null) { val dateStr = if (end != null) { "${dateFormatter.format(localStart)} - ${dateFormatter.format(localEnd)}" } else { dateFormatter.format(localStart) } items.add(SessionDateTimeItem(dateStr)) } // Location val locationName = session.locationName() if (locationName != null) items.add(SessionLocationItem(locationName)) // Description val description = session.description() if (description != null) { if (items.isNotEmpty()) items.add(SessionSeparatorItem()) items.add(SessionDescriptionItem(description)) } // TODO TAGS // Tags /* val tags = session.tags() if (tags != null) items.add(SessionTagsItem(tags)) */ // Speakers if (session.speakers().isNotEmpty()) { items.add(SessionSeparatorItem()) } session.speakers().forEach { items.add(SessionSpeakerItem(it)) } // TODO refactor return SessionDetail(session.id(), session.title(), session, items, session.favorite()) } }
2119214681
app/src/main/java/com/openconference/sessiondetails/presentationmodel/SessionDetailsPresentationModelTransformer.kt
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.analysis.impl import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy import com.google.android.libraries.pcc.chronicle.api.StorageMedia import com.google.android.libraries.pcc.chronicle.api.policy.annotation.Annotation import com.google.common.truth.Truth.assertThat import java.time.Duration import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class AnnotationTest { @Test fun duration_toAnnotation() { assertThat(Duration.ofMillis(150).toAnnotation()).isEqualTo(Annotation.createTtl("0 minutes")) assertThat(Duration.ofMillis(1500).toAnnotation()).isEqualTo(Annotation.createTtl("0 minutes")) assertThat(Duration.ofSeconds(60).toAnnotation()).isEqualTo(Annotation.createTtl("1 minutes")) assertThat(Duration.ofDays(10).toAnnotation()) .isEqualTo(Annotation.createTtl("${Duration.ofDays(10).toMinutes()} minutes")) } @Test fun managementStrategy_toAnnotations_passThru() { val annotations = ManagementStrategy.PassThru.toAnnotations() assertThat(annotations).containsExactly(ANNOTATION_IN_MEMORY) } @Test fun managementStrategy_toAnnotations_storedEncryptedLocalDiskNoTtl() { val annotations = ManagementStrategy.Stored(encrypted = true, media = StorageMedia.LOCAL_DISK, ttl = null) .toAnnotations() assertThat(annotations).containsExactly(ANNOTATION_PERSISTENT, ANNOTATION_ENCRYPTED) } @Test fun managementStrategy_toAnnotations_storedUnencryptedMemoryNoTtl() { val annotations = ManagementStrategy.Stored(encrypted = false, media = StorageMedia.MEMORY, ttl = null) .toAnnotations() assertThat(annotations).containsExactly(ANNOTATION_IN_MEMORY) } @Test fun managementStrategy_toAnnotations_storedUnencryptedMemoryTtl() { val annotations = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.MEMORY, ttl = Duration.ofMinutes(5) ) .toAnnotations() assertThat(annotations) .containsExactly(ANNOTATION_IN_MEMORY, Duration.ofMinutes(5).toAnnotation()) } @Test fun managementStrategy_toAnnotations_storedEncryptedRemoteTtl() { val annotations = ManagementStrategy.Stored( encrypted = true, media = StorageMedia.REMOTE_DISK, ttl = Duration.ofMinutes(500) ) .toAnnotations() assertThat(annotations) .containsExactly( ANNOTATION_REMOTE_PERSISTENT, ANNOTATION_ENCRYPTED, Duration.ofMinutes(500).toAnnotation() ) } }
2846956362
javatests/com/google/android/libraries/pcc/chronicle/analysis/impl/AnnotationTest.kt
package com.battlelancer.seriesguide.traktapi import android.content.Context import android.os.AsyncTask import android.os.Bundle import androidx.fragment.app.FragmentManager import com.battlelancer.seriesguide.provider.SgRoomDatabase.Companion.getInstance import com.battlelancer.seriesguide.util.TextTools import com.battlelancer.seriesguide.util.safeShow /** * Allows to check into an episode. Launching activities should subscribe to * [TraktTask.TraktActionCompleteEvent] to display status toasts. */ class CheckInDialogFragment : GenericCheckInDialogFragment() { override fun checkInTrakt(message: String) { TraktTask(requireContext()).checkInEpisode( requireArguments().getLong(ARG_EPISODE_ID), requireArguments().getString(ARG_ITEM_TITLE), message ).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } companion object { /** * Builds and shows a new [CheckInDialogFragment] setting all values based on the given * episode row ID. * * @return `false` if the fragment was not shown. */ fun show(context: Context, fragmentManager: FragmentManager, episodeId: Long): Boolean { val episode = getInstance(context).sgEpisode2Helper().getEpisodeWithShow(episodeId) ?: return false val f = CheckInDialogFragment() val args = Bundle() args.putLong(ARG_EPISODE_ID, episodeId) val episodeTitleWithNumbers = (episode.seriestitle + " " + TextTools.getNextEpisodeString( context, episode.season, episode.episodenumber, episode.episodetitle )) args.putString(ARG_ITEM_TITLE, episodeTitleWithNumbers) f.arguments = args return f.safeShow(fragmentManager, "checkInDialog") } } }
3532064690
app/src/main/java/com/battlelancer/seriesguide/traktapi/CheckInDialogFragment.kt
package cc.redpen.intellij import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.icons.AllIcons import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.LangDataKeys.PSI_FILE import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ProjectComponent import com.intellij.openapi.fileEditor.FileEditorManagerEvent import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.CustomStatusBarWidget import com.intellij.openapi.wm.StatusBarWidget import com.intellij.openapi.wm.StatusBarWidget.WidgetBorder.WIDE import com.intellij.openapi.wm.WindowManager import com.intellij.openapi.wm.impl.status.EditorBasedWidget import com.intellij.openapi.wm.impl.status.TextPanel import com.intellij.psi.PsiManager import com.intellij.ui.ClickListener import com.intellij.ui.awt.RelativePoint import com.intellij.util.ui.UIUtil import java.awt.Component import java.awt.Graphics import java.awt.Point import java.awt.event.MouseEvent open class StatusWidget constructor(project: Project) : EditorBasedWidget(project), CustomStatusBarWidget, ProjectComponent { val provider = RedPenProvider.forProject(project) var enabled: Boolean = false val actionGroupId = "RedPen " + project.basePath companion object { fun forProject(project: Project) = project.getComponent(StatusWidget::class.java)!! } var actionGroup: DefaultActionGroup? = null private val component = object: TextPanel.ExtraSize() { override fun paintComponent(g: Graphics) { super.paintComponent(g) if (enabled && text != null) { val arrows = AllIcons.Ide.Statusbar_arrows arrows.paintIcon(this, g, bounds.width - insets.right - arrows.iconWidth - 2, bounds.height / 2 - arrows.iconHeight / 2) } } } override fun projectOpened() { install(WindowManager.getInstance().getStatusBar(project)) myStatusBar.addWidget(this, "before Encoding") object : ClickListener() { override fun onClick(e: MouseEvent, clickCount: Int): Boolean { showPopup(e) return true } }.installOn(component) component.border = WIDE component.toolTipText = "RedPen language" registerActions() } override fun projectClosed() { myStatusBar.removeWidget(ID()) unregisterActions() } override fun getComponentName(): String = "StatusWidget" override fun initComponent() {} override fun disposeComponent() {} open fun registerActions() { val actionManager = ActionManager.getInstance() ?: return actionGroup = DefaultActionGroup() provider.configs.keys.forEach { key -> actionGroup!!.add(object : AnAction() { init { templatePresentation.text = key } override fun actionPerformed(e: AnActionEvent) { provider.setConfigFor(e.getData(PSI_FILE)!!, key) DaemonCodeAnalyzer.getInstance(e.project).restart() } }) } actionManager.registerAction(actionGroupId, actionGroup!!) } open internal fun unregisterActions() { ActionManager.getInstance()?.unregisterAction(actionGroupId) } override fun ID(): String { return "RedPen" } override fun getPresentation(platformType: StatusBarWidget.PlatformType): StatusBarWidget.WidgetPresentation? { return null } open fun update(configKey: String) { if (isDisposed) return ApplicationManager.getApplication().invokeLater { component.text = configKey component.foreground = if (enabled) UIUtil.getActiveTextColor() else UIUtil.getInactiveTextColor() } } override fun selectionChanged(event: FileEditorManagerEvent) { val file = if (event.newFile == null) null else PsiManager.getInstance(project!!).findFile(event.newFile!!) if (file != null && provider.getParser(file) != null) { enabled = true update(provider.getConfigKeyFor(file)) } else { enabled = false update("n/a") } } override fun getComponent(): TextPanel { return component } internal fun showPopup(e: MouseEvent) { if (!enabled) return val popup = JBPopupFactory.getInstance().createActionGroupPopup( "RedPen", actionGroup!!, getContext(), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false) val dimension = popup.content.preferredSize val at = Point(0, -dimension.height) popup.show(RelativePoint(e.component, at)) Disposer.register(this, popup) } private fun getContext(): DataContext { val editor = editor val parent = DataManager.getInstance().getDataContext(myStatusBar as Component) return SimpleDataContext.getSimpleContext( CommonDataKeys.VIRTUAL_FILE_ARRAY.name, arrayOf(selectedFile!!), SimpleDataContext.getSimpleContext(CommonDataKeys.PROJECT.name, project, SimpleDataContext.getSimpleContext(PlatformDataKeys.CONTEXT_COMPONENT.name, editor?.component, parent))) } fun rebuild() { unregisterActions() registerActions() } }
144039327
src/cc/redpen/intellij/StatusWidget.kt
package net import SearchResponse import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import data.Repository import java.io.PrintWriter import java.nio.file.Path class ProjectExtractor(val savePath: Path, val start:String, val end:String) { fun extract(page : Int = 0) { var results = HashMap<String, Repository>() var totalCount = 0 val requestBuilder = RequestBuilder(start, end) if(savePath.toFile().exists()) results = Gson().fromJson(savePath.toFile().readText(), object : TypeToken<HashMap<String, Repository>>() {}.type) requestBuilder.page = page; while(true) { val (request, response, result) = requestBuilder.build().responseObject(SearchResponse.Deserializer()); val (search, err) = result println(request.url) search?.let { search.items.forEach({ if(it.full_name.isNullOrEmpty() || it.language.isNullOrEmpty()) return@forEach if(!results.containsKey(it.full_name) && it.size < 2048000 && it.language.equals("Java")) { results.put(it.full_name, it); println("added ${it.full_name}") } }) totalCount += search.items.size; } if(requestBuilder.page > 34) break else if(err != null) { Thread.sleep(10000) }else if(search!!.items.isEmpty()) break else requestBuilder.page++; } savePath.toFile().printWriter().use { out: PrintWriter -> out.print(GsonBuilder().setPrettyPrinting().create().toJson(results)) } } }
2034555772
src/main/kotlin/net/ProjectExtractor.kt
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED import com.netflix.spinnaker.orca.events.ExecutionComplete import com.netflix.spinnaker.orca.pipeline.model.Execution import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import org.springframework.context.ApplicationListener import org.springframework.context.ConfigurableApplicationContext import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import java.util.function.Predicate /** * An [ApplicationListener] implementation you can use to wait for an execution * to complete. Much better than `Thread.sleep(whatever)` in your tests. */ class ExecutionLatch(private val predicate: Predicate<ExecutionComplete>) : ApplicationListener<ExecutionComplete> { private val latch = CountDownLatch(1) override fun onApplicationEvent(event: ExecutionComplete) { if (predicate.test(event)) { latch.countDown() } } fun await() = latch.await(10, TimeUnit.SECONDS) } fun ConfigurableApplicationContext.runToCompletion(execution: Execution, launcher: (Execution) -> Unit, repository: ExecutionRepository) { val latch = ExecutionLatch(Predicate { it.executionId == execution.id }) addApplicationListener(latch) launcher.invoke(execution) assert(latch.await()) { "Pipeline did not complete" } repository.waitForAllStagesToComplete(execution) } /** * Given parent and child pipelines: * 1) Start child pipeline * 2) Invoke parent pipeline and continue until completion * * Useful for testing failure interactions between pipelines. Child pipeline can be inspected prior to * completion, and subsequently completed via [runToCompletion]. */ fun ConfigurableApplicationContext.runParentToCompletion( parent: Execution, child: Execution, launcher: (Execution) -> Unit, repository: ExecutionRepository ) { val latch = ExecutionLatch(Predicate { it.executionId == parent.id }) addApplicationListener(latch) launcher.invoke(child) launcher.invoke(parent) assert(latch.await()) { "Pipeline did not complete" } repository.waitForAllStagesToComplete(parent) } fun ConfigurableApplicationContext.restartAndRunToCompletion(stage: Stage, launcher: (Execution, String) -> Unit, repository: ExecutionRepository) { val execution = stage.execution val latch = ExecutionLatch(Predicate { it.executionId == execution.id }) addApplicationListener(latch) launcher.invoke(execution, stage.id) assert(latch.await()) { "Pipeline did not complete after restarting" } repository.waitForAllStagesToComplete(execution) } private fun ExecutionRepository.waitForAllStagesToComplete(execution: Execution) { var complete = false while (!complete) { Thread.sleep(100) complete = retrieve(PIPELINE, execution.id) .run { status.isComplete && stages .map(Stage::getStatus) .all { it.isComplete || it == NOT_STARTED } } } }
1635152740
orca-queue-tck/src/main/kotlin/com/netflix/spinnaker/orca/q/ExecutionLatch.kt
/* * Copyright (C) 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 com.example.composemail.ui.utils import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.ConstraintSetScope @Composable fun rememberConstraintSet( key: Any = Unit, constraints: ConstraintSetScope.() -> Unit ): ConstraintSet { val constraintSet = remember(key) { ConstraintSet(constraints) } return constraintSet }
2783552708
demoProjects/ComposeMail/app/src/main/java/com/example/composemail/ui/utils/ConstraintUtils.kt
/* * Copyright 2022 Ren Binden * * 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.rpkit.permissions.bukkit.listener import com.rpkit.permissions.bukkit.RPKPermissionsBukkit import com.rpkit.permissions.bukkit.database.table.RPKProfileGroupTable import com.rpkit.players.bukkit.event.profile.RPKBukkitProfileDeleteEvent import org.bukkit.event.EventHandler import org.bukkit.event.Listener class RPKProfileDeleteListener(private val plugin: RPKPermissionsBukkit) : Listener { @EventHandler fun onProfileDelete(event: RPKBukkitProfileDeleteEvent) { val profileId = event.profile.id if (profileId != null) { plugin.database.getTable(RPKProfileGroupTable::class.java).delete(profileId) } } }
468279708
bukkit/rpk-permissions-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/listener/RPKProfileDeleteListener.kt
package test.assertk.assertions import assertk.assertThat import assertk.assertions.* import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails class MapTest { //region contains @Test fun contains_element_present_passes() { assertThat(mapOf("one" to 1, "two" to 2)).contains("two" to 2) } @Test fun contains_element_missing_fails() { val error = assertFails { assertThat(emptyMap<String, Int>()).contains("one" to 1) } assertEquals("expected to contain:<{\"one\"=1}> but was:<{}>", error.message) } @Test fun contains_element_with_nullable_value_missing_fails() { val error = assertFails { assertThat(emptyMap<String, Int?>()).contains("one" to null) } assertEquals("expected to contain:<{\"one\"=null}> but was:<{}>", error.message) } //endregion //region doesNotContain @Test fun doesNotContain_element_missing_passes() { assertThat(emptyMap<String, Int>()).doesNotContain("one" to 1) } @Test fun doesNotContain_element_with_missing_nullable_value_passes() { assertThat(emptyMap<String, Int?>()).doesNotContain("one" to null) } @Test fun doesNotContain_element_present_fails() { val error = assertFails { assertThat(mapOf("one" to 1, "two" to 2)).doesNotContain("two" to 2) } assertEquals("expected to not contain:<{\"two\"=2}> but was:<{\"one\"=1, \"two\"=2}>", error.message) } //endregion //region containsNone @Test fun containsNone_missing_elements_passes() { assertThat(emptyMap<String, Int>()).containsNone("one" to 1) } @Test fun containsNone_missing_elements_with_nullable_value_passes() { assertThat(emptyMap<String, Int?>()).containsNone("one" to null) } @Test fun containsNone_present_element_fails() { val error = assertFails { assertThat(mapOf("one" to 1, "two" to 2)).containsNone("two" to 2, "three" to 3) } assertEquals( """expected to contain none of:<{"two"=2, "three"=3}> but was:<{"one"=1, "two"=2}> | elements not expected:<{"two"=2}> """.trimMargin(), error.message ) } //region //region containsAll @Test fun containsAll_all_elements_passes() { assertThat(mapOf("one" to 1, "two" to 2)).containsAll("two" to 2, "one" to 1) } @Test fun containsAll_extra_elements_passes() { assertThat(mapOf("one" to 1, "two" to 2, "three" to 3)).containsAll("one" to 1, "two" to 2) } @Test fun containsAll_swapped_keys_and_values_fails() { val error = assertFails { assertThat(mapOf("one" to 2, "two" to 1)).containsAll("two" to 2, "one" to 1) } assertEquals( """expected to contain all:<{"two"=2, "one"=1}> but was:<{"one"=2, "two"=1}> | elements not found:<{"two"=2, "one"=1}> """.trimMargin(), error.message ) } @Test fun containsAll_nullable_values_fails() { val error = assertFails { assertThat(mapOf<String, Any?>()).containsAll("key" to null) } assertEquals( """expected to contain all:<{"key"=null}> but was:<{}> | elements not found:<{"key"=null}> """.trimMargin(), error.message ) } @Test fun containsAll_some_elements_fails() { val error = assertFails { assertThat(mapOf("one" to 1)).containsAll("one" to 1, "two" to 2) } assertEquals( """expected to contain all:<{"one"=1, "two"=2}> but was:<{"one"=1}> | elements not found:<{"two"=2}> """.trimMargin(), error.message ) } //endregion //region containsOnly @Test fun containsOnly_all_elements_passes() { assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("two" to 2, "one" to 1) } @Test fun containsOnly_swapped_keys_and_values_fails() { val error = assertFails { assertThat(mapOf("one" to 2, "two" to 1)).containsOnly("two" to 2, "one" to 1) } assertEquals( """expected to contain only:<{"two"=2, "one"=1}> but was:<{"one"=2, "two"=1}> | elements not found:<{"two"=2, "one"=1}> | extra elements found:<{"one"=2, "two"=1}> """.trimMargin(), error.message ) } @Test fun containsOnly_missing_element_fails() { val error = assertFails { assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("three" to 3) } assertEquals( """expected to contain only:<{"three"=3}> but was:<{"one"=1, "two"=2}> | elements not found:<{"three"=3}> | extra elements found:<{"one"=1, "two"=2}> """.trimMargin(), error.message ) } @Test fun containsOnly_extra_element_fails() { val error = assertFails { assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("one" to 1) } assertEquals( """expected to contain only:<{"one"=1}> but was:<{"one"=1, "two"=2}> | extra elements found:<{"two"=2}> """.trimMargin(), error.message ) } //endregion //region isEmpty @Test fun isEmpty_empty_passes() { assertThat(emptyMap<Any?, Any?>()).isEmpty() } @Test fun isEmpty_non_empty_fails() { val error = assertFails { assertThat(mapOf<Any?, Any?>(null to null)).isEmpty() } assertEquals("expected to be empty but was:<{null=null}>", error.message) } //endregion //region isNotEmpty @Test fun isNotEmpty_non_empty_passes() { assertThat(mapOf<Any?, Any?>(null to null)).isNotEmpty() } @Test fun isNotEmpty_empty_fails() { val error = assertFails { assertThat(mapOf<Any?, Any?>()).isNotEmpty() } assertEquals("expected to not be empty", error.message) } //endregion //region isNullOrEmpty @Test fun isNullOrEmpty_null_passes() { assertThat(null as Map<Any?, Any?>?).isNullOrEmpty() } @Test fun isNullOrEmpty_empty_passes() { assertThat(emptyMap<Any?, Any?>()).isNullOrEmpty() } @Test fun isNullOrEmpty_non_empty_fails() { val error = assertFails { assertThat(mapOf<Any?, Any?>(null to null)).isNullOrEmpty() } assertEquals("expected to be null or empty but was:<{null=null}>", error.message) } //endregion //region hasSize @Test fun hasSize_correct_size_passes() { assertThat(emptyMap<String, Int>()).hasSize(0) } @Test fun hasSize_wrong_size_fails() { val error = assertFails { assertThat(emptyMap<String, Int>()).hasSize(1) } assertEquals("expected [size]:<[1]> but was:<[0]> ({})", error.message) } //endregion //region hasSameSizeAs @Test fun hasSameSizeAs_equal_sizes_passes() { assertThat(emptyMap<String, Int>()).hasSameSizeAs(emptyMap<String, Int>()) } @Test fun hasSameSizeAs_non_equal_sizes_fails() { val error = assertFails { assertThat(emptyMap<String, Int>()).hasSameSizeAs(mapOf("one" to 1)) } assertEquals("expected to have same size as:<{\"one\"=1}> (1) but was size:(0)", error.message) } //endregion //region key @Test fun index_successful_assertion_passes() { assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("one").isEqualTo(1) } @Test fun index_unsuccessful_assertion_fails() { val error = assertFails { assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("one").isEqualTo(2) } assertEquals("expected [subject[\"one\"]]:<[2]> but was:<[1]> ({\"one\"=1, \"two\"=2})", error.message) } @Test fun index_missing_key_fails() { val error = assertFails { assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("wrong").isEqualTo(1) } assertEquals("expected [subject] to have key:<\"wrong\">", error.message) } //endregion }
1995895183
assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt
package test.assertk import assertk.assertAll import assertk.assertThat import assertk.assertions.isEqualTo import assertk.fail import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails import kotlin.test.assertFalse class AssertTest { //region transform @Test fun transform_that_throws_always_fails_assertion() { val error = assertFails { assertAll { assertThat(0).transform { fail("error") }.isEqualTo(0) } } assertEquals("error", error.message) } @Test fun transform_does_not_run_after_throws() { var run = false val error = assertFails { assertAll { assertThat(0).transform { fail("error") }.transform { run = true }.isEqualTo(0) } } assertEquals("error", error.message) assertFalse(run) } @Test fun transform_rethrows_thrown_exception() { val error = assertFails { assertAll { assertThat(0).transform { throw MyException("error") }.isEqualTo(0) } } assertEquals(MyException::class, error::class) assertEquals("error", error.message) } //endregion //region given @Test fun given_rethrows_thrown_exception() { val error = assertFails { assertAll { assertThat(0).given { throw MyException("error") } } } assertEquals(MyException::class, error::class) assertEquals("error", error.message) } //endregion //region assertThat @Test fun assertThat_inherits_name_of_parent_assertion_by_default() { val error = assertFails { assertThat(0, name = "test").assertThat(1).isEqualTo(2) } assertEquals("expected [test]:<[2]> but was:<[1]> (0)", error.message) } @Test fun assertThat_failing_transformed_assert_shows_original_by_displayActual_lambda() { val error = assertFails { assertThat(0, name = "test", displayActual = { "Number:${it}" }) .assertThat(1).isEqualTo(2) } assertEquals("expected [test]:<[2]> but was:<[1]> (Number:0)", error.message) } @Test fun assertThat_on_failing_assert_is_ignored() { val error = assertFails { assertAll { assertThat(0, name = "test").transform { fail("error") }.assertThat(1, name = "ignored").isEqualTo(2) } } assertEquals("error", error.message) } //endregion private class MyException(message: String) : Exception(message) }
1905445981
assertk/src/commonTest/kotlin/test/assertk/AssertTest.kt
/* * Copyright 2020 Ren Binden * * 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.rpkit.permissions.bukkit.event.group import com.rpkit.core.bukkit.event.RPKBukkitEvent import com.rpkit.permissions.bukkit.group.RPKGroup import com.rpkit.players.bukkit.profile.RPKProfile import org.bukkit.event.Cancellable import org.bukkit.event.HandlerList class RPKBukkitGroupUnassignProfileEvent( override val group: RPKGroup, override val profile: RPKProfile, isAsync: Boolean ) : RPKBukkitEvent(isAsync), RPKGroupUnassignProfileEvent, Cancellable { companion object { @JvmStatic val handlerList = HandlerList() } private var cancel: Boolean = false override fun isCancelled(): Boolean { return cancel } override fun setCancelled(cancel: Boolean) { this.cancel = cancel } override fun getHandlers(): HandlerList { return handlerList } }
3524945525
bukkit/rpk-permissions-lib-bukkit/src/main/kotlin/com/rpkit/permissions/bukkit/event/group/RPKBukkitGroupUnassignProfileEvent.kt
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.react.model data class ModelCodegenConfigAndroid(val javaPackageName: String?)
1921710925
packages/react-native-gradle-plugin/src/main/kotlin/com/facebook/react/model/ModelCodegenConfigAndroid.kt
package com.fsck.k9.storage.messages import android.database.Cursor import androidx.core.database.getLongOrNull import com.fsck.k9.Account.FolderMode import com.fsck.k9.helper.map import com.fsck.k9.mail.FolderClass import com.fsck.k9.mail.FolderType import com.fsck.k9.mailstore.FolderDetailsAccessor import com.fsck.k9.mailstore.FolderMapper import com.fsck.k9.mailstore.FolderNotFoundException import com.fsck.k9.mailstore.LockableDatabase import com.fsck.k9.mailstore.MoreMessages import com.fsck.k9.mailstore.toFolderType internal class RetrieveFolderOperations(private val lockableDatabase: LockableDatabase) { fun <T> getFolder(folderId: Long, mapper: FolderMapper<T>): T? { return getFolder( selection = "id = ?", selectionArguments = arrayOf(folderId.toString()), mapper = mapper ) } fun <T> getFolder(folderServerId: String, mapper: FolderMapper<T>): T? { return getFolder( selection = "server_id = ?", selectionArguments = arrayOf(folderServerId), mapper = mapper ) } private fun <T> getFolder(selection: String, selectionArguments: Array<String>, mapper: FolderMapper<T>): T? { return lockableDatabase.execute(false) { db -> db.query( "folders", FOLDER_COLUMNS, selection, selectionArguments, null, null, null ).use { cursor -> if (cursor.moveToFirst()) { val cursorFolderAccessor = CursorFolderAccessor(cursor) mapper.map(cursorFolderAccessor) } else { null } } } } fun <T> getFolders(excludeLocalOnly: Boolean = false, mapper: FolderMapper<T>): List<T> { val selection = if (excludeLocalOnly) "local_only = 0" else null return lockableDatabase.execute(false) { db -> db.query("folders", FOLDER_COLUMNS, selection, null, null, null, "id").use { cursor -> val cursorFolderAccessor = CursorFolderAccessor(cursor) cursor.map { mapper.map(cursorFolderAccessor) } } } } fun <T> getDisplayFolders(displayMode: FolderMode, outboxFolderId: Long?, mapper: FolderMapper<T>): List<T> { return lockableDatabase.execute(false) { db -> val displayModeSelection = getDisplayModeSelection(displayMode) val outboxFolderIdOrZero = outboxFolderId ?: 0 val query = """ SELECT ${FOLDER_COLUMNS.joinToString()}, ( SELECT COUNT(messages.id) FROM messages WHERE messages.folder_id = folders.id AND messages.empty = 0 AND messages.deleted = 0 AND (messages.read = 0 OR folders.id = ?) ), ( SELECT COUNT(messages.id) FROM messages WHERE messages.folder_id = folders.id AND messages.empty = 0 AND messages.deleted = 0 AND messages.flagged = 1 ) FROM folders $displayModeSelection """ db.rawQuery(query, arrayOf(outboxFolderIdOrZero.toString())).use { cursor -> val cursorFolderAccessor = CursorFolderAccessor(cursor) cursor.map { mapper.map(cursorFolderAccessor) } } } } private fun getDisplayModeSelection(displayMode: FolderMode): String { return when (displayMode) { FolderMode.ALL -> { "" } FolderMode.FIRST_CLASS -> { "WHERE display_class = '${FolderClass.FIRST_CLASS.name}'" } FolderMode.FIRST_AND_SECOND_CLASS -> { "WHERE display_class IN ('${FolderClass.FIRST_CLASS.name}', '${FolderClass.SECOND_CLASS.name}')" } FolderMode.NOT_SECOND_CLASS -> { "WHERE display_class != '${FolderClass.SECOND_CLASS.name}'" } FolderMode.NONE -> { throw AssertionError("Invalid folder display mode: $displayMode") } } } fun getFolderId(folderServerId: String): Long? { return lockableDatabase.execute(false) { db -> db.query( "folders", arrayOf("id"), "server_id = ?", arrayOf(folderServerId), null, null, null ).use { cursor -> if (cursor.moveToFirst()) cursor.getLong(0) else null } } } fun getFolderServerId(folderId: Long): String? { return lockableDatabase.execute(false) { db -> db.query( "folders", arrayOf("server_id"), "id = ?", arrayOf(folderId.toString()), null, null, null ).use { cursor -> if (cursor.moveToFirst()) cursor.getString(0) else null } } } fun getMessageCount(folderId: Long): Int { return lockableDatabase.execute(false) { db -> db.rawQuery( "SELECT COUNT(id) FROM messages WHERE empty = 0 AND deleted = 0 AND folder_id = ?", arrayOf(folderId.toString()) ).use { cursor -> if (cursor.moveToFirst()) cursor.getInt(0) else 0 } } } fun hasMoreMessages(folderId: Long): MoreMessages { return getFolder(folderId) { it.moreMessages } ?: throw FolderNotFoundException(folderId) } } private class CursorFolderAccessor(val cursor: Cursor) : FolderDetailsAccessor { override val id: Long get() = cursor.getLong(0) override val name: String get() = cursor.getString(1) override val type: FolderType get() = cursor.getString(2).toFolderType() override val serverId: String? get() = cursor.getString(3) override val isLocalOnly: Boolean get() = cursor.getInt(4) == 1 override val isInTopGroup: Boolean get() = cursor.getInt(5) == 1 override val isIntegrate: Boolean get() = cursor.getInt(6) == 1 override val syncClass: FolderClass get() = cursor.getString(7).toFolderClass(FolderClass.INHERITED) override val displayClass: FolderClass get() = cursor.getString(8).toFolderClass(FolderClass.NO_CLASS) override val notifyClass: FolderClass get() = cursor.getString(9).toFolderClass(FolderClass.INHERITED) override val pushClass: FolderClass get() = cursor.getString(10).toFolderClass(FolderClass.SECOND_CLASS) override val visibleLimit: Int get() = cursor.getInt(11) override val moreMessages: MoreMessages get() = MoreMessages.fromDatabaseName(cursor.getString(12)) override val lastChecked: Long? get() = cursor.getLongOrNull(13) override val unreadMessageCount: Int get() = cursor.getInt(14) override val starredMessageCount: Int get() = cursor.getInt(15) override fun serverIdOrThrow(): String { return serverId ?: error("No server ID found for folder '$name' ($id)") } } private fun String?.toFolderClass(defaultValue: FolderClass): FolderClass { return if (this == null) defaultValue else FolderClass.valueOf(this) } private val FOLDER_COLUMNS = arrayOf( "id", "name", "type", "server_id", "local_only", "top_group", "integrate", "poll_class", "display_class", "notify_class", "push_class", "visible_limit", "more_messages", "last_updated" )
3583381349
app/storage/src/main/java/com/fsck/k9/storage/messages/RetrieveFolderOperations.kt
package org.squarecell.wow.addon_support.builders import com.intellij.ide.plugins.PluginManager import com.intellij.ide.util.PropertiesComponent import com.intellij.ide.util.projectWizard.ModuleBuilder import com.intellij.ide.util.projectWizard.ModuleBuilderListener import com.intellij.ide.util.projectWizard.ModuleWizardStep import com.intellij.ide.util.projectWizard.WizardContext import com.intellij.openapi.Disposable import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleType import com.intellij.openapi.roots.ModifiableRootModel import com.intellij.openapi.ui.Messages import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFileManager import org.squarecell.wow.addon_support.config.MainFile import org.squarecell.wow.addon_support.config.ProjectSettingsKeys import org.squarecell.wow.addon_support.modules.AddOnModuleType import org.squarecell.wow.addon_support.wizard_steps.AddOnWizardStep import java.io.File class AddOnModuleBuilder : ModuleBuilder(), ModuleBuilderListener { init { addListener(this) } override fun moduleCreated(module: Module) { val tocFilePath = contentEntryPath + File.separator + module.name + ".toc" var mainFilePath = contentEntryPath + File.separator + PropertiesComponent .getInstance().getValue(ProjectSettingsKeys.AddOnMainFileName) if (!mainFilePath.endsWith(".lua")) mainFilePath += ".lua" File(tocFilePath).writeText(PropertiesComponent.getInstance().getValue("tocFile")!!) val file = File(mainFilePath) file.createNewFile() file.appendText(MainFile.initAce3AddOn) file.appendText(MainFile.defaultInitFunc) file.appendText(MainFile.defaultLoadFunc) file.appendText(MainFile.defaultUnloadFunc) } override fun setupRootModel(modifiableRootModel: ModifiableRootModel) { val path = contentEntryPath + File.separator + "Libs" File(path).mkdirs() val sourceRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(path)!! val jarUtil = JarFileSystem.getInstance() val desc = PluginManager.getPlugin(PluginId.getId("org.squarecell.wow.addon_support"))!! val pluginPath = desc.path.absolutePath val realPath = VfsUtil.pathToUrl(pluginPath) val pluginVD = VirtualFileManager.getInstance().findFileByUrl(realPath)!! val file = jarUtil.refreshAndFindFileByPath(pluginVD.path + "!/Wow_sdk")!! // val classesDir = pluginVD.findChild("classes")?: pluginVD // val deps = classesDir.findChild("Wow_sdk")!! file.children.forEach { VfsUtil.copy(this, it, sourceRoot) } super.doAddContentEntry(modifiableRootModel)?.addSourceFolder(sourceRoot, false) } override fun getModuleType(): ModuleType<*> { return AddOnModuleType.instance } override fun getCustomOptionsStep(context: WizardContext, parentDisposable: Disposable?): ModuleWizardStep? { return AddOnWizardStep() } }
1170516204
src/org/squarecell/wow/addon_support/builders/AddOnModuleBuilder.kt
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.summit.ast import com.google.common.truth.Truth.assertThat import com.google.summit.ast.Node import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class SourceLocationTest { @Test fun spanOf_chooses_nonNullValues() { val unknown = SourceLocation.UNKNOWN val withLinesOnly = SourceLocation(1, null, 3, null) val withLinesAndColumns = SourceLocation(withLinesOnly.startLine, 10, withLinesOnly.endLine, 10) assertThat(spanOf(unknown, unknown)).isEqualTo(unknown) assertThat(spanOf(withLinesOnly, unknown)).isEqualTo(withLinesOnly) assertThat(spanOf(unknown, withLinesOnly)).isEqualTo(withLinesOnly) assertThat(spanOf(withLinesOnly, withLinesAndColumns)).isEqualTo(withLinesAndColumns) assertThat(spanOf(withLinesAndColumns, withLinesOnly)).isEqualTo(withLinesAndColumns) } @Test fun spanOf_returns_newRange() { val lower = SourceLocation(1, 1, 2, 2) val upper = SourceLocation(2, 2, 3, 3) val expected = SourceLocation(lower.startLine, lower.startColumn, upper.endLine, upper.endColumn) assertThat(spanOf(lower, upper)).isEqualTo(expected) assertThat(spanOf(upper, lower)).isEqualTo(expected) } @Test fun spanOf_is_idempotent() { val loc = SourceLocation(1, 3, 4, 2) assertThat(spanOf(loc)).isEqualTo(loc) assertThat(spanOf(loc, loc, loc)).isEqualTo(loc) assertThat(spanOf(loc, spanOf(loc, loc))).isEqualTo(loc) } @Test fun spanOf_ranks_lineOverColumn() { val widerLines = SourceLocation(1, 6, 10, 5) val widerColumns = SourceLocation(5, 1, 6, 10) assertThat(spanOf(widerLines, widerColumns)).isEqualTo(widerLines) assertThat(spanOf(widerColumns, widerLines)).isEqualTo(widerLines) } }
3711422681
src/main/javatests/com/google/summit/ast/SourceLocationTest.kt
package com.fuyoul.sanwenseller.ui.money import android.content.Context import android.content.Intent import android.graphics.drawable.Drawable import android.os.Bundle import android.support.design.widget.AppBarLayout import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.widget.LinearLayout import android.widget.TextView import com.alibaba.fastjson.JSON import com.csl.refresh.SmartRefreshLayout import com.csl.refresh.api.RefreshLayout import com.csl.refresh.listener.OnRefreshLoadmoreListener import com.fuyoul.sanwenseller.R import com.fuyoul.sanwenseller.base.BaseActivity import com.fuyoul.sanwenseller.base.BaseAdapter import com.fuyoul.sanwenseller.base.BaseViewHolder import com.fuyoul.sanwenseller.bean.AdapterMultiItem import com.fuyoul.sanwenseller.bean.MultBaseBean import com.fuyoul.sanwenseller.bean.reqhttp.ReqInCome import com.fuyoul.sanwenseller.bean.reshttp.ResMoneyItem import com.fuyoul.sanwenseller.configs.Code import com.fuyoul.sanwenseller.configs.Data import com.fuyoul.sanwenseller.configs.TopBarOption import com.fuyoul.sanwenseller.listener.AppBarStateChangeListener import com.fuyoul.sanwenseller.structure.model.MoneyInComeM import com.fuyoul.sanwenseller.structure.presenter.MoneyInComeP import com.fuyoul.sanwenseller.structure.view.MoneyInComeV import com.fuyoul.sanwenseller.utils.GlideUtils import com.fuyoul.sanwenseller.utils.TimeDateUtils import com.netease.nim.uikit.NimUIKit import com.netease.nim.uikit.StatusBarUtils import kotlinx.android.synthetic.main.moneyinfolayout.* import kotlinx.android.synthetic.main.waitforsettlementlayout.* import java.util.* /** * @author: chen * @CreatDate: 2017\10\31 0031 * @Desc:待结算 */ class SettlementTypeActivity : BaseActivity<MoneyInComeM, MoneyInComeV, MoneyInComeP>() { companion object { fun start(context: Context, isHistoryType: Boolean, year: String?, month: String?) { val intent = Intent(context, SettlementTypeActivity::class.java) intent.putExtra("isHistoryType", isHistoryType) if (isHistoryType) { intent.putExtra("year", year) intent.putExtra("month", month) } context.startActivity(intent) } } private val req = ReqInCome() private var index = 0 private var defaultState = AppBarStateChangeListener.State.EXPANDED//默认是展开状态 private var adapter: ThisAdapter? = null override fun setLayoutRes(): Int = R.layout.waitforsettlementlayout override fun initData(savedInstanceState: Bundle?) { StatusBarUtils.setTranslucentForCoordinatorLayout(this, 30) setSupportActionBar(toolbar) //如果是结算历史 if (intent.getBooleanExtra("isHistoryType", false)) { req.ordersDate = "${intent.getStringExtra("year")}${intent.getStringExtra("month")}" } getPresenter().viewImpl?.initAdapter(this) getPresenter().getData(this, req, true) } override fun setListener() { waitForSettlementRefreshLayout.setOnRefreshLoadmoreListener(object : OnRefreshLoadmoreListener { override fun onRefresh(refreshlayout: RefreshLayout?) { index = 0 req.index = "$index" getPresenter().getData(this@SettlementTypeActivity, req, true) } override fun onLoadmore(refreshlayout: RefreshLayout?) { index++ req.index = "$index" getPresenter().getData(this@SettlementTypeActivity, req, false) } }) appBarLayoutOfWaitSettlement.addOnOffsetChangedListener(listener) toolbar.setNavigationOnClickListener { finish() } } override fun onResume() { super.onResume() appBarLayoutOfWaitSettlement.removeOnOffsetChangedListener(listener) } override fun onPause() { super.onPause() appBarLayoutOfWaitSettlement.removeOnOffsetChangedListener(listener) } override fun getPresenter(): MoneyInComeP = MoneyInComeP(initViewImpl()) override fun initViewImpl(): MoneyInComeV = object : MoneyInComeV() { override fun getAdapter(): BaseAdapter { if (adapter == null) { adapter = ThisAdapter() } return adapter!! } override fun initAdapter(context: Context) { val manager = LinearLayoutManager(this@SettlementTypeActivity) manager.orientation = LinearLayoutManager.VERTICAL waitForSettlementDataList.layoutManager = manager waitForSettlementDataList.adapter = getAdapter() } override fun setViewInfo(data: ResMoneyItem) { priceCount.text = "${data.countPrice}" orderCount.text = "${data.countOrders}" } } override fun initTopBar(): TopBarOption = TopBarOption() inner class ThisAdapter : BaseAdapter(this) { override fun convert(holder: BaseViewHolder, position: Int, datas: List<MultBaseBean>) { val item = datas[position] as ResMoneyItem.IncomeListBean GlideUtils.loadNormalImg(this@SettlementTypeActivity, JSON.parseArray(item.imgs).getJSONObject(0).getString("url"), holder.itemView.findViewById(R.id.orderItemIcon)) GlideUtils.loadNormalImg(this@SettlementTypeActivity, item.avatar, holder.itemView.findViewById(R.id.orderItemHead)) holder.itemView.findViewById<TextView>(R.id.orderItemPrice).text = "¥${item.totalPrice}" holder.itemView.findViewById<TextView>(R.id.orderItemTitle).text = "${item.name}" holder.itemView.findViewById<TextView>(R.id.orderItemDes).text = "${item.introduce}" holder.itemView.findViewById<TextView>(R.id.orderItemTime).text = "${TimeDateUtils.stampToDate(item.ordersDate)}" holder.itemView.findViewById<TextView>(R.id.orderItemNick).text = "${item.nickname}" var typeIcon: Drawable? = null if (item.type == Data.QUICKTESTBABY) { typeIcon = resources.getDrawable(R.mipmap.icon_quicktesttype) typeIcon.setBounds(0, 0, typeIcon.minimumWidth, typeIcon.minimumHeight) } holder.itemView.findViewById<TextView>(R.id.orderItemTitle).setCompoundDrawables(null, null, typeIcon, null) val orderItemState = holder.itemView.findViewById<TextView>(R.id.orderItemState) orderItemState.text = "交易完成" val orderItemFuncLayout = holder.itemView.findViewById<LinearLayout>(R.id.orderItemFuncLayout) orderItemFuncLayout.visibility = View.VISIBLE val orderItemReleaseTime = holder.itemView.findViewById<LinearLayout>(R.id.orderItemReleaseTime) orderItemReleaseTime.visibility = View.GONE val orderItemFuncRight = holder.itemView.findViewById<TextView>(R.id.orderItem_Func_Right) orderItemFuncRight.text = "联系买家" orderItemFuncRight.setOnClickListener { NimUIKit.startP2PSession(this@SettlementTypeActivity, "user_${item.user_info_id}") } } override fun addMultiType(multiItems: ArrayList<AdapterMultiItem>) { multiItems.add(AdapterMultiItem(Code.VIEWTYPE_MONEY, R.layout.orderitem)) } override fun onItemClicked(view: View, position: Int) { } override fun onEmpryLayou(view: View, layoutResId: Int) { } override fun getSmartRefreshLayout(): SmartRefreshLayout = waitForSettlementRefreshLayout override fun getRecyclerView(): RecyclerView = waitForSettlementDataList } private val listener = object : AppBarStateChangeListener() { override fun onStateChanged(appBarLayout: AppBarLayout?, state: State) { when (state) { State.EXPANDED -> { //展开状态 StatusBarUtils.StatusBarDarkMode(this@SettlementTypeActivity) StatusBarUtils.setTranslucentForCoordinatorLayout(this@SettlementTypeActivity, 30) toolbar.setBackgroundColor(resources.getColor(R.color.transparent)) } State.COLLAPSED -> { //折叠状态 toolbarOfMoneyInfo.setNavigationIcon(R.mipmap.ic_yb_top_back) StatusBarUtils.StatusBarLightMode(this@SettlementTypeActivity, R.color.color_white) toolbar.setBackgroundResource(R.drawable.back_titlebar) } else -> { //中间状态 //如果之前是折叠状态,则表示在向下滑动 if (defaultState == State.COLLAPSED) { StatusBarUtils.StatusBarDarkMode(this@SettlementTypeActivity) StatusBarUtils.setTranslucentForCoordinatorLayout(this@SettlementTypeActivity, 30) toolbar.setBackgroundColor(resources.getColor(R.color.transparent)) } } } defaultState = state } } }
915715459
app/src/main/java/com/fuyoul/sanwenseller/ui/money/SettlementTypeActivity.kt
package fr.free.nrw.commons.actions import io.reactivex.Observable import io.reactivex.Single import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.mwapi.MwQueryResponse import org.wikipedia.edit.Edit import org.wikipedia.wikidata.Entities import retrofit2.http.* /** * This interface facilitates wiki commons page editing services to the Networking module * which provides all network related services used by the app. * * This interface posts a form encoded request to the wikimedia API * with editing action as argument to edit a particular page */ interface PageEditInterface { /** * This method posts such that the Content which the page * has will be completely replaced by the value being passed to the * "text" field of the encoded form data * @param title Title of the page to edit. Cannot be used together with pageid. * @param summary Edit summary. Also section title when section=new and sectiontitle is not set * @param text Holds the page content * @param token A "csrf" token */ @FormUrlEncoded @Headers("Cache-Control: no-cache") @POST(Service.MW_API_PREFIX + "action=edit") fun postEdit( @Field("title") title: String, @Field("summary") summary: String, @Field("text") text: String, // NOTE: This csrf shold always be sent as the last field of form data @Field("token") token: String ): Observable<Edit> /** * This method posts such that the Content which the page * has will be appended with the value being passed to the * "appendText" field of the encoded form data * @param title Title of the page to edit. Cannot be used together with pageid. * @param summary Edit summary. Also section title when section=new and sectiontitle is not set * @param appendText Text to add to the end of the page * @param token A "csrf" token */ @FormUrlEncoded @Headers("Cache-Control: no-cache") @POST(Service.MW_API_PREFIX + "action=edit") fun postAppendEdit( @Field("title") title: String, @Field("summary") summary: String, @Field("appendtext") appendText: String, @Field("token") token: String ): Observable<Edit> /** * This method posts such that the Content which the page * has will be prepended with the value being passed to the * "prependText" field of the encoded form data * @param title Title of the page to edit. Cannot be used together with pageid. * @param summary Edit summary. Also section title when section=new and sectiontitle is not set * @param prependText Text to add to the beginning of the page * @param token A "csrf" token */ @FormUrlEncoded @Headers("Cache-Control: no-cache") @POST(Service.MW_API_PREFIX + "action=edit") fun postPrependEdit( @Field("title") title: String, @Field("summary") summary: String, @Field("prependtext") prependText: String, @Field("token") token: String ): Observable<Edit> @FormUrlEncoded @Headers("Cache-Control: no-cache") @POST(Service.MW_API_PREFIX + "action=wbsetlabel&format=json&site=commonswiki&formatversion=2") fun postCaptions( @Field("summary") summary: String, @Field("title") title: String, @Field("language") language: String, @Field("value") value: String, @Field("token") token: String ): Observable<Entities> /** * Get wiki text for provided file names * @param titles : Name of the file * @return Single<MwQueryResult> */ @GET( Service.MW_API_PREFIX + "action=query&prop=revisions&rvprop=content|timestamp&rvlimit=1&converttitles=" ) fun getWikiText( @Query("titles") title: String ): Single<MwQueryResponse?> }
157903978
app/src/main/java/fr/free/nrw/commons/actions/PageEditInterface.kt
package com.github.kittinunf.reactiveandroid.support.v4.widget import android.support.v4.widget.SwipeRefreshLayout import com.github.kittinunf.reactiveandroid.MutableProperty import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty //================================================================================ // Property //================================================================================ val SwipeRefreshLayout.rx_refreshing: MutableProperty<Boolean> get() { val getter = { isRefreshing } val setter: (Boolean) -> Unit = { isRefreshing = it } return createMainThreadMutableProperty(getter, setter) } val SwipeRefreshLayout.rx_nestedScrollingEnabled: MutableProperty<Boolean> get() { val getter = { isNestedScrollingEnabled } val setter: (Boolean) -> Unit = { isNestedScrollingEnabled = it } return createMainThreadMutableProperty(getter, setter) }
3481789443
reactiveandroid-support-v4/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v4/widget/SwipeRefreshLayoutProperty.kt
/** * Checks chat for user written messages and responds to specific queries * Created by zingmars on 04.10.2015. */ package BotPlugins import Containers.PluginBufferItem public class UserCommands : BasePlugin() { override fun pubInit() :Boolean { return true } override fun connector(buffer : PluginBufferItem) :Boolean { var message = buffer.message.split(" ") when(message[0].toLowerCase()) { "!ping" -> controller?.AddToBoxBuffer(buffer.userName + ": PONG!") "!nextstream" -> controller?.AddToBoxBuffer(buffer.userName + ": Soon™") //TODO: have some sort of database where plugins can register their commands so this command can be automated. "!help" -> { controller?.AddToBoxBuffer("For more information please see https://github.com/zingmars/Cbox-bot. For feature requests ask zingmars.") controller?.AddToBoxBuffer("!about - About this bot; !lastseen <username> - Output the date of user's last message; !ping - check if I'm alive; !help - display this; !time - time related commands (try help as a parameter)") controller?.AddToBoxBuffer("!laststream <username> - Get when an user has last streamed (try !laststream zingmars); !nextstream - OTG's next stream time") controller?.AddToBoxBuffer("Available commands:") } "!about" -> { controller?.AddToBoxBuffer("Hi! My name is " + handler?.username + " and I'm a bot for cbox.ws written in Kotlin. Check me out at: https://github.com/zingmars/Cbox-bot") } } return true } }
1259019030
src/BotPlugins/UserCommands.kt
package org.rust.ide.typing import org.intellij.lang.annotations.Language class RustEnterInStringLiteralHandlerTest : RustTypingTestCaseBase() { override val dataPath = "org/rust/ide/typing/string/fixtures" fun testSimple() = doTest(""" fn main() { let lit = "Hello, /*caret*/World"; println!("{}", lit); } """, """ fn main() { let lit = "Hello, \ /*caret*/World"; println!("{}", lit); } """) fun testMultilineText() = doTest(""" fn main() { let lit = "\ Multiline text last/*caret*/ line"; } """, """ fn main() { let lit = "\ Multiline text last /*caret*/line"; } """) fun testBeforeOpening() = doTest(""" fn main() { let lit =/*caret*/"Hello, World"; } """, """ fn main() { let lit = /*caret*/"Hello, World"; } """) fun testAfterOpening() = doTest(""" fn main() { "/*caret*/Hello, World"; } """, """ fn main() { "\ /*caret*/Hello, World"; } """) fun testInsideOpening() = doTest(""" fn main() { b/*caret*/"Hello, World"; } """, """ fn main() { b /*caret*/"Hello, World"; } """) fun testBeforeClosing() = doTest(""" fn main() { "Hello, World/*caret*/"; } """, """ fn main() { "Hello, World\ /*caret*/"; } """) fun testAfterClosing() = doTest(""" fn main() { "Hello, World"/*caret*/; } """, """ fn main() { "Hello, World" /*caret*/; } """) fun testRawLiteral() = doTest(""" fn main() { r"Hello,/*caret*/ World"; } """, """ fn main() { r"Hello, /*caret*/ World"; } """) fun testBeforeEscape() = doTest(""" fn main() { "foo/*caret*/\n" } """, """ fn main() { "foo\ /*caret*/\n" } """) fun testAfterEscape() = doTest(""" fn main() { "foo\n/*caret*/bar" } """, """ fn main() { "foo\n\ /*caret*/bar" } """) fun testInsideEscape() = doTest(""" fn main() { "foo\u{00/*caret*/00}" } """, """ fn main() { "foo\u{00 /*caret*/00}" } """) fun testInsideEscapeAfterSlash() = doTest(""" fn main() { "foo\/*caret*/u{0000}" } """, """ fn main() { "foo\ /*caret*/u{0000}" } """) fun testBetweenQuoteEscape() = doTest(""" fn main() { "/*caret*/\n" } """, """ fn main() { "\ /*caret*/\n" } """) fun testBetweenEscapeQuote() = doTest(""" fn main() { "foo\n/*caret*/" } """, """ fn main() { "foo\n\ /*caret*/" } """) fun testIncomplete() = doTest(""" fn main() { "foo/*caret*/ """, """ fn main() { "foo /*caret*/ """) fun testIncompleteEscape() = doTest(""" fn main() { "foo\n/*caret*/ """, """ fn main() { "foo\n\ /*caret*/ """) fun testRawIncomplete() = doTest(""" fn main() { r##"foo/*caret*/ """, """ fn main() { r##"foo /*caret*/ """) fun doTest(@Language("Rust") before: String, @Language("Rust") after: String) { InlineFile(before).withCaret() myFixture.type('\n') myFixture.checkResult(replaceCaretMarker(after)) } }
2154142024
src/test/kotlin/org/rust/ide/typing/RustEnterInStringLiteralHandlerTest.kt
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.windowmanagersample.embedding import android.graphics.Color import android.os.Bundle import android.view.View import com.example.windowmanagersample.R open class SplitActivityD : SplitActivityBase() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) findViewById<View>(R.id.root_split_activity_layout) .setBackgroundColor(Color.parseColor("#eeeeee")) } }
1653253238
WindowManager/app/src/main/java/com/example/windowmanagersample/embedding/SplitActivityD.kt
package org.luxons.sevenwonders.engine.data.definitions import org.luxons.sevenwonders.engine.cards.Requirements import org.luxons.sevenwonders.engine.wonders.Wonder import org.luxons.sevenwonders.engine.wonders.WonderStage import org.luxons.sevenwonders.model.resources.ResourceType import org.luxons.sevenwonders.model.wonders.WonderName import org.luxons.sevenwonders.model.wonders.WonderSide internal class WonderDefinition( val name: WonderName, val sides: Map<WonderSide, WonderSideDefinition>, ) { fun create(wonderSide: WonderSide): Wonder = sides[wonderSide]!!.createWonder(name) } internal class WonderSideDefinition( private val initialResource: ResourceType, private val stages: List<WonderStageDefinition>, val image: String, ) { fun createWonder(name: String): Wonder = Wonder(name, initialResource, stages.map { it.create() }, image) } internal class WonderStageDefinition( private val requirements: Requirements, private val effects: EffectsDefinition, ) { fun create(): WonderStage = WonderStage(requirements, effects.create()) }
535388536
sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/data/definitions/WonderDefinition.kt
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import org.rust.lang.core.psi.RustExternCrateItemElement import org.rust.lang.core.psi.impl.RustPsiImplUtil import org.rust.lang.core.psi.impl.RustStubbedNamedElementImpl import org.rust.lang.core.resolve.ref.RustExternCrateReferenceImpl import org.rust.lang.core.resolve.ref.RustReference import org.rust.lang.core.stubs.RustExternCrateItemElementStub abstract class RustExternCrateItemImplMixin : RustStubbedNamedElementImpl<RustExternCrateItemElementStub>, RustExternCrateItemElement { constructor(node: ASTNode) : super(node) constructor(stub: RustExternCrateItemElementStub, elementType: IStubElementType<*, *>) : super(stub, elementType) override fun getReference(): RustReference = RustExternCrateReferenceImpl(this) override val referenceNameElement: PsiElement get() = identifier override val isPublic: Boolean get() = RustPsiImplUtil.isPublic(this, stub) }
4000963059
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustExternCrateItemImplMixin.kt
package net.perfectdreams.loritta.serializable import kotlinx.serialization.Serializable @Serializable class CustomCommand( val label: String, val codeType: CustomCommandCodeType, val code: String )
2127709203
loritta-serializable-commons/src/commonMain/kotlin/net/perfectdreams/loritta/serializable/CustomCommand.kt
package com.jaynewstrom.concrete import android.content.Context import android.content.ContextWrapper import android.view.LayoutInflater internal class ConcreteWallContext<C>( baseContext: Context, private val wall: ConcreteWall<C> ) : ContextWrapper(baseContext) { private var inflater: LayoutInflater? = null override fun getSystemService(name: String): Any? { if (Concrete.isService(name)) { return wall } if (Context.LAYOUT_INFLATER_SERVICE == name) { if (inflater == null) { inflater = LayoutInflater.from(baseContext).cloneInContext(this) } return inflater } return super.getSystemService(name) } }
230516060
concrete/src/main/java/com/jaynewstrom/concrete/ConcreteWallContext.kt
package ir.iais.utilities.javautils.utils import com.fasterxml.jackson.annotation.JsonFormat import com.fasterxml.jackson.annotation.JsonFormat.Shape import com.fasterxml.jackson.annotation.JsonIgnoreProperties import ir.iais.utilities.javautils.enums.IOrdinal /** Created by mgh on 10/15/16. */ @JsonFormat(shape = Shape.OBJECT) @JsonIgnoreProperties("name", "ordinal", allowGetters = true) enum class InsuranceType constructor(val desc: String, val value: Boolean?) : IOrdinal { FullTime("تمام وقت", true), hourly("بر حسب حضور", true), None("ندارد", false) }
2016985467
src/test/java/ir/iais/utilities/javautils/utils/InsuranceType.kt
package nuclearbot.gui.components.chat import java.util.* import javax.swing.AbstractListModel import javax.swing.JList /* * Copyright (C) 2017 NuclearCoder * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Custom JList that uses a custom model which only keeps the last lines.<br></br> * <br></br> * NuclearBot (https://github.com/NuclearCoder/nuclear-bot/)<br></br> * @author NuclearCoder (contact on the GitHub repo) */ class LimitedStringList(capacity: Int = 50) : JList<String>() { private val listModel = LimitedStringList.Model(capacity).also { model = it } /** * Adds an element to the model. If the size of the list * will exceed the maximum capacity, the first element * is removed before adding the new element to the end * of the list. * * @param text the line to add to the list */ fun add(text: String) { listModel.add(text) } /** * The ListModel used by the LimitedStringList class */ class Model(private val capacity: Int) : AbstractListModel<String>() { private val arrayList = ArrayList<String>(capacity) /** * Adds an element to the model. If the size of the list * will exceed the maximum capacity, the first element * is removed before adding the new element to the end * of the list. * * @param text the line to add to the list */ fun add(text: String) { val index0: Int val index1: Int if (arrayList.size == capacity) { index0 = 0 index1 = capacity - 1 arrayList.removeAt(0) } else { index1 = arrayList.size index0 = index1 } arrayList.add(text) fireContentsChanged(this, index0, index1) } override fun getSize(): Int { return arrayList.size } override fun getElementAt(index: Int): String { return arrayList[index] } } }
2193133649
src/nuclearbot/gui/components/chat/LimitedStringList.kt
/** * Copyright 2021 Carl-Philipp Harmant * * * 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 fr.cph.chicago.core.model open class Bus(val id: Int, val position: Position, val heading: Int, val destination: String)
2928489330
android-app/src/main/kotlin/fr/cph/chicago/core/model/Bus.kt
package fr.free.nrw.commons.customselector.helper import android.net.Uri import fr.free.nrw.commons.customselector.model.Folder import fr.free.nrw.commons.customselector.model.Image import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import org.mockito.Mockito.mock /** * Custom Selector Image Helper Test */ internal class ImageHelperTest { var uri: Uri = mock(Uri::class.java) private val folderImage1 = Image(1, "image1", uri, "abc/abc", 1, "bucket1") private val folderImage2 = Image(2, "image1", uri, "xyz/xyz", 2, "bucket2") private val mockImageList = ArrayList<Image>(listOf(folderImage1, folderImage2)) private val folderImageList1 = ArrayList<Image>(listOf(folderImage1)) private val folderImageList2 = ArrayList<Image>(listOf(folderImage2)) /** * Test folder list from images. */ @Test fun folderListFromImages() { val folderList = ArrayList<Folder>(listOf(Folder(1, "bucket1", folderImageList1), Folder(2, "bucket2", folderImageList2))) assertEquals(folderList, ImageHelper.folderListFromImages(mockImageList)) } /** * Test filter images. */ @Test fun filterImages() { assertEquals(folderImageList1, ImageHelper.filterImages(mockImageList, 1)) } /** * Test get index from image list. */ @Test fun getIndex() { assertEquals(1,ImageHelper.getIndex(mockImageList, folderImage2)) } /** * Test get index list. */ @Test fun getIndexList() { assertEquals(ArrayList<Int>(listOf(0)), ImageHelper.getIndexList(mockImageList, folderImageList2)) } }
1078509340
app/src/test/kotlin/fr/free/nrw/commons/customselector/helper/ImageHelperTest.kt
package com.christian.nav.me import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.NonNull import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import com.christian.R import com.christian.common.GOSPEL_EN import com.christian.common.GOSPEL_ZH import com.christian.common.auth import com.christian.common.data.Gospel import com.christian.common.firestore import com.christian.databinding.ItemChatBinding import com.christian.databinding.ItemGospelBinding import com.christian.nav.disciple.ChatItemView import com.christian.nav.gospel.GospelItemView import com.christian.nav.gospel.HidingGospelItemView import com.christian.nav.home.VIEW_TYPE_CHAT import com.christian.nav.home.VIEW_TYPE_GOSPEL import com.christian.swipe.SwipeBackActivity import com.christian.util.ChristianUtil import com.christian.view.ItemDecoration import com.firebase.ui.firestore.FirestoreRecyclerAdapter import com.firebase.ui.firestore.FirestoreRecyclerOptions import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.Query import kotlinx.android.synthetic.main.fragment_detail_me.view.* import kotlinx.android.synthetic.main.fragment_nav_rv.view.* import kotlinx.android.synthetic.main.activity_tb_immersive.* class HidingGospelFragment: Fragment() { var meDetailTabId: Int = -1 private lateinit var v: View override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { v = inflater.inflate(R.layout.fragment_detail_me, container, false) initView() return v } private lateinit var gospelAdapter: FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder> private lateinit var query: Query var mPosition = -1 private fun initView() { initRv() v.me_detail_pb.isIndeterminate = true v.fragment_nav_rv.setProgressBar(v.me_detail_pb) } private fun initRv() { v.fragment_nav_rv.addItemDecoration(ItemDecoration(top = ChristianUtil.dpToPx(64))) getMeFromSettingId() if (::gospelAdapter.isInitialized) {gospelAdapter.startListening() v.fragment_nav_rv.adapter = gospelAdapter} // 我的-门徒-喜欢 崩溃处理 } override fun onDestroy() { super.onDestroy() if (::gospelAdapter.isInitialized) gospelAdapter.stopListening() // 我的-门徒-喜欢 崩溃处理 } /** * tabId = 0, settingId = 0, history gospels * tabId = 0, settingId = 1, favorite gospels * tabId = 0, settingId = 2, published gospels * * * tabId = 1, settingId = 0, history disciples * tabId = 1, settingId = 1, following disciples * tabId = 1, settingId = 2, followed disciples */ private fun getMeFromSettingId() { (requireActivity() as HidingGospelActivity).tb_immersive_toolbar.title = getString(R.string.hidden_gospel) query = if (meDetailTabId == 0) { firestore.collection(GOSPEL_EN).orderBy("createTime", Query.Direction.DESCENDING) .whereEqualTo("show", 0) } else { firestore.collection(GOSPEL_ZH).orderBy("createTime", Query.Direction.DESCENDING) .whereEqualTo("show", 0) } val options = FirestoreRecyclerOptions.Builder<Gospel>() // .setLifecycleOwner(this@NavFragment) .setQuery(query, Gospel::class.java) .build() gospelAdapter = object : FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder>(options) { override fun getItemViewType(position: Int): Int { return when { getItem(position).title.isEmpty() -> { VIEW_TYPE_CHAT } else -> { VIEW_TYPE_GOSPEL } } } @NonNull override fun onCreateViewHolder(@NonNull parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { when(viewType) { 0 -> { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_gospel, parent, false) val binding = ItemGospelBinding.bind(view) return HidingGospelItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId) } 1 -> { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_chat, parent, false) val binding = ItemChatBinding.bind(view) return ChatItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId) } else -> { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_gospel, parent, false) val binding = ItemGospelBinding.bind(view) return HidingGospelItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId) } } } override fun onBindViewHolder(@NonNull holder: RecyclerView.ViewHolder, position: Int, @NonNull model: Gospel ) { when { model.title.isEmpty() -> { applyViewHolderAnimation(holder as ChatItemView) holder.bind(meDetailTabId, model) } else -> { applyViewHolderAnimation(holder as HidingGospelItemView) holder.bind(meDetailTabId, model) } } } override fun onDataChanged() { super.onDataChanged() v.me_detail_pb.visibility = View.GONE v.me_detail_pb.isIndeterminate = false if (itemCount == 0) { } else { v.fragment_nav_rv.scheduleLayoutAnimation() } } override fun onError(e: FirebaseFirestoreException) { super.onError(e) Log.d("MeDetailFragment", e.toString()) } } v.fragment_nav_rv.adapter = gospelAdapter } fun applyViewHolderAnimation(holder: HidingGospelItemView) { if (holder.adapterPosition > mPosition) { holder.animateItemView(holder.itemView) mPosition = holder.adapterPosition } } fun applyViewHolderAnimation(holder: GospelItemView) { if (holder.adapterPosition > mPosition) { holder.animateItemView(holder.itemView) mPosition = holder.adapterPosition } } fun applyViewHolderAnimation(holder: ChatItemView) { if (holder.adapterPosition > mPosition) { holder.animateItemView(holder.itemView) mPosition = holder.adapterPosition } } }
2409808188
app/src/main/java/com/christian/nav/me/HidingGospelFragment.kt
package com.bl_lia.kirakiratter.data.repository.datasource.auth import io.reactivex.Single import com.bl_lia.kirakiratter.domain.value_object.AccessToken import com.bl_lia.kirakiratter.domain.value_object.AppCredentials import retrofit2.http.Field import retrofit2.http.FormUrlEncoded import retrofit2.http.POST interface AuthService { @FormUrlEncoded @POST("oauth/token") fun fetchOAuthToken( @Field("client_id") clientId: String, @Field("client_secret") clientSecret: String, @Field("redirect_uri") redirectUri: String, @Field("code") code: String, @Field("grant_type") grantType: String ): Single<AccessToken> @FormUrlEncoded @POST("api/v1/apps") fun authenticateApp( @Field("client_name") clientName: String, @Field("redirect_uris") redirectUri: String, @Field("scopes") scopes: String, @Field("website") website: String ): Single<AppCredentials> }
3141182615
app/src/main/kotlin/com/bl_lia/kirakiratter/data/repository/datasource/auth/AuthService.kt
package de.markhaehnel.rbtv.rocketbeanstv import androidx.test.InstrumentationRegistry import androidx.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("de.markhaehnel.rbtv.rocketbeanstv", appContext.packageName) } }
1070440991
app/src/androidTest/java/de/markhaehnel/rbtv/rocketbeanstv/ExampleInstrumentedTest.kt
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho import android.graphics.Rect import android.view.View import com.facebook.litho.testing.LegacyLithoViewRule import com.facebook.litho.testing.testrunner.LithoTestRunner import com.facebook.litho.widget.MountSpecLifecycleTester import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(LithoTestRunner::class) class DynamicPropsExtensionTest { @JvmField @Rule val lithoViewRule: LegacyLithoViewRule = LegacyLithoViewRule() @Test fun `when dynamic vale is set should override attribute set by MountSpec`() { val c: ComponentContext = lithoViewRule.context val root = MountSpecLifecycleTester.create(c) .intrinsicSize(Size(100, 100)) .lifecycleTracker(LifecycleTracker()) .defaultScale(0.5f) .scaleX(DynamicValue(0.2f)) .scaleY(DynamicValue(0.2f)) .build() lithoViewRule.render { root } val content: View = lithoViewRule.lithoView.getChildAt(0) assertThat(content.scaleX) .describedAs("scale should be applied from the dynamic value") .isEqualTo(0.2f) // unmount everything lithoViewRule.useComponentTree(null) assertThat(content.scaleX) .describedAs("scale should be restored to the initial value") .isEqualTo(0.5f) } @Test fun `when dynamic vale is set on LithoView should be unset when root is unmounted`() { val c: ComponentContext = lithoViewRule.context val root = Column.create(c) .alpha(DynamicValue(0.2f)) .child( MountSpecLifecycleTester.create(c) .intrinsicSize(Size(100, 100)) .lifecycleTracker(LifecycleTracker())) .build() lithoViewRule.render { root } assertThat(lithoViewRule.lithoView.alpha) .describedAs("alpha should be applied from the dynamic value") .isEqualTo(0.2f) lithoViewRule.componentTree.mountComponent(Rect(0, -10, 1080, -5), true) assertThat(lithoViewRule.lithoView.alpha) .describedAs("alpha should be restored to default value") .isEqualTo(1f) } }
1533390304
litho-it/src/test/java/com/facebook/litho/DynamicPropsExtensionTest.kt
/* * The MIT License (MIT) * * FXGL - JavaFX Game Library * * Copyright (c) 2015-2016 AlmasB (almaslvl@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.almasb.fxglgames.outrun import com.almasb.fxgl.entity.component.Component import javafx.beans.property.SimpleDoubleProperty import java.lang.Math.min /** * * * @author Almas Baimagambetov (almaslvl@gmail.com) */ class PlayerComponent : Component() { private var speed = 0.0 private var dy = 0.0 val boost = SimpleDoubleProperty(100.0) override fun onUpdate(tpf: Double) { speed = tpf * 200 dy += tpf / 4; if (entity.x < 80 || entity.rightX > 600 - 80) { if (dy > 0.017) { dy -= tpf } } entity.y -= dy boost.set(min(boost.get() + tpf * 5, 100.0)) } fun getSpeed() = dy fun up() { entity.translateY(-speed) } fun down() { entity.translateY(speed) } fun left() { if (entity.x >= speed) entity.translateX(-speed) } fun right() { if (entity.rightX + speed <= 600) entity.translateX(speed) } fun boost() { if (boost.get() <= speed * 2) return boost.set(Math.max(boost.get() - speed / 2, 0.0)) entity.y -= speed } fun applyExtraBoost() { dy += 10 } fun removeExtraBoost() { dy = Math.max(0.0, dy - 10) } fun reset() { dy = 0.0 // val anim = fadeOutIn(entity.view, Duration.seconds(1.5)) // anim.animatedValue.interpolator = Interpolators.BOUNCE.EASE_IN() // anim.startInPlayState() } }
4219513549
OutRun/src/main/kotlin/com/almasb/fxglgames/outrun/PlayerComponent.kt
package net.dinkla.raytracer.math import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.assertEquals class PolynomialsTest { @Test @Throws(Exception::class) fun testSolveQuadric() { // A*x^2 + B*x + C = 0 val s1 = doubleArrayOf(-16.0, 0.0, 1.0) val sol = doubleArrayOf(0.0, 0.0) val num = Polynomials.solveQuadric(s1, sol) assertEquals(2, num) assertEquals(4.0, sol[0]) assertEquals(-4.0, sol[1]) } @Test @Throws(Exception::class) fun testSolveQuartic() { // A*x^4 + B*x^3 + C*x^2+ D*x + E = 0 val s1 = doubleArrayOf(1.2, -3.2, 1.7, 2.5, -1.02) val sol = doubleArrayOf(0.0, 0.0, 0.0, 0.0) val num = Polynomials.solveQuartic(s1, sol) println("num=" + num) for (f in sol) { println("f=" + f) } } @Test @Throws(Exception::class) fun testSolveCubic() { // A*x^3 + B*x^2 + C*x + D = 0 val s1 = doubleArrayOf(0.0, 0.0, 0.0, 1.0) val sol = doubleArrayOf(0.0, 0.0, 0.0) var num = Polynomials.solveCubic(s1, sol) assertEquals(1, num) assertEquals(0.0, sol[0]) val s2 = doubleArrayOf(8.0, 0.0, 0.0, 1.0) num = Polynomials.solveCubic(s2, sol) assertEquals(1, num) assertEquals(-2.0, sol[0]) val s3 = doubleArrayOf(-8.0, 0.0, 0.0, 1.0) num = Polynomials.solveCubic(s3, sol) assertEquals(1, num) assertEquals(2.0, sol[0]) val s4 = doubleArrayOf(1.2, -3.2, 1.7, 2.5) num = Polynomials.solveCubic(s4, sol) assertEquals(1, num) assertEquals(-1.63938, sol[0], 0.00001) /* System.out.println("num=" + num); for (double f : sol) { System.out.println("f=" + f); } */ } }
628917214
src/test/kotlin/net/dinkla/raytracer/math/PolynomialsTest.kt
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.media.data.database.model import androidx.room.Entity import androidx.room.PrimaryKey import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi /** * A table to store playlist information. */ @ExperimentalHorologistMediaDataApi @Entity public data class PlaylistEntity( @PrimaryKey val playlistId: String, val name: String, val artworkUri: String? )
317901811
media-data/src/main/java/com/google/android/horologist/media/data/database/model/PlaylistEntity.kt
package br.com.codeteam.ctanywhere.ext import android.content.Context import android.content.pm.PackageManager import android.graphics.drawable.Drawable import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat /** * Created by Bruno Rodrigues e Rodrigues on 21/05/2018. */ fun Context.hasPermissions(vararg permissions: String): Boolean { for (permission in permissions) { if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) { return false } } return true } @Suppress("unused") fun Context.checkSelfPermissions(permission: String) = ContextCompat.checkSelfPermission(this, permission) fun Context.getColorCompat(@ColorRes res: Int): Int = ContextCompat.getColor(this, res) @Suppress("unused") fun Context.getDrawableCompat(@DrawableRes res: Int): Drawable = ContextCompat.getDrawable(this, res)!!
2581933500
app/src/main/java/br/com/codeteam/ctanywhere/ext/ContextExt.kt
package com.zhuinden.simplestacktutorials.steps.step_7.features.profile import android.os.Bundle import android.view.View import android.widget.Toast import com.zhuinden.simplestackextensions.fragments.KeyedFragment import com.zhuinden.simplestacktutorials.R class ProfileFragment : KeyedFragment(R.layout.step7_profile_fragment) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) Toast.makeText(requireContext(), "Welcome!", Toast.LENGTH_LONG).show() } }
1667724498
tutorials/tutorial-sample/src/main/java/com/zhuinden/simplestacktutorials/steps/step_7/features/profile/ProfileFragment.kt
package com.eden.orchid.swiftdoc.menu import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.theme.menus.OrchidMenuFactory import com.eden.orchid.api.theme.menus.MenuItem import com.eden.orchid.swiftdoc.SwiftdocModel import com.eden.orchid.swiftdoc.page.SwiftdocStatementPage import javax.inject.Inject @Description("Links to all Swift elements of a particular type.", name = "Swift Pages") class SwiftdocMenuItem @Inject constructor( context: OrchidContext, val model: SwiftdocModel ) : OrchidMenuFactory(context, "swiftdocPages", 100) { @Option lateinit var docType: String @Option lateinit var title: String override fun getMenuItems(): List<MenuItem> { val pages: List<SwiftdocStatementPage> = when(docType) { "class" -> model.classPages "struct" -> model.structPages "enum" -> model.enumPages "protocol" -> model.protocolPages "global" -> model.globalPages else -> emptyList() } if(!pages.isEmpty()) { return listOf( MenuItem.Builder(context) .title(title) .pages(pages.sortedBy { it.statement.name }) .build() ) } return emptyList() } }
3972374132
plugins/OrchidSwiftdoc/src/main/kotlin/com/eden/orchid/swiftdoc/menu/SwiftdocMenuItem.kt
/* * Copyright 2021 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.homebutton.main import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.pyamsoft.pydroid.arch.UiViewState import javax.inject.Inject internal interface ToolbarViewState : UiViewState { val topBarHeight: Int } internal class MutableToolbarViewState @Inject internal constructor() : ToolbarViewState { override var topBarHeight by mutableStateOf(0) }
4141823317
app/src/main/java/com/pyamsoft/homebutton/main/ToolbarViewState.kt
import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.JsonParser import com.google.gson.JsonPrimitive import javafx.application.Platform import javafx.embed.swing.JFXPanel import javafx.scene.Scene import javafx.scene.web.WebView import javax.swing.* import java.net.URL import javax.net.ssl.HttpsURLConnection import java.io.InputStreamReader import javax.swing.UIManager import java.awt.* import javax.swing.event.ListSelectionEvent import javax.swing.tree.DefaultMutableTreeNode import javax.swing.JTree import javax.swing.event.TreeModelEvent import javax.swing.event.TreeModelListener import javax.swing.plaf.metal.DefaultMetalTheme import javax.swing.plaf.metal.MetalLookAndFeel import javax.swing.tree.DefaultTreeCellRenderer import javax.swing.tree.DefaultTreeModel import kotlin.collections.ArrayList import javax.swing.text.html.HTMLDocument import javax.swing.text.html.HTMLEditorKit /** * Created by weston on 8/26/17. */ /** * TODO: * +Webview toggling * User profiles * (periodic?) Refresh */ class App : PubSub.Subscriber { companion object { init { // MetalLookAndFeel.setCurrentTheme(DefaultMetalTheme()) // UIManager.setLookAndFeel(MetalLookAndFeel()) UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel") } } val progressBar = JProgressBar(0, 30) var contentPane = JPanel() var storyControlPanel = JPanel() var storyPanel: JPanel = JPanel() var mainRightPane = JPanel() val listModel = DefaultListModel<Story>() val storyList = JList(listModel) val userLabel = JLabel() val pointsLabel = JLabel() val storyTimeLabel = JLabel() val storyURLLabel = JLabel() val commentCountLabel = JLabel() val contentToggleButton = JButton("View Page") var headlinePanel = JPanel() var storyIconPanel = JLabel() var commentTree = JTree() var commentTreeRoot = DefaultMutableTreeNode() var commentsProgressBar = JProgressBar() var loadedCommentCount = 0 val jfxPanel = JFXPanel() var activeStory: Story? = null var viewingComments = true init { val frame = JFrame("Hacker News") val screenSize = Toolkit.getDefaultToolkit().screenSize val frameSize = Dimension((screenSize.width*0.90f).toInt(), (screenSize.height*0.85f).toInt()) frame.size = frameSize frame.contentPane = contentPane contentPane.preferredSize = frameSize contentPane.layout = GridBagLayout() val c = GridBagConstraints() c.anchor = GridBagConstraints.CENTER progressBar.preferredSize = Dimension(400, 25) progressBar.isStringPainted = true //Just add so the display updates. Not sure why, but //it delays showing the progress bar if we don't do this. contentPane.add(JLabel(""), c) c.gridy = 1 contentPane.add(progressBar, c) progressBar.value = 0 frame.setLocation(screenSize.width / 2 - frame.size.width / 2, screenSize.height / 2 - frame.size.height / 2) frame.pack() frame.isVisible = true frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE val stories = getFrontPageStories() contentPane = JPanel(BorderLayout()) frame.contentPane = contentPane val mainPanel = getMainPanel(stories) contentPane.add(mainPanel) storyList.selectedIndex = 0 storyList.setCellRenderer(StoryCellRenderer()) contentToggleButton.addActionListener { if (activeStory != null) { if (viewingComments) { showPage(activeStory) } else { showComments(activeStory) } } } frame.revalidate() PubSub.subscribe(PubSub.STORY_ICON_LOADED, this) styleComponents() } fun styleComponents() { this.storyURLLabel.foreground = Color(100, 100, 100) this.storyList.background = Color(242, 242, 242) //Dimensions here are somewhat arbitrary, but if we want //equal priority given to both splitpane panels, they each //need minimum sizes mainRightPane.minimumSize = Dimension(300, 200) } fun getMainPanel(storyNodes: ArrayList<JsonObject>) : JComponent { val stories = storyNodes .filter { it.get("type").asString.equals("story", true) } .map { Story(it) } val def = DefaultListCellRenderer() val renderer = ListCellRenderer<Story> { list, value, index, isSelected, cellHasFocus -> def.getListCellRendererComponent(list, value.title, index, isSelected, cellHasFocus) } storyList.cellRenderer = renderer storyList.addListSelectionListener { e: ListSelectionEvent? -> if (e != null) { if (!e.valueIsAdjusting) { changeActiveStory(stories[storyList.selectedIndex]) } } } for (story in stories) { listModel.addElement(story) } mainRightPane = buildMainRightPanel() val storyScroller = JScrollPane(storyList) storyScroller.minimumSize = Dimension(200, 200) storyScroller.verticalScrollBar.unitIncrement = 16 val splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, storyScroller, mainRightPane) splitPane.isOneTouchExpandable = true return splitPane } fun changeActiveStory(story: Story) { activeStory = story userLabel.text = "Posted by: ${story.user}" pointsLabel.text = "Points: ${story.points}" storyTimeLabel.text = "Time: ${story.time}" commentCountLabel.text = "Comments: ${story.totalComments}" if (story.url != null) { storyURLLabel.text = story.url } showComments(activeStory) } fun showComments(story: Story?) { if (story != null) { viewingComments = true contentToggleButton.text = "View Page" storyPanel.removeAll() storyPanel.add(getCommentsPanel(story)) if (story.bigIcon != null) { storyIconPanel.icon = ImageIcon(story.bigIcon) } else { storyIconPanel.icon = story.favicon } storyIconPanel.preferredSize = Dimension(storyIconPanel.icon.iconWidth+6, storyIconPanel.icon.iconHeight) storyIconPanel.border = BorderFactory.createEmptyBorder(0, 3, 0, 3) headlinePanel.preferredSize = Dimension(storyControlPanel.size.width, Math.max(32, storyIconPanel.icon.iconHeight)) loadComments(story) } } fun showPage(story: Story?) { if (story != null) { viewingComments = false contentToggleButton.text = "View Comments" cancelCommentLoading() storyPanel.removeAll() storyPanel.add(jfxPanel) Platform.runLater { val webView = WebView() jfxPanel.scene = Scene(webView) webView!!.engine.load(story.url) } storyPanel.revalidate() } else { println("Tried showing page but story was null") } } override fun messageArrived(eventName: String, data: Any?) { if (eventName == PubSub.STORY_ICON_LOADED) { storyList.repaint() storyControlPanel.repaint() } } fun loadComments(story: Story) { if (story.totalComments == 0) return Thread(Runnable { if (story.kids != null) { var index = 0 val iter = story.kids.iterator() while(iter.hasNext() && viewingComments) { val commentId = iter.next().asInt val address = "$index" loadCommentAux(Comment(getItem(commentId), address), address) index++ } } }).start() } fun loadCommentAux(comment: Comment, treeAddress: String) { commentArrived(comment, treeAddress) if (comment.kids != null) { var index = 0 val iter = comment.kids.iterator() while(iter.hasNext() && viewingComments) { val commentId = iter.next().asInt val address = treeAddress+";$index" loadCommentAux(Comment(getItem(commentId), address), address) index++ } } } fun commentArrived(comment: Comment, treeAddress: String) { if (!viewingComments) return addNodeAtAddress(DefaultMutableTreeNode(comment), comment.treeAddress) commentsProgressBar.value = ++loadedCommentCount if (loadedCommentCount >= commentsProgressBar.maximum) { val parent = commentsProgressBar.parent if (parent != null) { parent.remove(commentsProgressBar) parent.revalidate() } } } fun cancelCommentLoading() { loadedCommentCount = commentsProgressBar.maximum } fun addNodeAtAddress(node: DefaultMutableTreeNode, address: String) { if (!viewingComments) return val addressArray = address.split(";") var parentNode = commentTreeRoot for ((index, addressComponent) in addressArray.withIndex()) { // Don't use the last component in the addressArray since that's the index // which the child should be added at if (index < addressArray.size - 1) { val childIndex = Integer.parseInt("$addressComponent") if (childIndex < parentNode.childCount) { parentNode = parentNode.getChildAt(childIndex) as DefaultMutableTreeNode } } } val childIndex = Integer.parseInt(addressArray[addressArray.size-1]) (commentTree.model as DefaultTreeModel).insertNodeInto(node, parentNode, childIndex) } fun getCommentsPanel(story: Story) : JPanel { loadedCommentCount = 0 val panel = JPanel(BorderLayout()) commentTreeRoot = DefaultMutableTreeNode("Comments") commentTree = JTree(commentTreeRoot) commentTree.toggleClickCount = 1 commentTree.cellRenderer = CommentCellRenderer() commentTree.model.addTreeModelListener(ExpandTreeListener(commentTree)) val treeScroller = JScrollPane(commentTree) treeScroller.verticalScrollBar.unitIncrement = 16 treeScroller.horizontalScrollBar.unitIncrement = 16 if (!(UIManager.getLookAndFeel() is MetalLookAndFeel)) { treeScroller.background = Color(242, 242, 242) commentTree.background = Color(242, 242, 242) } panel.add(treeScroller, BorderLayout.CENTER) var totalComments = 0 if (story.totalComments != null) { totalComments = story.totalComments } commentsProgressBar = JProgressBar() commentsProgressBar.minimum = 0 commentsProgressBar.maximum = totalComments panel.add(commentsProgressBar, BorderLayout.NORTH) return panel } fun buildMainRightPanel() : JPanel { val root = JPanel() root.layout = BorderLayout() storyControlPanel = JPanel(GridLayout(1, 1)) storyPanel = JPanel(BorderLayout()) root.add(storyControlPanel, BorderLayout.NORTH) headlinePanel = JPanel(BorderLayout()) headlinePanel.border = BorderFactory.createEmptyBorder(3, 3, 3, 3) headlinePanel.add(storyIconPanel, BorderLayout.WEST) headlinePanel.add(storyURLLabel, BorderLayout.CENTER) headlinePanel.add(contentToggleButton, BorderLayout.EAST) storyControlPanel.add(headlinePanel) root.add(storyPanel, BorderLayout.CENTER) return root } fun getFrontPageStories() : ArrayList<JsonObject> { val storyIDs = treeFromURL("https://hacker-news.firebaseio.com/v0/topstories.json") val iter = storyIDs.asJsonArray.iterator() val stories = ArrayList<JsonObject>() var count = 0 while (iter.hasNext()) { val id = (iter.next() as JsonPrimitive).asInt val story = getItem(id) stories.add(story.asJsonObject) count++ progressBar.value = count if (count > 29) break } return stories } fun getItem(id: Int) : JsonObject { val item = treeFromURL("https://hacker-news.firebaseio.com/v0/item/$id.json") return item.asJsonObject } fun treeFromURL(url: String) : JsonElement { val url = URL(url) val connection = (url.openConnection()) as HttpsURLConnection val reader = InputStreamReader(connection?.inputStream) val parser = JsonParser() val element = parser.parse(reader) reader.close() return element } class StoryCellRenderer : DefaultListCellRenderer() { override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) as JComponent this.border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(3, 3, 3, 3)) if (!isSelected && !cellHasFocus) { this.background = Color(242, 242, 242) } this.icon = (value as Story).favicon this.text = "<html><span style=\"color: #333333; font-size: 10px\">${value.title}</span><br><span style=\"color: #777777; font-size:8px;\"> ${value.points} points by ${value.user} ${value.time} | ${value.totalComments} comments</span></html>" return this } } class CommentCellRenderer : DefaultTreeCellRenderer() { override fun getTreeCellRendererComponent(tree: JTree?, value: Any?, sel: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component? { super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus) if ((value as DefaultMutableTreeNode).userObject !is Comment) { return JLabel() } val comment = value.userObject as Comment var originalCommentText = comment.text if (originalCommentText == null) originalCommentText = "" val panel = JPanel() panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS) panel.background = Color(225, 225, 235) val metaDataLabel = JLabel(comment.user + " " + comment.time) metaDataLabel.foreground = Color(60, 60, 60) metaDataLabel.font = Font("Arial", Font.PLAIN, 11) metaDataLabel.border = BorderFactory.createEmptyBorder(3, 3, 3, 3) panel.add(metaDataLabel) //Insert linebreaks periodically since this seems to be the only way to limit //the width of the html rendering JTextPane without also limiting the height var text = "" var index = 0 val words = originalCommentText.split(" ") for (word in words) { if (word.indexOf("<br>") != -1 || word.indexOf("</p>") != -1 || word.indexOf("</pre>") != -1) { index = 0 } else if (index > 20) { index = 0 text += "<br>" } text += " " + word index++ } val textPane = JTextPane() textPane.contentType = "text/html" textPane.isEditable = false val doc = textPane.document as HTMLDocument val editorKit = textPane.editorKit as HTMLEditorKit editorKit.insertHTML(doc, doc.length, text, 0, 0, null) textPane.background = Color(242, 242, 255) textPane.border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5)) textPane.minimumSize = Dimension(textPane.size.width, textPane.size.height) panel.add(textPane) return panel } } class ExpandTreeListener(theTree: JTree) : TreeModelListener { val tree = theTree override fun treeStructureChanged(e: TreeModelEvent?) { } override fun treeNodesChanged(e: TreeModelEvent?) { } override fun treeNodesRemoved(e: TreeModelEvent?) { } override fun treeNodesInserted(e: TreeModelEvent?) { if (e != null) { if (e.treePath.pathCount == 1) { this.tree.expandPath(e.treePath) } } } } } fun main(args: Array<String>) { App() }
376006442
src/main/java/App.kt
/* * Copyright 2020 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.favorites.presenter import com.github.vase4kin.teamcityapp.account.create.data.OnLoadingListener import com.github.vase4kin.teamcityapp.base.list.presenter.BaseListPresenterImpl import com.github.vase4kin.teamcityapp.favorites.interactor.FavoritesInteractor import com.github.vase4kin.teamcityapp.favorites.tracker.FavoritesTracker import com.github.vase4kin.teamcityapp.favorites.view.FavoritesView import com.github.vase4kin.teamcityapp.navigation.api.BuildType import com.github.vase4kin.teamcityapp.navigation.api.NavigationItem import com.github.vase4kin.teamcityapp.navigation.data.NavigationDataModel import com.github.vase4kin.teamcityapp.navigation.data.NavigationDataModelImpl import com.github.vase4kin.teamcityapp.navigation.extractor.NavigationValueExtractor import com.github.vase4kin.teamcityapp.navigation.router.NavigationRouter import javax.inject.Inject /** * Presenter to manage logic of favorites list */ class FavoritesPresenterImpl @Inject constructor( view: FavoritesView, interactor: FavoritesInteractor, tracker: FavoritesTracker, valueExtractor: NavigationValueExtractor, private val router: NavigationRouter ) : BaseListPresenterImpl<NavigationDataModel, NavigationItem, FavoritesView, FavoritesInteractor, FavoritesTracker, NavigationValueExtractor>( view, interactor, tracker, valueExtractor ), FavoritesView.ViewListener { /** * {@inheritDoc} */ override fun loadData(loadingListener: OnLoadingListener<List<NavigationItem>>, update: Boolean) { dataManager.loadFavorites(loadingListener, update) } /** * {@inheritDoc} */ override fun initViews() { super.initViews() view.setViewListener(this) } /** * {@inheritDoc} */ override fun createModel(data: List<NavigationItem>): NavigationDataModel { return NavigationDataModelImpl(data.toMutableList()) } /** * {@inheritDoc} */ override fun onClick(navigationItem: NavigationItem) { if (navigationItem is BuildType) { router.startBuildListActivity(navigationItem.getName(), navigationItem.getId()) tracker.trackUserOpensBuildType() } else { router.startNavigationActivity(navigationItem.name, navigationItem.getId()) } } /** * {@inheritDoc} */ override fun onViewsDestroyed() { super.onViewsDestroyed() dataManager.unsubscribe() } /** * {@inheritDoc} */ override fun onResume() { super.onResume() view.showRefreshAnimation() loadData(loadingListener, false) } /** * On pause activity callback */ fun onPause() { view.hideRefreshAnimation() dataManager.unsubscribe() } /** * {@inheritDoc} */ override fun loadDataOnViewsCreated() { // Don't load data when view is created, only on resume } }
4131956778
app/src/main/java/com/github/vase4kin/teamcityapp/favorites/presenter/FavoritesPresenterImpl.kt
package haru.worker.domain.model.processor interface TaskProcessingParams { }
1182895094
haru-worker/src/main/kotlin/haru/worker/domain/model/processor/TaskProcessingParams.kt
/* * Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/gpl.html */ package com.etesync.syncadapter.log import org.apache.commons.lang3.StringUtils import org.apache.commons.lang3.exception.ExceptionUtils import org.apache.commons.lang3.time.DateFormatUtils import java.util.logging.Formatter import java.util.logging.LogRecord class PlainTextFormatter private constructor(private val logcat: Boolean) : Formatter() { override fun format(r: LogRecord): String { val builder = StringBuilder() if (!logcat) builder.append(DateFormatUtils.format(r.millis, "yyyy-MM-dd HH:mm:ss")) .append(" ").append(r.threadID).append(" ") if (r.sourceClassName.replaceFirst("\\$.*".toRegex(), "") != r.loggerName) builder.append("[").append(shortClassName(r.sourceClassName)).append("] ") builder.append(r.message) if (r.thrown != null) builder.append("\nEXCEPTION ") .append(ExceptionUtils.getStackTrace(r.thrown)) if (r.parameters != null) { var idx = 1 for (param in r.parameters) builder.append("\n\tPARAMETER #").append(idx++).append(" = ").append(param) } if (!logcat) builder.append("\n") return builder.toString() } private fun shortClassName(className: String): String? { val s = StringUtils.replace(className, "com.etesync.syncadapter.", "") return StringUtils.replace(s, "at.bitfire.", "") } companion object { val LOGCAT = PlainTextFormatter(true) val DEFAULT = PlainTextFormatter(false) } }
922594615
app/src/main/java/com/etesync/syncadapter/log/PlainTextFormatter.kt
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * 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.devtools.ksp.symbol.impl.java import com.google.devtools.ksp.KSObjectCache import com.google.devtools.ksp.isConstructor import com.google.devtools.ksp.memoized import com.google.devtools.ksp.processing.impl.ResolverImpl import com.google.devtools.ksp.processing.impl.workaroundForNested import com.google.devtools.ksp.symbol.* import com.google.devtools.ksp.symbol.impl.* import com.google.devtools.ksp.symbol.impl.binary.getAllFunctions import com.google.devtools.ksp.symbol.impl.binary.getAllProperties import com.google.devtools.ksp.symbol.impl.kotlin.KSErrorType import com.google.devtools.ksp.symbol.impl.kotlin.KSExpectActualNoImpl import com.google.devtools.ksp.symbol.impl.kotlin.KSNameImpl import com.google.devtools.ksp.symbol.impl.kotlin.getKSTypeCached import com.google.devtools.ksp.symbol.impl.replaceTypeArguments import com.google.devtools.ksp.symbol.impl.synthetic.KSConstructorSyntheticImpl import com.google.devtools.ksp.toKSModifiers import com.intellij.psi.PsiClass import com.intellij.psi.PsiEnumConstant import com.intellij.psi.PsiJavaFile import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithStarProjections class KSClassDeclarationJavaImpl private constructor(val psi: PsiClass) : KSClassDeclaration, KSDeclarationJavaImpl(psi), KSExpectActual by KSExpectActualNoImpl() { companion object : KSObjectCache<PsiClass, KSClassDeclarationJavaImpl>() { fun getCached(psi: PsiClass) = cache.getOrPut(psi) { KSClassDeclarationJavaImpl(psi) } } override val origin = Origin.JAVA override val location: Location by lazy { psi.toLocation() } override val annotations: Sequence<KSAnnotation> by lazy { psi.annotations.asSequence().map { KSAnnotationJavaImpl.getCached(it) }.memoized() } override val classKind: ClassKind by lazy { when { psi.isAnnotationType -> ClassKind.ANNOTATION_CLASS psi.isInterface -> ClassKind.INTERFACE psi.isEnum -> ClassKind.ENUM_CLASS else -> ClassKind.CLASS } } override val containingFile: KSFile? by lazy { KSFileJavaImpl.getCached(psi.containingFile as PsiJavaFile) } override val isCompanionObject = false // Could the resolution ever fail? private val descriptor: ClassDescriptor? by lazy { ResolverImpl.instance!!.moduleClassResolver.resolveClass(JavaClassImpl(psi).apply { workaroundForNested() }) } // TODO in 1.5 + jvmTarget 15, will we return Java permitted types? override fun getSealedSubclasses(): Sequence<KSClassDeclaration> = emptySequence() override fun getAllFunctions(): Sequence<KSFunctionDeclaration> = descriptor?.getAllFunctions() ?: emptySequence() override fun getAllProperties(): Sequence<KSPropertyDeclaration> = descriptor?.getAllProperties() ?: emptySequence() override val declarations: Sequence<KSDeclaration> by lazy { val allDeclarations = ( psi.fields.asSequence().map { when (it) { is PsiEnumConstant -> KSClassDeclarationJavaEnumEntryImpl.getCached(it) else -> KSPropertyDeclarationJavaImpl.getCached(it) } } + psi.innerClasses.map { KSClassDeclarationJavaImpl.getCached(it) } + psi.constructors.map { KSFunctionDeclarationJavaImpl.getCached(it) } + psi.methods.map { KSFunctionDeclarationJavaImpl.getCached(it) } ) .distinct() // java annotation classes are interface. they get a constructor in .class // hence they should get one here. if (classKind == ClassKind.ANNOTATION_CLASS || !psi.isInterface) { val hasConstructor = allDeclarations.any { it is KSFunctionDeclaration && it.isConstructor() } if (hasConstructor) { allDeclarations.memoized() } else { (allDeclarations + KSConstructorSyntheticImpl.getCached(this)).memoized() } } else { allDeclarations.memoized() } } override val modifiers: Set<Modifier> by lazy { val modifiers = mutableSetOf<Modifier>() modifiers.addAll(psi.toKSModifiers()) if (psi.isAnnotationType) { modifiers.add(Modifier.ANNOTATION) } if (psi.isEnum) { modifiers.add(Modifier.ENUM) } modifiers } override val primaryConstructor: KSFunctionDeclaration? = null override val qualifiedName: KSName by lazy { KSNameImpl.getCached(psi.qualifiedName!!) } override val simpleName: KSName by lazy { KSNameImpl.getCached(psi.name!!) } override val superTypes: Sequence<KSTypeReference> by lazy { val adjusted = if (!psi.isInterface && psi.superTypes.size > 1) { psi.superTypes.filterNot { it.className == "Object" && it.canonicalText == "java.lang.Object" } } else { psi.superTypes.toList() } adjusted.asSequence().map { KSTypeReferenceJavaImpl.getCached(it, this) }.memoized() } override val typeParameters: List<KSTypeParameter> by lazy { psi.typeParameters.map { KSTypeParameterJavaImpl.getCached(it) } } override fun asType(typeArguments: List<KSTypeArgument>): KSType { return descriptor?.let { it.defaultType.replaceTypeArguments(typeArguments)?.let { getKSTypeCached(it, typeArguments) } } ?: KSErrorType } override fun asStarProjectedType(): KSType { return descriptor?.let { getKSTypeCached(it.defaultType.replaceArgumentsWithStarProjections()) } ?: KSErrorType } override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R { return visitor.visitClassDeclaration(this, data) } }
2685645873
compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/java/KSClassDeclarationJavaImpl.kt
/* AndroidSwissKnife Copyright (C) 2016 macleod2486 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see [http://www.gnu.org/licenses/]. */ package com.macleod2486.androidswissknife.components import android.Manifest import android.content.pm.PackageManager import android.graphics.SurfaceTexture import android.hardware.Camera import androidx.core.app.ActivityCompat import androidx.fragment.app.FragmentActivity import androidx.core.content.ContextCompat import android.util.Log import android.view.View import android.widget.Toast class Flashlight(var activity: FragmentActivity, var requestCode: Int) : View.OnClickListener { var torchOn = false lateinit var cam: Camera lateinit var p: Camera.Parameters override fun onClick(view: View) { Log.i("Flashlight", "Current toggle $torchOn") if (checkPermissions()) { if (torchOn) { turnOffLight() } else { turnOnLight() } } } fun toggleLight() { if (torchOn) { turnOffLight() } else { turnOnLight() } } private fun turnOnLight() { Log.i("Flashlight", "Toggling on light") try { cam = Camera.open() p = cam.getParameters() p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH) cam.setParameters(p) val mPreviewTexture = SurfaceTexture(0) cam.setPreviewTexture(mPreviewTexture) cam.startPreview() torchOn = true } catch (ex: Exception) { torchOn = false Log.e("Flashlight", ex.toString()) } } private fun turnOffLight() { Log.i("Flashlight", "Toggling off light") torchOn = false cam.stopPreview() cam.release() } private fun checkPermissions(): Boolean { var allowed = false if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) { Toast.makeText(activity.applicationContext, "Need to enable camera permissions", Toast.LENGTH_SHORT).show() } else { ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.CAMERA), requestCode) } } else { allowed = true } return allowed } }
3796758285
app/src/main/java/com/macleod2486/androidswissknife/components/Flashlight.kt
package wu.seal.jsontokotlin import com.google.gson.Gson import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.editor.Caret import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import wu.seal.jsontokotlin.feedback.StartAction import wu.seal.jsontokotlin.feedback.SuccessCompleteAction import wu.seal.jsontokotlin.feedback.dealWithException import wu.seal.jsontokotlin.feedback.sendActionInfo import wu.seal.jsontokotlin.model.UnSupportJsonException import wu.seal.jsontokotlin.ui.JsonInputDialog import wu.seal.jsontokotlin.utils.* import java.net.URL import java.util.* import kotlin.math.max /** * Plugin action * Created by Seal.Wu on 2017/8/18. */ class InsertKotlinClassAction : AnAction("Kotlin data classes from JSON") { private val gson = Gson() override fun actionPerformed(event: AnActionEvent) { var jsonString = "" try { actionStart() val project = event.getData(PlatformDataKeys.PROJECT) val caret = event.getData(PlatformDataKeys.CARET) val editor = event.getData(PlatformDataKeys.EDITOR_EVEN_IF_INACTIVE) if (couldNotInsertCode(editor)) return val document = editor?.document ?: return val editorText = document.text /** * temp class name for insert */ var tempClassName = "" val couldGetAndReuseClassNameInCurrentEditFileForInsertCode = couldGetAndReuseClassNameInCurrentEditFileForInsertCode(editorText) if (couldGetAndReuseClassNameInCurrentEditFileForInsertCode) { /** * auto obtain the current class name */ tempClassName = getCurrentEditFileTemClassName(editorText) } val inputDialog = JsonInputDialog(tempClassName, project!!) inputDialog.show() val className = inputDialog.getClassName() val inputString = inputDialog.inputString val json = if (inputString.startsWith("http")) { URL(inputString).readText() } else inputString if (json.isEmpty()) { return } jsonString = json if (reuseClassName(couldGetAndReuseClassNameInCurrentEditFileForInsertCode, className, tempClassName)) { executeCouldRollBackAction(project) { /** * if you don't clean then we will trick a conflict with two same class name error */ cleanCurrentEditFile(document) } } if (insertKotlinCode(project, document, className, jsonString, caret)) { actionComplete() } } catch (e: UnSupportJsonException) { val advice = e.advice Messages.showInfoMessage(dealWithHtmlConvert(advice), "Tip") } catch (e: Throwable) { dealWithException(jsonString, e) throw e } } private fun dealWithHtmlConvert(advice: String) = advice.replace("<", "&lt;").replace(">", "&gt;") private fun reuseClassName( couldGetAndReuseClassNameInCurrentEditFileForInserCode: Boolean, className: String, tempClassName: String ) = couldGetAndReuseClassNameInCurrentEditFileForInserCode && className == tempClassName private fun couldNotInsertCode(editor: Editor?): Boolean { if (editor == null || editor.document.isWritable.not()) { Messages.showWarningDialog("Please open a file in edited state for inserting Kotlin code!", "No Edited File") return true } return false } private fun actionComplete() { Thread { sendActionInfo(gson.toJson(SuccessCompleteAction())) }.start() } private fun actionStart() { Thread { sendActionInfo(gson.toJson(StartAction())) }.start() } private fun insertKotlinCode( project: Project?, document: Document, className: String, jsonString: String, caret: Caret? ): Boolean { ClassImportDeclarationWriter.insertImportClassCode(project, document) val codeMaker: KotlinClassCodeMaker try { //passing current file directory along with className and json val kotlinClass = KotlinClassMaker(className, jsonString).makeKotlinClass() codeMaker = KotlinClassCodeMaker(kotlinClass, jsonString.isJSONSchema()) } catch (e: IllegalFormatFlagsException) { e.printStackTrace() Messages.showErrorDialog(e.message, "UnSupport Json") return false } val generateClassesString = codeMaker.makeKotlinClassCode() executeCouldRollBackAction(project) { var offset: Int if (caret != null) { offset = caret.offset if (offset == 0) { offset = document.textLength } val lastPackageKeywordLineEndIndex = try { "^[\\s]*package\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.last } catch (e: Exception) { -1 } val lastImportKeywordLineEndIndex = try { "^[\\s]*import\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.last } catch (e: Exception) { -1 } if (offset < lastPackageKeywordLineEndIndex) { offset = lastPackageKeywordLineEndIndex + 1 } if (offset < lastImportKeywordLineEndIndex) { offset = lastImportKeywordLineEndIndex + 1 } } else { offset = document.textLength } document.insertString( max(offset, 0), ClassCodeFilter.removeDuplicateClassCode(generateClassesString) ) } return true } private fun cleanCurrentEditFile(document: Document, editorText: String = document.text) { val cleanText = getCleanText(editorText) document.setText(cleanText) } fun getCleanText(editorText: String): String { val tempCleanText = editorText.substringBeforeLast("class") return if (tempCleanText.trim().endsWith("data")) tempCleanText.trim().removeSuffix("data") else tempCleanText } fun getCurrentEditFileTemClassName(editorText: String) = editorText.substringAfterLast("class") .substringBefore("(").substringBefore("{").trim() /** * whether we could reuse current class name declared in the edit file for inserting data class code * if we could use it,then we would clean the kotlin file as it was new file without any class code . */ fun couldGetAndReuseClassNameInCurrentEditFileForInsertCode(editorText: String): Boolean { try { val removeDocComment = editorText.replace(Regex("/\\*\\*(.|\n)*\\*/", RegexOption.MULTILINE), "") val removeDocCommentAndPackageDeclareText = removeDocComment .replace(Regex("^(?:\\s*package |\\s*import ).*$", RegexOption.MULTILINE), "") removeDocCommentAndPackageDeclareText.run { if (numberOf("class") == 1 && (substringAfter("class").containsAnyOf(listOf("(", ":", "=")).not() || substringAfter("class").substringAfter("(").replace( Regex("\\s"), "" ).let { it == ")" || it == "){}" }) ) { return true } } } catch (e: Throwable) { e.printStackTrace() } return false } }
3278942107
src/main/kotlin/wu/seal/jsontokotlin/InsertKotlinClassAction.kt
package pl.mg6.likeornot.grid import io.reactivex.Single import io.reactivex.Single.zip import io.reactivex.functions.BiFunction import pl.mg6.likeornot.grid.api.LikableApi import pl.mg6.likeornot.grid.api.LikableFromApi import pl.mg6.likeornot.grid.entity.Likable fun getLikables(api: LikableApi, callLocalLikes: () -> Single<LikableIdToStatus>): Single<List<Likable>> = zip(api.call(), callLocalLikes.invoke(), BiFunction(::toLikableList)) private fun toLikableList(list: List<LikableFromApi>, uuidToStatus: LikableIdToStatus) = list.map { it.toLikable(uuidToStatus) } private fun LikableFromApi.toLikable(uuidToStatus: LikableIdToStatus) = Likable(uuid, name, image?.single(), uuidToStatus[uuid])
377472905
app/src/main/java/pl/mg6/likeornot/grid/LikableService.kt
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /* Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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 com.jtransc.compression.jzlib import com.jtransc.annotation.JTranscInvisible import java.io.IOException @JTranscInvisible class GZIPInputStream( `in`: java.io.InputStream?, inflater: Inflater?, size: Int, close_in: Boolean ) : InflaterInputStream(`in`, inflater, size, close_in) { @JvmOverloads constructor( `in`: java.io.InputStream?, size: Int = DEFAULT_BUFSIZE, close_in: Boolean = true ) : this(`in`, Inflater(15 + 16), size, close_in) { myinflater = true } val modifiedtime: Long get() = inflater.istate.getGZIPHeader().getModifiedTime() val oS: Int get() = inflater.istate.getGZIPHeader().getOS() val name: String get() = inflater.istate.getGZIPHeader().getName() val comment: String get() = inflater.istate.getGZIPHeader().getComment() /*DONE*/ @get:Throws(GZIPException::class) val cRC: Long get() { if (inflater.istate.mode !== 12 /*DONE*/) throw GZIPException("checksum is not calculated yet.") return inflater.istate.getGZIPHeader().getCRC() } @Throws(IOException::class) override fun readHeader() { val empty: ByteArray = "".toByteArray() inflater.setOutput(empty, 0, 0) inflater.setInput(empty, 0, 0, false) val b = ByteArray(10) var n = fill(b) if (n != 10) { if (n > 0) { inflater.setInput(b, 0, n, false) //inflater.next_in_index = n; inflater.next_in_index = 0 inflater.avail_in = n } throw IOException("no input") } inflater.setInput(b, 0, n, false) val b1 = ByteArray(1) do { if (inflater.avail_in <= 0) { val i: Int = `in`.read(b1) if (i <= 0) throw IOException("no input") inflater.setInput(b1, 0, 1, true) } val err: Int = inflater.inflate(JZlib.Z_NO_FLUSH) if (err != 0 /*Z_OK*/) { val len: Int = 2048 - inflater.next_in.length if (len > 0) { val tmp = ByteArray(len) n = fill(tmp) if (n > 0) { inflater.avail_in += inflater.next_in_index inflater.next_in_index = 0 inflater.setInput(tmp, 0, n, true) } } //inflater.next_in_index = inflater.next_in.length; inflater.avail_in += inflater.next_in_index inflater.next_in_index = 0 throw IOException(inflater.msg) } } while (inflater.istate.inParsingHeader()) } private fun fill(buf: ByteArray): Int { val len = buf.size var n = 0 do { var i = -1 try { i = `in`.read(buf, n, buf.size - n) } catch (e: IOException) { } if (i == -1) { break } n += i } while (n < len) return n } }
943564780
benchmark_kotlin_mpp/wip/jzlib/GZIPInputStream.kt
#!/usr/bin/env kscript /** * Functions for executing shell commands and receiving the result. */ import java.io.BufferedReader import java.io.File import java.io.IOException import java.lang.ProcessBuilder.Redirect import java.util.concurrent.TimeUnit import kotlin.system.exitProcess /** * Executes the receiving string and returns the stdOut as a single line. * If the result is more than one line an exception is thrown. * @throws IOException if an I/O error occurs */ fun String.executeForSingleLine( workingDir: File = File("."), timeoutAmount: Long = 60, timeoutUnit: TimeUnit = TimeUnit.SECONDS, suppressStderr: Boolean = false, redactedTokens: List<String> = emptyList(), throwOnFailure: Boolean = false ): String { val lines = executeForLines( workingDir, timeoutAmount, timeoutUnit, suppressStderr = suppressStderr, redactedTokens = redactedTokens, throwOnFailure = throwOnFailure ) .filter { it.isNotBlank() } return lines.singleOrNull() ?: throw IllegalStateException("Expected single line but got: $lines") } /** * Executes the receiving string and returns the stdOut as a list of all lines outputted. * @throws IOException if an I/O error occurs * @param clearQuotes If true, double quotes will be removed if they wrap the line */ fun String.executeForLines( workingDir: File = File("."), timeoutAmount: Long = 60, timeoutUnit: TimeUnit = TimeUnit.SECONDS, clearQuotes: Boolean = false, suppressStderr: Boolean = false, redactedTokens: List<String> = emptyList(), throwOnFailure: Boolean = false ): List<String> { return executeForBufferedReader( workingDir, timeoutAmount, timeoutUnit, suppressStderr = suppressStderr, redactedTokens = redactedTokens, throwOnFailure = throwOnFailure ) .readLines() .map { if (clearQuotes) it.removePrefix("\"").removeSuffix("\"") else it } } /** * Executes the receiving string and returns the stdOut as a BufferedReader. * @throws IOException if an I/O error occurs */ fun String.executeForBufferedReader( workingDir: File = File("."), timeoutAmount: Long = 60, timeoutUnit: TimeUnit = TimeUnit.SECONDS, suppressStderr: Boolean = false, redactedTokens: List<String> = emptyList(), throwOnFailure: Boolean = false ): BufferedReader { val stderrRedirectBehavior = if (suppressStderr) Redirect.PIPE else Redirect.INHERIT return execute( workingDir, timeoutAmount, timeoutUnit, stderrRedirectBehavior = stderrRedirectBehavior, redactedTokens = redactedTokens, throwOnFailure = throwOnFailure ).stdOut } /** * Executes the receiving string and returns the result, * including exit code, stdOut, and stdErr streams. * Some commands do not work if the command is redirected to PIPE. * Use ProcessBuilder.Redirect.INHERIT in those cases. * * @throws IOException if an I/O error occurs */ fun String.execute( workingDir: File = File("."), timeoutAmount: Long = 60, timeoutUnit: TimeUnit = TimeUnit.SECONDS, timeoutMessage: String? = null, stdoutRedirectBehavior: Redirect = Redirect.PIPE, stderrRedirectBehavior: Redirect = Redirect.PIPE, redactedTokens: List<String> = emptyList(), throwOnFailure: Boolean = false ): ProcessResult { var commandToLog = this redactedTokens.forEach { commandToLog = commandToLog.replace(it, "<redacted>") } // The command is disabled by default on local run to avoid cluttering people's consoles; // Only printed on CI or if KSCRIPT_SHELL_ACCESS_DEBUG is set if (!isMacOs() || !System.getenv("KSCRIPT_SHELL_ACCESS_DEBUG").isNullOrEmpty()) { System.err.println("Executing command [workingDir: '$workingDir']: $commandToLog") } return ProcessBuilder("/bin/sh", "-c", this) .directory(workingDir) .redirectOutput(stdoutRedirectBehavior) .redirectError(stderrRedirectBehavior) .start() .apply { waitFor(timeoutAmount, timeoutUnit) if (isAlive) { destroyForcibly() println("Command timed out after ${timeoutUnit.toSeconds(timeoutAmount)} seconds: '$commandToLog'") if ( stdoutRedirectBehavior.type() == Redirect.Type.PIPE || stderrRedirectBehavior.type() == Redirect.Type.PIPE ) { println( listOf( "Note: Timeout can potentially be due to deadlock when using stdout=PIPE and/or stderr=PIPE", " and the child process (subpocess running the command) generates enough output to a pipe", " (~50 KB) such that it blocks waiting for the OS pipe buffer to accept more data.", "Please consider writing to a stdout/stderr to temp-file instead in such situations!" ).joinToString("") ) } timeoutMessage?.let { println(it) } exitProcess(1) } } .let { process -> val result = ProcessResult(process.exitValue(), process.inputStream.bufferedReader(), process.errorStream.bufferedReader()) check(!(throwOnFailure && result.failed)) { "Command failed with exit-code(${process.exitValue()}): '$commandToLog'" } result } } fun isMacOs(): Boolean = System.getProperty("os.name").contains("mac", ignoreCase = true) data class ProcessResult(val exitCode: Int, val stdOut: BufferedReader, val stdErr: BufferedReader) { val succeeded: Boolean = exitCode == 0 val failed: Boolean = !succeeded } fun BufferedReader.print() { lineSequence().forEach { println(it) } }
2455664843
mock_generation/ShellAccess.kt
package com.openlattice.auditing interface AuditingManager { fun recordEvents(events: List<AuditableEvent>): Int }
3892875868
src/main/kotlin/com/openlattice/auditing/AuditingManager.kt
/* * Copyright 2016 Carlos Ballesteros Velasco * * 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.jtransc.ast.dependency import com.jtransc.ast.* import com.jtransc.error.noImpl // @TODO: Use generic visitor! object AstDependencyAnalyzer { enum class Reason { UNKNWON, STATIC } class Config( val reason: Reason = Reason.UNKNWON, val methodHandler: (AstExpr.CALL_BASE, AstDependencyAnalyzerGen) -> Unit = { b, d -> } ) @JvmStatic fun analyze(program: AstProgram, body: AstBody?, name: String? = null, config: Config): AstReferences { return AstDependencyAnalyzerGen(program, body, name, config = config).references } class AstDependencyAnalyzerGen(program: AstProgram, val body: AstBody?, val name: String? = null, val config: Config) { val methodHandler = config.methodHandler val ignoreExploring = hashSetOf<AstRef>() val allSortedRefs = linkedSetOf<AstRef>() val allSortedRefsStaticInit = linkedSetOf<AstRef>() val types = hashSetOf<FqName>() val fields = hashSetOf<AstFieldRef>() val methods = hashSetOf<AstMethodRef>() fun ignoreExploring(ref: AstRef) { ignoreExploring += ref } fun flow() { if (config.reason == Reason.STATIC) { //println("Conditional execution in ${body?.methodRef ?: $name}") } } fun ana(method: AstMethodRef) { if (method in ignoreExploring) return allSortedRefs.add(method) methods.add(method) } fun ana(field: AstFieldRef) { if (field in ignoreExploring) return allSortedRefs.add(field) fields.add(field) } fun ana(type: AstType) { //if (type in ignoreExploring) return allSortedRefs.addAll(type.getRefTypes()) types.addAll(type.getRefTypesFqName()) } fun ana(types: List<AstType>) = types.forEach { ana(it) } fun ana(expr: AstExpr.Box?) = ana(expr?.value) fun ana(stm: AstStm.Box?) = ana(stm?.value) fun ana(expr: AstExpr?) { if (expr == null) return when (expr) { is AstExpr.BaseCast -> { //is AstExpr.CAST -> { ana(expr.from) ana(expr.to) ana(expr.subject) } is AstExpr.NEW_ARRAY -> { for (c in expr.counts) ana(c) ana(expr.arrayType) allSortedRefsStaticInit += expr.arrayType.getRefClasses() } is AstExpr.INTARRAY_LITERAL -> { //for (c in expr.values) ana(c) ana(expr.arrayType) } is AstExpr.OBJECTARRAY_LITERAL -> { //for (c in expr.values) ana(c) ana(expr.arrayType) allSortedRefsStaticInit += AstType.STRING } is AstExpr.ARRAY_ACCESS -> { ana(expr.type) ana(expr.array) ana(expr.index) } is AstExpr.ARRAY_LENGTH -> { ana(expr.array) } is AstExpr.TERNARY -> { ana(expr.cond) ana(expr.etrue) ana(expr.efalse) } is AstExpr.BINOP -> { ana(expr.left) ana(expr.right) } is AstExpr.CALL_BASE -> { methodHandler(expr, this) ana(expr.method.type) for (arg in expr.args) ana(arg) ana(expr.method) if (expr is AstExpr.CALL_STATIC) ana(expr.clazz) if (expr is AstExpr.CALL_INSTANCE) ana(expr.obj) if (expr is AstExpr.CALL_SUPER) ana(expr.obj) allSortedRefsStaticInit += expr.method } is AstExpr.CONCAT_STRING -> { ana(expr.original) } is AstExpr.CAUGHT_EXCEPTION -> { ana(expr.type) } is AstExpr.FIELD_INSTANCE_ACCESS -> { ana(expr.expr) ana(expr.field) } is AstExpr.FIELD_STATIC_ACCESS -> { ana(expr.clazzName) ana(expr.field) allSortedRefsStaticInit += expr.field.containingTypeRef } is AstExpr.INSTANCE_OF -> { ana(expr.expr) ana(expr.checkType) } is AstExpr.UNOP -> ana(expr.right) is AstExpr.THIS -> ana(expr.type) is AstExpr.LITERAL -> { val value = expr.value when (value) { is AstType -> { ana(value) allSortedRefsStaticInit += value.getRefClasses() } //null -> Unit //is Void, is String -> Unit //is Boolean, is Byte, is Char, is Short, is Int, is Long -> Unit //is Float, is Double -> Unit is AstMethodHandle -> { ana(value.type) ana(value.methodRef) allSortedRefsStaticInit += value.methodRef } //else -> invalidOp("Literal: ${expr.value}") } } is AstExpr.LOCAL -> Unit is AstExpr.TYPED_LOCAL -> Unit is AstExpr.PARAM -> ana(expr.type) is AstExpr.INVOKE_DYNAMIC_METHOD -> { ana(expr.type) ana(expr.methodInInterfaceRef) ana(expr.methodToConvertRef) ana(expr.methodInInterfaceRef.allClassRefs) ana(expr.methodToConvertRef.allClassRefs) allSortedRefsStaticInit += expr.methodInInterfaceRef allSortedRefsStaticInit += expr.methodToConvertRef } is AstExpr.NEW_WITH_CONSTRUCTOR -> { ana(expr.target) allSortedRefsStaticInit += expr.target for (arg in expr.args) ana(arg) ana(AstExpr.CALL_STATIC(expr.constructor, expr.args.unbox, isSpecial = true)) } //is AstExpr.REF -> ana(expr.expr) is AstExpr.LITERAL_REFNAME -> { ana(expr.type) } else -> noImpl("Not implemented $expr") } } fun ana(stm: AstStm?) { if (stm == null) return when (stm) { is AstStm.STMS -> for (s in stm.stms) ana(s) is AstStm.STM_EXPR -> ana(stm.expr) is AstStm.STM_LABEL -> Unit is AstStm.MONITOR_ENTER -> ana(stm.expr) is AstStm.MONITOR_EXIT -> ana(stm.expr) is AstStm.SET_LOCAL -> ana(stm.expr) is AstStm.SET_ARRAY -> { ana(stm.array); ana(stm.expr); ana(stm.index) } is AstStm.SET_ARRAY_LITERALS -> { ana(stm.array) for (v in stm.values) ana(v) } is AstStm.SET_FIELD_INSTANCE -> { ana(stm.field); ana(stm.left); ana(stm.expr) } is AstStm.SET_FIELD_STATIC -> { ana(stm.field); ana(stm.expr) allSortedRefsStaticInit += stm.field.containingTypeRef } is AstStm.RETURN -> ana(stm.retval) is AstStm.RETURN_VOID -> Unit is AstStm.THROW -> { ana(stm.exception) } is AstStm.CONTINUE -> Unit is AstStm.BREAK -> Unit is AstStm.TRY_CATCH -> { ana(stm.trystm); ana(stm.catch) } is AstStm.LINE -> Unit is AstStm.NOP -> Unit is AstStm.SWITCH_GOTO -> { flow() ana(stm.subject) } is AstStm.SWITCH -> { flow() ana(stm.subject); ana(stm.default) for (catch in stm.cases) ana(catch.second) } is AstStm.IF_GOTO -> { flow() ana(stm.cond) } is AstStm.GOTO -> { flow() } is AstStm.IF -> { flow() ana(stm.cond); ana(stm.strue); } is AstStm.IF_ELSE -> { flow() ana(stm.cond); ana(stm.strue); ana(stm.sfalse) } is AstStm.WHILE -> { flow() ana(stm.cond); ana(stm.iter) } else -> noImpl("Not implemented STM $stm") } } init { if (body != null) { for (local in body.locals) ana(local.type) ana(body.stm) for (trap in body.traps) ana(trap.exception) } } val references = AstReferences( program = program, allSortedRefs = allSortedRefs, allSortedRefsStaticInit = allSortedRefsStaticInit, classes = types.map { AstType.REF(it) }.toSet(), fields = fields.toSet(), methods = methods.toSet() ) } }
3254916352
jtransc-core/src/com/jtransc/ast/dependency/analyzer.kt
package com.avast.mff.lecture2 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.avast.mff.lecture2", appContext.packageName) } }
323485882
Lecture 2/Demo-app/app/src/androidTest/java/com/avast/mff/lecture2/ExampleInstrumentedTest.kt
package org.http4k.contract import com.google.gson.JsonElement import org.http4k.format.Gson class GsonJsonErrorResponseRendererTest : JsonErrorResponseRendererContract<JsonElement>(Gson)
3512230328
http4k-format/gson/src/test/kotlin/org/http4k/contract/GsonJsonErrorResponseRendererTest.kt
package org.ooverkommelig.jvmreflect.retrievabledefinitions import kotlin.reflect.jvm.reflect @Suppress("CAST_NEVER_SUCCEEDS", "UNCHECKED_CAST") fun <T> t() = null as T internal fun <T> (() -> T).asKType() = reflect()?.returnType ?: throw IllegalStateException()
4101672172
jvm-reflect/src/main/kotlin/org/ooverkommelig/jvmreflect/retrievabledefinitions/ObjectType.kt
package com.otaliastudios.cameraview.demo import android.content.Context import android.util.AttributeSet import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView class MessageView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr) { init { orientation = VERTICAL View.inflate(context, R.layout.option_view, this) val content = findViewById<ViewGroup>(R.id.content) View.inflate(context, R.layout.spinner_text, content) } private val message: TextView = findViewById<ViewGroup>(R.id.content).getChildAt(0) as TextView private val title: TextView = findViewById(R.id.title) fun setMessage(message: String) { this.message.text = message } fun setTitle(title: String) { this.title.text = title } fun setTitleAndMessage(title: String, message: String) { setTitle(title) setMessage(message) } }
3573094125
demo/src/main/kotlin/com/otaliastudios/cameraview/demo/MessageView.kt
/* * Copyright 2012-2022 the original author or 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.docs.web.servlet.springmvc class Customer
3992024585
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/web/servlet/springmvc/Customer.kt
// 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 org.jetbrains.plugins.groovy.lang.resolve import com.intellij.psi.* import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.parentOfType import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement import org.jetbrains.plugins.groovy.lang.psi.GroovyFile import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrExtendsClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrImplementsClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement import org.jetbrains.plugins.groovy.lang.psi.api.types.CodeReferenceKind.* import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameter import org.jetbrains.plugins.groovy.lang.psi.impl.explicitTypeArguments import org.jetbrains.plugins.groovy.lang.psi.util.contexts import org.jetbrains.plugins.groovy.lang.psi.util.skipSameTypeParents import org.jetbrains.plugins.groovy.lang.psi.util.treeWalkUp import org.jetbrains.plugins.groovy.lang.resolve.imports.GroovyImport import org.jetbrains.plugins.groovy.lang.resolve.imports.StarImport import org.jetbrains.plugins.groovy.lang.resolve.imports.StaticImport import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.CollectElementsProcessor import org.jetbrains.plugins.groovy.lang.resolve.processors.TypeParameterProcessor // https://issues.apache.org/jira/browse/GROOVY-8358 // https://issues.apache.org/jira/browse/GROOVY-8359 // https://issues.apache.org/jira/browse/GROOVY-8361 // https://issues.apache.org/jira/browse/GROOVY-8362 // https://issues.apache.org/jira/browse/GROOVY-8364 // https://issues.apache.org/jira/browse/GROOVY-8365 internal object GrCodeReferenceResolver : GroovyResolver<GrCodeReferenceElement> { override fun resolve(ref: GrCodeReferenceElement, incomplete: Boolean): Collection<GroovyResolveResult> { return when (ref.kind) { PACKAGE_REFERENCE -> ref.resolveAsPackageReference() IMPORT_REFERENCE -> ref.resolveAsImportReference() REFERENCE -> ref.resolveReference() } } } private fun GrCodeReferenceElement.resolveAsPackageReference(): Collection<GroovyResolveResult> { val aPackage = resolvePackageFqn() ?: return emptyList() return listOf(ElementResolveResult(aPackage)) } private fun GrCodeReferenceElement.resolveAsImportReference(): Collection<GroovyResolveResult> { val file = containingFile as? GroovyFile ?: return emptyList() val statement = parentOfType<GrImportStatement>() ?: return emptyList() val topLevelReference = statement.importReference ?: return emptyList() val import = statement.import ?: return emptyList() if (this === topLevelReference) { return if (import is StaticImport) { resolveStaticImportReference(file, import) } else { resolveImportReference(file, import) } } if (parent === topLevelReference && import is StaticImport) { return resolveImportReference(file, import) } if (import is StarImport) { // reference inside star import return resolveAsPackageReference() } val clazz = import.resolveImport(file) as? PsiClass val classReference = if (import is StaticImport) topLevelReference.qualifier else topLevelReference if (clazz == null || classReference == null) return resolveAsPackageReference() return resolveAsPartOfFqn(classReference, clazz) } private fun resolveStaticImportReference(file: GroovyFile, import: StaticImport): Collection<GroovyResolveResult> { val processor = CollectElementsProcessor() import.processDeclarations(processor, ResolveState.initial(), file, file) return processor.results.collapseReflectedMethods().collapseAccessors().map(::ElementResolveResult) } private fun resolveImportReference(file: GroovyFile, import: GroovyImport): Collection<GroovyResolveResult> { val resolved = import.resolveImport(file) ?: return emptyList() return listOf(ElementResolveResult(resolved)) } private fun GrCodeReferenceElement.resolveReference(): Collection<GroovyResolveResult> { val name = referenceName ?: return emptyList() if (canResolveToTypeParameter()) { val typeParameters = resolveToTypeParameter(this, name) if (typeParameters.isNotEmpty()) return typeParameters } val (_, outerMostReference) = skipSameTypeParents() if (outerMostReference !== this) { val fqnReferencedClass = outerMostReference.resolveClassFqn() if (fqnReferencedClass != null) { return resolveAsPartOfFqn(outerMostReference, fqnReferencedClass) } } else if (isQualified) { val clazz = resolveClassFqn() if (clazz != null) { return listOf(ClassProcessor.createResult(clazz, this, ResolveState.initial(), explicitTypeArguments)) } } val processor = ClassProcessor(name, this, explicitTypeArguments, isAnnotationReference()) val state = ResolveState.initial() processClasses(processor, state) val classes = processor.results if (classes.isNotEmpty()) return classes if (canResolveToPackage()) { val packages = resolveAsPackageReference() if (packages.isNotEmpty()) return packages } return emptyList() } private fun GrReferenceElement<*>.canResolveToTypeParameter(): Boolean { if (isQualified) return false val parent = parent return when (parent) { is GrReferenceElement<*>, is GrExtendsClause, is GrImplementsClause, is GrAnnotation, is GrImportStatement, is GrNewExpression, is GrAnonymousClassDefinition, is GrCodeReferenceElement -> false else -> true } } private fun resolveToTypeParameter(place: PsiElement, name: String): Collection<GroovyResolveResult> { val processor = TypeParameterProcessor(name) place.treeWalkUp(processor) return processor.results } private fun GrReferenceElement<*>.canResolveToPackage(): Boolean = parent is GrReferenceElement<*> private fun GrCodeReferenceElement.resolveAsPartOfFqn(reference: GrCodeReferenceElement, clazz: PsiClass): Collection<GroovyResolveResult> { var currentReference = reference var currentElement: PsiNamedElement = clazz while (currentReference !== this) { currentReference = currentReference.qualifier ?: return emptyList() val e: PsiNamedElement? = when (currentElement) { is PsiClass -> currentElement.containingClass ?: currentElement.getPackage() is PsiPackage -> currentElement.parentPackage else -> null } currentElement = e ?: return emptyList() } return listOf(BaseGroovyResolveResult(currentElement, this)) } private fun PsiClass.getPackage(): PsiPackage? { val file = containingFile val name = (file as? PsiClassOwner)?.packageName ?: return null return JavaPsiFacade.getInstance(file.project).findPackage(name) } fun GrCodeReferenceElement.processClasses(processor: PsiScopeProcessor, state: ResolveState): Boolean { val qualifier = qualifier if (qualifier == null) { return processUnqualified(processor, state) } else { return processQualifier(qualifier, processor, state) } } fun PsiElement.processUnqualified(processor: PsiScopeProcessor, state: ResolveState): Boolean { return processInnerClasses(processor, state) && processFileLevelDeclarations(processor, state) } /** * @see org.codehaus.groovy.control.ResolveVisitor.resolveNestedClass */ private fun PsiElement.processInnerClasses(processor: PsiScopeProcessor, state: ResolveState): Boolean { val currentClass = getCurrentClass() ?: return true if (this !is GrCodeReferenceElement || canResolveToInnerClassOfCurrentClass()) { if (!currentClass.processInnerInHierarchy(processor, state, this)) return false } return currentClass.processInnersInOuters(processor, state, this) } /** * @see org.codehaus.groovy.control.ResolveVisitor.resolveFromModule * @see org.codehaus.groovy.control.ResolveVisitor.resolveFromDefaultImports */ private fun PsiElement.processFileLevelDeclarations(processor: PsiScopeProcessor, state: ResolveState): Boolean { // There is no point in processing imports in dummy files. val file = containingFile.skipDummies() ?: return true return file.treeWalkUp(processor, state, this) } private fun GrCodeReferenceElement.processQualifier(qualifier: GrCodeReferenceElement, processor: PsiScopeProcessor, state: ResolveState): Boolean { for (result in qualifier.multiResolve(false)) { val clazz = result.element as? PsiClass ?: continue if (!clazz.processDeclarations(processor, state.put(PsiSubstitutor.KEY, result.substitutor), null, this)) return false } return true } private fun GrCodeReferenceElement.canResolveToInnerClassOfCurrentClass(): Boolean { val (_, outerMostReference) = skipSameTypeParents() val parent = outerMostReference.getActualParent() return parent !is GrExtendsClause && parent !is GrImplementsClause && (parent !is GrAnnotation || parent.classReference != this) // annotation's can't be inner classes of current class } /** * Reference element may be created from stub. In this case containing file will be dummy, and its context will be reference parent */ private fun GrCodeReferenceElement.getActualParent(): PsiElement? = containingFile.context ?: parent /** * @see org.codehaus.groovy.control.ResolveVisitor.currentClass */ private fun PsiElement.getCurrentClass(): GrTypeDefinition? { for (context in contexts()) { if (context !is GrTypeDefinition) { continue } else if (context is GrTypeParameter) { continue } else if (context is GrAnonymousClassDefinition && this === context.baseClassReferenceGroovy) { continue } else { return context } } return null } private fun PsiFile?.skipDummies(): PsiFile? { var file: PsiFile? = this while (file != null && !file.isPhysical) { val context = file.context if (context == null) return file file = context.containingFile } return file }
2459486897
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GrCodeReferenceResolver.kt
/* * Copyright (C) 2022 Block, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.cli import com.google.common.truth.Truth.assertThat import java.io.PrintStream import kotlin.test.assertFailsWith import okio.Buffer import org.junit.Test import picocli.CommandLine import picocli.CommandLine.UnmatchedArgumentException class GenerateKeyPairTest { private val systemOut = Buffer() @Test fun happyPathDefault() { val generateKeyPair = fromArgs() generateKeyPair.run() assertThat(systemOut.readUtf8Line()).matches(" ALGORITHM: Ed25519") assertThat(systemOut.readUtf8Line()).matches(" PUBLIC KEY: [\\da-f]{64}") assertThat(systemOut.readUtf8Line()).matches("PRIVATE KEY: [\\da-f]{64}") assertThat(systemOut.readUtf8Line()).isNull() } @Test fun happyPathEd25519() { val generateKeyPair = fromArgs("-a", "Ed25519") generateKeyPair.run() assertThat(systemOut.readUtf8Line()).matches(" ALGORITHM: Ed25519") assertThat(systemOut.readUtf8Line()).matches(" PUBLIC KEY: [\\da-f]{64}") assertThat(systemOut.readUtf8Line()).matches("PRIVATE KEY: [\\da-f]{64}") assertThat(systemOut.readUtf8Line()).isNull() } @Test fun happyPathEcdsaP256() { val generateKeyPair = fromArgs("-a", "EcdsaP256") generateKeyPair.run() assertThat(systemOut.readUtf8Line()).matches(" ALGORITHM: EcdsaP256") assertThat(systemOut.readUtf8Line()).matches(" PUBLIC KEY: [\\da-f]{130}") // Expected lengths were determined experimentally! assertThat(systemOut.readUtf8Line()).matches("PRIVATE KEY: [\\da-f]{134}") assertThat(systemOut.readUtf8Line()).isNull() } @Test fun unmatchedArgument() { assertFailsWith<UnmatchedArgumentException> { fromArgs("-unexpected") } } private fun fromArgs(vararg args: String?): GenerateKeyPair { return CommandLine.populateCommand( GenerateKeyPair(PrintStream(systemOut.outputStream())), *args, ) } }
2507481480
zipline-cli/src/test/kotlin/app/cash/zipline/cli/GenerateKeyPairTest.kt
/*************************************************************************/ /* VkSurfaceView.kt */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ @file:JvmName("VkSurfaceView") package org.godotengine.godot.vulkan import android.content.Context import android.view.SurfaceHolder import android.view.SurfaceView /** * An implementation of SurfaceView that uses the dedicated surface for * displaying Vulkan rendering. * <p> * A [VkSurfaceView] provides the following features: * <p> * <ul> * <li>Manages a surface, which is a special piece of memory that can be * composited into the Android view system. * <li>Accepts a user-provided [VkRenderer] object that does the actual rendering. * <li>Renders on a dedicated [VkThread] thread to decouple rendering performance from the * UI thread. * </ul> */ open internal class VkSurfaceView(context: Context) : SurfaceView(context), SurfaceHolder.Callback { companion object { fun checkState(expression: Boolean, errorMessage: Any) { check(expression) { errorMessage.toString() } } } /** * Thread used to drive the vulkan logic. */ private val vkThread: VkThread by lazy { VkThread(this, renderer) } /** * Performs the actual rendering. */ private lateinit var renderer: VkRenderer init { isClickable = true holder.addCallback(this) } /** * Set the [VkRenderer] associated with the view, and starts the thread that will drive the vulkan * rendering. * * This method should be called once and only once in the life-cycle of [VkSurfaceView]. */ fun startRenderer(renderer: VkRenderer) { checkState(!this::renderer.isInitialized, "startRenderer must only be invoked once") this.renderer = renderer vkThread.start() } /** * Queues a runnable to be run on the Vulkan rendering thread. * * Must not be called before a [VkRenderer] has been set. */ fun queueOnVkThread(runnable: Runnable) { vkThread.queueEvent(runnable) } /** * Resumes the rendering thread. * * Must not be called before a [VkRenderer] has been set. */ open fun onResume() { vkThread.onResume() } /** * Pauses the rendering thread. * * Must not be called before a [VkRenderer] has been set. */ open fun onPause() { vkThread.onPause() } /** * Tear down the rendering thread. * * Must not be called before a [VkRenderer] has been set. */ fun onDestroy() { vkThread.blockingExit() } override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) { vkThread.onSurfaceChanged(width, height) } override fun surfaceDestroyed(holder: SurfaceHolder) { vkThread.onSurfaceDestroyed() } override fun surfaceCreated(holder: SurfaceHolder) { vkThread.onSurfaceCreated() } }
2985180290
platform/android/java/lib/src/org/godotengine/godot/vulkan/VkSurfaceView.kt
/* * Copyright (C) 2022 Block, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline.loader.internal.fetcher import app.cash.zipline.EventListener import app.cash.zipline.loader.FakeZiplineHttpClient import kotlin.test.Test import kotlin.test.assertEquals import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement class HttpFetcherTest { private val httpFetcher = HttpFetcher(FakeZiplineHttpClient(), EventListener.NONE) private val json = Json { prettyPrint = true } @Test fun happyPath() { val manifestWithRelativeUrls = """ |{ | "modules": { | "./hello.js": { | "url": "hello.zipline", | "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab" | }, | "./jello.js": { | "url": "jello.zipline", | "sha256": "7af37185091e22463ff627686aedfec3528376eb745026fae1d6153688885e73" | } | } |} """.trimMargin() val manifestWithBaseUrl = httpFetcher.withBaseUrl( manifest = json.parseToJsonElement(manifestWithRelativeUrls), baseUrl = "https://example.com/path/", ) assertEquals( """ |{ | "unsigned": { | "baseUrl": "https://example.com/path/" | }, | "modules": { | "./hello.js": { | "url": "hello.zipline", | "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab" | }, | "./jello.js": { | "url": "jello.zipline", | "sha256": "7af37185091e22463ff627686aedfec3528376eb745026fae1d6153688885e73" | } | } |} """.trimMargin(), json.encodeToString(JsonElement.serializer(), manifestWithBaseUrl), ) } @Test fun withBaseUrlRetainsUnknownFields() { val manifestWithRelativeUrls = """ |{ | "unknown string": "hello", | "modules": { | "./hello.js": { | "url": "hello.zipline", | "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab" | } | } |} """.trimMargin() val manifestWithResolvedUrls = httpFetcher.withBaseUrl( manifest = json.parseToJsonElement(manifestWithRelativeUrls), baseUrl = "https://example.com/path/", ) assertEquals( """ |{ | "unsigned": { | "baseUrl": "https://example.com/path/" | }, | "unknown string": "hello", | "modules": { | "./hello.js": { | "url": "hello.zipline", | "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab" | } | } |} """.trimMargin(), json.encodeToString(JsonElement.serializer(), manifestWithResolvedUrls), ) } }
4257887545
zipline-loader/src/commonTest/kotlin/app/cash/zipline/loader/internal/fetcher/HttpFetcherTest.kt
import java.security.* // MessageDigest import java.math.* // BigInteger import AocBase /** * AoC2016 Day11a main class. * Run with: * * ``` * run.sh * ``` * * Document with: * `java -jar dokka-fatjar.jar day13a.kt -format html -module "aoc16 day11a" -nodeprecated` */ class Day11a : AocBase() { val maxround = 256 val seen: MutableSet<String> init { seen = mutableSetOf(""); seen.clear() LOGLEVEL = 0 } val TESTSTR = """ The first floor contains a elerium generator, a elerium-compatible microchip, a dilithium generator, a dilithium-compatible microchip, a strontium generator, a strontium-compatible microchip, a plutonium generator, and a plutonium-compatible microchip. The second floor contains a thulium generator, a ruthenium generator, a ruthenium-compatible microchip, a curium generator, and a curium-compatible microchip. The third floor contains a thulium-compatible microchip. The fourth floor contains nothing relevant. """.trimIndent() /* val TESTSTR = """ The first floor contains a hydrogen-compatible microchip. The second floor contains nothing relevant. The third floor contains a hydrogen generator. The fourth floor contains a lithium-compatible microchip and a lithium generator. """.trimIndent() val TESTSTR = """ The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip. The second floor contains a hydrogen generator. The third floor contains a lithium generator. The fourth floor contains nothing relevant. """.trimIndent() //!! PART 1: val TESTSTR = """ The first floor contains a strontium generator, a strontium-compatible microchip, a plutonium generator, and a plutonium-compatible microchip. The second floor contains a thulium generator, a ruthenium generator, a ruthenium-compatible microchip, a curium generator, and a curium-compatible microchip. The third floor contains a thulium-compatible microchip. The fourth floor contains nothing relevant. """.trimIndent() */ companion object { /** * Factory create function. */ fun create(): Day11a = Day11a() /** * PSVM main entry point. */ @JvmStatic fun main(args: Array<String>) { println("Starting") val o = create() o.process() } } //**** problem domain /** * Get Elevator floor number stored in world. */ private fun elevatorAt(world: MutableList<MutableSet<String>>): Int { return world[4].toList().get(0).toInt() } /** * Return list of directions, 1; -1 oder 1, -1. */ private fun elevatorDirsOk(oldFloorNum: Int): List<Int> { if (oldFloorNum == 1) { return listOf<Int>(1) } else if (oldFloorNum == 4) { return listOf<Int>(-1) } else { return listOf<Int>(1, -1) } } /** * Returns Combinations (like Permutations, but order does not count) * of 2 and 1 items of the given set. */ private fun get2Permuts(fset: MutableSet<String>): MutableList<List<String>> { val ret = mutableListOf(listOf("")); ret.clear() val aset = fset.sorted() if (aset.size > 2) { for (idx in 0..aset.size-1) { // permutate-2 for (nxidx in idx+1..aset.size-1) { // permutate-2 //println("permut=($idx,$nxidx)") ret.add(listOf(aset[idx], aset[nxidx])) } } for (idx in 0..aset.size-1) { // permutate-1 ret.add(listOf(aset[idx])) } } else if (aset.size == 2) { ret.add(listOf(aset[0], aset[1])) ret.add(listOf(aset[0])) ret.add(listOf(aset[1])) } else if (fset.size == 1) { ret.add(listOf(aset[0])) } else { // nothing to add } tracelog("getPermuts($aset) => $ret") return ret } private fun getElevatorPermuts(world: MutableList<MutableSet<String>>): MutableList<List<String>> { val currentFloor = elevatorAt(world) //elevatorDirsOk(currentFloor).forEach { edir -> // tracelog("possible direction $edir; currently at $currentFloor") //} val fset = world[currentFloor-1] //deblog("fset.size=${fset.size} fset=$fset") return get2Permuts(fset) } private fun checkPayloadFloor(perm: List<String>, targetFloor: Int, world: MutableList<MutableSet<String>>): Boolean { val targetfset = world[targetFloor - 1] val micros = perm.filter { it.endsWith("M") } if (micros.size > 0) { val generators = targetfset.union(perm).filter { it.endsWith("G") } micros.forEach { micro -> val micGen = micro[0] + "G" if (generators.size > 0 && !generators.contains(micGen)) { tracelog("$micro fried on payload=$perm to floor#$targetFloor :: $targetfset. no $micGen") return false } } } return true } /** * Generate world from a multiline string. */ private fun generateWorld(mlstr: String): MutableList<MutableSet<String>> { // "The second floor contains a hydrogen generator." val rx1 = Regex("""^The (.*) floor contains (.*)\.$""") val rx2 = Regex("""a ([a-z].*?).(?:compatible )?(microchip|generator)""") val world = mutableListOf(mutableSetOf("")); world.clear() mlstr.split("\n").forEach { line -> val mset = mutableSetOf(""); mset.clear() //tracelog("line=$line") val mr1 = rx1.find(line) if (mr1 == null) { throw RuntimeException("unparseable line:: $line") } val (floorstr, rest) = mr1.destructured //tracelog("floorstr=$floorstr, rest=$rest") if (!rest.startsWith("nothing")) { rx2.findAll(rest).forEach { mr2 -> val (elem, device) = mr2.destructured val marker: String = "${elem[0]}${device[0]}".toUpperCase() //infolog("add marker $marker") mset.add(marker) } } world.add(mset) } world.add(mutableSetOf(1.toString())) infolog("world=${signat(world)}") //infolog("floor#1=${world[0]}") assertmsg(elevatorAt(world) == 1, "elevator at creation is at floor #1") return world } private fun printWorld(world: MutableList<MutableSet<String>>, title: String = "") { val allset = mutableSetOf(""); allset.clear() val cols = mutableListOf(""); cols.clear() world.forEachIndexed { idx, floor -> if (idx < 4) { floor.forEach { allset.add(it) } } } val items = allset.sorted() var s = "Wl>|" //">Wrld |" s += "El|" items.forEach { s += it + "|" cols.add(it) } if (title != "") { s += " :: >$title<" } s += " :: world-id=" + Integer.toHexString(world.hashCode()) s += "\n" for (f in 4 downTo 1) { s += " F#$f: ;" if (f == elevatorAt(world)) { s += "El;" } else { s += "__;" } val fset = world[f-1] items.forEach { if (fset.contains(it)) { s += "$it;" } else { s +="..;" } } if (f==1) { s += " :: signat=${signat(world)}" } s += "\n" } infolog("$s") // "\n$s" } /** * Process problem domain. */ fun process(): Boolean { infolog(":process() started.") //infolog("TESTSTR =>>$TESTSTR<<.") assertmsg(TESTSTR.length > 0, "found TESTSTR") val mlstr = TESTSTR val world = generateWorld(mlstr) seen.add(signat(world)) printWorld(world, "initial-world") var round = 0 var stack: MutableList<MutableList<MutableSet<String>>> var nextstack = mutableListOf(world) var stackCounts = mutableListOf(0); stackCounts.clear() var lastWorlds = 1 var lastMoves = 0 var invalidNum = 0 var rejectedNum = 0 stackCounts.add(nextstack.size) val starttm = System.currentTimeMillis() var lasttm = starttm var tooktm: Long while (round < maxround) { round += 1 tooktm = System.currentTimeMillis() stack = copyMListOfMListOfMSet(nextstack) nextstack.clear() //infolog("start-round#$round; stack=$stack; next-stack:$nextstack") infolog("START-ROUND #$round; stack-count=${stack.size}, seen-count=${seen.size}; invalid-ct=$invalidNum, rejected=$rejectedNum, last-TM=${tooktm-lasttm}, sum-TM=${(tooktm-starttm)/1000.0}") lasttm = tooktm infolog("stackCounts=" + stackCounts.joinToString(",")) deblog(" last-world=$lastWorlds, last-moves=$lastMoves") lastWorlds = 0; lastMoves = 0 //if (stack.size == 1) { // printWorld(stack[0], "stacked1") //} stack.forEach { baseworld -> lastWorlds += 1 val currentFloor = elevatorAt(baseworld) val permuts = getElevatorPermuts(baseworld) elevatorDirsOk(currentFloor).forEach { edir -> tracelog("possible direction $edir; currently at $currentFloor; permuts=$permuts") val targetFloor = currentFloor + edir permuts.forEach { perm -> if (checkPayloadFloor(perm, targetFloor, baseworld)){ deblog("ok-move to-flr=$targetFloor from-flr=$currentFloor, perm=$perm to=${baseworld[targetFloor-1]}") val newworld = compute_world(edir, perm, baseworld) val nwsig = signat(newworld) if (nwsig.contains(":;;;")) { printWorld(newworld, "solution-world") tooktm = System.currentTimeMillis() infolog("sum-TM=${(tooktm-starttm)/1000.0}") throw RuntimeException("finished-world found! at round $round") } if (!seen.contains(nwsig)) { lastMoves += 1 seen.add(nwsig) //printWorld(newworld, title="newworld :p") nextstack.add(newworld) //!!!deblog("OK added next-move newworld-sig=$nwsig"); //printWorld(newworld, "stacked-next-world") } else { //!!!deblog("rejected seen world $nwsig") rejectedNum += 1 } } else { //!!!deblog("invalid move to-flr=$targetFloor from-flr=$currentFloor, with=$perm to=${baseworld[targetFloor-1]}") invalidNum += 1 } } } } stackCounts.add(nextstack.size) } return false } private fun signat(world: MutableList<MutableSet<String>>): String { var sign = "" world.forEachIndexed { idx, floor -> if (idx == 4) { sign = floor.elementAt(0).toString() + ":" + sign } else if (idx == 3) { sign += floor.sorted().joinToString(",") + "." } else { sign += floor.sorted().joinToString(",") + ";" } } //tracelog("signat(wrld)=$sign from ${world}") return sign } private fun compute_world(edir: Int, perm: List<String>, baseWorld: MutableList<MutableSet<String>>): MutableList<MutableSet<String>> { val newWorld = copyMListOfMSet(baseWorld) //printWorld(baseWorld, "oldworld :compt1"); val currentFloor = elevatorAt(newWorld) val targetFloor = currentFloor + edir tracelog("compute ok: to-flr=$targetFloor from-flr=$currentFloor, perm=$perm to-flr-items=${baseWorld[targetFloor-1]}") val elevInfo = newWorld[4]; elevInfo.clear(); elevInfo.add(targetFloor.toString()) // set Elevator floor! val basefset = newWorld[currentFloor - 1] perm.forEach { basefset.remove(it) } val targetfset = newWorld[targetFloor - 1] perm.forEach { targetfset.add(it) } //printWorld(baseWorld, "oldworld :compt2") //printWorld(newWorld, "newworld") return newWorld } }
2556859705
day11/src_kotlin/Day11a.kt
/* * Copyright (C) 2019 Johannes Donath <johannesd@torchmind.com> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.beacon.ui.repository.model import com.google.protobuf.ByteString import tv.dotstart.beacon.core.delegate.logManager import tv.dotstart.beacon.repository.Model import java.awt.image.BufferedImage import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.IOException import java.net.URI import javax.imageio.ImageIO import tv.dotstart.beacon.core.model.Service as CoreService /** * Represents a service along with its human readable identification and port definitions. * * @author [Johannes Donath](mailto:johannesd@torchmind.com) */ data class Service( /** * Stores a URI with which this particular service is uniquely identified. * * This is most likely a store identifier (such as "game+steam://<id>") but may also be a * reference to the website of a game's developer (such as "game://example.org/game") */ override val id: URI, /** * Identifies the category in which this service is to be organized. */ val category: Model.Category, /** * Identifies the location at which an extracted version of this service's icon may be found. * * When no icon has been assigned for this particular icon, null is returned instead. In this * case, the icon is to be substituted with a standard fallback icon. */ val icon: BufferedImage?, /** * Provides a human readable name with which this service is identified. */ override val title: String, /** * Identifies the ports on which this service will typically listen. */ override val ports: List<Port>) : CoreService { companion object { private val logger by logManager() } constructor(model: Model.ServiceDefinition) : this( URI.create(model.id), model.category, model.icon ?.let { iconData -> try { ByteArrayInputStream(iconData.toByteArray()) .let { ImageIO.read(it) } } catch (ex: IOException) { logger.error("Failed to decode icon for service \"${model.id}\"", ex) null } }, model.title, model.portList.map(::Port) ) fun toRepositoryDefinition(): Model.ServiceDefinition { val icon = this.icon ?.let { ByteArrayOutputStream().use { stream -> try { ImageIO.write(it, "PNG", stream) stream.toByteArray() } catch (ex: IOException) { logger.error("Failed to encode icon for service \"$id\"", ex) null } } } return Model.ServiceDefinition.newBuilder() .setId(this.id.toASCIIString()) .setTitle(this.title) .setCategory(this.category) .addAllPort(this.ports.map(Port::toRepositoryDefinition)) .also { if (icon != null) { it.icon = ByteString.copyFrom(icon) } } .build() } }
1760085104
ui/src/main/kotlin/tv/dotstart/beacon/ui/repository/model/Service.kt
package org.needhamtrack.nytc.database import android.arch.persistence.room.Database import android.arch.persistence.room.RoomDatabase import android.arch.persistence.room.TypeConverters import org.needhamtrack.nytc.models.LongJumpRecord @Database(entities = arrayOf(LongJumpRecord::class), version = 1) @TypeConverters(Converters::class) abstract class NytcDatabase : RoomDatabase() { abstract fun longJumpRecordDao(): LongJumpRecordDao }
4123119184
app/src/main/kotlin/org/needhamtrack/nytc/database/NytcDatabase.kt
package de.christinecoenen.code.zapp.app.mediathek.ui.list.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.paging.LoadState import androidx.paging.LoadStateAdapter import de.christinecoenen.code.zapp.databinding.FragmentMediathekListItemFooterBinding class FooterLoadStateAdapter( private val retry: () -> Unit ) : LoadStateAdapter<LoadStateViewHolder>() { override fun onBindViewHolder(holder: LoadStateViewHolder, loadState: LoadState) = holder.bind(loadState) override fun onCreateViewHolder(parent: ViewGroup, loadState: LoadState): LoadStateViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = FragmentMediathekListItemFooterBinding.inflate(inflater, parent, false) return LoadStateViewHolder(binding, retry) } }
366690109
app/src/main/java/de/christinecoenen/code/zapp/app/mediathek/ui/list/adapter/FooterLoadStateAdapter.kt
package com.infinum.dbinspector.domain.history.interactors import com.infinum.dbinspector.data.Sources import com.infinum.dbinspector.data.models.local.proto.input.HistoryTask import com.infinum.dbinspector.data.models.local.proto.output.HistoryEntity import com.infinum.dbinspector.domain.Interactors internal class RemoveExecutionInteractor( private val dataStore: Sources.Local.History ) : Interactors.RemoveExecution { override suspend fun invoke(input: HistoryTask) { input.execution?.let { execution -> dataStore.store().updateData { value: HistoryEntity -> value.toBuilder() .removeExecutions( value.executionsList.indexOfFirst { it.databasePath == execution.databasePath && it.execution == execution.execution && it.timestamp == execution.timestamp && it.success == execution.success } ) .build() } } } }
39390320
dbinspector/src/main/kotlin/com/infinum/dbinspector/domain/history/interactors/RemoveExecutionInteractor.kt
package de.westnordost.streetcomplete.quests.max_height sealed class MaxHeightAnswer data class MaxHeight(val value: HeightMeasure) : MaxHeightAnswer() data class NoMaxHeightSign(val isTallEnough: Boolean) : MaxHeightAnswer()
1408904259
app/src/main/java/de/westnordost/streetcomplete/quests/max_height/MaxHeightAnswer.kt
/* * Copyright (c) 2017. Toshi Inc * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.toshi.model.local import com.toshi.model.sofa.SofaMessage import rx.subjects.PublishSubject data class ConversationObservables( val newMessageSubject: PublishSubject<SofaMessage>, val updateMessageSubject: PublishSubject<SofaMessage>, val conversationUpdatedSubject: PublishSubject<Conversation> )
4225509898
app/src/main/java/com/toshi/model/local/ConversationObservables.kt
package ninenine.com.duplicateuser.presenter import ninenine.com.duplicateuser.domain.User import ninenine.com.duplicateuser.initMocks import ninenine.com.duplicateuser.repository.UserRepository import ninenine.com.duplicateuser.view.UserContractView import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.* import org.mockito.Mockito.* import java.util.* class UserPresenterTest { @Mock private lateinit var userRepository: UserRepository @Mock private lateinit var userContractView: UserContractView private lateinit var userPresenter: UserPresenter private var users: MutableList<User> = mutableListOf() @Before fun setupUserPresenter() { initMocks(this) userPresenter = UserPresenterImpl(userRepository) userPresenter.attachView(userContractView) val userSteve = User(UUID.randomUUID().toString(), "Steve Jobs", "http://adsoftheworld.com/files/steve-jobs.jpg", "1955-02-24T00:00:00Z", "Steven Paul Jobs was an American businessman, inventor") val userCraig = User(UUID.randomUUID().toString(), "Craig Federighi", "http://adsoftheworld.com/files/steve-jobs.jpg", "1969-05-27T00:00:00Z", "Craig Federighi is Apple's senior vice president") users.add(userSteve) users.add(userCraig) } @Test fun loadAllUsersFromRepository() { doReturn(users.toSet()) .`when`(userRepository) .getUsersWithSet() with(userPresenter) { loadUsers() } verify(userContractView, times(1)).showUsers(users) Assert.assertTrue(users.size == 2) } }
2895579481
app/src/test/java/ninenine/com/duplicateuser/presenter/UserPresenterTest.kt
package de.westnordost.streetcomplete.quests.railway_crossing import de.westnordost.streetcomplete.quests.AImageListQuestAnswerFragment import de.westnordost.streetcomplete.quests.railway_crossing.RailwayCrossingBarrier.* class AddRailwayCrossingBarrierForm : AImageListQuestAnswerFragment<RailwayCrossingBarrier, RailwayCrossingBarrier>() { override val items get() = listOf(NO, HALF, DOUBLE_HALF, FULL).toItems(countryInfo.isLeftHandTraffic) override val itemsPerRow = 4 override fun onClickOk(selectedItems: List<RailwayCrossingBarrier>) { applyAnswer(selectedItems.single()) } }
501442866
app/src/main/java/de/westnordost/streetcomplete/quests/railway_crossing/AddRailwayCrossingBarrierForm.kt
/* * Copyright (C) 2017-2018 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow 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. * * Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>. * */ package org.akvo.flow.domain.interactor import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.akvo.flow.domain.entity.DownloadResult import org.akvo.flow.domain.exception.AssignmentRequiredException import org.akvo.flow.domain.repository.DataPointRepository import org.akvo.flow.domain.repository.FormRepository import org.akvo.flow.domain.util.ConnectivityStateManager import timber.log.Timber import javax.inject.Inject class DownloadDataPoints @Inject constructor( private val dataPointRepository: DataPointRepository, private val formRepository: FormRepository, private val connectivityStateManager: ConnectivityStateManager ) { suspend fun execute(parameters: Map<String, Any>): DownloadResult { if (parameters[KEY_SURVEY_ID] == null) { throw IllegalArgumentException("Missing surveyId or registrationFormId") } return if (!connectivityStateManager.isConnectionAvailable) { DownloadResult( DownloadResult.ResultCode.ERROR_NO_NETWORK, 0 ) } else { syncDataPoints(parameters) } } private suspend fun syncDataPoints(parameters: Map<String, Any>): DownloadResult { return withContext(Dispatchers.IO) { try { val surveyId = (parameters[KEY_SURVEY_ID] as Long?)!! val assignedForms = formRepository.getForms(surveyId) val assignedFormIds = mutableListOf<String>() for (f in assignedForms) { assignedFormIds.add(f.formId) } val downloadDataPoints = dataPointRepository.downloadDataPoints(surveyId, assignedFormIds) DownloadResult(DownloadResult.ResultCode.SUCCESS, downloadDataPoints) } catch (ex: AssignmentRequiredException) { Timber.e(ex) DownloadResult( DownloadResult.ResultCode.ERROR_ASSIGNMENT_MISSING, 0 ) } catch (ex: Exception) { Timber.e(ex) DownloadResult( DownloadResult.ResultCode.ERROR_OTHER, 0 ) } } } companion object { const val KEY_SURVEY_ID = "survey_id" } }
1963929426
domain/src/main/java/org/akvo/flow/domain/interactor/DownloadDataPoints.kt
package kies.prepass.speedtest import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * @see [Testing documentation](http://d.android.com/tools/testing) */ class ExampleUnitTest { @Test @Throws(Exception::class) fun addition_isCorrect() { assertEquals(4, (2 + 2).toLong()) } }
3724027074
app/src/test/java/kies/prepass/speedtest/ExampleUnitTest.kt
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.samples.apps.topeka.widget.quiz import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.view.View import android.view.inputmethod.EditorInfo import android.widget.EditText import android.widget.FrameLayout import android.widget.LinearLayout import com.google.samples.apps.topeka.quiz.R import com.google.samples.apps.topeka.model.Category import com.google.samples.apps.topeka.model.quiz.FillTwoBlanksQuiz @SuppressLint("ViewConstructor") class FillTwoBlanksQuizView( context: Context, category: Category, quiz: FillTwoBlanksQuiz ) : TextInputQuizView<FillTwoBlanksQuiz>(context, category, quiz) { private val KEY_ANSWER_ONE = "ANSWER_ONE" private val KEY_ANSWER_TWO = "ANSWER_TWO" private var answerOne: EditText? = null private var answerTwo: EditText? = null override fun createQuizContentView(): View { val layout = LinearLayout(context) answerOne = createEditText().apply { imeOptions = EditorInfo.IME_ACTION_NEXT } answerTwo = createEditText().apply { id = com.google.samples.apps.topeka.base.R.id.quiz_edit_text_two } layout.orientation = LinearLayout.VERTICAL addEditText(layout, answerOne) addEditText(layout, answerTwo) return layout } override var userInput: Bundle get() { return Bundle().apply { putString(KEY_ANSWER_ONE, answerOne?.text?.toString()) putString(KEY_ANSWER_TWO, answerTwo?.text?.toString()) } } set(savedInput) { answerOne?.setText(savedInput.getString(KEY_ANSWER_ONE)) answerTwo?.setText(savedInput.getString(KEY_ANSWER_TWO)) } private fun addEditText(layout: LinearLayout, editText: EditText?) { layout.addView(editText, LinearLayout .LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 0, 1f)) } override val isAnswerCorrect: Boolean get() { val partOne = getAnswerFrom(answerOne) val partTwo = getAnswerFrom(answerTwo) return quiz.isAnswerCorrect(arrayOf(partOne, partTwo)) } private fun getAnswerFrom(view: EditText?) = view?.text.toString() }
590224293
quiz/src/main/java/com/google/samples/apps/topeka/widget/quiz/FillTwoBlanksQuizView.kt
package br.com.insanitech.spritekit.easing object Quint { fun easeIn(t: Float, b: Float, c: Float, d: Float): Float { var t = t val tLambda = { a: Float -> Float t = a t } return c * (tLambda(t / d)) * t * t * t * t + b } fun easeOut(t: Float, b: Float, c: Float, d: Float): Float { var t = t val tLambda = { a: Float -> Float t = a t } return c * ((tLambda(t / d - 1)) * t * t * t * t + 1) + b } fun easeInOut(t: Float, b: Float, c: Float, d: Float): Float { var t = t val tLambda = { a: Float -> Float t = a t } return if ((tLambda(t / d / 2)) < 1) c / 2 * t * t * t * t * t + b else c / 2 * ((tLambda(t - 2f)) * t * t * t * t + 2) + b } }
437631870
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/easing/Quint.kt
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.command.argument object ArgumentTypes { val BOOL = argumentTypeOf("brigadier:bool") val GAME_PROFILE = argumentTypeOf("minecraft:game_profile") val BLOCK_POS = argumentTypeOf("minecraft:block_pos") val VEC3 = argumentTypeOf("minecraft:vec3") val VEC2 = argumentTypeOf("minecraft:vec2") val BLOCK = argumentTypeOf("minecraft:block") val ITEM = argumentTypeOf("minecraft:item") val COLOR = argumentTypeOf("minecraft:color") val COMPONENT = argumentTypeOf("minecraft:component") val MESSAGE = argumentTypeOf("minecraft:message") val NBT = argumentTypeOf("minecraft:nbt") val NBT_PATH = argumentTypeOf("minecraft:nbt_path") val OBJECTIVE = argumentTypeOf("minecraft:objective") val OBJECTIVE_CRITERIA = argumentTypeOf("minecraft:objective_criteria") val OPERATION = argumentTypeOf("minecraft:operation") val PARTICLE = argumentTypeOf("minecraft:particle") val ROTATION = argumentTypeOf("minecraft:rotation") val SCOREBOARD_SLOT = argumentTypeOf("minecraft:scoreboard_slot") val SWIZZLE = argumentTypeOf("minecraft:swizzle") val TEAM = argumentTypeOf("minecraft:team") val ITEM_SLOT = argumentTypeOf("minecraft:item_slot") val RESOURCE_LOCATION = argumentTypeOf("minecraft:resource_location") val MOB_EFFECT = argumentTypeOf("minecraft:mob_effect") val DOUBLE = numberArgumentTypeOf<DoubleArgument, Double>("brigadier:double") { writeDouble(it) } val FLOAT = numberArgumentTypeOf<FloatArgument, Float>("brigadier:float") { writeFloat(it) } val INTEGER = numberArgumentTypeOf<IntArgument, Int>("brigadier:integer") { writeInt(it) } val LONG = numberArgumentTypeOf<LongArgument, Long>("brigadier:long") { writeLong(it) } @JvmField val STRING = argumentTypeOf<StringArgument>("brigadier:string") { buf, message -> buf.writeVarInt(message.type.ordinal) } val ENTITY = argumentTypeOf<EntityArgument>("minecraft:entity") { buf, message -> var flags = 0 if (!message.allowMultipleEntities) flags += 0x1 if (!message.allowOnlyPlayers) flags += 0x2 buf.writeByte(flags.toByte()) } val SCORE_HOLDER = argumentTypeOf<ScoreHolderArgument>("minecraft:score_holder") { buf, message -> var flags = 0 if (message.hasUnknownFlag) flags += 0x1 if (message.allowMultipleEntities) flags += 0x2 buf.writeByte(flags.toByte()) } }
3387424621
src/main/kotlin/org/lanternpowered/server/network/vanilla/command/argument/ArgumentTypes.kt
/* * Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.json import kotlinx.serialization.* import kotlin.test.Test import kotlin.test.assertEquals class JsonUnionEnumTest : JsonTestBase() { enum class SomeEnum { ALPHA, BETA, GAMMA } @Serializable data class WithUnions(val s: String, val e: SomeEnum = SomeEnum.ALPHA, val i: Int = 42) @Test fun testEnum() = parametrizedTest { jsonTestingMode -> val data = WithUnions("foo", SomeEnum.BETA) val json = default.encodeToString(WithUnions.serializer(), data, jsonTestingMode) val restored = default.decodeFromString(WithUnions.serializer(), json, jsonTestingMode) assertEquals(data, restored) } }
3030863968
formats/json-tests/commonTest/src/kotlinx/serialization/json/JsonUnionEnumTest.kt
/* * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.protobuf import kotlinx.serialization.* import kotlin.test.* /* * TODO improve these tests: * * All primitive types * * All nullable types * * Built-in types (TBD) * * Primitives nullability */ class ProtobufPrimitiveWrappersTest { @Test fun testSignedInteger() { assertSerializedToBinaryAndRestored(TestInt(-150), TestInt.serializer(), ProtoBuf, hexResultToCheck = "08AB02") } @Test fun testIntList() { assertSerializedToBinaryAndRestored( TestList(listOf(1, 2, 3)), TestList.serializer(), ProtoBuf, hexResultToCheck = "080108020803" ) } @Test fun testString() { assertSerializedToBinaryAndRestored( TestString("testing"), TestString.serializer(), ProtoBuf, hexResultToCheck = "120774657374696E67" ) } @Test fun testTwiceNested() { assertSerializedToBinaryAndRestored( TestInner(TestInt(-150)), TestInner.serializer(), ProtoBuf, hexResultToCheck = "1A0308AB02" ) } @Test fun testMixedTags() { assertSerializedToBinaryAndRestored( TestComplex(42, "testing"), TestComplex.serializer(), ProtoBuf, hexResultToCheck = "D0022A120774657374696E67" ) } @Test fun testDefaultPrimitiveValues() { assertSerializedToBinaryAndRestored(TestInt(0), TestInt.serializer(), ProtoBuf, hexResultToCheck = "0800") assertSerializedToBinaryAndRestored(TestList(listOf()), TestList.serializer(), ProtoBuf, hexResultToCheck = "") assertSerializedToBinaryAndRestored( TestString(""), TestString.serializer(), ProtoBuf, hexResultToCheck = "1200" ) } @Test fun testFixedIntWithLong() { assertSerializedToBinaryAndRestored( TestNumbers(100500, Long.MAX_VALUE), TestNumbers.serializer(), ProtoBuf, hexResultToCheck = "0D9488010010FFFFFFFFFFFFFFFF7F" ) } }
1238309850
formats/protobuf/commonTest/src/kotlinx/serialization/protobuf/ProtobufPrimitiveWrappersTest.kt
package com.github.k0kubun.gitstar_ranking.db import com.github.k0kubun.gitstar_ranking.core.StarsCursor import com.github.k0kubun.gitstar_ranking.core.User import org.jooq.DSLContext private const val PAGE_SIZE = 5000 // This class does cursor-based-pagination for users order by stargazers_count DESC. class PaginatedUsers(private val database: DSLContext) { private var lastMinStars: Long? = null private var lastMinId: Long? = null fun nextUsers(): List<User> { val users = if (lastMinId != null && lastMinStars != null) { UserQuery(database).orderByStarsDesc( limit = PAGE_SIZE, after = StarsCursor(id = lastMinId!!, stars = lastMinStars!!), ) } else { UserQuery(database).orderByStarsDesc(limit = PAGE_SIZE) } if (users.isEmpty()) { return users } val lastUser = users[users.size - 1] lastMinStars = lastUser.stargazersCount lastMinId = lastUser.id return users } }
1774135257
worker/src/main/kotlin/com/github/k0kubun/gitstar_ranking/db/PaginatedUsers.kt
/* * Copyright (c) 2016. Sunghyouk Bae <sunghyouk.bae@gmail.com> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.timeperiod.timeranges import debop4k.core.kodatimes.asDateTime import debop4k.core.kodatimes.now import debop4k.timeperiod.DefaultTimeCalendar import debop4k.timeperiod.ITimeCalendar import debop4k.timeperiod.utils.hourRangeSequence import org.joda.time.DateTime /** * Created by debop */ open class HourRangeCollection @JvmOverloads constructor(startTime: DateTime = now(), hourCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar) : HourTimeRange(startTime, hourCount, calendar) { @JvmOverloads constructor(year: Int, monthOfYear: Int, dayOfMonth: Int, hour: Int, hourCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar) : this(asDateTime(year, monthOfYear, dayOfMonth, hour), hourCount, calendar) fun hourSequence(): Sequence<HourRange> { return hourRangeSequence(startHourOfStart, hourCount, calendar) } fun hours(): List<HourRange> { return hourSequence().toList() } companion object { @JvmStatic @JvmOverloads fun of(startTime: DateTime = now(), hourCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar): HourRangeCollection { return HourRangeCollection(startTime, hourCount, calendar) } @JvmStatic @JvmOverloads fun of(year: Int, monthOfYear: Int, dayOfMonth: Int, hour: Int, hourCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar): HourRangeCollection { return HourRangeCollection(year, monthOfYear, dayOfMonth, hour, hourCount, calendar) } } }
69640220
debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/HourRangeCollection.kt
package com.jaredsburrows.license import org.gradle.api.Plugin import org.gradle.api.Project /** A [Plugin] which grabs the POM.xml files from maven dependencies. */ class LicensePlugin : Plugin<Project> { override fun apply(project: Project) { project.extensions.add("licenseReport", LicenseReportExtension::class.java) project.afterEvaluate { when { project.isAndroidProject() -> project.configureAndroidProject() project.isJavaProject() -> project.configureJavaProject() else -> throw UnsupportedOperationException( "'com.jaredsburrows.license' requires Java or Android Gradle Plugins." ) } } } }
31683484
gradle-license-plugin/src/main/kotlin/com/jaredsburrows/license/LicensePlugin.kt
package fr.geobert.radis.tools import android.app.Activity import android.os.Handler import android.os.Message import java.util.* /** * Message Handler class that supports buffering up of messages when the activity is paused i.e. in the background. */ public abstract class PauseHandler : Handler() { /** * Message Queue Buffer */ private val messageQueueBuffer = Collections.synchronizedList(ArrayList<Message>()) /** * Flag indicating the pause state */ private var activity: Activity? = null /** * Resume the handler. */ @Synchronized public fun resume(activity: Activity) { this.activity = activity while (messageQueueBuffer.size > 0) { val msg = messageQueueBuffer.get(0) messageQueueBuffer.removeAt(0) sendMessage(msg) } } /** * Pause the handler. */ @Synchronized public fun pause() { activity = null } /** * Store the message if we have been paused, otherwise handle it now. * @param msg Message to handle. */ @Synchronized override fun handleMessage(msg: Message) { val act = activity if (act == null) { val msgCopy = Message() msgCopy.copyFrom(msg) messageQueueBuffer.add(msgCopy) } else { processMessage(act, msg) } } /** * Notification message to be processed. This will either be directly from * handleMessage or played back from a saved message when the activity was * paused. * @param act Activity owning this Handler that isn't currently paused. * * * @param message Message to be handled */ protected abstract fun processMessage(act: Activity, message: Message) }
3879967102
app/src/main/kotlin/fr/geobert/radis/tools/PauseHandler.kt
package se.ntlv.basiclauncher.image
1019016421
app/src/main/java/se/ntlv/basiclauncher/image/MemoryLruCache.kt
package io.github.areguig.sauron import org.junit.Test import org.junit.runner.RunWith import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) @SpringBootTest class SauronApplicationTests { @Test fun contextLoads() { } }
200222753
src/test/kotlin/io/github/areguig/sauron/SauronApplicationTests.kt
package io.gitlab.arturbosch.detekt.api import org.jetbrains.kotlin.com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.KtElement /** * Stores information about a specific code fragment. * * @author Artur Bosch */ data class Entity(val name: String, val className: String, val signature: String, val location: Location, val ktElement: KtElement? = null) : Compactable { override fun compact() = "[$name] at ${location.compact()}" companion object { fun from(element: PsiElement, offset: Int = 0): Entity { val name = element.searchName() val signature = element.buildFullSignature() val clazz = element.searchClass() return Entity(name, clazz, signature, Location.from(element, offset), element as? KtElement) } } }
132429696
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Entity.kt