content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.service.ui.project.path import com.intellij.ide.wizard.getCanonicalPath import com.intellij.ide.wizard.getPresentablePath import com.intellij.openapi.editor.colors.EditorColors import com.intellij.openapi.externalSystem.service.ui.completion.JTextCompletionContributor import com.intellij.openapi.externalSystem.service.ui.completion.JTextCompletionContributor.CompletionType import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionInfo import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionPopup import com.intellij.openapi.externalSystem.service.ui.completion.TextCompletionPopup.UpdatePopupType.SHOW_IF_HAS_VARIANCES import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.observable.properties.GraphPropertyImpl.Companion.graphProperty import com.intellij.openapi.observable.properties.PropertyGraph import com.intellij.openapi.observable.properties.map import com.intellij.openapi.observable.util.bind import com.intellij.openapi.project.Project import com.intellij.openapi.ui.addKeyboardAction import com.intellij.openapi.ui.getKeyStrokes import com.intellij.openapi.ui.isTextUnderMouse import com.intellij.openapi.ui.BrowseFolderRunnable import com.intellij.openapi.ui.TextComponentAccessor import com.intellij.openapi.util.RecursionManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.fields.ExtendableTextField import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.plaf.basic.BasicTextUI import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter import javax.swing.text.Highlighter class WorkingDirectoryField( project: Project, private val workingDirectoryInfo: WorkingDirectoryInfo ) : ExtendableTextField() { private val propertyGraph = PropertyGraph(isBlockPropagation = false) private val modeProperty = propertyGraph.graphProperty { Mode.NAME } private val textProperty = propertyGraph.graphProperty { "" } private val workingDirectoryProperty = propertyGraph.graphProperty { "" } private val projectNameProperty = propertyGraph.graphProperty { "" } var mode by modeProperty var workingDirectory by workingDirectoryProperty var projectName by projectNameProperty private val externalProjects = workingDirectoryInfo.externalProjects private var highlightTag: Any? = null private val highlightRecursionGuard = RecursionManager.createGuard<WorkingDirectoryField>(WorkingDirectoryField::class.java.name) init { val text by textProperty.map { it.trim() } workingDirectoryProperty.dependsOn(textProperty) { when (mode) { Mode.PATH -> getCanonicalPath(text) Mode.NAME -> resolveProjectPathByName(text) ?: text } } projectNameProperty.dependsOn(textProperty) { when (mode) { Mode.PATH -> resolveProjectNameByPath(getCanonicalPath(text)) ?: text Mode.NAME -> text } } textProperty.dependsOn(modeProperty) { when (mode) { Mode.PATH -> getPresentablePath(workingDirectory) Mode.NAME -> projectName } } textProperty.dependsOn(workingDirectoryProperty) { when (mode) { Mode.PATH -> getPresentablePath(workingDirectory) Mode.NAME -> resolveProjectNameByPath(workingDirectory) ?: getPresentablePath(workingDirectory) } } textProperty.dependsOn(projectNameProperty) { when (mode) { Mode.PATH -> resolveProjectPathByName(projectName) ?: projectName Mode.NAME -> projectName } } modeProperty.dependsOn(workingDirectoryProperty) { when { workingDirectory.isEmpty() -> Mode.NAME resolveProjectNameByPath(workingDirectory) != null -> mode else -> Mode.PATH } } modeProperty.dependsOn(projectNameProperty) { when { projectName.isEmpty() -> Mode.NAME resolveProjectPathByName(projectName) != null -> mode else -> Mode.PATH } } bind(textProperty) } private fun resolveProjectPathByName(projectName: String) = resolveValueByKey(projectName, externalProjects, { name }, { path }) private fun resolveProjectNameByPath(workingDirectory: String) = resolveValueByKey(workingDirectory, externalProjects, { path }, { name }) private fun <E> resolveValueByKey( key: String, entries: List<E>, getKey: E.() -> String, getValue: E.() -> String ): String? { if (key.isNotEmpty()) { val entry = entries.asSequence() .filter { it.getKey().startsWith(key) } .sortedBy { it.getKey().length } .firstOrNull() if (entry != null) { val suffix = entry.getKey().removePrefix(key) if (entry.getValue().endsWith(suffix)) { return entry.getValue().removeSuffix(suffix) } } val parentEntry = entries.asSequence() .filter { key.startsWith(it.getKey()) } .sortedByDescending { it.getKey().length } .firstOrNull() if (parentEntry != null) { val suffix = key.removePrefix(parentEntry.getKey()) return parentEntry.getValue() + suffix } } return null } init { addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (isTextUnderMouse(e)) { mode = Mode.PATH } } }) addKeyboardAction(getKeyStrokes("CollapseRegion", "CollapseRegionRecursively", "CollapseAllRegions")) { mode = Mode.NAME } addKeyboardAction(getKeyStrokes("ExpandRegion", "ExpandRegionRecursively", "ExpandAllRegions")) { mode = Mode.PATH } } init { addHighlighterListener { updateHighlight() } textProperty.afterChange { updateHighlight() } modeProperty.afterChange { updateHighlight() } updateHighlight() } private fun updateHighlight() { highlightRecursionGuard.doPreventingRecursion(this, false) { if (highlightTag != null) { highlighter.removeHighlight(highlightTag) foreground = null } if (mode == Mode.NAME) { val textAttributes = EditorColors.FOLDED_TEXT_ATTRIBUTES.defaultAttributes val painter = DefaultHighlightPainter(textAttributes.backgroundColor) highlightTag = highlighter.addHighlight(0, text.length, painter) foreground = textAttributes.foregroundColor } } } private fun addHighlighterListener(listener: () -> Unit) { highlighter = object : BasicTextUI.BasicHighlighter() { override fun changeHighlight(tag: Any, p0: Int, p1: Int) = super.changeHighlight(tag, p0, p1) .also { listener() } override fun removeHighlight(tag: Any) = super.removeHighlight(tag) .also { listener() } override fun removeAllHighlights() = super.removeAllHighlights() .also { listener() } override fun addHighlight(p0: Int, p1: Int, p: Highlighter.HighlightPainter) = super.addHighlight(p0, p1, p) .also { listener() } } } init { val fileBrowseAccessor = object : TextComponentAccessor<WorkingDirectoryField> { override fun getText(component: WorkingDirectoryField) = workingDirectory override fun setText(component: WorkingDirectoryField, text: String) { workingDirectory = text } } val browseFolderRunnable = object : BrowseFolderRunnable<WorkingDirectoryField>( workingDirectoryInfo.fileChooserTitle, workingDirectoryInfo.fileChooserDescription, project, workingDirectoryInfo.fileChooserDescriptor, this, fileBrowseAccessor ) { override fun chosenFileToResultingText(chosenFile: VirtualFile): String { return ExternalSystemApiUtil.getLocalFileSystemPath(chosenFile) } } addBrowseExtension(browseFolderRunnable, null) } init { val textCompletionContributor = JTextCompletionContributor.create<WorkingDirectoryField>(CompletionType.REPLACE) { textToComplete -> when (mode) { Mode.NAME -> { externalProjects .map { it.name } .map { TextCompletionInfo(it) } } Mode.PATH -> { val pathToComplete = getCanonicalPath(textToComplete, removeLastSlash = false) externalProjects .filter { it.path.startsWith(pathToComplete) } .map { it.path.substring(pathToComplete.length) } .map { textToComplete + FileUtil.toSystemDependentName(it) } .map { TextCompletionInfo(it) } } } } val textCompletionPopup = TextCompletionPopup(project, this, textCompletionContributor) modeProperty.afterChange { textCompletionPopup.updatePopup(SHOW_IF_HAS_VARIANCES) } } enum class Mode { PATH, NAME } }
platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/project/path/WorkingDirectoryField.kt
1590797445
// WITH_STDLIB // PROBLEM: Logger initialized with foreign class 'Bar::class' // FIX: Replace with 'Foo::class' package org.apache.commons.logging class Foo { private val logger = LogFactory.getLog(<caret>Bar::class.java) } class Bar object LogFactory { fun getLog(clazz: Class<*>) {} fun getLog(name: String?) {} }
plugins/kotlin/idea/tests/testData/inspectionsLocal/logging/loggerInitializedWithForeignClass/commons/simple.kt
1580388218
package com.zwq65.unity.data.network.retrofit.callback import android.net.ParseException import com.google.gson.JsonParseException import org.json.JSONException import retrofit2.HttpException import java.net.ConnectException import java.net.SocketTimeoutException /** * ================================================ * api交互异常处理统一返回[ApiException] * * * Created by NIRVANA on 2018/02/05. * Contact with <[email protected]> * ================================================ */ internal object ExceptionHandler { private const val UNAUTHORIZED = 401 private const val FORBIDDEN = 403 private const val NOT_FOUND = 404 private const val REQUEST_TIMEOUT = 408 private const val INTERNAL_SERVER_ERROR = 500 private const val BAD_GATEWAY = 502 private const val SERVICE_UNAVAILABLE = 503 private const val GATEWAY_TIMEOUT = 504 fun handleException(e: Throwable): ApiException { val ex: ApiException if (e is HttpException) { ex = ApiException(e, Error.HTTP_ERROR.toString()) when (e.code()) { UNAUTHORIZED, FORBIDDEN, NOT_FOUND, REQUEST_TIMEOUT, GATEWAY_TIMEOUT, INTERNAL_SERVER_ERROR, BAD_GATEWAY, SERVICE_UNAVAILABLE -> //均视为网络错误 ex.message = "网络异常" else -> ex.message = "网络异常" } return ex } else if (e is JsonParseException || e is JSONException || e is ParseException) { ex = ApiException(e, Error.PARSE_ERROR.toString()) //均视为解析错误 ex.message = "解析异常" return ex } else if (e is ConnectException) { ex = ApiException(e, Error.NETWORK_ERROR.toString()) ex.message = "网络异常:连接失败" return ex } else if (e is SocketTimeoutException) { ex = ApiException(e, Error.NETWORK_ERROR.toString()) ex.message = "网络异常:连接超时" return ex } else if (e is ServerException) { //服务器返回的错误 ex = ApiException(e, e.code) ex.message = e.message return ex } else { ex = ApiException(e, Error.UNKNOWN.toString()) //未知错误 ex.message = "未知异常" return ex } } object Error { /** * 未知错误 */ internal const val UNKNOWN = 1000 /** * 解析错误 */ internal const val PARSE_ERROR = 1001 /** * 网络错误 */ internal const val NETWORK_ERROR = 1002 /** * 协议出错 */ internal const val HTTP_ERROR = 1003 } }
app/src/main/java/com/zwq65/unity/data/network/retrofit/callback/ExceptionHandler.kt
3000319842
/* * Copyright 2018 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.container.tools.test /** * Indicates that the annotated test method should be run on UI event dispatch thread (EDT). * This annotation should be used for all unit tests that manipulate or create any Java Swing UI * components or their children or other UI state, including all IDE platform components. * * This is used in conjunction with the [@Test][org.junit.Test] annotation to run the test method * on EDT. * * ``` * @Test * @UiTest * fun manipulates_UI_components() { ... } * ``` */ @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) annotation class UiTest
common-test-lib/src/main/kotlin/com/google/container/tools/test/UiTest.kt
1955036354
/* * Copyright (C) 2016 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.solver.query.result import androidx.room.solver.CodeGenScope import androidx.room.solver.types.CursorValueReader /** * Wraps a row adapter when there is only 1 item with 1 column in the response. */ class SingleColumnRowAdapter(val reader: CursorValueReader) : RowAdapter(reader.typeMirror()) { override fun convert(outVarName: String, cursorVarName: String, scope: CodeGenScope) { reader.readFromCursor(outVarName, cursorVarName, "0", scope) } }
room/compiler/src/main/kotlin/androidx/room/solver/query/result/SingleColumnRowAdapter.kt
2296451761
/* * Copyright (c) 2017 Kotlin Algorithm Club * * 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 io.uuddlrlrba.ktalgs.graphs interface Graph { public val V: Int public var E: Int public fun adjacentVertices(from: Int): Collection<Int> public fun vertices(): IntRange = 0 until V }
src/main/io/uuddlrlrba/ktalgs/graphs/Graph.kt
3493083836
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.buildServer.clouds.azure import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.util.zip.GZIPInputStream import java.util.zip.GZIPOutputStream import javax.xml.bind.DatatypeConverter object AzureCompress { fun encode(env: Map<String, String>): String { val byteStream = ByteArrayOutputStream() GZIPOutputStream(byteStream).use { stream -> stream.bufferedWriter().use { writer -> env.forEach { writer.appendln("${it.key}=${it.value}") } } } return DatatypeConverter.printBase64Binary(byteStream.toByteArray()) } fun decode(text: String): Map<String, String> { val map = hashMapOf<String, String>() val byteStream = ByteArrayInputStream(DatatypeConverter.parseBase64Binary(text)) GZIPInputStream(byteStream).use { stream -> stream.bufferedReader().lines().forEach { val (key, value) = it.split('=') map[key] = value } } return map } }
plugin-azure-common/src/main/kotlin/jetbrains/buildServer/clouds/azure/AzureCompress.kt
2971146774
package com.niortreactnative.fragments import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.niortreactnative.R import com.niortreactnative.adapters.Line import com.niortreactnative.adapters.LineListAdapter import com.niortreactnative.interfaces.AdapterCallback import kotlinx.android.synthetic.main.fragment_line_list.* /** * A simple [Fragment] subclass. */ class LineListFragment : Fragment(), AdapterCallback{ private val TAG = "LineListFragment" private lateinit var _view:View lateinit var mCallback:OnLineSelectedListener interface OnLineSelectedListener { fun onLineSelected(line:Line) } override fun onAttach(context: Context?) { super.onAttach(context) if (context !is OnLineSelectedListener) { Log.e(TAG, "Failed cast :-(") throw ClassCastException(context.toString() + " must implement OnLineSelecteeListener") } else { mCallback = context } } override fun onAdapterCallback(line:Line) { mCallback.onLineSelected(line) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { _view = inflater!!.inflate(R.layout.fragment_line_list, container, false) return _view } override fun onResume() { super.onResume() Log.d(TAG, "on resume") populateLineList() addListeners() } private fun populateLineList (){ line_list.layoutManager = LinearLayoutManager(context) line_list.adapter = LineListAdapter(this) } private fun addListeners() { } }// Required empty public constructor
app/src/main/java/com/niortreactnative/fragments/LineListFragment.kt
2094617746
package net.ketc.numeri.presentation.presenter.fragment.tweet.display import net.ketc.numeri.domain.model.Tweet import net.ketc.numeri.domain.model.cache.convert import net.ketc.numeri.presentation.view.fragment.TimeLineFragmentInterface import twitter4j.Paging class UserListPresenter(timeLineFragment: TimeLineFragmentInterface) : TimeLinePresenter(timeLineFragment) { val listId = fragment.display.foreignId override fun getTweets(paging: Paging): List<Tweet> = client.twitter.getUserListStatuses(listId, paging).map { it.convert(client) } override fun beforeInitializeLoad() { } override fun afterInitializeLoad() { fragment.isRefreshable = fragment.refreshableConfig } }
app/src/main/kotlin/net/ketc/numeri/presentation/presenter/fragment/tweet/display/UserListPresenter.kt
2996606138
package io.kotlincheck.shrink import io.kotlincheck.* class PairShrinker<A, B>( val shrinker1: Shrinker<A>, val shrinker2: Shrinker<B> ) : Shrinker<Pair<A, B>> { override fun shrink( test: (Pair<A, B>) -> Boolean, counterexample: Pair<A, B> ): Pair<A, B> { var (first, second) = counterexample first = shrinker1.shrink({ test(Pair(it, second)) }, first) second = shrinker2.shrink({ test(Pair(first, it)) }, second) return Pair(first, second) } } class TripleShrinker<A, B, C>( val shrinker1: Shrinker<A>, val shrinker2: Shrinker<B>, val shrinker3: Shrinker<C> ) : Shrinker<Triple<A, B, C>> { override fun shrink( test: (Triple<A, B, C>) -> Boolean, counterexample: Triple<A, B, C> ): Triple<A, B, C> { var (first, second, third) = counterexample first = shrinker1.shrink({ test(Triple(it, second, third)) }, first) second = shrinker2.shrink({ test(Triple(first, it, third)) }, second) third = shrinker3.shrink({ test(Triple(first, second, it)) }, third) return Triple(first, second, third) } } internal class Tuple2Shrinker<T1, T2>( val shrinker1: Shrinker<T1>, val shrinker2: Shrinker<T2> ) : Shrinker<Tuple2<T1, T2>> { override fun shrink( test: (Tuple2<T1, T2>) -> Boolean, counterexample: Tuple2<T1, T2> ): Tuple2<T1, T2> { var (elem1, elem2) = counterexample elem1 = shrinker1.shrink({ test(Tuple2(it, elem2)) }, elem1) elem2 = shrinker2.shrink({ test(Tuple2(elem1, it)) }, elem2) return Tuple2(elem1, elem2) } } internal class Tuple3Shrinker<T1, T2, T3>( val shrinker1: Shrinker<T1>, val shrinker2: Shrinker<T2>, val shrinker3: Shrinker<T3> ) : Shrinker<Tuple3<T1, T2, T3>> { override fun shrink( test: (Tuple3<T1, T2, T3>) -> Boolean, counterexample: Tuple3<T1, T2, T3> ): Tuple3<T1, T2, T3> { var (elem1, elem2, elem3) = counterexample elem1 = shrinker1.shrink({ test(Tuple3(it, elem2, elem3)) }, elem1) elem2 = shrinker2.shrink({ test(Tuple3(elem1, it, elem3)) }, elem2) elem3 = shrinker3.shrink({ test(Tuple3(elem1, elem2, it)) }, elem3) return Tuple3(elem1, elem2, elem3) } } internal class Tuple4Shrinker<T1, T2, T3, T4>( val shrinker1: Shrinker<T1>, val shrinker2: Shrinker<T2>, val shrinker3: Shrinker<T3>, val shrinker4: Shrinker<T4> ) : Shrinker<Tuple4<T1, T2, T3, T4>> { override fun shrink( test: (Tuple4<T1, T2, T3, T4>) -> Boolean, counterexample: Tuple4<T1, T2, T3, T4> ): Tuple4<T1, T2, T3, T4> { var (elem1, elem2, elem3, elem4) = counterexample elem1 = shrinker1.shrink({ test(Tuple4(it, elem2, elem3, elem4)) }, elem1) elem2 = shrinker2.shrink({ test(Tuple4(elem1, it, elem3, elem4)) }, elem2) elem3 = shrinker3.shrink({ test(Tuple4(elem1, elem2, it, elem4)) }, elem3) elem4 = shrinker4.shrink({ test(Tuple4(elem1, elem2, elem3, it)) }, elem4) return Tuple4(elem1, elem2, elem3, elem4) } } internal class Tuple5Shrinker<T1, T2, T3, T4, T5>( val shrinker1: Shrinker<T1>, val shrinker2: Shrinker<T2>, val shrinker3: Shrinker<T3>, val shrinker4: Shrinker<T4>, val shrinker5: Shrinker<T5> ) : Shrinker<Tuple5<T1, T2, T3, T4, T5>> { override fun shrink( test: (Tuple5<T1, T2, T3, T4, T5>) -> Boolean, counterexample: Tuple5<T1, T2, T3, T4, T5> ): Tuple5<T1, T2, T3, T4, T5> { var (elem1, elem2, elem3, elem4, elem5) = counterexample elem1 = shrinker1.shrink({ test(Tuple5(it, elem2, elem3, elem4, elem5)) }, elem1) elem2 = shrinker2.shrink({ test(Tuple5(elem1, it, elem3, elem4, elem5)) }, elem2) elem3 = shrinker3.shrink({ test(Tuple5(elem1, elem2, it, elem4, elem5)) }, elem3) elem4 = shrinker4.shrink({ test(Tuple5(elem1, elem2, elem3, it, elem5)) }, elem4) elem5 = shrinker5.shrink({ test(Tuple5(elem1, elem2, elem3, elem4, it)) }, elem5) return Tuple5(elem1, elem2, elem3, elem4, elem5) } } internal class Tuple6Shrinker<T1, T2, T3, T4, T5, T6>( val shrinker1: Shrinker<T1>, val shrinker2: Shrinker<T2>, val shrinker3: Shrinker<T3>, val shrinker4: Shrinker<T4>, val shrinker5: Shrinker<T5>, val shrinker6: Shrinker<T6> ) : Shrinker<Tuple6<T1, T2, T3, T4, T5, T6>> { override fun shrink( test: (Tuple6<T1, T2, T3, T4, T5, T6>) -> Boolean, counterexample: Tuple6<T1, T2, T3, T4, T5, T6> ): Tuple6<T1, T2, T3, T4, T5, T6> { var (elem1, elem2, elem3, elem4, elem5, elem6) = counterexample elem1 = shrinker1.shrink({ test(Tuple6(it, elem2, elem3, elem4, elem5, elem6)) }, elem1) elem2 = shrinker2.shrink({ test(Tuple6(elem1, it, elem3, elem4, elem5, elem6)) }, elem2) elem3 = shrinker3.shrink({ test(Tuple6(elem1, elem2, it, elem4, elem5, elem6)) }, elem3) elem4 = shrinker4.shrink({ test(Tuple6(elem1, elem2, elem3, it, elem5, elem6)) }, elem4) elem5 = shrinker5.shrink({ test(Tuple6(elem1, elem2, elem3, elem4, it, elem6)) }, elem5) elem6 = shrinker6.shrink({ test(Tuple6(elem1, elem2, elem3, elem4, elem5, it)) }, elem6) return Tuple6(elem1, elem2, elem3, elem4, elem5, elem6) } } internal class Tuple7Shrinker<T1, T2, T3, T4, T5, T6, T7>( val shrinker1: Shrinker<T1>, val shrinker2: Shrinker<T2>, val shrinker3: Shrinker<T3>, val shrinker4: Shrinker<T4>, val shrinker5: Shrinker<T5>, val shrinker6: Shrinker<T6>, val shrinker7: Shrinker<T7> ) : Shrinker<Tuple7<T1, T2, T3, T4, T5, T6, T7>> { override fun shrink( test: (Tuple7<T1, T2, T3, T4, T5, T6, T7>) -> Boolean, counterexample: Tuple7<T1, T2, T3, T4, T5, T6, T7> ): Tuple7<T1, T2, T3, T4, T5, T6, T7> { var (elem1, elem2, elem3, elem4, elem5, elem6, elem7) = counterexample elem1 = shrinker1.shrink({ test(Tuple7(it, elem2, elem3, elem4, elem5, elem6, elem7)) }, elem1) elem2 = shrinker2.shrink({ test(Tuple7(elem1, it, elem3, elem4, elem5, elem6, elem7)) }, elem2) elem3 = shrinker3.shrink({ test(Tuple7(elem1, elem2, it, elem4, elem5, elem6, elem7)) }, elem3) elem4 = shrinker4.shrink({ test(Tuple7(elem1, elem2, elem3, it, elem5, elem6, elem7)) }, elem4) elem5 = shrinker5.shrink({ test(Tuple7(elem1, elem2, elem3, elem4, it, elem6, elem7)) }, elem5) elem6 = shrinker6.shrink({ test(Tuple7(elem1, elem2, elem3, elem4, elem5, it, elem7)) }, elem6) elem7 = shrinker7.shrink({ test(Tuple7(elem1, elem2, elem3, elem4, elem5, elem6, it)) }, elem7) return Tuple7(elem1, elem2, elem3, elem4, elem5, elem6, elem7) } } internal class Tuple8Shrinker<T1, T2, T3, T4, T5, T6, T7, T8>( val shrinker1: Shrinker<T1>, val shrinker2: Shrinker<T2>, val shrinker3: Shrinker<T3>, val shrinker4: Shrinker<T4>, val shrinker5: Shrinker<T5>, val shrinker6: Shrinker<T6>, val shrinker7: Shrinker<T7>, val shrinker8: Shrinker<T8> ) : Shrinker<Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>> { override fun shrink( test: (Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>) -> Boolean, counterexample: Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> ): Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> { var (elem1, elem2, elem3, elem4, elem5, elem6, elem7, elem8) = counterexample elem1 = shrinker1.shrink({ test(Tuple8(it, elem2, elem3, elem4, elem5, elem6, elem7, elem8)) }, elem1) elem2 = shrinker2.shrink({ test(Tuple8(elem1, it, elem3, elem4, elem5, elem6, elem7, elem8)) }, elem2) elem3 = shrinker3.shrink({ test(Tuple8(elem1, elem2, it, elem4, elem5, elem6, elem7, elem8)) }, elem3) elem4 = shrinker4.shrink({ test(Tuple8(elem1, elem2, elem3, it, elem5, elem6, elem7, elem8)) }, elem4) elem5 = shrinker5.shrink({ test(Tuple8(elem1, elem2, elem3, elem4, it, elem6, elem7, elem8)) }, elem5) elem6 = shrinker6.shrink({ test(Tuple8(elem1, elem2, elem3, elem4, elem5, it, elem7, elem8)) }, elem6) elem7 = shrinker7.shrink({ test(Tuple8(elem1, elem2, elem3, elem4, elem5, elem6, it, elem8)) }, elem7) elem8 = shrinker8.shrink({ test(Tuple8(elem1, elem2, elem3, elem4, elem5, elem6, elem7, it)) }, elem8) return Tuple8(elem1, elem2, elem3, elem4, elem5, elem6, elem7, elem8) } } internal class Tuple9Shrinker<T1, T2, T3, T4, T5, T6, T7, T8, T9>( val shrinker1: Shrinker<T1>, val shrinker2: Shrinker<T2>, val shrinker3: Shrinker<T3>, val shrinker4: Shrinker<T4>, val shrinker5: Shrinker<T5>, val shrinker6: Shrinker<T6>, val shrinker7: Shrinker<T7>, val shrinker8: Shrinker<T8>, val shrinker9: Shrinker<T9> ) : Shrinker<Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>> { override fun shrink( test: (Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>) -> Boolean, counterexample: Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9> ): Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9> { var (elem1, elem2, elem3, elem4, elem5, elem6, elem7, elem8, elem9) = counterexample elem1 = shrinker1.shrink( { test(Tuple9(it, elem2, elem3, elem4, elem5, elem6, elem7, elem8, elem9)) }, elem1 ) elem2 = shrinker2.shrink( { test(Tuple9(elem1, it, elem3, elem4, elem5, elem6, elem7, elem8, elem9)) }, elem2 ) elem3 = shrinker3.shrink( { test(Tuple9(elem1, elem2, it, elem4, elem5, elem6, elem7, elem8, elem9)) }, elem3 ) elem4 = shrinker4.shrink( { test(Tuple9(elem1, elem2, elem3, it, elem5, elem6, elem7, elem8, elem9)) }, elem4 ) elem5 = shrinker5.shrink( { test(Tuple9(elem1, elem2, elem3, elem4, it, elem6, elem7, elem8, elem9)) }, elem5 ) elem6 = shrinker6.shrink( { test(Tuple9(elem1, elem2, elem3, elem4, elem5, it, elem7, elem8, elem9)) }, elem6 ) elem7 = shrinker7.shrink( { test(Tuple9(elem1, elem2, elem3, elem4, elem5, elem6, it, elem8, elem9)) }, elem7 ) elem8 = shrinker8.shrink( { test(Tuple9(elem1, elem2, elem3, elem4, elem5, elem6, elem7, it, elem9)) }, elem8 ) elem9 = shrinker9.shrink( { test(Tuple9(elem1, elem2, elem3, elem4, elem5, elem6, elem7, elem8, it)) }, elem9 ) return Tuple9(elem1, elem2, elem3, elem4, elem5, elem6, elem7, elem8, elem9) } }
src/main/kotlin/io/kotlincheck/shrink/TuplesShrink.kt
3720286394
package me.proxer.library.enums import com.serjltt.moshi.adapters.FallbackEnum import com.squareup.moshi.Moshi import org.amshove.kluent.shouldBe import org.junit.jupiter.api.Test /** * @author Ruben Gees */ class GenderTest { private val adapter = Moshi.Builder() .add(FallbackEnum.ADAPTER_FACTORY) .build() .adapter(Gender::class.java) @Test fun testDefault() { adapter.fromJson("\"f\"") shouldBe Gender.FEMALE } @Test fun testFallback() { adapter.fromJson("\"xyz\"") shouldBe Gender.UNKNOWN } }
library/src/test/kotlin/me/proxer/library/enums/GenderTest.kt
329098723
package chat.rocket.android.db.model import androidx.room.Embedded import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey import androidx.room.TypeConverters import chat.rocket.android.emoji.internal.db.StringListConverter @Entity(tableName = "chatrooms", indices = [ Index(value = ["userId"]), Index(value = ["ownerId"]), Index(value = ["subscriptionId"], unique = true), Index(value = ["updatedAt"]), Index(value = ["lastMessageUserId"]) ], foreignKeys = [ ForeignKey(entity = UserEntity::class, parentColumns = ["id"], childColumns = ["ownerId"]), ForeignKey(entity = UserEntity::class, parentColumns = ["id"], childColumns = ["userId"]), ForeignKey(entity = UserEntity::class, parentColumns = ["id"], childColumns = ["lastMessageUserId"]) ] ) @TypeConverters(StringListConverter::class) data class ChatRoomEntity( @PrimaryKey var id: String, var subscriptionId: String, var parentId: String?, var type: String, var name: String, var fullname: String? = null, var userId: String? = null, var ownerId: String? = null, var readonly: Boolean? = false, var isDefault: Boolean? = false, var favorite: Boolean? = false, var topic: String? = null, var announcement: String? = null, var description: String? = null, var open: Boolean? = true, var alert: Boolean? = false, var unread: Long? = 0, var userMentions: Long? = 0, var groupMentions: Long? = 0, var updatedAt: Long? = -1, var timestamp: Long? = -1, var lastSeen: Long? = -1, var lastMessageText: String? = null, var lastMessageUserId: String? = null, var lastMessageTimestamp: Long? = null, var broadcast: Boolean? = false, var muted: List<String>? = null ) data class ChatRoom( @Embedded var chatRoom: ChatRoomEntity, var username: String?, var userFullname: String?, var status: String?, var lastMessageUserName: String?, var lastMessageUserFullName: String? )
app/src/main/java/chat/rocket/android/db/model/ChatRoomEntity.kt
423658871
package com.encodeering.conflate.experimental.epic import com.encodeering.conflate.experimental.api.Action import com.encodeering.conflate.experimental.api.Middleware import com.encodeering.conflate.experimental.epic.Story.Aspect import com.encodeering.conflate.experimental.epic.Story.Happening import com.encodeering.conflate.experimental.epic.rx.async import com.encodeering.conflate.experimental.epic.rx.await import com.encodeering.conflate.experimental.epic.rx.combine import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import kotlin.coroutines.experimental.CoroutineContext import kotlin.coroutines.experimental.EmptyCoroutineContext /** * @author Michael Clausen - [email protected] */ class Epic<State> ( private val context : CoroutineContext, vararg stories : Story<State> ) : Middleware<State> { constructor (vararg stories : Story<State>) : this (EmptyCoroutineContext, * stories) val daemons by lazy { stories.filter { it.endless } } val visuals by lazy { stories.filterNot { it.endless } } override fun interceptor (connection : Middleware.Connection<State>) : Middleware.Interceptor { return object : Middleware.Interceptor { val daemons by lazy { [email protected] (this::raconteur) } val visuals get () = [email protected] (this::raconteur) fun raconteur (story : Story<State>) : Raconteur<State> { val forward : suspend (Happening) -> Happening = { when (it) { is Happening.Next -> connection.next (it.action) is Happening.Initial -> connection.initial (it.action) } it } val aspects = PublishSubject.create<Aspect<Action, State>> ()!! return Raconteur (aspects, story.embellish (aspects).async (forward, context)) } suspend override fun dispatch (action : Action) { val aspect = Aspect (action, connection.state) daemons.run { tell (aspect, finish = false) } visuals.run { map { it.happenings }.combine ().doOnSubscribe { tell (aspect, finish = true) } }.await () } } } private fun Iterable<Raconteur<State>>.tell (aspect : Aspect<Action, State>, finish : Boolean) { forEach { try { it.tell (aspect) } catch (e : Exception) { it.abort (e) } finally { if (finish) it.finish () } } } private class Raconteur<in State> (private val aspects : Subject<Aspect<Action, State>>, val happenings : Observable<Happening>) { fun tell (aspect : Aspect<Action, State>) = aspects.onNext (aspect) fun abort (e : Exception) = aspects.onError (e) fun finish () = aspects.onComplete () } }
modules/conflate-epic/src/main/kotlin/com/encodeering/conflate/experimental/epic/Epic.kt
3584661135
package com.github.prologdb.runtime.term import com.github.prologdb.runtime.NullSourceInformation import com.github.prologdb.runtime.PrologSourceInformation import com.github.prologdb.runtime.RandomVariableScope import com.github.prologdb.runtime.unification.Unification import com.github.prologdb.runtime.unification.VariableDiscrepancyException import com.github.prologdb.runtime.util.OperatorRegistry @PrologTypeName("dict") class PrologDictionary(givenPairs: Map<Atom, Term>, givenTail: Term? = null) : Term { val tail: Variable? val pairs: Map<Atom, Term> init { if (givenTail !is Variable? && givenTail !is PrologDictionary?) { throw IllegalArgumentException("The tail must be a dict, variable or absent") } if (givenTail is PrologDictionary) { val combinedPairs = givenPairs as? MutableMap ?: givenPairs.toMutableMap() var pivot: Term? = givenTail while (pivot is PrologDictionary) { pivot.pairs.forEach { combinedPairs.putIfAbsent(it.key, it.value) } pivot = pivot.tail } pairs = combinedPairs tail = pivot as Variable? } else { pairs = givenPairs tail = givenTail as Variable? } } override fun unify(rhs: Term, randomVarsScope: RandomVariableScope): Unification? { if (rhs is Variable) return rhs.unify(this, randomVarsScope) if (rhs !is PrologDictionary) return Unification.FALSE val carryUnification = Unification() val commonKeys = this.pairs.keys.intersect(rhs.pairs.keys) if (this.pairs.size > commonKeys.size) { // LHS has more pairs than are common; those will have to go into RHSs tail if (rhs.tail == null) { // impossible => no unification return Unification.FALSE } else { val subDict = PrologDictionary(pairs.filterKeys { it !in commonKeys }) try { carryUnification.variableValues.incorporate( rhs.tail.unify(subDict, randomVarsScope).variableValues ) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } } else if (rhs.tail != null) { try { carryUnification.variableValues.incorporate( rhs.tail.unify(EMPTY, randomVarsScope).variableValues ) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } if (rhs.pairs.size > commonKeys.size) { // RHS has more pairs than are common; those will have to go into this' tail if (this.tail == null) { // impossible => no unification return Unification.FALSE } else { val subDict = PrologDictionary(rhs.pairs.filterKeys { it !in commonKeys }) try { carryUnification.variableValues.incorporate( this.tail.unify(subDict, randomVarsScope).variableValues ) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } } else if (this.tail != null) { try { carryUnification.variableValues.incorporate( this.tail.unify(EMPTY, randomVarsScope).variableValues ) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } for (commonKey in commonKeys) { val thisValue = this.pairs[commonKey]!! val rhsValue = rhs.pairs[commonKey]!! val keyUnification = thisValue.unify(rhsValue, randomVarsScope) if (keyUnification == null) { // common key did not unify => we're done return Unification.FALSE } try { carryUnification.variableValues.incorporate(keyUnification.variableValues) } catch (ex: VariableDiscrepancyException) { return Unification.FALSE } } return carryUnification } override val variables: Set<Variable> by lazy { var variables = pairs.values.flatMap { it.variables } val tail = this.tail // invoke override getter only once if (tail != null) { if (variables !is MutableList) variables = variables.toMutableList() variables.add(tail) } variables.toSet() } override fun substituteVariables(mapper: (Variable) -> Term): PrologDictionary { return PrologDictionary(pairs.mapValues { it.value.substituteVariables(mapper) }, tail?.substituteVariables(mapper)).also { it.sourceInformation = this.sourceInformation } } override fun compareTo(other: Term): Int { if (other is Variable || other is PrologNumber || other is PrologString || other is Atom || other is PrologList) { // these are by category lesser than compound terms return 1 } // dicts are not compared by content, neither against predicates nor against other dicts return 0 } override fun toString(): String { var str = pairs.entries .joinToString( separator = ", ", transform = { it.key.toString() + ": " + it.value.toString() } ) if (tail != null) { str += "|$tail" } return "{$str}" } override fun toStringUsingOperatorNotations(operators: OperatorRegistry): String { var str = pairs.entries .joinToString( separator = ", ", transform = { it.key.toStringUsingOperatorNotations(operators) + ": " + it.value.toStringUsingOperatorNotations(operators) } ) if (tail != null) { str += "|${tail.toStringUsingOperatorNotations(operators)}" } return "{$str}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is PrologDictionary) return false if (tail != other.tail) return false if (pairs != other.pairs) return false return true } override fun hashCode(): Int { var result = tail?.hashCode() ?: 0 result = 31 * result + pairs.hashCode() return result } companion object { val EMPTY = PrologDictionary(emptyMap()) } override var sourceInformation: PrologSourceInformation = NullSourceInformation }
core/src/main/kotlin/com/github/prologdb/runtime/term/PrologDictionary.kt
1497228343
package jp.co.tokubai.android.garage import okhttp3.Call import okhttp3.Request import okhttp3.Response abstract class GarageRequest { abstract fun url(): String abstract fun newCall(requestProcessing: (Request.Builder) -> Request.Builder): Call abstract suspend fun execute(): Response abstract fun requestTime(): Long }
garage-core/src/main/java/jp/co/tokubai/android/garage/GarageRequest.kt
1957723547
package org.klips.dsl interface Asserter { val asserted: List<Fact> val retired: List<Fact> fun assert(vararg facts: Fact): Array<out Fact> fun retire(vararg facts: Fact): Array<out Fact> operator fun <T : Fact> T.unaryPlus() : T { assert(this) return this } operator fun <T : Fact> T.unaryMinus() : T { retire(this) return this } }
src/main/java/org/klips/dsl/Asserter.kt
2142067585
/* * 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.Connection import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider import com.google.android.libraries.pcc.chronicle.api.ConnectionRequest import com.google.android.libraries.pcc.chronicle.api.DataType import com.google.android.libraries.pcc.chronicle.api.DeletionTrigger import com.google.android.libraries.pcc.chronicle.api.ManagedDataType 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.Trigger import com.google.android.libraries.pcc.chronicle.api.dataTypeDescriptor import com.google.android.libraries.pcc.chronicle.api.policy.StorageMedium import com.google.android.libraries.pcc.chronicle.api.policy.builder.PolicyCheck import com.google.android.libraries.pcc.chronicle.api.policy.builder.deletionTriggers import com.google.android.libraries.pcc.chronicle.api.policy.builder.policy import com.google.android.libraries.pcc.chronicle.api.policy.builder.target 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 ManagementStrategyValidationTest { @Test fun policy_verifyManagementStrategies() { val policy = policy("MyPolicy", "SomeKindaEgress") { target(FOO_DTD, maxAge = Duration.ofMillis(Long.MAX_VALUE)) { retention(StorageMedium.DISK) deletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg") } target(BAR_DTD, maxAge = Duration.ofMinutes(5)) { retention(StorageMedium.RAM) } // Baz won't be used. target(BAZ_DTD, maxAge = Duration.ofMillis(1)) { retention(StorageMedium.RAM, encryptionRequired = true) } } val connectionProviders = listOf( makeConnectionProvider( ManagedDataType( descriptor = dataTypeDescriptor(name = "Foo", Unit::class), managementStrategy = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.LOCAL_DISK, ttl = null, deletionTriggers = setOf( DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg"), DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "optional_trigger"), ) ), connectionTypes = emptySet() ) ), makeConnectionProvider( ManagedDataType( descriptor = dataTypeDescriptor(name = "Bar", Unit::class), managementStrategy = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.MEMORY, ttl = Duration.ofMinutes(5) ), connectionTypes = emptySet() ) ) ) assertThat(policy.verifyManagementStrategies(connectionProviders)).isEmpty() } @Test fun policyTarget_verifyRetentionSatisfiedBy_valid() { val dataType = ManagedDataType( descriptor = FOO_DTD, managementStrategy = ManagementStrategy.Stored( encrypted = true, media = StorageMedia.MEMORY, ttl = Duration.ofMinutes(5) ), connectionTypes = emptySet() ) assertThat(FOO_TARGET.verifyRetentionSatisfiedBy(dataType)).isEmpty() } @Test fun policyTarget_verifyRetentionSatisfiedBy_invalid() { val dataType = ManagedDataType( descriptor = FOO_DTD, managementStrategy = ManagementStrategy.Stored( encrypted = true, media = StorageMedia.LOCAL_DISK, ttl = Duration.ofMinutes(5) ), connectionTypes = emptySet() ) assertThat(FOO_TARGET.verifyRetentionSatisfiedBy(dataType)).hasSize(1) } @Test fun satifiesDeletion_whenPassthru_alwaysTrue() { val strategy = ManagementStrategy.PassThru FOO_TARGET.deletionTriggers().forEach { assertThat(strategy.satisfies(it)).isTrue() } } @Test fun satifiesDeletion_whenStored_passesWithCorrectTriggers() { val strategy = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.MEMORY, ttl = Duration.ofMinutes(5), deletionTriggers = setOf( DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg1"), DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg2"), DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "optional_trigger"), ) ) FOO_TARGET.deletionTriggers().forEach { assertThat(strategy.satisfies(it)).isTrue() } } @Test fun satifiesDeletion_whenStored_failsWithoutTrigger() { val dataType = ManagedDataType( descriptor = FOO_DTD, managementStrategy = ManagementStrategy.Stored( encrypted = false, media = StorageMedia.MEMORY, ttl = Duration.ofMinutes(5), deletionTriggers = setOf( DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "optional_trigger"), ) ), connectionTypes = emptySet() ) FOO_TARGET.deletionTriggers().forEach { assertThat(dataType.managementStrategy.satisfies(it)).isFalse() } assertThat(FOO_TARGET.verifyDeletionTriggersSatisfiedBy(dataType)) .containsExactly( PolicyCheck( "h:${FOO_DTD.name} is DeletionTrigger(trigger=PACKAGE_UNINSTALLED, targetField=pkg1)" ), PolicyCheck( "h:${FOO_DTD.name} is DeletionTrigger(trigger=PACKAGE_UNINSTALLED, targetField=pkg2)" ) ) } @Test fun deletionTriggersParsed_Normally() { val triggers = FOO_TARGET.deletionTriggers() val expectedTriggers = setOf( DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg1"), DeletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg2") ) assertThat(triggers).isEqualTo(expectedTriggers) } private fun makeConnectionProvider(managedDataType: ManagedDataType): ConnectionProvider { return object : ConnectionProvider { override val dataType: DataType = managedDataType override fun getConnection(connectionRequest: ConnectionRequest<out Connection>): Connection = throw UnsupportedOperationException("Not used here") } } companion object { val FOO_DTD = dataTypeDescriptor("Foo", Unit::class) val BAR_DTD = dataTypeDescriptor("Bar", Unit::class) val BAZ_DTD = dataTypeDescriptor("Baz", Unit::class) val FOO_TARGET = target(FOO_DTD, maxAge = Duration.ofMinutes(5)) { retention(StorageMedium.RAM, false) deletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg1") deletionTrigger(Trigger.PACKAGE_UNINSTALLED, "pkg2") } } }
javatests/com/google/android/libraries/pcc/chronicle/analysis/impl/ManagementStrategyValidationTest.kt
799950400
package com.wabadaba.dziennik import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.wabadaba.dziennik.ui.multiPutAll import io.reactivex.Observable import io.reactivex.Single import io.requery.Persistable import io.requery.reactivex.KotlinReactiveEntityStore import io.requery.reactivex.ReactiveResult import io.requery.reactivex.ReactiveScalar import kotlin.reflect.KClass import kotlin.reflect.full.superclasses @Suppress("UNCHECKED_CAST") class InMemoryEntityStore { companion object { fun getDatastore(): KotlinReactiveEntityStore<Persistable> { val multiMap = mutableMapOf<KClass<Persistable>, List<Persistable>>() return mock { on { upsert(any<List<Persistable>>()) } doAnswer { invocation -> val entities = invocation.getArgument<List<Persistable>>(0) if (entities.isNotEmpty()) { val kClass = entities.first()::class.superclasses[0] as KClass<Persistable> multiMap.multiPutAll(kClass, entities) } Single.just(entities) } on { select(any<KClass<Persistable>>()) } doAnswer { invocation -> val kClass = invocation.getArgument<KClass<Persistable>>(0) val res = multiMap[kClass] ?: emptyList() val resultMock = mock<ReactiveResult<Persistable>> { on { observable() } doReturn (Observable.fromIterable(res)) } mock { on { get() } doReturn resultMock } } on { delete(any<KClass<Persistable>>()) } doAnswer { invocation -> val kClass = invocation.getArgument<KClass<Persistable>>(0) multiMap.remove(kClass) val resultMock = mock<ReactiveScalar<Int>> { on { single() } doReturn (Single.just(0)) } mock { on { get() } doReturn resultMock } } } } } }
app/src/test/kotlin/com/wabadaba/dziennik/InMemoryEntityStore.kt
3612168485
package ca.josephroque.bowlingcompanion.transfer import ca.josephroque.bowlingcompanion.common.fragments.BaseFragment /** * Copyright (C) 2018 Joseph Roque * * Declares values which transfer menu fragments must provide */ abstract class BaseTransferFragment : BaseFragment() { abstract val toolbarTitle: Int? abstract val isBackEnabled: Boolean // MARK: BaseFragment override fun updateToolbarTitle() { // Intentionally left blank } }
app/src/main/java/ca/josephroque/bowlingcompanion/transfer/BaseTransferFragment.kt
56098070
/* * 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.essentials.bukkit.command.issue import com.rpkit.core.command.RPKCommandExecutor import com.rpkit.core.command.result.CommandResult import com.rpkit.core.command.result.IncorrectUsageFailure import com.rpkit.core.command.sender.RPKCommandSender import com.rpkit.essentials.bukkit.RPKEssentialsBukkit import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.completedFuture class IssueCommand(private val plugin: RPKEssentialsBukkit) : RPKCommandExecutor { private val issueSubmitCommand = IssueSubmitCommand(plugin) override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<out CommandResult> { if (args.isEmpty()) { sender.sendMessage(plugin.messages.issueUsage) return completedFuture(IncorrectUsageFailure()) } return when (args[0].lowercase()) { "submit", "create" -> issueSubmitCommand.onCommand(sender, args.drop(1).toTypedArray()) else -> { sender.sendMessage(plugin.messages.issueUsage) completedFuture(IncorrectUsageFailure()) } } } }
bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/issue/IssueCommand.kt
880191023
package test.assertk.assertions import assertk.assertThat import assertk.assertions.isFalse import assertk.assertions.isTrue import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails class BooleanTest { //region isTrue @Test fun isTrue_true_value_passes() { assertThat(true).isTrue() } @Test fun isTrue_false_value_fails() { val error = assertFails { assertThat(false).isTrue() } assertEquals("expected to be true", error.message) } //endregion //region isFalse @Test fun isFalse_false_value_passes() { assertThat(false).isFalse() } @Test fun isFalse_true_value_fails() { val error = assertFails { assertThat(true).isFalse() } assertEquals("expected to be false", error.message) } //endregion }
assertk/src/commonTest/kotlin/test/assertk/assertions/BooleanTest.kt
1919265687
/* * 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.compose.rally import android.os.Build import androidx.compose.foundation.background import androidx.compose.foundation.layout.size import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.MainTestClock import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onRoot import androidx.compose.ui.unit.dp import androidx.test.filters.SdkSuppress import com.example.compose.rally.ui.components.AnimatedCircle import com.example.compose.rally.ui.theme.RallyTheme import org.junit.Rule import org.junit.Test /** * Test to showcase [MainTestClock] present in [ComposeTestRule]. It allows for animation * testing at specific points in time. * * For assertions, a simple screenshot testing framework is used. It requires SDK 26+ and to * be run on a device with 420dpi, as that the density used to generate the golden images * present in androidTest/assets. It runs bitmap comparisons on device. * * Note that different systems can produce slightly different screenshots making the test fail. */ @ExperimentalTestApi @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) class AnimatingCircleTests { @get:Rule val composeTestRule = createComposeRule() @Test fun circleAnimation_idle_screenshot() { composeTestRule.mainClock.autoAdvance = true showAnimatedCircle() assertScreenshotMatchesGolden("circle_done", composeTestRule.onRoot()) } @Test fun circleAnimation_initial_screenshot() { compareTimeScreenshot(0, "circle_initial") } @Test fun circleAnimation_beforeDelay_screenshot() { compareTimeScreenshot(499, "circle_initial") } @Test fun circleAnimation_midAnimation_screenshot() { compareTimeScreenshot(600, "circle_100") } @Test fun circleAnimation_animationDone_screenshot() { compareTimeScreenshot(1500, "circle_done") } private fun compareTimeScreenshot(timeMs: Long, goldenName: String) { // Start with a paused clock composeTestRule.mainClock.autoAdvance = false // Start the unit under test showAnimatedCircle() // Advance clock (keeping it paused) composeTestRule.mainClock.advanceTimeBy(timeMs) // Take screenshot and compare with golden image in androidTest/assets assertScreenshotMatchesGolden(goldenName, composeTestRule.onRoot()) } private fun showAnimatedCircle() { composeTestRule.setContent { RallyTheme { AnimatedCircle( modifier = Modifier.background(Color.White).size(320.dp), proportions = listOf(0.25f, 0.5f, 0.25f), colors = listOf(Color.Red, Color.DarkGray, Color.Black) ) } } } }
TestingCodelab/app/src/androidTest/java/com/example/compose/rally/AnimatingCircleTests.kt
3891046621
package app.k9mail.dev import com.fsck.k9.backend.BackendFactory import org.koin.core.module.Module import org.koin.core.scope.Scope fun Scope.developmentBackends() = emptyMap<String, BackendFactory>() fun Module.developmentModuleAdditions() = Unit
app/k9mail/src/release/java/app/k9mail/dev/ReleaseConfig.kt
2264941664
package com.sbg.rpg.packing.common.extensions import com.sbg.rpg.packing.common.ImageReadException import java.awt.image.BufferedImage import java.nio.file.Path import javax.imageio.ImageIO fun Path.readImage(): BufferedImage { try { /* * An image is not guaranteed to contain an alpha channel. * Therefore we explicitly convert any loaded common to type ARGB for further processing. */ return ImageIO.read(this.toFile()).toBufferedImage(BufferedImage.TYPE_INT_ARGB) } catch (e: Exception) { throw ImageReadException("Could not convert file to an image! Is this really an image?", e) } } fun Path.filenameWithoutExtension(): String { val filename = this.fileName.toString() val extensionStart = filename.lastIndexOf(".") return if (extensionStart == -1) { filename } else { filename.substring(0, extensionStart) } }
src/main/java/com/sbg/rpg/packing/common/extensions/PathExtensions.kt
2973896604
/* * Copyright 2017 Niek Haarman * * 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.nhaarman.expect fun fail(reason: String): Nothing = throw AssertionError(reason) fun fail(reason: String, message: (() -> Any?)? = null): Nothing { var m = reason message?.invoke()?.let { m = "$reason\n$it" } throw AssertionError(m) } fun fail(expected: Any?, actual: Any?, message: (() -> Any?)? = null): Nothing { val m = message?.invoke()?.let { "$it\n" } ?: "" throw AssertionError("${m}Expected: $expected but was: $actual\n") }
expect.kt/src/main/kotlin/com.nhaarman.expect/Fail.kt
1865327269
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package xyz.cardstock.cardstock.commands import org.kitteh.irc.client.library.element.Channel import org.kitteh.irc.client.library.element.User import org.kitteh.irc.client.library.event.channel.ChannelMessageEvent import org.kitteh.irc.client.library.event.helper.ActorEvent import xyz.cardstock.cardstock.Cardstock import xyz.cardstock.cardstock.games.Game import xyz.cardstock.cardstock.players.Player /** * A command to be used during a game in a channel. */ abstract class GameChannelCommand<P : Player, G : Game<P>>(val cardstock: Cardstock, val mapper: (Channel) -> G?) : BaseCommand() { override fun run(event: ActorEvent<User>, callInfo: CallInfo, arguments: List<String>) { if (event !is ChannelMessageEvent) return val game = this.mapper(event.channel) val player = game?.getPlayer(event.actor, false) if (game == null || player == null) { event.actor.sendNotice("You are not in a game.") return } this.run(event, callInfo, game, player, arguments) } /** * Performs the action that this command is supposed to perform. Called every time that this command is used. */ abstract fun run(event: ChannelMessageEvent, callInfo: CallInfo, game: G, player: P, arguments: List<String>) }
src/main/kotlin/xyz/cardstock/cardstock/commands/GameChannelCommand.kt
1416667720
@file:JsModule("@blueprintjs/core") package com.palantir.blueprintjs import org.w3c.dom.HTMLElement import org.w3c.dom.events.MouseEvent import react.PureComponent import react.RState import react.ReactElement /** * Interface for a clickable action, such as a button or menu item. * These props can be spready directly to a `<Button>` or `<MenuItem>` element. */ external interface IActionProps : IIntentProps, IProps { /** Whether this action is non-interactive. */ var disabled: Boolean? /** Name of a Blueprint UI icon (or an icon element) to render before the text. */ var icon: IconName? /** Click event handler. */ var onClick: ((event: MouseEvent) -> Unit)? /** Action text. Can be any single React renderable. */ var text: String? } external interface IButtonProps : IActionProps { // artificially added to allow title on button (should probably be on more general props) var title: String? /** * If set to `true`, the button will display in an active state. * This is equivalent to setting `className={Classes.ACTIVE}`. * @default false */ var active: Boolean? /** * Text alignment within button. By default, icons and text will be centered * within the button. Passing `"left"` or `"right"` will align the button * text to that side and push `icon` and `rightIcon` to either edge. Passing * `"center"` will center the text and icons together. * @default Alignment.CENTER */ var alignText: Alignment? /** A ref handler that receives the native HTML element backing this component. */ var elementRef: ((ref: HTMLElement?) -> Any)? /** Whether this button should expand to fill its container. */ var fill: Boolean? /** Whether this button should use large styles. */ var large: Boolean? /** * If set to `true`, the button will display a centered loading spinner instead of its contents. * The width of the button is not affected by the value of this prop. * @default false */ var loading: Boolean? /** Whether this button should use minimal styles. */ var minimal: Boolean? /** Whether this button should use outlined styles. */ var outlined: Boolean? /** Name of a Blueprint UI icon (or an icon element) to render after the text. */ var rightIcon: IconName? /** Whether this button should use small styles. */ var small: Boolean? /** * HTML `type` attribute of button. Accepted values are `"button"`, `"submit"`, and `"reset"`. * Note that this prop has no effect on `AnchorButton`; it only affects `Button`. * @default "button" */ var type: String? // "submit" | "reset" | "button"; } external interface IButtonState : RState { var isActive: Boolean } abstract external class AbstractButton : PureComponent<IButtonProps, IButtonState> external class Button : AbstractButton { override fun render(): ReactElement } external class AnchorButton : AbstractButton { override fun render(): ReactElement } external interface IButtonGroupProps : IProps { /** * Text alignment within button. By default, icons and text will be centered * within the button. Passing `"left"` or `"right"` will align the button * text to that side and push `icon` and `rightIcon` to either edge. Passing * `"center"` will center the text and icons together. */ var alignText: Alignment? /** * Whether the button group should take up the full width of its container. * @default false */ var fill: Boolean? /** * Whether the child buttons should appear with minimal styling. * @default false */ var minimal: Boolean? /** * Whether the child buttons should appear with large styling. * @default false */ var large: Boolean? /** * Whether the button group should appear with vertical styling. * @default false */ var vertical: Boolean? } external class ButtonGroup : PureComponent<IButtonGroupProps, RState> { override fun render(): ReactElement? }
sw-ui/src/main/kotlin/com/palantir/blueprintjs/BpButtons.kt
785706218
/* * The MIT License (MIT) * * Copyright (c) skrypton-api by waicool20 * * 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.waicool20.skrypton.enums /** * Represents a policy for cookie policy, see * [here](https://doc.qt.io/qt-5/qwebengineprofile.html#PersistentCookiesPolicy-enum) * for more information. */ enum class PersistentCookiesPolicy { NoPersistentCookies, AllowPersistentCookies, ForcePersistentCookies }
src/main/kotlin/com/waicool20/skrypton/enums/PersistentCookiesPolicy.kt
3928027642
/* * 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 import android.app.Service import android.content.Intent import android.os.Binder import android.os.IBinder import java.lang.ref.WeakReference import java.util.* class AccountUpdateService : Service() { private val binder = InfoBinder() private val runningRefresh = HashSet<Long>() private val refreshingStatusListeners = LinkedList<WeakReference<RefreshingStatusListener>>() override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent != null) { val action = intent.action when (action) { } } return Service.START_NOT_STICKY } /* BOUND SERVICE PART for communicating with the activities */ override fun onBind(intent: Intent): IBinder? { return binder } interface RefreshingStatusListener { fun onDavRefreshStatusChanged(id: Long, refreshing: Boolean) } inner class InfoBinder : Binder() { fun isRefreshing(id: Long): Boolean { return runningRefresh.contains(id) } fun addRefreshingStatusListener(listener: RefreshingStatusListener, callImmediate: Boolean) { refreshingStatusListeners.add(WeakReference(listener)) if (callImmediate) for (id in runningRefresh) listener.onDavRefreshStatusChanged(id, true) } fun removeRefreshingStatusListener(listener: RefreshingStatusListener) { val iterator = refreshingStatusListeners.iterator() while (iterator.hasNext()) { val item = iterator.next().get() if (listener == item) iterator.remove() } } } }
app/src/main/java/com/etesync/syncadapter/AccountUpdateService.kt
2521542320
package eu.kanade.tachiyomi.ui.category import android.support.design.widget.Snackbar import android.support.v7.app.AppCompatActivity import android.support.v7.view.ActionMode import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.* import com.jakewharton.rxbinding.view.clicks import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.SelectableAdapter import eu.davidea.flexibleadapter.helpers.UndoHelper import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.util.toast import kotlinx.android.synthetic.main.categories_controller.* /** * Controller to manage the categories for the users' library. */ class CategoryController : NucleusController<CategoryPresenter>(), ActionMode.Callback, FlexibleAdapter.OnItemClickListener, FlexibleAdapter.OnItemLongClickListener, CategoryAdapter.OnItemReleaseListener, CategoryCreateDialog.Listener, CategoryRenameDialog.Listener, UndoHelper.OnActionListener { /** * Object used to show ActionMode toolbar. */ private var actionMode: ActionMode? = null /** * Adapter containing category items. */ private var adapter: CategoryAdapter? = null /** * Undo helper used for restoring a deleted category. */ private var undoHelper: UndoHelper? = null /** * Creates the presenter for this controller. Not to be manually called. */ override fun createPresenter() = CategoryPresenter() /** * Returns the toolbar title to show when this controller is attached. */ override fun getTitle(): String? { return resources?.getString(R.string.action_edit_categories) } /** * Returns the view of this controller. * * @param inflater The layout inflater to create the view from XML. * @param container The parent view for this one. */ override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View { return inflater.inflate(R.layout.categories_controller, container, false) } /** * Called after view inflation. Used to initialize the view. * * @param view The view of this controller. */ override fun onViewCreated(view: View) { super.onViewCreated(view) adapter = CategoryAdapter(this@CategoryController) recycler.layoutManager = LinearLayoutManager(view.context) recycler.setHasFixedSize(true) recycler.adapter = adapter adapter?.isHandleDragEnabled = true adapter?.isPermanentDelete = false fab.clicks().subscribeUntilDestroy { CategoryCreateDialog(this@CategoryController).showDialog(router, null) } } /** * Called when the view is being destroyed. Used to release references and remove callbacks. * * @param view The view of this controller. */ override fun onDestroyView(view: View) { // Manually call callback to delete categories if required undoHelper?.onDeleteConfirmed(Snackbar.Callback.DISMISS_EVENT_MANUAL) undoHelper = null actionMode = null adapter = null super.onDestroyView(view) } /** * Called from the presenter when the categories are updated. * * @param categories The new list of categories to display. */ fun setCategories(categories: List<CategoryItem>) { actionMode?.finish() adapter?.updateDataSet(categories) if (categories.isNotEmpty()) { empty_view.hide() val selected = categories.filter { it.isSelected } if (selected.isNotEmpty()) { selected.forEach { onItemLongClick(categories.indexOf(it)) } } } else { empty_view.show(R.drawable.ic_shape_black_128dp, R.string.information_empty_category) } } /** * Called when action mode is first created. The menu supplied will be used to generate action * buttons for the action mode. * * @param mode ActionMode being created. * @param menu Menu used to populate action buttons. * @return true if the action mode should be created, false if entering this mode should be * aborted. */ override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean { // Inflate menu. mode.menuInflater.inflate(R.menu.category_selection, menu) // Enable adapter multi selection. adapter?.mode = SelectableAdapter.Mode.MULTI return true } /** * Called to refresh an action mode's action menu whenever it is invalidated. * * @param mode ActionMode being prepared. * @param menu Menu used to populate action buttons. * @return true if the menu or action mode was updated, false otherwise. */ override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean { val adapter = adapter ?: return false val count = adapter.selectedItemCount mode.title = resources?.getString(R.string.label_selected, count) // Show edit button only when one item is selected val editItem = mode.menu.findItem(R.id.action_edit) editItem.isVisible = count == 1 return true } /** * Called to report a user click on an action button. * * @param mode The current ActionMode. * @param item The item that was clicked. * @return true if this callback handled the event, false if the standard MenuItem invocation * should continue. */ override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean { val adapter = adapter ?: return false when (item.itemId) { R.id.action_delete -> { undoHelper = UndoHelper(adapter, this) undoHelper?.start(adapter.selectedPositions, view!!, R.string.snack_categories_deleted, R.string.action_undo, 3000) mode.finish() } R.id.action_edit -> { // Edit selected category if (adapter.selectedItemCount == 1) { val position = adapter.selectedPositions.first() val category = adapter.getItem(position)?.category if (category != null) { editCategory(category) } } } else -> return false } return true } /** * Called when an action mode is about to be exited and destroyed. * * @param mode The current ActionMode being destroyed. */ override fun onDestroyActionMode(mode: ActionMode) { // Reset adapter to single selection adapter?.mode = SelectableAdapter.Mode.IDLE adapter?.clearSelection() actionMode = null } /** * Called when an item in the list is clicked. * * @param position The position of the clicked item. * @return true if this click should enable selection mode. */ override fun onItemClick(position: Int): Boolean { // Check if action mode is initialized and selected item exist. if (actionMode != null && position != RecyclerView.NO_POSITION) { toggleSelection(position) return true } else { return false } } /** * Called when an item in the list is long clicked. * * @param position The position of the clicked item. */ override fun onItemLongClick(position: Int) { val activity = activity as? AppCompatActivity ?: return // Check if action mode is initialized. if (actionMode == null) { // Initialize action mode actionMode = activity.startSupportActionMode(this) } // Set item as selected toggleSelection(position) } /** * Toggle the selection state of an item. * If the item was the last one in the selection and is unselected, the ActionMode is finished. * * @param position The position of the item to toggle. */ private fun toggleSelection(position: Int) { val adapter = adapter ?: return //Mark the position selected adapter.toggleSelection(position) if (adapter.selectedItemCount == 0) { actionMode?.finish() } else { actionMode?.invalidate() } } /** * Called when an item is released from a drag. * * @param position The position of the released item. */ override fun onItemReleased(position: Int) { val adapter = adapter ?: return val categories = (0 until adapter.itemCount).mapNotNull { adapter.getItem(it)?.category } presenter.reorderCategories(categories) } /** * Called when the undo action is clicked in the snackbar. * * @param action The action performed. */ override fun onActionCanceled(action: Int, positions: MutableList<Int>?) { adapter?.restoreDeletedItems() undoHelper = null } /** * Called when the time to restore the items expires. * * @param action The action performed. * @param event The event that triggered the action */ override fun onActionConfirmed(action: Int, event: Int) { val adapter = adapter ?: return presenter.deleteCategories(adapter.deletedItems.map { it.category }) undoHelper = null } /** * Show a dialog to let the user change the category name. * * @param category The category to be edited. */ private fun editCategory(category: Category) { CategoryRenameDialog(this, category).showDialog(router) } /** * Renames the given category with the given name. * * @param category The category to rename. * @param name The new name of the category. */ override fun renameCategory(category: Category, name: String) { presenter.renameCategory(category, name) } /** * Creates a new category with the given name. * * @param name The name of the new category. */ override fun createCategory(name: String) { presenter.createCategory(name) } /** * Called from the presenter when a category with the given name already exists. */ fun onCategoryExistsError() { activity?.toast(R.string.error_category_exists) } }
app/src/main/java/eu/kanade/tachiyomi/ui/category/CategoryController.kt
1610631344
package com.timepath.hl2 import com.timepath.Logger import com.timepath.hex.HexEditor import com.timepath.hl2.io.demo.HL2DEM import com.timepath.hl2.io.demo.Message import com.timepath.hl2.io.demo.MessageType import com.timepath.hl2.io.demo.Packet import com.timepath.plaf.x.filechooser.BaseFileChooser import com.timepath.plaf.x.filechooser.NativeFileChooser import com.timepath.steam.SteamUtils import com.timepath.with import org.jdesktop.swingx.JXFrame import org.jdesktop.swingx.JXTable import org.jdesktop.swingx.JXTree import org.jdesktop.swingx.decorator.AbstractHighlighter import org.jdesktop.swingx.decorator.ComponentAdapter import org.jetbrains.kotlin.utils.singletonOrEmptyList import java.awt.* import java.awt.event.ActionListener import java.beans.PropertyVetoException import java.io.File import java.io.IOException import java.util.ArrayList import java.util.concurrent.ExecutionException import java.util.logging.Level import javax.swing.* import javax.swing.event.ListSelectionListener import javax.swing.event.TreeSelectionListener import javax.swing.table.AbstractTableModel import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel import kotlin.platform.platformStatic public class DEMTest() : JPanel() { protected val menu: JMenuBar protected val hex: HexEditor protected val tabs: JTabbedPane protected val table: JXTable protected val tree: JXTree protected val tableModel: MessageModel init { tableModel = MessageModel() table = JXTable() with { setAutoCreateRowSorter(true) setColumnControlVisible(true) setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED) setModel(tableModel) setSelectionMode(ListSelectionModel.SINGLE_SELECTION) } tree = JXTree() with { setModel(DefaultTreeModel(DefaultMutableTreeNode("root"))) setRootVisible(false) setShowsRootHandles(true) } tabs = JTabbedPane() with { setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)) addTab("Hierarchy", JScrollPane(tree)) } hex = HexEditor() table.addHighlighter(object : AbstractHighlighter() { override fun doHighlight(component: Component, adapter: ComponentAdapter): Component { if (adapter.row >= 0 && tableModel.messages.size() > 0 && adapter.row < tableModel.messages.size()) { val msg = tableModel.messages[table.convertRowIndexToModel(adapter.row)] component.setBackground(when { adapter.isSelected() -> component.getBackground() else -> when { msg.incomplete -> Color.ORANGE else -> when (msg.type) { MessageType.Signon, MessageType.Packet -> Color.CYAN MessageType.UserCmd -> Color.GREEN MessageType.ConsoleCmd -> Color.PINK else -> Color.WHITE } } }) } return component } }) table.getSelectionModel().addListSelectionListener(ListSelectionListener { val row = table.getSelectedRow() if (row == -1) return@ListSelectionListener val frame = tableModel.messages[table.convertRowIndexToModel(row)] hex.setData(frame.data) val root = DefaultMutableTreeNode(frame) recurse(frame.meta, root) tree.setModel(DefaultTreeModel(DefaultMutableTreeNode() with { add(root) })) run { var i = -1 while (++i < tree.getRowCount()) { // Expand all val node = tree.getPathForRow(i).getLastPathComponent() as DefaultMutableTreeNode if (node.getLevel() < 3) tree.expandRow(i) } } }) tree.getSelectionModel().addTreeSelectionListener(TreeSelectionListener { val selectionPath = tree.getSelectionPath() ?: return@TreeSelectionListener val lastPathComponent = selectionPath.getLastPathComponent() val o = (lastPathComponent as DefaultMutableTreeNode).getUserObject() if (o is Packet) { try { val offsetBytes = o.offset / 8 val offsetBits = o.offset % 8 hex.seek((offsetBytes - (offsetBytes % 16)).toLong()) // Start of row hex.caretLocation = (offsetBytes.toLong()) hex.bitShift = (offsetBits) hex.update() } catch (e: PropertyVetoException) { e.printStackTrace() } } }) menu = JMenuBar() with { add(JMenu("File") with { setMnemonic('F') add(JMenuItem("Open") with { addActionListener(ActionListener { open() }) }) add(JMenuItem("Dump commands") with { addActionListener(ActionListener { showCommands() }) }) }) } setLayout(BorderLayout()) add(JSplitPane() with { setResizeWeight(1.0) setContinuousLayout(true) setOneTouchExpandable(true) setLeftComponent(JScrollPane(table)) setRightComponent(JSplitPane() with { setOrientation(JSplitPane.VERTICAL_SPLIT) setResizeWeight(1.0) setContinuousLayout(true) setOneTouchExpandable(true) setTopComponent(tabs) setRightComponent(hex) }) }) } protected fun recurse(iter: List<*>, parent: DefaultMutableTreeNode) { for (e in iter) { if (e !is Pair<*, *>) continue val v = e.second when (v) { is List<*> -> recurse(v, DefaultMutableTreeNode(e.first) with { parent.add(this) }) else -> parent.add(DefaultMutableTreeNode(e)) } } } protected fun open() { try { val fs = NativeFileChooser() .setTitle("Open DEM") .setDirectory(File(SteamUtils.getSteamApps(), "common/Team Fortress 2/tf/.")) .addFilter(BaseFileChooser.ExtensionFilter("Demo files", "dem")) .choose() ?: return object : SwingWorker<HL2DEM, Message>() { val listEvt = DefaultListModel<Pair<*, *>>() val listMsg = DefaultListModel<Pair<*, *>>() var incomplete = 0 override fun doInBackground(): HL2DEM { tableModel.messages.clear() val demo = HL2DEM.load(fs[0]) val frames = demo.frames // TODO: Stream publish(*frames.toTypedArray()) return demo } override fun process(chunks: List<Message>) { for (msg in chunks) { if (msg.incomplete) incomplete++ tableModel.messages.add(msg) when (msg.type) { MessageType.Packet, MessageType.Signon -> for ((k, v) in msg.meta) { if (k !is Packet) continue if (v !is List<*>) continue for (e in v) { if (e !is Pair<*, *>) continue when (k.type) { Packet.svc_GameEvent -> listEvt Packet.svc_UserMessage -> listMsg else -> null }?.addElement(e) } } } } tableModel.fireTableDataChanged() // FIXME } override fun done() { val demo = try { get() } catch (ignored: InterruptedException) { return } catch (e: ExecutionException) { LOG.log(Level.SEVERE, { null }, e) return } LOG.info({ "Total incomplete messages: ${incomplete} / ${demo.frames.size()}" }) while (tabs.getTabCount() > 1) tabs.remove(1) // Remove previous events and messages tabs.add("Events", JScrollPane(JList(listEvt)) with { getVerticalScrollBar().setUnitIncrement(16) }) tabs.add("Messages", JScrollPane(JList(listMsg)) with { getVerticalScrollBar().setUnitIncrement(16) }) table.setModel(tableModel) } }.execute() } catch (e: IOException) { LOG.log(Level.SEVERE, { null }, e) } } protected fun showCommands() { val sb = StringBuilder() for (m in tableModel.messages) { if (m.type != MessageType.ConsoleCmd) continue for (p in m.meta) { sb.append('\n').append(p.singletonOrEmptyList()) } } JOptionPane.showMessageDialog(this, JScrollPane(JTextArea(if (sb.length() > 0) sb.substring(1) else "")) with { setPreferredSize(Dimension(500, 500)) } ) } protected inner class MessageModel : AbstractTableModel() { val messages: MutableList<Message> = ArrayList() override fun getRowCount() = messages.size() protected val columns: Array<String> = arrayOf("Tick", "Type", "Size") protected val types: Array<Class<*>> = arrayOf(javaClass<Int>(), javaClass<Enum<*>>(), javaClass<Int>()) override fun getColumnCount() = columns.size() override fun getColumnName(columnIndex: Int) = columns[columnIndex] override fun getColumnClass(columnIndex: Int) = types[columnIndex] override fun isCellEditable(rowIndex: Int, columnIndex: Int) = false override fun getValueAt(rowIndex: Int, columnIndex: Int): Any? { if (messages.isEmpty()) return null val m = messages[rowIndex] when (columnIndex) { 0 -> return m.tick 1 -> return m.type 2 -> return m.data?.capacity() } return null } } companion object { private val LOG = Logger() public platformStatic fun main(args: Array<String>) { EventQueue.invokeLater { JXFrame("netdecode") with { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) val demTest = DEMTest() setContentPane(demTest) setJMenuBar(demTest.menu) pack() setLocationRelativeTo(null) setVisible(true) } } } } }
src/main/kotlin/com/timepath/hl2/DEMTest.kt
2680593869
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hil.psi.impl import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.util.text.StringUtil import com.intellij.psi.PsiElementVisitor import org.intellij.plugins.hcl.psi.HCLElement import org.intellij.plugins.hil.psi.ILElementVisitor import org.intellij.plugins.hil.psi.ILExpression abstract class ILExpressionBase(node: ASTNode) : ASTWrapperPsiElement(node), ILExpression { override fun accept(visitor: PsiElementVisitor) { if (visitor is ILElementVisitor) { visitor.visitILExpression(this) } else { visitor.visitElement(this) } } open fun getTypeClass(): Class<out Any>? { return null } override fun toString(): String { val name = this.javaClass.simpleName val trimmed = StringUtil.trimEnd(name, "Impl") if (trimmed.startsWith("ILBinary")) return "ILBinaryExpression" if ("ILLiteralExpression" == trimmed || "ILParameterListExpression" == trimmed) return StringUtil.trimEnd(trimmed, "Expression") return trimmed } } fun ILExpression.getHCLHost(): HCLElement? { val host = InjectedLanguageManager.getInstance(this.project).getInjectionHost(this) return if (host is HCLElement) host else null }
src/kotlin/org/intellij/plugins/hil/psi/impl/ILExpressionBase.kt
748752381
package host.serenity.serenity.event.player import host.serenity.synapse.util.Cancellable class PushOutOfBlocks : Cancellable()
src/main/java/host/serenity/serenity/event/player/PushOutOfBlocks.kt
2837866126
package ee.design.swagger import ee.common.ext.* import ee.design.DslTypes import ee.design.Module import ee.lang.* import ee.lang.gen.kt.toDslDoc import io.swagger.models.* import io.swagger.models.parameters.Parameter import io.swagger.models.parameters.RefParameter import io.swagger.models.parameters.SerializableParameter import io.swagger.models.properties.* import io.swagger.parser.SwaggerParser import org.slf4j.LoggerFactory import java.nio.file.Path import java.util.* private val log = LoggerFactory.getLogger("SwaggerToDesign") class SwaggerToDesign( private val pathsToEntityNames: MutableMap<String, String> = mutableMapOf(), private val namesToTypeName: MutableMap<String, String> = mutableMapOf(), private val ignoreTypes: MutableSet<String> = mutableSetOf()) { fun toDslTypes(swaggerFile: Path): DslTypes = SwaggerToDesignExecutor(swaggerFile, namesToTypeName, ignoreTypes).toDslTypes() } private class SwaggerToDesignExecutor( swaggerFile: Path, private val namesToTypeName: MutableMap<String, String> = mutableMapOf(), private val ignoreTypes: MutableSet<String> = mutableSetOf()) { private val log = LoggerFactory.getLogger(javaClass) private val primitiveTypes = mapOf("integer" to "n.Int", "string" to "n.String") private val typeToPrimitive = mutableMapOf<String, String>() private val swagger = SwaggerParser().read(swaggerFile.toString()) private val typesToFill = TreeMap<String, String>() fun toDslTypes(): DslTypes { extractTypeDefsFromPrimitiveAliases().forEach { it.value.toDslValues(it.key.toDslTypeName()) } return DslTypes(name = swagger.info?.title ?: "", desc = "", types = typesToFill) } private fun extractTypeDefsFromPrimitiveAliases(): Map<String, io.swagger.models.Model> { val ret = mutableMapOf<String, io.swagger.models.Model>() swagger.definitions?.entries?.forEach { (defName, def) -> if (!ignoreTypes.contains(defName)) { if (def is ModelImpl && def.isPrimitive()) { typeToPrimitive[defName] = primitiveTypes[def.type]!! typeToPrimitive[defName.toDslTypeName()] = primitiveTypes[def.type]!! } else { ret[defName] = def } } else { log.debug("ignore type ") } } return ret } private fun Model.isPrimitive() = this is ModelImpl && (enum == null || enum.isEmpty()) && primitiveTypes.containsKey(type) private fun Swagger.toModule(): Module { return Module { name("Shared") definitions?.forEach { defName, def -> values(def.toValues(defName)) } }.init() } private fun Map<String, Property>?.toDslProperties(): String { return (this != null).ifElse( { this!!.entries.joinToString(nL, nL) { it.value.toDslProp(it.key) } }, { "" }) } private fun io.swagger.models.properties.Property.toDslProp(name: String): String { val nameCamelCase = name.toCamelCase() return " val $nameCamelCase = prop { ${(name != nameCamelCase) .then { "externalName(\"$name\")." }}${toDslInit(nameCamelCase)} }" } private fun Property.toDslPropValue(name: String, suffix: String = "", prefix: String = ""): String { return ((this is StringProperty && default.isNullOrEmpty().not())).ifElse({ "${suffix}value(${(this as StringProperty).enum.isNotEmpty().ifElse({ "$name.${default.toUnderscoredUpperCase()}" }, { "\"$name.$default\"" })})$prefix" }, { "" }) } private fun io.swagger.models.Model.toDslValues(name: String) { if (this is ComposedModel) { typesToFill[name] = """ object ${name.toDslTypeName()} : Values({ ${ interfaces.joinSurroundIfNotEmptyToString(",", "superUnit(", ")") { it.simpleRef.toDslTypeName() }}${description.toDslDoc()} }) {${allOf.filterNot { interfaces.contains(it) }.joinToString("") { it.properties.toDslProperties() }} }""" } else if (this is ArrayModel) { val prop = items if (prop is ObjectProperty) { val typeName = prop.toDslTypeName() typesToFill[typeName] = prop.toDslType(typeName) } else { log.info("not supported yet {} {}", this, prop) } } else if (this is ModelImpl && this.enum != null && this.enum.isNotEmpty()) { typesToFill[name] = """ object $name : EnumType(${description.toDslDoc("{", "}")}) {${ enum.joinToString(nL, nL) { val externalName = it.toString() val literalName = externalName.toUnderscoredUpperCase() val init = if (literalName != externalName) " { externalName(\"$externalName\") }" else "()" " val $literalName = lit$init" }} }""" } else { typesToFill[name] = """ object ${name.toDslTypeName()} : Values(${ description.toDslDoc("{ ", " }")}) {${ properties.toDslProperties()} }""" } } private fun io.swagger.models.properties.StringProperty.toDslEnum(name: String): String { return """ object $name : EnumType(${description.toDslDoc("{", "}")}) {${ enum.joinToString(nL, nL) { val externalName = it.toString() val literalName = externalName.toUnderscoredUpperCase() val init = if (literalName != externalName) " { externalName(\"$externalName\") }" else "()" " val $literalName = lit$init" }} }""" } private fun io.swagger.models.properties.ObjectProperty.toDslType(name: String): String { return """ object $name : Values(${description.toDslDoc("{", "}")}) {${properties.toDslProperties()} }""" } private fun io.swagger.models.properties.Property.toDslTypeName(name: String): String { val prop = this return when (prop) { is ArrayProperty -> { "n.List.GT(${prop.items.toDslTypeName(name)})" } is BinaryProperty -> { "n.Bytes" } is BooleanProperty -> { "n.Boolean" } is ByteArrayProperty -> { "n.Bytes" } is DateProperty -> { "n.Date" } is DateTimeProperty -> { "n.Date" } is DecimalProperty -> { "n.Double" } is DoubleProperty -> { "n.Double" } is EmailProperty -> { "n.String" } is FileProperty -> { "n.File" } is FloatProperty -> { "n.Float" } is IntegerProperty -> { "n.Int" } is BaseIntegerProperty -> { "n.Int" } is LongProperty -> { "n.Long" } is MapProperty -> { "n.Map" } is ObjectProperty -> { val typeName = prop.toDslTypeName() if (!typesToFill.containsKey(typeName)) { typesToFill[typeName] = prop.toDslType(typeName) } typeName } is PasswordProperty -> { "n.String" } is UntypedProperty -> { "n.String" } is UUIDProperty -> { "n.String" } is RefProperty -> { prop.simpleRef.toDslTypeName() } is StringProperty -> { if (prop.enum != null && prop.enum.isNotEmpty()) { val typeName = name.toDslTypeName() if (!typesToFill.containsKey(typeName)) { typesToFill[typeName] = prop.toDslEnum(typeName) } typeName } else { "n.String" } } else -> { "" } } } private fun Parameter.toDslTypeName(name: String): String { val prop = this return when (prop) { is SerializableParameter -> { primitiveTypes.getOrDefault(prop.type, "n.String") } is RefParameter -> { swagger.parameters[prop.simpleRef]!!.toDslTypeName(name) } else -> { log.warn("can't find type for {}, use n.String", prop) "n.String" } } } private fun ObjectProperty.toDslTypeName(): String = properties.keys.joinToString( "") { it.capitalize() }.toDslTypeName() private fun String.toDslTypeName(): String { return typeToPrimitive[this] ?: namesToTypeName.getOrPut(this) { toCamelCase().capitalize() } } private fun io.swagger.models.properties.Property.toDslInit(name: String): String { return if (this is RefProperty) { if (swagger.parameters != null && swagger.parameters.containsKey(simpleRef)) { swagger.parameters[simpleRef]!!.toDslInit(name) } else if (swagger.definitions != null && swagger.definitions.containsKey(simpleRef)) { toDslInitDirect(name) } else { toDslInitDirect(name) } } else { toDslInitDirect(name) } } private fun Parameter.toDslInit(name: String): String { val typeName = toDslTypeName(name) return "type($typeName)${required.not().then { ".nullable()" }}${description.toDslDoc(".")}" } private fun io.swagger.models.properties.Property.toDslInitDirect(name: String): String { val typeName = toDslTypeName(name) return "type($typeName)${required.not().then { ".nullable()" }}${(this is PasswordProperty) .then { ".hidden()" }}${toDslPropValue(typeName, ".")}${description.toDslDoc(".")}" } private fun io.swagger.models.Model.toValues(name: String): Values { val model = this return Values { name(name).doc(model.description ?: "") model.properties?.forEach { propName, p -> prop { name(propName).type(p.type.toType()).doc(p.description ?: "") } } }.init() } private fun String?.toType(): TypeI<*> { return if (this == null) { n.String } else { log.info("type: {}", this) n.String } } }
ee-design_swagger/src/main/kotlin/ee/design/swagger/SwaggerToDesign.kt
3338116879
package icurves.graph import javafx.geometry.Point2D import javafx.scene.shape.Path /** * * * @author Almas Baimagambetov ([email protected]) */ data class GraphCycle<V, E>(val nodes: List<V>, val edges: List<E>) { lateinit var path: Path lateinit var smoothingData: MutableList<Point2D> fun length() = nodes.size /** * Computes length - nodes that lie in the same basic region */ fun lengthUnique() = nodesUnique().size fun nodesUnique() = nodes.map { it as EulerDualNode }.distinctBy { it.zone.toString() } // fun contains(node: V): Boolean { // for (n in nodes) { // if (n.toString() == node.toString()) { // return true // } // } // // return false // } // fun contains(zones: List<AbstractBasicRegion>): Boolean { // val mappedNodes = nodes.map { it.zone.abstractZone } // // return mappedNodes.containsAll(zones) // } override fun toString(): String { return nodes.joinToString() } }
src/main/kotlin/icurves/graph/GraphCycle.kt
1551436128
/* * Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.vladsch.smart import org.junit.Assert.assertEquals import org.junit.Test class SmartReversedCharSequenceTest { val string = """0123456789 0123456789 0123456789 0123456789 """ val chars = string.toCharArray() @Test @Throws(Exception::class) fun test_basic1() { val charSeq = SmartReversedCharSequence(chars); assertEquals(string.reversed(), charSeq.toString()) } @Test @Throws(Exception::class) fun test_basic2() { val charSeq = SmartReversedCharSequence(chars, 0, string.length); assertEquals(string.reversed(), charSeq.toString()) assertEquals(0, charSeq.trackedSourceLocation(charSeq.length - 1).offset) assertEquals(1, charSeq.trackedSourceLocation(charSeq.length - 2).offset) assertEquals(charSeq.length - 2, charSeq.trackedSourceLocation(1).offset) assertEquals(charSeq.length - 1, charSeq.trackedSourceLocation(0).offset) } @Test @Throws(Exception::class) fun test_basic3() { val charSeq = SmartReversedCharSequence(chars, 0, string.length); val charSeq2 = charSeq.subSequence(0, string.length) assertEquals(charSeq, charSeq2) } @Test @Throws(Exception::class) fun test_basic4() { val charSeq = SmartReversedCharSequence(chars, 0, string.length); val charSeq2 = charSeq.subSequence(11, string.length) assertEquals(string.substring(11).reversed(), charSeq2.toString()) } @Test @Throws(Exception::class) fun test_basic5() { val charSeq = SmartReversedCharSequence(chars, 0, string.length); val charSeq1 = charSeq.subSequence(0, 11) val charSeq2 = charSeq.subSequence(11, 22) assertEquals(string.substring(0, 11).reversed(), charSeq1.toString()) assertEquals(string.substring(11, 22).reversed(), charSeq2.toString()) } @Test @Throws(Exception::class) fun test_basic6() { val charSeq = SmartReversedCharSequence(chars, 0, string.length); val charSeq1 = charSeq.subSequence(0, 11) val charSeq2 = charSeq.subSequence(11, 22) val charSeq3 = charSeq.subSequence(22, 33) assertEquals(string.substring(0, 11).reversed(), charSeq1.toString()) assertEquals(string.substring(11, 22).reversed(), charSeq2.toString()) assertEquals(string.substring(22, 33).reversed(), charSeq3.toString()) // these are contiguous // assertEquals(true, charSeq3.splicedWith(charSeq2) != null) // assertEquals(true, charSeq2.splicedWith(charSeq1) != null) // assertEquals(charSeq.subSequence(0, 33), charSeq3.splicedWith(charSeq2.splicedWith(charSeq1))) } }
test/src/com/vladsch/smart/SmartReversedCharSequenceTest.kt
2928684983
package com.guoxiaoxing.cloud.music.ui.activity import android.app.Activity import android.app.ActivityManager import android.content.Intent import android.os.Build import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.support.v4.view.ViewPager import android.support.v7.widget.Toolbar import android.view.Gravity import android.view.KeyEvent import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.ImageView import android.widget.Toast import com.guoxiaoxing.cloud.music.R import com.guoxiaoxing.cloud.music.adapter.MenuItemAdapter import com.guoxiaoxing.cloud.music.handler.HandlerUtil import com.guoxiaoxing.cloud.music.magicasakura.utils.ThemeUtils import com.guoxiaoxing.cloud.music.ui.BaseActivity import com.guoxiaoxing.cloud.music.ui.fragment.BitSetFragment import com.guoxiaoxing.cloud.music.ui.fragment.MineFragment import com.guoxiaoxing.cloud.music.ui.fragment.TimingFragment import com.guoxiaoxing.cloud.music.ui.fragment.MusicLibraryFragment import com.guoxiaoxing.cloud.music.service.MusicPlayer import com.guoxiaoxing.cloud.music.uitl.ThemeHelper import com.guoxiaoxing.cloud.music.widget.CustomViewPager import com.guoxiaoxing.cloud.music.widget.SplashScreen import com.guoxiaoxing.cloud.music.widget.dialog.CardPickerDialog import kotlinx.android.synthetic.main.activity_main.* import java.util.ArrayList class MainActivity : BaseActivity(), CardPickerDialog.ClickListener { private val tabs = ArrayList<ImageView?>() private var time: Long = 0 var splashScreen: SplashScreen? = null override fun onCreate(savedInstanceState: Bundle?) { splashScreen = SplashScreen(this) splashScreen?.show(R.drawable.art_login_bg, SplashScreen.SLIDE_LEFT) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) window.setBackgroundDrawableResource(R.color.background_material_light_1) setToolBar() setViewPager() setupDrawer() HandlerUtil.getInstance(this).postDelayed({ splashScreen?.removeSplashScreen() }, 3000) } private fun setToolBar() { val toolbar = findViewById(R.id.activity_main_toolbar) as Toolbar setSupportActionBar(toolbar) val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) actionBar?.setHomeAsUpIndicator(R.drawable.ic_menu) actionBar?.title = "" } private fun setViewPager() { tabs.add(activity_main_bar_music_library) tabs.add(activity_main_bar_mine) val customViewPager = findViewById(R.id.activity_main_viewpager) as CustomViewPager val mineFragment = MineFragment() val musicLibraryFragment = MusicLibraryFragment() val customViewPagerAdapter = CustomViewPagerAdapter(supportFragmentManager) customViewPagerAdapter.addFragment(musicLibraryFragment) customViewPagerAdapter.addFragment(mineFragment) customViewPager.adapter = customViewPagerAdapter customViewPager.currentItem = 1 activity_main_bar_mine.isSelected = true customViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { switchTabs(position) } override fun onPageScrollStateChanged(state: Int) { } }) activity_main_bar_music_library.setOnClickListener { customViewPager.currentItem = 0 } activity_main_bar_mine.setOnClickListener { customViewPager.currentItem = 1 } activity_main_bar_search.setOnClickListener { val intent = Intent(this@MainActivity, NetSearchWordsActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NO_ANIMATION [email protected](intent) } } private fun setupDrawer() { val inflater = LayoutInflater.from(this) activity_main_id_lv_left_menu.addHeaderView(inflater.inflate(R.layout.nav_header_main, activity_main_id_lv_left_menu, false)) activity_main_id_lv_left_menu.adapter = MenuItemAdapter(this) activity_main_id_lv_left_menu.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> when (position) { 1 -> activity_main_fd.closeDrawers() 2 -> { val dialog = CardPickerDialog() dialog.setClickListener(this@MainActivity) dialog.show(supportFragmentManager, "theme") activity_main_fd.closeDrawers() } 3 -> { val fragment3 = TimingFragment() fragment3.show(supportFragmentManager, "timing") activity_main_fd.closeDrawers() } 4 -> { val bfragment = BitSetFragment() bfragment.show(supportFragmentManager, "bitset") activity_main_fd.closeDrawers() } 5 -> { if (MusicPlayer.isPlaying()) { MusicPlayer.playOrPause() } unbindService() finish() activity_main_fd.closeDrawers() } } } } private fun switchTabs(position: Int) { for (i in tabs.indices) { tabs.get(i)?.isSelected = position == i } } override fun onConfirm(currentTheme: Int) { if (ThemeHelper.getTheme(this@MainActivity) != currentTheme) { ThemeHelper.setTheme(this@MainActivity, currentTheme) ThemeUtils.refreshUI(this@MainActivity, object : ThemeUtils.ExtraRefreshable { override fun refreshGlobal(activity: Activity) { //for global setting, just do once if (Build.VERSION.SDK_INT >= 21) { val context = this@MainActivity val taskDescription = ActivityManager.TaskDescription(null, null, ThemeUtils.getThemeAttrColor(context, android.R.attr.colorPrimary)) setTaskDescription(taskDescription) window.statusBarColor = ThemeUtils.getColorById(context, R.color.theme_color_primary) } } override fun refreshSpecificView(view: View) {} } ) } changeTheme() } internal class CustomViewPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { private val mFragments = ArrayList<Fragment>() fun addFragment(fragment: Fragment) { mFragments.add(fragment) } override fun getItem(position: Int): Fragment { return mFragments[position] } override fun getCount(): Int { return mFragments.size } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home //Menu icon -> { activity_main_fd.openDrawer(Gravity.LEFT) return true } else -> return super.onOptionsItemSelected(item) } } override fun onDestroy() { super.onDestroy() splashScreen?.removeSplashScreen() } override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { if (System.currentTimeMillis() - time > 1000) { Toast.makeText(this, "再按一次返回桌面", Toast.LENGTH_SHORT).show() time = System.currentTimeMillis() } else { val intent = Intent(Intent.ACTION_MAIN) intent.addCategory(Intent.CATEGORY_HOME) startActivity(intent) } return true } else { return super.onKeyDown(keyCode, event) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) val fragments = supportFragmentManager.fragments if (fragments != null) { for (fragment in fragments) { fragment?.onRequestPermissionsResult(requestCode, permissions, grantResults) } } } override fun onBackPressed() { super.onBackPressed() } }
cloud/src/main/java/com/guoxiaoxing/cloud/music/ui/activity/MainActivity.kt
3489215133
/* * Copyright (C) 2016 Piotr Wittchen * * 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.pwittchen.reactivenetwork.kotlinapp import android.app.Activity import android.os.Bundle import android.util.Log import com.github.pwittchen.reactivenetwork.library.rx2.ReactiveNetwork import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_main.connectivity_status import kotlinx.android.synthetic.main.activity_main.internet_status class MainActivity : Activity() { private var connectivityDisposable: Disposable? = null private var internetDisposable: Disposable? = null companion object { private val TAG = "ReactiveNetwork" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onResume() { super.onResume() connectivityDisposable = ReactiveNetwork.observeNetworkConnectivity(applicationContext) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { connectivity -> Log.d(TAG, connectivity.toString()) val state = connectivity.state() val name = connectivity.typeName() connectivity_status.text = String.format("state: %s, typeName: %s", state, name) } internetDisposable = ReactiveNetwork.observeInternetConnectivity() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { isConnectedToInternet -> internet_status.text = isConnectedToInternet.toString() } } override fun onPause() { super.onPause() safelyDispose(connectivityDisposable) safelyDispose(internetDisposable) } private fun safelyDispose(disposable: Disposable?) { if (disposable != null && !disposable.isDisposed) { disposable.dispose() } } }
app-kotlin/src/main/kotlin/com/github/pwittchen/reactivenetwork/kotlinapp/MainActivity.kt
1377394019
/* * Copyright (c) 2019 David Aguiar Gonzalez * * 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 gc.david.dfm.ui.fragment import android.os.Bundle import android.transition.Fade import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import butterknife.BindView import butterknife.ButterKnife import com.google.android.material.snackbar.Snackbar import gc.david.dfm.DFMApplication import gc.david.dfm.R import gc.david.dfm.adapter.OpenSourceLibraryAdapter import gc.david.dfm.dagger.DaggerOpenSourceComponent import gc.david.dfm.dagger.OpenSourceModule import gc.david.dfm.dagger.RootModule import gc.david.dfm.logger.DFMLogger import gc.david.dfm.opensource.domain.OpenSourceUseCase import gc.david.dfm.opensource.presentation.OpenSource import gc.david.dfm.opensource.presentation.OpenSourcePresenter import gc.david.dfm.opensource.presentation.mapper.OpenSourceLibraryMapper import gc.david.dfm.opensource.presentation.model.OpenSourceLibraryModel import gc.david.dfm.ui.animation.DetailsTransition import javax.inject.Inject /** * Created by david on 24.01.17. */ class OpenSourceMasterFragment : Fragment(), OpenSource.View { @BindView(R.id.opensourcelibrary_fragment_recyclerview) lateinit var recyclerView: RecyclerView @BindView(R.id.opensourcelibrary_fragment_progressbar) lateinit var progressbar: ProgressBar @Inject lateinit var openSourceUseCase: OpenSourceUseCase @Inject lateinit var openSourceLibraryMapper: OpenSourceLibraryMapper private lateinit var presenter: OpenSource.Presenter private lateinit var adapter: OpenSourceLibraryAdapter private val listener = object : OnItemClickListener { override fun onItemClick(openSourceLibraryModel: OpenSourceLibraryModel, viewHolder: OpenSourceLibraryAdapter.OpenSourceLibraryViewHolder) { val openSourceDetailFragment = OpenSourceDetailFragment().apply { val changeBoundsTransition = DetailsTransition() val fadeTransition = Fade() [email protected] = fadeTransition sharedElementEnterTransition = changeBoundsTransition enterTransition = fadeTransition sharedElementReturnTransition = changeBoundsTransition arguments = bundleOf(OpenSourceDetailFragment.LIBRARY_KEY to openSourceLibraryModel) } requireActivity().supportFragmentManager .beginTransaction() .addSharedElement(viewHolder.tvName, getString(R.string.transition_opensourcelibrary_name)) .addSharedElement(viewHolder.tvShortLicense, getString(R.string.transition_opensourcelibrary_description)) .replace(R.id.about_activity_container_framelayout, openSourceDetailFragment) .addToBackStack(null) .commit() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) DaggerOpenSourceComponent.builder() .rootModule(RootModule(requireActivity().application as DFMApplication)) .openSourceModule(OpenSourceModule()) .build() .inject(this) adapter = OpenSourceLibraryAdapter(listener) presenter = OpenSourcePresenter(this, openSourceUseCase, openSourceLibraryMapper) presenter.start() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_opensourcelibrary_master, container, false) ButterKnife.bind(this, view) return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { if (adapter.itemCount != 0) { hideLoading() setupList() } } override fun setPresenter(presenter: OpenSource.Presenter) { this.presenter = presenter } override fun showLoading() { if (view != null) { // Workaround: at this point, onCreateView could not have been executed progressbar.isVisible = true recyclerView.isVisible = false } } override fun hideLoading() { progressbar.isVisible = false recyclerView.isVisible = true } override fun add(openSourceLibraryModelList: List<OpenSourceLibraryModel>) { adapter.add(openSourceLibraryModelList) } override fun showError(errorMessage: String) { DFMLogger.logException(Exception(errorMessage)) Snackbar.make(recyclerView, R.string.opensourcelibrary_error_message, Snackbar.LENGTH_LONG).show() } override fun setupList() { recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.adapter = adapter } interface OnItemClickListener { fun onItemClick(openSourceLibraryModel: OpenSourceLibraryModel, item: OpenSourceLibraryAdapter.OpenSourceLibraryViewHolder) } }
app/src/main/java/gc/david/dfm/ui/fragment/OpenSourceMasterFragment.kt
2184016536
@file:Suppress("UNCHECKED_CAST") package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_8_R3 import com.github.shynixn.petblocks.api.PetBlocksApi import com.github.shynixn.petblocks.api.bukkit.event.PetBlocksAIPreChangeEvent import com.github.shynixn.petblocks.api.business.proxy.EntityPetProxy import com.github.shynixn.petblocks.api.business.proxy.NMSPetProxy import com.github.shynixn.petblocks.api.business.proxy.PetProxy import com.github.shynixn.petblocks.api.business.service.AIService import com.github.shynixn.petblocks.api.business.service.ConfigurationService import com.github.shynixn.petblocks.api.business.service.LoggingService import com.github.shynixn.petblocks.api.persistence.entity.* import com.github.shynixn.petblocks.core.logic.business.extension.hasChanged import com.github.shynixn.petblocks.core.logic.business.extension.relativeFront import com.github.shynixn.petblocks.core.logic.persistence.entity.PositionEntity import net.minecraft.server.v1_8_R3.* import org.bukkit.Bukkit import org.bukkit.Location import org.bukkit.craftbukkit.v1_8_R3.CraftWorld import org.bukkit.entity.ArmorStand import org.bukkit.entity.LivingEntity import org.bukkit.entity.Player import org.bukkit.event.entity.CreatureSpawnEvent import org.bukkit.util.Vector import java.lang.reflect.Field /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class NMSPetArmorstand(owner: Player, val petMeta: PetMeta) : EntityArmorStand((owner.location.world as CraftWorld).handle), NMSPetProxy { private var internalProxy: PetProxy? = null private var jumpingField: Field = EntityLiving::class.java.getDeclaredField("aY") private var internalHitBox: EntityInsentient? = null private val aiService = PetBlocksApi.resolve(AIService::class.java) private val flyCanHitWalls = PetBlocksApi.resolve(ConfigurationService::class.java) .findValue<Boolean>("global-configuration.fly-wall-colision") private var flyHasTakenOffGround = false private var flyIsOnGround: Boolean = false private var flyHasHitFloor: Boolean = false private var flyWallCollisionVector: Vector? = null /** * Proxy handler. */ override val proxy: PetProxy get() = internalProxy!! /** * Initializes the nms design. */ init { jumpingField.isAccessible = true val location = owner.location val mcWorld = (location.world as CraftWorld).handle val position = PositionEntity() position.x = location.x position.y = location.y position.z = location.z position.yaw = location.yaw.toDouble() position.pitch = location.pitch.toDouble() position.worldName = location.world.name position.relativeFront(3.0) this.setPositionRotation(position.x, position.y, position.z, location.yaw, location.pitch) mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM) internalProxy = Class.forName("com.github.shynixn.petblocks.bukkit.logic.business.proxy.PetProxyImpl") .getDeclaredConstructor(PetMeta::class.java, ArmorStand::class.java, Player::class.java) .newInstance(petMeta, this.bukkitEntity, owner) as PetProxy petMeta.propertyTracker.onPropertyChanged(PetMeta::aiGoals, true) applyNBTTagForArmorstand() } /** * Spawns a new hitbox */ private fun spawnHitBox() { val shouldDeleteHitBox = shouldDeleteHitBox() if (shouldDeleteHitBox && internalHitBox != null) { (internalHitBox!!.bukkitEntity as EntityPetProxy).deleteFromWorld() internalHitBox = null proxy.changeHitBox(internalHitBox) } val player = proxy.getPlayer<Player>() this.applyNBTTagForArmorstand() val hasRidingAi = petMeta.aiGoals.count { a -> a is AIGroundRiding || a is AIFlyRiding } > 0 if (hasRidingAi) { val armorstand = proxy.getHeadArmorstand<ArmorStand>() if (armorstand.passenger != player) { armorstand.velocity = Vector(0, 1, 0) armorstand.passenger = player } return } else { if (player.passenger != null) { player.eject() } } val aiWearing = this.petMeta.aiGoals.firstOrNull { a -> a is AIWearing } if (aiWearing != null) { this.applyNBTTagForArmorstand() val armorstand = proxy.getHeadArmorstand<ArmorStand>() if (player.passenger != armorstand) { player.passenger = armorstand } return } val flyingAi = petMeta.aiGoals.firstOrNull { a -> a is AIFlying } if (flyingAi != null) { if (internalHitBox == null) { internalHitBox = NMSPetBat(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetBat).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) return } val hoppingAi = petMeta.aiGoals.firstOrNull { a -> a is AIHopping } if (hoppingAi != null) { if (internalHitBox == null) { internalHitBox = NMSPetRabbit(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetRabbit).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) return } if (internalHitBox == null) { internalHitBox = NMSPetVillager(this, getBukkitEntity().location) proxy.changeHitBox(internalHitBox!!.bukkitEntity as LivingEntity) } val aiGoals = aiService.convertPetAiBasesToPathfinders(proxy, petMeta.aiGoals) (internalHitBox as NMSPetVillager).applyPathfinders(aiGoals) applyNBTTagToHitBox(internalHitBox!!) } /** * Disable setting slots. */ override fun setEquipment(i: Int, itemstack: ItemStack?) { } /** * Sets the slot securely. */ fun setSecureSlot(enumitemslot: Int, itemstack: ItemStack?) { super.setEquipment(enumitemslot, itemstack) } /** * Entity tick. */ override fun doTick() { super.doTick() try { proxy.run() if (dead) { return } if (this.internalHitBox != null) { val location = internalHitBox!!.bukkitEntity.location val aiGoal = petMeta.aiGoals.lastOrNull { p -> p is AIMovement } ?: return var y = location.y + (aiGoal as AIMovement).movementYOffSet if (this.isSmall) { y += 0.6 } if (y > -100) { this.setPositionRotation(location.x, y, location.z, location.yaw, location.pitch) this.motX = this.internalHitBox!!.motX this.motY = this.internalHitBox!!.motY this.motZ = this.internalHitBox!!.motZ } } if (proxy.teleportTarget != null) { val location = proxy.teleportTarget!! as Location if (this.internalHitBox != null) { this.internalHitBox!!.setPositionRotation( location.x, location.y, location.z, location.yaw, location.pitch ) } this.setPositionRotation(location.x, location.y, location.z, location.yaw, location.pitch) proxy.teleportTarget = null } if (PetMeta::aiGoals.hasChanged(petMeta)) { val event = PetBlocksAIPreChangeEvent(proxy.getPlayer(), proxy) Bukkit.getPluginManager().callEvent(event) if (event.isCancelled) { return } spawnHitBox() proxy.aiGoals = null } } catch (e: Exception) { PetBlocksApi.resolve(LoggingService::class.java).error("Failed to execute tick.", e) } } /** * Overrides the moving of the pet design. */ override fun move(d0: Double, d1: Double, d2: Double) { super.move(d0, d1, d2) if (passenger == null || passenger !is EntityHuman) { return } val groundAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding } val airAi = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding } var offSet = when { groundAi != null -> (groundAi as AIGroundRiding).ridingYOffSet airAi != null -> (airAi as AIFlyRiding).ridingYOffSet else -> 0.0 } if (this.isSmall) { offSet += 0.6 } val axisBoundingBox = this.boundingBox this.locX = (axisBoundingBox.a + axisBoundingBox.d) / 2.0 this.locY = axisBoundingBox.b + offSet this.locZ = (axisBoundingBox.c + axisBoundingBox.f) / 2.0 } /** * Gets the bukkit entity. */ override fun getBukkitEntity(): CraftPetArmorstand { if (this.bukkitEntity == null) { this.bukkitEntity = CraftPetArmorstand(this.world.server, this) } return this.bukkitEntity as CraftPetArmorstand } /** * Riding function. */ override fun g(sidemot: Float, formot: Float) { if (passenger == null || passenger !is EntityHuman) { flyHasTakenOffGround = false return } val human = passenger as EntityHuman val aiFlyRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIFlyRiding } if (aiFlyRiding != null) { rideInAir(human, aiFlyRiding as AIFlyRiding) return } val aiGroundRiding = this.petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding } if (aiGroundRiding != null) { rideOnGround(human, aiGroundRiding as AIGroundRiding) return } } /** * Handles the riding in air. */ private fun rideInAir(human: EntityHuman, ai: AIFlyRiding) { val sideMot: Float = human.aZ * 0.5f val forMot: Float = human.ba this.yaw = human.yaw this.lastYaw = this.yaw this.pitch = human.pitch * 0.5f this.setYawPitch(this.yaw, this.pitch) this.aK = this.yaw this.aI = this.aK val flyingVector = Vector() val flyingLocation = Location(this.world.world, this.locX, this.locY, this.locZ) if (sideMot < 0.0f) { flyingLocation.yaw = human.yaw - 90 flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5)) } else if (sideMot > 0.0f) { flyingLocation.yaw = human.yaw + 90 flyingVector.add(flyingLocation.direction.normalize().multiply(-0.5)) } if (forMot < 0.0f) { flyingLocation.yaw = human.yaw flyingVector.add(flyingLocation.direction.normalize().multiply(0.5)) } else if (forMot > 0.0f) { flyingLocation.yaw = human.yaw flyingVector.add(flyingLocation.direction.normalize().multiply(0.5)) } if (!flyHasTakenOffGround) { flyHasTakenOffGround = true flyingVector.setY(1f) } if (this.isPassengerJumping()) { flyingVector.setY(0.5f) this.flyIsOnGround = true this.flyHasHitFloor = false } else if (this.flyIsOnGround) { flyingVector.setY(-0.2f) } if (this.flyHasHitFloor) { flyingVector.setY(0) flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed)) this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z) } else { flyingLocation.add(flyingVector.multiply(2.25).multiply(ai.ridingSpeed)) this.setPosition(flyingLocation.x, flyingLocation.y, flyingLocation.z) } val vec3d = Vec3D(this.locX, this.locY, this.locZ) val vec3d1 = Vec3D(this.locX + this.motX, this.locY + this.motY, this.locZ + this.motZ) val movingObjectPosition = this.world.rayTrace(vec3d, vec3d1) if (movingObjectPosition == null) { this.flyWallCollisionVector = flyingLocation.toVector() } else if (this.flyWallCollisionVector != null && flyCanHitWalls) { this.setPosition( this.flyWallCollisionVector!!.x, this.flyWallCollisionVector!!.y, this.flyWallCollisionVector!!.z ) } } /** * Handles the riding on ground. */ private fun rideOnGround(human: EntityHuman, ai: AIGroundRiding) { val sideMot: Float = human.aZ * 0.5f var forMot: Float = human.ba this.yaw = human.yaw this.lastYaw = this.yaw this.pitch = human.pitch * 0.5f this.setYawPitch(this.yaw, this.pitch) this.aK = this.yaw this.aI = this.aK if (forMot <= 0.0f) { forMot *= 0.25f } if (this.onGround && this.isPassengerJumping()) { this.motY = 0.5 } this.S = ai.climbingHeight.toFloat() this.aM = this.bI() * 0.1f if (!this.world.isClientSide) { this.k(0.35f) super.g(sideMot * ai.ridingSpeed.toFloat(), forMot * ai.ridingSpeed.toFloat()) } this.aA = this.aB val d0 = this.locX - this.lastX val d1 = this.locZ - this.lastZ var f4 = MathHelper.sqrt(d0 * d0 + d1 * d1) * 4.0f if (f4 > 1.0f) { f4 = 1.0f } this.aB += (f4 - this.aB) * 0.4f this.aC += this.aB } /** * Applies the entity NBT to the hitbox. */ private fun applyNBTTagToHitBox(hitBox: EntityInsentient) { val compound = NBTTagCompound() hitBox.b(compound) applyAIEntityNbt( compound, this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.hitBoxNbt }.toList() ) hitBox.a(compound) // CustomNameVisible does not working via NBT Tags. hitBox.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1 } /** * Applies the entity NBT to the armorstand. */ private fun applyNBTTagForArmorstand() { val compound = NBTTagCompound() this.b(compound) applyAIEntityNbt( compound, this.petMeta.aiGoals.asSequence().filterIsInstance<AIEntityNbt>().map { a -> a.armorStandNbt }.toList() ) this.a(compound) // CustomNameVisible does not working via NBT Tags. this.customNameVisible = compound.hasKey("CustomNameVisible") && compound.getInt("CustomNameVisible") == 1 } /** * Applies the raw NbtData to the given target. */ private fun applyAIEntityNbt(target: NBTTagCompound, rawNbtDatas: List<String>) { val compoundMapField = NBTTagCompound::class.java.getDeclaredField("map") compoundMapField.isAccessible = true val rootCompoundMap = compoundMapField.get(target) as MutableMap<Any?, Any?> for (rawNbtData in rawNbtDatas) { if (rawNbtData.isEmpty()) { continue } val parsedCompound = try { MojangsonParser.parse(rawNbtData) } catch (e: Exception) { throw RuntimeException("NBT Tag '$rawNbtData' cannot be parsed.", e) } val parsedCompoundMap = compoundMapField.get(parsedCompound) as Map<*, *> for (key in parsedCompoundMap.keys) { rootCompoundMap[key] = parsedCompoundMap[key] } } } /** * Should the hitbox of the armorstand be deleted. */ private fun shouldDeleteHitBox(): Boolean { val hasEmptyHitBoxAi = petMeta.aiGoals.firstOrNull { a -> a is AIGroundRiding || a is AIFlyRiding || a is AIWearing } != null if (hasEmptyHitBoxAi) { return true } if (internalHitBox != null) { if (internalHitBox is NMSPetVillager && petMeta.aiGoals.firstOrNull { a -> a is AIWalking } == null) { return true } else if (internalHitBox is NMSPetRabbit && petMeta.aiGoals.firstOrNull { a -> a is AIHopping } == null) { return true } else if (internalHitBox is NMSPetBat && petMeta.aiGoals.firstOrNull { a -> a is AIFlying } == null) { return true } } return false } /** * Gets if a passenger of the pet is jumping. */ private fun isPassengerJumping(): Boolean { if (passenger == null) { return false } return jumpingField.getBoolean(this.passenger) } }
petblocks-bukkit-plugin/petblocks-bukkit-nms-108R3/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_8_R3/NMSPetArmorstand.kt
38925824
package block.itemblock import com.teamwizardry.librarianlib.common.base.block.BlockMod import com.teamwizardry.librarianlib.common.base.block.ItemModBlock /** * Created by cout970 on 30/06/2016. */ class ItemBlockElectricPole(block: BlockMod) : ItemModBlock(block) { //hmmm... todo /*override fun getBlocksToPlace(world: World, pos: BlockPos, facing: EnumFacing, player: EntityPlayer, stack: ItemStack): List<BlockPos> = listOf(pos, pos.offset(EnumFacing.UP, 1), pos.offset(EnumFacing.UP, 2), pos.offset(EnumFacing.UP, 3), pos.offset(EnumFacing.UP, 4))*/ }
ignore/test/block/itemblock/ItemBlockElectricPole.kt
1817956090
package org.botellier.serializer import org.botellier.value.* import org.junit.Assert import org.junit.Test class ByteSerializerTest { @Test fun renderInt() { val value = IntValue(1) Assert.assertArrayEquals(value.toByteArray(), ":1\r\n".toByteArray()) } @Test fun renderFloat() { val value = FloatValue(2.0) Assert.assertArrayEquals(value.toByteArray(), ";2.0\r\n".toByteArray()) } @Test fun renderString() { val value = StringValue("Hello, World!") Assert.assertArrayEquals(value.toByteArray(), "$13\r\nHello, World!\r\n".toByteArray()) } @Test fun renderRaw() { val bytes = "Hello, World!".toByteArray() val value = RawValue(bytes) Assert.assertArrayEquals(value.toByteArray(), "$13\r\nHello, World!\r\n".toByteArray()) } @Test fun renderEmptyString() { val value = StringValue("") Assert.assertArrayEquals(value.toByteArray(), "$0\r\n\r\n".toByteArray()) } @Test fun renderList() { val value = ListValue(listOf(IntValue(1), FloatValue(2.0), StringValue("three"))) Assert.assertArrayEquals( value.toByteArray(), "*3\r\n:1\r\n;2.0\r\n$5\r\nthree\r\n".toByteArray() ) } @Test fun renderEmptyList() { val value = ListValue() Assert.assertArrayEquals(value.toByteArray(), "*0\r\n".toByteArray()) } @Test fun renderSet() { val value = SetValue(listOf("one", "two", "three").toSet()) Assert.assertArrayEquals( value.toByteArray(), "&3\r\n$3\r\none\r\n$3\r\ntwo\r\n$5\r\nthree\r\n".toByteArray() ) } @Test fun renderEmptySet() { val value = SetValue() Assert.assertArrayEquals(value.toByteArray(), "&0\r\n".toByteArray()) } @Test fun renderMap() { val value = MapValue(mapOf("one" to IntValue(1), "two" to FloatValue(2.0), "three" to StringValue("three"))) Assert.assertArrayEquals( value.toByteArray(), "#3\r\n$3\r\none\r\n:1\r\n$3\r\ntwo\r\n;2.0\r\n$5\r\nthree\r\n$5\r\nthree\r\n".toByteArray() ) } @Test fun renderEmptyMap() { val value = MapValue() Assert.assertArrayEquals(value.toByteArray(), "#0\r\n".toByteArray()) } }
src/test/kotlin/org/botellier/serializer/ByteSerializer.kt
2577485891
package icons import com.intellij.openapi.util.IconLoader import com.intellij.ui.AnimatedIcon import javax.swing.Icon // FYI: Icons are defined in C# files in the backend. When being shown in the frontend, only the icon ID is passed to // the frontend, and IJ will look it up in resources/resharper. The name of the enclosing C# class is stripped of any // trailing "Icons" or "ThemedIcons" and used as the folder name. The icon is named after the inner class. IJ will // automatically add `_dark` to the basename of the SVG file if in Darcula. // Note that IJ has a different palette and colour scheme to ReSharper. This means that the front end svg files might // not be the same as the backed C# files... // We need to be in the icons root package so we can use this class from plugin.xml. We also need to use @JvmField so // that the kotlin value is visible as a JVM field via reflection class UnityIcons { class Icons { companion object { val UnityLogo = IconLoader.getIcon("/resharper/Logo/Unity.svg", UnityIcons::class.java) } } class Toolbar { companion object { val Toolbar = IconLoader.getIcon("/resharper/Toolbar/UnityToolbar.svg", UnityIcons::class.java) val ToolbarConnected = IconLoader.getIcon("/resharper/Toolbar/UnityToolbarConnected.svg", UnityIcons::class.java) val ToolbarDisconnected = IconLoader.getIcon("/resharper/Toolbar/UnityToolbarDisconnected.svg", UnityIcons::class.java) } } class Common { companion object { val UnityEditMode = IconLoader.getIcon("/unityIcons/common/unityEditMode.svg", UnityIcons::class.java) val UnityPlayMode = IconLoader.getIcon("/unityIcons/common/unityPlayMode.svg", UnityIcons::class.java) val UnityToolWindow = IconLoader.getIcon("/unityIcons/common/unityToolWindow.svg", UnityIcons::class.java) } } class LogView { companion object { val FilterBeforePlay = IconLoader.getIcon("/unityIcons/logView/filterBeforePlay.svg", UnityIcons::class.java) val FilterBeforeRefresh = IconLoader.getIcon("/unityIcons/logView/filterBeforeRefresh.svg", UnityIcons::class.java) } } class FileTypes { companion object { val ShaderLab = IconLoader.getIcon("/resharper/ShaderFileType/FileShader.svg", UnityIcons::class.java) val Cg = ShaderLab val AsmDef: Icon = ReSharperIcons.PsiJavaScript.Json val AsmRef: Icon = ReSharperIcons.PsiJavaScript.Json val UnityYaml = IconLoader.getIcon("/resharper/YamlFileType/FileYaml.svg", UnityIcons::class.java) val UnityScene = IconLoader.getIcon("/resharper/UnityFileType/FileUnity.svg", UnityIcons::class.java) val Meta = IconLoader.getIcon("/resharper/UnityFileType/FileUnityMeta.svg", UnityIcons::class.java) val Asset = IconLoader.getIcon("/resharper/UnityFileType/FileUnityAsset.svg", UnityIcons::class.java) val Prefab = IconLoader.getIcon("/resharper/UnityFileType/FileUnityPrefab.svg", UnityIcons::class.java) val Controller = IconLoader.getIcon("/resharper/UnityFileType/FileAnimatorController.svg", UnityIcons::class.java) val Anim = IconLoader.getIcon("/resharper/UnityFileType/FileAnimationClip.svg", UnityIcons::class.java) // These are front end only file types val Uss = IconLoader.getIcon("/unityIcons/fileTypes/uss.svg", UnityIcons::class.java) val Uxml = IconLoader.getIcon("/unityIcons/fileTypes/uxml.svg", UnityIcons::class.java) } } class Debugger { // Field and file names deliberately match the AllIcons.Debugger icons. // Pausepoints are by definition "no suspend". Where the default breakpoint icon set includes a "no_suspend" // variant, the same file name is used. Otherwise, the default name is drawn as "no_suspend". companion object { val Db_dep_line_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_dep_line_pausepoint.svg", UnityIcons::class.java) val Db_disabled_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_disabled_pausepoint.svg", UnityIcons::class.java) val Db_invalid_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_invalid_pausepoint.svg", UnityIcons::class.java) val Db_muted_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_muted_pausepoint.svg", UnityIcons::class.java) val Db_muted_disabled_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_muted_disabled_pausepoint.svg", UnityIcons::class.java) val Db_no_suspend_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_no_suspend_pausepoint.svg", UnityIcons::class.java) val Db_set_pausepoint = Db_no_suspend_pausepoint val Db_verified_no_suspend_pausepoint = IconLoader.getIcon("/unityIcons/debugger/db_verified_no_suspend_pausepoint.svg", UnityIcons::class.java) val Db_verified_pausepoint = Db_verified_no_suspend_pausepoint } } class Explorer { companion object { val AssetsRoot = IconLoader.getIcon("/unityIcons/Explorer/UnityAssets.svg", UnityIcons::class.java) val PackagesRoot = IconLoader.getIcon("/resharper/UnityObjectType/UnityPackages.svg", UnityIcons::class.java) val ReferencesRoot: Icon = ReSharperIcons.Common.CompositeElement val ReadOnlyPackagesRoot = IconLoader.getIcon("/unityIcons/Explorer/FolderReadOnly.svg", UnityIcons::class.java) val DependenciesRoot = IconLoader.getIcon("/unityIcons/Explorer/FolderDependencies.svg", UnityIcons::class.java) val BuiltInPackagesRoot = IconLoader.getIcon("/unityIcons/Explorer/FolderModules.svg", UnityIcons::class.java) val BuiltInPackage = IconLoader.getIcon("/unityIcons/Explorer/UnityModule.svg", UnityIcons::class.java) val ReferencedPackage = IconLoader.getIcon("/resharper/UnityFileType/FolderPackageReferenced.svg", UnityIcons::class.java) val EmbeddedPackage = IconLoader.getIcon("/unityIcons/Explorer/FolderPackageEmbedded.svg", UnityIcons::class.java) val LocalPackage = IconLoader.getIcon("/unityIcons/Explorer/FolderPackageLocal.svg", UnityIcons::class.java) val LocalTarballPackage = LocalPackage val GitPackage = IconLoader.getIcon("/unityIcons/Explorer/FolderGit.svg", UnityIcons::class.java) val UnknownPackage = IconLoader.getIcon("/unityIcons/Explorer/UnityPackageUnresolved.svg", UnityIcons::class.java) val PackageDependency = IconLoader.getIcon("/unityIcons/Explorer/UnityPackageDependency.svg", UnityIcons::class.java) val Reference: Icon = ReSharperIcons.ProjectModel.Assembly val AsmdefFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderAssetsAlt.svg", UnityIcons::class.java) val AssetsFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderAssets.svg", UnityIcons::class.java) val EditorDefaultResourcesFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderEditorResources.svg", UnityIcons::class.java) val EditorFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderEditor.svg", UnityIcons::class.java) val GizmosFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderGizmos.svg", UnityIcons::class.java) val PluginsFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderPlugins.svg", UnityIcons::class.java) val ResourcesFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderResources.svg", UnityIcons::class.java) val StreamingAssetsFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderStreamingAssets.svg", UnityIcons::class.java) val UnloadedFolder = IconLoader.getIcon("/unityIcons/Explorer/FolderUnloaded.svg", UnityIcons::class.java) } } class Actions { companion object { val UnityActionsGroup = Icons.UnityLogo @JvmField val StartUnity = Icons.UnityLogo @JvmField val Execute = IconLoader.getIcon("/unityIcons/actions/execute.svg", UnityIcons::class.java) @JvmField val Pause = IconLoader.getIcon("/unityIcons/actions/pause.svg", UnityIcons::class.java) @JvmField val Step = IconLoader.getIcon("/unityIcons/actions/step.svg", UnityIcons::class.java) val FilterEditModeMessages = Common.UnityEditMode val FilterPlayModeMessages = Common.UnityPlayMode @JvmField val OpenEditorLog = FilterEditModeMessages @JvmField val OpenPlayerLog = FilterPlayModeMessages @JvmField val AttachToUnity = IconLoader.getIcon("/unityIcons/actions/attachToUnityProcess.svg", UnityIcons::class.java) @JvmField val RefreshInUnity = IconLoader.getIcon("/unityIcons/actions/refreshInUnity.svg", UnityIcons::class.java) } } class RunConfigurations { companion object { val AttachToUnityParentConfiguration = Icons.UnityLogo val AttachAndDebug = Common.UnityEditMode val AttachDebugAndPlay = Common.UnityPlayMode val UnityExe = Common.UnityPlayMode } } class Ide { companion object { val Warning = IconLoader.getIcon("/unityIcons/ide/warning.svg", UnityIcons::class.java) val Info = IconLoader.getIcon("/unityIcons/ide/info.svg", UnityIcons::class.java) val Error = IconLoader.getIcon("/unityIcons/ide/error.svg", UnityIcons::class.java) } } class ToolWindows { companion object { val UnityLog = Common.UnityToolWindow val UnityExplorer = Common.UnityToolWindow } } }
rider/src/main/kotlin/icons/UnityIcons.kt
155771189
package com.sys1yagi.goatreader import android.app.Application import com.activeandroid.ActiveAndroid import com.sys1yagi.goatreader.tools.Logger import com.sys1yagi.goatreader.tools.Seeds class GoatReaderApplication : Application() { override fun onCreate() { super<Application>.onCreate() init() } override fun onTerminate() { terminate() } fun init() { Logger.d("GoatReaderApplication", "init") ActiveAndroid.initialize(this) Seeds.initDb() } fun terminate() { ActiveAndroid.dispose() } }
app/src/main/kotlin/com/sys1yagi/goatreader/GoatReaderApplication.kt
1548608282
package org.gradle.kotlin.dsl.resolver import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest import org.junit.Test class SourceDistributionResolverIntegrationTest : AbstractKotlinIntegrationTest() { @Test fun `can download source distribution`() { withBuildScript(""" val sourceDirs = ${SourceDistributionResolver::class.qualifiedName}(project).run { sourceDirs() } require(sourceDirs.isNotEmpty()) { "Expected source directories but got none" } """) build() } }
subprojects/kotlin-dsl/src/integTest/kotlin/org/gradle/kotlin/dsl/resolver/SourceDistributionResolverIntegrationTest.kt
1184320234
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions class MoveTypeConstraintToWhereClauseIntentionTest : RsIntentionTestBase(MoveTypeConstraintToWhereClauseIntention()) { fun `test function with return`() = doAvailableTest( """ fn foo<T: Send,/*caret*/ F: Sync>(t: T, f: F) -> i32 { 0 } """, """ fn foo<T, F>(t: T, f: F) -> i32 where T: Send, F: Sync/*caret*/ { 0 } """ ) fun `test lifetimes and traits`() = doAvailableTest( """ fn foo<'a, 'b: 'a, T: Send,/*caret*/ F: Sync>(t: &'a T, f: &'b F) { } """, """ fn foo<'a, 'b, T, F>(t: &'a T, f: &'b F) where 'b: 'a, T: Send, F: Sync/*caret*/ { } """ ) fun `test multiple bounds`() = doAvailableTest( """ fn foo<T: /*caret*/Send + Sync>(t: T, f: F) { } """, """ fn foo<T>(t: T, f: F) where T: Send + Sync/*caret*/ { } """ ) fun `test multiple lifetimes`() = doAvailableTest( """ fn foo<'a, /*caret*/'b: 'a>(t: &'a i32, f: &'b i32) { } """, """ fn foo<'a, 'b>(t: &'a i32, f: &'b i32) where 'b: 'a/*caret*/ { } """ ) fun `test multiple traits`() = doAvailableTest( """ fn foo<T: Send,/*caret*/ F: Sync>(t: T, f: F) { } """, """ fn foo<T, F>(t: T, f: F) where T: Send, F: Sync/*caret*/ { } """ ) fun `test type item element`() = doAvailableTest( """ type O<T: /*caret*/Copy> = Option<T>; """, """ type O<T> where T: Copy/*caret*/ = Option<T>; """ ) fun `test impl item element`() = doAvailableTest( """ impl<T: /*caret*/Copy> Foo<T> {} """, """ impl<T> Foo<T> where T: Copy/*caret*/ {} """ ) fun `test trait item element`() = doAvailableTest( """ trait Foo<T:/*caret*/ Copy> {} """, """ trait Foo<T> where T: Copy/*caret*/ {} """ ) fun `test struct item element`() = doAvailableTest( """ struct Foo<T:/*caret*/ Copy> { x: T } """, """ struct Foo<T> where T: Copy/*caret*/ { x: T } """ ) fun `test tuple struct item element`() = doAvailableTest( """ struct Foo<T:/*caret*/ Copy>(T); """, """ struct Foo<T>(T) where T: Copy/*caret*/; """ ) fun `test enum item element`() = doAvailableTest( """ enum Foo<T:/*caret*/ Copy> { X(T) } """, """ enum Foo<T> where T: Copy/*caret*/ { X(T) } """ ) fun `test partial where clause exists`() = doAvailableTest(""" impl<Fut, Req, Func:/*caret*/ Fn(Req) -> Fut, Resp, Err> Service for ServiceFn<Func> where Fut: IntoFuture<Item=Resp, Error=Err>, { """, """ impl<Fut, Req, Func, Resp, Err> Service for ServiceFn<Func> where Fut: IntoFuture<Item=Resp, Error=Err>, Func: Fn(Req) -> Fut { """) fun `test partial where clause exists adds comma`() = doAvailableTest(""" struct Spam<Foo, Bar: /*caret*/Future> where Foo: Iterator { } """, """ struct Spam<Foo, Bar> where Foo: Iterator, Bar: Future { } """) fun `test no lifetime bounds`() = doUnavailableTest(""" fn foo<'a, /*caret*/'b>(t: &'a i32, f: &'b i32) { } """) fun `test no trait bounds`() = doUnavailableTest(""" fn foo<T, /*caret*/F>(t: T, f: F) { } """) }
src/test/kotlin/org/rust/ide/intentions/MoveTypeConstraintToWhereClauseIntentionTest.kt
3945433225
package com.inverse.unofficial.proxertv.base.client.interceptors import okhttp3.HttpUrl import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response import org.mozilla.javascript.Context /** * Interceptor that tries to handle the CloudFlare js challenge */ class CloudFlareInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response? { // always set the user agent val request = chain.request().newBuilder() .header("User-Agent", USER_AGENT) .build() val response = chain.proceed(request) if (response.code() == 503 && "cloudflare-nginx" == response.header("Server")) { val body = response.body().string() val operationPattern = Regex("setTimeout\\(function\\(\\)\\{\\s+(var s,t,o,p,b,r,e,a,k,i,n,g,f.+?\\r?\\n[\\s\\S]+?a\\.value =.+?)\\r?\\n") val passPattern = Regex("name=\"pass\" value=\"(.+?)\"") val challengePattern = Regex("name=\"jschl_vc\" value=\"(\\w+)\"") val rawOperation = operationPattern.find(body)?.groupValues?.get(1) val challenge = challengePattern.find(body)?.groupValues?.get(1) val challengePass = passPattern.find(body)?.groupValues?.get(1) if (rawOperation != null && challenge != null && challengePass != null) { val js = rawOperation.replace(Regex("a\\.value = (parseInt\\(.+?\\)).+"), "$1") .replace(Regex("\\s{3,}[a-z](?: = |\\.).+"), "") .replace("\n", "") // init js engine val rhino = Context.enter() rhino.optimizationLevel = -1 val scope = rhino.initStandardObjects() val result = (rhino.evaluateString(scope, js, "CloudFlare JS Challenge", 1, null) as Double).toInt() val requestUrl = response.request().url() val answer = (result + requestUrl.host().length).toString() val url = HttpUrl.Builder() .scheme(requestUrl.scheme()) .host(requestUrl.host()) .addPathSegment("/cdn-cgi/l/chk_jschl") .addQueryParameter("jschl_vc", challenge) .addQueryParameter("pass", challengePass) .addQueryParameter("jschl_answer", answer) .build() val challengeRequest = Request.Builder().get() .url(url) .header("Referer", requestUrl.toString()) .header("User-Agent", USER_AGENT) .build() // javascript waits 4 seconds until it proceeds Thread.sleep(4500) return chain.proceed(challengeRequest) } } return response } companion object { private const val USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0" } }
app/src/main/java/com/inverse/unofficial/proxertv/base/client/interceptors/CloudFlareInterceptor.kt
1423580355
package com.ff14.chousei.domain.model import javax.persistence.Entity import javax.persistence.Column import javax.persistence.Id import javax.persistence.GeneratedValue import javax.persistence.GenerationType import java.util.Date import javax.persistence.OneToMany; import javax.persistence.Table import org.springframework.security.core.GrantedAuthority import org.springframework.security.core.userdetails.UserDetails /* * UserテーブルのEntity. * @param id 主キー * @param title 書籍名 * @param subTitle 書籍の副題 ない場合はnull * @param leadingSentence リード文 * @param url リンク先URLパス */ @Entity @Table(name = "user") data class User( @Id @GeneratedValue(strategy = GenerationType.AUTO) var id: Long = 0, @Column(nullable = false) var name: String = "", @Column(nullable = false) var pass: String = "", @OneToMany(mappedBy = "user") @Column val charcters: List<Character>? = null, @Column(nullable = false, updatable = false) val createTime: Date? = null, @Column(nullable = false) val imagePath: String = "", @Column(nullable = false) val twitterId: String = "" ) : UserDetails { override fun getAuthorities(): MutableCollection<out GrantedAuthority>? { return null } override fun getUsername(): String? { return this.name } override fun getPassword(): String? { return this.pass } override fun isAccountNonExpired(): Boolean { return true } override fun isAccountNonLocked(): Boolean { return true } override fun isCredentialsNonExpired(): Boolean { return true } override fun isEnabled(): Boolean { return true } }
src/main/kotlin/com/ff14/chousei/domain/model/User.kt
1084553163
/* * Copyright 2018 Allan Wang * * 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.pitchedapps.frost.utils import com.pitchedapps.frost.facebook.FACEBOOK_COM import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue import org.junit.Test /** Created by Allan Wang on 2017-11-15. */ class UrlTests { val GOOGLE = "https://www.google.ca" @Test fun independence() { mapOf( GOOGLE to true, FACEBOOK_COM to true, "#!/photos/viewer/?photoset_token=pcb.1234" to false, "#test-id" to false, "#" to false, "#!" to false, "#!/" to false, "#!/events/permalink/going/?event_id=" to false, "/this/is/valid" to true, "#!/facebook/segment" to true ) .forEach { (url, valid) -> assertEquals( valid, url.isIndependent, "Independence test failed for $url; should be $valid" ) } } @Test fun isFacebook() { assertFalse(GOOGLE.isFacebookUrl, "google") assertTrue(FACEBOOK_COM.isFacebookUrl, "facebook") } @Test fun queryEncoding() { assertEquals("%23foo", "#foo".urlEncode()) } }
app/src/test/kotlin/com/pitchedapps/frost/utils/UrlTests.kt
2864796970
package com.automation.remarks.kirk.test import com.automation.remarks.kirk.core.WebDriverFactory import com.automation.remarks.kirk.ext.isAlive import me.tatarka.assertk.assertions.isEqualTo import org.testng.annotations.Test /** * Created by sepi on 8/11/2017. */ class ExtensionsTest : BaseTest() { @Test fun testCanVerifyDriverInNotAliveAfterClose() { val driver = WebDriverFactory().getDriver() driver.quit() assertThat(driver.isAlive()).isEqualTo(false) } }
kirk-core/src/test/kotlin/com/automation/remarks/kirk/test/ExtensionsTest.kt
3298597341
object Versions { const val targetSdk = 33 // https://developer.android.com/jetpack/androidx/releases/biometric const val andxBiometric = "1.1.0" // https://mvnrepository.com/artifact/org.apache.commons/commons-text // Updates blocked due to javax.script dependency const val apacheCommonsText = "1.4" // https://github.com/brianwernick/ExoMedia/releases const val exoMedia = "4.3.0" // https://github.com/jhy/jsoup/releases const val jsoup = "1.15.3" // https://square.github.io/okhttp/changelog/ const val okhttp = "4.10.0" // https://developer.android.com/jetpack/androidx/releases/room const val room = "2.4.3" // http://robolectric.org/getting-started/ const val roboelectric = "4.8" // https://github.com/Piasy/BigImageViewer#add-the-dependencies const val bigImageViewer = "1.8.1" // https://github.com/node-gradle/gradle-node-plugin/releases const val nodeGradle = "3.4.0" }
buildSrc/src/main/kotlin/Versions.kt
3794464731
/* * Copyright 2019 Allan Wang * * 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.pitchedapps.frost.utils import android.content.Context import ca.allanwang.kau.utils.string import com.pitchedapps.frost.R import java.text.DateFormat import java.text.SimpleDateFormat import java.util.Calendar import java.util.Date import java.util.Locale /** * Converts time in millis to readable date, eg Apr 24 at 7:32 PM * * With regards to date modifications in calendars, it appears to respect calendar rules; see * https://stackoverflow.com/a/43227817/4407321 */ fun Long.toReadableTime(context: Context): String { val cal = Calendar.getInstance() cal.timeInMillis = this val timeFormatter = SimpleDateFormat.getTimeInstance(DateFormat.SHORT) val time = timeFormatter.format(Date(this)) val day = when { cal >= Calendar.getInstance().apply { add(Calendar.DAY_OF_MONTH, -1) } -> context.string(R.string.today) cal >= Calendar.getInstance().apply { add(Calendar.DAY_OF_MONTH, -2) } -> context.string(R.string.yesterday) else -> { val dayFormatter = SimpleDateFormat("MMM dd", Locale.getDefault()) dayFormatter.format(Date(this)) } } return context.getString(R.string.time_template, day, time) }
app/src/main/kotlin/com/pitchedapps/frost/utils/TimeUtils.kt
2411966709
@file:Suppress("UNCHECKED_CAST", "CascadeIf") package com.github.shynixn.blockball.core.logic.business.service import com.github.shynixn.blockball.api.business.annotation.YamlSerialize import com.github.shynixn.blockball.api.business.serializer.YamlSerializer import com.github.shynixn.blockball.api.business.service.YamlSerializationService import java.lang.reflect.Field import java.lang.reflect.ParameterizedType import java.util.* import kotlin.collections.ArrayList import kotlin.collections.set /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class YamlSerializationServiceImpl : YamlSerializationService { /** * Serializes the given [instance] to a key value pair map. */ override fun serialize(instance: Any): Map<String, Any?> { return if (instance.javaClass.isArray) { serializeArray(null, instance as Array<Any?>) } else if (Collection::class.java.isAssignableFrom(instance.javaClass)) { serializeCollection(null, instance as Collection<Any?>) } else if (Map::class.java.isAssignableFrom(instance.javaClass)) { serializeMap(instance as Map<Any, Any>) } else { serializeObject(instance)!! } } /** * Deserializes the given [dataSource] into a new instance of the given [targetObjectClass]. */ override fun <R> deserialize(targetObjectClass: Class<R>, dataSource: Map<String, Any?>): R { if (targetObjectClass.isInterface) { throw IllegalArgumentException("Use a class intead of the interface $targetObjectClass.") } val instance: R? try { instance = targetObjectClass.newInstance() } catch (e: Exception) { throw IllegalArgumentException("Cannot instanciate the class $targetObjectClass. Does it have a default constructor?") } deserializeObject(instance!!, targetObjectClass, dataSource) return instance } /** * Deserialize the given object collection. */ private fun deserializeCollection( annotation: YamlSerialize, field: Field, collection: MutableCollection<Any?>, dataSource: Any ) { if (dataSource is Map<*, *>) { dataSource.keys.forEach { key -> if (key is String && key.toIntOrNull() == null) { throw IllegalArgumentException("Initializing " + annotation.value + " as collection failed as dataSource contains a invalid key.") } val value = dataSource[key] if (value == null) { collection.add(null) } else if (getArgumentType(field, 0).isEnum) { @Suppress("UPPER_BOUND_VIOLATED", "UNCHECKED_CAST") collection.add( java.lang.Enum.valueOf<Any>( getArgumentType(field, 0) as Class<Any>, value.toString().toUpperCase(Locale.ENGLISH) ) ) } else if (isPrimitive(value.javaClass)) { collection.add(value) } else { collection.add(deserialize(getArgumentType(field, 0) as Class<Any>, value as Map<String, Any?>)) } } } else if (dataSource is Collection<*>) { dataSource.forEach { item -> collection.add(item) } } else { throw IllegalArgumentException("Initializing " + annotation.value + " from given data source did succeed.") } } /** * Deserialize the given object map. */ private fun deserializeMap( annotation: YamlSerialize, map: MutableMap<Any, Any?>, keyClazz: Class<*>, valueClazz: Class<*>, dataSource: Map<String, Any?> ) { dataSource.keys.forEach { key -> val value = dataSource[key] val finalKey = if (keyClazz.isEnum) { @Suppress("UPPER_BOUND_VIOLATED", "UNCHECKED_CAST") java.lang.Enum.valueOf<Any>(keyClazz as Class<Any>, key.toUpperCase(Locale.ENGLISH)) } else if (isPrimitive(keyClazz)) { key } else { throw java.lang.IllegalArgumentException("Initializing " + annotation.value + " as map failed as map key is not primitiv or an enum.") } if (value == null) { map[finalKey] = null } else if (isPrimitive(valueClazz)) { map[finalKey] = value } else { if (valueClazz.isInterface) { if (annotation.implementation == Any::class) { throw IllegalArgumentException("Map Value $annotation is an interface without deserialization implementation.") } map[finalKey] = deserialize(annotation.implementation.javaObjectType, value as Map<String, Any?>) } else { map[finalKey] = deserialize(valueClazz, value as Map<String, Any?>) } } } } /** * Deserialize the given object array. */ private fun deserializeArray( annotation: YamlSerialize, field: Field, array: Array<Any?>, dataSource: Map<String, Any?> ) { dataSource.keys.forEach { key -> if (key.toIntOrNull() == null) { throw java.lang.IllegalArgumentException("Initializing " + annotation.value + " as array failed as dataSource contains a invalid key.") } val keyPlace = key.toInt() - 1 val value = dataSource[key] if (keyPlace < array.size) { if (value == null) { array[keyPlace] = null } else if (annotation.customserializer != Any::class) { array[keyPlace] = (annotation.customserializer.java.newInstance() as YamlSerializer<*, Map<String, Any?>>).onDeserialization( value as Map<String, Any?> ) } else if (field.type.componentType.isEnum) { @Suppress("UPPER_BOUND_VIOLATED", "UNCHECKED_CAST") array[keyPlace] = java.lang.Enum.valueOf<Any>(field.type as Class<Any>, value.toString().toUpperCase(Locale.ENGLISH)) } else if (isPrimitive(value.javaClass)) { array[keyPlace] = value } else { array[keyPlace] = deserialize(value.javaClass, value as Map<String, Any?>) } } } } /** * Deserializes the given [instance] of the [instanceClazz] from the [dataSource]. */ private fun deserializeObject(instance: Any, instanceClazz: Class<*>, dataSource: Map<String, Any?>) { var runningClazz: Class<*>? = instanceClazz while (runningClazz != null) { runningClazz.declaredFields.forEach { field -> field.isAccessible = true field.declaredAnnotations.forEach { annotation -> if (annotation.annotationClass == YamlSerialize::class) { deserializeField(field, annotation as YamlSerialize, instance, dataSource) } } } runningClazz = runningClazz.superclass } } /** * Deserializes a single field of an object. */ private fun deserializeField( field: Field, annotation: YamlSerialize, instance: Any, dataSource: Map<String, Any?> ) { if (!dataSource.containsKey(annotation.value)) { return } val value = dataSource[annotation.value] if (value == null) { field.set(instance, value) } else if (annotation.customserializer != Any::class && !field.type.isArray && !Collection::class.java.isAssignableFrom( field.type ) ) { val deserializedValue = (annotation.customserializer.java.newInstance() as YamlSerializer<Any, Any>).onDeserialization(value) field.set(instance, deserializedValue) } else if (isPrimitive(field.type)) { field.set(instance, value) } else if (field.type.isEnum) run { @Suppress("UPPER_BOUND_VIOLATED", "UNCHECKED_CAST") field.set(instance, java.lang.Enum.valueOf<Any>(field.type as Class<Any>, value.toString().toUpperCase(Locale.ENGLISH))) } else if (field.type.isArray) { val array = field.get(instance) if (array == null) { throw IllegalArgumentException("Array field " + field.name + " should already be initialized with a certain array.") } deserializeArray(annotation, field, array as Array<Any?>, value as Map<String, Any?>) } else if (Collection::class.java.isAssignableFrom(field.type)) { val collection = field.get(instance) if (collection == null) { throw IllegalArgumentException("Collection field " + field.name + " should already be initialized with a certain collection.") } (collection as MutableCollection<Any?>).clear() deserializeCollection(annotation, field, collection, value) } else if (Map::class.java.isAssignableFrom(field.type)) { val map = field.get(instance) if (map == null) { throw IllegalArgumentException("Map field " + field.name + " should already be initialized with a certain map.") } (map as MutableMap<Any, Any?>).clear() deserializeMap( annotation, map, getArgumentType(field, 0), getArgumentType(field, 1), value as Map<String, Any?> ) } else { val instanceClazz: Class<*> = if (field.type.isInterface) { if (annotation.implementation == Any::class) { throw IllegalArgumentException("Type of field " + field.name + " is an interface without deserialization implementation.") } annotation.implementation.java } else { field.type } field.set(instance, deserialize(instanceClazz, value as Map<String, Any?>)) } } /** * Serializes the given [instance] into a key value pair map. */ private fun serializeCollection(annotation: YamlSerialize?, instance: Collection<Any?>): Map<String, Any?> { return serializeArray(annotation, instance.toTypedArray()) } /** * Serializes the given [instances] into a key value pair map. */ private fun serializeArray(annotation: YamlSerialize?, instances: Array<Any?>): Map<String, Any?> { val data = LinkedHashMap<String, Any?>() for (i in 1..instances.size) { val instance = instances[i - 1] if (instance == null) { data[i.toString()] = null } else if (isPrimitive(instance::class.java)) { data[i.toString()] = instance } else if (annotation != null && annotation.customserializer != Any::class) { data[i.toString()] = (annotation.customserializer.java.newInstance() as YamlSerializer<Any, Any>).onSerialization( instance ) } else if (instance::class.java.isEnum) { data[i.toString()] = (instance as Enum<*>).name } else { data[i.toString()] = serialize(instance) } } return data } /** * Serializes the given [instance] map into a key value pair map. */ private fun serializeMap(instance: Map<Any, Any?>): Map<String, Any?> { val data = LinkedHashMap<String, Any?>() for (key in instance.keys) { if (isPrimitive(key::class.java)) { data[key.toString()] = serialize(instance[key]!!) } else if (key.javaClass.isEnum) { val value = instance[key] if (value == null) { data[(key as Enum<*>).name] = null } else if (isPrimitive(value.javaClass)) { data[(key as Enum<*>).name] = value } else { data[(key as Enum<*>).name] = serialize(value) } } else { throw IllegalArgumentException("Given map [$instance] does not contain a primitive type key or enum key.") } } return data } /** * Serializes the given [instance] into a key value pair map. */ private fun serializeObject(instance: Any?): Map<String, Any?>? { if (instance == null) { return null } val data = LinkedHashMap<String, Any?>() getOrderedAnnotations(instance::class.java).forEach { element -> val field = element.second val yamlAnnotation = element.first if (field.get(instance) == null) { } else if (yamlAnnotation.customserializer != Any::class && !field.type.isArray && !Collection::class.java.isAssignableFrom( field.type ) ) { val serializedValue = (yamlAnnotation.customserializer.java.newInstance() as YamlSerializer<Any, Any>).onSerialization( field.get(instance) ) data[yamlAnnotation.value] = serializedValue } else if (isPrimitive(field.type)) { data[yamlAnnotation.value] = field.get(instance) } else if (field.type.isEnum || field.type == Enum::class.java) { data[yamlAnnotation.value] = (field.get(instance) as Enum<*>).name.toUpperCase() } else if (field.type.isArray) { data[yamlAnnotation.value] = serializeArray(yamlAnnotation, field.get(instance) as Array<Any?>) } else if (Collection::class.java.isAssignableFrom(field.type)) { if (getArgumentType(field, 0) == String::class.java) { data[yamlAnnotation.value] = field.get(instance) } else { data[yamlAnnotation.value] = serializeCollection(yamlAnnotation, field.get(instance) as Collection<*>) } } else if (Map::class.java.isAssignableFrom(field.type)) { data[yamlAnnotation.value] = serializeMap(field.get(instance) as Map<Any, Any?>) } else { data[yamlAnnotation.value] = serializeObject(field.get(instance)) } } return data } /** * Gets all yaml annotations ordered from a class. */ private fun getOrderedAnnotations(clazz: Class<*>): List<Pair<YamlSerialize, Field>> { val result = ArrayList<Pair<YamlSerialize, Field>>() var runningClazz: Class<*>? = clazz while (runningClazz != null) { runningClazz.declaredFields.forEach { field -> field.isAccessible = true field.declaredAnnotations.forEach { annotation -> if (annotation.annotationClass == YamlSerialize::class) { result.add(Pair(annotation as YamlSerialize, field)) } } } runningClazz = runningClazz.superclass } return result.sortedBy { param -> param.first.orderNumber } } /** * Gets the type of the argument at the given [number] index. */ private fun getArgumentType(field: Field, number: Int): Class<*> { return (field.genericType as ParameterizedType).actualTypeArguments[number] as Class<*> } /** * Gets if the given [clazz] is a primitive class. */ private fun isPrimitive(clazz: Class<*>): Boolean { return clazz.isPrimitive || clazz == String::class.java || clazz == Int::class.java || clazz == Double::class.java || clazz == Long::class.java || clazz == Float::class.java || clazz == Integer::class.java } }
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/service/YamlSerializationServiceImpl.kt
1993614275
package com.yy.codex.uikit import android.content.Context import android.util.AttributeSet import android.view.View import com.yy.codex.coreanimation.CALayer /** * Created by adi on 17/2/6. */ class UIPageControl : UIView { constructor(context: Context, view: View) : super(context, view) constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) override fun init() { super.init() dotView = UIView(context) dotView.wantsLayer = true addSubview(dotView) } override fun prepareProps(attrs: AttributeSet) { super.prepareProps(attrs) val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.UIPageControl, 0, 0) typedArray.getInteger(R.styleable.UIPageControl_pagecontrol_currentPage, 0)?.let { initializeAttributes.put("UIPageControl.currentPage", it) } typedArray.getInteger(R.styleable.UIPageControl_pagecontrol_numberOfPages, 0)?.let { initializeAttributes.put("UIPageControl.numberOfPages", it) } typedArray.getBoolean(R.styleable.UIPageControl_pagecontrol_hidesForSinglePage, false)?.let { initializeAttributes.put("UIPageControl.hidesForSinglePage", it) } typedArray.getColor(R.styleable.UIPageControl_pagecontrol_pageIndicatorColor, -1)?.let { if (it != -1) { initializeAttributes.put("UIPageControl.pageIndicatorColor", UIColor(it)) } } typedArray.getColor(R.styleable.UIPageControl_pagecontrol_currentPageIndicatorColor, -1)?.let { if (it != -1) { initializeAttributes.put("UIPageControl.currentPageIndicatorColor", UIColor(it)) } } } override fun resetProps() { super.resetProps() initializeAttributes?.let { (it["UIPageControl.currentPage"] as? Int)?.let { currentPage = it } (it["UIPageControl.numberOfPages"] as? Int)?.let { numberOfPages = it } (it["UIPageControl.hidesForSinglePage"] as? Boolean)?.let { hidesForSinglePage = it } (it["UIPageControl.pageIndicatorColor"] as? UIColor)?.let { pageIndicatorColor = it } (it["UIPageControl.currentPageIndicatorColor"] as? UIColor)?.let { currentPageIndicatorColor = it } } } override fun intrinsicContentSize(): CGSize { return CGSize(0.0, 16.0) } private val dotSpacing: Double = 10.0 private val dotRadius: Double = 5.0 private lateinit var dotView: UIView var currentPage: Int = 0 set(value) { if (field != value){ field = value updatePagesColor() } } var numberOfPages: Int = 3 set(value) { if (field != value){ field = value updatePagesLayout() updatePagesColor() } } var hidesForSinglePage: Boolean = false set(value) { if (field != value){ field = value updatePagesLayout() } } var pageIndicatorColor: UIColor = (tintColor ?: UIColor(0x12 / 255.0, 0x6a / 255.0, 1.0, 1.0)).colorWithAlpha(0.50) set(value) { if (field != value){ field = value updatePagesColor() } } var currentPageIndicatorColor: UIColor = tintColor ?: UIColor(0x12 / 255.0, 0x6a / 255.0, 1.0, 1.0) set(value) { if (field != value){ field = value updatePagesColor() } } override fun layoutSubviews() { super.layoutSubviews() updatePagesLayout() updatePagesColor() } private fun updatePagesLayout(){ if (hidesForSinglePage && numberOfPages == 1){ dotView.hidden = true return } val contentWidth = numberOfPages * ( dotSpacing + dotRadius*2 ) dotView.frame = CGRect((frame.width - contentWidth) / 2.0, 0.0, contentWidth, dotRadius * 2) dotView.layer.removeSubLayers() dotView.hidden = false for (i in 0..numberOfPages - 1) { val x = dotSpacing / 2.0 + i * (dotSpacing + dotRadius * 2) val layer = CALayer(CGRect(x, 0.0, dotRadius * 2, dotRadius * 2)) layer.cornerRadius = dotRadius dotView.layer.addSubLayer(layer) } } private fun updatePagesColor(){ dotView.layer.sublayers.forEachIndexed { idx, dotLayer -> dotLayer.backgroundColor = if (currentPage == idx) currentPageIndicatorColor else pageIndicatorColor } } fun sizeForNumberOfPages(): CGSize { return CGSize( numberOfPages * (dotSpacing+dotRadius*2), dotRadius * 2 ) } }
library/src/main/java/com/yy/codex/uikit/UIPageControl.kt
3921631937
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.psi.element import com.intellij.lang.ASTNode open class MdTextBlockImpl(node: ASTNode) : MdCompositeImpl(node), MdTextBlock
src/main/java/com/vladsch/md/nav/psi/element/MdTextBlockImpl.kt
2197677091
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.article_viewer.bookmark import androidx.room.Entity import androidx.room.PrimaryKey /** * @author toastkidjp */ @Entity data class Bookmark(@PrimaryKey(autoGenerate = false) var id: Int)
article/src/main/java/jp/toastkid/article_viewer/bookmark/Bookmark.kt
813587096
package org.stt.persistence.stt import org.stt.model.TimeTrackingItem import org.stt.persistence.ItemReader import org.stt.persistence.ItemWriter internal class InsertHelper(val reader: ItemReader, val writer: ItemWriter, val itemToInsert: TimeTrackingItem) { private var lastReadItem: TimeTrackingItem? = null fun performInsert() { copyAllItemsEndingAtOrBeforeItemToInsert() lastReadItem?.let { this.adjustEndOfLastItemReadAndWrite(it) } writer.write(itemToInsert) skipAllItemsCompletelyCoveredByItemToInsert() lastReadItem?.let { this.adjustStartOfLastItemReadAndWrite(it) } copyRemainingItems() } private fun copyAllItemsEndingAtOrBeforeItemToInsert() { copyWhile { it.endsAtOrBefore(itemToInsert.start) } } private fun adjustStartOfLastItemReadAndWrite(item: TimeTrackingItem) { val itemToWrite = itemToInsert.end?.let { end -> if (end.isAfter(item.start)) item.withStart(end) else null } ?: item writer.write(itemToWrite) } private fun adjustEndOfLastItemReadAndWrite(item: TimeTrackingItem) { if (item.start.isBefore(itemToInsert.start)) { val itemBeforeItemToInsert = item .withEnd(itemToInsert.start) writer.write(itemBeforeItemToInsert) } } private fun copyRemainingItems() { copyWhile { true } } private fun skipAllItemsCompletelyCoveredByItemToInsert() { var currentItem = lastReadItem while (currentItem != null && itemToInsert.endsSameOrAfter(currentItem)) { currentItem = reader.read() } lastReadItem = currentItem } private fun copyWhile(condition: (TimeTrackingItem) -> Boolean) { do { lastReadItem = reader.read() lastReadItem?.let { if (condition(it)) writer.write(it) else return } } while (lastReadItem != null) } }
src/main/kotlin/org/stt/persistence/stt/InsertHelper.kt
236038234
package net.cad.config import org.slf4j.LoggerFactory import org.springframework.boot.bind.RelaxedPropertyResolver import org.springframework.context.EnvironmentAware import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.env.Environment import org.springframework.util.StopWatch import springfox.documentation.builders.PathSelectors import springfox.documentation.builders.RequestHandlerSelectors import springfox.documentation.service.ApiInfo import springfox.documentation.service.ApiKey import springfox.documentation.service.Contact import springfox.documentation.service.SecurityScheme import springfox.documentation.spi.DocumentationType import springfox.documentation.spring.web.plugins.Docket import springfox.documentation.swagger.web.ApiKeyVehicle import springfox.documentation.swagger.web.SecurityConfiguration import springfox.documentation.swagger2.annotations.EnableSwagger2 import java.util.* @Configuration @EnableSwagger2 open class SwaggerConfig : EnvironmentAware { private lateinit var propertyResolver: RelaxedPropertyResolver; private fun apiInfo(): ApiInfo { val contactInfo = Contact( propertyResolver.getProperty("contact.name"), propertyResolver.getProperty("contact.url"), propertyResolver.getProperty("contact.email")) return ApiInfo( propertyResolver.getProperty("api.title"), propertyResolver.getProperty("api.description"), propertyResolver.getProperty("api.version"), propertyResolver.getProperty("api.termsofserviceurl"), contactInfo, propertyResolver.getProperty("api.license"), propertyResolver.getProperty("api.licenseurl")) } override fun setEnvironment(environment: Environment) { this.propertyResolver = RelaxedPropertyResolver(environment, "swagger.") } @Bean open fun api(): Docket { log.info("Starting Swagger") val watch = StopWatch() watch.start() val docket = Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("net.cad.controllers")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()) .forCodeGeneration(true) .directModelSubstitute(java.time.LocalDate::class.java, String::class.java) .directModelSubstitute(java.time.ZonedDateTime::class.java, Date::class.java) .directModelSubstitute(java.time.LocalDateTime::class.java, Date::class.java) watch.stop() log.info("Started Swagger in {} ms", watch.totalTimeMillis) return docket } @Bean open fun apiKey(): SecurityScheme { return ApiKey("myKey", "Authorization", "header") } @Bean open fun security(): SecurityConfiguration { return SecurityConfiguration( "", // clientId "", // clientSecret "", // realm "Salesforce Integration API", // appName "api_key", // apiKeyValue ApiKeyVehicle.HEADER, //apiKeyVechicle "Authorization", // apiKeyName ",") // scopeSeparator } companion object { private val log = LoggerFactory.getLogger(SwaggerConfig::class.java) } }
src/main/kotlin/net/cad/config/SwaggerConfig.kt
2232849093
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve class RsNamespaceResolveTest : RsResolveTestBase() { fun testModAndFn() = checkByCode(""" mod test { //X pub struct Test { pub a: u32, } } fn main() { let mut test = test::Test { a: 42 }; let test: test::Test = test; // New immutable binding so test is not accidentally modified //^ println!("Value: {}", test.a); } """) fun testModFnInner() = checkByCode(""" mod m { fn bar() {} } //X fn m() { } fn main() { let _ = m::bar(); } //^ """) fun testModFnInnerInner() = checkByCode(""" mod outer { mod m { fn bar() {} } //X fn m() { } } fn main() { let _ = outer::m::bar(); } //^ """) fun testTypeAndConst() = checkByCode(""" struct T { } //X const T: i32 = 0; fn main() { let _: T = T { }; //^ } """) fun testFnStruct() = checkByCode(""" struct P { } //X fn P() -> P { } //^ """) fun testStaticIsNotType() = checkByCode(""" static S: u8 = 0; fn main() { let _: S = unimplemented!(); //^ unresolved } """) fun testPath() = checkByCode(""" mod m { fn foo() {} } fn main() { let _: m::foo = unimplemented!(); //^ unresolved } """) fun testUseFn() = checkByCode(""" use m::foo; mod m { fn foo() {} //X mod foo { fn bar() {} } } fn main() { foo(); //^ foo::bar(); } """) fun testUseMod() = checkByCode(""" use m::foo; mod m { fn foo() {} mod foo { fn bar() {} } //X } fn main() { foo(); foo::bar(); //^ } """) fun testUseModGlob() = checkByCode(""" use m::{foo}; mod m { fn foo() {} mod foo { fn bar() {} } //X } fn main() { foo(); foo::bar(); //^ } """) fun testUseFnGlob() = checkByCode(""" use m::{foo}; mod m { fn foo() {} //X mod foo { fn bar() {} } } fn main() { foo(); //^ foo::bar(); } """) fun `test issue 1138`() = checkByCode(""" mod foo { mod inner { pub fn inner() {} } //X pub use self::inner::inner; } mod bar { pub use foo::inner; } use bar::inner; fn f() { inner(); } //^ """) fun `test constructor`() = checkByCode(""" struct Foo {} //X fn Foo() -> Foo { Foo {}} //^ """) fun `test assoc namespaces 1`() = checkByCode(""" trait Foo { type X; //X const X: Self::X; } fn foo<T: Foo>() { let _: T::X = T::X; } //^ """) fun `test assoc namespaces 2`() = checkByCode(""" trait Foo { type X; const X: Self::X; } //X fn foo<T: Foo>() { let _: T::X = T::X; } //^ """) }
src/test/kotlin/org/rust/lang/core/resolve/RsNamespaceResolveTest.kt
1612205730
package com.github.dirkraft.cartograph import org.junit.Assert.assertEquals import org.junit.Assert.fail import org.junit.Test import org.mockito.Mockito.* import java.sql.PreparedStatement import java.sql.Types import java.util.* class mappingTest { @Test fun `test null Date mapForSqlWrite`() { val writeMappings = calcWriteMappings(MyData(id = 0, name = "yoyo")) val dateIndex = writeMappings.keys.withIndex().first { it.value == "tempo" }.index val dateVal = writeMappings.values.map { it.value }.toList()[dateIndex] when (dateVal) { is TypedNull -> assertEquals(Types.TIMESTAMP, dateVal.sqlType) else -> fail() } } @Test fun `test non-null Date mapForSqlWrite`() { val date = Date() val writeMappings = calcWriteMappings(MyData(id = 0, name = "yoyo", tempo = date)) val dateIndex = writeMappings.keys.withIndex().first { it.value == "tempo" }.index assertEquals(date, writeMappings.values.map { it.value }.toList()[dateIndex]) } @Test fun `test null Date PreparedStatement_mapIn`() { val writeMappings = calcWriteMappings(MyData(id = 0, name = "yoyo", someNum = 123)) // +1 because SQL columns are 1-indexed val dateColIndex = 1 + writeMappings.keys.withIndex().first { it.value == "tempo" }.index val ps = mock<PreparedStatement>() ps.mapIn(writeMappings.values.map { it.value }.toList()) verify(ps).setNull(eq(dateColIndex), eq(Types.TIMESTAMP)) } @Test fun `test non-null Date PreparedStatement_mapIn`() { val date = Date() val writeMappings = calcWriteMappings(MyData(id = 0, name = "yoyo", tempo = date)) // +1 because SQL columns are 1-indexed val dateColIndex = 1 + writeMappings.keys.withIndex().first { it.value == "tempo" }.index val ps = mock<PreparedStatement>() ps.mapIn(writeMappings.values.map { it.value }.toList()) verify(ps, times(1)).setTimestamp(eq(dateColIndex), notNull()) } @Test fun `test null Long PreparedStatement_mapIn`() { val writeMappings = calcWriteMappings(MyData(id = null, name = "yoyo", someNum = 123, tempo = Date())) // +1 because SQL columns are 1-indexed val longColIndex = 1 + writeMappings.keys.withIndex().first { it.value == "id" }.index val ps = mock<PreparedStatement>() ps.mapIn(writeMappings.values.map { it.value }.toList()) verify(ps, times(1)).setNull(eq(longColIndex), eq(Types.INTEGER)) } }
cartograph/src/test/kotlin/com/github/dirkraft/cartograph/mappingTest.kt
2994962734
package com.apkupdater.model.ui import android.net.Uri import com.apkupdater.util.adapter.Id data class AppInstalled( override val id: Int, val name: String, val packageName: String, val version: String, val versionCode: Int, val iconUri: Uri = Uri.EMPTY, val ignored: Boolean = false ): Id
app/src/main/java/com/apkupdater/model/ui/AppInstalled.kt
442847438
package com.booboot.vndbandroid.util.view import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout import androidx.annotation.AttrRes import com.booboot.vndbandroid.R class Divider @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, @AttrRes defStyleAttr: Int = 0, defStyleRes: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr, defStyleRes) { init { inflate(context, R.layout.card_divider, this) } }
app/src/main/java/com/booboot/vndbandroid/util/view/Divider.kt
118676032
/* * Copyright (c) 2016-2019 PSPDFKit GmbH. All rights reserved. * * THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW * AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT. * UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES. * This notice may not be removed from this file */ package com.pspdfkit.labs.quickdemo import android.content.Context import android.widget.Toast /** Shows a normal toast message. */ fun Context.toast(message: CharSequence, length: Int = Toast.LENGTH_SHORT) = Toast.makeText(this, message, length).show()
app/src/main/kotlin/com/pspdfkit/labs/quickdemo/Utils.kt
1489913523
/*- * #%L * Lincheck * %% * Copyright (C) 2015 - 2018 Devexperts, LLC * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ package com.devexperts.dxlab.lincheck.verifier import com.devexperts.dxlab.lincheck.Actor import com.devexperts.dxlab.lincheck.Result import com.devexperts.dxlab.lincheck.execution.ExecutionResult import com.devexperts.dxlab.lincheck.execution.ExecutionScenario import com.devexperts.dxlab.lincheck.verifier.quantitative.ExtendedLTS /** * An abstraction for verifiers which use the labeled transition system (LTS) under the hood. * The main idea of such verifiers is finding a path in LTS, which starts from the initial * LTS state (see [LTS.initialState]) and goes through all actors with the specified results. * To determine which transitions are possible from the current state, we store related * to the current path prefix information in the special [LTSContext], which determines * the next possible transitions using [LTSContext.nextContexts] function. This verifier * uses depth-first search to find a proper path. */ abstract class AbstractLTSVerifier<STATE>(val scenario: ExecutionScenario, val testClass: Class<*>) : CachedVerifier() { abstract fun createInitialContext(results: ExecutionResult): LTSContext<STATE> override fun verifyResultsImpl(results: ExecutionResult): Boolean { return verify(createInitialContext(results)) } private fun verify(context: LTSContext<STATE>): Boolean { // Check if a possible path is found. if (context.completed) return true // Traverse through next possible transitions using depth-first search (DFS). Note that // initial and post parts are represented as threads with ids `0` and `threads + 1` respectively. for (threadId in 0..scenario.threads + 1) { for (c in context.nextContexts(threadId)) { if (verify(c)) return true } } return false } } /** * Common interface for different labeled transition systems, which several correctness formalisms use. * Lin-Check widely uses LTS-based formalisms for verification, see [Verifier] implementations as examples. * Essentially, LTS provides an information of the possibility to do a transition from one state to another * by the specified actor with the specified result. Nevertheless, it should be extended and provide any additional * information, like the transition penalty in [ExtendedLTS]. */ interface LTS<STATE> { /** * Returns the state corresponding to the initial state of the data structure. */ val initialState: STATE } /** * Reflects the current path prefix information and stores the current LTS state * (which essentially indicates the data structure state) for a single step of a legal path search * in LTS-based verifiers. It counts next possible transitions via [nextContexts] function. */ abstract class LTSContext<STATE>( /** * Current execution scenario. */ val scenario: ExecutionScenario, /** * LTS state of this context */ val state: STATE, /** * Number of executed actors in each thread. Note that initial and post parts * are represented as threads with ids `0` and `threads + 1` respectively. */ val executed: IntArray) { /** * Counts next possible states and the corresponding contexts if the specified thread is executed. */ abstract fun nextContexts(threadId: Int): List<LTSContext<STATE>> // The total number of actors in init part of the execution scenario. val initActors: Int = scenario[0].size // The number of executed actors in the init part. val initExecuted: Int = executed[0] // `true` if all actors in the init part are executed. val initCompleted: Boolean = initActors == initExecuted // The total number of actors in parallel part of the execution scenario. val parallelActors: Int = scenario.parallelExecution.fold(0) { sum, t -> sum + t.size } // The number of executed actors in the parallel part. val parallelExecuted: Int = executed.slice(1..scenario.threads).fold(0) { sum, e -> sum + e } // `true` if all actors in the init part are executed. val parallelCompleted: Boolean = parallelActors == parallelExecuted // The total number of actors in post part of the execution scenario. val postActors: Int = scenario[scenario.threads + 1].size // The number of executed actors in the post part. val postExecuted: Int = executed[scenario.threads + 1] // `true` if all actors in the post part are executed. val postCompleted: Boolean = postActors == postExecuted // The total number of actors in the execution scenario. val totalActors: Int = initActors + parallelActors + postActors // The total number of executed actors. val totalExecuted: Int = initExecuted + parallelExecuted + postExecuted // `true` if all actors are executed and a legal path is found therefore. val completed: Boolean = totalActors == totalExecuted // Returns `true` if all actors in the specified thread are executed. fun isCompleted(threadId: Int) = executed[threadId] == scenario[threadId].size } /** * Returns scenario for the specified thread. Note that initial and post parts * are represented as threads with ids `0` and `threads + 1` respectively. */ operator fun ExecutionScenario.get(threadId: Int): List<Actor> = when (threadId) { 0 -> initExecution threads + 1 -> postExecution else -> parallelExecution[threadId - 1] } /** * Returns results for the specified thread. Note that initial and post parts * are represented as threads with ids `0` and `threads + 1` respectively. */ operator fun ExecutionResult.get(threadId: Int): List<Result> = when (threadId) { 0 -> initResults parallelResults.size + 1 -> postResults else -> parallelResults[threadId - 1] }
lincheck/src/main/java/com/devexperts/dxlab/lincheck/verifier/LTS.kt
3046874911
package kodando.mithril.routing import kodando.history.Location import kodando.mithril.* import kodando.mithril.context.contextConsumer external interface RouteProps : Props { var computedMatch: Match? var location: Location? var path: String? var exact: Boolean var strict: Boolean var sensitive: Boolean var view: View<*> var render: (RoutedProps) -> VNode<*>? } object Route : View<RouteProps> { private fun computeMatch(props: RouteProps, context: RouterContext): Match? { val computedMatch = props.computedMatch if (computedMatch != null) { return computedMatch } val route = context.route val pathName = (props.location ?: context.route.location).pathname return matchPath( pathName, props.path, props.strict, props.exact, props.sensitive, route.match ) } override fun view(vnode: VNode<RouteProps>): VNode<*>? { val attrs = vnode.attrs ?: return null return root { contextConsumer(routerContextKey) { context -> val route = context.route val history = context.history val location = attrs.location ?: route.location val match = computeMatch(attrs, context) val routedProps = routedProps(match, location, history) if (addView(attrs.view, routedProps)) { return@contextConsumer } if (addRender(attrs.render, routedProps)) { return@contextConsumer } addChildren(vnode.children, match) } } } private fun Props.addView(view: View<*>, routedProps: RoutedProps): Boolean { if (view === undefined) { return false } val match = routedProps.match addChild( match?.let { createElement(view, routedProps) } ) return true } private fun Props.addRender(render: (RoutedProps) -> VNode<*>?, routedProps: RoutedProps): Boolean { if (render === undefined) { return false } val match = routedProps.match addChild( match?.let { render(routedProps) } ) return true } private fun Props.addChildren(children: Array<out VNode<*>?>, match: Match?) { val child = children.firstOrNull() addChild( match?.let { child } ) } } fun Props.route( path: String, exact: Boolean = true, strict: Boolean = false, applier: Props.(RoutedProps) -> Unit) { addChild(Route) { this.path = path this.exact = exact this.strict = strict this.render = { root { applier(it) } } } } fun Props.route(applier: Applier<RouteProps>) { addChild(Route, applier) }
kodando-mithril-router-dom/src/main/kotlin/kodando/mithril/router/dom/Route.kt
1652058972
package kodando.elmish interface View
kodando-elmish/src/main/kotlin/kodando/elmish/View.kt
88886531
package me.sweetll.tucao.extension import io.reactivex.Observable import io.reactivex.schedulers.Schedulers import io.reactivex.android.schedulers.AndroidSchedulers import me.sweetll.tucao.di.service.ApiConfig import me.sweetll.tucao.model.json.BaseResponse import me.sweetll.tucao.model.json.ListResponse import okhttp3.ResponseBody import org.jsoup.Jsoup import org.jsoup.nodes.Document fun <T> Observable<BaseResponse<T>>.sanitizeJson(): Observable<T> = this .subscribeOn(Schedulers.io()) .retryWhen(ApiConfig.RetryWithDelay()) .flatMap { response -> if (response.code == "200") { Observable.just(response.result!!) } else { Observable.error(Throwable(response.msg)) } } .observeOn(AndroidSchedulers.mainThread()) fun <T> Observable<ListResponse<T>>.sanitizeJsonList(): Observable<ListResponse<T>> = this .subscribeOn(Schedulers.io()) .retryWhen(ApiConfig.RetryWithDelay()) .flatMap { response -> if (response.code == "200") { response.result = response.result ?: mutableListOf() Observable.just(response) } else { Observable.error(Throwable(response.msg)) } } .observeOn(AndroidSchedulers.mainThread()) fun <T> Observable<ResponseBody>.sanitizeHtml(transform: Document.() -> T): Observable<T> = this .subscribeOn(Schedulers.io()) .retryWhen(ApiConfig.RetryWithDelay()) .map { response -> Jsoup.parse(response.string()).transform() } .observeOn(AndroidSchedulers.mainThread())
app/src/main/kotlin/me/sweetll/tucao/extension/ObservableExtensions.kt
2909753540
/* * Copyright (C) 2021 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption.REPLACE_EXISTING import java.util.Locale.US @Suppress("UnsafeDynamicallyLoadedCode") // Only loading from our own JAR contents. internal fun loadNativeLibrary() { val osName = System.getProperty("os.name").lowercase(US) val osArch = System.getProperty("os.arch").lowercase(US) val nativeLibraryJarPath = if (osName.contains("linux")) { "/jni/$osArch/libquickjs.so" } else if (osName.contains("mac")) { "/jni/$osArch/libquickjs.dylib" } else { throw IllegalStateException("Unsupported OS: $osName") } val nativeLibraryUrl = QuickJs::class.java.getResource(nativeLibraryJarPath) ?: throw IllegalStateException("Unable to read $nativeLibraryJarPath from JAR") val nativeLibraryFile: Path try { nativeLibraryFile = Files.createTempFile("quickjs", null) // File-based deleteOnExit() uses a special internal shutdown hook that always runs last. nativeLibraryFile.toFile().deleteOnExit() nativeLibraryUrl.openStream().use { nativeLibrary -> Files.copy(nativeLibrary, nativeLibraryFile, REPLACE_EXISTING) } } catch (e: IOException) { throw RuntimeException("Unable to extract native library from JAR", e) } System.load(nativeLibraryFile.toAbsolutePath().toString()) }
zipline/src/jvmMain/kotlin/app/cash/zipline/QuickJsNativeLoader.kt
209348531
package com.balanza.android.harrypotter.domain.interactor.character import android.util.Log import com.balanza.android.harrypotter.domain.model.character.CharacterBasic import com.balanza.android.harrypotter.domain.repository.character.CharacterRepository import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread /** * Created by balanza on 15/02/17. */ class GetAllCharactersImp(val characterRepository: CharacterRepository) : GetAllCharacters { override fun getAllCharacters(refresh: Boolean, onCharactersAvailable: GetAllCharacters.OnCharactersAvailable) { doAsync { if (refresh) { characterRepository.clear() } characterRepository.getAllCharacters(object : CharacterRepository.OnCharacterAvailable { override fun onSuccess(characterList: List<CharacterBasic>) { uiThread { onCharactersAvailable.onSuccess(characterList) } } override fun onError(message: String?) { uiThread { onCharactersAvailable.onError(message) } } }) } } }
app/src/main/java/com/balanza/android/harrypotter/domain/interactor/character/GetAllCharactersImp.kt
2243826169
package com.rm.translateit.api.translation import com.rm.translateit.api.translation.source.Source import com.rm.translateit.api.translation.source.babla.BablaModule import com.rm.translateit.api.translation.source.wiki.WikiModule import dagger.Component import javax.inject.Singleton @Component( modules = arrayOf( WikiModule::class, BablaModule::class ) ) @Singleton internal interface SourcesComponent { fun sources(): Set<Source> }
api/src/main/kotlin/com/rm/translateit/api/translation/SourcesComponent.kt
48981075
package com.ddiehl.android.htn.view.text import android.graphics.Rect import android.text.TextPaint import android.text.style.MetricAffectingSpan /** * https://stackoverflow.com/a/37088653/3238938 */ class CenteredRelativeSizeSpan(val sizeChange: Float) : MetricAffectingSpan() { override fun updateDrawState(ds: TextPaint) { updateAnyState(ds) } override fun updateMeasureState(ds: TextPaint) { updateAnyState(ds) } private fun updateAnyState(ds: TextPaint) { val bounds = Rect() ds.getTextBounds("1A", 0, 2, bounds) var shift = bounds.top - bounds.bottom ds.textSize = ds.textSize * sizeChange ds.getTextBounds("1A", 0, 2, bounds) shift -= bounds.top - bounds.bottom shift /= 2 ds.baselineShift += shift } }
app/src/main/java/com/ddiehl/android/htn/view/text/CenteredRelativeSizeSpan.kt
1101218364
package io.gitlab.arturbosch.detekt.test import java.io.OutputStream internal class NullOutputStream : OutputStream() { override fun write(b: Int) { // no-op } }
detekt-test/src/main/kotlin/io/gitlab/arturbosch/detekt/test/NullOutputStream.kt
765489010
/* * Copyright (c) 2022 David Allison <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.testutils import android.Manifest.permission.READ_EXTERNAL_STORAGE import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.app.Application import android.content.Context import androidx.test.core.app.ApplicationProvider import org.robolectric.Shadows /** Executes [runnable] without [WRITE_EXTERNAL_STORAGE] and [READ_EXTERNAL_STORAGE] */ fun withNoWritePermission(runnable: (() -> Unit)) { try { revokeWritePermissions() runnable() } finally { grantWritePermissions() } } fun grantWritePermissions() { val app = Shadows.shadowOf(ApplicationProvider.getApplicationContext<Context>() as Application) app.grantPermissions(WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE) } fun revokeWritePermissions() { val app = Shadows.shadowOf(ApplicationProvider.getApplicationContext<Context>() as Application) app.denyPermissions(WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE) }
AnkiDroid/src/test/java/com/ichi2/testutils/PermissionUtils.kt
1821390814
package com.infinum.dbinspector.domain.schema.view.usecases import com.infinum.dbinspector.domain.Repositories import com.infinum.dbinspector.domain.UseCases import com.infinum.dbinspector.domain.shared.models.Page import com.infinum.dbinspector.domain.shared.models.parameters.ConnectionParameters import com.infinum.dbinspector.domain.shared.models.parameters.ContentParameters internal class DropViewUseCase( private val connectionRepository: Repositories.Connection, private val schemaRepository: Repositories.Schema ) : UseCases.DropView { override suspend fun invoke(input: ContentParameters): Page { val connection = connectionRepository.open(ConnectionParameters(input.databasePath)) return schemaRepository.dropByName(input.copy(connection = connection)) } }
dbinspector/src/main/kotlin/com/infinum/dbinspector/domain/schema/view/usecases/DropViewUseCase.kt
1471889229
package io.javalin.plugin.openapi.dsl data class OpenApiCrudHandlerDocumentation( var getAllDocumentation: OpenApiDocumentation = OpenApiDocumentation(), var getOneDocumentation: OpenApiDocumentation = OpenApiDocumentation(), var createDocumentation: OpenApiDocumentation = OpenApiDocumentation(), var updateDocumentation: OpenApiDocumentation = OpenApiDocumentation(), var deleteDocumentation: OpenApiDocumentation = OpenApiDocumentation() ) { fun getAll(doc: OpenApiDocumentation) = apply { this.getAllDocumentation = doc } fun getOne(doc: OpenApiDocumentation) = apply { this.getOneDocumentation = doc } fun create(doc: OpenApiDocumentation) = apply { this.createDocumentation = doc } fun update(doc: OpenApiDocumentation) = apply { this.updateDocumentation = doc } fun delete(doc: OpenApiDocumentation) = apply { this.deleteDocumentation = doc } }
javalin-openapi/src/main/java/io/javalin/plugin/openapi/dsl/OpenApiCrudHandlerDocumentation.kt
3483819686
package org.needhamtrack.nytc.screens.event.officiate import android.os.Bundle import org.needhamtrack.nytc.base.BaseFragment import org.needhamtrack.nytc.base.PresenterConfiguration import org.needhamtrack.nytc.models.Event import org.needhamtrack.nytc.screens.event.EventActivity class OfficiateFragment : BaseFragment<OfficiateContract.Presenter>(), OfficiateContract.View { override val layoutResourceId: Int get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. override fun createPresenter(configuration: PresenterConfiguration): OfficiateContract.Presenter { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } companion object { const val TAG = "OfficiateFragment" fun newInstance(event: Event): OfficiateFragment { val fragment = OfficiateFragment() val arguments = Bundle() arguments.putSerializable(EventActivity.EVENT_EXTRA, event) fragment.arguments = arguments return fragment } } }
app/src/main/kotlin/org/needhamtrack/nytc/screens/event/officiate/OfficiateFragment.kt
3015185086
/* * Copyright (c) 2022 Akshit Sinha <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.servicelayer import com.ichi2.anki.CardUtils object CardService { /** * get unique note ids from a list of card ids * @param selectedCardIds list of card ids * can do better with performance here * TODO: blocks the UI, should be fixed */ fun selectedNoteIds(selectedCardIds: List<Long>, col: com.ichi2.libanki.Collection) = CardUtils.getNotes( selectedCardIds.map { col.getCard(it) } ).map { it.id } }
AnkiDroid/src/main/java/com/ichi2/anki/servicelayer/CardService.kt
1974270552
/* * Copyright (C) 2017-2020 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.presentation.datapoints.map import com.mapbox.geojson.FeatureCollection interface DataPointsMapView { fun showProgress() fun hideProgress() fun displayDataPoints(dataPoints: FeatureCollection?) fun showDownloadedResults(numberOfNewItems: Int) fun showErrorAssignmentMissing() fun showErrorNoNetwork() fun showErrorSync() fun showNoDataPointsToDownload() fun hideMenu() fun showMonitoredMenu() fun showNonMonitoredMenu() fun showFab() }
app/src/main/java/org/akvo/flow/presentation/datapoints/map/DataPointsMapView.kt
2117202392
/* * Copyright (c) 2021. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.util.xml import nl.adaptivity.xmlutil.* @OptIn(XmlUtilInternal::class) class IterableCombinedNamespaceContext( val primary: NamespaceContext, val secondary: NamespaceContext ) : IterableNamespaceContext, NamespaceContextImpl { override fun getNamespaceURI(prefix: String): String? { val namespaceURI = primary.getNamespaceURI(prefix) return if (namespaceURI == null || XMLConstants.NULL_NS_URI == namespaceURI) { secondary.getNamespaceURI(prefix) } else namespaceURI } override fun getPrefix(namespaceURI: String): String? { val prefix = primary.getPrefix(namespaceURI) return if (prefix == null || XMLConstants.NULL_NS_URI == namespaceURI && XMLConstants.DEFAULT_NS_PREFIX == prefix) { secondary.getPrefix(namespaceURI) } else prefix } @OptIn(XmlUtilInternal::class) override fun freeze(): IterableNamespaceContext = when { primary is SimpleNamespaceContext && secondary is SimpleNamespaceContext -> this primary !is IterableNamespaceContext -> (secondary as? IterableNamespaceContext)?.freeze() ?: SimpleNamespaceContext() secondary !is IterableNamespaceContext || ! secondary.iterator().hasNext() -> primary.freeze() !primary.iterator().hasNext() -> secondary.freeze() else -> { val frozenPrimary = primary.freeze() val frozenSecondary = secondary.freeze() if (frozenPrimary === primary && frozenSecondary == secondary) { this } else { @Suppress("DEPRECATION") (IterableCombinedNamespaceContext(primary.freeze(), secondary.freeze())) } } } @OptIn(XmlUtilInternal::class) override fun iterator(): Iterator<Namespace> { val p = (primary as? IterableNamespaceContext)?.run { freeze().asSequence() } ?: emptySequence() val s = (secondary as? IterableNamespaceContext)?.run { freeze().asSequence() } ?: emptySequence() return (p + s).iterator() } @Suppress("OverridingDeprecatedMember") override fun getPrefixesCompat(namespaceURI: String): Iterator<String> { val prefixes1 = primary.prefixesFor(namespaceURI) val prefixes2 = secondary.prefixesFor(namespaceURI) val prefixes = hashSetOf<String>() while (prefixes1.hasNext()) { prefixes.add(prefixes1.next()) } while (prefixes2.hasNext()) { prefixes.add(prefixes2.next()) } return prefixes.iterator() } override fun plus(secondary: FreezableNamespaceContext): FreezableNamespaceContext = @Suppress("DEPRECATION") (IterableCombinedNamespaceContext(this, secondary)) }
PE-common/src/commonMain/kotlin/nl/adaptivity/util/xml/IterableCombinedNamespaceContext.kt
2442493028
/** * Copyright (C) 2019 SchoolPower Studio */ package com.carbonylgroup.schoolpower.activities import android.animation.AnimatorListenerAdapter import android.app.Activity import android.os.Bundle import androidx.fragment.app.Fragment import androidx.core.app.NavUtils import androidx.appcompat.widget.Toolbar import android.view.MenuItem import android.view.View import android.view.ViewAnimationUtils import android.widget.RelativeLayout import com.carbonylgroup.schoolpower.R import com.carbonylgroup.schoolpower.fragments.SettingsFragment import kotterknife.bindView private var recreated = false class SettingsActivity : BaseActivity(), SettingsFragment.SettingsCallBack { private val settingsToolBar: Toolbar by bindView(R.id.settings_toolbar) private val rootLayout: RelativeLayout by bindView(R.id.settings_root_layout) override fun onRecreate() { recreated = true setResult(Activity.RESULT_OK) recreate() } override fun initActivity() { super.initActivity() setContentView(R.layout.settings_toolbar) setSupportActionBar(settingsToolBar) supportFragmentManager.beginTransaction().replace(R.id.settings_content, SettingsFragment()).commit() supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = getString(R.string.settings) setResult(Activity.RESULT_OK) if (recreated) { rootLayout.post( { startAnimation() }) // to invoke onActivityResult to apply settings recreated = false } } private fun startAnimation() { val cx = rootLayout.width / 2 val cy = rootLayout.height / 2 val finalRadius = Math.hypot(cx.toDouble(), cy.toDouble()).toFloat() val anim = ViewAnimationUtils.createCircularReveal(rootLayout, cx, cy, 0f, finalRadius) anim.addListener(object : AnimatorListenerAdapter() {}) rootLayout.visibility = View.VISIBLE anim.start() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { NavUtils.navigateUpFromSameTask(this) return true } } return super.onOptionsItemSelected(item) } override fun onSupportNavigateUp(): Boolean { finish() return true } override fun onSaveInstanceState(outState: Bundle) { // finish setting activity to avoid java.io.NotSerializableException // com.thirtydegreesray.openhub.ui.widget.colorChooser.ColorChooserPreference // android.os.Parcel.writeSerializable(Parcel.java:1761) if (recreated) { super.onSaveInstanceState(outState) } else { finish() } } fun addFragmentOnTop(fragment: Fragment){ supportFragmentManager.beginTransaction() .add(R.id.settings_content, fragment) .addToBackStack("TAG") .commit() } }
app/src/main/java/com/carbonylgroup/schoolpower/activities/SettingsActivity.kt
3693458910
package org.fossasia.openevent.general.attendees import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.os.CountDownTimer import android.telephony.TelephonyManager import android.text.Editable import android.text.Spannable import android.text.SpannableStringBuilder import android.text.TextPaint import android.text.TextWatcher import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.Navigation.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.LinearLayoutManager import com.paypal.android.sdk.payments.PayPalConfiguration import com.paypal.android.sdk.payments.PayPalPayment import com.paypal.android.sdk.payments.PayPalService import com.paypal.android.sdk.payments.PaymentActivity import com.paypal.android.sdk.payments.PaymentConfirmation import com.paypal.android.sdk.payments.ShippingAddress import com.stripe.android.ApiResultCallback import com.stripe.android.Stripe import com.stripe.android.model.Card import com.stripe.android.model.Token import java.math.BigDecimal import java.util.Calendar import java.util.Currency import kotlin.collections.ArrayList import kotlinx.android.synthetic.main.fragment_attendee.view.accept import kotlinx.android.synthetic.main.fragment_attendee.view.acceptCheckbox import kotlinx.android.synthetic.main.fragment_attendee.view.amount import kotlinx.android.synthetic.main.fragment_attendee.view.attendeeRecycler import kotlinx.android.synthetic.main.fragment_attendee.view.attendeeScrollView import kotlinx.android.synthetic.main.fragment_attendee.view.bankRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.billingAddress import kotlinx.android.synthetic.main.fragment_attendee.view.billingAddressLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingCity import kotlinx.android.synthetic.main.fragment_attendee.view.billingCityLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingCompany import kotlinx.android.synthetic.main.fragment_attendee.view.billingCompanyLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingEnabledCheckbox import kotlinx.android.synthetic.main.fragment_attendee.view.billingInfoCheckboxSection import kotlinx.android.synthetic.main.fragment_attendee.view.billingInfoContainer import kotlinx.android.synthetic.main.fragment_attendee.view.billingPostalCode import kotlinx.android.synthetic.main.fragment_attendee.view.billingPostalCodeLayout import kotlinx.android.synthetic.main.fragment_attendee.view.billingState import kotlinx.android.synthetic.main.fragment_attendee.view.cancelButton import kotlinx.android.synthetic.main.fragment_attendee.view.cardNumber import kotlinx.android.synthetic.main.fragment_attendee.view.cardNumberLayout import kotlinx.android.synthetic.main.fragment_attendee.view.chequeRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.countryPicker import kotlinx.android.synthetic.main.fragment_attendee.view.cvc import kotlinx.android.synthetic.main.fragment_attendee.view.cvcLayout import kotlinx.android.synthetic.main.fragment_attendee.view.email import kotlinx.android.synthetic.main.fragment_attendee.view.emailLayout import kotlinx.android.synthetic.main.fragment_attendee.view.eventName import kotlinx.android.synthetic.main.fragment_attendee.view.firstName import kotlinx.android.synthetic.main.fragment_attendee.view.firstNameLayout import kotlinx.android.synthetic.main.fragment_attendee.view.helloUser import kotlinx.android.synthetic.main.fragment_attendee.view.lastName import kotlinx.android.synthetic.main.fragment_attendee.view.lastNameLayout import kotlinx.android.synthetic.main.fragment_attendee.view.loginButton import kotlinx.android.synthetic.main.fragment_attendee.view.month import kotlinx.android.synthetic.main.fragment_attendee.view.monthText import kotlinx.android.synthetic.main.fragment_attendee.view.offlinePayment import kotlinx.android.synthetic.main.fragment_attendee.view.offlinePaymentDescription import kotlinx.android.synthetic.main.fragment_attendee.view.onSiteRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.paymentOptionsGroup import kotlinx.android.synthetic.main.fragment_attendee.view.paymentSelectorContainer import kotlinx.android.synthetic.main.fragment_attendee.view.paypalRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.qty import kotlinx.android.synthetic.main.fragment_attendee.view.register import kotlinx.android.synthetic.main.fragment_attendee.view.sameBuyerCheckBox import kotlinx.android.synthetic.main.fragment_attendee.view.signInEditLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInEmail import kotlinx.android.synthetic.main.fragment_attendee.view.signInEmailLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInPassword import kotlinx.android.synthetic.main.fragment_attendee.view.signInPasswordLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signInText import kotlinx.android.synthetic.main.fragment_attendee.view.signInTextLayout import kotlinx.android.synthetic.main.fragment_attendee.view.signOut import kotlinx.android.synthetic.main.fragment_attendee.view.signOutLayout import kotlinx.android.synthetic.main.fragment_attendee.view.stripePayment import kotlinx.android.synthetic.main.fragment_attendee.view.stripeRadioButton import kotlinx.android.synthetic.main.fragment_attendee.view.taxId import kotlinx.android.synthetic.main.fragment_attendee.view.taxLayout import kotlinx.android.synthetic.main.fragment_attendee.view.taxPrice import kotlinx.android.synthetic.main.fragment_attendee.view.ticketDetails import kotlinx.android.synthetic.main.fragment_attendee.view.ticketTableDetails import kotlinx.android.synthetic.main.fragment_attendee.view.ticketsRecycler import kotlinx.android.synthetic.main.fragment_attendee.view.time import kotlinx.android.synthetic.main.fragment_attendee.view.timeoutCounterLayout import kotlinx.android.synthetic.main.fragment_attendee.view.timeoutInfoTextView import kotlinx.android.synthetic.main.fragment_attendee.view.timeoutTextView import kotlinx.android.synthetic.main.fragment_attendee.view.totalAmountLayout import kotlinx.android.synthetic.main.fragment_attendee.view.totalPrice import kotlinx.android.synthetic.main.fragment_attendee.view.year import kotlinx.android.synthetic.main.fragment_attendee.view.yearText import org.fossasia.openevent.general.BuildConfig import org.fossasia.openevent.general.ComplexBackPressFragment import org.fossasia.openevent.general.R import org.fossasia.openevent.general.auth.User import org.fossasia.openevent.general.event.Event import org.fossasia.openevent.general.event.EventId import org.fossasia.openevent.general.event.EventUtils import org.fossasia.openevent.general.order.Charge import org.fossasia.openevent.general.ticket.TicketDetailsRecyclerAdapter import org.fossasia.openevent.general.ticket.TicketId import org.fossasia.openevent.general.utils.StringUtils.getTermsAndPolicyText import org.fossasia.openevent.general.utils.Utils import org.fossasia.openevent.general.utils.Utils.isNetworkConnected import org.fossasia.openevent.general.utils.Utils.setToolbar import org.fossasia.openevent.general.utils.Utils.show import org.fossasia.openevent.general.utils.checkEmpty import org.fossasia.openevent.general.utils.checkValidEmail import org.fossasia.openevent.general.utils.extensions.nonNull import org.fossasia.openevent.general.utils.nullToEmpty import org.fossasia.openevent.general.utils.setRequired import org.jetbrains.anko.design.longSnackbar import org.jetbrains.anko.design.snackbar import org.koin.androidx.viewmodel.ext.android.viewModel private const val PAYPAL_REQUEST_CODE = 101 class AttendeeFragment : Fragment(), ComplexBackPressFragment { private lateinit var rootView: View private val attendeeViewModel by viewModel<AttendeeViewModel>() private val ticketsRecyclerAdapter: TicketDetailsRecyclerAdapter = TicketDetailsRecyclerAdapter() private val attendeeRecyclerAdapter: AttendeeRecyclerAdapter = AttendeeRecyclerAdapter() private val safeArgs: AttendeeFragmentArgs by navArgs() private lateinit var timer: CountDownTimer private lateinit var card: Card override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (attendeeViewModel.ticketIdAndQty == null) { attendeeViewModel.ticketIdAndQty = safeArgs.ticketIdAndQty?.value attendeeViewModel.singleTicket = safeArgs.ticketIdAndQty?.value?.map { it.second }?.sum() == 1 } attendeeRecyclerAdapter.setEventId(safeArgs.eventId) if (attendeeViewModel.paymentCurrency.isNotBlank()) ticketsRecyclerAdapter.setCurrency(attendeeViewModel.paymentCurrency) safeArgs.ticketIdAndQty?.value?.let { val quantities = it.map { pair -> pair.second }.filter { it != 0 } val donations = it.filter { it.second != 0 }.map { pair -> pair.third * pair.second } ticketsRecyclerAdapter.setQuantity(quantities) ticketsRecyclerAdapter.setDonations(donations) attendeeRecyclerAdapter.setQuantity(quantities) } attendeeViewModel.forms.value?.let { attendeeRecyclerAdapter.setCustomForm(it) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.fragment_attendee, container, false) setToolbar(activity, getString(R.string.attendee_details)) setHasOptionsMenu(true) attendeeViewModel.message .nonNull() .observe(viewLifecycleOwner, Observer { rootView.longSnackbar(it) }) val progressDialog = Utils.progressDialog(context, getString(R.string.creating_order_message)) attendeeViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { progressDialog.show(it) }) attendeeViewModel.redirectToProfile .observe(viewLifecycleOwner, Observer { rootView.longSnackbar(getString(R.string.verify_your_profile)) findNavController(rootView).navigate( AttendeeFragmentDirections.actionTicketsToProfile() ) }) rootView.sameBuyerCheckBox.setOnCheckedChangeListener { _, isChecked -> if (isChecked) { val firstName = rootView.firstName.text.toString() val lastName = rootView.lastName.text.toString() if (firstName.isEmpty() || lastName.isEmpty()) { rootView.longSnackbar(getString(R.string.fill_required_fields_message)) rootView.sameBuyerCheckBox.isChecked = false return@setOnCheckedChangeListener } attendeeRecyclerAdapter.setFirstAttendee( Attendee(firstname = firstName, lastname = lastName, email = rootView.email.text.toString(), id = attendeeViewModel.getId()) ) } else { attendeeRecyclerAdapter.setFirstAttendee(null) } } setupEventInfo() setupPendingOrder() setupTicketDetailTable() setupSignOutLogIn() setupAttendeeDetails() setupCustomForms() setupBillingInfo() setupCountryOptions() setupCardNumber() setupMonthOptions() setupYearOptions() setupTermsAndCondition() setupRegisterOrder() return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val attendeeDetailChangeListener = object : AttendeeDetailChangeListener { override fun onAttendeeDetailChanged(attendee: Attendee, position: Int) { attendeeViewModel.attendees[position] = attendee } } attendeeRecyclerAdapter.apply { attendeeChangeListener = attendeeDetailChangeListener } } override fun onResume() { super.onResume() if (!isNetworkConnected(context)) { rootView.attendeeScrollView.longSnackbar(getString(R.string.no_internet_connection_message)) } } override fun onDestroyView() { super.onDestroyView() attendeeRecyclerAdapter.attendeeChangeListener = null } override fun onDestroy() { super.onDestroy() if (this::timer.isInitialized) timer.cancel() activity?.stopService(Intent(activity, PayPalService::class.java)) } override fun handleBackPress() { AlertDialog.Builder(requireContext()) .setTitle(getString(R.string.cancel_order)) .setMessage(getString(R.string.cancel_order_message)) .setPositiveButton(getString(R.string.cancel_order_button)) { _, _ -> findNavController(rootView).popBackStack() }.setNeutralButton(getString(R.string.continue_order_button)) { dialog, _ -> dialog.cancel() }.create() .show() } private fun setupEventInfo() { attendeeViewModel.event .nonNull() .observe(viewLifecycleOwner, Observer { loadEventDetailsUI(it) setupPaymentOptions(it) }) attendeeViewModel.getSettings() attendeeViewModel.orderExpiryTime .nonNull() .observe(viewLifecycleOwner, Observer { setupCountDownTimer(it) }) val currentEvent = attendeeViewModel.event.value if (currentEvent == null) attendeeViewModel.loadEvent(safeArgs.eventId) else { setupPaymentOptions(currentEvent) loadEventDetailsUI(currentEvent) } rootView.register.text = if (safeArgs.amount > 0) getString(R.string.pay_now) else getString(R.string.register) } private fun setupPendingOrder() { val currentPendingOrder = attendeeViewModel.pendingOrder.value if (currentPendingOrder == null) { attendeeViewModel.initializeOrder(safeArgs.eventId) } } private fun setupCountDownTimer(orderExpiryTime: Int) { rootView.timeoutCounterLayout.isVisible = true rootView.timeoutInfoTextView.text = getString(R.string.ticket_timeout_info_message, orderExpiryTime.toString()) val timeLeft: Long = if (attendeeViewModel.timeout == -1L) orderExpiryTime * 60 * 1000L else attendeeViewModel.timeout timer = object : CountDownTimer(timeLeft, 1000) { override fun onFinish() { findNavController(rootView).navigate(AttendeeFragmentDirections .actionAttendeeToTicketPop(safeArgs.eventId, safeArgs.currency, true)) } override fun onTick(millisUntilFinished: Long) { attendeeViewModel.timeout = millisUntilFinished val minutes = millisUntilFinished / 1000 / 60 val seconds = millisUntilFinished / 1000 % 60 rootView.timeoutTextView.text = "$minutes:$seconds" } } timer.start() } private fun setupTicketDetailTable() { attendeeViewModel.ticketIdAndQty?.map { it.second }?.sum()?.let { rootView.qty.text = resources.getQuantityString(R.plurals.order_quantity_item, it, it) } rootView.ticketsRecycler.layoutManager = LinearLayoutManager(activity) rootView.ticketsRecycler.adapter = ticketsRecyclerAdapter rootView.ticketsRecycler.isNestedScrollingEnabled = false rootView.taxLayout.isVisible = safeArgs.taxAmount > 0f rootView.taxPrice.text = "${Currency.getInstance(safeArgs.currency).symbol}${"%.2f".format(safeArgs.taxAmount)}" rootView.totalAmountLayout.isVisible = safeArgs.amount > 0f rootView.totalPrice.text = "${Currency.getInstance(safeArgs.currency).symbol}${"%.2f".format(safeArgs.amount)}" rootView.ticketTableDetails.setOnClickListener { attendeeViewModel.ticketDetailsVisible = !attendeeViewModel.ticketDetailsVisible loadTicketDetailsTableUI(attendeeViewModel.ticketDetailsVisible) } loadTicketDetailsTableUI(attendeeViewModel.ticketDetailsVisible) attendeeViewModel.totalAmount.value = safeArgs.amount rootView.paymentSelectorContainer.isVisible = safeArgs.amount > 0 attendeeViewModel.tickets .nonNull() .observe(viewLifecycleOwner, Observer { tickets -> ticketsRecyclerAdapter.addAll(tickets) attendeeRecyclerAdapter.addAllTickets(tickets) }) val currentTickets = attendeeViewModel.tickets.value if (currentTickets != null) { rootView.paymentSelectorContainer.isVisible = safeArgs.amount > 0 ticketsRecyclerAdapter.addAll(currentTickets) attendeeRecyclerAdapter.addAllTickets(currentTickets) } else { attendeeViewModel.getTickets() } } private fun setupSignOutLogIn() { rootView.signInEmailLayout.setRequired() rootView.signInPasswordLayout.setRequired() rootView.firstNameLayout.setRequired() rootView.lastNameLayout.setRequired() rootView.emailLayout.setRequired() setupSignInLayout() setupUser() setupLoginSignoutClickListener() attendeeViewModel.signedIn .nonNull() .observe(viewLifecycleOwner, Observer { signedIn -> rootView.signInLayout.isVisible = !signedIn rootView.signOutLayout.isVisible = signedIn if (signedIn) { rootView.sameBuyerCheckBox.isVisible = true attendeeViewModel.loadUser() } else { attendeeViewModel.isShowingSignInText = true handleSignedOut() } }) if (attendeeViewModel.isLoggedIn()) { rootView.signInLayout.isVisible = false rootView.signOutLayout.isVisible = true rootView.sameBuyerCheckBox.isVisible = true val currentUser = attendeeViewModel.user.value if (currentUser == null) attendeeViewModel.loadUser() else loadUserUI(currentUser) } else { handleSignedOut() } } private fun handleSignedOut() { rootView.signInEditLayout.isVisible = !attendeeViewModel.isShowingSignInText rootView.signInTextLayout.isVisible = attendeeViewModel.isShowingSignInText rootView.email.setText("") rootView.firstName.setText("") rootView.lastName.setText("") rootView.sameBuyerCheckBox.isChecked = false rootView.sameBuyerCheckBox.isVisible = false } private fun setupSignInLayout() { val stringBuilder = SpannableStringBuilder() val signIn = getString(R.string.sign_in) val signInForOrderText = getString(R.string.sign_in_order_text) stringBuilder.append(signIn) stringBuilder.append(" $signInForOrderText") val signInSpan = object : ClickableSpan() { override fun onClick(widget: View) { rootView.signInTextLayout.isVisible = false rootView.signInEditLayout.isVisible = true attendeeViewModel.isShowingSignInText = false } override fun updateDrawState(ds: TextPaint) { super.updateDrawState(ds) ds.isUnderlineText = false } } stringBuilder.setSpan(signInSpan, 0, signIn.length + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) rootView.signInText.text = stringBuilder rootView.signInText.movementMethod = LinkMovementMethod.getInstance() } private fun setupLoginSignoutClickListener() { rootView.cancelButton.setOnClickListener { rootView.signInTextLayout.isVisible = true rootView.signInEditLayout.isVisible = false attendeeViewModel.isShowingSignInText = true } rootView.loginButton.setOnClickListener { var validForLogin = true validForLogin = rootView.signInEmail.checkEmpty(rootView.signInEmailLayout) && validForLogin validForLogin = rootView.signInEmail.checkValidEmail(rootView.signInEmailLayout) && validForLogin validForLogin = rootView.signInPassword.checkEmpty(rootView.signInEmailLayout) && validForLogin if (validForLogin) attendeeViewModel.login(rootView.signInEmail.text.toString(), rootView.signInPassword.text.toString()) } rootView.signOut.setOnClickListener { if (!isNetworkConnected(context)) { rootView.snackbar(getString(R.string.no_internet_connection_message)) return@setOnClickListener } attendeeViewModel.logOut() } } private fun setupUser() { attendeeViewModel.user .nonNull() .observe(viewLifecycleOwner, Observer { user -> loadUserUI(user) if (attendeeViewModel.singleTicket) { val pos = attendeeViewModel.ticketIdAndQty?.map { it.second }?.indexOf(1) val ticket = pos?.let { it1 -> attendeeViewModel.ticketIdAndQty?.get(it1)?.first?.toLong() } ?: -1 val attendee = Attendee(id = attendeeViewModel.getId(), firstname = rootView.firstName.text.toString(), lastname = rootView.lastName.text.toString(), email = rootView.email.text.toString(), ticket = TicketId(ticket), event = EventId(safeArgs.eventId)) attendeeViewModel.attendees.clear() attendeeViewModel.attendees.add(attendee) } }) } private fun setupAttendeeDetails() { rootView.attendeeRecycler.layoutManager = LinearLayoutManager(activity) rootView.attendeeRecycler.adapter = attendeeRecyclerAdapter rootView.attendeeRecycler.isNestedScrollingEnabled = false if (attendeeViewModel.attendees.isEmpty()) { attendeeViewModel.ticketIdAndQty?.let { it.forEach { pair -> repeat(pair.second) { attendeeViewModel.attendees.add(Attendee( id = attendeeViewModel.getId(), firstname = "", lastname = "", email = "", ticket = TicketId(pair.first.toLong()), event = EventId(safeArgs.eventId) )) } } } } attendeeRecyclerAdapter.addAllAttendees(attendeeViewModel.attendees) } private fun setupCustomForms() { attendeeViewModel.forms .nonNull() .observe(viewLifecycleOwner, Observer { attendeeRecyclerAdapter.setCustomForm(it) }) val currentForms = attendeeViewModel.forms.value if (currentForms == null) { attendeeViewModel.getCustomFormsForAttendees(safeArgs.eventId) } else { attendeeRecyclerAdapter.setCustomForm(currentForms) } } private fun setupBillingInfo() { rootView.billingInfoCheckboxSection.isVisible = safeArgs.amount > 0 rootView.billingCompanyLayout.setRequired() rootView.billingAddressLayout.setRequired() rootView.billingCityLayout.setRequired() rootView.billingPostalCodeLayout.setRequired() rootView.billingInfoContainer.isVisible = rootView.billingEnabledCheckbox.isChecked attendeeViewModel.billingEnabled = rootView.billingEnabledCheckbox.isChecked rootView.billingEnabledCheckbox.setOnCheckedChangeListener { _, isChecked -> attendeeViewModel.billingEnabled = isChecked rootView.billingInfoContainer.isVisible = isChecked } } private fun setupCountryOptions() { ArrayAdapter.createFromResource( requireContext(), R.array.country_arrays, android.R.layout.simple_spinner_dropdown_item ).also { adapter -> rootView.countryPicker.adapter = adapter if (attendeeViewModel.countryPosition == -1) autoSetCurrentCountry() else rootView.countryPicker.setSelection(attendeeViewModel.countryPosition) } rootView.countryPicker.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) { /*Do nothing*/ } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { attendeeViewModel.countryPosition = position } } } private fun setupPaymentOptions(event: Event) { rootView.paypalRadioButton.isVisible = event.canPayByPaypal rootView.stripeRadioButton.isVisible = event.canPayByStripe rootView.chequeRadioButton.isVisible = event.canPayByCheque rootView.bankRadioButton.isVisible = event.canPayByBank rootView.onSiteRadioButton.isVisible = event.canPayOnsite rootView.paymentOptionsGroup.setOnCheckedChangeListener { _, checkedId -> when (checkedId) { R.id.stripeRadioButton -> { rootView.stripePayment.isVisible = true rootView.offlinePayment.isVisible = false attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_STRIPE rootView.register.text = getString(R.string.pay_now) } R.id.onSiteRadioButton -> { rootView.offlinePayment.isVisible = true rootView.stripePayment.isVisible = false rootView.offlinePaymentDescription.text = event.onsiteDetails attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_ONSITE rootView.register.text = getString(R.string.register) } R.id.bankRadioButton -> { rootView.offlinePayment.isVisible = true rootView.stripePayment.isVisible = false rootView.offlinePaymentDescription.text = event.bankDetails attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_BANK rootView.register.text = getString(R.string.register) } R.id.chequeRadioButton -> { rootView.offlinePayment.isVisible = true rootView.stripePayment.isVisible = false rootView.offlinePaymentDescription.text = event.chequeDetails attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_CHEQUE rootView.register.text = getString(R.string.register) } else -> { rootView.stripePayment.isVisible = false rootView.offlinePayment.isVisible = false attendeeViewModel.selectedPaymentMode = PAYMENT_MODE_PAYPAL rootView.register.text = getString(R.string.pay_now) } } } } private fun setupCardNumber() { rootView.cardNumberLayout.setRequired() rootView.cvcLayout.setRequired() rootView.cardNumber.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) { /*Do Nothing*/ } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { /*Do Nothing*/ } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (s != null) { val cardType = Utils.getCardType(s.toString()) if (cardType == Utils.cardType.NONE) { rootView.cardNumberLayout.error = getString(R.string.invalid_card_number_message) return } } rootView.cardNumber.error = null } }) attendeeViewModel.stripeOrderMade .nonNull() .observe(viewLifecycleOwner, Observer { if (it && this::card.isInitialized) sendToken(card) }) attendeeViewModel.paypalOrderMade .nonNull() .observe(viewLifecycleOwner, Observer { startPaypalPayment() }) } private fun setupMonthOptions() { val month = mutableListOf( getString(R.string.month_string), getString(R.string.january), getString(R.string.february), getString(R.string.march), getString(R.string.april), getString(R.string.may), getString(R.string.june), getString(R.string.july), getString(R.string.august), getString(R.string.september), getString(R.string.october), getString(R.string.november), getString(R.string.december) ) rootView.month.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, month) rootView.month.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { /* Do nothing */ } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { attendeeViewModel.monthSelectedPosition = p2 rootView.monthText.text = month[p2] } } rootView.monthText.setOnClickListener { rootView.month.performClick() } rootView.month.setSelection(attendeeViewModel.monthSelectedPosition) } private fun setupYearOptions() { val year = ArrayList<String>() val currentYear = Calendar.getInstance().get(Calendar.YEAR) val a = currentYear + 20 for (i in currentYear..a) { year.add(i.toString()) } rootView.year.adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, year) rootView.year.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { /* Do nothing */ } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, pos: Int, p3: Long) { attendeeViewModel.yearSelectedPosition = pos rootView.yearText.text = year[pos] } } rootView.yearText.setOnClickListener { rootView.year.performClick() } rootView.year.setSelection(attendeeViewModel.yearSelectedPosition) } private fun setupTermsAndCondition() { rootView.accept.text = getTermsAndPolicyText(requireContext(), resources) rootView.accept.movementMethod = LinkMovementMethod.getInstance() } private fun checkPaymentOptions(): Boolean = when (attendeeViewModel.selectedPaymentMode) { PAYMENT_MODE_STRIPE -> { card = Card.create(rootView.cardNumber.text.toString(), attendeeViewModel.monthSelectedPosition, rootView.year.selectedItem.toString().toInt(), rootView.cvc.text.toString()) if (!card.validateCard()) { rootView.snackbar(getString(R.string.invalid_card_data_message)) false } else { true } } PAYMENT_MODE_CHEQUE, PAYMENT_MODE_ONSITE, PAYMENT_MODE_FREE, PAYMENT_MODE_BANK, PAYMENT_MODE_PAYPAL -> true else -> { rootView.snackbar(getString(R.string.select_payment_option_message)) false } } private fun startPaypalPayment() { val paypalEnvironment = if (BuildConfig.DEBUG) PayPalConfiguration.ENVIRONMENT_SANDBOX else PayPalConfiguration.ENVIRONMENT_PRODUCTION val paypalConfig = PayPalConfiguration() .environment(paypalEnvironment) .clientId(BuildConfig.PAYPAL_CLIENT_ID) val paypalIntent = Intent(activity, PaymentActivity::class.java) paypalIntent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig) activity?.startService(paypalIntent) val paypalPayment = paypalThingsToBuy(PayPalPayment.PAYMENT_INTENT_SALE) val payeeEmail = attendeeViewModel.event.value?.paypalEmail ?: "" paypalPayment.payeeEmail(payeeEmail) addShippingAddress(paypalPayment) val intent = Intent(activity, PaymentActivity::class.java) intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, paypalConfig) intent.putExtra(PaymentActivity.EXTRA_PAYMENT, paypalPayment) startActivityForResult(intent, PAYPAL_REQUEST_CODE) } private fun addShippingAddress(paypalPayment: PayPalPayment) { if (rootView.billingEnabledCheckbox.isChecked) { val shippingAddress = ShippingAddress() .recipientName("${rootView.firstName.text} ${rootView.lastName.text}") .line1(rootView.billingAddress.text.toString()) .city(rootView.billingCity.text.toString()) .state(rootView.billingState.text.toString()) .postalCode(rootView.billingPostalCode.text.toString()) .countryCode(getCountryCodes(rootView.countryPicker.selectedItem.toString())) paypalPayment.providedShippingAddress(shippingAddress) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PAYPAL_REQUEST_CODE && resultCode == Activity.RESULT_OK) { val paymentConfirm = data?.getParcelableExtra<PaymentConfirmation>(PaymentActivity.EXTRA_RESULT_CONFIRMATION) if (paymentConfirm != null) { val paymentId = paymentConfirm.proofOfPayment.paymentId attendeeViewModel.sendPaypalConfirm(paymentId) } } } private fun paypalThingsToBuy(paymentIntent: String): PayPalPayment = PayPalPayment(BigDecimal(safeArgs.amount.toString()), Currency.getInstance(safeArgs.currency).currencyCode, getString(R.string.tickets_for, attendeeViewModel.event.value?.name), paymentIntent) private fun checkRequiredFields(): Boolean { val checkBasicInfo = rootView.firstName.checkEmpty(rootView.firstNameLayout) && rootView.lastName.checkEmpty(rootView.lastNameLayout) && rootView.email.checkEmpty(rootView.emailLayout) var checkBillingInfo = true if (rootView.billingEnabledCheckbox.isChecked) { checkBillingInfo = rootView.billingCompany.checkEmpty(rootView.billingCompanyLayout) && checkBillingInfo checkBillingInfo = rootView.billingAddress.checkEmpty(rootView.billingAddressLayout) && checkBillingInfo checkBillingInfo = rootView.billingCity.checkEmpty(rootView.billingCityLayout) && checkBillingInfo checkBillingInfo = rootView.billingPostalCode.checkEmpty(rootView.billingPostalCodeLayout) && checkBillingInfo } var checkStripeInfo = true if (safeArgs.amount != 0F && attendeeViewModel.selectedPaymentMode == PAYMENT_MODE_STRIPE) { checkStripeInfo = rootView.cardNumber.checkEmpty(rootView.cardNumberLayout) && rootView.cvc.checkEmpty(rootView.cvcLayout) } return checkAttendeesInfo() && checkBasicInfo && checkBillingInfo && checkStripeInfo } private fun checkAttendeesInfo(): Boolean { var valid = true for (pos in 0..attendeeRecyclerAdapter.itemCount) { val viewHolderItem = rootView.attendeeRecycler.findViewHolderForAdapterPosition(pos) if (viewHolderItem is AttendeeViewHolder) { if (!viewHolderItem.checkValidFields()) valid = false } } return valid } private fun setupRegisterOrder() { rootView.register.setOnClickListener { val currentUser = attendeeViewModel.user.value if (currentUser == null) { rootView.longSnackbar(getString(R.string.sign_in_to_order_ticket)) return@setOnClickListener } if (!isNetworkConnected(context)) { rootView.attendeeScrollView.longSnackbar(getString(R.string.no_internet_connection_message)) return@setOnClickListener } if (!rootView.acceptCheckbox.isChecked) { rootView.attendeeScrollView.longSnackbar(getString(R.string.term_and_conditions)) return@setOnClickListener } if (!checkRequiredFields()) { rootView.snackbar(R.string.fill_required_fields_message) return@setOnClickListener } if (attendeeViewModel.totalAmount.value != 0F && !checkPaymentOptions()) return@setOnClickListener val attendees = attendeeViewModel.attendees if (attendeeViewModel.areAttendeeEmailsValid(attendees)) { val country = rootView.countryPicker.selectedItem.toString() val paymentOption = if (safeArgs.amount != 0F) attendeeViewModel.selectedPaymentMode else PAYMENT_MODE_FREE val company = rootView.billingCompany.text.toString() val city = rootView.billingCity.text.toString() val state = rootView.billingState.text.toString() val taxId = rootView.taxId.text.toString() val address = rootView.billingAddress.text.toString() val postalCode = rootView.billingPostalCode.text.toString() attendeeViewModel.createAttendees(attendees, country, company, taxId, address, city, postalCode, state, paymentOption) } else { rootView.attendeeScrollView.longSnackbar(getString(R.string.invalid_email_address_message)) } } attendeeViewModel.ticketSoldOut .nonNull() .observe(viewLifecycleOwner, Observer { showTicketSoldOutDialog(it) }) attendeeViewModel.orderCompleted .nonNull() .observe(viewLifecycleOwner, Observer { if (it) openOrderCompletedFragment() }) } private fun showTicketSoldOutDialog(show: Boolean) { if (show) { val builder = AlertDialog.Builder(requireContext()) builder.setMessage(getString(R.string.tickets_sold_out)) .setPositiveButton(getString(R.string.ok)) { dialog, _ -> dialog.cancel() } builder.show() } } private fun sendToken(card: Card) { Stripe(requireContext(), BuildConfig.STRIPE_API_KEY) .createCardToken(card = card, callback = object : ApiResultCallback<Token> { override fun onSuccess(token: Token) { val charge = Charge(attendeeViewModel.getId().toInt(), token.id, null) attendeeViewModel.chargeOrder(charge) } override fun onError(error: Exception) { rootView.snackbar(error.localizedMessage.toString()) } }) } private fun loadEventDetailsUI(event: Event) { val startsAt = EventUtils.getEventDateTime(event.startsAt, event.timezone) val endsAt = EventUtils.getEventDateTime(event.endsAt, event.timezone) attendeeViewModel.paymentCurrency = Currency.getInstance(event.paymentCurrency).symbol ticketsRecyclerAdapter.setCurrency(attendeeViewModel.paymentCurrency) rootView.eventName.text = event.name val total = if (safeArgs.amount > 0) "${attendeeViewModel.paymentCurrency} ${"%.2f".format(safeArgs.amount)}" else getString(R.string.free) rootView.amount.text = getString(R.string.total_amount, total) rootView.time.text = EventUtils.getFormattedDateTimeRangeDetailed(startsAt, endsAt) } private fun loadUserUI(user: User) { rootView.helloUser.text = getString(R.string.hello_user, user.firstName.nullToEmpty()) rootView.firstName.text = SpannableStringBuilder(user.firstName.nullToEmpty()) rootView.lastName.text = SpannableStringBuilder(user.lastName.nullToEmpty()) rootView.email.text = SpannableStringBuilder(user.email.nullToEmpty()) rootView.firstName.isEnabled = user.firstName.isNullOrEmpty() rootView.lastName.isEnabled = user.lastName.isNullOrEmpty() rootView.email.isEnabled = false } private fun loadTicketDetailsTableUI(show: Boolean) { if (show) { rootView.ticketDetails.isVisible = true rootView.ticketTableDetails.text = context?.getString(R.string.hide) } else { rootView.ticketDetails.isVisible = false rootView.ticketTableDetails.text = context?.getString(R.string.view) } } private fun openOrderCompletedFragment() { attendeeViewModel.orderCompleted.value = false findNavController(rootView).navigate(AttendeeFragmentDirections .actionAttendeeToOrderCompleted(safeArgs.eventId)) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { activity?.onBackPressed() true } else -> super.onOptionsItemSelected(item) } } private fun autoSetCurrentCountry() { val telephonyManager: TelephonyManager = activity?.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager val currentCountryCode = telephonyManager.networkCountryIso val countryCodes = resources.getStringArray(R.array.country_code_arrays) val countryIndex = countryCodes.indexOf(currentCountryCode.toUpperCase()) if (countryIndex != -1) rootView.countryPicker.setSelection(countryIndex) } private fun getCountryCodes(countryName: String): String { val countryCodes = resources.getStringArray(R.array.country_code_arrays) val countryList = resources.getStringArray(R.array.country_arrays) val index = countryList.indexOf(countryName) return countryCodes[index] } }
app/src/main/java/org/fossasia/openevent/general/attendees/AttendeeFragment.kt
2568475636
package app.youkai.data.models import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.github.jasminb.jsonapi.Links import com.github.jasminb.jsonapi.annotations.Relationship import com.github.jasminb.jsonapi.annotations.RelationshipLinks import com.github.jasminb.jsonapi.annotations.Type @Type("castings") @JsonIgnoreProperties(ignoreUnknown = true) class Casting : BaseJsonModel(JsonType("castings")) { companion object FieldNames { val ROLE = "role" val VOICE_ACTOR = "voiceActor" val FEATURED = "featured" val LANGUAGE = "language" val PERSON = "person" val MEDIA = "media" val CHARACTER = "character" } var role: String? = null @JsonProperty("voiceActor") var isVoiceActor: Boolean? = null var featured: Boolean? = null var language: String? = null @Relationship("person") var person: Person? = null @RelationshipLinks("person") var personLinks: Links? = null @Relationship("media") var media: BaseMedia? = null @RelationshipLinks("media") var mediaLinks: Links? = null @Relationship("character") var character: Character? = null @RelationshipLinks("character") var characterLinks: Links? = null }
app/src/main/kotlin/app/youkai/data/models/Casting.kt
4265833275
/* * Copyright 2019 Johannes Donath <[email protected]> * 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 org.basinmc.sink import org.apache.logging.log4j.LogManager import java.io.IOException import java.util.* /** * @author [Johannes Donath](mailto:[email protected]) */ object SinkVersion { val version: String val guava: String val log4j: String val commonsLang: String val gson: String val netty: String val findbugs: String init { val p = Properties() try { SinkVersion::class.java .getResourceAsStream("/sink-version.properties") .use(p::load) } catch (ex: IOException) { LogManager.getLogger(SinkVersion::class.java) .error("Could not load Sink version information: " + ex.message, ex) } version = p.getProperty("sink.version", "0.0.0") guava = p.getProperty("dependency.guava.version", "0.0.0") log4j = p.getProperty("dependency.log4j.version", "0.0.0") commonsLang = p.getProperty("dependency.commons.lang.version", "0.0.0") gson = p.getProperty("dependency.gson.version", "0.0.0") netty = p.getProperty("dependency.netty.version", "0.0.0") findbugs = p.getProperty("dependency.findbugs.version", "0.0.0") } }
sink/src/main/kotlin/org/basinmc/sink/SinkVersion.kt
1005382051
/* * Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.json.serializers import kotlinx.serialization.json.* import kotlinx.serialization.test.assertFailsWithSerialMessage import kotlinx.serialization.test.assertStringFormAndRestored import kotlin.test.* class JsonNullSerializerTest : JsonTestBase() { @Test fun testJsonNull() = parametrizedTest(default) { assertStringFormAndRestored("{\"element\":null}", JsonNullWrapper(JsonNull), JsonNullWrapper.serializer()) } @Test fun testJsonNullFailure() = parametrizedTest(default) { assertFailsWithSerialMessage("JsonDecodingException", "'null' literal") { default.decodeFromString(JsonNullWrapper.serializer(), "{\"element\":\"foo\"}", JsonTestingMode.STREAMING) } } @Test fun testJsonNullAsElement() = parametrizedTest(default) { assertStringFormAndRestored("{\"element\":null}", JsonElementWrapper(JsonNull), JsonElementWrapper.serializer()) } @Test fun testJsonNullAsPrimitive() = parametrizedTest(default) { assertStringFormAndRestored("{\"primitive\":null}", JsonPrimitiveWrapper(JsonNull), JsonPrimitiveWrapper.serializer()) } @Test fun testTopLevelJsonNull() = parametrizedTest { jsonTestingMode -> val string = default.encodeToString(JsonNull.serializer(), JsonNull, jsonTestingMode) assertEquals("null", string) assertEquals(JsonNull, default.decodeFromString(JsonNull.serializer(), string, jsonTestingMode)) } @Test fun testTopLevelJsonNullAsElement() = parametrizedTest { jsonTestingMode -> val string = default.encodeToString(JsonElement.serializer(), JsonNull, jsonTestingMode) assertEquals("null", string) assertEquals(JsonNull, default.decodeFromString(JsonElement.serializer(), string, jsonTestingMode)) } @Test fun testTopLevelJsonNullAsPrimitive() = parametrizedTest { jsonTestingMode -> val string = default.encodeToString(JsonPrimitive.serializer(), JsonNull, jsonTestingMode) assertEquals("null", string) assertEquals(JsonNull, default.decodeFromString(JsonPrimitive.serializer(), string, jsonTestingMode)) } @Test fun testJsonNullToString() { val string = default.encodeToString(JsonPrimitive.serializer(), JsonNull) assertEquals(string, JsonNull.toString()) } }
formats/json-tests/commonTest/src/kotlinx/serialization/json/serializers/JsonNullSerializerTest.kt
2724256734
/* * 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.packet.type.play import org.lanternpowered.api.effect.sound.SoundCategory import org.lanternpowered.server.network.packet.Packet import org.spongepowered.math.vector.Vector3d data class SoundEffectPacket( val type: Int, val position: Vector3d, val category: SoundCategory, val volume: Float, val pitch: Float ) : Packet
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/type/play/SoundEffectPacket.kt
3879938170
/* * 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.state import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import com.google.common.collect.ImmutableTable import com.google.common.collect.Lists import org.lanternpowered.api.catalog.CatalogType import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.api.key.namespacedKey import org.lanternpowered.api.registry.CatalogTypeRegistry import org.lanternpowered.api.util.collections.immutableMapBuilderOf import org.lanternpowered.api.util.collections.immutableMapOf import org.lanternpowered.api.util.collections.immutableSetBuilderOf import org.lanternpowered.api.util.collections.immutableSetOf import org.lanternpowered.api.util.collections.toImmutableList import org.lanternpowered.api.util.uncheckedCast import org.spongepowered.api.data.Key import org.spongepowered.api.data.persistence.DataContainer import org.spongepowered.api.data.persistence.DataQuery import org.spongepowered.api.data.persistence.DataView import org.spongepowered.api.data.value.Value import org.spongepowered.api.state.State import org.spongepowered.api.state.StateContainer import org.spongepowered.api.state.StateProperty import java.util.LinkedHashMap import java.util.Optional abstract class AbstractStateContainer<S : State<S>>( baseKey: NamespacedKey, stateProperties: Iterable<StateProperty<*>>, constructor: (StateBuilder<S>) -> S ) : StateContainer<S> { // The lookup to convert between key <--> state property val keysToProperty: ImmutableMap<Key<out Value<*>>, StateProperty<*>> private val validStates: ImmutableList<S> init { val properties = stateProperties.toMutableList() properties.sortBy { property -> property.getName() } val keysToPropertyBuilder = immutableMapBuilderOf<Key<out Value<*>>, StateProperty<*>>() for (property in properties) keysToPropertyBuilder.put((property as IStateProperty<*,*>).valueKey, property) this.keysToProperty = keysToPropertyBuilder.build() val cartesianProductInput = properties.map { property -> property.getPossibleValues().map { comparable -> @Suppress("UNCHECKED_CAST") val valueKey = (property as IStateProperty<*,*>).valueKey as Key<Value<Any>> val value = Value.immutableOf(valueKey, comparable as Any).asImmutable() Triple(property, comparable, value) } } val cartesianProduct = Lists.cartesianProduct(cartesianProductInput) val stateBuilders = mutableListOf<LanternStateBuilder<S>>() // A map with as the key the property values map and as value the state val stateByValuesMap = LinkedHashMap<Map<*, *>, S>() for ((internalId, list) in cartesianProduct.withIndex()) { val stateValuesBuilder = immutableMapBuilderOf<StateProperty<*>, Comparable<*>>() val immutableValuesBuilder = immutableSetBuilderOf<Value.Immutable<*>>() for ((property, comparable, value) in list) { stateValuesBuilder.put(property, comparable) immutableValuesBuilder.add(value) } val stateValues = stateValuesBuilder.build() val immutableValues = immutableValuesBuilder.build() val key = this.buildKey(baseKey, stateValues) val dataContainer = this.buildDataContainer(baseKey, stateValues) @Suppress("LeakingThis") stateBuilders += LanternStateBuilder(key, dataContainer, this, stateValues, immutableValues, internalId) } // There are no properties, so just add // the single state of this container if (properties.isEmpty()) { val dataContainer = this.buildDataContainer(baseKey, immutableMapOf()) @Suppress("LeakingThis") stateBuilders += LanternStateBuilder(baseKey, dataContainer, this, immutableMapOf(), immutableSetOf(), 0) } this.validStates = stateBuilders.map { val state = constructor(it) stateByValuesMap[it.stateValues] = state state }.toImmutableList() for (state in this.validStates) { val tableBuilder = ImmutableTable.builder<StateProperty<*>, Comparable<*>, S>() for (property in properties) { @Suppress("UNCHECKED_CAST") property as StateProperty<Comparable<Comparable<*>>> for (value in property.possibleValues) { if (value == state.getStateProperty(property).get()) continue val valueByProperty = HashMap<StateProperty<*>, Any>(state.statePropertyMap) valueByProperty[property] = value tableBuilder.put(property, value, checkNotNull(stateByValuesMap[valueByProperty])) } } @Suppress("UNCHECKED_CAST") (state as AbstractState<S,*>).propertyValueTable = tableBuilder.build() } // Call the completion for (stateBuilder in stateBuilders) { stateBuilder.whenCompleted.forEach { it() } } } companion object { private val NAME = DataQuery.of("Name") private val PROPERTIES = DataQuery.of("Properties") fun <T, S : State<S>> deserializeState(dataView: DataView, registry: CatalogTypeRegistry<T>): S where T : CatalogType, T : StateContainer<S> { val id = dataView.getString(NAME).get() val catalogType = registry.require(NamespacedKey.resolve(id)) var state = catalogType.defaultState val properties = dataView.getView(PROPERTIES).orElse(null) if (properties != null) { for ((key, rawValue) in properties.getValues(false)) { val stateProperty = state.getStatePropertyByName(key.toString()).orElse(null) if (stateProperty != null) { val value = stateProperty.parseValue(rawValue.toString()).orElse(null) if (value != null) { @Suppress("UNCHECKED_CAST") stateProperty as StateProperty<Comparable<Comparable<*>>> val newState = state.withStateProperty(stateProperty, value.uncheckedCast()).orElse(null) if (newState != null) { state = newState } } } } } return state } } private fun buildDataContainer(baseKey: NamespacedKey, values: Map<StateProperty<*>, Comparable<*>>): DataContainer { val dataContainer = DataContainer.createNew(DataView.SafetyMode.NO_DATA_CLONED) dataContainer[NAME] = baseKey.toString() if (values.isEmpty()) return dataContainer val propertiesView = dataContainer.createView(PROPERTIES) for ((property, comparable) in values) { propertiesView[DataQuery.of(property.getName())] = comparable } return dataContainer } private fun buildKey(baseKey: NamespacedKey, values: Map<StateProperty<*>, Comparable<*>>): NamespacedKey { if (values.isEmpty()) return baseKey val builder = StringBuilder() builder.append(baseKey.value).append('[') val propertyValues = mutableListOf<String>() for ((property, comparable) in values) { val value = if (comparable is Enum) comparable.name else comparable.toString() propertyValues.add(property.getName() + '=' + value.toLowerCase()) } builder.append(propertyValues.joinToString(separator = ",")) builder.append(']') return namespacedKey(baseKey.namespace, builder.toString()) } override fun getValidStates(): ImmutableList<S> = this.validStates override fun getDefaultState(): S = this.validStates[0] override fun getStateProperties(): Collection<StateProperty<*>> = this.keysToProperty.values override fun getStatePropertyByName(statePropertyId: String): Optional<StateProperty<*>> = this.defaultState.getStatePropertyByName(statePropertyId) }
src/main/kotlin/org/lanternpowered/server/state/AbstractStateContainer.kt
977521885
package i_introduction._9_Extension_Functions import util.TODO import util.doc9 fun String.lastChar() = this.get(this.length - 1) // 'this' can be omitted fun String.lastChar1() = get(length - 1) fun use() { // try Ctrl+Space "default completion" after the dot: lastChar() is visible "abc".lastChar() } // 'lastChar' is compiled to a static function in the class ExtensionFunctionsKt (see JavaCode9.useExtension) fun todoTask9(): Nothing = TODO( """ Task 9. Implement the extension functions Int.r(), Pair<Int, Int>.r() to support the following manner of creating rational numbers: 1.r(), Pair(1, 2).r() """, documentation = doc9(), references = { 1.r(); Pair(1, 2).r(); RationalNumber(1, 9) }) data class RationalNumber(val numerator: Int, val denominator: Int) fun Int.r(): RationalNumber = RationalNumber(numerator = this, denominator = 1) fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(numerator = this.first, denominator = this.second)
src/i_introduction/_9_Extension_Functions/ExtensionFunctions.kt
363941105
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.widget import android.content.Context import android.os.Build import android.support.v7.preference.Preference import android.support.v7.preference.PreferenceViewHolder import android.util.AttributeSet import android.widget.Switch import org.mozilla.focus.R import org.mozilla.focus.telemetry.TelemetryWrapper import org.mozilla.focus.utils.Browsers import org.mozilla.focus.utils.SupportUtils class DefaultBrowserPreference : Preference { private var switchView: Switch? = null // Instantiated from XML constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) // Instantiated from XML constructor(context: Context, attrs: AttributeSet) : super(context, attrs) init { widgetLayoutResource = R.layout.preference_default_browser val appName = context.resources.getString(R.string.app_name) val title = context.resources.getString(R.string.preference_default_browser2, appName) setTitle(title) } override fun onBindViewHolder(holder: PreferenceViewHolder) { super.onBindViewHolder(holder) switchView = holder.findViewById(R.id.switch_widget) as Switch update() } fun update() { if (switchView != null) { val browsers = Browsers(context, Browsers.TRADITIONAL_BROWSER_URL) switchView?.isChecked = browsers.isDefaultBrowser(context) } } public override fun onClick() { val context = context if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { SupportUtils.openDefaultAppsSettings(context) TelemetryWrapper.makeDefaultBrowserSettings() } else { SupportUtils.openDefaultBrowserSumoPage(context) } } }
app/src/main/java/org/mozilla/focus/widget/DefaultBrowserPreference.kt
2449409933
/* * Copyright (c) 2016. Sunghyouk Bae <[email protected]> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package debop4k.core.io.serializers /** * 직렬화 인스턴스를 제공합니다. * * @author [email protected] */ object Serializers { /** Binary Serializer */ @JvmField val BINARY = BinarySerializer() /** FST Serializer for Java 6 */ @JvmField val FST = FstSerializer() /** Deflater + Binary Serializer */ @JvmField val DEFLATER_BINARY = DeflaterBinarySerializer() /** Deflater + FST Serializer */ @JvmField val DEFLATER_FST = DeflaterFstSerializer() /** GZip + Binary Serializer */ @JvmField val GZIP_BINARY = GZipBinarySerializer() /** GZip + FST Serializer */ @JvmField val GZIP_FST = GZipFstSerializer() /** LZ4 + Binary Serializer */ @JvmField val LZ4_BINARY = LZ4BinarySerializer() /** LZ4 + FST Serializer */ @JvmField val LZ4_FST = LZ4FstSerializer() /** SNAPPY + Binary Serializer */ @JvmField val SNAPPY_BINARY = SnappyBinarySerializer() /** SNAPPY + FST Serializer */ @JvmField val SNAPPY_FST_JAVA6 = SnappyFstSerializer() }
debop4k-core/src/main/kotlin/debop4k/core/io/serializers/Serializers.kt
1265836386
package voice.data.repo.internals.migrations import android.annotation.SuppressLint import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import com.squareup.anvil.annotations.ContributesMultibinding import org.json.JSONObject import voice.common.AppScope import voice.data.repo.internals.moveToNextLoop import javax.inject.Inject // tables private const val TABLE_BOOK = "tableBooks" private const val TABLE_CHAPTERS = "tableChapters" private const val TABLE_BOOKMARKS = "tableBookmarks" private const val BOOK_ID = "bookId" private const val BOOK_NAME = "bookName" private const val BOOK_AUTHOR = "bookAuthor" private const val BOOK_CURRENT_MEDIA_PATH = "bookCurrentMediaPath" private const val BOOK_PLAYBACK_SPEED = "bookSpeed" private const val BOOK_ROOT = "bookRoot" private const val BOOK_TIME = "bookTime" private const val BOOK_TYPE = "bookType" private const val BOOK_USE_COVER_REPLACEMENT = "bookUseCoverReplacement" private const val BOOK_ACTIVE = "BOOK_ACTIVE" // chapter keys private const val CHAPTER_DURATION = "chapterDuration" private const val CHAPTER_NAME = "chapterName" private const val CHAPTER_PATH = "chapterPath" // bookmark keys private const val BOOKMARK_TIME = "bookmarkTime" private const val BOOKMARK_PATH = "bookmarkPath" private const val BOOKMARK_TITLE = "bookmarkTitle" private const val CREATE_TABLE_BOOK = """ CREATE TABLE $TABLE_BOOK ( $BOOK_ID INTEGER PRIMARY KEY AUTOINCREMENT, $BOOK_NAME TEXT NOT NULL, $BOOK_AUTHOR TEXT, $BOOK_CURRENT_MEDIA_PATH TEXT NOT NULL, $BOOK_PLAYBACK_SPEED REAL NOT NULL, $BOOK_ROOT TEXT NOT NULL, $BOOK_TIME INTEGER NOT NULL, $BOOK_TYPE TEXT NOT NULL, $BOOK_USE_COVER_REPLACEMENT INTEGER NOT NULL, $BOOK_ACTIVE INTEGER NOT NULL DEFAULT 1 ) """ private const val CREATE_TABLE_CHAPTERS = """ CREATE TABLE $TABLE_CHAPTERS ( $CHAPTER_DURATION INTEGER NOT NULL, $CHAPTER_NAME TEXT NOT NULL, $CHAPTER_PATH TEXT NOT NULL, $BOOK_ID INTEGER NOT NULL, FOREIGN KEY ($BOOK_ID) REFERENCES $TABLE_BOOK($BOOK_ID) ) """ private const val CREATE_TABLE_BOOKMARKS = """ CREATE TABLE $TABLE_BOOKMARKS ( $BOOKMARK_PATH TEXT NOT NULL, $BOOKMARK_TITLE TEXT NOT NULL, $BOOKMARK_TIME INTEGER NOT NULL, $BOOK_ID INTEGER NOT NULL, FOREIGN KEY ($BOOK_ID) REFERENCES $TABLE_BOOK($BOOK_ID) ) """ @ContributesMultibinding( scope = AppScope::class, boundType = Migration::class, ) @SuppressLint("Recycle") class Migration29to30 @Inject constructor() : IncrementalMigration(29) { override fun migrate(db: SupportSQLiteDatabase) { // fetching old contents val cursor = db.query( "TABLE_BOOK", arrayOf("BOOK_JSON", "BOOK_ACTIVE"), ) val bookContents = ArrayList<String>(cursor.count) val activeMapping = ArrayList<Boolean>(cursor.count) cursor.moveToNextLoop { bookContents.add(cursor.getString(0)) activeMapping.add(cursor.getInt(1) == 1) } db.execSQL("DROP TABLE TABLE_BOOK") // drop tables in case they exist db.execSQL("DROP TABLE IF EXISTS $TABLE_BOOK") db.execSQL("DROP TABLE IF EXISTS $TABLE_CHAPTERS") db.execSQL("DROP TABLE IF EXISTS $TABLE_BOOKMARKS") // create new tables db.execSQL(CREATE_TABLE_BOOK) db.execSQL(CREATE_TABLE_CHAPTERS) db.execSQL(CREATE_TABLE_BOOKMARKS) for (i in bookContents.indices) { val bookJson = bookContents[i] val bookActive = activeMapping[i] val bookObj = JSONObject(bookJson) val bookmarks = bookObj.getJSONArray("bookmarks") val chapters = bookObj.getJSONArray("chapters") val currentMediaPath = bookObj.getString("currentMediaPath") val bookName = bookObj.getString("name") val speed = bookObj.getDouble("playbackSpeed").toFloat() val root = bookObj.getString("root") val time = bookObj.getInt("time") val type = bookObj.getString("type") val useCoverReplacement = bookObj.getBoolean("useCoverReplacement") val bookCV = ContentValues() bookCV.put(BOOK_CURRENT_MEDIA_PATH, currentMediaPath) bookCV.put(BOOK_NAME, bookName) bookCV.put(BOOK_PLAYBACK_SPEED, speed) bookCV.put(BOOK_ROOT, root) bookCV.put(BOOK_TIME, time) bookCV.put(BOOK_TYPE, type) bookCV.put(BOOK_USE_COVER_REPLACEMENT, if (useCoverReplacement) 1 else 0) bookCV.put(BOOK_ACTIVE, if (bookActive) 1 else 0) val bookId = db.insert(TABLE_BOOK, SQLiteDatabase.CONFLICT_FAIL, bookCV) for (j in 0 until chapters.length()) { val chapter = chapters.getJSONObject(j) val chapterDuration = chapter.getInt("duration") val chapterName = chapter.getString("name") val chapterPath = chapter.getString("path") val chapterCV = ContentValues() chapterCV.put(CHAPTER_DURATION, chapterDuration) chapterCV.put(CHAPTER_NAME, chapterName) chapterCV.put(CHAPTER_PATH, chapterPath) chapterCV.put(BOOK_ID, bookId) db.insert(TABLE_CHAPTERS, SQLiteDatabase.CONFLICT_FAIL, chapterCV) } for (j in 0 until bookmarks.length()) { val bookmark = bookmarks.getJSONObject(j) val bookmarkTime = bookmark.getInt("time") val bookmarkPath = bookmark.getString("mediaPath") val bookmarkTitle = bookmark.getString("title") val bookmarkCV = ContentValues() bookmarkCV.put(BOOKMARK_PATH, bookmarkPath) bookmarkCV.put(BOOKMARK_TITLE, bookmarkTitle) bookmarkCV.put(BOOKMARK_TIME, bookmarkTime) bookmarkCV.put(BOOK_ID, bookId) db.insert(TABLE_BOOKMARKS, SQLiteDatabase.CONFLICT_FAIL, bookmarkCV) } } } }
data/src/main/kotlin/voice/data/repo/internals/migrations/Migration29to30.kt
1180536004
package avalon.group import avalon.api.Flag.at import avalon.tool.pool.Constants.Basic.CURRENT_SERVLET import avalon.tool.pool.Constants.Basic.LANG import avalon.util.GroupConfig import avalon.util.GroupMessage import java.util.regex.Pattern object ShowAdmin : GroupMessageResponder() { override fun doPost(message: GroupMessage, groupConfig: GroupConfig) { val adminUid = groupConfig.admins val builder = StringBuilder() for (uid in adminUid) { val card = CURRENT_SERVLET.getGroupSenderNickname(message.groupUid, uid) if (!card.isEmpty()) builder.append(card).append(" - ").append(uid).append(", ") } if (builder.isEmpty()) { message.response("${at(message)} ${LANG.getString("group.show_admin.no_admin")}") return } val toDisplay = LANG.getString("group.show_admin.reply") .format("\n" + builder.toString().substring(0, builder.length - 2)) message.response("${at(message)} $toDisplay") } override fun responderInfo(): ResponderInfo = ResponderInfo( Pair("(wia|whoisadmin)", LANG.getString("group.show_admin.help")), Pattern.compile("(wia|whoisadmin)") ) override fun instance(): GroupMessageResponder = this }
src/main/kotlin/avalon/group/ShowAdmin.kt
331446409
/* * Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.asynchronous.asynctasks.ftp.auth import androidx.annotation.WorkerThread import com.amaze.filemanager.filesystem.ftp.FTPClientImpl import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.CONNECT_TIMEOUT import com.amaze.filemanager.filesystem.ftp.NetCopyClientConnectionPool.FTP_URI_PREFIX import net.schmizz.sshj.userauth.UserAuthException import org.apache.commons.net.ftp.FTPClient import java.util.concurrent.Callable open class FtpAuthenticationTaskCallable( protected val hostname: String, protected val port: Int, protected val username: String, protected val password: String ) : Callable<FTPClient> { @WorkerThread override fun call(): FTPClient { val ftpClient = createFTPClient() ftpClient.connectTimeout = CONNECT_TIMEOUT ftpClient.controlEncoding = Charsets.UTF_8.name() ftpClient.connect(hostname, port) val loginSuccess = if (username.isBlank() && password.isBlank()) { ftpClient.login( FTPClientImpl.ANONYMOUS, FTPClientImpl.generateRandomEmailAddressForLogin() ) } else { ftpClient.login(username, password) } return if (loginSuccess) { ftpClient.enterLocalPassiveMode() ftpClient } else { throw UserAuthException("Login failed") } } protected open fun createFTPClient(): FTPClient = NetCopyClientConnectionPool.ftpClientFactory.create(FTP_URI_PREFIX) }
app/src/main/java/com/amaze/filemanager/asynchronous/asynctasks/ftp/auth/FtpAuthenticationTaskCallable.kt
500206940
package org.blitzortung.android.app.components import android.content.Context import org.assertj.core.api.KotlinAssertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(manifest=Config.NONE) class VersionComponentTest { lateinit private var versionComponent: VersionComponent @Before fun setUp() { versionComponent = VersionComponent(RuntimeEnvironment.application) } @Test fun configuredVersionCodeShouldBeMinusOneWhenUndefied() { assertThat(versionComponent.configuredVersionCode).isEqualTo(-1) } @Test fun stateShouldBeFirstRunWhenConfiguredVersionIsUndefined() { assertThat(versionComponent.state).isEqualTo(VersionComponent.State.FIRST_RUN) } @Test fun shouldReturnVersionCode() { assertThat(versionComponent.versionCode).isEqualTo(CURRENT_VERSION_CODE) } @Test fun shouldReturnVersionName() { assertThat(versionComponent.versionName).isEqualTo(CURRENT_VERSION_NAME) } @Test fun shouldReturnNoUpdateStateWhenCalledNextTime() { versionComponent = VersionComponent(RuntimeEnvironment.application) assertThat(versionComponent.configuredVersionCode).isEqualTo(CURRENT_VERSION_CODE) assertThat(versionComponent.state).isEqualTo(VersionComponent.State.NO_UPDATE) } @Test fun shouldReturnUpdatedStateWhenCalledFirstTimeAfterVersionChange() { val context = RuntimeEnvironment.application val preferences = context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE) preferences .edit().putInt(VersionComponent.CONFIGURED_VERSION_CODE, 1).apply() versionComponent = VersionComponent(context) assertThat(versionComponent.configuredVersionCode).isEqualTo(1) assertThat(versionComponent.state).isEqualTo(VersionComponent.State.FIRST_RUN_AFTER_UPDATE) } companion object { val CURRENT_VERSION_CODE = 169 val CURRENT_VERSION_NAME = "1.5.0" } }
app/src/test/java/org/blitzortung/android/app/components/VersionComponentTest.kt
1301824925
package ademar.study.reddit.core.interactor import ademar.study.reddit.core.model.Post import ademar.study.reddit.core.model.internal.Child import ademar.study.reddit.core.model.internal.Data import ademar.study.reddit.core.model.internal.PostResponse import ademar.study.reddit.core.repository.PostRepository import io.reactivex.Observable import javax.inject.Inject class GetPostsUseCase @Inject constructor( private val repository: PostRepository ) { private var lastReference: String? = null fun currentPage(): Observable<Post> { return repository.getPosts() .map(PostResponse::data) .map(Data::children) .flatMapIterable { it } .map(Child::post) .doOnNext { lastReference = it.reference } } fun previousPage(): Observable<Post> { return repository.getPosts(lastReference) .map(PostResponse::data) .map(Data::children) .flatMapIterable { it } .map(Child::post) .doOnNext { lastReference = it.reference } } }
Projects/Reddit/core/src/main/java/ademar/study/reddit/core/interactor/GetPostsUseCase.kt
715983308
package ademar.study.reddit.navigation import ademar.study.reddit.plataform.factories.IntentFactory import ademar.study.reddit.view.base.BaseActivity import ademar.study.reddit.view.comment.CommentActivity import ademar.study.reddit.view.home.HomeActivity import javax.inject.Inject class FlowController @Inject constructor( private val context: BaseActivity, private val intentFactory: IntentFactory ) { fun launchHome() { var intent = intentFactory.makeIntent() intent = HomeActivity.populateIntent(intent, context) context.startActivity(intent) } fun launchComment(link: String) { var intent = intentFactory.makeIntent() intent = CommentActivity.populateIntent(intent, context, link) context.startActivity(intent) } }
Projects/Reddit/app/src/main/java/ademar/study/reddit/navigation/FlowController.kt
1088808523
package gsonpath.adapter.standard.adapter import com.google.gson.Gson import com.squareup.javapoet.ClassName import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeSpec import gsonpath.LazyFactoryMetadata import gsonpath.ProcessingException import gsonpath.adapter.AdapterGenerationResult import gsonpath.adapter.Constants.GENERATED_ANNOTATION import gsonpath.adapter.standard.adapter.read.ReadFunctions import gsonpath.adapter.standard.adapter.write.WriteFunctions import gsonpath.adapter.util.writeFile import gsonpath.annotation.AutoGsonAdapter import gsonpath.internal.GsonPathTypeAdapter import gsonpath.util.FileWriter import gsonpath.util.TypeSpecExt import gsonpath.util.constructor import javax.lang.model.element.Modifier import javax.lang.model.element.TypeElement class StandardGsonAdapterGenerator( private val adapterModelMetadataFactory: AdapterModelMetadataFactory, private val fileWriter: FileWriter, private val readFunctions: ReadFunctions, private val writeFunctions: WriteFunctions) { @Throws(ProcessingException::class) fun handle( modelElement: TypeElement, autoGsonAnnotation: AutoGsonAdapter, lazyFactoryMetadata: LazyFactoryMetadata): AdapterGenerationResult { val metadata = adapterModelMetadataFactory.createMetadata(modelElement, autoGsonAnnotation, lazyFactoryMetadata) val adapterClassName = metadata.adapterClassName return TypeSpecExt.finalClassBuilder(adapterClassName) .addDetails(metadata) .let { it.writeFile(fileWriter, adapterClassName.packageName()) AdapterGenerationResult(metadata.adapterGenericTypeClassNames.toTypedArray(), adapterClassName) } } private fun TypeSpec.Builder.addDetails(metadata: AdapterModelMetadata): TypeSpec.Builder { superclass(ParameterizedTypeName.get(ClassName.get(GsonPathTypeAdapter::class.java), metadata.modelClassName)) addAnnotation(GENERATED_ANNOTATION) // Add the constructor which takes a gson instance for future use. constructor { addModifiers(Modifier.PUBLIC) addParameter(Gson::class.java, "gson") addStatement("super(gson)") } readFunctions.handleRead(this, metadata.readParams) writeFunctions.handleWrite(this, metadata.writeParams) return this } }
compiler/standard/src/main/java/gsonpath/adapter/standard/adapter/StandardGsonAdapterGenerator.kt
1183809233
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.beam.learning.katas.coretransforms.combine.combineperkey import org.apache.beam.learning.katas.coretransforms.combine.combineperkey.Task.applyTransform import org.apache.beam.sdk.testing.PAssert import org.apache.beam.sdk.testing.TestPipeline import org.apache.beam.sdk.transforms.Create import org.apache.beam.sdk.values.KV import org.junit.Rule import org.junit.Test class TaskTest { @get:Rule @Transient val testPipeline: TestPipeline = TestPipeline.create() @Test fun core_transforms_combine_combine_perkey() { val values = Create.of( KV.of(Task.PLAYER_1, 15), KV.of(Task.PLAYER_2, 10), KV.of(Task.PLAYER_1, 100), KV.of(Task.PLAYER_3, 25), KV.of(Task.PLAYER_2, 75) ) val numbers = testPipeline.apply(values) val results = applyTransform(numbers) PAssert.that(results).containsInAnyOrder( KV.of(Task.PLAYER_1, 115), KV.of(Task.PLAYER_2, 85), KV.of(Task.PLAYER_3, 25) ) testPipeline.run().waitUntilFinish() } }
learning/katas/kotlin/Core Transforms/Combine/Combine PerKey/test/org/apache/beam/learning/katas/coretransforms/combine/combineperkey/TaskTest.kt
747721257
package coconautti.sql import io.kotlintest.matchers.shouldEqual import io.kotlintest.specs.BehaviorSpec class DeleteSpec : BehaviorSpec() { init { given("a delete statement") { val stmt = Database.deleteFrom("users") {} `when`("extracting SQL") { val sql = stmt.toString() then("it should match expectation") { sql.shouldEqual("DELETE FROM users") } } } given("a delete statement with where clause") { val stmt = Database.deleteFrom("users") { where("id" eq 1) } `when`("extracting SQL") { val sql = stmt.toString() then("it should match expectation") { sql.shouldEqual("DELETE FROM users WHERE id = ?") } } } given("a delete statement with composite where clause") { val stmt = Database.deleteFrom("users") { where(("id" eq 1) or ("name" ne "Donald")) } `when`("extracting SQL") { val sql = stmt.toString() then("it should match expectation") { sql.shouldEqual("DELETE FROM users WHERE id = ? OR name != ?") } } } } }
src/test/kotlin/coconautti/sql/DeleteSpec.kt
1929520930
package net.nemerosa.ontrack.job import io.micrometer.core.instrument.Tag data class JobKey( val type: JobType, val id: String ) { fun sameType(type: JobType): Boolean { return this.type == type } fun sameCategory(category: JobCategory): Boolean { return this.type.category == category } override fun toString(): String { return "$type[$id]" } val metricTags: List<Tag> get() = listOf( Tag.of("job-type", type.key), Tag.of("job-category", type.category.key) ) companion object { @JvmStatic fun of(type: JobType, id: String): JobKey { return JobKey(type, id) } } }
ontrack-job/src/main/java/net/nemerosa/ontrack/job/JobKey.kt
2129639744
package it.liceoarzignano.bold.settings import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.preference.PreferenceFragmentCompat import com.afollestad.materialdialogs.MaterialDialog import it.liceoarzignano.bold.R class SettingsActivity : AppCompatActivity() { override fun onCreate(savedInstance: Bundle?) { super.onCreate(savedInstance) setContentView(R.layout.activity_settings) val toolbar = findViewById<Toolbar>(R.id.toolbar_include) setSupportActionBar(toolbar) toolbar.setNavigationIcon(R.drawable.ic_toolbar_back) toolbar.setNavigationOnClickListener { finish() } } class MyPreferenceFragment : PreferenceFragmentCompat() { private lateinit var mContext: Context private lateinit var mPrefs: AppPrefs override fun onCreatePreferences(savedInstance: Bundle?, key: String?) { addPreferencesFromResource(R.xml.settings) mContext = activity ?: return mPrefs = AppPrefs(mContext) val changeLog = findPreference("changelog_key") val name = findPreference("username_key") changeLog.setOnPreferenceClickListener { MaterialDialog.Builder(mContext) .title(getString(R.string.pref_changelog)) .content(getString(R.string.dialog_updated_content)) .positiveText(getString(android.R.string.ok)) .negativeText(R.string.dialog_updated_changelog) .onNegative { dialog, _ -> dialog.hide() val mIntent = Intent(Intent.ACTION_VIEW) mIntent.data = Uri.parse(getString(R.string.config_url_changelog)) startActivity(mIntent) } .show() true } name.summary = mPrefs.get(AppPrefs.KEY_USERNAME, "") name.setOnPreferenceChangeListener { _, newValue -> name.summary = newValue.toString() true } } } }
app/src/main/kotlin/it/liceoarzignano/bold/settings/SettingsActivity.kt
708874656