content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
// PROBLEM: none // WITH_STDLIB class Test { var s: String? = null fun test() { if (s != null) { <caret>requireNotNull(s) } } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantRequireNotNullCall/nullable2.kt
796112382
// RUNTIME_WITH_FULL_JDK fun main() { val list: /*T5@*/List</*T4@*/String?> = listOf</*T0@*/String?>(""/*LIT*/, null/*NULL!!U*/)/*List<T0@String>!!L*/ .map</*T2@*/String?, /*T3@*/String?>({ x: /*T1@*/String? -> x/*T1@String*/ }/*Function1<T1@String, T6@String>!!L*/)/*List<T3@String>!!L*/ } //LOWER <: T0 due to 'PARAMETER' //UPPER <: T0 due to 'PARAMETER' //T1 <: T6 due to 'RETURN' //T0 <: T2 due to 'RECEIVER_PARAMETER' //T2 <: T1 due to 'PARAMETER' //T6 <: T3 due to 'PARAMETER' //T3 <: T4 due to 'INITIALIZER' //LOWER <: T5 due to 'INITIALIZER'
plugins/kotlin/j2k/new/tests/testData/inference/nullability/notNullCallSequence.kt
1033230969
// AFTER-WARNING: Parameter 'ignoreCase' is never used // AFTER-WARNING: Parameter 'other' is never used @Suppress("INAPPLICABLE_OPERATOR_MODIFIER") public operator fun CharSequence.contains(other: CharSequence, ignoreCase: Boolean = false): Boolean = false fun test() { val foo = "foo" foo.c<caret>ontains("bar") }
plugins/kotlin/idea/tests/testData/intentions/conventionNameCalls/replaceContains/simpleStringLiteral.kt
3777983436
package implicit.prefix.source import implicit.prefix.target.NamedFaceO class G: NamedFaceO
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveFile/moveMultipleFilesWithImplicitPrefix/after/source/test.kt
1010046041
interface I<T> { fun <U> a(t: T, u: U) fun b() fun c(t: T) fun <U> d(t: T, u: U) } class <caret>C : I<Int> { override fun b() { } override fun <U> d(t: Int, u: U) { } }
plugins/kotlin/idea/tests/testData/codeInsight/overrideImplement/genericClass.kt
2232421763
package com.google.android.apps.muzei import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.support.wearable.notifications.BridgingConfig import android.support.wearable.notifications.BridgingManager import android.util.Log import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import com.google.android.apps.muzei.room.MuzeiDatabase import com.google.android.apps.muzei.sync.ProviderChangedWorker import com.google.android.apps.muzei.sync.ProviderManager import com.google.android.apps.muzei.util.goAsync import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import net.nurik.roman.muzei.BuildConfig class ProviderChangedReceiver : BroadcastReceiver() { companion object { private const val TAG = "ProviderChangedReceiver" /** * Call this when a persistent listener changes visibility */ fun onVisibleChanged(context: Context) { GlobalScope.launch { updateBridging(context) } } /** * Observe the [Lifecycle] of this component to get callbacks for when this * changes visibility. */ fun observeForVisibility(context: Context, lifecycleOwner: LifecycleOwner) { lifecycleOwner.lifecycle.addObserver(LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_START) { onVisibleChanged(context) } else if (event == Lifecycle.Event.ON_STOP) { onVisibleChanged(context) } }) } suspend fun updateBridging(context: Context) { val provider = MuzeiDatabase.getInstance(context).providerDao() .getCurrentProvider() val dataLayerSelected = provider?.authority == BuildConfig.DATA_LAYER_AUTHORITY // Either we have an active listener or a persistent listener val isActive = ProviderManager.getInstance(context).hasActiveObservers() || ProviderChangedWorker.hasPersistentListeners(context) // Only bridge notifications if we're not currently showing any wallpaper // on the watch or if we're showing the same wallpaper as the phone // (i.e., the DataLayerArtProvider is selected) val bridgeNotifications = !isActive || dataLayerSelected if (BuildConfig.DEBUG) { Log.d(TAG, "Bridging changed to $bridgeNotifications: isActive=$isActive, " + "selected Provider=$provider") } // Use the applicationContext because BridgingManager binds to a Service // and that's not allowed from a BroadcastReceiver's Context BridgingManager.fromContext(context.applicationContext).setConfig( BridgingConfig.Builder(context, bridgeNotifications).build() ) } } override fun onReceive(context: Context, intent: Intent) { if (intent.`package` != context.packageName) { // Filter out Intents that don't explicitly // have our package name return } goAsync { updateBridging(context) } } }
wearable/src/main/java/com/google/android/apps/muzei/ProviderChangedReceiver.kt
3577730144
package io.fotoapparat.exif import androidx.exifinterface.media.ExifInterface import io.fotoapparat.exception.FileSaveException import java.io.File import java.io.IOException /** * Writes Exif attributes. */ internal object ExifWriter : ExifOrientationWriter { @Throws(FileSaveException::class) override fun writeExifOrientation(file: File, rotationDegrees: Int) { try { ExifInterface(file.path).apply { setAttribute( ExifInterface.TAG_ORIENTATION, toExifOrientation(rotationDegrees).toString() ) saveAttributes() } } catch (e: IOException) { throw FileSaveException(e) } } private fun toExifOrientation(rotationDegrees: Int): Int { val compensationRotationDegrees = (360 - rotationDegrees) % 360 return when (compensationRotationDegrees) { 90 -> ExifInterface.ORIENTATION_ROTATE_90 180 -> ExifInterface.ORIENTATION_ROTATE_180 270 -> ExifInterface.ORIENTATION_ROTATE_270 else -> ExifInterface.ORIENTATION_NORMAL } } }
fotoapparat/src/main/java/io/fotoapparat/exif/ExifWriter.kt
3883235551
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.utils public interface ReflectionUtils { fun <T> initializeClass(clazz: Class<out T>): T { try { val constructor = clazz.getConstructor() return constructor.newInstance() } catch (e: NoSuchMethodException) { throw RuntimeException("Can't initialize class ${clazz.getName()}, no <init>()", e) } } fun <T> initializeClass(clazz: Class<out T>, vararg args: Pair<Any, Class<*>>): T { // https://youtrack.jetbrains.com/issue/KT-5793 val argList = args.map { it.first }.toTypedArray() val argTypes = args.map { it.second }.toTypedArray() try { val constructor = clazz.getConstructor(*argTypes) return constructor.newInstance(*argList) } catch (e: NoSuchMethodException) { throw RuntimeException("Can't initialize class ${clazz.getName()}, no <init>(${argTypes.joinToString()})", e) } } }
dsl/src/org/jetbrains/android/anko/utils/ReflectionUtils.kt
3541759867
package com.timepath.vfs.server.cifs import com.timepath.vfs.FileChangeListener import java.io.IOException import java.io.InputStream import java.net.InetAddress import java.net.ServerSocket import java.net.Socket import java.nio.ByteBuffer import java.util.Arrays import java.util.LinkedList import java.util.logging.Level import java.util.logging.Logger import kotlin.platform.platformStatic /** * http://www.codefx.com/CIFS_Explained.htm * smbclient --ip-address=localhost --port=8000 -M hi * * @author TimePath */ class CIFSWatcher private constructor(port: Int) { private val listeners = LinkedList<FileChangeListener>() init { try { // On windows, the loopback address does not prompt the firewall // Also good for security in general val sock = ServerSocket(port, 0, InetAddress.getLoopbackAddress()) val realPort = sock.getLocalPort() LOG.log(Level.INFO, "Listening on port {0}", realPort) Runtime.getRuntime().addShutdownHook (Thread { LOG.info("CIFS server shutting down...") }) Thread(object : Runnable { private val data: Socket? = null private val pasv: ServerSocket? = null override fun run() { while (true) { val client: Socket try { LOG.info("Waiting for client...") client = sock.accept() LOG.info("Connected") } catch (ex: IOException) { Logger.getLogger(javaClass<CIFSWatcher>().getName()).log(Level.SEVERE, null, ex) continue } Thread(object : Runnable { override fun run() { try { val input = client.getInputStream() while (!client.isClosed()) { try { val buf = ByteArray(200) while (input.read(buf) != -1) { val text = String(buf).trim() LOG.info(Arrays.toString(text.toByteArray())) LOG.info(text) } // TODO: Packet handling } catch (ex: Exception) { LOG.log(Level.SEVERE, null, ex) client.close() break } } LOG.info("Socket closed") } catch (ex: IOException) { Logger.getLogger(javaClass<CIFSWatcher>().getName()).log(Level.SEVERE, null, ex) } } inner class Packet { private var header: Int = 0 // \0xFF S M B throws(IOException::class) private fun read(`is`: InputStream): Packet { val buf = ByteBuffer.allocate(42) // Average CIFS header size val head = ByteArray(24) `is`.read(head) LOG.info(Arrays.toString(head)) LOG.info(String(head)) buf.put(head) buf.flip() header = buf.getInt() command = buf.get() errorClass = buf.get() buf.get() // == 0 errorCode = buf.getShort() flags = buf.get() flags2 = buf.getShort() secure = buf.getLong() // or padding tid = buf.getShort() // Tree ID pid = buf.getShort() // Process ID uid = buf.getShort() // User ID mid = buf.getShort() // Multiplex ID val wordCount = `is`.read() val words = ByteArray(wordCount * 2) `is`.read(words) val wordBuffer = ByteBuffer.wrap(words) val arr = ShortArray(wordCount) parameterWords = arr for (i in words.indices) { arr[i] = wordBuffer.getShort() } val payloadLength = `is`.read() buffer = ByteArray(payloadLength) `is`.read(buffer) return this } private var command: Byte = 0 /** * ERRDOS (0x01) – * Error is from the * core DOS operating * system * set * ERRSRV (0x02) – * Error is generated * by the server * network * file manager * ERRHRD (0x03) – * Hardware error * ERRCMD (0xFF) – * Command was not * in the “SMB” * format */ private var errorClass: Byte = 0 /** * As specified in * CIFS1.0 draft */ private var errorCode: Short = 0 /** * When bit 3 is set * to ‘1’, all pathnames * in this particular * packet must be * treated as * caseless * When bit 3 is set * to ‘0’, all pathnames * are case sensitive */ private var flags: Byte = 0 /** * Bit 0, if set, * indicates that * the server may * return long * file names in the * response * Bit 6, if set, * indicates that * any pathname in * the request is * a long file name * Bit 16, if set, * indicates strings * in the packet are * encoded * as UNICODE */ private var flags2: Short = 0 /** * Typically zero */ private var secure: Long = 0 private var tid: Short = 0 private var buffer: ByteArray? = null private var parameterWords: ShortArray? = null private var pid: Short = 0 private var uid: Short = 0 private var mid: Short = 0 val bytes: ByteArray? = null } }).start() } } }, "CIFS Server").start() } catch (ex: IOException) { Logger.getLogger(javaClass<CIFSWatcher>().getName()).log(Level.SEVERE, null, ex) } } public fun addFileChangeListener(listener: FileChangeListener) { listeners.add(listener) } companion object { private val LOG = Logger.getLogger(javaClass<CIFSWatcher>().getName()) private var instance: CIFSWatcher? = null public platformStatic fun main(args: Array<String>) { var port = 8000 if (args.size() >= 1) { port = Integer.parseInt(args[0]) } getInstance(port) } private fun getInstance(port: Int): CIFSWatcher { if (instance == null) { instance = CIFSWatcher(port) } return instance!! } } }
src/main/kotlin/com/timepath/vfs/server/cifs/CIFSWatcher.kt
2617435698
package com.jraska.console import android.widget.OverScroller import android.widget.ScrollView /** * Utility using reflection to pull up OverScroller and then use it as fling indicator. */ internal class FlingProperty private constructor(private val overScroller: OverScroller) { val isFlinging: Boolean get() = !overScroller.isFinished companion object { fun create(scrollView: ScrollView): FlingProperty { val scrollerField = ScrollView::class.java.getDeclaredField("mScroller") scrollerField.isAccessible = true val scroller = scrollerField.get(scrollView) as OverScroller return FlingProperty(scroller) } } }
console/src/main/java/com/jraska/console/FlingProperty.kt
375540328
package ch.rmy.android.http_shortcuts.http import ch.rmy.android.http_shortcuts.exceptions.DigestAuthException import com.burgstaller.okhttp.digest.Credentials import com.burgstaller.okhttp.digest.DigestAuthenticator import okhttp3.Request import okhttp3.Response import okhttp3.Route class DigestAuthenticator(credentials: Credentials) : DigestAuthenticator(credentials) { override fun authenticate(route: Route?, response: Response): Request? { try { return super.authenticate(route, response) } catch (e: IllegalArgumentException) { throw DigestAuthException(e.message!!) } } }
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/DigestAuthenticator.kt
1344916847
package me.srodrigo.kotlinwars.model.people import android.os.Bundle import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import kotlinx.android.synthetic.main.activity_people_list.* import me.srodrigo.kotlinwars.R import me.srodrigo.kotlinwars.infrastructure.view.DividerItemDecoration import me.srodrigo.kotlinwars.infrastructure.view.ViewStateHandler import me.srodrigo.kotlinwars.infrastructure.view.app import me.srodrigo.kotlinwars.infrastructure.view.showMessage import me.srodrigo.kotlinwars.people.PeopleListPresenter import me.srodrigo.kotlinwars.people.PeopleListView import kotlin.properties.Delegates class PeopleListActivity : AppCompatActivity(), SwipeRefreshLayout.OnRefreshListener, PeopleListView { val peopleListAdapter = PeopleListAdapter() val peopleListStateHolder = ViewStateHandler<PeopleListState>() var peopleListPresenter by Delegates.notNull<PeopleListPresenter>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_people_list) if (savedInstanceState == null) { peopleListPresenter = PeopleListPresenter(app().executor, app().createGetPeopleCommand()) } peopleListPresenter.attachView(this) } override fun onResume() { super.onResume() peopleListPresenter.onRefresh() } override fun onDestroy() { peopleListPresenter.detachView() super.onDestroy() } override fun onRefresh() { peopleListPresenter.onRefresh() } //--- View actions override fun initPeopleListView() { initToolbar() initSwipeLayout() initPeopleList() } private fun initToolbar() { val toolbar = findViewById(R.id.toolbar) as? Toolbar if (toolbar != null) { setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(false) } } private fun initSwipeLayout() { peopleSwipeLayout.setOnRefreshListener(this) peopleSwipeLayout.isEnabled = true } private fun initPeopleList() { peopleListView.layoutManager = LinearLayoutManager(this) peopleListView.adapter = peopleListAdapter peopleListView.itemAnimator = DefaultItemAnimator() peopleListView.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL)) peopleListView.addOnScrollListener(object : RecyclerView.OnScrollListener() { }) peopleListStateHolder.bind(PeopleListState.LOADING, peopleLoadingView) peopleListStateHolder.bind(PeopleListState.EMPTY, peopleEmptyView) peopleListStateHolder.bind(PeopleListState.LIST, peopleListView) } override fun refreshPeopleList(peopleList: List<Person>) { peopleListAdapter.set(peopleList) peopleListStateHolder.show(PeopleListState.LIST) } override fun showLoadingView() { peopleListStateHolder.show(PeopleListState.LOADING) } override fun hideLoadingView() { peopleSwipeLayout.isRefreshing = false } override fun showPeopleEmptyView() { peopleListStateHolder.show(PeopleListState.EMPTY) } override fun showGenericError() { showMessage(R.string.unknown_error) } override fun showNetworkUnavailableError() { showMessage(R.string.network_unavailable) } enum class PeopleListState { LOADING, EMPTY, LIST } }
app/src/main/kotlin/me/srodrigo/kotlinwars/model/people/PeopleListActivity.kt
2367613863
package hu.juzraai.ted.xml.model.test import hu.juzraai.ted.xml.model.TedExport import hu.juzraai.ted.xml.model.meta.consistency.Consistency import org.junit.Test /** * @author Zsolt Jurányi */ class ConsistencyTest { @Test fun consistencyTest() { val r = Consistency().check(TedExport::class.java) Consistency().printReport(r) // TODO fail if warn count > 0 ? } }
src/test/kotlin/hu/juzraai/ted/xml/model/test/ConsistencyTest.kt
573873920
package org.andreych.workcalendar.datasource.model import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import org.junit.Assert.assertEquals import org.junit.Test internal class CalendarDataMappingTest { /** * Тестовый json корректно преобразуется в объектное представление. */ @Test fun shouldMap() { val mapper = jacksonObjectMapper() val file = javaClass.classLoader.getResourceAsStream("response_example.json") val readValue = mapper.readValue(file, YearData::class.java) assertEquals("Unexpected year value has been parsed.", 2021, readValue.year) val months = readValue.months assertEquals("Unexpected number of months has been parsed.", 12, months.size) (0..11).forEach { assertEquals("Unexpected month number value has been parsed.", it + 1, months[it].month) } assertEquals("1,2,3,4,5,6,7,8,9,10,16,17,23,24,30,31", months[0].days) assertEquals("6,7,13,14,20*,21,22,23,27,28", months[1].days) assertEquals("6,7,8,13,14,20,21,27,28", months[2].days) assertEquals("3,4,10,11,17,18,24,25,30*", months[3].days) assertEquals("1,2,3,8,9,10,15,16,22,23,29,30", months[4].days) assertEquals("5,6,11*,12,13,14,19,20,26,27", months[5].days) assertEquals("3,4,10,11,17,18,24,25,31", months[6].days) assertEquals("1,7,8,14,15,21,22,28,29", months[7].days) assertEquals("4,5,11,12,18,19,25,26", months[8].days) assertEquals("2,3,9,10,16,17,23,24,30,31", months[9].days) assertEquals("3*,4,5,6,7,13,14,20,21,27,28", months[10].days) assertEquals("4,5,11,12,18,19,25,26,31", months[11].days) } }
src/test/kotlin/org/andreych/workcalendar/datasource/model/CalendarDataMappingTest.kt
4071048229
package io.kotest.assertions import kotlin.native.concurrent.ThreadLocal @ThreadLocal actual val errorCollector: ErrorCollector = BasicErrorCollector()
kotest-assertions/kotest-assertions-shared/src/desktopMain/kotlin/io/kotest/assertions/ErrorCollector.kt
14090461
package jp.hitting.svn_diff_browser.service; import jp.hitting.svn_diff_browser.model.LogInfo import jp.hitting.svn_diff_browser.model.PathInfo import jp.hitting.svn_diff_browser.model.RepositoryModel import jp.hitting.svn_diff_browser.util.DiffUtil import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service import org.springframework.util.StringUtils import org.tmatesoft.svn.core.* import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory import org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl import org.tmatesoft.svn.core.io.SVNRepository import org.tmatesoft.svn.core.io.SVNRepositoryFactory import org.tmatesoft.svn.core.wc.SVNDiffClient import org.tmatesoft.svn.core.wc.SVNLogClient import org.tmatesoft.svn.core.wc.SVNRevision import org.tmatesoft.svn.core.wc.SVNWCUtil import java.io.ByteArrayOutputStream import java.util.* /** * Repository Service Implementation. * Created by hitting on 2016/02/14. */ @Service class RepositoryServiceImpl : RepositoryService { @Value("\${commit-log-chunk}") private val commitLogChunk: Long = 10 /** * constructor. * Repository setup. */ init { DAVRepositoryFactory.setup() SVNRepositoryFactoryImpl.setup() FSRepositoryFactory.setup() } /** * {@inheritDoc} */ override fun existsRepository(repositoryModel: RepositoryModel): Boolean { try { val repository = this.initRepository(repositoryModel) ?: return false val nodeKind = repository.checkPath("", -1) if (SVNNodeKind.NONE == nodeKind) { return false } } catch (e: SVNException) { e.printStackTrace() return false } return true } /** * {@inheritDoc} */ override fun getLogList(repositoryModel: RepositoryModel, path: String, lastRev: Long?): List<LogInfo> { val list = ArrayList<LogInfo>() try { val url = repositoryModel.url if (StringUtils.isEmpty(url)) { return Collections.emptyList() } // val svnUrl = SVNURL.parseURIDecoded(url) // FIXME val auth = SVNWCUtil.createDefaultAuthenticationManager(repositoryModel.userId, repositoryModel.password.toCharArray()) val logClient = SVNLogClient(auth, null) val endRev = if (lastRev == null) SVNRevision.HEAD else SVNRevision.create(lastRev) logClient.doLog(svnUrl, arrayOf(path), endRev, endRev, SVNRevision.create(1), false, false, this.commitLogChunk, { logEntry -> println(logEntry.revision) val l = LogInfo() l.rev = logEntry.revision l.comment = logEntry.message ?: "" list.add(l) }) } catch (e: SVNException) { e.printStackTrace() return Collections.emptyList() } return list } /** * {@inheritDoc} */ override fun getPathList(repositoryModel: RepositoryModel, path: String): List<PathInfo> { val list = ArrayList<PathInfo>() try { val repository = this.initRepository(repositoryModel) ?: return Collections.emptyList() val rev = repository.latestRevision val dirs = repository.getDir(path, rev, null, null as? Collection<*>) as Collection<SVNDirEntry> dirs.forEach { val p = PathInfo() p.path = it.relativePath p.comment = it.commitMessage ?: "" p.isDir = (SVNNodeKind.DIR == it.kind) list.add(p) } } catch (e: SVNException) { e.printStackTrace() return Collections.emptyList() } return list } /** * {@inheritDoc} */ override fun getDiffList(repositoryModel: RepositoryModel, rev: Long): String { try { val url = repositoryModel.url if (StringUtils.isEmpty(url)) { return "" } // val svnUrl = SVNURL.parseURIDecoded(url) // FIXME val auth = SVNWCUtil.createDefaultAuthenticationManager(repositoryModel.userId, repositoryModel.password.toCharArray()) val diffClient = SVNDiffClient(auth, null) val outputStream = ByteArrayOutputStream() diffClient.doDiff(svnUrl, SVNRevision.create(rev - 1), svnUrl, SVNRevision.create(rev), SVNDepth.INFINITY, false, outputStream) return DiffUtil.formatDiff(outputStream.toByteArray()) } catch (e: SVNException) { e.printStackTrace() return "" } } /** * init repository. * * @param repositoryModel repository information * @return svn repository with auth info * @throws SVNException throw it when svnkit can't connect repository */ @Throws(SVNException::class) private fun initRepository(repositoryModel: RepositoryModel): SVNRepository? { val url = repositoryModel.url if (StringUtils.isEmpty(url)) { return null } val svnUrl = SVNURL.parseURIDecoded(url) // FIXME val auth = SVNWCUtil.createDefaultAuthenticationManager(repositoryModel.userId, repositoryModel.password.toCharArray()) val repository = SVNRepositoryFactory.create(svnUrl) repository.authenticationManager = auth return repository } }
SvnDiffBrowser/src/main/kotlin/jp/hitting/svn_diff_browser/service/RepositoryServiceImpl.kt
3552785486
/* * Copyright (C) 2017-2019 Hazuki * * 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 jp.hazuki.yuzubrowser.core const val MIME_TYPE_UNKNOWN = "application/octet-stream" const val MIME_TYPE_MHTML = "multipart/related" const val MIME_TYPE_HTML = "text/html" const val READER_FONT_NAME = "reader_font.bin" const val THEME_DIR = "theme" const val USER_AGENT_PC = "yuzu://useragent/type/pc"
module/core/src/main/java/jp/hazuki/yuzubrowser/core/Constants.kt
3601551054
/* * Copyright (C) 2017 Wiktor Nizio * * 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/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.navigator.main.data.fb import com.google.android.gms.maps.model.LatLng import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseReference import io.reactivex.Observable import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.ReplaySubject import pl.org.seva.navigator.contact.Contact import pl.org.seva.navigator.debug.debug import pl.org.seva.navigator.main.init.instance import pl.org.seva.navigator.main.ui.colorFactory val fbReader by instance<FbReader>() class FbReader : Fb() { fun peerLocationListener(email: String): Observable<LatLng> { return email.toReference().child(LAT_LNG).listen() .filter { it.value != null } .map { checkNotNull(it.value) } .map { it as String } .map { it.toLatLng() } } fun debugListener(email: String): Observable<String> { return email.toReference().child(DEBUG).listen() .filter { it.value != null } .map { checkNotNull(it.value) } .map { it as String } .filter { !debug.isIgnoredForPeer(email, it) } } fun friendshipRequestedListener(): Observable<Contact> = FRIENDSHIP_REQUESTED.contactListener() fun friendshipAcceptedListener(): Observable<Contact> = FRIENDSHIP_ACCEPTED.contactListener() fun friendshipDeletedListener(): Observable<Contact> = FRIENDSHIP_DELETED.contactListener() fun readFriends(): Observable<Contact> { val reference = currentUserReference().child(FRIENDS) return reference.read() .concatMapIterable { it.children } .filter { it.exists() } .map { it.toContact() } } fun findContact(email: String): Observable<Contact> = email.toReference().readContact() private fun DatabaseReference.readContact(): Observable<Contact> = read().map { it.toContact() } private fun String.contactListener(): Observable<Contact> { val reference = currentUserReference().child(this) return reference.read() .concatMapIterable<DataSnapshot> { it.children } .concatWith(reference.childListener()) .doOnNext { reference.child(checkNotNull(it.key)).removeValue() } .map { it.toContact() } } private fun DatabaseReference.childListener(): Observable<DataSnapshot> { val result = ReplaySubject.create<DataSnapshot>() addChildEventListener(RxChildEventListener(result)) return result.hide() } private fun DatabaseReference.read(): Observable<DataSnapshot> { val resultSubject = PublishSubject.create<DataSnapshot>() return resultSubject .doOnSubscribe { addListenerForSingleValueEvent(RxValueEventListener(resultSubject)) } .take(READ_ONCE) } private fun DatabaseReference.listen(): Observable<DataSnapshot> { val resultSubject = PublishSubject.create<DataSnapshot>() val value = RxValueEventListener(resultSubject) return resultSubject .doOnSubscribe { addValueEventListener(value) } .doOnDispose { removeEventListener(value) } } private fun DataSnapshot.toContact() = if (exists()) { Contact(checkNotNull(key).from64(), child(DISPLAY_NAME).value as String, colorFactory.nextColor()) } else Contact() companion object { const val READ_ONCE = 1L } }
navigator/src/main/kotlin/pl/org/seva/navigator/main/data/fb/FbReader.kt
418728768
/* * Copyright 2016 Ross 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.characters.bukkit.database.table import com.rpkit.characters.bukkit.RPKCharactersBukkit import com.rpkit.characters.bukkit.database.jooq.rpkit.Tables.RPKIT_GENDER import com.rpkit.characters.bukkit.gender.RPKGender import com.rpkit.characters.bukkit.gender.RPKGenderImpl import com.rpkit.core.database.Database import com.rpkit.core.database.Table import org.ehcache.config.builders.CacheConfigurationBuilder import org.ehcache.config.builders.ResourcePoolsBuilder import org.jooq.impl.DSL.constraint import org.jooq.impl.SQLDataType /** * Represents the gender table. */ class RPKGenderTable(database: Database, private val plugin: RPKCharactersBukkit): Table<RPKGender>(database, RPKGender::class) { private val cache = if (plugin.config.getBoolean("caching.rpkit_gender.id.enabled")) { database.cacheManager.createCache("rpk-characters-bukkit.rpkit_gender.id", CacheConfigurationBuilder.newCacheConfigurationBuilder(Int::class.javaObjectType, RPKGender::class.java, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_gender.id.size"))).build()) } else { null } private val nameCache = if (plugin.config.getBoolean("caching.rpkit_gender.name.enabled")) { database.cacheManager.createCache("rpk-characters-bukkit.rpkit_gender.name", CacheConfigurationBuilder.newCacheConfigurationBuilder(String::class.java, Int::class.javaObjectType, ResourcePoolsBuilder.heap(plugin.config.getLong("caching.rpkit_gender.name.size"))).build()) } else { null } override fun create() { database.create.createTableIfNotExists(RPKIT_GENDER) .column(RPKIT_GENDER.ID, SQLDataType.INTEGER.identity(true)) .column(RPKIT_GENDER.NAME, SQLDataType.VARCHAR(256)) .constraints( constraint("pk_rpkit_gender").primaryKey(RPKIT_GENDER.ID) ) .execute() } override fun applyMigrations() { if (database.getTableVersion(this) == null) { database.setTableVersion(this, "0.1.0") } } override fun insert(entity: RPKGender): Int { database.create .insertInto( RPKIT_GENDER, RPKIT_GENDER.NAME ) .values( entity.name ) .execute() val id = database.create.lastID().toInt() entity.id = id cache?.put(id, entity) nameCache?.put(entity.name, id) return id } override fun update(entity: RPKGender) { database.create .update(RPKIT_GENDER) .set(RPKIT_GENDER.NAME, entity.name) .where(RPKIT_GENDER.ID.eq(entity.id)) .execute() } override fun get(id: Int): RPKGender? { if (cache?.containsKey(id) == true) { return cache.get(id) } else { val result = database.create .select( RPKIT_GENDER.ID, RPKIT_GENDER.NAME ) .from(RPKIT_GENDER) .where(RPKIT_GENDER.ID.eq(id)) .fetchOne() ?: return null val gender = RPKGenderImpl( result.get(RPKIT_GENDER.ID), result.get(RPKIT_GENDER.NAME) ) cache?.put(id, gender) nameCache?.put(gender.name, id) return gender } } fun getAll(): List<RPKGender> { val results = database.create .select(RPKIT_GENDER.ID) .from(RPKIT_GENDER) .fetch() return results.map { result -> get(result.get(RPKIT_GENDER.ID)) } .filterNotNull() } /** * Gets a gender by name. * If no gender is found with the given name, null is returned. * * @param name The name of the gender * @return The gender, or null if no gender is found with the given name */ operator fun get(name: String): RPKGender? { if (nameCache?.containsKey(name) == true) { return get(nameCache.get(name) as Int) } else { val result = database.create .select( RPKIT_GENDER.ID, RPKIT_GENDER.NAME ) .from(RPKIT_GENDER) .where(RPKIT_GENDER.NAME.eq(name)) .fetchOne() ?: return null val gender = RPKGenderImpl( result.get(RPKIT_GENDER.ID), result.get(RPKIT_GENDER.NAME) ) cache?.put(gender.id, gender) nameCache?.put(name, gender.id) return gender } } override fun delete(entity: RPKGender) { database.create .deleteFrom(RPKIT_GENDER) .where(RPKIT_GENDER.ID.eq(entity.id)) .execute() cache?.remove(entity.id) nameCache?.remove(entity.name) } }
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/database/table/RPKGenderTable.kt
1842146235
/* * Copyright (C) 2017-2021 Hazuki * * 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 jp.hazuki.yuzubrowser.adblock.ui.original import androidx.lifecycle.ViewModel import jp.hazuki.yuzubrowser.core.lifecycle.KotlinLiveData import jp.hazuki.yuzubrowser.core.lifecycle.LiveEvent class AdBlockImportViewModel : ViewModel() { val isExclude = KotlinLiveData(true) val isButtonEnable = KotlinLiveData(true) val text = KotlinLiveData("") val event = LiveEvent<Int>() fun onOkClick() { event.notify(EVENT_OK) } fun onCancelClick() { event.notify(EVENT_CANCEL) } companion object { const val EVENT_OK = 1 const val EVENT_CANCEL = 2 } }
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/original/AdBlockImportViewModel.kt
4292667041
package org.triplepy.sh8email.sh8.api import okhttp3.Interceptor import org.triplepy.sh8email.sh8.Constants import org.triplepy.sh8email.sh8.app.App import java.util.* /** * The sh8email-android Project. * ============================== * org.triplepy.sh8email.sh8.api * ============================== * Created by igangsan on 2016. 8. 28.. * * AddCookiesInterceptor와 마찬가지로 Interceptor를 Implements 하여 구현합니다. * 다른점은 request를 수행시키고 받아온 response값을 조작한다는 점 입니다. * 만약 response Header에 Set-Cookie란 값이 있다면 cookies값을 Preferences에 저장시킵니다. * 그리고는 header가 추가 된 response값을 반환시킵니다. * * @author 이강산 (river-mountain) * */ class ReceivedCookiesInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): okhttp3.Response { val response = chain.proceed(chain.request()) if (!response.headers("Set-Cookie").isEmpty()) { val cookies = HashSet<String>() cookies.addAll(response.headers("Set-Cookie")) App.pref.put(Constants.PREF_COOKIE, cookies) } return response } }
app/src/main/kotlin/org/triplepy/sh8email/sh8/api/ReceivedCookiesInterceptor.kt
1647814876
package com.androidessence.cashcaretaker.ui.transactionlist import com.androidessence.cashcaretaker.CoroutinesTestRule import com.androidessence.cashcaretaker.core.models.Transaction import org.junit.Before import org.junit.Rule import org.junit.Test class TransactionListViewModelTest { private lateinit var testRobot: TransactionListViewModelRobot @JvmField @Rule val coroutineTestRule = CoroutinesTestRule() @Before fun setUp() { testRobot = TransactionListViewModelRobot() } @Test fun fetchValidTransactions() { val accountName = "Checking" val testTransactions = listOf( Transaction( description = "Test Transaction" ) ) val expectedViewState = TransactionListViewState( showLoading = false, accountName = accountName, transactions = testTransactions, ) testRobot .mockTransactionsForAccount( accountName, testTransactions ) .buildViewModel(accountName) .assertViewState(expectedViewState) } @Test fun fetchEmptyTransactionList() { val accountName = "Checking" val expectedViewState = TransactionListViewState( showLoading = false, accountName = accountName, transactions = emptyList(), ) testRobot .mockTransactionsForAccount( accountName, emptyList() ) .buildViewModel(accountName) .assertViewState(expectedViewState) } }
app/src/test/java/com/androidessence/cashcaretaker/ui/transactionlist/TransactionListViewModelTest.kt
4207275300
package chat.rocket.android.chatroom.adapter import android.view.View import chat.rocket.android.chatroom.uimodel.MessageReplyUiModel import chat.rocket.android.emoji.EmojiReactionListener import kotlinx.android.synthetic.main.item_message_reply.view.* class MessageReplyViewHolder( itemView: View, listener: ActionsListener, reactionListener: EmojiReactionListener? = null, private val replyCallback: (roomName: String, permalink: String) -> Unit ) : BaseViewHolder<MessageReplyUiModel>(itemView, listener, reactionListener) { init { setupActionMenu(itemView) } override fun bindViews(data: MessageReplyUiModel) { with(itemView) { button_message_reply.setOnClickListener { with(data.rawData) { replyCallback.invoke(roomName, permalink) } } } } }
app/src/main/java/chat/rocket/android/chatroom/adapter/MessageReplyViewHolder.kt
488350366
package me.proxer.library.entity.info import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.enums.MediaLanguage /** * Entity holding the data of a single manga chapter. * * @property title The title of the chapter. Can be empty. * * @author Ruben Gees */ @JsonClass(generateAdapter = true) data class MangaEpisode( @Json(name = "no") override val number: Int, @Json(name = "typ") override val language: MediaLanguage, @Json(name = "title") val title: String ) : Episode(number, language)
library/src/main/kotlin/me/proxer/library/entity/info/MangaEpisode.kt
2505385076
package org.eurofurence.connavigator.util.v2 import nl.komponents.kovenant.Promise import nl.komponents.kovenant.then import nl.komponents.kovenant.unwrap /** * [then] with an immediate [unwrap]. */ infix fun <V, R> Promise<V, Exception>.thenNested(bind: (V) -> Promise<R, Exception>) = this.then(bind).unwrap()
app/src/main/kotlin/org/eurofurence/connavigator/util/v2/Promises.kt
529922766
package com.jukebot.jukebot import android.app.ActivityManager import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.AsyncTask import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.text.method.MovementMethod import android.text.method.ScrollingMovementMethod import android.view.Menu import android.view.MenuItem import android.widget.ImageView import android.widget.TextView import com.google.gson.Gson import com.jukebot.jukebot.logging.Logger import com.jukebot.jukebot.manager.MessageManager import com.jukebot.jukebot.storage.PersistentStorage import com.jukebot.jukebot.telegram.Bot import com.pengrad.telegrambot.model.PhotoSize import com.pengrad.telegrambot.request.GetFile import com.pengrad.telegrambot.request.GetMe import com.pengrad.telegrambot.request.GetUserProfilePhotos import com.pengrad.telegrambot.response.BaseResponse import com.pengrad.telegrambot.response.GetFileResponse import com.pengrad.telegrambot.response.GetMeResponse import com.pengrad.telegrambot.response.GetUserProfilePhotosResponse import java.io.InputStream import java.net.URL class ConsoleActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_console) // jukebot val tv: TextView = findViewById(R.id.debugTextView) as TextView tv.movementMethod = ScrollingMovementMethod() as MovementMethod? Logger.debugConsole = tv // --------------------- val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val drawer = findViewById(R.id.drawer_layout) as DrawerLayout //val toggle = ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) val toggle = ActionBarDrawerToggle(this, drawer, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer.setDrawerListener(toggle) toggle.syncState() val navigationView = findViewById(R.id.nav_view) as NavigationView navigationView.setNavigationItemSelectedListener(this) Logger.log(this.javaClass.simpleName, "token=${PersistentStorage.get(Constant.KEY_BOT_TOKEN)}") FetchBotInfoTask().execute() } private fun getAvatar(userId: Int) = MessageManager.enqueue(Pair(GetUserProfilePhotos(userId), { resp: BaseResponse? -> if (resp != null && resp.isOk && resp is GetUserProfilePhotosResponse) { resp.photos().photos()[0].forEach { photoSize -> if (photoSize is PhotoSize // for smart cast && photoSize.height() <= 160) { Logger.log(this.javaClass.simpleName, "selected photo=$photoSize") MessageManager.enqueue(Pair(GetFile(photoSize.fileId()), { resp: BaseResponse? -> if (resp != null && resp.isOk && resp is GetFileResponse && resp.file().filePath() != null) { // grab file FetchImageTask(findViewById(R.id.drawerBotAvatar) as ImageView) .execute("https://api.telegram.org/file/bot${PersistentStorage.get(Constant.KEY_BOT_TOKEN) as String}/${resp.file().filePath()}") } })) return@forEach } } } })) override fun onPrepareOptionsMenu(menu: Menu?): Boolean = false private fun isServiceRunning(clazz: Class<*>): Boolean { val manager: ActivityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager for (service in manager.getRunningServices(Int.MAX_VALUE)) { if (clazz.name == service.service.className && service.started && service.foreground) { Logger.log(this.javaClass.simpleName, "service=${Gson().toJson(service)}") return true } } return false } override fun onBackPressed() { val drawer = findViewById(R.id.drawer_layout) as DrawerLayout if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.console, menu) return true } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. val id = item.itemId if (id == R.id.nav_settings) { fragmentManager .beginTransaction() .replace(R.id.contentPanel, SettingsFragment()) .addToBackStack(null) .commit() } if (id == R.id.nav_exit) { closeApp() } val drawer = findViewById(R.id.drawer_layout) as DrawerLayout drawer.closeDrawer(GravityCompat.START) return true } inner class FetchBotInfoTask : AsyncTask<Unit, Unit, Unit>() { override fun doInBackground(vararg params: Unit?) { // get bot info while (!isServiceRunning(Bot::class.java)) { Logger.log(this.javaClass.simpleName, "await service") Thread.sleep(500) } Logger.log(this.javaClass.simpleName, "service started") MessageManager.enqueue(Pair(GetMe(), { resp: BaseResponse? -> try { if (resp != null && resp.isOk && resp is GetMeResponse) { (findViewById(R.id.drawerBotName) as TextView).text = "@${resp.user().username()}" getAvatar(resp.user().id()) } } catch (e: Exception) { e.printStackTrace() } })) } } inner class FetchImageTask(val imgView: ImageView) : AsyncTask<String, Unit, Bitmap?>() { override fun doInBackground(vararg urls: String?): Bitmap? { var bitmap: Bitmap? = null if (urls[0] != null) { try { val inputStream: InputStream = URL(urls[0]).openStream() bitmap = BitmapFactory.decodeStream(inputStream) inputStream.close() } catch (e: Exception) { e.printStackTrace() } } return bitmap } override fun onPostExecute(bitmap: Bitmap?) { super.onPostExecute(bitmap) if (bitmap != null) imgView.setImageBitmap(bitmap) } } fun closeApp() { stopService(Intent(this, Bot::class.java)) System.exit(0) } }
app/src/main/java/com/jukebot/jukebot/ConsoleActivity.kt
982077858
package com.github.sybila.checker.operator import com.github.sybila.checker.Channel import com.github.sybila.checker.Operator import com.github.sybila.checker.map.mutable.HashStateMap class ForAllOperator<out Params : Any>( full: Operator<Params>, inner: MutableList<Operator<Params>?>, bound: Operator<Params>, channel: Channel<Params> ) : LazyOperator<Params>(channel, { //forall x in B: A <=> forall x: ((at x: B) => A) <=> forall x: (!(at x: B) || A) val b = HashStateMap(ff, bound.compute().entries().asSequence().toMap()) val boundTransmission = (0 until partitionCount).map { b } mapReduce(boundTransmission.prepareTransmission(partitionId))?.forEach { b[it.first] = it.second } //now everyone has a full bound val result = newLocalMutableMap(partitionId) full.compute().entries().forEach { result[it.first] = it.second } for (state in 0 until stateCount) { if (state in b) { val i = inner[state]!!.compute() result.states().forEach { result[it] = result[it] and (i[it] or b[state].not()) } } inner[state] = null } result }) class ExistsOperator<out Params : Any>( inner: MutableList<Operator<Params>?>, bound: Operator<Params>, channel: Channel<Params> ) : LazyOperator<Params>(channel, { //exists x in B: A <=> exists x: ((at x: B) && A) val result = newLocalMutableMap(partitionId) val b = HashStateMap(ff, bound.compute().entries().asSequence().toMap()) val boundTransmission = (0 until partitionCount).map { b } mapReduce(boundTransmission.prepareTransmission(partitionId))?.forEach { b[it.first] = it.second } //now everyone has a full bound for (state in 0 until stateCount) { if (state in b) { val i = inner[state]!!.compute() i.entries().forEach { result[it.first] = result[it.first] or (it.second and b[state]) } } inner[state] = null } result }) class BindOperator<out Params : Any>( inner: MutableList<Operator<Params>?>, channel: Channel<Params> ) : LazyOperator<Params>(channel, { val result = newLocalMutableMap(partitionId) for (state in 0 until stateCount) { val i = inner[state]!!.compute() if (state in this) { result[state] = i[state] } inner[state] = null } result }) class AtOperator<out Params : Any>( state: Int, inner: Operator<Params>, channel: Channel<Params> ) : LazyOperator<Params>(channel, { val i = inner.compute() val transmission: Array<List<Pair<Int, Params>>?> = if (state in this) { (0 until partitionCount).map { listOf(state to i[state]) }.toTypedArray() } else kotlin.arrayOfNulls<List<Pair<Int, Params>>>(partitionCount) val result = mapReduce(transmission)?.first() ?: (state to i[state]) (0 until stateCount).asStateMap(result.second) })
src/main/kotlin/com/github/sybila/checker/operator/FirstOrderOperator.kt
1708258528
/* * * Copyright (C) 2017 YangBin * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package tech.summerly.quiet.module.common.fragment import android.support.v7.app.AppCompatActivity import com.transitionseverywhere.TransitionManager import org.jetbrains.anko.dimen import tech.summerly.quiet.R /** * author : SUMMERLY * e-mail : [email protected] * time : 2017/9/2 * desc : 包含 [BottomControllerFragment] 的 activity 需要实现此接口, * 便于手动的对[BottomControllerFragment]的移除和显示。 */ interface BottomControllerContainer { /** * 如果想使用默认实现进行BottomControllerFragment的显示和隐藏, * 那么需要在添加fragment的时候对fragment设置tag为 [R.string.common_tag_fragment_bottom_controller] */ fun hideBottomController() { if (this !is AppCompatActivity) { return } TransitionManager.beginDelayedTransition(findViewById(android.R.id.content)) val fragment = supportFragmentManager.findFragmentByTag(getString(R.string.common_tag_fragment_bottom_controller)) with(fragment.view) { this ?: return@with layoutParams.height = 0 parent.requestLayout() } } fun showBottomController() { if (this !is AppCompatActivity) { return } TransitionManager.beginDelayedTransition(findViewById(android.R.id.content)) val fragment = supportFragmentManager.findFragmentByTag(getString(R.string.common_tag_fragment_bottom_controller)) with(fragment.view) { this ?: return@with layoutParams.height = dimen(R.dimen.common_bottom_controller_height) parent.requestLayout() } } }
app/src/main/java/tech/summerly/quiet/module/common/fragment/BottomControllerContainer.kt
1090983467
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.macrobenchmark.ui.sampledata /** * From [androidx.compose.ui.tooling.preview.datasource.LoremIpsum] */ private val LOREM_IPSUM = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sodales laoreet commodo. Phasellus a purus eu risus elementum consequat. Aenean eu elit ut nunc convallis laoreet non ut libero. Suspendisse interdum placerat risus vel ornare. Donec vehicula, turpis sed consectetur ullamcorper, ante nunc egestas quam, ultricies adipiscing velit enim at nunc. Aenean id diam neque. Praesent ut lacus sed justo viverra fermentum et ut sem. Fusce convallis gravida lacinia. Integer semper dolor ut elit sagittis lacinia. Praesent sodales scelerisque eros at rhoncus. Duis posuere sapien vel ipsum ornare interdum at eu quam. Vestibulum vel massa erat. Aenean quis sagittis purus. Phasellus arcu purus, rutrum id consectetur non, bibendum at nibh. Duis nec erat dolor. Nulla vitae consectetur ligula. Quisque nec mi est. Ut quam ante, rutrum at pellentesque gravida, pretium in dui. Cras eget sapien velit. Suspendisse ut sem nec tellus vehicula eleifend sit amet quis velit. Phasellus quis suscipit nisi. Nam elementum malesuada tincidunt. Curabitur iaculis pretium eros, malesuada faucibus leo eleifend a. Curabitur congue orci in neque euismod a blandit libero vehicula.""".trim() private val LOREM_IPSUM_WORDS = LOREM_IPSUM.split(" ") private val names = listOf( "Jacob", "Sophia", "Noah", "Emma", "Mason", "Isabella", "William", "Olivia", "Ethan", "Ava", "Liam", "Emily", "Michael", "Abigail", "Alexander", "Mia", "Jayden", "Madison", "Daniel", "Elizabeth", "Aiden", "Chloe", "James", "Ella", "Elijah", "Avery", "Matthew", "Charlotte", "Benjamin", "Sofia" ) private val surnames = arrayOf( "Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller", "Davis", "Rodriguez", "Martinez" ) private val cities = arrayOf( "Shanghai", "Karachi", "Beijing", "Delhi", "Lagos", "Tianjin", "Istanbul", "Tokyo", "Guangzhou", "Mumbai", "Moscow", "São Paulo", "Shenzhen", "Jakarta", "Lahore", "Seoul", "Wuhan", "Kinshasa", "Cairo", "Mexico City", "Lima", "London", "New York City" ) internal fun randomFirstName(): String = names.random() internal fun randomLastName(): String = surnames.random() internal fun randomFullName(): String = randomFirstName() + " " + randomLastName() internal fun randomCity(): String = cities.random() internal object LoremIpsum { fun string(wordCount: Int, withLineBreaks: Boolean = false): String = words(wordCount, withLineBreaks).joinToString(separator = " ") fun words(wordCount: Int, withLineBreaks: Boolean = false): List<String> = if (withLineBreaks) { // Source includes line breaks LOREM_IPSUM_WORDS.take(wordCount.coerceIn(1, LOREM_IPSUM_WORDS.size)) } else { LOREM_IPSUM.filter { it != '\n' }.split(' ') .take(wordCount.coerceIn(1, LOREM_IPSUM_WORDS.size)) } }
projects/ComposeConstraintLayout/macrobenchmark-app/src/main/java/com/example/macrobenchmark/ui/sampledata/Strings.kt
3855630959
package es.danirod.rectball.android import de.golfgl.gdxgamesvcs.IGameServiceClient class GsvcsGameServices(private val client: IGameServiceClient, private val constants: GameServicesConstants) : GameServices { override fun signIn() { client.logIn() } override fun signOut() { client.logOff() } override val isSignedIn: Boolean get() = client.isSessionActive override fun uploadScore(score: Int, time: Int) { if (!client.isSessionActive) { return } client.submitToLeaderboard(constants.leaderboardHighestScore, score.toLong(), client.gameServiceId) client.submitToLeaderboard(constants.leaderboardHighestLength, time.toLong(), client.gameServiceId) if (score > 250) { client.unlockAchievement(constants.achievementStarter) } if (score > 2500) { client.unlockAchievement(constants.achievementExperienced) } if (score > 7500) { client.unlockAchievement(constants.achievementMaster) } if (score > 10000) { client.unlockAchievement(constants.achievementScoreBreaker) } if (score > 500) { client.incrementAchievement(constants.achievementCasualPlayer, 1, 1f) client.incrementAchievement(constants.achievementPerserverant, 1, 1f) client.incrementAchievement(constants.achievementCommuter, 1, 1f) } } override fun showLeaderboards() { client.showLeaderboards(constants.leaderboardHighestScore) } override fun showAchievements() { client.showAchievements() } }
app/src/main/java/es/danirod/rectball/android/GsvcsGameServices.kt
1008613558
package net.perfectdreams.loritta.morenitta.website.routes.dashboard.configure import net.perfectdreams.loritta.morenitta.dao.ServerConfig import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.morenitta.website.evaluate import io.ktor.server.application.ApplicationCall import net.dv8tion.jda.api.entities.Guild import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.website.routes.dashboard.RequiresGuildAuthLocalizedRoute import net.perfectdreams.loritta.morenitta.website.session.LorittaJsonWebSession import net.perfectdreams.loritta.morenitta.website.utils.extensions.legacyVariables import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondHtml import net.perfectdreams.temmiediscordauth.TemmieDiscordAuth class ConfigureEventLogRoute(loritta: LorittaBot) : RequiresGuildAuthLocalizedRoute(loritta, "/configure/event-log") { override suspend fun onGuildAuthenticatedRequest(call: ApplicationCall, locale: BaseLocale, discordAuth: TemmieDiscordAuth, userIdentification: LorittaJsonWebSession.UserIdentification, guild: Guild, serverConfig: ServerConfig) { loritta as LorittaBot val eventLogConfig = loritta.newSuspendedTransaction { serverConfig.eventLogConfig } val variables = call.legacyVariables(loritta, locale) variables["saveType"] = "event_log" variables["serverConfig"] = FakeServerConfig( FakeServerConfig.FakeEventLogConfig( eventLogConfig?.enabled ?: false, eventLogConfig?.eventLogChannelId?.toString(), eventLogConfig?.memberBanned ?: false, eventLogConfig?.memberUnbanned ?: false, eventLogConfig?.messageEdited ?: false, eventLogConfig?.messageDeleted ?: false, eventLogConfig?.nicknameChanges ?: false, eventLogConfig?.avatarChanges ?: false, eventLogConfig?.voiceChannelJoins ?: false, eventLogConfig?.voiceChannelLeaves ?: false ) ) call.respondHtml(evaluate("event_log.html", variables)) } /** * Fake Server Config for Pebble, in the future this will be removed */ private class FakeServerConfig(val eventLogConfig: FakeEventLogConfig) { class FakeEventLogConfig( val isEnabled: Boolean, val eventLogChannelId: String?, val memberBanned: Boolean, val memberUnbanned: Boolean, val messageEdit: Boolean, val messageDeleted: Boolean, val nicknameChanges: Boolean, val avatarChanges: Boolean, val voiceChannelJoins: Boolean, val voiceChannelLeaves: Boolean ) } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/dashboard/configure/ConfigureEventLogRoute.kt
453743151
package com.intellij.stats.completion import com.intellij.openapi.application.PathManager import java.io.File import java.io.FileFilter import java.nio.file.Files abstract class UrlProvider { abstract val statsServerPostUrl: String abstract val experimentDataUrl: String } abstract class FilePathProvider { abstract fun getUniqueFile(): File abstract fun getDataFiles(): List<File> abstract fun getStatsDataDirectory(): File abstract fun cleanupOldFiles() } class InternalUrlProvider: UrlProvider() { private val internalHost = "http://unit-617.labs.intellij.net" private val host: String get() = internalHost override val statsServerPostUrl = "http://test.jetstat-resty.aws.intellij.net/uploadstats" override val experimentDataUrl = "$host:8090/experiment/info" } class PluginDirectoryFilePathProvider : UniqueFilesProvider("chunk", PathManager.getSystemPath()) open class UniqueFilesProvider(private val baseName: String, private val rootDirectoryPath: String) : FilePathProvider() { private val MAX_ALLOWED_SEND_SIZE = 2 * 1024 * 1024 override fun cleanupOldFiles() { val files = getDataFiles() val sizeToSend = files.fold(0L, { totalSize, file -> totalSize + file.length() }) if (sizeToSend > MAX_ALLOWED_SEND_SIZE) { var currentSize = sizeToSend val iterator = files.iterator() while (iterator.hasNext() && currentSize > MAX_ALLOWED_SEND_SIZE) { val file = iterator.next() val fileSize = file.length() Files.delete(file.toPath()) currentSize -= fileSize } } } override fun getUniqueFile(): File { val dir = getStatsDataDirectory() val currentMaxIndex = dir .listFiles(FileFilter { it.isFile }) .filter { it.name.startsWith(baseName) } .map { it.name.substringAfter('_') } .filter { it.isIntConvertable() } .map(String::toInt) .max() val newIndex = if (currentMaxIndex != null) currentMaxIndex + 1 else 0 val file = File(dir, "${baseName}_$newIndex") return file } override fun getDataFiles(): List<File> { val dir = getStatsDataDirectory() return dir.listFiles(FileFilter { it.isFile }) .filter { it.name.startsWith(baseName) } .filter { it.name.substringAfter('_').isIntConvertable() } .sortedBy { it.getChunkNumber() } } override fun getStatsDataDirectory(): File { val dir = File(rootDirectoryPath, "completion-stats-data") if (!dir.exists()) { dir.mkdir() } return dir } private fun File.getChunkNumber() = this.name.substringAfter('_').toInt() private fun String.isIntConvertable(): Boolean { try { this.toInt() return true } catch (e: NumberFormatException) { return false } } }
plugins/stats-collector/src/com/intellij/stats/completion/Utils.kt
1479115213
package com.github.shiraji.permissionsdispatcherplugin.data enum class PdVersion { NOTFOUND, VERSION_2_1_3, UNKNOWN; companion object { const val latestVersion = "3.1.0" } }
src/main/kotlin/com/github/shiraji/permissionsdispatcherplugin/data/PdVersion.kt
2347869350
package mogul.platform.jvm import mogul.microdom.Color import mogul.microdom.Position import mogul.microdom.setSourceRgb import mogul.platform.Antialias import mogul.platform.AutoClose import sdl2cairo.* import sdl2cairo.SDL2.* import sdl2cairo.pango.* import mogul.platform.Window as WindowInterface import mogul.platform.Cairo as CairoInterface val SDL_EventType.l; get() = (javaClass.getMethod("swigValue").invoke(this) as Int).toLong() class Window( title: String, val userEvents: UserEvents, val width: Int, val height: Int, val background: Color = Color.black, val autoClose: AutoClose = AutoClose.Close ) : WindowInterface { val window = SDL_CreateWindow( title, SDL_WINDOWPOS_UNDEFINED.toInt(), SDL_WINDOWPOS_UNDEFINED.toInt(), width, height, SDL_WindowFlags.SDL_WINDOW_SHOWN.swigValue().toLong() ) ?: throw Exception("Failed to create window") internal val id: Long = SDL_GetWindowID(window) val renderer = SDL_CreateRenderer( window, -1, SDL_RendererFlags.SDL_RENDERER_ACCELERATED.swigValue().toLong() or SDL_RendererFlags.SDL_RENDERER_PRESENTVSYNC.swigValue().toLong() ) ?: throw Exception("Failed to initialize renderer") val texture = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_ARGB8888.toLong(), SDL_TextureAccess.SDL_TEXTUREACCESS_STREAMING.swigValue(), width, height ) ?: throw Exception("Failed to create texture") private var invalidated = true override fun wasInvalidated() = invalidated override fun draw(code: (cairo: CairoInterface) -> Unit) { val pixels = new_voidpp() val pitch = new_intp() SDL_LockTexture(texture, null, pixels, pitch) val surface = cairo_image_surface_create_for_data( voidp_to_ucharp(voidpp_value(pixels)), cairo_format_t.CAIRO_FORMAT_ARGB32, width, height, intp_value(pitch) ) val cairoT = cairo_create(surface) ?: throw Exception("Failed to initialize cairo") val cairo = Cairo(cairoT) cairo.setSourceRgb(background) cairo.setAntialias(Antialias.None) cairo_paint(cairoT) code(cairo) cairo_destroy(cairoT) cairo_surface_destroy(surface) SDL_UnlockTexture(texture) invalidate() delete_voidpp(pixels) delete_intp(pitch) } override fun invalidate() { invalidated = true SDL_PushEvent(userEvents.newInvalidated(this)) } override fun render() { SDL2.SDL_RenderClear(renderer) SDL2.SDL_RenderCopy(renderer, texture, null, null) SDL2.SDL_RenderPresent(renderer) invalidated = false } override fun getPosition(): Position { val xPtr = new_intp() val yPtr = new_intp() SDL_GetWindowPosition(window, xPtr, yPtr) return Position(intp_value(xPtr), intp_value(yPtr)).also { delete_intp(xPtr) delete_intp(yPtr) } } }
jvm/src/main/kotlin/mogul/platform/jvm/Window.kt
2228252909
package org.wonderbeat.dota.api.json import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty @JsonIgnoreProperties(ignoreUnknown = true) data class MatchPlayerDetailsJson(val accountId: Long, val playerSlot: Int, val heroId: Int, @JsonProperty("item_0") val item0: Int, @JsonProperty("item_1") val item1: Int, @JsonProperty("item_2") val item2: Int, @JsonProperty("item_3") val item3: Int, @JsonProperty("item_4") val item4: Int, @JsonProperty("item_5") val item5: Int, val kills: Int, val deaths: Int, val assists: Int, val leaverStatus: Int, val lastHits: Int, val denies: Int, val goldPerMin: Int, val xpPerMin: Int, val level: Int, val gold: Int, val goldSpent: Int, val heroDamage: Int, val heroHealing: Int, val abilityUpgrades: List<MatchAbilityUpgradeJson>)
src/main/kotlin/org/wonderbeat/dota/api/json/MatchPlayerDetailsJson.kt
638936932
package rectangledbmi.com.pittsburghrealtimetracker.patterns.stops.rendering import com.rectanglel.patstatic.patterns.response.Pt /** * * Rendering info for getStopRenderRequests * * Created by epicstar on 9/20/16. * @since 78 * @author Jeremy Jao * @author Michael Antonacci */ data class StopRenderRequest (val stopPt: Pt, val isVisible: Boolean)
app/src/main/java/rectangledbmi/com/pittsburghrealtimetracker/patterns/stops/rendering/StopRenderRequest.kt
2757700480
package library.enrichment.gateways.library import feign.Logger.Level import org.springframework.boot.context.properties.ConfigurationProperties @ConfigurationProperties("library") class LibrarySettings { /** The base URL of the main library service. */ lateinit var url: String /** The log [Level] to use when logging requests and responses. */ lateinit var logLevel: Level /** The username to use when communication with the main library service. */ lateinit var username: String /** The password to use when communication with the main library service. */ lateinit var password: String }
library-enrichment/src/main/kotlin/library/enrichment/gateways/library/LibrarySettings.kt
2892740419
package uk.co.appsbystudio.geoshare.authentication.login interface LoginPresenter { fun validate(email: String, password: String) }
mobile/src/main/java/uk/co/appsbystudio/geoshare/authentication/login/LoginPresenter.kt
3091757823
package com.lasthopesoftware.bluewater.client.playback.engine.selection.GivenATypicalPreferenceManagerAndBroadcaster import androidx.test.core.app.ApplicationProvider import com.lasthopesoftware.AndroidContext import com.lasthopesoftware.bluewater.client.playback.engine.selection.PlaybackEngineType import com.lasthopesoftware.bluewater.client.playback.engine.selection.PlaybackEngineTypeSelectionPersistence import com.lasthopesoftware.bluewater.client.playback.engine.selection.broadcast.PlaybackEngineTypeChangedBroadcaster import com.lasthopesoftware.bluewater.settings.repository.ApplicationSettings import com.lasthopesoftware.bluewater.settings.repository.access.HoldApplicationSettings import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.lasthopesoftware.resources.FakeMessageBus import com.namehillsoftware.handoff.promises.Promise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.Test import java.util.concurrent.TimeUnit class WhenPersistingTheSelectedPlaybackEngine : AndroidContext() { companion object { private val fakeMessageSender = FakeMessageBus(ApplicationProvider.getApplicationContext()) private var persistedEngineType: String? = null } override fun before() { val applicationSettings = mockk<HoldApplicationSettings>() every { applicationSettings.promiseApplicationSettings() } returns Promise(ApplicationSettings()) every { applicationSettings.promiseUpdatedSettings(any()) } answers { val settings = firstArg<ApplicationSettings>() persistedEngineType = settings.playbackEngineTypeName Promise(settings) } PlaybackEngineTypeSelectionPersistence(applicationSettings, PlaybackEngineTypeChangedBroadcaster(fakeMessageSender)) .selectPlaybackEngine(PlaybackEngineType.ExoPlayer) .toFuture()[1, TimeUnit.SECONDS] } @Test fun thenTheExoPlayerSelectionIsBroadcast() { assertThat(fakeMessageSender.recordedIntents.first().getStringExtra(PlaybackEngineTypeChangedBroadcaster.playbackEngineTypeKey)).isEqualTo(PlaybackEngineType.ExoPlayer.name) } @Test fun thenTheExoPlayerSelectionIsPersisted() { assertThat(persistedEngineType).isEqualTo(PlaybackEngineType.ExoPlayer.name) } }
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/engine/selection/GivenATypicalPreferenceManagerAndBroadcaster/WhenPersistingTheSelectedPlaybackEngine.kt
470601442
/* * 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 me.kyleclemens.ffxivraffler import me.kyleclemens.ffxivraffler.gui.GUIUtils import me.kyleclemens.ffxivraffler.gui.Raffle import me.kyleclemens.ffxivraffler.util.OS import me.kyleclemens.osx.HelperApplication import me.kyleclemens.osx.HelperQuitResponse import me.kyleclemens.osx.HelperQuitStrategy import me.kyleclemens.osx.events.HelperAppReOpenedEvent import me.kyleclemens.osx.events.HelperQuitEvent import me.kyleclemens.osx.handlers.HelperQuitHandler import me.kyleclemens.osx.listeners.HelperAppReOpenedListener import java.awt.Dimension import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import javax.swing.UIManager import javax.swing.UnsupportedLookAndFeelException import javax.swing.WindowConstants class FFXIVRaffler { companion object { fun cleanUp() { if (FFXIVRaffler.getOS() != OS.OS_X) { System.exit(0) } } fun getOS(): OS { return with(System.getProperty("os.name").toLowerCase()) { when { this.contains("mac") -> OS.OS_X this.contains("linux") -> OS.LINUX this.contains("windows") -> OS.WINDOWS else -> OS.OTHER } } } } } fun main(args: Array<String>) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) } catch (e: ClassNotFoundException) { e.printStackTrace() } catch (e: InstantiationException) { e.printStackTrace() } catch (e: UnsupportedLookAndFeelException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } val os = FFXIVRaffler.getOS() if (os == OS.OS_X) { val osxApplication = HelperApplication() System.setProperty("apple.laf.useScreenMenuBar", "true") osxApplication.addAppEventListener(object : HelperAppReOpenedListener { override fun appReOpened(event: HelperAppReOpenedEvent) { val frame = GUIUtils.openedFrames["FFXIV Raffler"] ?: return frame.pack() frame.isVisible = true } }) osxApplication.setQuitStrategy(HelperQuitStrategy.CLOSE_ALL_WINDOWS) osxApplication.setQuitHandler(object : HelperQuitHandler { override fun handleQuitRequestWith(event: HelperQuitEvent, response: HelperQuitResponse) { FFXIVRaffler.cleanUp() System.exit(0) } }) } val raffle = Raffle() GUIUtils.openWindow( raffle, "FFXIV Raffler", { frame -> val menuBar = GUIUtils.createMenuBar(frame, raffle) frame.jMenuBar = menuBar if (os == OS.OS_X) { val osxApplication = HelperApplication() osxApplication.setDefaultMenuBar(menuBar) } frame.addWindowListener(object : WindowAdapter() { override fun windowOpened(e: WindowEvent) { raffle.targetField.requestFocus() } override fun windowClosed(e: WindowEvent) { FFXIVRaffler.cleanUp() } override fun windowDeactivated(e: WindowEvent) { if (os == OS.OS_X) { this.windowClosed(e) } } }) }, WindowConstants.HIDE_ON_CLOSE, { it.minimumSize = Dimension(it.width, it.height) } ) }
FFXIVRaffler/src/main/kotlin/me/kyleclemens/ffxivraffler/FFXIVRaffler.kt
2986492787
package fr.smarquis.fcm.data.model import androidx.annotation.Keep import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity @Keep data class Message( @PrimaryKey @ColumnInfo(name = "messageId") val messageId: String, @ColumnInfo(name = "from") val from: String?, @ColumnInfo(name = "to") val to: String?, @ColumnInfo(name = "data") val data: Map<String, String>, @ColumnInfo(name = "collapseKey") val collapseKey: String?, @ColumnInfo(name = "messageType") val messageType: String?, @ColumnInfo(name = "sentTime") val sentTime: Long, @ColumnInfo(name = "ttl") val ttl: Int, @ColumnInfo(name = "priority") val priority: Int, @ColumnInfo(name = "originalPriority") val originalPriority: Int, @ColumnInfo(name = "payload") val payload: Payload? = null)
app/src/main/java/fr/smarquis/fcm/data/model/Message.kt
4008260682
package com.newsblur.subscription import android.app.Activity import android.content.Context import com.android.billingclient.api.AcknowledgePurchaseParams import com.android.billingclient.api.AcknowledgePurchaseResponseListener import com.android.billingclient.api.BillingClient import com.android.billingclient.api.BillingClientStateListener import com.android.billingclient.api.BillingFlowParams import com.android.billingclient.api.BillingResult import com.android.billingclient.api.Purchase import com.android.billingclient.api.PurchasesUpdatedListener import com.android.billingclient.api.SkuDetails import com.android.billingclient.api.SkuDetailsParams import com.newsblur.R import com.newsblur.network.APIManager import com.newsblur.service.NBSyncService import com.newsblur.util.AppConstants import com.newsblur.util.FeedUtils import com.newsblur.util.Log import com.newsblur.util.NBScope import com.newsblur.util.PrefsUtils import com.newsblur.util.executeAsyncTask import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.text.DateFormat import java.text.SimpleDateFormat import java.util.* interface SubscriptionManager { /** * Open connection to Play Store to retrieve * purchases and subscriptions. */ fun startBillingConnection(listener: SubscriptionsListener? = null) /** * Generated subscription state by retrieve all available subscriptions * and checking whether the user has an active subscription. * * Subscriptions are configured via the Play Store console. */ fun syncSubscriptionState() /** * Launch the billing flow overlay for a specific subscription. * @param activity Activity on which the billing overlay will be displayed. * @param skuDetails Subscription details for the intended purchases. */ fun purchaseSubscription(activity: Activity, skuDetails: SkuDetails) /** * Sync subscription state between NewsBlur and Play Store. */ suspend fun syncActiveSubscription(): Job /** * Notify backend of active Play Store subscription. */ fun saveReceipt(purchase: Purchase) suspend fun hasActiveSubscription(): Boolean } interface SubscriptionsListener { fun onActiveSubscription(renewalMessage: String?) {} fun onAvailableSubscription(skuDetails: SkuDetails) {} fun onBillingConnectionReady() {} fun onBillingConnectionError(message: String? = null) {} } @EntryPoint @InstallIn(SingletonComponent::class) interface SubscriptionManagerEntryPoint { fun apiManager(): APIManager } class SubscriptionManagerImpl( private val context: Context, private val scope: CoroutineScope = NBScope, ) : SubscriptionManager { private var listener: SubscriptionsListener? = null private val acknowledgePurchaseListener = AcknowledgePurchaseResponseListener { billingResult: BillingResult -> when (billingResult.responseCode) { BillingClient.BillingResponseCode.OK -> { Log.d(this, "acknowledgePurchaseResponseListener OK") scope.launch(Dispatchers.Default) { syncActiveSubscription() } } BillingClient.BillingResponseCode.BILLING_UNAVAILABLE -> { // Billing API version is not supported for the type requested. Log.d(this, "acknowledgePurchaseResponseListener BILLING_UNAVAILABLE") } BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE -> { // Network connection is down. Log.d(this, "acknowledgePurchaseResponseListener SERVICE_UNAVAILABLE") } else -> { // Handle any other error codes. Log.d(this, "acknowledgePurchaseResponseListener ERROR - message: " + billingResult.debugMessage) } } } /** * Billing client listener triggered after every user purchase intent. */ private val purchaseUpdateListener = PurchasesUpdatedListener { billingResult: BillingResult, purchases: List<Purchase>? -> if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) { Log.d(this, "purchaseUpdateListener OK") for (purchase in purchases) { handlePurchase(purchase) } } else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) { // Handle an error caused by a user cancelling the purchase flow. Log.d(this, "purchaseUpdateListener USER_CANCELLED") } else if (billingResult.responseCode == BillingClient.BillingResponseCode.BILLING_UNAVAILABLE) { // Billing API version is not supported for the type requested. Log.d(this, "purchaseUpdateListener BILLING_UNAVAILABLE") } else if (billingResult.responseCode == BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE) { // Network connection is down. Log.d(this, "purchaseUpdateListener SERVICE_UNAVAILABLE") } else { // Handle any other error codes. Log.d(this, "purchaseUpdateListener ERROR - message: " + billingResult.debugMessage) } } private val billingClientStateListener: BillingClientStateListener = object : BillingClientStateListener { override fun onBillingSetupFinished(billingResult: BillingResult) { if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) { Log.d(this, "onBillingSetupFinished OK") listener?.onBillingConnectionReady() } else { listener?.onBillingConnectionError("Error connecting to Play Store.") } } override fun onBillingServiceDisconnected() { Log.d(this, "onBillingServiceDisconnected") // Try to restart the connection on the next request to // Google Play by calling the startConnection() method. listener?.onBillingConnectionError("Error connecting to Play Store.") } } private val billingClient: BillingClient = BillingClient.newBuilder(context) .setListener(purchaseUpdateListener) .enablePendingPurchases() .build() override fun startBillingConnection(listener: SubscriptionsListener?) { this.listener = listener billingClient.startConnection(billingClientStateListener) } override fun syncSubscriptionState() { scope.launch(Dispatchers.Default) { if (hasActiveSubscription()) syncActiveSubscription() else syncAvailableSubscription() } } override fun purchaseSubscription(activity: Activity, skuDetails: SkuDetails) { Log.d(this, "launchBillingFlow for sku: ${skuDetails.sku}") val billingFlowParams = BillingFlowParams.newBuilder() .setSkuDetails(skuDetails) .build() billingClient.launchBillingFlow(activity, billingFlowParams) } override suspend fun syncActiveSubscription() = scope.launch(Dispatchers.Default) { val hasNewsBlurSubscription = PrefsUtils.getIsPremium(context) val activePlayStoreSubscription = getActiveSubscriptionAsync().await() if (hasNewsBlurSubscription || activePlayStoreSubscription != null) { listener?.let { val renewalString: String? = getRenewalMessage(activePlayStoreSubscription) withContext(Dispatchers.Main) { it.onActiveSubscription(renewalString) } } } if (!hasNewsBlurSubscription && activePlayStoreSubscription != null) { saveReceipt(activePlayStoreSubscription) } } override suspend fun hasActiveSubscription(): Boolean = PrefsUtils.getIsPremium(context) || getActiveSubscriptionAsync().await() != null override fun saveReceipt(purchase: Purchase) { Log.d(this, "saveReceipt: ${purchase.orderId}") val hiltEntryPoint = EntryPointAccessors .fromApplication(context.applicationContext, SubscriptionManagerEntryPoint::class.java) scope.executeAsyncTask( doInBackground = { hiltEntryPoint.apiManager().saveReceipt(purchase.orderId, purchase.skus.first()) }, onPostExecute = { if (!it.isError) { NBSyncService.forceFeedsFolders() FeedUtils.triggerSync(context) } } ) } private suspend fun syncAvailableSubscription() = scope.launch(Dispatchers.Default) { val skuDetails = getAvailableSubscriptionAsync().await() withContext(Dispatchers.Main) { skuDetails?.let { Log.d(this, it.toString()) listener?.onAvailableSubscription(it) } ?: listener?.onBillingConnectionError() } } private fun getAvailableSubscriptionAsync(): Deferred<SkuDetails?> { val deferred = CompletableDeferred<SkuDetails?>() val params = SkuDetailsParams.newBuilder().apply { // add subscription SKUs from Play Store setSkusList(listOf(AppConstants.PREMIUM_SKU)) setType(BillingClient.SkuType.SUBS) }.build() billingClient.querySkuDetailsAsync(params) { _: BillingResult?, skuDetailsList: List<SkuDetails>? -> Log.d(this, "SkuDetailsResponse ${skuDetailsList.toString()}") skuDetailsList?.let { // Currently interested only in the premium yearly News Blur subscription. val skuDetails = it.find { skuDetails -> skuDetails.sku == AppConstants.PREMIUM_SKU } Log.d(this, skuDetails.toString()) deferred.complete(skuDetails) } ?: deferred.complete(null) } return deferred } private fun getActiveSubscriptionAsync(): Deferred<Purchase?> { val deferred = CompletableDeferred<Purchase?>() billingClient.queryPurchasesAsync(BillingClient.SkuType.SUBS) { _, purchases -> val purchase = purchases.find { purchase -> purchase.skus.contains(AppConstants.PREMIUM_SKU) } deferred.complete(purchase) } return deferred } private fun handlePurchase(purchase: Purchase) { Log.d(this, "handlePurchase: ${purchase.orderId}") if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED && purchase.isAcknowledged) { scope.launch(Dispatchers.Default) { syncActiveSubscription() } } else if (purchase.purchaseState == Purchase.PurchaseState.PURCHASED && !purchase.isAcknowledged) { // need to acknowledge first time sub otherwise it will void Log.d(this, "acknowledge purchase: ${purchase.orderId}") AcknowledgePurchaseParams.newBuilder() .setPurchaseToken(purchase.purchaseToken) .build() .also { billingClient.acknowledgePurchase(it, acknowledgePurchaseListener) } } } /** * Generate subscription renewal message. */ private fun getRenewalMessage(purchase: Purchase?): String? { val expirationTimeMs = PrefsUtils.getPremiumExpire(context) return when { // lifetime subscription expirationTimeMs == 0L -> { context.getString(R.string.premium_subscription_no_expiration) } expirationTimeMs > 0 -> { // date constructor expects ms val expirationDate = Date(expirationTimeMs * 1000) val dateFormat: DateFormat = SimpleDateFormat("EEE, MMMM d, yyyy", Locale.getDefault()) dateFormat.timeZone = TimeZone.getDefault() if (purchase != null && !purchase.isAutoRenewing) { context.getString(R.string.premium_subscription_expiration, dateFormat.format(expirationDate)) } else { context.getString(R.string.premium_subscription_renewal, dateFormat.format(expirationDate)) } } else -> null } } }
clients/android/NewsBlur/src/com/newsblur/subscription/SubscriptionManager.kt
564176978
package com.ruuvi.station.network.data.response typealias SharedSensorsResponse = RuuviNetworkResponse<SharedSensorsResponseBody> data class SharedSensorsResponseBody ( val sensors: List<SharedSensorDataResponse> ) data class SharedSensorDataResponse( val sensor: String, val name: String, val picture: String, val public: Boolean, val sharedTo: String )
app/src/main/java/com/ruuvi/station/network/data/response/SharedSensorsResponse.kt
2943563052
package com.jetbrains.rider.plugins.unity.css.uss import com.intellij.lang.css.CSSLanguage object UssLanguage: CSSLanguage(INSTANCE, "USS")
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/css/uss/UssLanguage.kt
648325250
package org.eyeseetea.malariacare.data.repositories import okhttp3.OkHttpClient import org.eyeseetea.malariacare.data.d2api.BasicAuthInterceptor import org.eyeseetea.malariacare.data.d2api.UserD2Api import org.eyeseetea.malariacare.data.database.utils.PreferencesState import org.eyeseetea.malariacare.domain.boundary.repositories.UserFailure import org.eyeseetea.malariacare.domain.boundary.repositories.UserRepository import org.eyeseetea.malariacare.domain.common.Either import org.eyeseetea.malariacare.domain.entity.User import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class UserD2ApiRepository : UserRepository { private lateinit var userD2Api: UserD2Api private var lastServerURL: String? = null init { initializeApi() } override fun getCurrent(): Either<UserFailure, User> { return try { initializeApi() val userResponse = userD2Api.getMe().execute() if (userResponse!!.isSuccessful && userResponse.body() != null) { val user = userResponse.body() Either.Right(user!!) } else { Either.Left(UserFailure.UnexpectedError) } } catch (e: Exception) { Either.Left(UserFailure.NetworkFailure) } } private fun initializeApi() { val credentials = PreferencesState.getInstance().creedentials if (credentials != null && credentials.serverURL != lastServerURL) { val authInterceptor = BasicAuthInterceptor(credentials.username, credentials.password) val retrofit = Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .client( OkHttpClient.Builder() .addInterceptor(authInterceptor).build() ) .baseUrl(credentials.serverURL) .build() userD2Api = retrofit.create(UserD2Api::class.java) lastServerURL = credentials.serverURL } } }
app/src/main/java/org/eyeseetea/malariacare/data/repositories/UserD2ApiRepository.kt
3997652790
package cz.vhromada.catalog.web.validator import cz.vhromada.catalog.web.fo.MovieFO import cz.vhromada.catalog.web.validator.constraints.Imdb import javax.validation.ConstraintValidator import javax.validation.ConstraintValidatorContext /** * A class represents show validator for IMDB code constraint. * * @author Vladimir Hromada */ class ImdbMovieValidator : ConstraintValidator<Imdb, MovieFO> { override fun isValid(movie: MovieFO?, constraintValidatorContext: ConstraintValidatorContext): Boolean { if (movie == null) { return false } return if (!movie.imdb) { true } else !movie.imdbCode.isNullOrBlank() } }
src/main/kotlin/cz/vhromada/catalog/web/validator/ImdbMovieValidator.kt
3216819208
package com.waz.zclient.storage.db.accountdata import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldEqualTo import org.amshove.kluent.shouldNotBe import org.junit.Before import org.junit.Test class AccessTokenConverterTest { private lateinit var accessTokenConverter: AccessTokenConverter @Before fun setUp() { accessTokenConverter = AccessTokenConverter() } @Test fun `given a string with token, type and expires, when fromStringToAccessToken called, maps it to AccessTokenEntity`() { val tokenString = """ { "token":"fbLpw9Entnm9WWbTyrEhE7GywnTTLqBDI6MAF6JyzdoerAHQQ9BsuubUjGO77GMiW1WJ8jJxqXaA9fHbXAMnCA==.v=1.k=1.d=1579283492.t=a.l=.u=1c5af167-fd5d-4ee5-a11b-fe93b1882ade.c=6843294628315865806", "type":"Bearer", "expires":1579283491844 } """.trimIndent() val entity = accessTokenConverter.fromStringToAccessToken(tokenString) entity shouldNotBe null entity!!.token shouldEqualTo "fbLpw9Entnm9WWbTyrEhE7GywnTTLqBDI6MAF6JyzdoerAHQQ9BsuubUjGO77GMiW1WJ8jJxqXaA9fHbXAMnCA==.v=1.k=1.d=1579283492.t=a.l=.u=1c5af167-fd5d-4ee5-a11b-fe93b1882ade.c=6843294628315865806" entity.tokenType shouldEqualTo "Bearer" entity.expiresInMillis shouldEqualTo 1579283491844 } @Test fun `given a string with invalid structure, when fromStringToAccessToken called, returns null AccessTokenEntity`() { val tokenString = """ { "name": "unrelated" } """.trimIndent() val entity = accessTokenConverter.fromStringToAccessToken(tokenString) entity shouldBe null } @Test fun `given an AccessTokenEntity, when accessTokenToString called, maps it to correct json string`() { val entity = AccessTokenEntity("token", "type", 1000) val jsonString = accessTokenConverter.accessTokenToString(entity)!! jsonString shouldEqualTo """ { "token": "token", "type": "type", "expires": 1000 } """.trimIndent() } }
storage/src/test/kotlin/com/waz/zclient/storage/db/accountdata/AccessTokenConverterTest.kt
1638732363
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.gradle.gradlebuild.testing.integrationtests.cleanup enum class WhenNotEmpty { /** Fail the build when files are found */ FAIL, /** Report only that files were found */ REPORT; }
buildSrc/subprojects/cleanup/src/main/kotlin/org/gradle/gradlebuild/testing/integrationtests/cleanup/WhenNotEmpty.kt
2575758562
package jp.toastkid.yobidashi.search.suggestion import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import androidx.cardview.widget.CardView import androidx.core.view.isVisible import androidx.databinding.DataBindingUtil import com.google.android.flexbox.AlignItems import com.google.android.flexbox.FlexDirection import com.google.android.flexbox.FlexWrap import com.google.android.flexbox.FlexboxLayoutManager import com.google.android.flexbox.JustifyContent import jp.toastkid.api.suggestion.SuggestionApi import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.ViewCardSearchSuggestionBinding import jp.toastkid.yobidashi.libs.Toaster import jp.toastkid.yobidashi.libs.network.NetworkChecker import jp.toastkid.yobidashi.search.SearchFragmentViewModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Facade of search suggestion module. * Initialize with binding object. * * @author toastkidjp */ class SuggestionCardView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : CardView(context, attrs, defStyleAttr) { /** * Suggest ModuleAdapter. */ private var adapter: Adapter? = null /** * Suggestion API. */ private val suggestionApi = SuggestionApi() /** * Cache. */ private val cache = HashMap<String, List<String>>(SUGGESTION_CACHE_CAPACITY) private var binding: ViewCardSearchSuggestionBinding? = null /** * Last subscription's lastSubscription. */ private var lastSubscription: Job? = null init { val from = LayoutInflater.from(context) binding = DataBindingUtil.inflate( from, R.layout.view_card_search_suggestion, this, true ) adapter = Adapter(from) val layoutManager = FlexboxLayoutManager(context) layoutManager.flexDirection = FlexDirection.ROW layoutManager.flexWrap = FlexWrap.WRAP layoutManager.justifyContent = JustifyContent.FLEX_START layoutManager.alignItems = AlignItems.STRETCH initializeSearchSuggestionList(layoutManager) } private fun initializeSearchSuggestionList(layoutManager: FlexboxLayoutManager) { binding?.searchSuggestions?.layoutManager = layoutManager binding?.searchSuggestions?.adapter = adapter } /** * Clear suggestion items. */ fun clear() { adapter?.clear() adapter?.notifyDataSetChanged() } /** * Request web API. * * @param key */ fun request(key: String) { lastSubscription?.cancel() if (cache.containsKey(key)) { val cachedList = cache[key] ?: return lastSubscription = replace(cachedList) return } val context = context if (NetworkChecker.isNotAvailable(context)) { return } if (PreferenceApplier(context).wifiOnly && NetworkChecker.isUnavailableWiFi(context)) { Toaster.tShort(context, R.string.message_wifi_not_connecting) return } suggestionApi.fetchAsync(key) { suggestions -> if (suggestions.isEmpty()) { CoroutineScope(Dispatchers.Main).launch { hide() } return@fetchAsync } cache[key] = suggestions lastSubscription = replace(suggestions) } } /** * Use for voice search. * * @param words Recognizer result words. */ internal fun addAll(words: List<String>) { CoroutineScope(Dispatchers.Main).launch { withContext(Dispatchers.Default) { words.forEach { adapter?.add(it) } } adapter?.notifyDataSetChanged() } } /** * Replace suggestions with specified items. * * @param suggestions * @return [Job] */ private fun replace(suggestions: Iterable<String>): Job { return CoroutineScope(Dispatchers.Main).launch { withContext(Dispatchers.Default) { adapter?.clear() suggestions.forEach { adapter?.add(it) } } show() adapter?.notifyDataSetChanged() } } /** * Show this module. */ fun show() { if (!isVisible && isEnabled) { runOnMainThread { isVisible = true } } } /** * Hide this module. */ fun hide() { if (isVisible) { runOnMainThread { isVisible = false } } } private fun runOnMainThread(action: () -> Unit) = post { action() } fun setViewModel(viewModel: SearchFragmentViewModel) { adapter?.setViewModel(viewModel) } /** * Dispose last subscription. */ fun dispose() { lastSubscription?.cancel() binding = null } companion object { /** * Suggest cache capacity. */ private const val SUGGESTION_CACHE_CAPACITY = 30 } }
app/src/main/java/jp/toastkid/yobidashi/search/suggestion/SuggestionCardView.kt
1644813384
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trackr.ui import android.view.View import androidx.databinding.ViewDataBinding import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver /** * Retrieves a data binding handle in a Fragment. The property should not be accessed before * [Fragment.onViewCreated]. * * ``` * private val binding by dataBindings(HomeFragmentBinding::bind) * * override fun onViewCreated(view: View, savedInstanceState: Bundle?) { * // Use the binding. * } * ``` */ inline fun <reified BindingT : ViewDataBinding> Fragment.dataBindings( crossinline bind: (View) -> BindingT ) = object : Lazy<BindingT> { private var cached: BindingT? = null private val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_DESTROY) { cached = null } } override val value: BindingT get() = cached ?: bind(requireView()).also { it.lifecycleOwner = viewLifecycleOwner viewLifecycleOwner.lifecycle.addObserver(observer) cached = it } override fun isInitialized() = cached != null }
app/src/main/java/com/example/android/trackr/ui/DataBindingDelegates.kt
3147158924
@file:JsQualifier("debug") @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "DEPRECATION" ) package debug import kotlin.js.* import kotlin.js.Json import org.khronos.webgl.* import org.w3c.dom.* import org.w3c.dom.events.* import org.w3c.dom.parsing.* import org.w3c.dom.svg.* import org.w3c.dom.url.* import org.w3c.fetch.* import org.w3c.files.* import org.w3c.notifications.* import org.w3c.performance.* import org.w3c.workers.* import org.w3c.xhr.* external interface Debug { @nativeInvoke operator fun invoke(namespace: String): Debugger var coerce: (`val`: Any) -> Any var disable: () -> String var enable: (namespaces: String) -> Unit var enabled: (namespaces: String) -> Boolean var log: (args: Any) -> Any var names: Array<RegExp> var skips: Array<RegExp> var formatters: Formatters } external interface Formatters { @nativeGetter operator fun get(formatter: String): ((v: Any) -> String)? @nativeSetter operator fun set(formatter: String, value: (v: Any) -> String) } external interface Debugger { @nativeInvoke operator fun invoke(formatter: Any, vararg args: Any) var color: String var enabled: Boolean var log: (args: Any) -> Any var namespace: String var destroy: () -> Boolean var extend: (namespace: String, delimiter: String? /* = null */) -> Debugger }
src/jsMain/kotlin/debug/index.debug.module_debug.kt
4066661374
package com.eden.orchid.bsdoc import com.eden.orchid.api.registration.OrchidModule import com.eden.orchid.api.theme.Theme import com.eden.orchid.utilities.addToSet class BsDocModule : OrchidModule() { override fun configure() { addToSet<Theme, BSDocTheme>() } }
themes/OrchidBsDoc/src/main/kotlin/com/eden/orchid/bsdoc/BsDocModule.kt
3804594753
/** * DO NOT EDIT THIS FILE. * * This source code was autogenerated from source code within the `app/src/gms` directory * and is not intended for modifications. If any edits should be made, please do so in the * corresponding file under the `app/src/gms` directory. */ /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.kotlindemos import android.Manifest import android.annotation.SuppressLint import android.os.Bundle import android.view.View import android.widget.CheckBox import androidx.appcompat.app.AppCompatActivity import com.google.android.libraries.maps.GoogleMap import com.google.android.libraries.maps.OnMapReadyCallback import com.google.android.libraries.maps.SupportMapFragment import pub.devrel.easypermissions.AfterPermissionGranted import pub.devrel.easypermissions.EasyPermissions const val REQUEST_CODE_LOCATION = 123 class UiSettingsDemoActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var map: GoogleMap override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_ui_settings_demo) val mapFragment: SupportMapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) } override fun onMapReady(googleMap: GoogleMap?) { // Return early if map is not initialised properly map = googleMap ?: return enableMyLocation() // Set all the settings of the map to match the current state of the checkboxes with(map.uiSettings) { isZoomControlsEnabled = isChecked(R.id.zoom_button) isCompassEnabled = isChecked(R.id.compass_button) isMyLocationButtonEnabled = isChecked(R.id.myloc_button) isIndoorLevelPickerEnabled = isChecked(R.id.level_button) isMapToolbarEnabled = isChecked(R.id.maptoolbar_button) isZoomGesturesEnabled = isChecked(R.id.zoomgest_button) isScrollGesturesEnabled = isChecked(R.id.scrollgest_button) isTiltGesturesEnabled = isChecked(R.id.tiltgest_button) isRotateGesturesEnabled = isChecked(R.id.rotategest_button) } } /** On click listener for checkboxes */ fun onClick(view: View) { if (view !is CheckBox) { return } val isChecked: Boolean = view.isChecked with(map.uiSettings) { when (view.id) { R.id.zoom_button -> isZoomControlsEnabled = isChecked R.id.compass_button -> isCompassEnabled = isChecked R.id.myloc_button -> isMyLocationButtonEnabled = isChecked R.id.level_button -> isIndoorLevelPickerEnabled = isChecked R.id.maptoolbar_button -> isMapToolbarEnabled = isChecked R.id.zoomgest_button -> isZoomGesturesEnabled = isChecked R.id.scrollgest_button -> isScrollGesturesEnabled = isChecked R.id.tiltgest_button -> isTiltGesturesEnabled = isChecked R.id.rotategest_button -> isRotateGesturesEnabled = isChecked } } } /** Returns whether the checkbox with the given id is checked */ private fun isChecked(id: Int) = findViewById<CheckBox>(id)?.isChecked ?: false /** Override the onRequestPermissionResult to use EasyPermissions */ override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this) } /** * enableMyLocation() will enable the location of the map if the user has given permission * for the app to access their device location. * Android Studio requires an explicit check before setting map.isMyLocationEnabled to true * but we are using EasyPermissions to handle it so we can suppress the "MissingPermission" * check. */ @SuppressLint("MissingPermission") @AfterPermissionGranted(REQUEST_CODE_LOCATION) private fun enableMyLocation() { if (hasLocationPermission()) { map.isMyLocationEnabled = true } else { EasyPermissions.requestPermissions(this, getString(R.string.location), REQUEST_CODE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION ) } } private fun hasLocationPermission(): Boolean { return EasyPermissions.hasPermissions(this, Manifest.permission.ACCESS_FINE_LOCATION) } }
ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/UiSettingsDemoActivity.kt
4160071796
package com.supercilex.robotscouter.core.data import android.content.Intent import android.os.Bundle import androidx.core.os.bundleOf import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.supercilex.robotscouter.core.model.Team const val TEAM_KEY = "com.supercilex.robotscouter.data.util.Team" const val TEAMS_KEY = "com.supercilex.robotscouter.data.util.Teams" const val REF_KEY = "com.supercilex.robotscouter.REF" const val TAB_KEY = "tab_key" const val SCOUT_ARGS_KEY = "scout_args" const val TEMPLATE_ARGS_KEY = "template_args" const val KEY_ADD_SCOUT = "add_scout" const val KEY_OVERRIDE_TEMPLATE_KEY = "override_template_key" fun <T : CharSequence> T?.nullOrFull() = takeUnless { isNullOrBlank() } fun Bundle.putRef(ref: DocumentReference) = putString(REF_KEY, ref.path) fun Bundle.getRef() = Firebase.firestore.document(checkNotNull(getString(REF_KEY))) fun Team.toBundle() = bundleOf(TEAM_KEY to this@toBundle) fun Intent.putExtra(teams: List<Team>): Intent = putExtra(TEAMS_KEY, ArrayList(teams)) fun Bundle.getTeam(): Team = checkNotNull(getParcelable(TEAM_KEY)) fun Intent.getTeamListExtra(): List<Team> = getParcelableArrayListExtra<Team>(TEAMS_KEY).orEmpty() fun getTabIdBundle(key: String?) = bundleOf(TAB_KEY to key) fun getTabId(bundle: Bundle?): String? = bundle?.getString(TAB_KEY) fun getScoutBundle( team: Team, addScout: Boolean = false, overrideTemplateId: String? = null, scoutId: String? = null ): Bundle { require(addScout || overrideTemplateId == null) { "Can't use an override id without adding a scout." } return team.toBundle().apply { putBoolean(KEY_ADD_SCOUT, addScout) putString(KEY_OVERRIDE_TEMPLATE_KEY, overrideTemplateId) putAll(getTabIdBundle(scoutId)) } }
library/core-data/src/main/java/com/supercilex/robotscouter/core/data/Args.kt
1707128592
package org.koin.sample.androidx.scope import android.os.Bundle import kotlinx.android.synthetic.main.scoped_activity_a.* import org.junit.Assert.* import org.koin.androidx.scope.ScopeActivity import org.koin.core.qualifier.named import org.koin.sample.android.R import org.koin.sample.androidx.components.* import org.koin.sample.androidx.components.scope.Session import org.koin.sample.androidx.components.scope.SessionActivity import org.koin.sample.androidx.utils.navigateTo class ScopedActivityA : ScopeActivity(contentLayoutId = R.layout.scoped_activity_a) { // Inject from current scope val currentSession by inject<Session>() val currentActivitySession by inject<SessionActivity>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) assertEquals(currentSession, get<Session>()) // Conpare different scope instances val scopeSession1 = getKoin().createScope(SESSION_1, named(SCOPE_ID)) val scopeSession2 = getKoin().createScope(SESSION_2, named(SCOPE_ID)) assertNotEquals(scopeSession1.get<Session>(named(SCOPE_SESSION)), currentSession) assertNotEquals(scopeSession1.get<Session>(named(SCOPE_SESSION)), scopeSession2.get<Session>(named(SCOPE_SESSION))) // set data in scope SCOPE_ID val session = getKoin().createScope(SCOPE_ID, named(SCOPE_ID)).get<Session>(named(SCOPE_SESSION)) session.id = ID title = "Scope Activity A" scoped_a_button.setOnClickListener { navigateTo<ScopedActivityB>(isRoot = true) } assertTrue(this == currentActivitySession.activity) } }
koin-projects/examples/androidx-samples/src/main/java/org/koin/sample/androidx/scope/ScopedActivityA.kt
1407719804
// 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.actions.styling.util import com.intellij.psi.PsiElement import com.vladsch.plugin.util.ArrayListBag import java.util.function.Function class ElementListBag<T : Any>(mapper: Function<PsiElement, T>) : ArrayListBag<PsiElement, T>(mapper)
src/main/java/com/vladsch/md/nav/actions/styling/util/ElementListBag.kt
1045514744
package ch.yvu.teststore.run.overview import ch.yvu.teststore.run.overview.RunStatistics.RunResult.* import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class RunResultTest { @Test fun passedIsMoreSevereThanUnknown() { assertTrue(PASSED.isMoreSevere(UNKNOWN)) } @Test fun passedWithRetriesIsMoreSevereThanPassed() { assertTrue(PASSED_WITH_RETRIES.isMoreSevere(PASSED)) } @Test fun failedIsMoreSevereThanPassedWithRetries() { assertTrue(FAILED.isMoreSevere(PASSED_WITH_RETRIES)) } @Test fun runResultIsNotMoreSevereThanItself() { assertFalse(PASSED.isMoreSevere(PASSED)) } }
backend/src/test/kotlin/ch/yvu/teststore/run/overview/RunResultTest.kt
2290447116
package com.booboot.vndbandroid.repository import android.app.Application import com.booboot.vndbandroid.api.VNDBService import com.booboot.vndbandroid.dao.TagDao import com.booboot.vndbandroid.di.BoxManager import com.booboot.vndbandroid.extensions.get import com.booboot.vndbandroid.extensions.save import com.booboot.vndbandroid.extensions.saveToDisk import com.booboot.vndbandroid.extensions.toBufferedSource import com.booboot.vndbandroid.extensions.unzip import com.booboot.vndbandroid.extensions.use import com.booboot.vndbandroid.model.vndb.Tag import com.booboot.vndbandroid.model.vndbandroid.Expiration import com.squareup.moshi.Moshi import com.squareup.moshi.Types import javax.inject.Inject import javax.inject.Singleton @Singleton class TagsRepository @Inject constructor( private var vndbService: VNDBService, var moshi: Moshi, var app: Application, var boxManager: BoxManager ) : Repository<Tag>() { override suspend fun getItems(cachePolicy: CachePolicy<Map<Long, Tag>>) = cachePolicy .fetchFromMemory { items } .fetchFromDatabase { boxManager.boxStore.get<TagDao, Map<Long, Tag>> { it.all.map { tagDao -> tagDao.toBo() }.associateBy { tag -> tag.id } } } .fetchFromNetwork { vndbService .getTags() .saveToDisk("tags.json.gz", app.cacheDir) .unzip() .use { moshi .adapter<List<Tag>>(Types.newParameterizedType(List::class.java, Tag::class.java)) .fromJson(it.toBufferedSource()) ?.associateBy { tag -> tag.id } ?: throw Exception("Error while getting tags : empty.") } } .putInMemory { items = it.toMutableMap() } .putInDatabase { boxManager.boxStore.save(true) { it.map { TagDao(it.value, boxManager.boxStore) } } } .isExpired { System.currentTimeMillis() > Expiration.tags } .putExpiration { Expiration.tags = System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 7 } .get() }
app/src/main/java/com/booboot/vndbandroid/repository/TagsRepository.kt
1470303451
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek class ThrowingNewInstanceOfSameExceptionSpek : SubjectSpek<ThrowingNewInstanceOfSameException>({ subject { ThrowingNewInstanceOfSameException() } given("a catch block which rethrows a new instance of the caught exception") { val code = """ fun x() { try { } catch (e: IllegalStateException) { throw IllegalStateException(e) } } """ it("should report") { val findings = subject.lint(code) Assertions.assertThat(findings).hasSize(1) } } given("a catch block which rethrows a new instance of another exception") { val code = """ fun x() { try { } catch (e: IllegalStateException) { throw IllegalArgumentException(e) } } """ it("should not report") { val findings = subject.lint(code) Assertions.assertThat(findings).hasSize(0) } } given("a catch block which throws a new instance of the same exception type without wrapping the caught exception") { val code = """ fun x() { try { } catch (e: IllegalStateException) { throw IllegalStateException() } } """ it("should not report") { val findings = subject.lint(code) Assertions.assertThat(findings).hasSize(0) } } })
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/ThrowingNewInstanceOfSameExceptionSpek.kt
3650429750
package com.openlattice.conductor.rpc import com.openlattice.edm.EntitySet import com.openlattice.edm.type.PropertyType import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import java.io.Serializable import java.util.* import java.util.function.Function @SuppressFBWarnings(value = ["SE_BAD_FIELD"], justification = "Custom Stream Serializer is implemented") data class ReIndexEntitySetMetadataLambdas( val entitySets: Map<EntitySet, Set<UUID>>, val propertyTypes: Map<UUID, PropertyType> ) : Function<ConductorElasticsearchApi, Boolean>, Serializable { override fun apply(api: ConductorElasticsearchApi): Boolean { return api.triggerEntitySetIndex(entitySets, propertyTypes) } }
src/main/kotlin/com/openlattice/conductor/rpc/ReIndexEntitySetMetadataLambdas.kt
1428901751
package io.gitlab.arturbosch.detekt.rules.exceptions import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek class ThrowingExceptionsWithoutMessageOrCauseSpek : SubjectSpek<ThrowingExceptionsWithoutMessageOrCause>({ subject { ThrowingExceptionsWithoutMessageOrCause( TestConfig(mapOf(ThrowingExceptionsWithoutMessageOrCause.EXCEPTIONS to "IllegalArgumentException")) ) } given("several exception calls") { val code = """ fun x() { IllegalArgumentException(IllegalArgumentException()) IllegalArgumentException("foo") throw IllegalArgumentException() }""" it("reports calls to the default constructor") { assertThat(subject.lint(code)).hasSize(2) } it("does not report calls to the default constructor with empty configuration") { val config = TestConfig(mapOf(ThrowingExceptionsWithoutMessageOrCause.EXCEPTIONS to "")) val findings = ThrowingExceptionsWithoutMessageOrCause(config).lint(code) assertThat(findings).hasSize(0) } } })
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/ThrowingExceptionsWithoutMessageOrCauseSpek.kt
247312251
package com.geckour.egret.model import com.github.gfx.android.orma.annotation.* import java.util.* @Table data class AccessToken( @Setter("id") @PrimaryKey(autoincrement = true) val id: Long = -1L, @Setter("access_token") @Column val token: String = "", @Setter("instance_id") @Column val instanceId: Long = -1L, @Setter("account_id") @Column(indexed = true) val accountId: Long = -1L, @Setter("is_current") @Column(indexed = true) var isCurrent: Boolean = false )
app/src/main/java/com/geckour/egret/model/AccessToken.kt
2350206840
package org.http4k.hamkrest import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.has import com.natpryce.hamkrest.present import org.http4k.core.cookie.Cookie import org.http4k.core.cookie.SameSite import java.time.Instant fun hasCookieName(expected: CharSequence): Matcher<Cookie> = has(Cookie::name, equalTo(expected)) @JvmName("hasCookieValueNullableString") fun hasCookieValue(matcher: Matcher<String?>): Matcher<Cookie> = has(Cookie::value, matcher) fun hasCookieValue(matcher: Matcher<String>): Matcher<Cookie> = has(Cookie::value, present(matcher)) fun hasCookieValue(expected: CharSequence): Matcher<Cookie> = has(Cookie::value, equalTo(expected)) fun hasCookieDomain(expected: CharSequence): Matcher<Cookie> = has("domain", { c: Cookie -> c.domain }, equalTo(expected)) fun hasCookiePath(expected: CharSequence): Matcher<Cookie> = has("path", { c: Cookie -> c.path }, equalTo(expected)) fun isSecureCookie(expected: Boolean = true): Matcher<Cookie> = has("secure", { c: Cookie -> c.secure }, equalTo(expected)) fun isHttpOnlyCookie(expected: Boolean = true): Matcher<Cookie> = has("httpOnly", { c: Cookie -> c.httpOnly }, equalTo(expected)) fun hasCookieExpiry(expected: Instant): Matcher<Cookie> = hasCookieExpiry(equalTo(expected)) fun hasCookieExpiry(matcher: Matcher<Instant>): Matcher<Cookie> = has("expiry", { c: Cookie -> c.expires!! }, matcher) fun hasCookieSameSite(expected: SameSite): Matcher<Cookie> = has("sameSite", { c: Cookie -> c.sameSite }, equalTo(expected))
http4k-testing/hamkrest/src/main/kotlin/org/http4k/hamkrest/cookie.kt
1392848944
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.docs.actuator.endpoints.health.reactivehealthindicators import org.springframework.boot.actuate.health.Health import org.springframework.boot.actuate.health.ReactiveHealthIndicator import org.springframework.stereotype.Component import reactor.core.publisher.Mono @Component class MyReactiveHealthIndicator : ReactiveHealthIndicator { override fun health(): Mono<Health> { // @formatter:off return doHealthCheck()!!.onErrorResume { exception: Throwable? -> Mono.just(Health.Builder().down(exception).build()) } // @formatter:on } private fun doHealthCheck(): Mono<Health>? { // perform some specific health check return /**/ null } }
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/actuator/endpoints/health/reactivehealthindicators/MyReactiveHealthIndicator.kt
719585654
package at.hschroedl.fluentast.ast.type import at.hschroedl.fluentast.test.toInlineString import org.eclipse.jdt.core.dom.AST import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource internal class PrimitiveTypeTest { private lateinit var ast: AST @BeforeEach internal fun setUp() { ast = AST.newAST(AST.JLS8) } @ParameterizedTest(name = "Create primtive type '{0}") @ValueSource(strings = arrayOf("byte", "short", "char", "int", "long", "float", "double", "boolean", "void")) internal fun primitiveType_withInt_shouldReturnInt(type: String) { val result = FluentPrimitiveType(type).build(ast) assertEquals(type, result.toInlineString()) } }
core/src/test/kotlin/at.hschroedl.fluentast/ast/type/PrimitiveTypeTest.kt
439798363
/* * Copyright (c) 2010-2022 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.habdroid.ui.preference import android.content.Context import android.os.Build import android.text.InputType import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.ArrayAdapter import androidx.core.content.edit import androidx.core.os.bundleOf import androidx.fragment.app.DialogFragment import androidx.preference.DialogPreference import androidx.preference.PreferenceDialogFragmentCompat import com.google.android.material.switchmaterial.SwitchMaterial import com.google.android.material.textfield.MaterialAutoCompleteTextView import com.google.android.material.textfield.TextInputLayout import org.openhab.habdroid.R import org.openhab.habdroid.core.OpenHabApplication import org.openhab.habdroid.model.toWifiSsids import org.openhab.habdroid.ui.CustomDialogPreference import org.openhab.habdroid.util.getCurrentWifiSsid class WifiSsidInputPreference constructor(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs), CustomDialogPreference { private var value: Pair<String, Boolean>? = null init { dialogTitle = null setPositiveButtonText(android.R.string.ok) setNegativeButtonText(android.R.string.cancel) } override fun getDialogLayoutResource(): Int { return R.layout.pref_dialog_wifi_ssid } private fun updateSummary() { val ssids = value?.first?.toWifiSsids() summary = if (ssids.isNullOrEmpty()) { context.getString(R.string.info_not_set) } else { ssids.joinToString(", ") } } fun setValue(value: Pair<String, Boolean>? = this.value) { if (callChangeListener(value)) { this.value = value updateSummary() } } override fun createDialog(): DialogFragment { return PrefFragment.newInstance(key, title) } class PrefFragment : PreferenceDialogFragmentCompat() { private lateinit var editorWrapper: TextInputLayout private lateinit var editor: MaterialAutoCompleteTextView private lateinit var restrictButton: SwitchMaterial override fun onCreateDialogView(context: Context): View { val inflater = LayoutInflater.from(activity) val v = inflater.inflate(R.layout.pref_dialog_wifi_ssid, null) editorWrapper = v.findViewById(R.id.input_wrapper) editor = v.findViewById(android.R.id.edit) restrictButton = v.findViewById(R.id.restrict_switch) editor.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE arguments?.getCharSequence(KEY_TITLE)?.let { title -> editorWrapper.hint = title } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { editor.importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_NO } val currentValue = (preference as WifiSsidInputPreference).value val currentSsid = preference.context.getCurrentWifiSsid(OpenHabApplication.DATA_ACCESS_TAG_SELECT_SERVER_WIFI) val currentSsidAsArray = currentSsid?.let { arrayOf(it) } ?: emptyArray() val adapter = ArrayAdapter(editor.context, android.R.layout.simple_dropdown_item_1line, currentSsidAsArray) editor.setAdapter(adapter) editor.setText(currentValue?.first.orEmpty()) editor.setSelection(editor.text.length) restrictButton.isChecked = currentValue?.second ?: false return v } override fun onDialogClosed(positiveResult: Boolean) { if (positiveResult) { val prefs = preference.sharedPreferences!! prefs.edit { val pref = preference as WifiSsidInputPreference pref.setValue(Pair(editor.text.toString(), restrictButton.isChecked)) } } } companion object { private const val KEY_TITLE = "title" fun newInstance( key: String, title: CharSequence? ): PrefFragment { val f = PrefFragment() f.arguments = bundleOf( ARG_KEY to key, KEY_TITLE to title ) return f } } } }
mobile/src/main/java/org/openhab/habdroid/ui/preference/WifiSsidInputPreference.kt
1500044441
package uy.kohesive.kovert.template.freemarker.test import freemarker.cache.TemplateNameFormat import freemarker.template.Configuration import io.vertx.core.http.HttpMethod import io.vertx.ext.web.RoutingContext import org.junit.Before import org.junit.Test import uy.kohesive.kovert.core.KovertConfig import uy.kohesive.kovert.core.Rendered import uy.kohesive.kovert.template.freemarker.KovertFreemarkerTemplateEngine import uy.kohesive.kovert.vertx.AbstractKovertTest import uy.kohesive.kovert.vertx.bindController import uy.kohesive.kovert.vertx.test.testServer class TestKovertFreemarkerTemplateEngine : AbstractKovertTest() { @Before override fun beforeTest() { KovertConfig.registerTemplateEngine(KovertFreemarkerTemplateEngine(FreeMarker.engine), ".html.ftl", "text/html") super.beforeTest() } @Test fun testFreemarker() { val controller = RenderController() _router.bindController(controller, "/app") _client.testServer(HttpMethod.GET, "/app/search/people", assertResponse = """ <html> <body> <div>Frank: 88</div> <div>Dave: 20</div> </body> </html>""", assertContentType = "text/html") } } internal class RenderController { @Rendered("test-people-search.html.ftl") fun RoutingContext.getSearchPeople(): PeopleResults { return PeopleResults(listOf(Person("Frank", 88), Person("Dave", 20))) } } internal data class PeopleResults(val persons: List<Person>) internal data class Person(val name: String, val age: Int) // configured Freemarker internal object FreeMarker { val engine: Configuration = run { val cfg = Configuration(Configuration.VERSION_2_3_22) cfg.setDefaultEncoding("UTF-8") cfg.setTemplateNameFormat(TemplateNameFormat.DEFAULT_2_4_0) // cfg.setObjectWrapper(JodaAwareObjectWrapper()) // TODO: dev mode only cfg.setClassLoaderForTemplateLoading(ClassLoader.getSystemClassLoader(), "templates") // alternatively, some locatinn on disk // cfg.setDirectoryForTemplateLoading(File("src/main/resources/templates")) // TODO: dev mode only cfg.setTemplateExceptionHandler(freemarker.template.TemplateExceptionHandler.HTML_DEBUG_HANDLER) // alternatively, RETHROW_HANDLER better for prod cfg } }
template-engine-freemarker/src/test/kotlin/uy/kohesive/kovert/template/freemarker/TestKovertFreemarkerTemplateEngine.kt
3336374659
package rest.repository import model.GoogleResponse import model.GoogleResponseList import model.Location import model.LocationDetails import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query /** * Created by naik on 20.02.16. */ interface GoogleMaps { @GET("maps/api/place/nearbysearch/json") fun getPlaceNear(@Query("location") lonLat: String, @Query("radius") radius: Int, @Query("types") types: String, @Query("name") name: String, @Query("key") apiKey: String) : Call<GoogleResponseList<List<Location>>> @GET("maps/api/place/details/json") fun getPlaceDetails(@Query("placeid") placeId: String, @Query("key") apiKey: String) : Call<GoogleResponse<LocationDetails>> }
src/rest/repository/GoogleMaps.kt
864895233
package de.tfelix.bestia.worldgen.map import java.io.Serializable /** * Map parts describe some discrete unit of a map. This chunks of the map must * be somehow be countable in order to create random data from it. Implementing * this interface describes certain maps. * * @author Thomas Felix */ interface MapChunk : Serializable { /** * Iterator to iterate over all the contained map coordinates contained in * this bunch of map.. * * @return The iterator to iterate all over the contained * [MapCoordinate]. */ val iterator: Iterator<MapCoordinate> /** * Returns an identifier for this specific part of the map. * * @return A unique identifier for this specific part of the map. */ val ident: String /** * Returns the total size/number of [MapCoordinate] inside this map * part. * * @return Total size of this [MapChunk]. */ fun size(): Long fun toGlobalCoordinates(localCords: MapCoordinate): MapCoordinate }
src/main/kotlin/de/tfelix/bestia/worldgen/map/MapChunk.kt
3425345843
package com.michaelflisar.lumberjack import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.core.app.NotificationCompat import com.michaelflisar.feedbackmanager.Feedback import com.michaelflisar.feedbackmanager.FeedbackFile import com.michaelflisar.lumberjack.core.CoreUtil import java.io.File /* * convenient extension to simply show a notification for exceptions/infos/whatever that the user should report if possible * * - app version will be appended to the subject automatically * - file should be local and accessible files - they will be exposed via a ContentProvider so that the email client can access the file */ fun L.showCrashNotification( context: Context, logFile: File?, receiver: String, appIcon: Int, notificationChannelId: String, notificationId: Int, notificationTitle: String = "Rare exception found", notificationText: String = "Please report this error by clicking this notification, thanks", subject: String = "Exception found in ${context.packageName}", titleForChooser: String = "Send report with", filesToAppend: List<File> = emptyList() ) { val allFiles = filesToAppend.toMutableList() logFile?.let { allFiles.add(0, it) } val feedback = Feedback( listOf(receiver), CoreUtil.getRealSubject(context, subject), attachments = allFiles.map { FeedbackFile.DefaultName(it) } ) feedback .startNotification( context, titleForChooser, notificationTitle, notificationText, appIcon, notificationChannelId, notificationId ) } /* * convenient extension to simply show a notification to the user or for debugging infos */ fun L.showInfoNotification( context: Context, notificationChannelId: String, notificationId: Int, notificationTitle: String, notificationText: String, notificationIcon: Int, clickIntent: Intent? = null, apply: ((builder: NotificationCompat.Builder) -> Unit)? = null ) { val pendingIntent = clickIntent?.let { val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_IMMUTABLE } else 0 PendingIntent.getActivity(context, 0, it, flag) } val builder: NotificationCompat.Builder = NotificationCompat.Builder(context, notificationChannelId) .setSmallIcon(notificationIcon) .setContentTitle(notificationTitle) .setContentText(notificationText) pendingIntent?.let { builder.setContentIntent(it) } apply?.let { it(builder) } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(notificationId, builder.build()) }
library-notification/src/main/java/com/michaelflisar/lumberjack/ExtensionNotification.kt
957862642
/* Copyright (c) 2020 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.async import androidx.test.ext.junit.runners.AndroidJUnit4 import com.ichi2.anki.RobolectricTest import com.ichi2.async.CollectionTask.CheckDatabase import com.ichi2.testutils.CollectionUtils import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.mock @RunWith(AndroidJUnit4::class) class CheckDatabaseTest : RobolectricTest() { @Test fun checkDatabaseWithLockedCollectionReturnsLocked() { lockDatabase() val result = CheckDatabase().execTask(col, mock()) assertThat("The result should specify a failure", result.first, equalTo(false)) val checkDbResult = result.second!! assertThat("The result should specify the database was locked", checkDbResult.databaseLocked) } private fun lockDatabase() { CollectionUtils.lockDatabase(col) } }
AnkiDroid/src/test/java/com/ichi2/async/CheckDatabaseTest.kt
3349165865
package v_builders import util.TODO import util.doc36 fun todoTask36(): Nothing = TODO( """ Task 36. Read about extension function literals. You can declare `isEven` and `isOdd` as values, that can be called as extension functions. Complete the declarations below. """, documentation = doc36() ) fun task36(): List<Boolean> { val isEven: Int.() -> Boolean = { this % 2 == 0 } val isOdd: Int.() -> Boolean = { this % 2 == 1 } return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven()) }
src/v_builders/_36_ExtensionFunctionLiterals.kt
2031803387
package jgappsandgames.smartreminderslite.utility // Java import java.util.Arrays // Android OS import android.app.Activity import android.content.pm.ShortcutInfo import android.content.pm.ShortcutManager import android.graphics.drawable.Icon // App import jgappsandgames.smartreminderslite.R // Save import jgappsandgames.smartreminderssave.tasks.TaskManager import jgappsandgames.smartreminderssave.utility.hasShortcuts import org.jetbrains.anko.shortcutManager /** * ShortcutUtility * Created by joshua on 1/5/2018. */ // Create Shortcuts ------------------------------------------------------------------------ fun createTagShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "tag") .setShortLabel("Tags") .setLongLabel("Tags") .setIcon(Icon.createWithResource(activity, R.drawable.label)) .setIntent(buildHomeIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createPriorityShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "priority") .setShortLabel("Priority") .setLongLabel("Priority") .setIcon(Icon.createWithResource(activity, android.R.drawable.btn_star)) .setIntent(buildPriorityIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createStatusShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "status") .setShortLabel("Status") .setLongLabel("Status") .setIcon(Icon.createWithResource(activity, R.drawable.status)) .setIntent(buildStatusIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createTodayShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "today") .setShortLabel("Today") .setLongLabel("Today") .setIcon(Icon.createWithResource(activity, R.drawable.today)) .setIntent(buildDayIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createWeekShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "week") .setShortLabel("Week") .setLongLabel("Week") .setIcon(Icon.createWithResource(activity, R.drawable.week)) .setIntent(buildWeekIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createMonthShortcut(activity: Activity) { if (hasShortcuts()) activity.shortcutManager.addDynamicShortcuts( Arrays.asList(ShortcutInfo.Builder(activity, "month") .setShortLabel("Month") .setLongLabel("Month") .setIntent(buildMonthIntent(activity, IntentOptions(shortcut = true))) .build())) } fun createTaskShortcut(activity: Activity, task: String) { if (hasShortcuts()) { val taskObject = TaskManager.taskPool.getPoolObject().load(task) val sT: String = if (taskObject.getTitle().length > 8) taskObject.getTitle().substring(0, 8) else taskObject.getTitle() activity.shortcutManager.addDynamicShortcuts(Arrays.asList(ShortcutInfo.Builder(activity, task) .setShortLabel(sT) .setLongLabel(taskObject.getTitle()) .setIcon(Icon.createWithResource(activity, android.R.drawable.ic_menu_agenda)) .setIntent(buildTaskIntent(activity, IntentOptions(shortcut = true), TaskOptions(task = taskObject))) .build())) } } // Remove Shortcuts ------------------------------------------------------------------------ fun removeTagShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("tag") manager!!.removeDynamicShortcuts(s) } } fun removePriorityShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("priority") manager!!.removeDynamicShortcuts(s) } } fun removeStatusShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("status") manager!!.removeDynamicShortcuts(s) } } fun removeTodayShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("today") manager!!.removeDynamicShortcuts(s) } } fun removeWeekShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("week") manager!!.removeDynamicShortcuts(s) } } fun removeMonthShortcut(activity: Activity) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add("month") manager!!.removeDynamicShortcuts(s) } } fun removeTaskShortcut(activity: Activity, task: String) { if (hasShortcuts()) { val manager = activity.getSystemService(ShortcutManager::class.java) val s = ArrayList<String>() s.add(task) manager!!.removeDynamicShortcuts(s) } }
app/src/main/java/jgappsandgames/smartreminderslite/utility/ShortcutUtility.kt
2514179256
package com.laimiux.rxmaps.kotlin import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.laimiux.rxmaps.RxGoogleMaps import rx.Observable public fun GoogleMap.cameraPosition(): Observable<CameraPosition> = RxGoogleMaps.cameraPosition(this) public fun GoogleMap.moveAndZoom(latLng: LatLng, zoom: Float) { this.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom)) }
rxmaps-kotlin/src/main/kotlin/com/laimiux/rxmaps/kotlin/googlemaps.kt
1009814308
package de.westnordost.streetcomplete.quests.drinking_water import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.OUTDOORS class AddDrinkingWater : OsmFilterQuestType<DrinkingWater>() { override val elementFilter = """ nodes with ( man_made = water_tap or man_made = water_well or natural = spring ) and access !~ private|no and indoor != yes and !drinking_water and !drinking_water:legal and amenity != drinking_water """ override val commitMessage = "Add whether water is drinkable" override val wikiLink = "Key:drinking_water" override val icon = R.drawable.ic_quest_drinking_water override val isDeleteElementEnabled = true override val questTypeAchievements = listOf(OUTDOORS) override fun getTitle(tags: Map<String, String>) = R.string.quest_drinking_water_title override fun getTitleArgs(tags: Map<String, String>, featureName: Lazy<String?>) = arrayOf(featureName.value.toString()) override fun createForm() = AddDrinkingWaterForm() override fun applyAnswerTo(answer: DrinkingWater, changes: StringMapChangesBuilder) { changes.addOrModify("drinking_water", answer.osmValue) answer.osmLegalValue?.let { changes.addOrModify("drinking_water:legal", it) } } }
app/src/main/java/de/westnordost/streetcomplete/quests/drinking_water/AddDrinkingWater.kt
2132062681
package org.wordpress.android.fluxc.example.ui.products import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_woo_products.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.action.WCProductAction.ADDED_PRODUCT_CATEGORY import org.wordpress.android.fluxc.action.WCProductAction.ADDED_PRODUCT_TAGS import org.wordpress.android.fluxc.action.WCProductAction.DELETED_PRODUCT import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCTS import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCT_CATEGORIES import org.wordpress.android.fluxc.action.WCProductAction.FETCH_PRODUCT_TAGS import org.wordpress.android.fluxc.action.WCProductAction.FETCH_SINGLE_PRODUCT_SHIPPING_CLASS import org.wordpress.android.fluxc.example.R.layout import org.wordpress.android.fluxc.example.prependToLog import org.wordpress.android.fluxc.example.replaceFragment import org.wordpress.android.fluxc.example.ui.StoreSelectingFragment import org.wordpress.android.fluxc.example.utils.showSingleLineDialog import org.wordpress.android.fluxc.generated.WCProductActionBuilder import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.WCProductCategoryModel import org.wordpress.android.fluxc.model.WCProductImageModel import org.wordpress.android.fluxc.store.MediaStore import org.wordpress.android.fluxc.store.WCAddonsStore import org.wordpress.android.fluxc.store.WCProductStore import org.wordpress.android.fluxc.store.WCProductStore.AddProductCategoryPayload import org.wordpress.android.fluxc.store.WCProductStore.AddProductTagsPayload import org.wordpress.android.fluxc.store.WCProductStore.DeleteProductPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductCategoriesPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductReviewsPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductShippingClassListPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductSkuAvailabilityPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductTagsPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductVariationsPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchProductsPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductReviewPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductShippingClassPayload import org.wordpress.android.fluxc.store.WCProductStore.OnProductCategoryChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductImagesChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductShippingClassesChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductSkuAvailabilityChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductTagChanged import org.wordpress.android.fluxc.store.WCProductStore.OnProductsSearched import org.wordpress.android.fluxc.store.WCProductStore.SearchProductsPayload import org.wordpress.android.fluxc.store.WCProductStore.UpdateProductImagesPayload import org.wordpress.android.fluxc.store.WooCommerceStore import javax.inject.Inject @Suppress("LargeClass") class WooProductsFragment : StoreSelectingFragment() { @Inject internal lateinit var dispatcher: Dispatcher @Inject internal lateinit var wcProductStore: WCProductStore @Inject lateinit var addonsStore: WCAddonsStore @Inject internal lateinit var wooCommerceStore: WooCommerceStore @Inject internal lateinit var mediaStore: MediaStore private var pendingFetchSingleProductShippingClassRemoteId: Long? = null private var pendingFetchProductVariationsProductRemoteId: Long? = null private var pendingFetchSingleProductVariationOffset: Int = 0 private var pendingFetchProductShippingClassListOffset: Int = 0 private var pendingFetchProductCategoriesOffset: Int = 0 private var pendingFetchProductTagsOffset: Int = 0 private var enteredCategoryName: String? = null private val enteredTagNames: MutableList<String> = mutableListOf() private val coroutineScope = CoroutineScope(Dispatchers.Main) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(layout.fragment_woo_products, container, false) @Suppress("LongMethod", "ComplexMethod") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fetch_single_product.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog(activity, "Enter the remoteProductId of product to fetch:") { editText -> editText.text.toString().toLongOrNull()?.let { remoteProductId -> prependToLog("Submitting request to fetch product by remoteProductID $remoteProductId") coroutineScope.launch { val result = wcProductStore.fetchSingleProduct( FetchSingleProductPayload( site, remoteProductId ) ) val product = wcProductStore.getProductByRemoteId(site, result.remoteProductId) product?.let { val numVariations = it.getVariationIdList().size if (numVariations > 0) { prependToLog("Single product with $numVariations variations fetched! ${it.name}") } else { prependToLog("Single product fetched! ${it.name}") } } ?: prependToLog("WARNING: Fetched product not found in the local database!") } } ?: prependToLog("No valid remoteOrderId defined...doing nothing") } } } fetch_single_variation.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteProductId of variation to fetch:" ) { productIdText -> val productRemoteId = productIdText.text.toString().toLongOrNull() productRemoteId?.let { productId -> showSingleLineDialog( activity, "Enter the remoteVariationId of variation to fetch:" ) { variationIdText -> variationIdText.text.toString().toLongOrNull()?.let { variationId -> coroutineScope.launch { prependToLog( "Submitting request to fetch product by " + "remoteProductId $productRemoteId, " + "remoteVariationProductID $variationId" ) val result = wcProductStore.fetchSingleVariation(site, productId, variationId) prependToLog("Fetching single variation " + "${result.error?.let { "failed" } ?: "was successful"}" ) val variation = wcProductStore.getVariationByRemoteId( site, result.remoteProductId, result.remoteVariationId ) variation?.let { prependToLog("Variation with id! ${it.remoteVariationId} found in local db") } ?: prependToLog("WARNING: Fetched product not found in the local database!") } } ?: prependToLog("No valid remoteVariationId defined...doing nothing") } } ?: prependToLog("No valid remoteProductId defined...doing nothing") } } } fetch_product_sku_availability.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter a product SKU:" ) { editText -> val payload = FetchProductSkuAvailabilityPayload(site, editText.text.toString()) dispatcher.dispatch(WCProductActionBuilder.newFetchProductSkuAvailabilityAction(payload)) } } } fetch_products.setOnClickListener { selectedSite?.let { site -> val payload = FetchProductsPayload(site) dispatcher.dispatch(WCProductActionBuilder.newFetchProductsAction(payload)) } } fetch_products_with_filters.setOnClickListener { replaceFragment(WooProductFiltersFragment.newInstance(selectedPos)) } fetch_specific_products.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog(activity, "Enter remote product IDs, separated by comma:") { editText -> val ids = editText.text.toString().replace(" ", "").split(",").mapNotNull { val id = it.toLongOrNull() if (id == null) { prependToLog("$it is not a valid remote product ID, ignoring...") } id } if (ids.isNotEmpty()) { coroutineScope.launch { val result = wcProductStore.fetchProducts( site, includedProductIds = ids ) if (result.isError) { prependToLog("Fetching products failed: ${result.error.message}") } else { val products = wcProductStore.getProductsByRemoteIds(site, ids) prependToLog("${products.size} were fetched") prependToLog("$products") } } } else { prependToLog("No valid product IDs...doing nothing") } } } } search_products.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter a search query:" ) { editText -> val payload = SearchProductsPayload( site = site, searchQuery = editText.text.toString() ) dispatcher.dispatch(WCProductActionBuilder.newSearchProductsAction(payload)) } } } search_products_sku.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter a SKU to search for:" ) { editText -> val payload = SearchProductsPayload( site = site, searchQuery = editText.text.toString(), isSkuSearch = true ) dispatcher.dispatch(WCProductActionBuilder.newSearchProductsAction(payload)) } } } fetch_product_variations.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteProductId of product to fetch variations:" ) { editText -> editText.text.toString().toLongOrNull()?.let { id -> coroutineScope.launch { pendingFetchProductVariationsProductRemoteId = id prependToLog("Submitting request to fetch product variations by remoteProductID $id") val result = wcProductStore.fetchProductVariations(FetchProductVariationsPayload(site, id)) prependToLog( "Fetched ${result.rowsAffected} product variants. " + "More variants available ${result.canLoadMore}" ) if (result.canLoadMore) { pendingFetchSingleProductVariationOffset += result.rowsAffected load_more_product_variations.visibility = View.VISIBLE load_more_product_variations.isEnabled = true } else { pendingFetchSingleProductVariationOffset = 0 load_more_product_variations.isEnabled = false } } } ?: prependToLog("No valid remoteProductId defined...doing nothing") } } } load_more_product_variations.setOnClickListener { selectedSite?.let { site -> pendingFetchProductVariationsProductRemoteId?.let { id -> coroutineScope.launch { prependToLog("Submitting offset request to fetch product variations by remoteProductID $id") val payload = FetchProductVariationsPayload( site, id, offset = pendingFetchSingleProductVariationOffset ) val result = wcProductStore.fetchProductVariations(payload) prependToLog( "Fetched ${result.rowsAffected} product variants. " + "More variants available ${result.canLoadMore}" ) if (result.canLoadMore) { pendingFetchSingleProductVariationOffset += result.rowsAffected load_more_product_variations.visibility = View.VISIBLE load_more_product_variations.isEnabled = true } else { pendingFetchSingleProductVariationOffset = 0 load_more_product_variations.isEnabled = false } } } ?: prependToLog("No valid remoteProductId defined...doing nothing") } } fetch_reviews_for_product.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteProductId of product to fetch reviews:" ) { editText -> val remoteProductId = editText.text.toString().toLongOrNull() remoteProductId?.let { id -> coroutineScope.launch { prependToLog("Submitting request to fetch product reviews for remoteProductID $id") val result = wcProductStore.fetchProductReviews( FetchProductReviewsPayload( site, productIds = listOf(remoteProductId) ) ) prependToLog("Fetched ${result.rowsAffected} product reviews") } } ?: prependToLog("No valid remoteProductId defined...doing nothing") } } } fetch_all_reviews.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { prependToLog("Submitting request to fetch product reviews for site ${site.id}") val payload = FetchProductReviewsPayload(site) val result = wcProductStore.fetchProductReviews(payload) prependToLog("Fetched ${result.rowsAffected} product reviews") } } } fetch_review_by_id.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteReviewId of the review to fetch:" ) { editText -> val reviewId = editText.text.toString().toLongOrNull() reviewId?.let { id -> coroutineScope.launch { prependToLog("Submitting request to fetch product review for ID $id") val payload = FetchSingleProductReviewPayload(site, id) val result = wcProductStore.fetchSingleProductReview(payload) if (!result.isError) { prependToLog("Fetched ${result.rowsAffected} single product review") } else { prependToLog("Fetching single product review FAILED") } } } ?: prependToLog("No valid remoteReviewId defined...doing nothing") } } } update_review_status.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val id = showSingleLineDialog( activity = requireActivity(), message = "Enter the remoteReviewId of the review", isNumeric = true )?.toLongOrNull() if (id == null) { prependToLog("Please enter a valid id") return@launch } val newStatus = showSingleLineDialog( activity = requireActivity(), message = "Enter the new status: (approved|hold|spam|trash)" ) if (newStatus == null) { prependToLog("Please enter a valid status") return@launch } val result = wcProductStore.updateProductReviewStatus( site = site, reviewId = id, newStatus = newStatus ) if (!result.isError) { prependToLog("Product Review status updated successfully") } else { prependToLog( "Product Review status update failed, " + "${result.error.type} ${result.error.message}" ) } } } } fetch_product_shipping_class.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter the remoteShippingClassId of the site to fetch:" ) { editText -> pendingFetchSingleProductShippingClassRemoteId = editText.text.toString().toLongOrNull() pendingFetchSingleProductShippingClassRemoteId?.let { id -> prependToLog("Submitting request to fetch product shipping class for ID $id") val payload = FetchSingleProductShippingClassPayload(site, id) dispatcher.dispatch(WCProductActionBuilder.newFetchSingleProductShippingClassAction(payload)) } ?: prependToLog("No valid remoteShippingClassId defined...doing nothing") } } } fetch_product_shipping_classes.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting request to fetch product shipping classes for site ${site.id}") val payload = FetchProductShippingClassListPayload(site) dispatcher.dispatch(WCProductActionBuilder.newFetchProductShippingClassListAction(payload)) } } load_more_product_shipping_classes.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting offset request to fetch product shipping classes for site ${site.id}") val payload = FetchProductShippingClassListPayload( site, offset = pendingFetchProductShippingClassListOffset ) dispatcher.dispatch(WCProductActionBuilder.newFetchProductShippingClassListAction(payload)) } } fetch_product_categories.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting request to fetch product categories for site ${site.id}") val payload = FetchProductCategoriesPayload(site) dispatcher.dispatch(WCProductActionBuilder.newFetchProductCategoriesAction(payload)) } } observe_product_categories.setOnClickListener { selectedSite?.let { site -> coroutineScope.launch { val categories = wcProductStore.observeCategories(site).first() prependToLog("Categories: $categories") } } } load_more_product_categories.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting offset request to fetch product categories for site ${site.id}") val payload = FetchProductCategoriesPayload( site, offset = pendingFetchProductCategoriesOffset ) dispatcher.dispatch(WCProductActionBuilder.newFetchProductCategoriesAction(payload)) } } add_product_category.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter a category name:" ) { editText -> enteredCategoryName = editText.text.toString() if (enteredCategoryName != null && enteredCategoryName?.isNotEmpty() == true) { prependToLog("Submitting request to add product category") val wcProductCategoryModel = WCProductCategoryModel().apply { name = enteredCategoryName!! } val payload = AddProductCategoryPayload(site, wcProductCategoryModel) dispatcher.dispatch(WCProductActionBuilder.newAddProductCategoryAction(payload)) } else { prependToLog("No category name entered...doing nothing") } } } } fetch_product_tags.setOnClickListener { showSingleLineDialog( activity, "Enter a search query, leave blank for none:" ) { editText -> val searchQuery = editText.text.toString() selectedSite?.let { site -> prependToLog("Submitting request to fetch product tags for site ${site.id}") val payload = FetchProductTagsPayload(site, searchQuery = searchQuery) dispatcher.dispatch(WCProductActionBuilder.newFetchProductTagsAction(payload)) } } } load_more_product_tags.setOnClickListener { selectedSite?.let { site -> prependToLog("Submitting offset request to fetch product tags for site ${site.id}") val payload = FetchProductTagsPayload(site, offset = pendingFetchProductTagsOffset) dispatcher.dispatch(WCProductActionBuilder.newFetchProductTagsAction(payload)) } } add_product_tags.setOnClickListener { selectedSite?.let { site -> showSingleLineDialog( activity, "Enter tag name:" ) { editTextTagName1 -> showSingleLineDialog( activity, "Enter another tag name:" ) { editTextTagName2 -> val tagName1 = editTextTagName1.text.toString() val tagName2 = editTextTagName2.text.toString() if (tagName1.isNotEmpty() && tagName2.isNotEmpty()) { enteredTagNames.add(tagName1) enteredTagNames.add(tagName2) prependToLog("Submitting request to add product tags for site ${site.id}") val payload = AddProductTagsPayload(site, enteredTagNames) dispatcher.dispatch(WCProductActionBuilder.newAddProductTagsAction(payload)) } else { prependToLog("Tag name is empty. Doing nothing..") } } } } } test_add_ons.setOnClickListener { selectedSite?.let { site -> WooAddonsTestFragment.show(childFragmentManager, site.siteId) } } update_product_images.setOnClickListener { showSingleLineDialog( activity, "Enter the remoteProductId of the product to update images:" ) { editTextProduct -> editTextProduct.text.toString().toLongOrNull()?.let { productId -> showSingleLineDialog( activity, "Enter the mediaId of the image to assign to the product:" ) { editTextMedia -> editTextMedia.text.toString().toLongOrNull()?.let { mediaId -> updateProductImages(productId, mediaId) } } } } } update_product.setOnClickListener { replaceFragment(WooUpdateProductFragment.newInstance(selectedPos)) } update_variation.setOnClickListener { replaceFragment(WooUpdateVariationFragment.newInstance(selectedPos)) } add_new_product.setOnClickListener { replaceFragment(WooUpdateProductFragment.newInstance(selectedPos, isAddNewProduct = true)) } delete_product.setOnClickListener { showSingleLineDialog( activity, "Enter the remoteProductId of the product to delete:" ) { editTextProduct -> editTextProduct.text.toString().toLongOrNull()?.let { productId -> selectedSite?.let { site -> val payload = DeleteProductPayload(site, productId) dispatcher.dispatch(WCProductActionBuilder.newDeleteProductAction(payload)) } } } } batch_update_variations.setOnClickListener { replaceFragment(WooBatchUpdateVariationsFragment.newInstance(selectedPos)) } } /** * Note that this will replace all this product's images with a single image, as defined by mediaId. Also note * that the media must already be cached for this to work (ie: you may need to go to the first screen in the * example app, tap Media, then ensure the media is fetched) */ private fun updateProductImages(productId: Long, mediaId: Long) { selectedSite?.let { site -> mediaStore.getSiteMediaWithId(site, mediaId)?.let { media -> prependToLog("Submitting request to update product images") val imageList = ArrayList<WCProductImageModel>().also { it.add(WCProductImageModel.fromMediaModel(media)) } val payload = UpdateProductImagesPayload(site, productId, imageList) dispatcher.dispatch(WCProductActionBuilder.newUpdateProductImagesAction(payload)) } ?: prependToLog(("Not a valid media id")) } ?: prependToLog(("No site selected")) } override fun onStart() { super.onStart() dispatcher.register(this) } override fun onStop() { super.onStop() dispatcher.unregister(this) } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductChanged(event: OnProductChanged) { if (event.isError) { prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type) return } selectedSite?.let { site -> when (event.causeOfChange) { FETCH_PRODUCTS -> { prependToLog("Fetched ${event.rowsAffected} products") } DELETED_PRODUCT -> { prependToLog("${event.rowsAffected} product deleted") } else -> prependToLog("Product store was updated from a " + event.causeOfChange) } } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductsSearched(event: OnProductsSearched) { if (event.isError) { prependToLog("Error searching products - error: " + event.error.type) } else { prependToLog("Found ${event.searchResults.size} products matching ${event.searchQuery}") } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductSkuAvailabilityChanged(event: OnProductSkuAvailabilityChanged) { if (event.isError) { prependToLog("Error searching product sku availability - error: " + event.error.type) } else { prependToLog("Sku ${event.sku} available for site ${selectedSite?.name}: ${event.available}") } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductImagesChanged(event: OnProductImagesChanged) { if (event.isError) { prependToLog("Error updating product images - error: " + event.error.type) } else { prependToLog("Product images updated") } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductCategoriesChanged(event: OnProductCategoryChanged) { if (event.isError) { prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type) return } selectedSite?.let { site -> when (event.causeOfChange) { FETCH_PRODUCT_CATEGORIES -> { prependToLog("Fetched ${event.rowsAffected} product categories. " + "More categories available ${event.canLoadMore}") if (event.canLoadMore) { pendingFetchProductCategoriesOffset += event.rowsAffected load_more_product_categories.visibility = View.VISIBLE load_more_product_categories.isEnabled = true } else { pendingFetchProductCategoriesOffset = 0 load_more_product_categories.isEnabled = false } } ADDED_PRODUCT_CATEGORY -> { val category = enteredCategoryName?.let { wcProductStore.getProductCategoryByNameAndParentId(site, it) } prependToLog("${event.rowsAffected} product category added with name: ${category?.name}") } else -> { } } } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductShippingClassesChanged(event: OnProductShippingClassesChanged) { if (event.isError) { prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type) return } selectedSite?.let { site -> when (event.causeOfChange) { FETCH_SINGLE_PRODUCT_SHIPPING_CLASS -> logFetchSingleProductShippingClass(site) else -> checkProductShippingClassesAndLoadMore(event) } } } private fun logFetchSingleProductShippingClass(site: SiteModel) { pendingFetchSingleProductShippingClassRemoteId?.let { remoteId -> pendingFetchSingleProductShippingClassRemoteId = null val productShippingClass = wcProductStore.getShippingClassByRemoteId(site, remoteId) productShippingClass?.let { prependToLog("Single product shipping class fetched! ${it.name}") } ?: prependToLog("WARNING: Fetched shipping class not found in the local database!") } } private fun checkProductShippingClassesAndLoadMore(event: OnProductShippingClassesChanged) { prependToLog( "Fetched ${event.rowsAffected} product shipping classes. " + "More shipping classes available ${event.canLoadMore}" ) if (event.canLoadMore) { pendingFetchProductShippingClassListOffset += event.rowsAffected load_more_product_shipping_classes.visibility = View.VISIBLE load_more_product_shipping_classes.isEnabled = true } else { pendingFetchProductShippingClassListOffset = 0 load_more_product_shipping_classes.isEnabled = false } } @Suppress("unused") @Subscribe(threadMode = ThreadMode.MAIN) fun onProductTagChanged(event: OnProductTagChanged) { if (event.isError) { prependToLog("Error from " + event.causeOfChange + " - error: " + event.error.type) return } selectedSite?.let { site -> when (event.causeOfChange) { FETCH_PRODUCT_TAGS -> { prependToLog("Fetched ${event.rowsAffected} product tags. More tags available ${event.canLoadMore}") if (event.canLoadMore) { pendingFetchProductTagsOffset += event.rowsAffected load_more_product_tags.visibility = View.VISIBLE load_more_product_tags.isEnabled = true } else { pendingFetchProductTagsOffset = 0 load_more_product_tags.isEnabled = false } } ADDED_PRODUCT_TAGS -> { val tags = wcProductStore.getProductTagsByNames(site, enteredTagNames) val tagNames = tags.map { it.name }.joinToString(",") prependToLog("${event.rowsAffected} product tags added for $tagNames") if (enteredTagNames.size > event.rowsAffected) { prependToLog("Error occurred when trying to add some product tags") } } else -> { } } } } }
example/src/main/java/org/wordpress/android/fluxc/example/ui/products/WooProductsFragment.kt
1543494876
package com.android.vocab.provider import android.content.ContentProvider import android.content.ContentUris import android.content.ContentValues import android.content.UriMatcher import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.net.Uri import android.util.Log @Suppress("unused") class VocabProvider : ContentProvider() { private val LOG_TAG: String = VocabProvider::class.java.simpleName lateinit var vocabHelper: VocabHelper companion object { val queryWordsAndType:String = """ SELECT * FROM ${VocabContract.WordEntry.TABLE_NAME} INNER JOIN ${VocabContract.WordTypeEntry.TABLE_NAME} ON ${VocabContract.WordEntry.TABLE_NAME}.${VocabContract.WordEntry.COLUMN_TYPE_ID} = ${VocabContract.WordTypeEntry.TABLE_NAME}.${VocabContract.WordTypeEntry._ID} """ val queryWordsAndTypeForId:String = "$queryWordsAndType WHERE ${VocabContract.WordEntry._ID} = ?" val queryForSynonymsWord: String = """ SELECT * FROM ${VocabContract.SynonymEntry.TABLE_NAME} INNER JOIN ${VocabContract.WordEntry.TABLE_NAME} ON ${VocabContract.SynonymEntry.TABLE_NAME}.${VocabContract.SynonymEntry.COLUMN_SYNONYM_WORD_ID} = ${VocabContract.WordEntry.TABLE_NAME}.${VocabContract.WordEntry._ID} WHERE ${VocabContract.SynonymEntry.TABLE_NAME}.${VocabContract.SynonymEntry.COLUMN_MAIN_WORD_ID} = ? """ val queryForAntonymsWord: String = """ SELECT * FROM ${VocabContract.AntonymEntry.TABLE_NAME} INNER JOIN ${VocabContract.WordEntry.TABLE_NAME} ON ${VocabContract.AntonymEntry.TABLE_NAME}.${VocabContract.AntonymEntry.COLUMN_ANTONYM_WORD_ID} = ${VocabContract.WordEntry.TABLE_NAME}.${VocabContract.WordEntry._ID} WHERE ${VocabContract.AntonymEntry.TABLE_NAME}.${VocabContract.AntonymEntry.COLUMN_MAIN_WORD_ID} = ? """ val URI_MATCHER: UriMatcher = UriMatcher(UriMatcher.NO_MATCH) val WORD_TYPE_LIST: Int = 100 val WORD_TYPE_ITEM: Int = 101 val WORD_LIST: Int = 200 val WORD_ITEM: Int = 201 val SENTENCE_LIST: Int = 300 val SENTENCE_ITEM: Int = 301 val SYNONYM_LIST: Int = 400 val SYNONYM_ITEM: Int = 401 val ANTONYM_LIST: Int = 500 val ANTONYM_ITEM: Int = 501 val WORD_AND_TYPE_LIST:Int = 600 val WORD_AND_TYPE_ITEM: Int = 601 val SYNONYM_FOR_WORD_LIST: Int = 700 val ANTONYM_FOR_WORD_LIST: Int = 701 init { URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_WORD_TYPE, WORD_TYPE_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_WORD_TYPE}/#", WORD_TYPE_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_WORD, WORD_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_WORD}/#", WORD_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_SENTENCE, SENTENCE_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_SENTENCE}/#", SENTENCE_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_SYNONYM, SYNONYM_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_SYNONYM}/#", SYNONYM_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_ANTONYM, ANTONYM_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_ANTONYM}/#", ANTONYM_ITEM) /* Custom Query Registration */ URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, VocabContract.PATH_WORD_AND_TYPE, WORD_AND_TYPE_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_WORD_AND_TYPE}/#", WORD_AND_TYPE_ITEM) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_SYNONYM_FOR_WORD}/#", SYNONYM_FOR_WORD_LIST) URI_MATCHER.addURI(VocabContract.CONTENT_AUTHORITY, "${VocabContract.PATH_ANTONYM_FOR_WORD}/#", ANTONYM_FOR_WORD_LIST) } } override fun insert(uri: Uri?, contentValues: ContentValues?): Uri { val sqliteDatabase: SQLiteDatabase = vocabHelper.writableDatabase val id: Long = when (URI_MATCHER.match(uri)) { WORD_TYPE_LIST -> sqliteDatabase.insert(VocabContract.WordTypeEntry.TABLE_NAME, null, contentValues) WORD_LIST -> sqliteDatabase.insert(VocabContract.WordEntry.TABLE_NAME, null, contentValues) SENTENCE_LIST -> sqliteDatabase.insert(VocabContract.SentenceEntry.TABLE_NAME, null, contentValues) SYNONYM_LIST -> sqliteDatabase.insert(VocabContract.SynonymEntry.TABLE_NAME, null, contentValues) ANTONYM_LIST -> sqliteDatabase.insert(VocabContract.AntonymEntry.TABLE_NAME, null, contentValues) else -> throw IllegalArgumentException("Uri not supported: $uri") } return ContentUris.withAppendedId(uri, id) } override fun query(uri: Uri?, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor { val sqliteDatabase: SQLiteDatabase = vocabHelper.readableDatabase val cursor: Cursor = when (URI_MATCHER.match(uri)) { WORD_TYPE_LIST -> sqliteDatabase.query(VocabContract.WordTypeEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder) WORD_TYPE_ITEM -> sqliteDatabase.query(VocabContract.WordTypeEntry.TABLE_NAME, projection, "${VocabContract.WordTypeEntry.COLUMN_TYPE_NAME}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) WORD_LIST -> sqliteDatabase.query(VocabContract.WordEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder) WORD_ITEM -> sqliteDatabase.query(VocabContract.WordEntry.TABLE_NAME, projection, "${VocabContract.WordEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) SENTENCE_LIST -> sqliteDatabase.query(VocabContract.SentenceEntry.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder) SENTENCE_ITEM -> sqliteDatabase.query(VocabContract.SentenceEntry.TABLE_NAME, projection, "${VocabContract.SentenceEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) SYNONYM_ITEM -> sqliteDatabase.query(VocabContract.SynonymEntry.TABLE_NAME, projection, "${VocabContract.SynonymEntry.COLUMN_MAIN_WORD_ID}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) ANTONYM_ITEM -> sqliteDatabase.query(VocabContract.AntonymEntry.TABLE_NAME, projection, "${VocabContract.AntonymEntry.COLUMN_MAIN_WORD_ID}=?", arrayOf(ContentUris.parseId(uri).toString()), null, null, sortOrder) WORD_AND_TYPE_LIST -> sqliteDatabase.rawQuery(queryWordsAndType, null) WORD_AND_TYPE_ITEM -> sqliteDatabase.rawQuery(queryWordsAndTypeForId, arrayOf(ContentUris.parseId(uri).toString())) SYNONYM_FOR_WORD_LIST -> sqliteDatabase.rawQuery(queryForSynonymsWord, arrayOf(ContentUris.parseId(uri).toString())) ANTONYM_FOR_WORD_LIST -> sqliteDatabase.rawQuery(queryForAntonymsWord, arrayOf(ContentUris.parseId(uri).toString())) else -> throw IllegalArgumentException("Cannot query unknown uri: $uri") } cursor.setNotificationUri(context?.contentResolver, uri) return cursor } override fun onCreate(): Boolean { vocabHelper = VocabHelper(context) return true } override fun update(uri: Uri?, contentValues: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int { val sqliteDatabase: SQLiteDatabase = vocabHelper.writableDatabase val rows: Int = when (URI_MATCHER.match(uri)) { // WORD_TYPE_ITEM -> sqliteDatabase.update(VocabContract.WordTypeEntry.TABLE_NAME, contentValues, VocabContract.WordTypeEntry._, selectionArgs) WORD_ITEM -> sqliteDatabase.update(VocabContract.WordEntry.TABLE_NAME, contentValues , "${VocabContract.WordEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) // SENTENCE_ITEM -> SYNONYM_ITEM -> sqliteDatabase.update(VocabContract.SynonymEntry.TABLE_NAME, contentValues, "${VocabContract.SynonymEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) ANTONYM_ITEM -> sqliteDatabase.update(VocabContract.AntonymEntry.TABLE_NAME, contentValues, "${VocabContract.AntonymEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) else -> throw IllegalArgumentException("Uri not supported: $uri") } if (rows != 0) { context?.contentResolver?.notifyChange(uri, null) } return rows } override fun delete(uri: Uri?, selection: String?, selectionArgs: Array<out String>?): Int { val sqliteDatabase: SQLiteDatabase = vocabHelper.writableDatabase val rows: Int = when (URI_MATCHER.match(uri)) { // WORD_TYPE_ITEM -> sqliteDatabase.delete(VocabContract.WordTypeEntry.TABLE_NAME, selection, selectionArgs) WORD_ITEM -> sqliteDatabase.delete(VocabContract.WordEntry.TABLE_NAME, "${VocabContract.WordEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) SYNONYM_ITEM -> sqliteDatabase.delete(VocabContract.SynonymEntry.TABLE_NAME, "${VocabContract.SynonymEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) ANTONYM_ITEM -> sqliteDatabase.delete(VocabContract.AntonymEntry.TABLE_NAME, "${VocabContract.AntonymEntry._ID}=?", arrayOf(ContentUris.parseId(uri).toString())) else -> throw IllegalArgumentException("Uri not supported: $uri") } if (rows != 0) { context?.contentResolver?.notifyChange(uri, null) } return rows } override fun getType(uri: Uri?): String { return when (URI_MATCHER.match(uri)) { WORD_TYPE_LIST -> VocabContract.WordTypeEntry.CONTENT_LIST_TYPE WORD_TYPE_ITEM -> VocabContract.WordTypeEntry.CONTENT_ITEM_TYPE WORD_LIST -> VocabContract.WordEntry.CONTENT_LIST_TYPE WORD_ITEM -> VocabContract.WordEntry.CONTENT_ITEM_TYPE SENTENCE_LIST -> VocabContract.SentenceEntry.CONTENT_LIST_TYPE SENTENCE_ITEM -> VocabContract.SentenceEntry.CONTENT_ITEM_TYPE SYNONYM_ITEM -> VocabContract.SynonymEntry.CONTENT_LIST_TYPE ANTONYM_ITEM -> VocabContract.AntonymEntry.CONTENT_LIST_TYPE // Todo: Custom items left else -> throw IllegalArgumentException("No type for uri: $uri") } } }
app/src/main/java/com/android/vocab/provider/VocabProvider.kt
425566147
package sample import kotlin.test.Test import kotlin.test.assertTrue class SampleTestsNative { @Test fun testHello() { assertTrue("Native" in hello()) } }
integration-test/src/macosTest/kotlin/sample/SampleTestsNative.kt
3159937505
package com.devulex.eventorage.react external interface ReactUpdater { fun enqueueSetState(dest: Any, state: Any?) fun enqueueReplaceState(dest: Any, state: Any?) fun enqueueCallback(dest: Any, callback: Any, method: String) } @JsModule("react") @JsNonModule external object React { fun createElement(type: Any, props: dynamic, vararg child: Any): ReactElement }
frontend/src/com/devulex/eventorage/react/Imports.kt
1390821682
package ch.difty.scipamato.core.web.paper.search import ch.difty.scipamato.common.web.LABEL_RESOURCE_TAG import ch.difty.scipamato.common.web.LABEL_TAG import ch.difty.scipamato.common.web.Mode import ch.difty.scipamato.core.entity.CoreEntity import ch.difty.scipamato.core.entity.IdScipamatoEntity import ch.difty.scipamato.core.entity.search.SearchOrder import ch.difty.scipamato.core.entity.search.SearchOrder.SearchOrderFields import ch.difty.scipamato.core.persistence.SearchOrderService import ch.difty.scipamato.core.web.common.BasePanel import ch.difty.scipamato.core.web.model.SearchOrderModel import ch.difty.scipamato.core.web.paper.SearchOrderChangeEvent import de.agilecoders.wicket.core.markup.html.bootstrap.button.ButtonBehavior import de.agilecoders.wicket.extensions.markup.html.bootstrap.confirmation.ConfirmationBehavior import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.checkboxx.CheckBoxX import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelect import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelectConfig import org.apache.wicket.AttributeModifier import org.apache.wicket.ajax.AjaxRequestTarget import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink import org.apache.wicket.event.Broadcast import org.apache.wicket.markup.html.basic.Label import org.apache.wicket.markup.html.form.ChoiceRenderer import org.apache.wicket.markup.html.form.Form import org.apache.wicket.markup.html.form.IChoiceRenderer import org.apache.wicket.markup.html.form.TextField import org.apache.wicket.model.CompoundPropertyModel import org.apache.wicket.model.IModel import org.apache.wicket.model.StringResourceModel import org.apache.wicket.request.mapper.parameter.PageParameters import org.apache.wicket.spring.injection.annot.SpringBean // HARDCODED static number of search orders to be visible in the select box. // Might need to become more dynamic private const val SEARCH_ORDER_MAX = 200 /** * Panel offering the user the option of: * * * * selecting from previously saved search orders via a select box * * changing the name and/or global flag of search orders * * changing whether excluded papers are excluded or selected * * saving new or modified search orders * * * * Once a modification has been issued, the panel will issue a * [SearchOrderChangeEvent] to the page. The page and other panels within * the page can then react to the new or modified selection. * * @author u.joss */ @Suppress("SameParameterValue") class SearchOrderSelectorPanel internal constructor( id: String, model: IModel<SearchOrder?>?, mode: Mode, ) : BasePanel<SearchOrder?>(id, model, mode) { @SpringBean private lateinit var searchOrderService: SearchOrderService private lateinit var form: Form<SearchOrder?> private lateinit var searchOrder: BootstrapSelect<SearchOrder?> private lateinit var name: TextField<String?> private lateinit var global: CheckBoxX private lateinit var showExcluded: AjaxCheckBox private lateinit var showExcludedLabel: Label override fun onInitialize() { super.onInitialize() queueForm("form") } private fun queueForm(id: String) { form = Form(id, CompoundPropertyModel(model)).also { queue(it) } makeAndQueueSearchOrderSelectBox("searchOrder") makeAndQueueName(SearchOrderFields.NAME.fieldName) makeAndQueueGlobalCheckBox(SearchOrderFields.GLOBAL.fieldName) makeAndQueueNewButton("new") makeAndQueueDeleteButton("delete") makeAndQueueShowExcludedCheckBox(SearchOrderFields.SHOW_EXCLUDED.fieldName) } private fun makeAndQueueSearchOrderSelectBox(id: String) { val choices = SearchOrderModel(activeUser.id!!, SEARCH_ORDER_MAX) val choiceRenderer: IChoiceRenderer<SearchOrder?> = ChoiceRenderer( CoreEntity.CoreEntityFields.DISPLAY_VALUE.fieldName, IdScipamatoEntity.IdScipamatoEntityFields.ID.fieldName ) val noneSelectedModel = StringResourceModel("$id.noneSelected", this, null) val config = BootstrapSelectConfig() .withNoneSelectedText(noneSelectedModel.getObject()) .withLiveSearch(true) searchOrder = BootstrapSelect(id, model, choices, choiceRenderer).with(config).apply { add(object : AjaxFormComponentUpdatingBehavior(CHANGE) { override fun onUpdate(target: AjaxRequestTarget) { modelChanged() target.add(global) target.add(name) target.add(showExcluded) target.add(showExcludedLabel) send(page, Broadcast.BREADTH, SearchOrderChangeEvent(target)) } }) add(AttributeModifier("data-width", "fit")) }.also { queue(it) } } private fun makeAndQueueName(id: String) { name = object : TextField<String?>(id) { override fun onConfigure() { super.onConfigure() isEnabled = isUserEntitled } }.apply { convertEmptyInputStringToNull = true outputMarkupId = true add(object : AjaxFormComponentUpdatingBehavior(CHANGE) { override fun onUpdate(target: AjaxRequestTarget) { saveOrUpdate() target.apply { add(name) add(global) add(showExcluded) add(showExcludedLabel) } send(page, Broadcast.BREADTH, SearchOrderChangeEvent(target)) } }) }.also { queue(it) } StringResourceModel(id + LABEL_RESOURCE_TAG, this, null).also { queue(Label(id + LABEL_TAG, it)) } } private fun makeAndQueueGlobalCheckBox(id: String) { global = object : CheckBoxX(id) { override fun onConfigure() { super.onConfigure() isEnabled = !isViewMode && isUserEntitled } override fun onChange(value: Boolean?, target: AjaxRequestTarget) { super.onChange(value, target) saveOrUpdate() target.add(searchOrder) } }.apply { outputMarkupId = true config.withThreeState(false).withUseNative(true) }.also { queueCheckBoxAndLabel(it) } } private fun makeAndQueueNewButton(id: String) { queue( object : AjaxSubmitLink(id, form) { override fun onSubmit(target: AjaxRequestTarget) { super.onSubmit(target) target.apply { add(name) add(global) add(showExcluded) add(showExcludedLabel) } send(page, Broadcast.BREADTH, SearchOrderChangeEvent(target).requestingNewSearchOrder()) } }.apply { add(ButtonBehavior()) body = StringResourceModel("button.new.label") defaultFormProcessing = false } ) } private fun saveOrUpdate() { modelObject?.let { mo -> searchOrderService.saveOrUpdate(mo)?.let { saved -> form.defaultModelObject = saved } } } private val isModelSelected: Boolean get() = modelObject?.id != null private val isUserEntitled: Boolean get() = modelObject?.let { mo -> if (isViewMode) !mo.isGlobal && mo.owner == activeUser.id else mo.owner == activeUser.id } ?: false private fun hasExclusions(): Boolean = isModelSelected && modelObject!!.excludedPaperIds.isNotEmpty() private fun makeAndQueueDeleteButton(id: String) { queue( object : AjaxSubmitLink(id, form) { override fun onConfigure() { super.onConfigure() isEnabled = isModelSelected && isUserEntitled } override fun onSubmit(target: AjaxRequestTarget) { super.onSubmit(target) modelObject?.let { searchOrderService.remove(it) setResponsePage(PaperSearchPage(PageParameters())) } } }.apply { add(ButtonBehavior()) body = StringResourceModel("button.delete.label") defaultFormProcessing = false add(ConfirmationBehavior()) outputMarkupId = true } ) } private fun makeAndQueueShowExcludedCheckBox(id: String) { showExcluded = object : AjaxCheckBox(id) { override fun onConfigure() { super.onConfigure() if (isVisible && !hasExclusions() && modelObject != null) modelObject = false isVisible = hasExclusions() } override fun onUpdate(target: AjaxRequestTarget) { target.apply { add(showExcluded) add(showExcludedLabel) send(page, Broadcast.BREADTH, ToggleExclusionsEvent(this)) } } }.apply { outputMarkupPlaceholderTag = true }.also { queue(it) } showExcludedLabel = object : Label("$id$LABEL_TAG", StringResourceModel("$id$LABEL_RESOURCE_TAG", this, null)) { override fun onConfigure() { super.onConfigure() isVisible = hasExclusions() } }.apply { outputMarkupPlaceholderTag = true }.also { queue(it) } } companion object { private const val serialVersionUID = 1L private const val CHANGE = "change" } }
core/core-web/src/main/java/ch/difty/scipamato/core/web/paper/search/SearchOrderSelectorPanel.kt
4136723726
package com.xander.panel import org.junit.Assert import org.junit.Test /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ class ExampleUnitTest { @Test @Throws(Exception::class) fun addition_isCorrect() { Assert.assertEquals(4, (2 + 2).toLong()) } }
xanderpanel/src/test/java/com/xander/panel/ExampleUnitTest.kt
1432729629
package com.github.feed.sample.data.repository.datasource.event.remote import com.github.feed.sample.data.repository.datasource.event.EventDataSource import javax.inject.Inject import javax.inject.Singleton @Singleton class RemoteEventDataSource @Inject constructor(private val service: EventService) : EventDataSource { override fun getEvents() = service.getEvents() }
app/src/main/kotlin/com/github/feed/sample/data/repository/datasource/event/remote/RemoteEventDataSource.kt
1594949784
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.diagnostic import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.progress.ProcessCanceledException import kotlin.reflect.KProperty import kotlin.reflect.jvm.javaGetter inline fun <reified T : Any> logger(): Logger = Logger.getInstance(T::class.java) fun logger(category: String): Logger = Logger.getInstance(category) /** * Get logger instance to be used in Kotlin package methods. Usage: * ``` * private val LOG: Logger get() = logger(::LOG) // define at top level of the file containing the function * ``` * In Kotlin 1.1 even simpler declaration will be possible: * ``` * private val LOG: Logger = logger(::LOG) * ``` * Notice explicit type declaration which can't be skipped in this case. */ fun logger(field: KProperty<Logger>): Logger = Logger.getInstance(field.javaGetter!!.declaringClass) inline fun Logger.debug(e: Exception? = null, lazyMessage: () -> String) { if (isDebugEnabled) { debug(lazyMessage(), e) } } inline fun Logger.debugOrInfoIfTestMode(e: Exception? = null, lazyMessage: () -> String) { if (ApplicationManager.getApplication()?.isUnitTestMode == true) { info(lazyMessage()) } else { debug(e, lazyMessage) } } inline fun <T> Logger.runAndLogException(runnable: () -> T): T? { try { return runnable() } catch (e: ProcessCanceledException) { return null } catch (e: Throwable) { error(e) return null } }
platform/projectModel-api/src/com/intellij/openapi/diagnostic/logger.kt
2320530921
package com.mercadopago.android.px.di import android.content.Context import com.mercadopago.android.px.di.module.LocalRepositoryModule import com.mercadopago.android.px.di.module.ViewModelModule internal class Dependencies { var viewModelModule: ViewModelModule? = null private set var localPreferences: LocalRepositoryModule? = null private set fun initialize(context: Context) { localPreferences = LocalRepositoryModule(context.applicationContext) viewModelModule = ViewModelModule() } fun clean() { viewModelModule = null localPreferences = null } companion object { @JvmStatic val instance: Dependencies by lazy { Dependencies() } } }
example/src/main/java/com/mercadopago/android/px/di/Dependencies.kt
1857773359
/* * Copyright (C) 2017 The sxxxxxxxxxu's Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.shunwang.alarmmanagersample.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import android.widget.Toast /** * Fun: * Created by sxx.xu on 12/19/2017. */ class MyReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { var msg = intent!!.getStringExtra("msg") Log.e("alarm receiver:" , msg) Toast.makeText(context, msg, Toast.LENGTH_SHORT).show() } }
alarmmanagersample/src/main/java/com/shunwang/alarmmanagersample/receiver/MyReceiver.kt
850118316
package debop4k.spring.jdbc.config import debop4k.spring.jdbc.core.config.embeddedDatabase import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.jdbc.core.JdbcTemplate import org.springframework.jdbc.datasource.DataSourceTransactionManager import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType.H2 import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration open class PerfDataConfiguration { @Bean open fun dataSource(): DataSource { return embeddedDatabase(H2) { script(location = "classpath:db/schema-h2.sql") script(location = "classpath:db/performance-h2.sql") } } @Bean open fun jdbcTemplate(): JdbcTemplate { return JdbcTemplate(dataSource()) } @Bean open fun transactionManager(): PlatformTransactionManager { return DataSourceTransactionManager(dataSource()) } }
debop4k-spring-jdbc/src/test/kotlin/debop4k/spring/jdbc/config/PerfDataConfiguration.kt
3917301745
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference.browse import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.android.tv.reference.repository.VideoRepository import com.android.tv.reference.shared.datamodel.Video import com.android.tv.reference.shared.datamodel.VideoType import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations @LargeTest @RunWith(AndroidJUnit4::class) class BrowseViewModelUnitTest { private lateinit var testVideos: List<Video> @Mock private lateinit var mockVideoRepository: VideoRepository @Before fun setupTests() { MockitoAnnotations.initMocks(this) testVideos = createTestVideos() Mockito.`when`(mockVideoRepository.getAllVideos()).thenReturn(testVideos) } @Test fun getVideoGroupList_isCorrect() { val viewModel = BrowseViewModel(ApplicationProvider.getApplicationContext()) val videoGroups = viewModel.getVideoGroupList(mockVideoRepository) assertThat(videoGroups).hasSize(2) // Categories are different assertThat(videoGroups.map { it.category }) .containsExactly("category_a", "category_b").inOrder() // Each Video in a VideoGroup should belong to the same category videoGroups.forEach { videoGroup -> val testCategory = videoGroup.category val videoCategories = videoGroup.videoList.map { it.category }.distinct() assertThat(videoCategories).containsExactly(testCategory) } } private fun createTestVideos(): List<Video> { return listOf( Video( id = "category_a_video_0", name = "name", description = "description", uri = "https://example.com/valid", videoUri = "https://example.com/valid", thumbnailUri = "https://example.com/valid", backgroundImageUri = "https://example.com/valid", category = "category_a", videoType = VideoType.CLIP, duration = "PT00H01M", seriesUri = "https://example.com/valid", seasonUri = "https://example.com/valid" ), Video( id = "category_b_video_0", name = "name", description = "description", uri = "https://example.com/valid", videoUri = "https://example.com/valid", thumbnailUri = "https://example.com/valid", backgroundImageUri = "https://example.com/valid", category = "category_b", videoType = VideoType.CLIP, duration = "PT00H01M", seriesUri = "https://example.com/valid", seasonUri = "https://example.com/valid" ), Video( id = "category_a_video_1", name = "name", description = "description", uri = "https://example.com/valid", videoUri = "https://example.com/valid", thumbnailUri = "https://example.com/valid", backgroundImageUri = "https://example.com/valid", category = "category_a", videoType = VideoType.CLIP, duration = "PT00H01M", seriesUri = "https://example.com/valid", seasonUri = "https://example.com/valid" ) ) } }
step_4_completed/src/test/java/com/android/tv/reference/browse/BrowseViewModelUnitTest.kt
3626288750
package com.syedmuzani.umbrella.activities import android.app.Activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.support.v7.widget.Toolbar import com.syedmuzani.umbrella.R import com.syedmuzani.umbrella.adapters.MainPageListAdapter import com.syedmuzani.umbrella.models.MainMenuLink import java.util.* /** * Central point to visit all other libraries */ class MainActivity : AppCompatActivity() { internal var activity: Activity = this internal var links: MutableList<MainMenuLink> = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.listview) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val rv: RecyclerView = findViewById(R.id.rv) initRecyclerView() rv.layoutManager = LinearLayoutManager(this) val orientation = (rv.layoutManager as LinearLayoutManager).orientation val dividerItemDecoration = DividerItemDecoration(this, orientation) rv.addItemDecoration(dividerItemDecoration) rv.adapter = MainPageListAdapter(links) } private fun initRecyclerView() { links.add(MainMenuLink("Facebook Login", FacebookLoginActivity::class.java)) links.add(MainMenuLink("To Do List (File based)", ToDoFileBasedActivity::class.java)) links.add(MainMenuLink("To Do List (DB based)", ToDoDatabasedActivity::class.java)) links.add(MainMenuLink("Anko DSL Layouts", DslActivity::class.java)) links.add(MainMenuLink("VideoView", VideoActivity::class.java)) links.add(MainMenuLink("Fingerprint", FingerprintActivity::class.java)) links.add(MainMenuLink("Firebase With Countdown", FirebaseActivity::class.java)) links.add(MainMenuLink("Date/TimePicker", DateTimePickerActivity::class.java)) } }
app/src/main/java/com/syedmuzani/umbrella/activities/MainActivity.kt
2660370259
/* * Copyright 2015, 2017 Thomas Harning Jr. <[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 us.eharning.atomun.keygen.spi import us.eharning.atomun.keygen.KeyGeneratorAlgorithm /** * Common service implementation for key generators. * @since 0.0.1 */ abstract class KeyGeneratorServiceProvider { /** * Obtain a key generator builder SPI for the given algorithm. * * @param algorithm * mnemonic algorithm to try to retrieve. * * @return SPI instance for the given algorithm, else null. * * @since 0.0.1 */ abstract fun getKeyGeneratorBuilder(algorithm: KeyGeneratorAlgorithm): KeyGeneratorBuilderSpi? }
src/main/java/us/eharning/atomun/keygen/spi/KeyGeneratorServiceProvider.kt
3207978782
/**************************************************************************** * * Created by menion on 06.04.2021. * Copyright (c) 2021. All rights reserved. * * This file is part of the Asamm team software. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * ***************************************************************************/ package locus.api.android.features.sendToApp import locus.api.android.utils.LocusConst /** * Mode that define how data are send into the Locus application. */ sealed class SendMode(val action: String) { /** * Basic mode. Data are send over direct intent. App is started if not running and request * is handled once basic app initialization is done. * * @param centerOnData apply centering mechanism, so move & zoom map to display loaded content. */ class Basic(val centerOnData: Boolean = false) : SendMode(LocusConst.ACTION_DISPLAY_DATA) /** * Silent mode. Data are send over broadcast. In case, app is not running, request is lost * and no data are delivered. */ class Silent : SendMode(LocusConst.ACTION_DISPLAY_DATA_SILENTLY) /** * Import mode is based on 'BASIC' mode, but after app is started, import is called instead * of basic display on the map. */ class Import : SendMode(LocusConst.ACTION_DISPLAY_DATA) }
locus-api-android/src/main/java/locus/api/android/features/sendToApp/SendMode.kt
3435484210
package io.gitlab.arturbosch.detekt.api /** * A rule set provider, as the name states, is responsible for creating rule sets. * * When writing own rule set providers make sure to register them according the ServiceLoader documentation. * http://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html * * @author Artur Bosch */ interface RuleSetProvider { /** * Every rule set must be pre-configured with an ID to validate if this rule set * must be created for current analysis. */ val ruleSetId: String /** * Can return a rule set if this specific rule set is not considered as ignore. * * Api notice: As the rule set id is not known before creating the rule set instance, * we must first create the rule set and then check if it is active. */ fun buildRuleset(config: Config): RuleSet? { val subConfig = config.subConfig(ruleSetId) val active = subConfig.valueOrDefault("active", true) return if (active) instance(subConfig) else null } /** * This function must be implemented to provide custom rule sets. * Make sure to pass the configuration to each rule to allow rules * to be self configurable. */ fun instance(config: Config): RuleSet }
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/RuleSetProvider.kt
3328040317
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.test.assertThat import io.gitlab.arturbosch.detekt.test.lint import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek class SafeCastSpec : SubjectSpek<SafeCast>({ subject { SafeCast() } given("some cast expressions") { it("reports negated expression") { val code = """ fun test() { if (element !is KtElement) { null } else { element } }""" assertThat(subject.lint(code)).hasSize(1) } it("reports expression") { val code = """ fun test() { if (element is KtElement) { element } else { null } }""" assertThat(subject.lint(code)).hasSize(1) } it("does not report wrong condition") { val code = """ fun test() { if (element == other) { element } else { null } }""" assertThat(subject.lint(code)).hasSize(0) } it("does not report wrong else clause") { val code = """ fun test() { if (element is KtElement) { element } else { KtElement() } }""" assertThat(subject.lint(code)).hasSize(0) } } })
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/SafeCastSpec.kt
4036184926
package me.ykrank.s1next.data.pref import android.content.Context import android.content.SharedPreferences import androidx.preference.PreferenceManager import com.fasterxml.jackson.databind.ObjectMapper import dagger.Module import dagger.Provides import me.ykrank.s1next.data.Wifi import javax.inject.Singleton /** * Created by ykrank on 2016/11/4. */ @Module class PrefModule(private val prefContext: Context) { @Provides @Singleton internal fun provideSharedPreferences(): SharedPreferences { return PreferenceManager.getDefaultSharedPreferences(prefContext) } @Provides @Singleton internal fun provideNetworkPreferencesRepository(sharedPreferences: SharedPreferences): NetworkPreferences { return NetworkPreferencesImpl(prefContext, sharedPreferences) } @Provides @Singleton internal fun provideNetworkPreferencesManager(networkPreferences: NetworkPreferences): NetworkPreferencesManager { return NetworkPreferencesManager(networkPreferences) } @Provides @Singleton internal fun provideGeneralPreferencesProvider(sharedPreferences: SharedPreferences): GeneralPreferences { return GeneralPreferencesImpl(prefContext, sharedPreferences) } @Provides @Singleton internal fun provideGeneralPreferencesManager(generalPreferencesProvider: GeneralPreferences): GeneralPreferencesManager { return GeneralPreferencesManager(generalPreferencesProvider) } @Provides @Singleton internal fun provideThemeManager(generalPreferencesProvider: GeneralPreferences): ThemeManager { return ThemeManager(prefContext, generalPreferencesProvider) } @Provides @Singleton internal fun provideDownloadPreferencesProvider(sharedPreferences: SharedPreferences): DownloadPreferences { return DownloadPreferencesImpl(prefContext, sharedPreferences) } @Provides @Singleton internal fun provideDownloadPreferencesManager(downloadPreferencesProvider: DownloadPreferences, wifi: Wifi): DownloadPreferencesManager { return DownloadPreferencesManager(downloadPreferencesProvider, wifi) } @Provides @Singleton internal fun provideReadProgressPreferencesProvider(sharedPreferences: SharedPreferences, objectMapper: ObjectMapper): ReadPreferences { return ReadPreferencesImpl(prefContext, sharedPreferences, objectMapper) } @Provides @Singleton internal fun provideReadProgressPreferencesManager(readPreferences: ReadPreferences): ReadPreferencesManager { return ReadPreferencesManager(readPreferences) } @Provides @Singleton internal fun provideDataPreferencesProvider(sharedPreferences: SharedPreferences): DataPreferences { return DataPreferencesImpl(prefContext, sharedPreferences) } @Provides @Singleton internal fun provideDataPreferencesManager(preferencesRepository: DataPreferences): DataPreferencesManager { return DataPreferencesManager(preferencesRepository) } @Provides @Singleton internal fun provideAppDataPreferencesProvider(sharedPreferences: SharedPreferences): AppDataPreferences { return AppDataPreferencesImpl(prefContext, sharedPreferences) } @Provides @Singleton internal fun provideAppDataPreferencesManager(preferencesRepository: AppDataPreferences): AppDataPreferencesManager { return AppDataPreferencesManager(preferencesRepository) } }
app/src/main/java/me/ykrank/s1next/data/pref/PrefModule.kt
2615113633
package com.github.ykrank.androidtools.ui.adapter.simple import android.content.Context import androidx.databinding.ViewDataBinding import androidx.annotation.LayoutRes import com.github.ykrank.androidtools.ui.adapter.LibBaseRecyclerViewAdapter import com.github.ykrank.androidtools.ui.adapter.delegate.item.ProgressItem import com.hannesdorfmann.adapterdelegates3.AdapterDelegate /** * Simple adapter, just one type item, or [ProgressItem]. * Layout databinding variable name should be only "model". * Created by ykrank on 2017/3/22. */ class SimpleRecycleViewAdapter : LibBaseRecyclerViewAdapter { constructor(context: Context, @LayoutRes layoutRes: Int, stableId: Boolean = false, bindViewHolderCallback: BindViewHolderCallback? = null, createViewHolderCallback: ((ViewDataBinding) -> Unit)? = null) : super(context, stableId) { addAdapterDelegate(SimpleAdapterDelegate(context, layoutRes, null, createViewHolderCallback, bindViewHolderCallback)) } constructor(context: Context, adapterDelegate: AdapterDelegate<MutableList<Any>>, stableId: Boolean = false) : super(context, stableId) { addAdapterDelegate(adapterDelegate) } }
library/src/main/java/com/github/ykrank/androidtools/ui/adapter/simple/SimpleRecycleViewAdapter.kt
2790302675
package io.gitlab.arturbosch.detekt.formatting import java.util.ArrayList /** * Extracted and adapted from KtLint. * * @author Artur Bosch */ internal fun calculateLineColByOffset(text: String): (offset: Int) -> Pair<Int, Int> { var i = -1 val e = text.length val arr = ArrayList<Int>() do { arr.add(i + 1) i = text.indexOf('\n', i + 1) } while (i != -1) arr.add(e + if (arr.last() == e) 1 else 0) val segmentTree = SegmentTree(arr.toTypedArray()) return { offset -> val line = segmentTree.indexOf(offset) if (line != -1) { val col = offset - segmentTree.get(line).left line + 1 to col + 1 } else { 1 to 1 } } } internal fun calculateLineBreakOffset(fileContent: String): (offset: Int) -> Int { val arr = ArrayList<Int>() var i = 0 do { arr.add(i) i = fileContent.indexOf("\r\n", i + 1) } while (i != -1) arr.add(fileContent.length) return if (arr.size != 2) { SegmentTree(arr.toTypedArray()).let { return { offset -> it.indexOf(offset) } } } else { _ -> 0 } } internal class SegmentTree(sortedArray: Array<Int>) { private val segments: List<Segment> fun get(i: Int): Segment = segments[i] fun indexOf(v: Int): Int = binarySearch(v, 0, this.segments.size - 1) private fun binarySearch(v: Int, l: Int, r: Int): Int = when { l > r -> -1 else -> { val i = l + (r - l) / 2 val s = segments[i] if (v < s.left) binarySearch(v, l, i - 1) else (if (s.right < v) binarySearch(v, i + 1, r) else i) } } init { require(sortedArray.size > 1) { "At least two data points are required" } sortedArray.reduce { r, v -> require(r <= v) { "Data points are not sorted (ASC)" }; v } segments = sortedArray.take(sortedArray.size - 1) .mapIndexed { i: Int, v: Int -> Segment(v, sortedArray[i + 1] - 1) } } } internal data class Segment(val left: Int, val right: Int)
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/OffsetsToLineColumn.kt
3991301581
package com.hea3ven.dulcedeleche object DulceDeLecheModServer : DulceDeLecheMod() { init { addModule("redstone", "com.hea3ven.dulcedeleche.modules.redstone.RedstoneModuleServer.INSTANCE") } }
src/main/kotlin/com/hea3ven/dulcedeleche/DulceDeLecheModServer.kt
483773683
package com.simplecity.amp_library.ui.dialog import android.annotation.SuppressLint import android.app.Dialog import android.content.Context import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v4.app.FragmentManager import android.view.LayoutInflater import android.widget.NumberPicker import com.afollestad.materialdialogs.MaterialDialog import com.simplecity.amp_library.R import com.simplecity.amp_library.model.Playlist import com.simplecity.amp_library.utils.SettingsManager import dagger.android.support.AndroidSupportInjection import javax.inject.Inject class WeekSelectorDialog : DialogFragment() { @Inject lateinit var settingsManager: SettingsManager override fun onAttach(context: Context?) { AndroidSupportInjection.inject(this) super.onAttach(context) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { @SuppressLint("InflateParams") val view = LayoutInflater.from(context).inflate(R.layout.weekpicker, null) val numberPicker: NumberPicker numberPicker = view.findViewById(R.id.weeks) numberPicker.maxValue = 12 numberPicker.minValue = 1 numberPicker.value = settingsManager.numWeeks return MaterialDialog.Builder(context!!) .title(R.string.week_selector) .customView(view, false) .negativeText(R.string.cancel) .positiveText(R.string.button_ok) .onPositive { _, _ -> settingsManager.numWeeks = numberPicker.value } .build() } fun show(fragmentManager: FragmentManager) { show(fragmentManager, TAG) } companion object { const val TAG = "WeekSelectorDialog" } }
app/src/main/java/com/simplecity/amp_library/ui/dialog/WeekSelectorDialog.kt
1306258843
/* * ************************************************************************ * BitmapCache.kt * ************************************************************************* * Copyright © 2020 VLC authors and VideoLAN * Author: Nicolas POMEPUY * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ /***************************************************************************** * BitmapCache.java * * Copyright © 2012 VLC authors and VideoLAN * * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.tools import android.graphics.Bitmap import android.util.Log import androidx.collection.LruCache import videolan.org.commontools.BuildConfig object BitmapCache { private val mMemCache: LruCache<String, Bitmap> private val TAG = "VLC/BitmapCache" init { // Use 20% of the available memory for this memory cache. val cacheSize = Runtime.getRuntime().maxMemory() / 5 if (BuildConfig.DEBUG) Log.i(TAG, "LRUCache size set to " + cacheSize.readableSize()) mMemCache = object : LruCache<String, Bitmap>(cacheSize.toInt()) { override fun sizeOf(key: String, value: Bitmap): Int { return value.rowBytes * value.height } } } @Synchronized fun getBitmapFromMemCache(key: String?): Bitmap? { if (key == null) return null val b = mMemCache.get(key) if (b == null) { mMemCache.remove(key) return null } return b } @Synchronized fun addBitmapToMemCache(key: String?, bitmap: Bitmap?) { if (key != null && bitmap != null && getBitmapFromMemCache(key) == null) { mMemCache.put(key, bitmap) } } private fun getBitmapFromMemCache(resId: Int): Bitmap? { return getBitmapFromMemCache("res:$resId") } private fun addBitmapToMemCache(resId: Int, bitmap: Bitmap?) { addBitmapToMemCache("res:$resId", bitmap) } @Synchronized fun clear() { mMemCache.evictAll() } }
application/tools/src/main/java/org/videolan/tools/BitmapCache.kt
2266026687
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.compressed.extractcontents import android.os.Environment import org.junit.Assert.assertTrue import java.io.File /** * Test for extracting 7z archives without timestamps in entries. See #3035 */ class SevenZipWithoutTimestampTest : SevenZipExtractorTest() { override val archiveFile: File get() = File( Environment.getExternalStorageDirectory(), "test-archive-no-timestamp.$archiveType" ) /** * As timestamp is only the time we extract the file, we just check it's created recently. */ override fun assertFileTimestampCorrect(file: File) { assertTrue(System.currentTimeMillis() - file.lastModified() < 1000) } }
app/src/test/java/com/amaze/filemanager/filesystem/compressed/extractcontents/SevenZipWithoutTimestampTest.kt
3385941258
/* * Copyright (C) 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.kotlincoroutines.main import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.example.android.kotlincoroutines.fakes.MainNetworkCompletableFake import com.example.android.kotlincoroutines.fakes.MainNetworkFake import com.example.android.kotlincoroutines.fakes.TitleDaoFake import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.launch import kotlinx.coroutines.test.runBlockingTest import org.junit.Rule import org.junit.Test class TitleRepositoryTest { @get:Rule val instantTaskExecutorRule = InstantTaskExecutorRule() @Test fun whenRefreshTitleSuccess_insertsRows() = runBlockingTest { val titleDao = TitleDaoFake("title") val subject = TitleRepository( MainNetworkFake("OK"), titleDao ) subject.refreshTitle() assertThat(titleDao.nextInsertedOrNull()).isEqualTo("OK") } @Test(expected = TitleRefreshError::class) fun whenRefreshTitleTimeout_throws() = runBlockingTest { val network = MainNetworkCompletableFake() val subject = TitleRepository( network, TitleDaoFake("title") ) launch { subject.refreshTitle() } advanceTimeBy(5_000) } }
coroutines-codelab/finished_code/src/test/java/com/example/android/kotlincoroutines/main/TitleRepositoryTest.kt
375289592