path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
modules/nav/src/main/kotlin/dev/jonpoulton/actual/nav/NavDestination.kt
jonapoul
766,282,291
false
{"Kotlin": 233128}
package dev.jonpoulton.actual.nav import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import dev.jonpoulton.actual.listbudgets.ui.ListBudgetsScreen import dev.jonpoulton.actual.login.ui.LoginScreen import dev.jonpoulton.actual.serverurl.ui.ServerUrlScreen sealed class NavDestination( val route: String, val composable: @Composable (NavHostController) -> Unit, ) { data object ServerUrl : NavDestination( route = "server-url", composable = { ServerUrlScreen(ServerUrlNavigator(it)) }, ) data object Login : NavDestination( route = "login", composable = { LoginScreen(LoginNavigator(it)) }, ) data object ListBudgets : NavDestination( route = "listBudgets", composable = { ListBudgetsScreen(ListBudgetsNavigator(it)) }, ) data object Bootstrap : NavDestination( route = "bootstrap", composable = { // TODO: Implement }, ) }
0
Kotlin
0
0
64a503e36f47edce84cd72f68a6833e90fcce73c
926
actual-android
Apache License 2.0
shared/src/commonMain/kotlin/com/movies/domain/util/FlowHelper.kt
ahmedorabi94
630,220,598
false
null
package com.movies.domain.util import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* /** * Got my idea for this from stackoverflow post * Source: * https://stackoverflow.com/questions/64175099/listen-to-kotlin-coroutine-flow-from-ios */ /** * Must create a (class + function) since extension functions can't be used on iOS with KMM. * Otherwise I'd simply create a Flow<T>.collectCommon() function. */ fun <T> Flow<T>.asCommonFlow(): CommonFlow<T> = CommonFlow(this) class CommonFlow<T>(private val origin: Flow<T>): Flow<T> by origin { fun collectCommon( coroutineScope: CoroutineScope? = null, // 'viewModelScope' on Android and 'nil' on iOS callback: (T) -> Unit, // callback on each emission ){ onEach { callback(it) }.launchIn(coroutineScope ?: CoroutineScope(Dispatchers.Main)) } }
0
Kotlin
0
0
f6f2dc4c49e9f15dcdbf0c6a024b8bec1696afbe
914
MoviesKMMCompose
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ec2/CfnTransitGatewayVpcAttachmentPropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.ec2 import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.ec2.CfnTransitGatewayVpcAttachmentProps @Generated public fun buildCfnTransitGatewayVpcAttachmentProps(initializer: @AwsCdkDsl CfnTransitGatewayVpcAttachmentProps.Builder.() -> Unit): CfnTransitGatewayVpcAttachmentProps = CfnTransitGatewayVpcAttachmentProps.Builder().apply(initializer).build()
1
Kotlin
0
0
b22e397ff37c5fce365a5430790e5d83f0dd5a64
489
aws-cdk-kt
Apache License 2.0
platform/platform-tests/testSrc/com/intellij/formatting/engine/FormatterEngineTests.kt
androidports
115,100,208
false
null
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.formatting.engine import com.intellij.formatting.Block import com.intellij.formatting.FormatterEx import com.intellij.formatting.engine.testModel.TestFormattingModel import com.intellij.formatting.engine.testModel.getRoot import com.intellij.formatting.toFormattingBlock import com.intellij.openapi.editor.EditorFactory import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.testFramework.LightPlatformTestCase import junit.framework.TestCase import org.junit.Test class FormatterEngineTests : LightPlatformTestCase() { @Test fun `test simple alignment`() { doReformatTest( """ [a0]fooooo [a1]foo [a0]go [a1]boo """, """ fooooo foo go boo """) } @Test fun `test empty block alignment`() { doReformatTest( """ [a0]fooooo [a1] [a0]go [a1]boo """, """ fooooo go boo """) } } class TestData(val rootBlock: Block, val textToFormat: String, val markerPosition: Int?) fun doReformatTest(before: String, expectedText: String, settings: CodeStyleSettings = CodeStyleSettings()) { val data = extractFormattingTestData(before) val rightMargin = data.markerPosition if (rightMargin != null) { settings.setRightMargin(null, rightMargin) } val document = EditorFactory.getInstance().createDocument(data.textToFormat) val model = TestFormattingModel(data.rootBlock, document) FormatterEx.getInstanceEx().format(model, settings, settings.indentOptions, null) TestCase.assertEquals(expectedText.trimStart(), document.text) } fun extractFormattingTestData(before: String) : TestData { var root = getRoot(before.trimStart()) var beforeText = root.text val marker = beforeText.indexOf('|') if (marker > 0) { root = getRoot(before.trimStart().replace("|", "")) beforeText = root.text } val rootBlock = root.toFormattingBlock(0) return TestData(rootBlock, beforeText, if (marker > 0) marker else null) }
6
null
1
4
6e4f7135c5843ed93c15a9782f29e4400df8b068
2,532
intellij-community
Apache License 2.0
app/src/main/java/com/example/bricklist/AddActivity.kt
CookieDinner
267,930,029
false
null
package com.example.bricklist import android.annotation.SuppressLint import android.app.Activity import android.content.ContentValues import android.content.Context import android.content.Intent import android.database.sqlite.SQLiteDatabase import android.os.* import androidx.appcompat.app.AppCompatActivity import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.MenuItem import android.view.View import androidx.preference.PreferenceManager import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_add.* import org.w3c.dom.Document import org.w3c.dom.Element import org.w3c.dom.Node import org.w3c.dom.NodeList import org.xml.sax.InputSource import java.io.IOException import java.io.StringReader import java.lang.Exception import java.net.MalformedURLException import java.net.URL import javax.xml.parsers.DocumentBuilderFactory class AddActivity : AppCompatActivity() { var db : SQLiteDatabase? = null var lastCorrectId: String = "" var xml : String = "" var dbpath : String? = null override fun onCreate(savedInstanceState: Bundle?) { dbpath = PreferenceManager.getDefaultSharedPreferences(baseContext).getString("database_file", "") super.onCreate(savedInstanceState) setContentView(R.layout.activity_add) supportActionBar?.setDisplayHomeAsUpEnabled(true) addButton.isEnabled = false loadDb() idText.addTextChangedListener(object: TextWatcher { override fun afterTextChanged(editable: Editable?) { addButton.isEnabled = false } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) idText.addTextChangedListener(object: TextWatcher { override fun afterTextChanged(editable: Editable?) { idText.removeTextChangedListener(this) val regex = """[^0-9]""".toRegex() val matched = regex.containsMatchIn(input = editable.toString()) when { matched -> { idText.setText(lastCorrectId) idText.setSelection(idText.text.toString().length) } editable.toString().length > 6 -> { idText.setText(lastCorrectId) idText.setSelection(idText.text.toString().length) } editable.toString().isNotEmpty() -> { lastCorrectId = editable.toString() idText.setSelection(idText.text.toString().length) } } idText.addTextChangedListener(this) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} }) } override fun finish() { val data = Intent() setResult(Activity.RESULT_OK, data) super.finish() } fun onClickCheck(v: View){ if (idText.text.isNotEmpty() and nameText.text.isNotEmpty()) { if(checkQuery("SELECT * FROM Inventories WHERE id=${idText.text} OR Name='${nameText.text}'")){ Log.i("test", "starting download") DownloadXML(baseContext).execute(idText.text.toString()) //Próbowałem dodać delay/sprawdzanie czy wciąż jest pobierane ale wątek ui nie poznalał addButton.isEnabled = true } } else Snackbar.make(lay, "Fields can't be empty!", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } fun onClickAdd(v: View){ val values = ContentValues() val projectId = idText.text.toString() values.put("ID", projectId) values.put("NAME", nameText.text.toString()) values.put("ACTIVE", 1) values.put("LASTACCESSED", 0) db?.insert("INVENTORIES", null, values) val xmlDoc: Document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse( InputSource(StringReader(xml))) xmlDoc.documentElement.normalize() val bricks: NodeList = xmlDoc.getElementsByTagName("ITEM") for(i in 0 until bricks.length){ val brickNode: Node = bricks.item(i) if(brickNode.nodeType == Node.ELEMENT_NODE){ val elem = brickNode as Element val children = elem.childNodes var currentType:String? = null var currentItemID:String? = null var currentQuantity:Int? = null var currentColor:Int? = null var currentExtra:String? = null var currentAlternate:String? = null for (j in 0 until children.length - 1){ val node = children.item(j) if(node is Element){ when(node.nodeName){ "ITEMTYPE" -> currentType = node.textContent "ITEMID" -> currentItemID = node.textContent "QTY" -> currentQuantity = node.textContent.toInt() "COLOR" -> currentColor = node.textContent.toInt() "EXTRA" -> currentExtra = node.textContent "ALTERNATE" -> currentAlternate = node.textContent } } } if(currentAlternate == "N" && currentType != "M"){ val brickValues = ContentValues() val extraid = runQueryForResult("SELECT MAX(id) FROM INVENTORIESPARTS", 0) if (extraid != null) brickValues.put("ID", 1+extraid.toInt()) else brickValues.put("ID", i) brickValues.put("INVENTORYID", projectId) brickValues.put("TYPEID", runQueryForResult( "SELECT * FROM ItemTypes WHERE Code='$currentType'",0)) brickValues.put("ITEMID", currentItemID) brickValues.put("QUANTITYINSET", currentQuantity) brickValues.put("QUANTITYINSTORE", 0) brickValues.put("COLORID", currentColor) brickValues.put("EXTRA", currentExtra) db?.insert("INVENTORIESPARTS", null, brickValues) val tItemID: String? = runQueryForResult("select id from Parts where Code='$currentItemID'", 0) val tColorID: String? = runQueryForResult("select id from Colors where Code=$currentColor", 0) val code = runQueryForResult("SELECT CODE FROM CODES WHERE ITEMID=$tItemID AND COLORID=$tColorID", 0) if(checkIfImageExists(tItemID, tColorID, db)) { if (code != null) DownloadImage(code).execute( "https://www.lego.com/service/bricks/5/2/$code", tItemID, tColorID ) DownloadImage(code).execute( "http://img.bricklink.com/P/$currentColor/$currentItemID.gif", tItemID, tColorID ) DownloadImage(code).execute( "https://www.bricklink.com/PL/$currentItemID.jpg", tItemID, tColorID ) } } } } db?.close() finish() } fun checkQuery(query: String): Boolean { val cursor = db?.rawQuery(query, null) if (cursor != null) { if(cursor.moveToFirst()){ Snackbar.make(lay, "Project already exists!", Snackbar.LENGTH_LONG) .setAction("Action", null).show() cursor.close() return false } cursor.close() return true } return false } fun runQueryForResult(query: String, column: Int): String? { val cursor = db?.rawQuery(query, null) var result : String? = null if (cursor != null) { if (cursor.moveToFirst()){ result = cursor.getString(column) } } cursor?.close() return result } fun loadDb(){ db = dbpath?.let { SQLiteDatabase.openDatabase(it,null, 0) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if(item.itemId == android.R.id.home) { finish() true } else super.onOptionsItemSelected(item) } @SuppressLint("StaticFieldLeak") private inner class DownloadXML(val baseContext: Context) : AsyncTask<String, Int, String>(){ override fun doInBackground(vararg params: String?): String { try { val urlText = PreferenceManager.getDefaultSharedPreferences(baseContext) .getString("prefix","") Log.i("test", "URL: $urlText${params[0]}.xml") val url = URL(urlText+params[0]+".xml") Log.i("test", "1") val connection = url.openConnection() Log.i("test", "2") connection.connect() Log.i("test", "3") val lengthOfFile = connection.contentLength val isStream = url.openStream() val data = ByteArray(1024) var total: Long = 0 var progress = 0 var finXML = "" var count = isStream.read(data) while (count != -1){ total += count.toLong() val progress_temp = total.toInt() * 100 / lengthOfFile if (progress_temp % 10 == 0 && progress != progress_temp) progress = progress_temp finXML += String(data.copyOfRange(0, count)) count = isStream.read(data) } isStream.close() xml = finXML } catch (e : MalformedURLException) { e.printStackTrace() return "Malformed URL" }catch (e : IOException){ e.printStackTrace() return "IO Exception" } Log.i("test", "download finished") return "Success" } } @SuppressLint("StaticFieldLeak") private inner class DownloadImage(val code : String?) : AsyncTask<String, Int, String>(){ val tempdb = dbpath?.let { SQLiteDatabase.openDatabase(it,null, 0) } override fun doInBackground(vararg params: String?): String { try { val urlText = params[0] Log.i("test", "URL: $urlText") val url = URL(urlText) Log.i("test", "1") val connection = url.openConnection() Log.i("test", "2") connection.connect() Log.i("test", "3") val lengthOfFile = connection.contentLength val isStream = url.openStream() val data = ByteArray(1024) var total: Long = 0 var progress = 0 var finImage = ArrayList<Byte>() var count = isStream.read(data) while (count != -1){ total += count.toLong() val progress_temp = total.toInt() * 100 / lengthOfFile if (progress_temp % 10 == 0 && progress != progress_temp) progress = progress_temp finImage.addAll(data.copyOfRange(0, count).toList()) count = isStream.read(data) } isStream.close() if(checkIfImageExists(params[1], params[2], tempdb)) { if (code != null) saveImageToDb(finImage, params[1], params[2], tempdb) else saveImageToDbButWithMoreFunctionalityThatFixesStuff( finImage, params[1], params[2], tempdb ) } } catch (e : Exception) { e.printStackTrace() return "Exception" } Log.i("test", "download finished") return "Success" } } fun saveImageToDb(img: ArrayList<Byte>, itemID: String?, colorID: String?, tempdb: SQLiteDatabase?){ val values = ContentValues().apply { put("Image", img.toByteArray()) } tempdb?.update("Codes", values, "ITEMID= ? AND COLORID= ?", arrayOf(itemID,colorID)) } fun saveImageToDbButWithMoreFunctionalityThatFixesStuff(img: ArrayList<Byte>, itemID: String?, colorID: String?, tempdb: SQLiteDatabase?){ val values = ContentValues() values.put("ItemID", itemID) values.put("ColorID", colorID) values.put("Image", img.toByteArray()) tempdb?.insert("Codes", null, values) } fun checkIfImageExists(itemID: String?, colorID: String?, tempdb : SQLiteDatabase?) : Boolean{ val query = "select Image from Codes where ItemID=$itemID and ColorID=$colorID" val cursor = tempdb?.rawQuery(query, null) if (cursor != null) { if(cursor.moveToFirst()){ val img = cursor.getBlob(0) cursor.close() return img == null } } return true } }
0
Kotlin
0
0
72301ec966f6fae94c1262ea1ccaa13cf845928e
14,063
BrickList
MIT License
src/oracle-tools/src/main/kotlin/org/icpclive/oracle/MjpegRunner.kt
icpc
447,849,919
false
{"Kotlin": 630579, "TypeScript": 281606, "JavaScript": 120527, "HTML": 77318, "Python": 2840, "CSS": 1184, "Ruby": 1042, "SCSS": 1034, "Batchfile": 726, "Shell": 600, "Dockerfile": 453}
package org.icpclive.oracle import java.io.* import java.net.SocketTimeoutException import java.net.URL import javax.imageio.ImageIO /** * Given an extended JPanel and URL read and create BufferedImages to be displayed from a MJPEG stream * * @author shrub34 Copyright 2012 * Free for reuse, just please give me a credit if it is for a redistributed package */ class MjpegRunner(private val viewer: MJpegViewer, url: URL) : Runnable { private val urlStream: InputStream private var stringWriter: StringWriter private var processing = true private var last: Long = 0 init { val urlConn = url.openConnection() // change the timeout to taste, I like 1 second urlConn.readTimeout = 10000 urlConn.connect() urlStream = urlConn.getInputStream() stringWriter = StringWriter(128) } /** * Stop the loop, and allow it to clean up */ @Synchronized fun stop() { processing = false } /** * Keeps running while process() returns true * * * Each loop asks for the next JPEG image and then sends it to our JPanel to draw * * @see java.lang.Runnable.run */ override fun run() { while (processing) { try { val imageBytes = retrieveNextImage() val bais = ByteArrayInputStream(imageBytes) if (System.currentTimeMillis() > last + 1000) { val image = ImageIO.read(bais) if (image != null) { viewer.setBufferedImage(image) viewer.repaint() } last = System.currentTimeMillis() } } catch (ste: SocketTimeoutException) { System.err.println("failed stream read: $ste") viewer.setFailedString("Lost Camera connection: $ste") viewer.repaint() stop() } catch (e: IOException) { System.err.println("failed stream read: $e") stop() } } System.err.println("Stopping") // close streams try { urlStream.close() } catch (ioe: IOException) { System.err.println("Failed to close the stream: $ioe") } } /** * Using the urlStream get the next JPEG image as a byte[] * * @return byte[] of the JPEG * @throws IOException */ @Throws(IOException::class) private fun retrieveNextImage(): ByteArray { var haveHeader = false var currByte: Int var header: String? = null // build headers // the DCS-930L stops it's headers while (urlStream.read().also { currByte = it } > -1 && !haveHeader) { stringWriter.write(currByte) val tempString = stringWriter.toString() if (tempString.endsWith("\r\n\r\n")) { haveHeader = true header = tempString } } // 255 indicates the start of the jpeg image var lastByte = -1 while (true) { if (lastByte == 255 && currByte == 0xd8) { break } lastByte = currByte currByte = urlStream.read() // just skip extras } // rest is the buffer val contentLength = contentLength(header) val imageBytes = ByteArray(contentLength + 1) // since we ate the original 255 , shove it back in imageBytes[0] = 255.toByte() imageBytes[1] = 0xd8.toByte() var offset = 2 var numRead = 0 while (offset < imageBytes.size && urlStream.read(imageBytes, offset, imageBytes.size - offset).also { numRead = it } >= 0 ) { offset += numRead } stringWriter = StringWriter(128) return imageBytes } companion object { private const val CONTENT_LENGTH = "Content-Length: " private const val CONTENT_TYPE = "Content-Type: image/jpeg" // dirty but it works content-length parsing private fun contentLength(header: String?): Int { val indexOfContentLength = header!!.indexOf(CONTENT_LENGTH) val valueStartPos = indexOfContentLength + CONTENT_LENGTH.length val indexOfEOL = header.indexOf('\n', indexOfContentLength) val lengthValStr = header.substring(valueStartPos, indexOfEOL).trim { it <= ' ' } return lengthValStr.toInt() } } }
17
Kotlin
15
46
70298cce63165ab79c77823b6f8a261db81e5b28
4,583
live-v3
MIT License
src/test/kotlin/org/jmailen/gradle/kotlinter/support/HasErrorReporterTest.kt
samzurcher
179,701,204
true
{"Kotlin": 38727}
package org.jmailen.gradle.kotlinter.support import com.pinterest.ktlint.core.LintError import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test class HasErrorReporterTest { private lateinit var reporter: HasErrorReporter @Before fun setUp() { reporter = HasErrorReporter() } @Test fun hasErrorReturnsFalseForOnLintErrorNeverCalled() { val result = reporter.hasError assertFalse(result) } @Test fun hasErrorReturnsTrueForOnLintErrorCalled() { reporter.onLintError("", LintError(0, 0, "", ""), false) val result = reporter.hasError assertTrue(result) } }
0
Kotlin
0
0
d81e6b7d6d5eadff968b6cca6e77041efe34665a
711
kotlinter-gradle
Apache License 2.0
android/app/src/main/java/com/algorand/android/customviews/AlgorandFloatingActionButton.kt
perawallet
364,359,642
false
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
/* * Copyright 2022 Pera Wallet, LDA * 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.algorand.android.customviews import android.content.Context import android.util.AttributeSet import androidx.constraintlayout.motion.widget.MotionLayout import androidx.core.view.isVisible import com.algorand.android.R import com.algorand.android.databinding.CustomAlgorandFabBinding import com.algorand.android.utils.viewbinding.viewBinding import kotlin.properties.Delegates class AlgorandFloatingActionButton @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : MotionLayout(context, attrs) { private val binding = viewBinding(CustomAlgorandFabBinding::inflate) private var listener: Listener? = null private var isExpanded by Delegates.observable(false) { _, _, newValue -> listener?.onStateChange(newValue) } init { initUi() } fun setBuyAlgoActionButtonVisibility(isVisible: Boolean) { binding.buyAlgoActionButton.isVisible = isVisible } private fun initUi() { with(binding) { receiveActionButton.setOnClickListener { listener?.onReceiveClick() } sendActionButton.setOnClickListener { listener?.onSendClick() } buyAlgoActionButton.setOnClickListener { listener?.onBuyAlgoClick() } openCloseActionButton.setOnClickListener { handleButtonClick() } } } private fun handleButtonClick() { updateOpenCloseButtonDrawable() animateView() isExpanded = !isExpanded } private fun updateOpenCloseButtonDrawable() { val buttonIconRes = if (isExpanded) R.drawable.ic_arrow_swap else R.drawable.ic_close binding.openCloseActionButton.setImageResource(buttonIconRes) } private fun animateView() { if (isExpanded) transitionToStart() else transitionToEnd() } fun setListener(listener: Listener) { this.listener = listener } interface Listener { fun onReceiveClick() fun onSendClick() fun onBuyAlgoClick() fun onStateChange(isExtended: Boolean) } }
22
Swift
62
181
92fc77f73fa4105de82d5e87b03c1e67600a57c0
2,637
pera-wallet
Apache License 2.0
RickMortyAndroidApp/network/src/main/kotlin/io/github/brunogabriel/rickmorty/network/di/RetrofitModule.kt
brunogabriel
437,544,186
false
null
package io.github.brunogabriel.rickmorty.network.di import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import dagger.Module import dagger.Provides import io.github.brunogabriel.rickmorty.network.BuildConfig import io.github.brunogabriel.rickmorty.network.di.qualifiers.BaseUrl import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttp import okhttp3.OkHttpClient import retrofit2.Retrofit import javax.inject.Singleton @Module( includes = [ OkHttpModule::class ] ) internal class RetrofitModule { companion object { @Singleton @Provides @BaseUrl fun providesBaseUrl(): String = BuildConfig.BASE_URL @Singleton @Provides @ExperimentalSerializationApi fun providesRetrofit( @BaseUrl baseUrl: String, client: OkHttpClient ): Retrofit { val json = Json { ignoreUnknownKeys = true } return Retrofit.Builder() .baseUrl(baseUrl) .client(client) .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) .build() } } }
0
Kotlin
0
3
6e40b2cdc157cf07a5b4574e9c308335112deb4d
1,321
rick-and-morty-app
MIT License
src/main/kotlin/io/vlang/debugger/renderers/VlangRendererEvaluationContext.kt
vlang
754,996,747
false
{"Kotlin": 1648092, "V": 250415, "Java": 68641, "Lex": 20424, "HTML": 6275}
package org.vlang.debugger.renderers import com.jetbrains.cidr.execution.debugger.backend.DebuggerDriver import com.jetbrains.cidr.execution.debugger.backend.LLValue import com.jetbrains.cidr.execution.debugger.backend.LLValueData import org.vlang.debugger.lang.VlangLldbEvaluationContext import org.vlang.debugger.mapItems import org.vlang.debugger.withContext class VlangRendererEvaluationContext( val evaluationContext: VlangLldbEvaluationContext, root: LLValue, ) { private val dataStack = mutableSetOf(root) private val childStack = mutableSetOf(root) fun getData(value: LLValue): LLValueData { if (dataStack.add(value)) { val data = evaluationContext.getData(value) dataStack.remove(value) return data } return evaluationContext.getRawData(value) } fun evaluate(expression: String): LLValue = evaluationContext.evaluate(expression) fun getVariableChildren( value: VlangValue, offset: Int, size: Int, raw: Boolean, ): DebuggerDriver.ResultList<VlangValue> { if (!raw && childStack.add(value.llValue)) try { val renderer = evaluationContext.findRenderer(value.llValue) if (renderer != null) { return renderer.getVariableChildren(value, offset, size) } } finally { childStack.remove(value.llValue) } return evaluationContext.getRawVariableChildren(value.llValue, offset, size) .mapItems { it.withContext(this) } } }
53
Kotlin
5
33
5b05a7b1f71ef8dcd7f26425a756259081fe5122
1,612
intellij-v
MIT License
common/src/commonMain/kotlin/com/niji/claudio/common/ui/widget/ClaudioDropdownMenu.kt
GuillaumeMuret
718,024,230
false
{"Kotlin": 268180, "Shell": 4408, "Swift": 571, "HTML": 357, "CSS": 108}
package com.niji.claudio.common.ui.widget import androidx.compose.foundation.layout.ColumnScope import androidx.compose.material.DropdownMenu import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable fun ClaudioDropdownMenu( modifier: Modifier, expanded: Boolean, onDismissRequest: () -> Unit, content: @Composable ColumnScope.() -> Unit ) { DropdownMenu( modifier = modifier, expanded = expanded, onDismissRequest = onDismissRequest, content = content ) }
0
Kotlin
0
0
c872bf35dcc54f700720817555d80ecf370e1d6d
548
claudio-app
Apache License 2.0
src/main/kotlin/com/github/ichanzhar/rsql/operations/Params.kt
ichanzhar
294,157,745
false
null
package com.github.ichanzhar.rsql.operations import javax.persistence.criteria.CriteriaBuilder import javax.persistence.criteria.Path data class Params( var root: Path<*>, var builder: CriteriaBuilder, var property: String, var globalProperty: String, var args: List<Any>, var argument: Any? )
0
Kotlin
0
1
d3bcdd1bf92a1704aa9697b363826ab9619e73f5
320
rsql-hibernate-jpa
MIT License
sphereon-kmp-crypto/src/commonTest/kotlin/com/sphereon/jose/JwkTest.kt
Sphereon-Opensource
832,677,457
false
{"Kotlin": 532209, "JavaScript": 3855}
package com.sphereon.jose.jwk import com.sphereon.cbor.cose.CoseCurve import com.sphereon.cbor.cose.CoseKeyCbor import com.sphereon.cbor.cose.CoseKeyType import com.sphereon.jose.jwa.JwaCurve import com.sphereon.jose.jwa.JwaKeyType import com.sphereon.kmp.Encoding import com.sphereon.kmp.decodeFrom import com.sphereon.kmp.encodeTo import kotlinx.coroutines.test.TestResult import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals private const val HEX_ENCODED_CBOR_KEY = "a401022001215820bb11cddd6e9e869d1559729a30d89ed49f3631524215961271abbbe28d7b731f225820dbd639132e2ee561965b830530a6a024f1098888f313550515921184c86acac3" class JWKTest { @Test fun shouldConvertECJWKToCoseKey(): TestResult = runTest { val jwk = Jwk( kty = JwaKeyType.EC, crv = JwaCurve.P_256, x = "uxHN3W6ehp0VWXKaMNie1J82MVJCFZYScau74o17cx8", y = "29Y5Ey4u5WGWW4MFMKagJPEJiIjzE1UFFZIRhMhqysM" ) val coseKey = jwk.jwkToCoseKeyCbor() assertEquals(CoseKeyType.EC2.toCbor(), coseKey.kty) assertEquals(CoseCurve.P_256.toCbor(), coseKey.crv) assertContentEquals( byteArrayOf( -69, 17, -51, -35, 110, -98, -122, -99, 21, 89, 114, -102, 48, -40, -98, -44, -97, 54, 49, 82, 66, 21, -106, 18, 113, -85, -69, -30, -115, 123, 115, 31 ), coseKey.x!!.value ) assertEquals("bb11cddd6e9e869d1559729a30d89ed49f3631524215961271abbbe28d7b731f", coseKey.x!!.encodeTo(Encoding.HEX)) assertEquals(jwk.x, coseKey.x!!.encodeTo(Encoding.BASE64URL)) assertContentEquals( byteArrayOf( -37, -42, 57, 19, 46, 46, -27, 97, -106, 91, -125, 5, 48, -90, -96, 36, -15, 9, -120, -120, -13, 19, 85, 5, 21, -110, 17, -124, -56, 106, -54, -61 ), coseKey.y!!.value ) assertEquals("dbd639132e2ee561965b830530a6a024f1098888f313550515921184c86acac3", coseKey.y!!.encodeTo(Encoding.HEX)) assertEquals(jwk.y, coseKey.y!!.encodeTo(Encoding.BASE64URL)) assertEquals( HEX_ENCODED_CBOR_KEY, coseKey.toCbor().cborEncode().encodeTo(Encoding.HEX) ) } @Test fun shouldConvertECJWKToCoseKeyAndBack(): TestResult = runTest { val jwk = Jwk( kty = JwaKeyType.EC, crv = JwaCurve.P_256, x = "uxHN3W6ehp0VWXKaMNie1J82MVJCFZYScau74o17cx8", y = "29Y5Ey4u5WGWW4MFMKagJPEJiIjzE1UFFZIRhMhqysM" ) assertEquals(jwk, jwk.jwkToCoseKeyCbor().cborToJwk()) } @Test fun shouldConvertECCoseKeyToJWKandBack(): TestResult = runTest { val cborKey = CoseKeyCbor.cborDecode(HEX_ENCODED_CBOR_KEY.decodeFrom(Encoding.HEX)) assertEquals(cborKey, cborKey.cborToJwk().jwkToCoseKeyCbor()) } @Test fun shouldHaveSomeFunWithConversion(): TestResult = runTest { val cborKey = CoseKeyCbor.cborDecode(HEX_ENCODED_CBOR_KEY.decodeFrom(Encoding.HEX)) assertEquals(cborKey, cborKey.cborToJwk().jwkToCoseKeyJson().jsonToJwk().jwkToCoseKeyCbor().cborToJwk().jwkToCoseKeyCbor()) } }
0
Kotlin
0
2
15a6f133cd830a213eccc96726d4167a6fd81891
4,168
mdoc-cbor-crypto-multiplatform
Apache License 2.0
imagepipeline/src/main/java/com/facebook/imagepipeline/core/ImagePipelineExperiments.kt
facebook
31,533,997
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.core import android.content.Context import android.graphics.Bitmap import com.facebook.cache.common.CacheKey import com.facebook.common.internal.Supplier import com.facebook.common.internal.Suppliers import com.facebook.common.memory.ByteArrayPool import com.facebook.common.memory.PooledByteBuffer import com.facebook.common.memory.PooledByteBufferFactory import com.facebook.common.memory.PooledByteStreams import com.facebook.common.webp.WebpBitmapFactory import com.facebook.common.webp.WebpBitmapFactory.WebpErrorLogger import com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory import com.facebook.imagepipeline.cache.BufferedDiskCache import com.facebook.imagepipeline.cache.CacheKeyFactory import com.facebook.imagepipeline.cache.MemoryCache import com.facebook.imagepipeline.decoder.ImageDecoder import com.facebook.imagepipeline.decoder.ProgressiveJpegConfig import com.facebook.imagepipeline.image.CloseableImage import com.facebook.imagepipeline.platform.PlatformDecoderOptions import com.facebook.imageutils.BitmapUtil /** * Encapsulates additional elements of the [ImagePipelineConfig] which are currently in an * experimental state. * * These options may often change or disappear altogether and it is not recommended to change their * values from their defaults. */ class ImagePipelineExperiments private constructor(builder: Builder) { val isWebpSupportEnabled: Boolean val webpErrorLogger: WebpErrorLogger? val isDecodeCancellationEnabled: Boolean val webpBitmapFactory: WebpBitmapFactory? val useDownsamplingRatioForResizing: Boolean val useBitmapPrepareToDraw: Boolean val useBalancedAnimationStrategy: Boolean val animationStrategyBufferLengthMilliseconds: Int val bitmapPrepareToDrawMinSizeBytes: Int val bitmapPrepareToDrawMaxSizeBytes: Int val bitmapPrepareToDrawForPrefetch: Boolean val maxBitmapSize: Int val isNativeCodeDisabled: Boolean val isPartialImageCachingEnabled: Boolean val producerFactoryMethod: ProducerFactoryMethod val isLazyDataSource: Supplier<Boolean> val isGingerbreadDecoderEnabled: Boolean val downscaleFrameToDrawableDimensions: Boolean val suppressBitmapPrefetchingSupplier: Supplier<Boolean> val isExperimentalThreadHandoffQueueEnabled: Boolean val memoryType: Long val keepCancelledFetchAsLowPriority: Boolean val downsampleIfLargeBitmap: Boolean val isEncodedCacheEnabled: Boolean val isEnsureTranscoderLibraryLoaded: Boolean val isEncodedMemoryCacheProbingEnabled: Boolean val isDiskCacheProbingEnabled: Boolean val trackedKeysSize: Int val allowDelay: Boolean val handOffOnUiThreadOnly: Boolean val shouldStoreCacheEntrySize: Boolean val shouldIgnoreCacheSizeMismatch: Boolean val shouldUseDecodingBufferHelper: Boolean val allowProgressiveOnPrefetch: Boolean val cancelDecodeOnCacheMiss: Boolean val animationRenderFpsLimit: Int val prefetchShortcutEnabled: Boolean val platformDecoderOptions: PlatformDecoderOptions class Builder(private val configBuilder: ImagePipelineConfig.Builder) { @JvmField var shouldUseDecodingBufferHelper = false @JvmField var webpSupportEnabled = false @JvmField var webpErrorLogger: WebpErrorLogger? = null @JvmField var decodeCancellationEnabled = false @JvmField var webpBitmapFactory: WebpBitmapFactory? = null @JvmField var useDownsamplingRatioForResizing = false @JvmField var useBitmapPrepareToDraw = false @JvmField var useBalancedAnimationStrategy = false @JvmField var animationStrategyBufferLengthMilliseconds = 1000 @JvmField var bitmapPrepareToDrawMinSizeBytes = 0 @JvmField var bitmapPrepareToDrawMaxSizeBytes = 0 @JvmField var bitmapPrepareToDrawForPrefetch = false @JvmField var maxBitmapSize = BitmapUtil.MAX_BITMAP_SIZE.toInt() @JvmField var nativeCodeDisabled = false @JvmField var isPartialImageCachingEnabled = false @JvmField var producerFactoryMethod: ProducerFactoryMethod? = null @JvmField var lazyDataSource: Supplier<Boolean>? = null @JvmField var gingerbreadDecoderEnabled = false @JvmField var downscaleFrameToDrawableDimensions = false @JvmField var suppressBitmapPrefetchingSupplier = Suppliers.of(false) @JvmField var experimentalThreadHandoffQueueEnabled = false @JvmField var memoryType: Long = 0 @JvmField var keepCancelledFetchAsLowPriority = false @JvmField var downsampleIfLargeBitmap = false @JvmField var encodedCacheEnabled = true @JvmField var ensureTranscoderLibraryLoaded = true @JvmField var isEncodedMemoryCacheProbingEnabled = false @JvmField var isDiskCacheProbingEnabled = false @JvmField var trackedKeysSize = 20 @JvmField var allowDelay = false @JvmField var handOffOnUiThreadOnly = false @JvmField var shouldStoreCacheEntrySize = false @JvmField var shouldIgnoreCacheSizeMismatch = false @JvmField var allowProgressiveOnPrefetch = false @JvmField var animationRenderFpsLimit = 30 @JvmField var cancelDecodeOnCacheMiss = false @JvmField var prefetchShortcutEnabled = false @JvmField var platformDecoderOptions = PlatformDecoderOptions() private fun asBuilder(block: () -> Unit): Builder { block() return this } fun setHandOffOnUiThreadOnly(handOffOnUiThreadOnly: Boolean) = asBuilder { this.handOffOnUiThreadOnly = handOffOnUiThreadOnly } fun setStoreCacheEntrySize(shouldStoreCacheEntrySize: Boolean) = asBuilder { this.shouldStoreCacheEntrySize = shouldStoreCacheEntrySize } fun setIgnoreCacheSizeMismatch(shouldIgnoreCacheSizeMismatch: Boolean) = asBuilder { this.shouldIgnoreCacheSizeMismatch = shouldIgnoreCacheSizeMismatch } fun setWebpSupportEnabled(webpSupportEnabled: Boolean) = asBuilder { this.webpSupportEnabled = webpSupportEnabled } fun setPrefetchShortcutEnabled(prefetchShortcutEnabled: Boolean) = asBuilder { this.prefetchShortcutEnabled = prefetchShortcutEnabled } fun shouldUseDecodingBufferHelper(): Boolean = shouldUseDecodingBufferHelper fun setShouldUseDecodingBufferHelper(shouldUseDecodingBufferHelper: Boolean) = asBuilder { this.shouldUseDecodingBufferHelper = shouldUseDecodingBufferHelper } fun setUseDownsampligRatioForResizing(useDownsamplingRatioForResizing: Boolean) = asBuilder { this.useDownsamplingRatioForResizing = useDownsamplingRatioForResizing } /** * Enables the caching of partial image data, for example if the request is cancelled or fails * after some data has been received. */ fun setPartialImageCachingEnabled(partialImageCachingEnabled: Boolean) = asBuilder { isPartialImageCachingEnabled = partialImageCachingEnabled } /** * If true we cancel decoding jobs when the related request has been cancelled * * @param decodeCancellationEnabled If true the decoding of cancelled requests are cancelled * @return The Builder itself for chaining */ fun setDecodeCancellationEnabled(decodeCancellationEnabled: Boolean) = asBuilder { this.decodeCancellationEnabled = decodeCancellationEnabled } fun setWebpErrorLogger(webpErrorLogger: WebpErrorLogger?) = asBuilder { this.webpErrorLogger = webpErrorLogger } fun setWebpBitmapFactory(webpBitmapFactory: WebpBitmapFactory?) = asBuilder { this.webpBitmapFactory = webpBitmapFactory } /** * If enabled, the pipeline will call [android.graphics.Bitmap.prepareToDraw] after decoding. * This potentially reduces lag on Android N+ as this step now happens async when the * RendererThread is idle. * * @param useBitmapPrepareToDraw set true for enabling prepareToDraw * @param minBitmapSizeBytes Bitmaps with a [Bitmap.getByteCount] smaller than this value are * not uploaded * @param maxBitmapSizeBytes Bitmaps with a [Bitmap.getByteCount] larger than this value are not * uploaded * @param preparePrefetch If this is true, also pre-fetching image requests will trigger the * [android.graphics.Bitmap.prepareToDraw] call. * @return The Builder itself for chaining */ fun setBitmapPrepareToDraw( useBitmapPrepareToDraw: Boolean, minBitmapSizeBytes: Int, maxBitmapSizeBytes: Int, preparePrefetch: Boolean ) = asBuilder { this.useBitmapPrepareToDraw = useBitmapPrepareToDraw this.bitmapPrepareToDrawMinSizeBytes = minBitmapSizeBytes this.bitmapPrepareToDrawMaxSizeBytes = maxBitmapSizeBytes this.bitmapPrepareToDrawForPrefetch = preparePrefetch } /** Enable balance strategy between RAM and CPU for rendering bitmap animations (WebP, Gif) */ fun setBalancedAnimationStrategy(useBalancedAnimationStrategy: Boolean) = asBuilder { this.useBalancedAnimationStrategy = useBalancedAnimationStrategy } /** The balanced animation strategy buffer length for single animation */ fun setAnimationStrategyBufferLengthMilliseconds( animationStrategyBufferLengthMilliseconds: Int ) = asBuilder { this.animationStrategyBufferLengthMilliseconds = animationStrategyBufferLengthMilliseconds } /** * Sets the maximum bitmap size use to compute the downsampling value when decoding Jpeg images. */ fun setMaxBitmapSize(maxBitmapSize: Int) = asBuilder { this.maxBitmapSize = maxBitmapSize } /** * If true, the pipeline will use alternative implementations without native code. * * @param nativeCodeDisabled set true for disabling native implementation. * @return The Builder itself for chaining */ fun setNativeCodeDisabled(nativeCodeDisabled: Boolean) = asBuilder { this.nativeCodeDisabled = nativeCodeDisabled } /** * Stores an alternative method to instantiate the [ProducerFactory]. This allows experimenting * with overridden producers. */ fun setProducerFactoryMethod(producerFactoryMethod: ProducerFactoryMethod?) = asBuilder { this.producerFactoryMethod = producerFactoryMethod } /** Stores an alternative lazy method to instantiate the data souce. */ fun setLazyDataSource(lazyDataSource: Supplier<Boolean>?) = asBuilder { this.lazyDataSource = lazyDataSource } fun setGingerbreadDecoderEnabled(gingerbreadDecoderEnabled: Boolean) = asBuilder { this.gingerbreadDecoderEnabled = gingerbreadDecoderEnabled } fun setShouldDownscaleFrameToDrawableDimensions(downscaleFrameToDrawableDimensions: Boolean) = asBuilder { this.downscaleFrameToDrawableDimensions = downscaleFrameToDrawableDimensions } fun setSuppressBitmapPrefetchingSupplier(suppressBitmapPrefetchingSupplier: Supplier<Boolean>) = asBuilder { this.suppressBitmapPrefetchingSupplier = suppressBitmapPrefetchingSupplier } fun setExperimentalThreadHandoffQueueEnabled(experimentalThreadHandoffQueueEnabled: Boolean) = asBuilder { this.experimentalThreadHandoffQueueEnabled = experimentalThreadHandoffQueueEnabled } fun setExperimentalMemoryType(MemoryType: Long) = asBuilder { this.memoryType = MemoryType } fun setKeepCancelledFetchAsLowPriority(keepCancelledFetchAsLowPriority: Boolean) = asBuilder { this.keepCancelledFetchAsLowPriority = keepCancelledFetchAsLowPriority } fun setDownsampleIfLargeBitmap(downsampleIfLargeBitmap: Boolean) = asBuilder { this.downsampleIfLargeBitmap = downsampleIfLargeBitmap } fun setEncodedCacheEnabled(encodedCacheEnabled: Boolean) = asBuilder { this.encodedCacheEnabled = encodedCacheEnabled } fun setEnsureTranscoderLibraryLoaded(ensureTranscoderLibraryLoaded: Boolean) = asBuilder { this.ensureTranscoderLibraryLoaded = ensureTranscoderLibraryLoaded } fun setIsDiskCacheProbingEnabled(isDiskCacheProbingEnabled: Boolean) = asBuilder { this.isDiskCacheProbingEnabled = isDiskCacheProbingEnabled } fun setIsEncodedMemoryCacheProbingEnabled(isEncodedMemoryCacheProbingEnabled: Boolean) = asBuilder { this.isEncodedMemoryCacheProbingEnabled = isEncodedMemoryCacheProbingEnabled } fun setTrackedKeysSize(trackedKeysSize: Int) = asBuilder { this.trackedKeysSize = trackedKeysSize } fun setAllowDelay(allowDelay: Boolean) = asBuilder { this.allowDelay = allowDelay } fun setAllowProgressiveOnPrefetch(allowProgressiveOnPrefetch: Boolean) = asBuilder { this.allowProgressiveOnPrefetch = allowProgressiveOnPrefetch } fun setAnimationRenderFpsLimit(animationRenderFpsLimit: Int) = asBuilder { this.animationRenderFpsLimit = animationRenderFpsLimit } fun setCancelDecodeOnCacheMiss(cancelDecodeOnCacheMiss: Boolean) = asBuilder { this.cancelDecodeOnCacheMiss = cancelDecodeOnCacheMiss } fun setPlatformDecoderOptions(platformDecoderOptions: PlatformDecoderOptions) = asBuilder { this.platformDecoderOptions = platformDecoderOptions } fun build(): ImagePipelineExperiments = ImagePipelineExperiments(this) } interface ProducerFactoryMethod { fun createProducerFactory( context: Context, byteArrayPool: ByteArrayPool, imageDecoder: ImageDecoder, progressiveJpegConfig: ProgressiveJpegConfig, downsampleMode: DownsampleMode, resizeAndRotateEnabledForNetwork: Boolean, decodeCancellationEnabled: Boolean, executorSupplier: ExecutorSupplier, pooledByteBufferFactory: PooledByteBufferFactory, pooledByteStreams: PooledByteStreams, bitmapMemoryCache: MemoryCache<CacheKey?, CloseableImage?>, encodedMemoryCache: MemoryCache<CacheKey?, PooledByteBuffer?>, defaultBufferedDiskCache: BufferedDiskCache, smallImageBufferedDiskCache: BufferedDiskCache, dynamicBufferedDiskCaches: Map<String, BufferedDiskCache>?, cacheKeyFactory: CacheKeyFactory, platformBitmapFactory: PlatformBitmapFactory, bitmapPrepareToDrawMinSizeBytes: Int, bitmapPrepareToDrawMaxSizeBytes: Int, bitmapPrepareToDrawForPrefetch: Boolean, maxBitmapSize: Int, closeableReferenceFactory: CloseableReferenceFactory, keepCancelledFetchAsLowPriority: Boolean, trackedKeysSize: Int ): ProducerFactory } class DefaultProducerFactoryMethod : ProducerFactoryMethod { override fun createProducerFactory( context: Context, byteArrayPool: ByteArrayPool, imageDecoder: ImageDecoder, progressiveJpegConfig: ProgressiveJpegConfig, downsampleMode: DownsampleMode, resizeAndRotateEnabledForNetwork: Boolean, decodeCancellationEnabled: Boolean, executorSupplier: ExecutorSupplier, pooledByteBufferFactory: PooledByteBufferFactory, pooledByteStreams: PooledByteStreams, bitmapMemoryCache: MemoryCache<CacheKey?, CloseableImage?>, encodedMemoryCache: MemoryCache<CacheKey?, PooledByteBuffer?>, defaultBufferedDiskCache: BufferedDiskCache, smallImageBufferedDiskCache: BufferedDiskCache, dynamicBufferedDiskCaches: Map<String, BufferedDiskCache>?, cacheKeyFactory: CacheKeyFactory, platformBitmapFactory: PlatformBitmapFactory, bitmapPrepareToDrawMinSizeBytes: Int, bitmapPrepareToDrawMaxSizeBytes: Int, bitmapPrepareToDrawForPrefetch: Boolean, maxBitmapSize: Int, closeableReferenceFactory: CloseableReferenceFactory, keepCancelledFetchAsLowPriority: Boolean, trackedKeysSize: Int ): ProducerFactory = ProducerFactory( context!!, byteArrayPool!!, imageDecoder!!, progressiveJpegConfig!!, downsampleMode, resizeAndRotateEnabledForNetwork, decodeCancellationEnabled, executorSupplier!!, pooledByteBufferFactory!!, bitmapMemoryCache!!, encodedMemoryCache!!, defaultBufferedDiskCache!!, smallImageBufferedDiskCache!!, dynamicBufferedDiskCaches, cacheKeyFactory!!, platformBitmapFactory!!, bitmapPrepareToDrawMinSizeBytes, bitmapPrepareToDrawMaxSizeBytes, bitmapPrepareToDrawForPrefetch, maxBitmapSize, closeableReferenceFactory!!, keepCancelledFetchAsLowPriority, trackedKeysSize) } init { isWebpSupportEnabled = builder.webpSupportEnabled webpErrorLogger = builder.webpErrorLogger isDecodeCancellationEnabled = builder.decodeCancellationEnabled webpBitmapFactory = builder.webpBitmapFactory useDownsamplingRatioForResizing = builder.useDownsamplingRatioForResizing useBitmapPrepareToDraw = builder.useBitmapPrepareToDraw useBalancedAnimationStrategy = builder.useBalancedAnimationStrategy animationStrategyBufferLengthMilliseconds = builder.animationStrategyBufferLengthMilliseconds bitmapPrepareToDrawMinSizeBytes = builder.bitmapPrepareToDrawMinSizeBytes bitmapPrepareToDrawMaxSizeBytes = builder.bitmapPrepareToDrawMaxSizeBytes bitmapPrepareToDrawForPrefetch = builder.bitmapPrepareToDrawForPrefetch maxBitmapSize = builder.maxBitmapSize isNativeCodeDisabled = builder.nativeCodeDisabled isPartialImageCachingEnabled = builder.isPartialImageCachingEnabled producerFactoryMethod = builder.producerFactoryMethod ?: DefaultProducerFactoryMethod() isLazyDataSource = builder.lazyDataSource ?: Suppliers.BOOLEAN_FALSE isGingerbreadDecoderEnabled = builder.gingerbreadDecoderEnabled downscaleFrameToDrawableDimensions = builder.downscaleFrameToDrawableDimensions suppressBitmapPrefetchingSupplier = builder.suppressBitmapPrefetchingSupplier isExperimentalThreadHandoffQueueEnabled = builder.experimentalThreadHandoffQueueEnabled memoryType = builder.memoryType keepCancelledFetchAsLowPriority = builder.keepCancelledFetchAsLowPriority downsampleIfLargeBitmap = builder.downsampleIfLargeBitmap isEncodedCacheEnabled = builder.encodedCacheEnabled isEnsureTranscoderLibraryLoaded = builder.ensureTranscoderLibraryLoaded isEncodedMemoryCacheProbingEnabled = builder.isEncodedMemoryCacheProbingEnabled isDiskCacheProbingEnabled = builder.isDiskCacheProbingEnabled trackedKeysSize = builder.trackedKeysSize allowProgressiveOnPrefetch = builder.allowProgressiveOnPrefetch animationRenderFpsLimit = builder.animationRenderFpsLimit allowDelay = builder.allowDelay handOffOnUiThreadOnly = builder.handOffOnUiThreadOnly shouldStoreCacheEntrySize = builder.shouldStoreCacheEntrySize shouldIgnoreCacheSizeMismatch = builder.shouldIgnoreCacheSizeMismatch shouldUseDecodingBufferHelper = builder.shouldUseDecodingBufferHelper cancelDecodeOnCacheMiss = builder.cancelDecodeOnCacheMiss prefetchShortcutEnabled = builder.prefetchShortcutEnabled platformDecoderOptions = builder.platformDecoderOptions } companion object { @JvmStatic fun newBuilder(configBuilder: ImagePipelineConfig.Builder): Builder = Builder(configBuilder) } }
243
null
3789
17,055
7df742d4bc023bf393824a6102ae0154c4ee61de
19,433
fresco
MIT License
form/src/main/java/com/thejuki/kformmaster/model/FormPickerDropDownElement.kt
TheJuki
121,467,673
false
{"Gradle Kotlin DSL": 4, "XML": 66, "Markdown": 42, "Java Properties": 3, "Shell": 2, "Text": 1, "Ignore List": 3, "Batchfile": 2, "YAML": 5, "Proguard": 2, "Kotlin": 122, "Java": 1, "JSON": 1}
package com.thejuki.kformmaster.model import android.app.AlertDialog import android.view.View import android.widget.ArrayAdapter import android.widget.TextView import androidx.appcompat.widget.AppCompatEditText import com.thejuki.kformmaster.R import com.thejuki.kformmaster.helper.FormBuildHelper import com.thejuki.kformmaster.listener.OnFormElementValueChangedListener /** * Form Picker Dropdown Element * * Form element for AppCompatEditText (which on click opens a Single Choice dialog) * * @author **TheJuki** ([GitHub](https://github.com/TheJuki)) * @version 1.0 */ class FormPickerDropDownElement<T>(tag: String = "-1") : FormPickerElement<T>(tag) { /** * Form Element Options */ var options: List<T>? = null set(value) { field = value reInitDialog() } override fun clear() { super.clear() reInitDialog() } /** * Enable to display the radio buttons */ var displayRadioButtons: Boolean = false /** * Alert Dialog Builder * Used to call reInitDialog without needing context again. */ private var alertDialogBuilder: AlertDialog.Builder? = null /** * Alert Dialog Title * (optional - uses R.string.form_master_pick_one) */ var dialogTitle: String? = null /** * Alert Dialog Empty Message * (optional - uses R.string.form_master_empty) */ var dialogEmptyMessage: String? = null /** * ArrayAdapter for Alert Dialog * (optional - uses setItems(options)) */ var arrayAdapter: ArrayAdapter<*>? = null /** * Hold the [OnFormElementValueChangedListener] from [FormBuildHelper] */ private var listener: OnFormElementValueChangedListener? = null /** * Theme */ var theme: Int = 0 /** * Display Value For * Used to specify a string value to be displayed */ var displayValueFor: ((T?) -> String?) = { it?.toString() ?: "" } override val valueAsString: String get() = this.displayValueFor(this.value) ?: "" /** * Alert Dialog Title Custom View * If set, this will set the custom title for the alert dialog */ var dialogTitleCustomView: View? = null /** * Re-initializes the dialog * Should be called after the options list changes */ @Suppress("UNCHECKED_CAST") fun reInitDialog(formBuilder: FormBuildHelper? = null) { // reformat the options in format needed val options = arrayOfNulls<CharSequence>(this.options?.size ?: 0) val selectedIndex: Int = this.options?.indexOf(this.value) ?: -1 this.options?.let { for (i in it.indices) { options[i] = this.displayValueFor(it[i]) } } if (formBuilder != null) { listener = formBuilder.listener } lateinit var alertDialog: AlertDialog val editTextView = this.editView as? AppCompatEditText if (alertDialogBuilder == null && editTextView?.context != null) { alertDialogBuilder = AlertDialog.Builder(editTextView.context, theme) if (this.dialogTitle == null) { this.dialogTitle = editTextView.context.getString(R.string.form_master_pick_one) } if (this.dialogEmptyMessage == null) { this.dialogEmptyMessage = editTextView.context.getString(R.string.form_master_empty) } if (this.confirmTitle == null) { this.confirmTitle = editTextView.context.getString(R.string.form_master_confirm_title) } if (this.confirmMessage == null) { this.confirmMessage = editTextView.context.getString(R.string.form_master_confirm_message) } } alertDialogBuilder?.let { if (this.arrayAdapter != null) { this.arrayAdapter?.apply { it.setTitle([email protected]) .setMessage(null) .setPositiveButton(null, null) .setNegativeButton(null, null) if (displayRadioButtons) { it.setSingleChoiceItems(this, selectedIndex) { dialogInterface, which -> [email protected] = null [email protected](this.getItem(which)) listener?.onValueChanged(this@FormPickerDropDownElement) dialogInterface.dismiss() } } else { it.setAdapter(this) { _, which -> [email protected] = null [email protected](this.getItem(which)) listener?.onValueChanged(this@FormPickerDropDownElement) } } } } else { if (this.options?.isEmpty() == true) { it.setTitle(this.dialogTitle).setMessage(dialogEmptyMessage) } else { it.setTitle(this.dialogTitle).setMessage(null) .setPositiveButton(null, null) .setNegativeButton(null, null) if (displayRadioButtons) { it.setSingleChoiceItems(options, selectedIndex) { dialogInterface, which -> this.error = null this.options?.let { option -> this.setValue(option[which]) } listener?.onValueChanged(this) dialogInterface.dismiss() } } else { it.setItems(options) { _, which -> this.error = null this.options?.let { option -> this.setValue(option[which]) } listener?.onValueChanged(this) } } } } alertDialog = it.create() if (dialogTitleCustomView != null) { alertDialog.setCustomTitle(dialogTitleCustomView) } } // display the dialog on click val listener = View.OnClickListener { // Invoke onClick Unit this.onClick?.invoke() if (!confirmEdit || valueAsString.isEmpty()) { alertDialog.show() } else if (confirmEdit && value != null) { alertDialogBuilder ?.setTitle(confirmTitle) ?.setMessage(confirmMessage) ?.setPositiveButton(android.R.string.ok) { _, _ -> alertDialog.show() }?.setNegativeButton(android.R.string.cancel) { _, _ -> }?.show() } } itemView?.setOnClickListener(listener) editTextView?.setOnClickListener(listener) } override fun displayNewValue() { editView?.let { if (it is TextView) { it.text = valueAsString } } } }
16
Kotlin
45
195
d58338e52b22db38daf282183b9d962b9b9587e2
7,460
KFormMaster
Apache License 2.0
livecallback/src/main/java/com/ricarvalho/livecallback/registry/TokenizedOutputLiveCallbackRegistry.kt
rih-carv
398,972,259
false
null
package com.ricarvalho.livecallback.registry import androidx.lifecycle.Lifecycle import androidx.lifecycle.Lifecycle.State.DESTROYED import androidx.lifecycle.Lifecycle.State.RESUMED import androidx.lifecycle.Lifecycle.State.STARTED import androidx.lifecycle.LifecycleOwner import com.ricarvalho.livecallback.CallbackToken import com.ricarvalho.livecallback.LiveCallbackContainer import com.ricarvalho.livecallback.OutputCallback import com.ricarvalho.livecallback.OutputCallbackToken /** * An auto-releasing registry of [LiveCallbackContainer]s that correlates callbacks and its origins. * * It respects the lifecycle of other app components, such as activities, fragments, or services. * This awareness ensures the registered callbacks are only invoked when appropriate. * * You can register a callback paired with an object that implements the [LifecycleOwner] interface. * This relationship allows the callback to be released when the state of the lifecycle changes to * [DESTROYED]. This is especially useful for activities and fragments because they can safely * register callbacks and not worry about leaks: the callback and lifecycle are instantly released * when their lifecycles are destroyed. * * Registered callbacks can be invoked when appropriate, given that an [OutputCallbackToken] * corresponding to the one returned by [register] is provided on [invoke]. * * This is meant to be used with callbacks that receive no parameters and return a value. * For other kinds of callbacks, there are more specific versions: * - [TokenizedLiveCallbackRegistry]: for callbacks that receive a parameter and return a value. * - [TokenizedInputLiveCallbackRegistry]: for callbacks that receive a parameter and return no * value. * - [TokenizedSimpleLiveCallbackRegistry]: for callbacks that receive no parameters and return no * value. * * @param[O] The type of return of the callbacks. * @property[registry] The container that keeps the registered callbacks paired with respective * [Lifecycle]s into [LiveCallbackContainer]s identified by [OutputCallbackToken]s. * @constructor Creates a registry with the provided container, that relays invocations to the * registered callbacks based on the provided [OutputCallbackToken]s. The register creates * [LiveCallbackContainer]s as needed to keep callbacks and their associated [Lifecycle], then * removes a container when all its contained [Lifecycle]s are [DESTROYED]. */ @JvmInline value class TokenizedOutputLiveCallbackRegistry<O> private constructor( private val registry: MutableMap<OutputCallbackToken<O>, LiveCallbackContainer<Any?, O>> ) : OutputLiveCallbackRegistry<O>, (OutputCallbackToken<O>) -> List<O> { /** * Creates an empty registry that relays invocations to the registered callbacks based on the * provided [OutputCallbackToken]s. * * The register creates [LiveCallbackContainer]s as needed to keep callbacks and their * associated [Lifecycle], then removes a container when all its contained [Lifecycle]s are * [DESTROYED]. */ constructor() : this(mutableMapOf()) /** * Registers [callback] paired with [lifecycle] to be invoked later, and releases them when * [lifecycle] is [DESTROYED]. * * [callback] can be invoked when appropriate, given that an [OutputCallbackToken] corresponding * to the one returned is provided on [invoke]. * * It respects the lifecycle of other app components, such as activities, fragments, or services. * This ensures [callback] is only invoked when [lifecycle] is in an active state, unless * [runWhileStopped] is passed as `true`, in which case it is invoked at any state until * [DESTROYED]. * * [lifecycle] is considered to be active when in the [STARTED] or [RESUMED] state. * * @param[lifecycle] The [Lifecycle] which [callback] will be paired to. * @param[runWhileStopped] Indicates to invoke [callback] even when [lifecycle] is not active. * @param[callback] The callback to be registered. Will be released when [lifecycle] be * destroyed. May be invoked only when [lifecycle] is in an active state, or in whatever state * until [lifecycle] be destroyed, according to [runWhileStopped]'s value. * @return An [OutputCallbackToken] that identifies [callback] by it's origin, allowing it to be * retrieved and invoked later. */ override fun register( lifecycle: Lifecycle, runWhileStopped: Boolean, callback: OutputCallback<O> ) = CallbackToken.output(callback).also { token -> val container = registry.getOrPut(token) { LiveCallbackContainer(whenAllBeDestroyed = { registry.remove(token) }) } container.add(lifecycle, runWhileStopped) { callback() } } /** * Relays invocations to the registered callbacks whose tokens matches [token]. * * The return values of registered callbacks that are in inactive states (unless otherwise * indicated by runWhileStopped when being registered) or that returned null are discarded and * will not be included in the returned list. * * @param[token] The token identifying the registered callbacks that should be invoked. * @return The returned values of the callbacks with active [Lifecycle]s. */ override operator fun invoke(token: OutputCallbackToken<O>) = registry[token]?.invoke(null).orEmpty() }
14
Kotlin
0
6
5348f8db6540c6a1b0ac0d17b7939fa37945cd57
5,464
LiveCallback
MIT License
App/app/src/main/java/com/mengfou/ui/section/SectionFragment.kt
baiyazi
489,327,411
false
null
package com.mengfou.ui.section import android.annotation.SuppressLint import android.os.Bundle import android.util.Log import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebViewClient import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import com.mengfou.R import com.mengfou.databinding.FragmentSectionBinding import com.mengfou.entity.NovelDetail import com.mengfou.repository.DetailRepository import com.mengfou.ui.detail.DetailFragment import com.mengfou.utils.HTMLGenerator import com.mengfou.viewmodels.HomeFragmentViewModel import com.mengfou.views.HorizontalPopupLayout import com.mengfou.views.IHorizontalPopupLayoutItemClickListener import com.scwang.smartrefresh.layout.SmartRefreshLayout class SectionFragment : Fragment() { private var binding: FragmentSectionBinding? = null private var novelType: HomeFragmentViewModel.NovelType? = null private var novelDetail: NovelDetail? = null private var currentSectionId: Int = 1 // 小说章节编号从1开始 private lateinit var horizontalPopupLayout: HorizontalPopupLayout override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { if(binding == null) { binding = DataBindingUtil.inflate<FragmentSectionBinding>( inflater, R.layout.fragment_section, container, false ) novelType = arguments?.getSerializable(DetailFragment.NOVEL_BOOK_TYPE) as HomeFragmentViewModel.NovelType novelDetail = arguments?.getParcelable<NovelDetail>(DetailFragment.NOVEL_BOOK_DETAIL) } return binding!!.root } @SuppressLint("SetJavaScriptEnabled") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val actionBar = (activity as AppCompatActivity).supportActionBar actionBar?.title = novelDetail?.bookName val html = loadPageHTMLString(novelDetail) binding!!.apply { smartRefreshLayout.apply(::addSmartRefreshLayoutListener) webView.apply { setPadding(0, 0, 0, 0) settings.javaScriptEnabled = true settings.defaultTextEncodingName = "utf-8" webViewClient = WebViewClient() loadDataWithBaseURL(null, html, "text/html", "utf-8", null) } fab.setOnClickListener(fabOnClickListener) [email protected] = this.horizontalPopupLayout } } val fabOnClickListener = object : View.OnClickListener { override fun onClick(view: View?) { // todo 这里应该是startActivityForResult // ActivityJumpUtil.jumpToContentActivity(this@SectionFragment, novelDetail!!) horizontalPopupLayout.openView() horizontalPopupLayout.setOnItemClickListener(object : IHorizontalPopupLayoutItemClickListener { override fun onItemClick(itemId: Int) { Log.e("TAG", "SectionFragment => onItemClick: ${itemId}" ) } }) } } private fun addSmartRefreshLayoutListener(smartRefreshLayout: SmartRefreshLayout) { smartRefreshLayout.apply { setOnRefreshListener { // 下拉刷新 Log.e("TAG", "SectionFragment => addSmartRefreshLayoutListener: 下拉刷新" ) this.finishRefresh(200) } setOnLoadMoreListener { Log.e("TAG", "SectionFragment => addSmartRefreshLayoutListener: 上拉加载" ) this.finishLoadMore(200) } } } private fun loadPageHTMLString(novelDetail: NovelDetail?): String { var content: String? = null novelDetail?.let{ content = DetailRepository.loadNovelSectionByIdAndSectionId(novelDetail.id, currentSectionId) } if(content.isNullOrEmpty()) { content = HTMLGenerator.loadDefaultHTMLInfoPage() } return HTMLGenerator.loadSectionPage(content!!) } }
0
Kotlin
1
0
bb5229f121980237d09402678e4011fafc5e24fa
4,249
NovelApp
MIT License
backend/src/main/kotlin/com/cookbyte/backend/controllers/CategoryController.kt
matejapetkovska
708,374,701
false
{"Kotlin": 58255, "TypeScript": 46962, "HTML": 32189, "CSS": 25895, "JavaScript": 309}
package com.cookbyte.backend.controllers import com.cookbyte.backend.domain.Category import com.cookbyte.backend.service.CategoryService import com.cookbyte.backend.service.IngredientService import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/categories") class CategoryController(private val categoryService: CategoryService) { @GetMapping fun getAllCategories(): List<Category>? = categoryService.findAll() }
0
Kotlin
0
0
f1b47f089ab2f8c70de1e781c038a165b333f030
644
CookByte
MIT License
compiler/fir/entrypoint/src/org/jetbrains/kotlin/fir/session/FirJsSessionFactory.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.session import org.jetbrains.kotlin.config.* import org.jetbrains.kotlin.fir.* import org.jetbrains.kotlin.fir.analysis.FirOverridesBackwardCompatibilityHelper import org.jetbrains.kotlin.fir.checkers.registerJsCheckers import org.jetbrains.kotlin.fir.deserialization.ModuleDataProvider import org.jetbrains.kotlin.fir.extensions.FirExtensionRegistrar import org.jetbrains.kotlin.fir.java.FirProjectSessionProvider import org.jetbrains.kotlin.fir.resolve.calls.ConeCallConflictResolverFactory import org.jetbrains.kotlin.fir.resolve.providers.impl.* import org.jetbrains.kotlin.fir.scopes.FirKotlinScopeProvider import org.jetbrains.kotlin.fir.scopes.FirPlatformClassMapper import org.jetbrains.kotlin.incremental.components.LookupTracker import org.jetbrains.kotlin.library.metadata.resolver.KotlinResolvedLibrary import org.jetbrains.kotlin.name.Name object FirJsSessionFactory : FirAbstractSessionFactory() { fun createJsModuleBasedSession( moduleData: FirModuleData, sessionProvider: FirProjectSessionProvider, extensionRegistrars: List<FirExtensionRegistrar>, languageVersionSettings: LanguageVersionSettings = LanguageVersionSettingsImpl.DEFAULT, lookupTracker: LookupTracker?, init: FirSessionConfigurator.() -> Unit ): FirSession { return createModuleBasedSession( moduleData, sessionProvider, extensionRegistrars, languageVersionSettings, lookupTracker, null, init, registerExtraComponents = { it.registerJsSpecificResolveComponents() }, registerExtraCheckers = { it.registerJsCheckers() }, createKotlinScopeProvider = { FirKotlinScopeProvider { _, declaredMemberScope, _, _ -> declaredMemberScope } }, createProviders = { _, _, symbolProvider, generatedSymbolsProvider, dependenciesSymbolProvider -> listOfNotNull( symbolProvider, generatedSymbolsProvider, dependenciesSymbolProvider, ) } ) } fun createJsLibrarySession( mainModuleName: Name, resolvedLibraries: List<KotlinResolvedLibrary>, sessionProvider: FirProjectSessionProvider, moduleDataProvider: ModuleDataProvider, languageVersionSettings: LanguageVersionSettings = LanguageVersionSettingsImpl.DEFAULT, ) = createLibrarySession( mainModuleName, sessionProvider, moduleDataProvider, languageVersionSettings, registerExtraComponents = { it.registerJsSpecificResolveComponents() }, createKotlinScopeProvider = { FirKotlinScopeProvider { _, declaredMemberScope, _, _ -> declaredMemberScope } }, createProviders = { session, builtinsModuleData, kotlinScopeProvider -> listOf( KlibBasedSymbolProvider(session, moduleDataProvider, kotlinScopeProvider, resolvedLibraries), FirCloneableSymbolProvider(session, builtinsModuleData, kotlinScopeProvider), // (Most) builtins should be taken from the dependencies in JS compilation, therefore builtins provider is the last one // TODO: consider using "poisoning" provider for builtins to ensure that proper ones are taken from dependencies // NOTE: it requires precise filtering for true nuiltins, like Function* FirBuiltinSymbolProvider(session, builtinsModuleData, kotlinScopeProvider), ) } ) @OptIn(SessionConfiguration::class) fun FirSession.registerJsSpecificResolveComponents() { register(FirVisibilityChecker::class, FirVisibilityChecker.Default) register(ConeCallConflictResolverFactory::class, JsCallConflictResolverFactory) register(FirPlatformClassMapper::class, FirPlatformClassMapper.Default) register(FirOverridesBackwardCompatibilityHelper::class, FirOverridesBackwardCompatibilityHelper.Default()) } }
7
null
5478
44,267
7545472dd3b67d2ac5eb8024054e3e6ff7795bf6
4,264
kotlin
Apache License 2.0
Application/app/src/main/java/com/wrmh/allmyfood/views/recipes/RecipeFragment.kt
MiguelPortillo18
259,108,086
false
{"Kotlin": 94364}
package com.wrmh.allmyfood.views.recipes import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProviders import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.squareup.picasso.Picasso import com.wrmh.allmyfood.R import com.wrmh.allmyfood.adapters.IngredientsRecyclerAdapter import com.wrmh.allmyfood.adapters.StepsRecyclerAdapter import com.wrmh.allmyfood.api.API import com.wrmh.allmyfood.databinding.FragmentRecipeBinding import com.wrmh.allmyfood.factory.RecipesViewModelFactory import com.wrmh.allmyfood.models.CurrentUser import com.wrmh.allmyfood.models.RecipeModel import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlin.concurrent.fixedRateTimer /** * A simple [Fragment] subclass. */ class RecipeFragment : Fragment() { private val viewModelJob = Job() private val coroutineScope = CoroutineScope(viewModelJob + Dispatchers.Main) private val ingredientAdapter by lazy { IngredientsRecyclerAdapter() } private val stepsAdapter by lazy { StepsRecyclerAdapter() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { (activity as AppCompatActivity).supportActionBar?.title = getString(R.string.title_recipe) val application = requireNotNull(activity).application val binding = DataBindingUtil.inflate<FragmentRecipeBinding>( inflater, R.layout.fragment_recipe, container, false ) val recipe = arguments?.get("recipe") as RecipeModel val viewModelFactory = RecipesViewModelFactory(recipe, application) binding.viewModel = ViewModelProviders.of(this@RecipeFragment, viewModelFactory) .get(DetailRecipeViewModel::class.java) binding.apply { recyclerViewIngredients.apply { layoutManager = LinearLayoutManager(container?.context) adapter = ingredientAdapter recipe.ingredients?.let { ingredientAdapter.submitList(it) } } recyclerViewSteps.apply { layoutManager = LinearLayoutManager(container?.context) adapter = stepsAdapter recipe.steps?.let { stepsAdapter.submitList(it) } } recipeDetailDesc.text = recipe.desc } if(CurrentUser.previousFragmentForRecipe == "exp"){ binding.btnDeleteRecipePublic.visibility = View.INVISIBLE } binding.btnDeleteRecipePublic.setOnClickListener { deleteRecipe(recipe._id!!, [email protected]!!) } Picasso.get().load(recipe.recipeImage).into(binding.recipeDetailImage) return binding.root } private fun deleteRecipe(_id: String, context: Context) { coroutineScope.launch { val deleteRecipeDeferred = API().deleteRecipeAsync(_id) try { val apiResponse = deleteRecipeDeferred.await() if (apiResponse.error) throw java.lang.Exception() Toast.makeText(context, "Receta eliminada ...", Toast.LENGTH_LONG).show() [email protected]().popBackStack() } catch (e: Exception) { Toast.makeText(context, R.string.error, Toast.LENGTH_LONG).show() } } } }
0
Kotlin
0
1
375977d261788687bfae093d1d09c8b58d7b6593
3,820
Food-app
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsstrengthsbasedneedsassessmentsapi/service/AssessmentService.kt
ministryofjustice
623,389,131
false
{"Kotlin": 367233, "Makefile": 4171, "Dockerfile": 1146, "JavaScript": 323}
package uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.service import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.controller.request.UserDetails import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.formconfig.FormConfigProvider import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.persistence.entity.Assessment import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.persistence.entity.AssessmentVersionAudit import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.persistence.repository.AssessmentRepository import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.persistence.repository.AssessmentVersionAuditRepository import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.service.exception.AssessmentNotFoundException import java.util.UUID @Service class AssessmentService( val assessmentRepository: AssessmentRepository, val assessmentVersionAuditRepository: AssessmentVersionAuditRepository, val formConfigProvider: FormConfigProvider, val assessmentVersionService: AssessmentVersionService, ) { fun findByUuid(uuid: UUID): Assessment { return assessmentRepository.findByUuid(uuid) ?: throw AssessmentNotFoundException("No assessment found with UUID $uuid") } fun create(): Assessment { return Assessment.new(formConfigProvider.getLatest()) .apply { assessmentVersions.forEach { assessmentVersionService.setOasysEquivalents(it) } } .run(assessmentRepository::save) .also { log.info("Created assessment with UUID ${it.uuid}") } } @Transactional fun createAndAudit(userDetails: UserDetails): Assessment { return create().also { AssessmentVersionAudit( assessmentVersion = it.assessmentVersions.first(), userDetails = userDetails, ).run(assessmentVersionAuditRepository::save) } } companion object { private val log = LoggerFactory.getLogger(this::class.java) } }
4
Kotlin
0
0
a42922863e180fd274b6062a261d3ae5079194dc
2,177
hmpps-strengths-based-needs-assessments-api
MIT License
EcoSwapAndroid/src/main/java/com/darrenthiores/ecoswap/android/presentation/home/HomeScreen.kt
darrenthiores
688,372,873
false
{"Kotlin": 770054, "Swift": 362583}
package com.darrenthiores.ecoswap.android.presentation.home import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material.FabPosition import androidx.compose.material.FloatingActionButton import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Add import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.darrenthiores.ecoswap.android.R import com.darrenthiores.ecoswap.android.presentation.home.components.CategorySection import com.darrenthiores.ecoswap.android.presentation.home.components.HomeHeader import com.darrenthiores.ecoswap.android.presentation.home.components.ItemSection import com.darrenthiores.ecoswap.android.presentation.home.components.StoreSection import com.darrenthiores.ecoswap.presentation.home.HomeEvent import com.darrenthiores.ecoswap.presentation.home.HomeState @OptIn(ExperimentalFoundationApi::class) @Composable fun HomeScreen( state: HomeState, searchText: String, onAndroidEvent: (AndroidHomeEvent) -> Unit, onEvent: (HomeEvent) -> Unit, onCategoryClick: (String) -> Unit, onSearch: () -> Unit, onItemClick: (String) -> Unit, onStoreClick: (String) -> Unit, onAddClick: () -> Unit ) { val categoryPagingState = rememberPagerState() val recommendationListState = rememberLazyListState() val nearbyListState = rememberLazyListState() val storeListState = rememberLazyListState() Scaffold( topBar = { HomeHeader( searchText = searchText, onTextChange = { onAndroidEvent(AndroidHomeEvent.OnSearchChange(it)) }, onNotificationClick = { }, onSearch = onSearch ) }, floatingActionButton = { FloatingActionButton( onClick = onAddClick, backgroundColor = MaterialTheme.colors.primary ) { Icon( modifier = Modifier .size(32.dp), imageVector = Icons.Rounded.Add, contentDescription = stringResource(id = R.string.add_item), tint = MaterialTheme.colors.onPrimary ) } }, floatingActionButtonPosition = FabPosition.End ) { contentPadding -> LazyColumn( modifier = Modifier .fillMaxSize() .padding(contentPadding), verticalArrangement = Arrangement.spacedBy(24.dp), contentPadding = PaddingValues( vertical = 24.dp ) ) { item { CategorySection( pagerState = categoryPagingState, viewAll = state.viewAll, onItemClick = { category -> onCategoryClick(category.id) }, onToggleViewAll = { onEvent(HomeEvent.ToggleViewAll) } ) } item { ItemSection( title = stringResource(id = R.string.item_recommend), items = state.recommendations, state = recommendationListState, onSeeAllClick = { }, onItemClick = { item -> onItemClick(item.id) }, isLoading = state.isRecommendationLoading ) } item { ItemSection( title = stringResource(id = R.string.item_nearby), items = state.nearby, state = nearbyListState, onSeeAllClick = { }, onItemClick = { item -> onItemClick(item.id) }, isLoading = state.isNearbyLoading ) } item { StoreSection( title = stringResource(id = R.string.store_subtitle), stores = state.stores, state = storeListState, onSeeAllClick = { }, onStoreClick = { store -> onStoreClick(store.id) }, isLoading = state.isStoreLoading ) } } } }
0
Kotlin
0
0
792b3293b4e378b7482f948ce4de622cb88f3cf1
5,145
EcoSwap
MIT License
libraries/stdlib/src/kotlin/collections/MapsJVM.kt
EasyKotlin
93,485,627
false
null
package kotlin import java.util.Comparator import java.util.LinkedHashMap import java.util.Properties import java.util.SortedMap import java.util.TreeMap /** * Allows to use the index operator for storing values in a mutable map. */ // this code is JVM-specific, because JS has native set function public fun <K, V> MutableMap<K, V>.set(key: K, value: V): V? = put(key, value) /** * Converts this [Map] to a [SortedMap] so iteration order will be in key order. * * @sample test.collections.MapJVMTest.toSortedMap */ public fun <K : Comparable<K>, V> Map<K, V>.toSortedMap(): SortedMap<K, V> = TreeMap(this) /** * Converts this [Map] to a [SortedMap] using the given [comparator] so that iteration order will be in the order * defined by the comparator. * * @sample test.collections.MapJVMTest.toSortedMapWithComparator */ public fun <K, V> Map<K, V>.toSortedMap(comparator: Comparator<K>): SortedMap<K, V> { val result = TreeMap<K, V>(comparator) result.putAll(this) return result } /** * Returns a new [SortedMap] with the specified contents, given as a list of pairs * where the first value is the key and the second is the value. * * @sample test.collections.MapJVMTest.createSortedMap */ public fun <K, V> sortedMapOf(vararg values: Pair<K, V>): SortedMap<K, V> { val answer = TreeMap<K, V>() /** TODO replace by this simpler call when we can pass vararg values into other methods answer.putAll(values) */ for (v in values) { answer.put(v.first, v.second) } return answer } /** * Converts this [Map] to a [Properties] object. * * @sample test.collections.MapJVMTest.toProperties */ public fun Map<String, String>.toProperties(): Properties { val answer = Properties() for (e in this) { answer.put(e.key, e.value) } return answer }
0
null
0
1
133e9354a4ccec21eb4d226cf3f6c1f3da072309
1,840
exp
Apache License 2.0
clients/graphql-kotlin-client-serialization/src/test/kotlin/com/expediagroup/graphql/client/serialization/data/OptionalInputQuery.kt
ExpediaGroup
148,706,161
false
null
/* * Copyright 2021 Expedia, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.expediagroup.graphql.client.gson.data import com.expediagroup.graphql.client.gson.OptionalInput import com.expediagroup.graphql.client.types.GraphQLClientRequest import kotlin.reflect.KClass class InputQuery( override val variables: Variables ) : GraphQLClientRequest<InputQuery.Result> { override val query: String = "INPUT_QUERY" override val operationName: String = "InputQuery" override fun responseType(): KClass<Result> = Result::class data class Variables( val requiredInput: Int, val optionalIntInput: OptionalInput<Int> = OptionalInput.Undefined, val optionalStringInput: OptionalInput<String> = OptionalInput.Undefined, val optionalBooleanInput: OptionalInput<Boolean> = OptionalInput.Undefined ) data class Result( val stringResult: String ) }
68
null
345
1,739
d3ad96077fc6d02471f996ef34c67066145acb15
1,443
graphql-kotlin
Apache License 2.0
app/src/test/java/com/talhahasanzia/deezal/app/search/interactor/SearchInteractorImplTest.kt
talhahasanzia
201,644,695
false
null
package com.talhahasanzia.deezal.app.search.interactor import com.talhahasanzia.deezal.app.search.api.SearchArtistResponse import com.talhahasanzia.deezal.app.search.contracts.SearchInteractorOut import com.talhahasanzia.deezal.app.util.TestUtils import com.talhahasanzia.deezal.commons.network.Request import com.talhahasanzia.deezal.commons.network.ResponseCallback import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.Mockito import org.mockito.junit.MockitoJUnitRunner @RunWith(MockitoJUnitRunner::class) class SearchInteractorImplTest { @InjectMocks private lateinit var searchInteractorImpl: SearchInteractorImpl @Mock private lateinit var out: SearchInteractorOut @Mock private lateinit var searchArtistRequest: Request<SearchArtistResponse, String> @Mock private lateinit var requestData: HashMap<String, String> @Mock private lateinit var responseCallback: ResponseCallback<SearchArtistResponse> @Before fun setUp() { responseCallback = searchInteractorImpl searchInteractorImpl.initOut(out) } @Test fun getArtists_query_shouldCallExecute() { val query = "Two Door" searchInteractorImpl.getArtists(query) Mockito.verify(searchArtistRequest).execute(requestData, searchInteractorImpl) } @Test fun onSuccess_withResponse_shouldCallOnArtistsFound() { val response = TestUtils.getDummySearchResponse() searchInteractorImpl.onSuccess(response) Mockito.verify(out).onArtistsFound(response.data) Mockito.verify(searchArtistRequest).dispose() } @Test fun onFailure_withErrorMessage_shouldCallOnArtistFailure() { val message: String? = "Error message" searchInteractorImpl.onFailure(message, -1) Mockito.verify(out).onArtistFailure(message!!) Mockito.verify(searchArtistRequest).dispose() } }
0
Kotlin
0
1
e4a34ecdb805ff129350bb2033399fc8292752ce
1,997
deezal
Apache License 2.0
features/rageshake/impl/src/test/kotlin/io/element/android/features/rageshake/impl/reporter/DefaultBugReporterTest.kt
element-hq
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.rageshake.impl.reporter import com.google.common.truth.Truth.assertThat import io.element.android.features.rageshake.api.reporter.BugReporterListener import io.element.android.features.rageshake.test.crash.FakeCrashDataStore import io.element.android.features.rageshake.test.screenshot.FakeScreenshotHolder import io.element.android.libraries.matrix.test.FakeMatrixClient import io.element.android.libraries.matrix.test.FakeMatrixClientProvider import io.element.android.libraries.matrix.test.FakeSdkMetadata import io.element.android.libraries.matrix.test.core.aBuildMeta import io.element.android.libraries.matrix.test.encryption.FakeEncryptionService import io.element.android.libraries.network.useragent.DefaultUserAgentProvider import io.element.android.libraries.sessionstorage.api.LoginType import io.element.android.libraries.sessionstorage.api.SessionData import io.element.android.libraries.sessionstorage.impl.memory.InMemorySessionStore import io.element.android.tests.testutils.testCoroutineDispatchers import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest import okhttp3.MultipartReader import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okhttp3.mockwebserver.RecordedRequest import okio.buffer import okio.source import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment @RunWith(RobolectricTestRunner::class) class DefaultBugReporterTest { @Test fun `test sendBugReport success`() = runTest { val server = MockWebServer() server.enqueue( MockResponse() .setResponseCode(200) ) server.start() val sut = createDefaultBugReporter(server) var onUploadCancelledCalled = false var onUploadFailedCalled = false val progressValues = mutableListOf<Int>() var onUploadSucceedCalled = false sut.sendBugReport( withDevicesLogs = true, withCrashLogs = true, withScreenshot = true, problemDescription = "a bug occurred", canContact = true, listener = object : BugReporterListener { override fun onUploadCancelled() { onUploadCancelledCalled = true } override fun onUploadFailed(reason: String?) { onUploadFailedCalled = true } override fun onProgress(progress: Int) { progressValues.add(progress) } override fun onUploadSucceed() { onUploadSucceedCalled = true } }, ) val request = server.takeRequest() assertThat(request.path).isEqualTo("/") assertThat(request.method).isEqualTo("POST") server.shutdown() assertThat(onUploadCancelledCalled).isFalse() assertThat(onUploadFailedCalled).isFalse() assertThat(progressValues.size).isEqualTo(EXPECTED_NUMBER_OF_PROGRESS_VALUE) assertThat(onUploadSucceedCalled).isTrue() } @Test fun `test sendBugReport form data`() = runTest { val server = MockWebServer() server.enqueue( MockResponse() .setResponseCode(200) ) server.start() val mockSessionStore = InMemorySessionStore().apply { storeData(mockSessionData("@foo:eample.com", "ABCDEFGH")) } val buildMeta = aBuildMeta() val fakeEncryptionService = FakeEncryptionService() val matrixClient = FakeMatrixClient(encryptionService = fakeEncryptionService) fakeEncryptionService.givenDeviceKeys("CURVECURVECURVE", "EDKEYEDKEYEDKY") val sut = DefaultBugReporter( context = RuntimeEnvironment.getApplication(), screenshotHolder = FakeScreenshotHolder(), crashDataStore = FakeCrashDataStore(), coroutineDispatchers = testCoroutineDispatchers(), okHttpClient = { OkHttpClient.Builder().build() }, userAgentProvider = DefaultUserAgentProvider(buildMeta, FakeSdkMetadata("123456789")), sessionStore = mockSessionStore, buildMeta = buildMeta, bugReporterUrlProvider = { server.url("/") }, sdkMetadata = FakeSdkMetadata("123456789"), matrixClientProvider = FakeMatrixClientProvider(getClient = { Result.success(matrixClient) }) ) val progressValues = mutableListOf<Int>() sut.sendBugReport( withDevicesLogs = true, withCrashLogs = true, withScreenshot = true, problemDescription = "a bug occurred", canContact = true, listener = object : BugReporterListener { override fun onUploadCancelled() {} override fun onUploadFailed(reason: String?) {} override fun onProgress(progress: Int) { progressValues.add(progress) } override fun onUploadSucceed() {} }, ) val request = server.takeRequest() val foundValues = collectValuesFromFormData(request) assertThat(foundValues["app"]).isEqualTo("element-x-android") assertThat(foundValues["can_contact"]).isEqualTo("true") assertThat(foundValues["device_id"]).isEqualTo("ABCDEFGH") assertThat(foundValues["sdk_sha"]).isEqualTo("123456789") assertThat(foundValues["user_id"]).isEqualTo("@foo:eample.com") assertThat(foundValues["text"]).isEqualTo("a bug occurred") assertThat(foundValues["device_keys"]).isEqualTo("curve25519:CURVECURVECURVE, ed25519:EDKEYEDKEYEDKY") // device_key now added given they are not null assertThat(progressValues.size).isEqualTo(EXPECTED_NUMBER_OF_PROGRESS_VALUE + 1) server.shutdown() } @Test fun `test sendBugReport should not report device_keys if not known`() = runTest { val server = MockWebServer() server.enqueue( MockResponse() .setResponseCode(200) ) server.start() val mockSessionStore = InMemorySessionStore().apply { storeData(mockSessionData("@foo:eample.com", "ABCDEFGH")) } val buildMeta = aBuildMeta() val fakeEncryptionService = FakeEncryptionService() val matrixClient = FakeMatrixClient(encryptionService = fakeEncryptionService) fakeEncryptionService.givenDeviceKeys(null, null) val sut = DefaultBugReporter( context = RuntimeEnvironment.getApplication(), screenshotHolder = FakeScreenshotHolder(), crashDataStore = FakeCrashDataStore(), coroutineDispatchers = testCoroutineDispatchers(), okHttpClient = { OkHttpClient.Builder().build() }, userAgentProvider = DefaultUserAgentProvider(buildMeta, FakeSdkMetadata("123456789")), sessionStore = mockSessionStore, buildMeta = buildMeta, bugReporterUrlProvider = { server.url("/") }, sdkMetadata = FakeSdkMetadata("123456789"), matrixClientProvider = FakeMatrixClientProvider(getClient = { Result.success(matrixClient) }) ) sut.sendBugReport( withDevicesLogs = true, withCrashLogs = true, withScreenshot = true, problemDescription = "a bug occurred", canContact = true, listener = NoopBugReporterListener(), ) val request = server.takeRequest() val foundValues = collectValuesFromFormData(request) assertThat(foundValues["device_keys"]).isNull() server.shutdown() } @Test fun `test sendBugReport no client provider no session data`() = runTest { val server = MockWebServer() server.enqueue( MockResponse() .setResponseCode(200) ) server.start() val buildMeta = aBuildMeta() val fakeEncryptionService = FakeEncryptionService() fakeEncryptionService.givenDeviceKeys(null, null) val sut = DefaultBugReporter( context = RuntimeEnvironment.getApplication(), screenshotHolder = FakeScreenshotHolder(), crashDataStore = FakeCrashDataStore("I did crash", true), coroutineDispatchers = testCoroutineDispatchers(), okHttpClient = { OkHttpClient.Builder().build() }, userAgentProvider = DefaultUserAgentProvider(buildMeta, FakeSdkMetadata("123456789")), sessionStore = InMemorySessionStore(), buildMeta = buildMeta, bugReporterUrlProvider = { server.url("/") }, sdkMetadata = FakeSdkMetadata("123456789"), matrixClientProvider = FakeMatrixClientProvider(getClient = { Result.failure(Exception("Mock no client")) }) ) sut.sendBugReport( withDevicesLogs = true, withCrashLogs = true, withScreenshot = true, problemDescription = "a bug occurred", canContact = true, listener = NoopBugReporterListener(), ) val request = server.takeRequest() val foundValues = collectValuesFromFormData(request) println("## FOUND VALUES $foundValues") assertThat(foundValues["device_keys"]).isNull() assertThat(foundValues["device_id"]).isEqualTo("undefined") assertThat(foundValues["user_id"]).isEqualTo("undefined") assertThat(foundValues["label"]).isEqualTo("crash") } private fun collectValuesFromFormData(request: RecordedRequest): HashMap<String, String> { val boundary = request.headers["Content-Type"]!!.split("=").last() val foundValues = HashMap<String, String>() request.body.inputStream().source().buffer().use { val multipartReader = MultipartReader(it, boundary) // Just use simple parsing to detect basic properties val regex = "form-data; name=\"(\\w*)\".*".toRegex() multipartReader.use { var part = multipartReader.nextPart() while (part != null) { part.headers["Content-Disposition"]?.let { contentDisposition -> regex.find(contentDisposition)?.groupValues?.get(1)?.let { name -> foundValues.put(name, part!!.body.readUtf8()) } } part = multipartReader.nextPart() } } } return foundValues } private fun mockSessionData(userId: String, deviceId: String) = SessionData( userId = userId, deviceId = deviceId, homeserverUrl = "example.com", accessToken = "AA", isTokenValid = true, loginType = LoginType.DIRECT, loginTimestamp = null, oidcData = null, refreshToken = null, slidingSyncProxy = null, passphrase = <PASSWORD>, sessionPath = "session", ) @Test fun `test sendBugReport error`() = runTest { val server = MockWebServer() server.enqueue( MockResponse() .setResponseCode(400) .setBody("""{"error": "An error body"}""") ) server.start() val sut = createDefaultBugReporter(server) var onUploadCancelledCalled = false var onUploadFailedCalled = false var onUploadFailedReason: String? = null val progressValues = mutableListOf<Int>() var onUploadSucceedCalled = false sut.sendBugReport( withDevicesLogs = true, withCrashLogs = true, withScreenshot = true, problemDescription = "a bug occurred", canContact = true, listener = object : BugReporterListener { override fun onUploadCancelled() { onUploadCancelledCalled = true } override fun onUploadFailed(reason: String?) { onUploadFailedCalled = true onUploadFailedReason = reason } override fun onProgress(progress: Int) { progressValues.add(progress) } override fun onUploadSucceed() { onUploadSucceedCalled = true } }, ) val request = server.takeRequest() assertThat(request.path).isEqualTo("/") assertThat(request.method).isEqualTo("POST") server.shutdown() assertThat(onUploadCancelledCalled).isFalse() assertThat(onUploadFailedCalled).isTrue() assertThat(onUploadFailedReason).isEqualTo("An error body") assertThat(progressValues.size).isEqualTo(EXPECTED_NUMBER_OF_PROGRESS_VALUE) assertThat(onUploadSucceedCalled).isFalse() } private fun TestScope.createDefaultBugReporter( server: MockWebServer ): DefaultBugReporter { val buildMeta = aBuildMeta() return DefaultBugReporter( context = RuntimeEnvironment.getApplication(), screenshotHolder = FakeScreenshotHolder(), crashDataStore = FakeCrashDataStore(), coroutineDispatchers = testCoroutineDispatchers(), okHttpClient = { OkHttpClient.Builder().build() }, userAgentProvider = DefaultUserAgentProvider(buildMeta, FakeSdkMetadata("123456789")), sessionStore = InMemorySessionStore(), buildMeta = buildMeta, bugReporterUrlProvider = { server.url("/") }, sdkMetadata = FakeSdkMetadata("123456789"), matrixClientProvider = FakeMatrixClientProvider() ) } companion object { private const val EXPECTED_NUMBER_OF_PROGRESS_VALUE = 17 } }
9
null
4
955
31d0621fa15fe153bfd36104e560c9703eabe917
14,668
element-x-android
Apache License 2.0
android/src/main/java/com/zondy/mapgis/mobile/geoobjects/JSSplitMode.kt
MapGIS
463,426,830
false
{"TypeScript": 1360825, "Kotlin": 197019, "JavaScript": 2750, "Java": 1126, "Objective-C": 341, "Swift": 253}
package com.zondy.mapgis.mobile.geoobjects import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.zondy.mapgis.geodatabase.raster.PixelType class JSPixelType(context: ReactApplicationContext?) : ReactContextBaseJavaModule(context) { override fun getName(): String { return REACT_CLASS } override fun getConstants(): Map<String, Any>? { val constants: MutableMap<String, Any> = HashMap() val values = PixelType.values() for (i in values.indices) { val enumObj = values[i] constants[enumObj.name] = enumObj.name } return constants } companion object { private const val REACT_CLASS = "JSPixelType" } }
0
TypeScript
0
0
156db7d18afd91bcf720c6429dbcd359364abaf2
729
MapGIS-Mobile-React-Native
MIT License
relax-business-component/src/main/java/com/ustory/relax_business_component/utils/ErrorUtil.kt
UCodeUStory
146,243,987
false
null
package com.ustory.relax_business_component.utils import android.app.Activity import android.content.Context import android.content.DialogInterface import com.google.gson.JsonSyntaxException import com.ustory.relax_basic_component.core.dialog.ErrorDialog import com.ustory.relax_business_component.R import com.ustory.relax_business_component.exception.NullDataException import com.ustory.relax_business_component.exception.RequestFailedException import retrofit2.HttpException import timber.log.Timber import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException fun handleError(context: Context, throwable: Throwable?, onDismissListener: DialogInterface.OnDismissListener? = null) { if (context is Activity && context.isFinishing) { return } Timber.e(throwable, "handleError()") var title = context.getString(R.string.c_common_error) var message = throwable?.message ?: "" var overrideListener: DialogInterface.OnDismissListener? = null if (throwable is RequestFailedException) { val code = throwable.code //针对code码做统一处理 } else if (throwable is NullDataException) { //发现数据为null抛出异常 title = context.getString(R.string.c_error_service_failed) message = context.getString(R.string.m_null_response_data) } else if (throwable is JsonSyntaxException) { title = context.getString(R.string.c_error_service_failed) message = context.getString(R.string.m_json_parse_failed) } else if (throwable is SocketTimeoutException) { title = context.getString(R.string.c_request_timeout) message = context.getString(R.string.m_check_network) } else if (throwable is ConnectException || throwable is UnknownHostException) { title = context.getString(R.string.c_connect_failed) message = context.getString(R.string.m_check_network) } else if (throwable is HttpException) { title = context.getString(R.string.c_http_error) } else { message = throwable?.message ?: "" } val dialog = ErrorDialog( context = context, title = title, message = message ) dialog.setOnDismissListener(overrideListener ?: onDismissListener) dialog.show() }
0
Kotlin
17
250
7bd38ad751eb929514f996deaf08a19c24860be2
2,319
Relax
MIT License
src/main/kotlin/playground/common/observability/sentry/SentryConfiguration.kt
dtkmn
596,118,171
false
{"Kotlin": 333222, "Dockerfile": 763}
package playground.common.observability.sentry import io.sentry.IHub import io.sentry.Sentry import io.sentry.SentryOptions import io.sentry.spring.jakarta.SentryExceptionResolver import io.sentry.spring.jakarta.tracing.TransactionNameProvider import jakarta.servlet.http.HttpServletRequest import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.core.Ordered import org.springframework.web.servlet.HandlerExceptionResolver @Configuration @ConditionalOnProperty(name = ["sentry.enabled"], havingValue = "true") class SentryConfiguration { @Bean fun initializeSentry( @Value("\${sentry.project.dsn}") dsn: String, @Value("\${sentry.project.environment}") environment: String, @Value("\${service.name:unnamed-service}") serviceName: String ): HandlerExceptionResolver { // Sentry.init(dsn) // Sentry.getStoredClient().environment = environment // Sentry.getStoredClient().addTag("service", serviceName) Sentry.init { options: SentryOptions -> options.environment = environment options.setTag("service", serviceName) options.dsn = dsn } val hub: IHub = Sentry.getCurrentHub() val transactionNameProvider = TransactionNameProvider { request: HttpServletRequest -> // Example: Use the request URI as the transaction name. request.requestURI } val order = Ordered.HIGHEST_PRECEDENCE // High precedence. return SentryExceptionResolver(hub, transactionNameProvider, order) } }
0
Kotlin
0
0
49b517c2197a6fa79a8532225ce294b213f2356a
1,770
kotlin-playground
MIT License
mazes-for-programmers/kotlin/src/main/kotlin/io/github/ocirne/mazes/algorithms/GrowingTree.kt
ocirne
496,354,199
false
{"Kotlin": 127854, "Python": 88203}
package io.github.ocirne.mazes.algorithms import io.github.ocirne.mazes.grids.Cell import io.github.ocirne.mazes.grids.GridProvider import io.github.ocirne.mazes.grids.Maze class GrowingTree(private val f : (List<Cell>) -> Cell): PassageCarver { override fun on(gridProvider: GridProvider, startAt: (Maze) -> Cell): Maze { val grid = gridProvider.forPassageCarver() val active = mutableListOf(startAt.invoke(grid)) while (active.isNotEmpty()) { val cell: Cell = f.invoke(active) val availableNeighbors = cell.neighbors().filter { it.links().isEmpty() } if (availableNeighbors.isNotEmpty()) { val neighbor = availableNeighbors.random() cell.link(neighbor) active.add(neighbor) } else { active.remove(cell) } } return grid } }
0
Kotlin
0
0
dbd59fe45bbad949937ccef29910a0b6d075cbb3
901
mazes
The Unlicense
app/src/main/java/com/rubyh/mlbcodechallenge/BeersApplication.kt
RHjelte
457,583,801
false
{"Kotlin": 23105}
package com.rubyh.mlbcodechallenge import android.app.Application import android.content.Context import com.rubyh.mlbcodechallenge.di.appModule import com.rubyh.mlbcodechallenge.di.networkModule import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin class BeersApplication : Application() { init { instance = this } override fun onCreate() { super.onCreate() startKoin { androidContext(this@BeersApplication) modules( appModule, networkModule ) } } companion object { private var instance : BeersApplication? = null fun requireContext() : Context { return instance!!.applicationContext } } }
0
Kotlin
0
0
581eb0cf859eb5477d830ff40e924fdce1267f67
791
mlb-code-challenge
MIT License
DaggerSingleModuleApp/app/src/main/java/com/github/yamamotoj/daggersinglemoduleapp/package04/Foo00400.kt
yamamotoj
163,851,411
false
{"Text": 1, "Ignore List": 30, "Markdown": 1, "Gradle": 34, "Java Properties": 11, "Shell": 6, "Batchfile": 6, "Proguard": 22, "Kotlin": 36021, "XML": 93, "INI": 1, "Java": 32, "Python": 2}
package com.github.yamamotoj.daggersinglemoduleapp.package04 import javax.inject.Inject import com.github.yamamotoj.daggersinglemoduleapp.package03.Foo00399 class Foo00400 @Inject constructor(){ fun method0() { Foo00399().method5() } fun method1() { method0() } fun method2() { method1() } fun method3() { method2() } fun method4() { method3() } fun method5() { method4() } }
0
Kotlin
0
9
2a771697dfebca9201f6df5ef8441578b5102641
400
android_multi_module_experiment
Apache License 2.0
feature/sponsors/src/commonMain/kotlin/io/github/droidkaigi/confsched/sponsors/SponsorsScreen.kt
DroidKaigi
776,354,672
false
{"Kotlin": 1017316, "Swift": 198427, "Shell": 2954, "Makefile": 1314, "Ruby": 386}
package io.github.droidkaigi.confsched.sponsors import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Surface import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.lifecycle.compose.dropUnlessResumed import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import conference_app_2024.feature.sponsors.generated.resources.content_description_back import conference_app_2024.feature.sponsors.generated.resources.sponsor import io.github.droidkaigi.confsched.compose.rememberEventFlow import io.github.droidkaigi.confsched.designsystem.theme.KaigiTheme import io.github.droidkaigi.confsched.droidkaigiui.SnackbarMessageEffect import io.github.droidkaigi.confsched.droidkaigiui.UserMessageStateHolder import io.github.droidkaigi.confsched.droidkaigiui.UserMessageStateHolderImpl import io.github.droidkaigi.confsched.droidkaigiui.component.AnimatedLargeTopAppBar import io.github.droidkaigi.confsched.model.Plan.GOLD import io.github.droidkaigi.confsched.model.Plan.PLATINUM import io.github.droidkaigi.confsched.model.Plan.SUPPORTER import io.github.droidkaigi.confsched.model.Sponsor import io.github.droidkaigi.confsched.model.fakes import io.github.droidkaigi.confsched.sponsors.section.SponsorsList import kotlinx.collections.immutable.PersistentList import kotlinx.collections.immutable.toPersistentList import org.jetbrains.compose.resources.stringResource import org.jetbrains.compose.ui.tooling.preview.Preview const val sponsorsScreenRoute = "sponsors" fun NavGraphBuilder.sponsorsScreens( onNavigationIconClick: () -> Unit, onSponsorsItemClick: (url: String) -> Unit, ) { composable(sponsorsScreenRoute) { SponsorsScreen( onNavigationIconClick = dropUnlessResumed(block = onNavigationIconClick), onSponsorsItemClick = onSponsorsItemClick, ) } } data class SponsorsScreenUiState( val sponsorsListUiState: SponsorsListUiState, val userMessageStateHolder: UserMessageStateHolder, ) data class SponsorsListUiState( val platinumSponsors: PersistentList<Sponsor>, val goldSponsors: PersistentList<Sponsor>, val supporters: PersistentList<Sponsor>, ) @Composable fun SponsorsScreen( onNavigationIconClick: () -> Unit, onSponsorsItemClick: (url: String) -> Unit, modifier: Modifier = Modifier, isTopAppBarHidden: Boolean = false, ) { val eventFlow = rememberEventFlow<SponsorsScreenEvent>() val uiState = sponsorsScreenPresenter(events = eventFlow) val snackbarHostState = remember { SnackbarHostState() } SnackbarMessageEffect( snackbarHostState = snackbarHostState, userMessageStateHolder = uiState.userMessageStateHolder, ) SponsorsScreen( uiState = uiState, snackbarHostState = snackbarHostState, onBackClick = onNavigationIconClick, onSponsorsItemClick = onSponsorsItemClick, modifier = modifier, isTopAppBarHidden = isTopAppBarHidden, ) } @OptIn(ExperimentalMaterial3Api::class) @Composable fun SponsorsScreen( uiState: SponsorsScreenUiState, snackbarHostState: SnackbarHostState, onBackClick: () -> Unit, isTopAppBarHidden: Boolean, modifier: Modifier = Modifier, onSponsorsItemClick: (url: String) -> Unit, ) { val scrollBehavior = if (!isTopAppBarHidden) { TopAppBarDefaults.exitUntilCollapsedScrollBehavior() } else { null } Scaffold( modifier = modifier, snackbarHost = { SnackbarHost(hostState = snackbarHostState) }, topBar = { if (!isTopAppBarHidden) { AnimatedLargeTopAppBar( title = stringResource(SponsorsRes.string.sponsor), onBackClick = onBackClick, scrollBehavior = scrollBehavior, navIconContentDescription = stringResource(SponsorsRes.string.content_description_back), ) } }, ) { padding -> SponsorsList( modifier = Modifier .padding(top = padding.calculateTopPadding()) .fillMaxSize(), uiState = uiState.sponsorsListUiState, scrollBehavior = scrollBehavior, onSponsorsItemClick = onSponsorsItemClick, contentPadding = PaddingValues(bottom = padding.calculateBottomPadding()), ) } } @Composable @Preview fun SponsorsScreenPreview() { KaigiTheme { Surface { SponsorsScreen( uiState = SponsorsScreenUiState( sponsorsListUiState = SponsorsListUiState( platinumSponsors = Sponsor.fakes().filter { it.plan == PLATINUM }.toPersistentList(), goldSponsors = Sponsor.fakes().filter { it.plan == GOLD }.toPersistentList(), supporters = Sponsor.fakes().filter { it.plan == SUPPORTER }.toPersistentList(), ), userMessageStateHolder = UserMessageStateHolderImpl(), ), snackbarHostState = SnackbarHostState(), onSponsorsItemClick = {}, onBackClick = {}, isTopAppBarHidden = false, ) } } }
71
Kotlin
172
374
e2628330065f71abc1b58d742576dd6bf497da0f
5,738
conference-app-2024
Apache License 2.0
js/js.translator/testData/box/expression/for/rangeOptimization.kt
JakeWharton
99,388,807
false
null
// IGNORE_BACKEND: JS_IR // EXPECTED_REACHABLE_NODES: 1121 // CHECK_CONTAINS_NO_CALLS: testRangeTo // CHECK_CONTAINS_NO_CALLS: testRangeToFunction // CHECK_CONTAINS_NO_CALLS: testUntil // CHECK_CONTAINS_NO_CALLS: testDownTo // CHECK_CONTAINS_NO_CALLS: testStep // CHECK_CONTAINS_NO_CALLS: testEmptyRange // CHECK_CONTAINS_NO_CALLS: testRangeToParams except=from;to fun testRangeTo(): String { var result = "" for (x in 1..3) { result += x } return result } fun testRangeToFunction(): String { var result = "" for (x in 1.rangeTo(3)) { result += x } return result } fun testUntil(): String { var result = "" for (x in 1 until 4) { result += x } return result } fun testDownTo(): String { var result = "" for (x in 3 downTo 1) { result += x } return result } fun testStep(): String { var result = "" for (x in 1..5 step 2) { result += x } result += ";" for (x in 1 until 6 step 2) { result += x } result += ";" for (x in 6.downTo(1).step(2)) { result += x } return result } fun testEmptyRange(): String { var result = "" for (x in 3..1) { result += x } return result } fun testRangeToParams(from: () -> Int, to: () -> Int): String { var result = "" for (x in (from()..to())) { result += x } return result } fun box(): String { var r = testRangeTo() if (r != "123") return "fail: rangeTo: $r" r = testRangeToFunction() if (r != "123") return "fail: rangeToFunction: $r" r = testUntil() if (r != "123") return "fail: until: $r" r = testDownTo() if (r != "321") return "fail: downTo: $r" r = testStep() if (r != "135;135;642") return "fail: $r" r = testEmptyRange() if (r != "") return "fail: emptyRange: $r" r = testRangeToParams({ 1 }, { 3 }) if (r != "123") return "fail: rangeTo(1, 3): $r" var se = "" r = testRangeToParams({ se += "Q"; 1 }, { se += "W"; 3 }) if (r != "123") return "fail: rangeTo(1, 3) with side effects: $r" if (se != "QW") return "fail: rangeTo(1, 3): side effects: $se" se = "" r = testRangeToParams({ se += "Q"; 3 }, { se += "W"; 1 }) if (r != "") return "fail: rangeTo(1, 3) with side effects: $r" if (se != "QW") return "fail: rangeTo(1, 3): side effects: $se" return "OK" }
184
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
2,417
kotlin
Apache License 2.0
command-client/src/main/kotlin/momosetkn/liquibase/command/client/LiquibaseCommandClientConfig.kt
momosetkn
844,062,460
false
{"Kotlin": 507898, "Java": 178}
package momosetkn.liquibase.command.client import java.time.format.DateTimeFormatter object LiquibaseCommandClientConfig { var dateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME }
6
Kotlin
1
5
a409e47712bb755ddc21f9108211ea4e76e6c9c7
187
liquibase-kotlin
Apache License 2.0
src/main/kotlin/addict/AddictContainer.kt
Valefant
167,674,220
false
null
package addict import addict.exceptions.EqualBindingNotAllowedException import addict.exceptions.InterpolationException import java.util.* import kotlin.reflect.KClass /** * Basic IoC container with module capabilities. */ class AddictContainer { /** * Contains the parsed keys and values of the property source file. */ val properties = mutableMapOf<String, Any>() /** * Modules provide a separation for the bindings. */ private val modules = mutableMapOf<String, AddictModule>() /** * The current active module. */ private var activeModule: AddictModule = modules.getOrPut(DEFAULT_MODULE) { AddictModule(properties) } /** * Reads a properties file from the resource folder and makes them available to the container instance. * The default file to look for is "application.properties". * @param name The name of the property source */ fun readPropertySource(name: String = "application.properties") { // kotlin let is used because we need the context of `this` for the classloader val unresolvedProperties = Properties().let { it.load(this::class.java.classLoader.getResourceAsStream(name)) // can be safely casted as the initial keys and values are available as strings it.toMap() as Map<String, String> } unresolvedProperties .mapValues { property -> property .value .split(" ") .map { word-> // matches following expressions ${example}, ${example.name} ... val regex = """\$\{(\w+(?:\.\w+)*)}""".toRegex() regex.find(word)?.let { val variable = it.destructured.component1() unresolvedProperties[variable] ?: InterpolationException("$variable does not exist in $name") } ?: word }.joinToString(" ") }.also { properties.putAll(it) } } /** * Changes the module of the current container instance. * If the modules does not exists it will be created. * @param name The name of the module to change or create */ fun changeModule(name: String) { activeModule = modules.getOrPut(name) { AddictModule(properties) } } /** * Binds an interface to a class so it can be injected as dependency when assembling an object. * Use a different module if you want to wire different implementations * Note: Using the same binding with another implementation will overwrite it. * @param kInterface The interface to bind for the [activeModule] * @param kClass The class which implements the interface * @param properties The properties to inject into [kClass] * @param scope Scoping of the binding */ fun <I : Any, C> bind( kInterface: KClass<I>, kClass: KClass<C>, properties: Map<String, Any> = emptyMap(), scope: Scope = Scope.SINGLETON ) where C : I { if (kInterface == kClass) { throw EqualBindingNotAllowedException("You cannot bind to the same instance of ${kInterface.qualifiedName}") } activeModule.bind(kInterface, kClass, properties, scope) } /** * Assembles an object with all its dependencies. * The type is provided within the angle brackets. * @return The type T which is specified */ inline fun <reified T : Any> assemble(): T { return assemble(T::class) } /** * Assembles an object with all its dependencies. * @param kClass The class provides the type to assemble. * @return The type T which is specified */ fun <T : Any> assemble(kClass: KClass<T>): T { return activeModule.assemble(kClass) } /** * CONSTANTS */ companion object { const val DEFAULT_MODULE = "default" } }
0
Kotlin
0
1
514d0b649d47d7b5bd68d254e65da07afe679b79
3,894
Addict
MIT License
src/main/kotlin/kr/entree/spigradle/module/bungee/BungeeExtension.kt
spigradle
227,876,875
false
null
/* * Copyright (c) 2023 Spigradle contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.entree.spigradle.bungee import groovy.lang.Closure import kr.entree.spigradle.StandardDescription import kr.entree.spigradle.Transient import kr.entree.spigradle.debugDir import org.gradle.api.Project import org.gradle.kotlin.dsl.newInstance import org.gradle.util.ConfigureUtil import java.io.File /** * Bungeecord configuration for the 'plugin.yml' description, and debug settings. * * Groovy Example: * ```groovy * spigot { * author 'Me' * depends 'ProtocolLib', 'Vault' * debug { * agentPort 5005 * } * } * ``` * * Kotlin Example: * ```kotlin * import kr.entree.spigradle.data.Load * * spigot { * author = "Me" * depends = listOf("ProtocolLib", "Vault") * debug { * agentPort = 5005 * } * } * ``` * * See: [https://www.spigotmc.org/wiki/create-your-first-bungeecord-plugin-proxy-spigotmc/#making-it-load] */ open class BungeeExtension(project: Project) : StandardDescription { override var main: String? = null override var name: String? = null override var version: String? = null override var description: String? = null var author: String? = null var depends: List<String> = emptyList() var softDepends: List<String> = emptyList() @Transient val debug: BungeeDebug = project.objects.newInstance(File(project.debugDir, "bungee/bungee.jar")) fun debug(configure: Closure<*>) { ConfigureUtil.configure(configure, debug) } fun debug(configure: BungeeDebug.() -> Unit) = configure(debug) fun depends(vararg depends: String) { this.depends = depends.toList() } fun softDepends(vararg softDepends: String) { this.softDepends = softDepends.toList() } }
16
null
7
95
b9473e5b22eddab10c39e4689a465ecac44b5154
2,321
spigradle
Apache License 2.0
compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/MemoizedInlineClassReplacements.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.backend.jvm.lower.inlineclasses import org.jetbrains.kotlin.backend.common.ir.copyTo import org.jetbrains.kotlin.backend.common.ir.copyTypeParameters import org.jetbrains.kotlin.backend.common.ir.copyTypeParametersFrom import org.jetbrains.kotlin.backend.common.ir.createDispatchReceiverParameter import org.jetbrains.kotlin.backend.jvm.JvmLoweredDeclarationOrigin import org.jetbrains.kotlin.backend.jvm.ir.isStaticInlineClassReplacement import org.jetbrains.kotlin.backend.jvm.lower.inlineclasses.InlineClassAbi.mangledNameFor import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.ir.builders.declarations.addValueParameter import org.jetbrains.kotlin.ir.builders.declarations.buildFun import org.jetbrains.kotlin.ir.builders.declarations.buildProperty import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.ir.descriptors.IrBuiltIns import org.jetbrains.kotlin.ir.symbols.IrPropertySymbol import org.jetbrains.kotlin.ir.types.impl.IrSimpleTypeImpl import org.jetbrains.kotlin.ir.types.impl.IrStarProjectionImpl import org.jetbrains.kotlin.ir.util.* import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.resolve.InlineClassDescriptorResolver import org.jetbrains.kotlin.storage.LockBasedStorageManager import org.jetbrains.kotlin.utils.addToStdlib.safeAs /** * Keeps track of replacement functions and inline class box/unbox functions. */ class MemoizedInlineClassReplacements(private val mangleReturnTypes: Boolean, private val irFactory: IrFactory) { private val storageManager = LockBasedStorageManager("inline-class-replacements") private val propertyMap = mutableMapOf<IrPropertySymbol, IrProperty>() /** * Get a replacement for a function or a constructor. */ val getReplacementFunction: (IrFunction) -> IrSimpleFunction? = storageManager.createMemoizedFunctionWithNullableValues { when { // Don't mangle anonymous or synthetic functions it.origin == IrDeclarationOrigin.LOCAL_FUNCTION_FOR_LAMBDA || (it.origin == IrDeclarationOrigin.DELEGATED_PROPERTY_ACCESSOR && it.visibility == Visibilities.LOCAL) || it.isStaticInlineClassReplacement || it.origin.isSynthetic -> null it.isInlineClassFieldGetter -> if (it.hasMangledReturnType) createMethodReplacement(it) else null // Mangle all functions in the body of an inline class it.parent.safeAs<IrClass>()?.isInline == true -> createStaticReplacement(it) // Otherwise, mangle functions with mangled parameters, ignoring constructors it is IrSimpleFunction && (it.hasMangledParameters || mangleReturnTypes && it.hasMangledReturnType) -> if (it.dispatchReceiverParameter != null) createMethodReplacement(it) else createStaticReplacement(it) else -> null } } /** * Get the box function for an inline class. Concretely, this is a synthetic * static function named "box-impl" which takes an unboxed value and returns * a boxed value. */ val getBoxFunction: (IrClass) -> IrSimpleFunction = storageManager.createMemoizedFunction { irClass -> require(irClass.isInline) irFactory.buildFun { name = Name.identifier(KotlinTypeMapper.BOX_JVM_METHOD_NAME) origin = JvmLoweredDeclarationOrigin.SYNTHETIC_INLINE_CLASS_MEMBER returnType = irClass.defaultType }.apply { parent = irClass copyTypeParametersFrom(irClass) addValueParameter { name = InlineClassDescriptorResolver.BOXING_VALUE_PARAMETER_NAME type = InlineClassAbi.getUnderlyingType(irClass) } } } /** * Get the unbox function for an inline class. Concretely, this is a synthetic * member function named "unbox-impl" which returns an unboxed result. */ val getUnboxFunction: (IrClass) -> IrSimpleFunction = storageManager.createMemoizedFunction { irClass -> require(irClass.isInline) irFactory.buildFun { name = Name.identifier(KotlinTypeMapper.UNBOX_JVM_METHOD_NAME) origin = JvmLoweredDeclarationOrigin.SYNTHETIC_INLINE_CLASS_MEMBER returnType = InlineClassAbi.getUnderlyingType(irClass) }.apply { parent = irClass createDispatchReceiverParameter() } } private val specializedEqualsCache = storageManager.createCacheWithNotNullValues<IrClass, IrSimpleFunction>() fun getSpecializedEqualsMethod(irClass: IrClass, irBuiltIns: IrBuiltIns): IrSimpleFunction { require(irClass.isInline) return specializedEqualsCache.computeIfAbsent(irClass) { irFactory.buildFun { name = InlineClassDescriptorResolver.SPECIALIZED_EQUALS_NAME // TODO: Revisit this once we allow user defined equals methods in inline classes. origin = JvmLoweredDeclarationOrigin.INLINE_CLASS_GENERATED_IMPL_METHOD returnType = irBuiltIns.booleanType }.apply { parent = irClass // We ignore type arguments here, since there is no good way to go from type arguments to types in the IR anyway. val typeArgument = IrSimpleTypeImpl(null, irClass.symbol, false, List(irClass.typeParameters.size) { IrStarProjectionImpl }, listOf()) addValueParameter { name = InlineClassDescriptorResolver.SPECIALIZED_EQUALS_FIRST_PARAMETER_NAME type = typeArgument } addValueParameter { name = InlineClassDescriptorResolver.SPECIALIZED_EQUALS_SECOND_PARAMETER_NAME type = typeArgument } } } } private fun createMethodReplacement(function: IrFunction): IrSimpleFunction = buildReplacement(function, function.origin) { require(function.dispatchReceiverParameter != null && function is IrSimpleFunction) val newValueParameters = ArrayList<IrValueParameter>() for ((index, parameter) in function.explicitParameters.withIndex()) { val name = if (parameter == function.extensionReceiverParameter) Name.identifier("\$receiver") else parameter.name val newParameter: IrValueParameter if (parameter == function.dispatchReceiverParameter) { newParameter = parameter.copyTo(this, index = -1, name = name, defaultValue = null) dispatchReceiverParameter = newParameter } else { newParameter = parameter.copyTo(this, index = index - 1, name = name, defaultValue = null) newValueParameters += newParameter } // Assuming that constructors and non-override functions are always replaced with the unboxed // equivalent, deep-copying the value here is unnecessary. See `JvmInlineClassLowering`. newParameter.defaultValue = parameter.defaultValue?.patchDeclarationParents(this) } valueParameters = newValueParameters } private fun createStaticReplacement(function: IrFunction): IrSimpleFunction = buildReplacement(function, JvmLoweredDeclarationOrigin.STATIC_INLINE_CLASS_REPLACEMENT, noFakeOverride = true) { val newValueParameters = ArrayList<IrValueParameter>() for ((index, parameter) in function.explicitParameters.withIndex()) { newValueParameters += when (parameter) { // FAKE_OVERRIDEs have broken dispatch receivers function.dispatchReceiverParameter -> function.parentAsClass.thisReceiver!!.copyTo( this, index = index, name = Name.identifier("arg$index"), type = function.parentAsClass.defaultType, origin = IrDeclarationOrigin.MOVED_DISPATCH_RECEIVER ) function.extensionReceiverParameter -> parameter.copyTo( this, index = index, name = Name.identifier("\$this\$${function.name}"), origin = IrDeclarationOrigin.MOVED_EXTENSION_RECEIVER ) else -> parameter.copyTo(this, index = index, defaultValue = null).also { // See comment next to a similar line above. it.defaultValue = parameter.defaultValue?.patchDeclarationParents(this) } } } valueParameters = newValueParameters } private fun buildReplacement( function: IrFunction, replacementOrigin: IrDeclarationOrigin, noFakeOverride: Boolean = false, body: IrFunction.() -> Unit ): IrSimpleFunction = irFactory.buildFun { updateFrom(function) if (function is IrConstructor) { // The [updateFrom] call will set the modality to FINAL for constructors, while the JVM backend would use OPEN here. modality = Modality.OPEN } origin = when { function.origin == IrDeclarationOrigin.GENERATED_INLINE_CLASS_MEMBER -> JvmLoweredDeclarationOrigin.INLINE_CLASS_GENERATED_IMPL_METHOD function is IrConstructor && function.constructedClass.isInline -> JvmLoweredDeclarationOrigin.STATIC_INLINE_CLASS_CONSTRUCTOR else -> replacementOrigin } if (noFakeOverride) { isFakeOverride = false } name = mangledNameFor(function, mangleReturnTypes) returnType = function.returnType }.apply { parent = function.parent annotations += function.annotations copyTypeParameters(function.allTypeParameters) if (function.metadata != null) { metadata = function.metadata function.metadata = null } copyAttributes(function as? IrAttributeContainer) if (function is IrSimpleFunction) { val propertySymbol = function.correspondingPropertySymbol if (propertySymbol != null) { val property = propertyMap.getOrPut(propertySymbol) { irFactory.buildProperty() { name = propertySymbol.owner.name updateFrom(propertySymbol.owner) }.apply { parent = propertySymbol.owner.parent copyAttributes(propertySymbol.owner) } } correspondingPropertySymbol = property.symbol when (function) { propertySymbol.owner.getter -> property.getter = this propertySymbol.owner.setter -> property.setter = this else -> error("Orphaned property getter/setter: ${function.render()}") } } overriddenSymbols = function.overriddenSymbols.map { getReplacementFunction(it.owner)?.symbol ?: it } } body() } }
4
null
5209
42,102
65f712ab2d54e34c5b02ffa3ca8c659740277133
12,002
kotlin
Apache License 2.0
app/src/main/java/com/dunchi/android_view/general/ConstraintLayoutActivity.kt
dunchi-develop-blog
318,939,411
false
null
package com.dunchi.android_view.general import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.dunchi.android_view.R class ConstraintLayoutActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_constraint_layout) } }
0
Kotlin
0
0
062c136707b0275919d5efbee5697f4e36266459
372
android-view
MIT License
door-runtime/src/commonMain/kotlin/com/ustadmobile/door/paging/HttpResponsePagingExt.kt
UstadMobile
344,538,858
false
{"Kotlin": 1028056, "JavaScript": 1100, "HTML": 430, "Shell": 89}
package com.ustadmobile.door.paging import com.ustadmobile.door.DoorConstants import io.ktor.client.statement.* /** * Where the receiver HttpResponse is the response for a PagingSource which uses PULL_REPLICATE_ENTITIES, gets * endOfPaginationReached from the response using the header. */ fun HttpResponse.endOfPaginationReached(): Boolean { return headers[DoorConstants.HEADER_PAGING_END_REACHED]?.toBoolean() ?: true }
5
Kotlin
1
162
9912ce18848c6f3d4c5e78e06aeb78542e2670a5
431
door
Apache License 2.0
app/src/main/java/com/mobilebreakero/Gamezone/ui/components/GameZoneTopAppBar.kt
OmarLkhalil
672,856,200
false
null
package com.mobilebreakero.Gamezone.ui.composables import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.* import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.* import androidx.navigation.NavController import androidx.navigation.compose.currentBackStackEntryAsState @OptIn(ExperimentalMaterial3Api::class) @Composable fun GameZoneTopAppBar(navController: NavController) { TopAppBar( colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = Color(0xFF778FD2)), title = { TopBarTitle(navController = navController) }, navigationIcon = { NavIcon(navController = navController) }, ) } @Composable fun NavIcon(navController: NavController) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route if (currentRoute != "Home") { IconButton(onClick = { navController.popBackStack() }) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = "back", tint = Color.White ) } } } @Composable fun TopBarTitle(navController: NavController) { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.destination?.route if (currentRoute == "Details?name={name}&description={description}&image={image}&rating={rating}&link={link}") { Text( text = "Details", textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth(), maxLines = 1, color = Color.Black, fontSize = 25.sp, overflow = TextOverflow.Ellipsis ) } else { Text( text = currentRoute.toString(), textAlign = TextAlign.Center, modifier = Modifier .fillMaxWidth(), maxLines = 1, color = Color.Black, fontSize = 25.sp, overflow = TextOverflow.Ellipsis ) } }
10
null
0
2
03f92d6f786e9f5d7fa5bd61cf171dfbbe8325c2
2,429
GameZone
MIT License
compiler/testData/diagnostics/jvmIntegration/classpath/sameLibraryTwiceInClasspath.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// FIR_IDENTICAL // MODULE: library1 // FILE: source.kt package testing object TopLevelObject class Outer { inner class Inner class Nested } // MODULE: library2 // FILE: source.kt package testing object TopLevelObject class Outer { inner class Inner class Nested } // MODULE: main(library1, library2) // FILE: source.kt package test import testing.* val testObjectProperty = TopLevelObject val outer = Outer() val inn3r = Outer().Inner() val nested = Outer.Nested()
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
491
kotlin
Apache License 2.0
app/src/main/java/io/github/takusan23/Kaisendon/Home.kt
takusan23
161,504,060
false
{"Gradle": 5, "Markdown": 2, "Java Properties": 4, "Shell": 1, "Text": 13, "Ignore List": 3, "Batchfile": 1, "Proguard": 1, "Java": 51, "XML": 337, "Kotlin": 86, "AIDL": 4, "JSON": 6}
package io.github.takusan23.Kaisendon import android.Manifest import android.animation.ObjectAnimator import androidx.appcompat.app.AlertDialog import android.annotation.SuppressLint import android.app.* import android.content.* import android.content.pm.PackageManager import android.content.res.ColorStateList import android.content.res.Configuration import android.database.Cursor import android.database.CursorIndexOutOfBoundsException import android.database.sqlite.SQLiteDatabase import android.graphics.* import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.net.Uri import android.os.BatteryManager import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.speech.tts.TextToSpeech import android.text.Editable import android.text.Html import android.text.TextWatcher import android.util.TypedValue import android.view.* import android.view.inputmethod.InputMethodManager import android.widget.* import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.view.menu.MenuBuilder import androidx.appcompat.view.menu.MenuPopupHelper import androidx.appcompat.widget.Toolbar import androidx.browser.customtabs.CustomTabsIntent import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.Fragment import androidx.preference.PreferenceManager.getDefaultSharedPreferences import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.google.android.material.appbar.AppBarLayout import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.navigation.NavigationView import com.google.android.material.snackbar.Snackbar import com.google.android.material.textfield.TextInputLayout import com.squareup.picasso.Picasso import io.github.takusan23.Kaisendon.APIJSONParse.GlideSupport import io.github.takusan23.Kaisendon.Activity.LoginActivity import io.github.takusan23.Kaisendon.CustomMenu.* import io.github.takusan23.Kaisendon.CustomMenu.Dialog.MenuBottomSheetFragment import io.github.takusan23.Kaisendon.CustomMenu.Dialog.MisskeyDriveBottomDialog import io.github.takusan23.Kaisendon.CustomMenu.Dialog.TLQuickSettingSnackber import io.github.takusan23.Kaisendon.Theme.DarkModeSupport import io.github.takusan23.Kaisendon.DesktopTL.DesktopFragment import io.github.takusan23.Kaisendon.Fragment.HelloFragment import io.github.takusan23.Kaisendon.Omake.LunchBonus import io.github.takusan23.Kaisendon.Omake.ShinchokuLayout import io.github.takusan23.Kaisendon.PaintPOST.PaintPOSTActivity import kotlinx.android.synthetic.main.app_bar_home2.* import kotlinx.android.synthetic.main.bottom_bar_layout.* import kotlinx.android.synthetic.main.content_account_info_update.* import kotlinx.android.synthetic.main.list_item.view.* import okhttp3.* import org.chromium.customtabsclient.shared.CustomTabsHelper import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.io.File import java.io.IOException import java.util.* class Home : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener { internal var toot_text: String? = null internal var user: String? = null private var helper: CustomMenuSQLiteHelper? = null private var db: SQLiteDatabase? = null internal var display_name: String? = null internal var user_id: String? = null internal var user_avater: String? = null internal var user_header: String? = null internal var toot_count = "0" internal lateinit var account_id: String private val dialog: ProgressDialog? = null internal var alertDialog: AlertDialog? = null private val snackbar: Snackbar? = null internal var nicoru = false internal var test = 0 internal var textToSpeech: TextToSpeech? = null internal var networkChangeBroadcast: BroadcastReceiver? = null /* @Override protected void onResume() { super.onResume(); //設定のプリファレンス SharedPreferences pref_setting = PreferenceManager.getDefaultSharedPreferences(Preference_ApplicationContext.getContext()); pref_setting.registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); //設定のプリファレンス SharedPreferences pref_setting = PreferenceManager.getDefaultSharedPreferences(Preference_ApplicationContext.getContext()); pref_setting.unregisterOnSharedPreferenceChangeListener(this); } */ //TextViewがどうしても欲しかった //TextViewを押す→ListViewの一番上に移動←これがしたかった /* https://stackoverflow.com/questions/31428086/access-toolbar-textview-from-fragment-in-android */ lateinit var toolBer: Toolbar internal set internal lateinit var navigationView: NavigationView internal lateinit var drawer: DrawerLayout lateinit var toot_snackbar: Snackbar internal set internal var newNote_Snackbar: Snackbar? = null internal lateinit var pref_setting: SharedPreferences internal lateinit var fab: FloatingActionButton internal lateinit var media_LinearLayout: LinearLayout internal lateinit var post_button: Button internal lateinit var toot_area_Button: ImageButton internal lateinit var toot_EditText: EditText //公開範囲 internal var toot_area = "public" //名前とか internal lateinit var snackber_DisplayName: String internal var snackber_Name = "" internal var Instance: String? = null internal var AccessToken: String? = null internal lateinit var snackber_Avatar: String internal lateinit var snackber_Avatar_notGif: String internal lateinit var snackberAccountAvaterImageView: ImageView internal lateinit var snackberAccount_TextView: TextView internal lateinit var account_menuBuilder: MenuBuilder internal lateinit var account_optionsMenu: MenuPopupHelper internal lateinit var misskey_account_menuBuilder: MenuBuilder internal lateinit var misskey_account_optionMenu: MenuPopupHelper internal lateinit var account_LinearLayout: LinearLayout internal var misskey_account_LinearLayout: LinearLayout? = null internal lateinit var misskey_drive_Button: ImageButton //時間指定投稿 internal lateinit var mastodon_time_post_Button: ImageButton internal var post_date: String? = null internal var post_time: String? = null internal var time_post_Switch: Switch? = null internal var isTimePost = false internal var isMastodon_time_post: Boolean = false //投票 internal lateinit var mastodon_vote_Button: ImageButton internal lateinit var paintPOSTButton: ImageButton internal lateinit var toot_Button_LinearLayout: LinearLayout internal var isMastodon_vote = false internal var isMastodon_vote_layout = false internal lateinit var vote_1: EditText internal lateinit var vote_2: EditText internal lateinit var vote_3: EditText internal lateinit var vote_4: EditText internal lateinit var vote_time: EditText internal lateinit var vote_use_Switch: Switch internal lateinit var vote_multi_Switch: Switch internal lateinit var vote_hide_Switch: Switch //マルチアカウント読み込み用 internal var multi_account_instance: ArrayList<String>? = null internal lateinit var multi_account_access_token: ArrayList<String> internal var misskey_multi_account_instance: ArrayList<String>? = null internal lateinit var misskey_multi_account_access_token: ArrayList<String> //文字数カウント internal var tootTextCount = 0 //カスタム絵文字表示に使う配列 private var emojis_show = false //最後に開いたカスタムメニューを保管() private val lastMenuName = "" //DesktomMode用Mastodon Misskey分岐 private val isDesktoopMisskeyMode = false private val misskey_switch: Switch? = null private var isDesktop = false /*クイック設定を返すやつ*/ var tlQuickSettingSnackber: TLQuickSettingSnackber? = null private set var customMenuLoadSupport: CustomMenuLoadSupport? = null //裏機能? internal lateinit var shinchokuLayout: ShinchokuLayout //画像POST internal var count = 0 internal var media_list = ArrayList<String>() internal var media_uri_list: ArrayList<Uri>? = ArrayList() //アカウント情報一回一回取ってくるの通信量的にどうなのってことで var tootSnackbarCustomMenuName = "" // lateinit var popupView: View //新しいトゥート画面 lateinit var tootCardView: TootCardView //共有Intent、投稿したら次回から表示されないように var shareText = "" //カスタムメニューを切り替えるとintentの内容のせいでもう一度作成される問題 var tmpOkekakiList = arrayListOf<String>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //設定のプリファレンス pref_setting = getDefaultSharedPreferences(this@Home) popupView = layoutInflater.inflate(R.layout.overlay_player_layout, null) //Wi-Fi接続状況確認 val connectivityManager = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) //通信量節約 val setting_avater_hidden = pref_setting.getBoolean("pref_drawer_avater", false) //Wi-Fi接続時は有効? val setting_avater_wifi = pref_setting.getBoolean("pref_avater_wifi", true) //GIFを再生するか? val setting_avater_gif = pref_setting.getBoolean("pref_avater_gif", false) //ダークモード処理 val conf = resources.configuration var currecntNightMode = conf.uiMode and Configuration.UI_MODE_NIGHT_MASK val darkModeSupport = DarkModeSupport(this) currecntNightMode = darkModeSupport.setIsDarkModeSelf(currecntNightMode) when (currecntNightMode) { Configuration.UI_MODE_NIGHT_NO -> setTheme(R.style.AppTheme_NoActionBar) Configuration.UI_MODE_NIGHT_YES -> setTheme(R.style.OLED_Theme) } setContentView(R.layout.activity_home) navigationView = findViewById(R.id.nav_view) customMenuLoadSupport = CustomMenuLoadSupport(this, navigationView) //アプリ起動カウント LunchBonus(this) //進捗 shinchokuLayout = ShinchokuLayout(this) //ログイン情報があるか //アクセストークンがない場合はログイン画面へ飛ばす if (pref_setting.getString("main_token", "") == "" && pref_setting.getString("misskey_instance_list", "") == "") { val login = Intent(this, LoginActivity::class.java) //login.putExtra("first_applunch", true); startActivity(login) } //SQLite if (helper == null) { helper = CustomMenuSQLiteHelper(this) } if (db == null) { db = helper!!.writableDatabase db!!.disableWriteAheadLogging() } //起動時の FragmentChange(HelloFragment()) //最後に開いたメニューを開くようにする val lastName = pref_setting.getString("custom_menu_last", null) //メニュー入れ替え navigationView.menu.clear() navigationView.inflateMenu(R.menu.custom_menu) customMenuLoadSupport!!.loadCustomMenu(null) if (lastName != null) { try { customMenuLoadSupport!!.loadCustomMenu(lastName) } catch (e: CursorIndexOutOfBoundsException) { e.printStackTrace() } } //ViewPager /* if (pref_setting.getBoolean("pref_view_pager_mode", false)) { //動的にViewPager生成 val viewPager = ViewPager(this) viewPager.id = View.generateViewId() val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT) viewPager.layoutParams = layoutParams container_container.addView(viewPager, 0) //Adapter val fragmentPagerAdapter = FragmentPagerAdapter(supportFragmentManager, this) viewPager.adapter = fragmentPagerAdapter } */ //デスクトップモード時で再生成されないようにする val fragment = supportFragmentManager.findFragmentById(R.id.container_container) if (fragment != null && fragment is DesktopFragment) { val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.replace(R.id.container_container, DesktopFragment(), "desktop") fragmentTransaction.commit() isDesktop = true } else { isDesktop = false } //カスタム絵文字有効/無効 if (pref_setting.getBoolean("pref_custom_emoji", true)) { if (pref_setting.getBoolean("pref_avater_wifi", true)) { //WIFIのみ表示有効時 //ネットワーク未接続時はnullか出る if (networkCapabilities != null) { if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { //WIFI emojis_show = true } } } else { //WIFI/MOBILE DATA 関係なく表示 emojis_show = true } } //アクセストークン AccessToken = null //インスタンス Instance = null val accessToken_boomelan = pref_setting.getBoolean("pref_advanced_setting_instance_change", false) if (accessToken_boomelan) { AccessToken = pref_setting.getString("pref_mastodon_accesstoken", "") Instance = pref_setting.getString("pref_mastodon_instance", "") } else { AccessToken = pref_setting.getString("main_token", "") Instance = pref_setting.getString("main_instance", "") } //カスタムメニューの場合は追加処理 if (pref_setting.getBoolean("custom_menu", false)) { //メニュー入れ替え navigationView.menu.clear() navigationView.inflateMenu(R.menu.custom_menu) customMenuLoadSupport!!.loadCustomMenu(null) } //TootSnackBerのコードがクソ長いのでメゾット化 //Misskey //setNewNote_Snackber(); tootSnackBer() tootCardView = TootCardView(this, false) home_activity_frame_layout.addView(tootCardView.linearLayout) setAppBar() /* //共有を受け取る val intent = intent val action_string = intent.action if (Intent.ACTION_SEND == action_string) { val extras = intent.extras if (extras != null) { //URL var text = extras.getCharSequence(Intent.EXTRA_TEXT) //タイトル val title = extras.getCharSequence(Intent.EXTRA_SUBJECT) //画像URI val uri = extras.getParcelable<Uri>(Intent.EXTRA_STREAM) //EXTRA TEXTにタイトルが含まれているかもしれない? //含まれているときは消す println(text) if (text != null) { if (title != null) { text = text.toString().replace(title.toString(), "") tootCardView.linearLayout.toot_card_textinput.append(title) tootCardView.linearLayout.toot_card_textinput.append("\n") } tootCardView.linearLayout.toot_card_textinput.append(text) } //画像 if (uri != null) { tootCardView.attachMediaList.add(uri) tootCardView.setAttachImageLinearLayout() } //表示 tootCardView.cardViewShow() } } */ //App Shortcutから起動 if (getIntent().getBooleanExtra("toot", false)) { //表示 tootCardView.cardViewShow() } //お絵かき投稿から if (intent.getBooleanExtra("paint_data", false)) { //画像URI val uri = Uri.parse(intent.getStringExtra("paint_uri")) //画像配列に追加 tootCardView.attachMediaList.add(uri) //表示 tootCardView.cardViewShow() } /* fab.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { //従来のTootActivityへー Intent toot = new Intent(Home.this, TestDragListView.class); startActivity(toot); return false; } }); */ //val navigationView = findViewById<View>(R.id.nav_view) as NavigationView navigationView.setNavigationItemSelectedListener(this) val finalInstance = Instance val finalAccessToken = AccessToken //どろわーのイメージとか文字とか //LinearLayout linearLayout = (LinearLayout) findViewById(R.id.nav_header_home_linearlayout); val navHeaderView = navigationView.getHeaderView(0) val avater_imageView = navHeaderView.findViewById<ImageView>(R.id.icon_image) val header_imageView = navHeaderView.findViewById<ImageView>(R.id.drawer_header) //ImageView header_imageView = navHeaderView val user_account_textView = navHeaderView.findViewById<TextView>(R.id.drawer_account) val user_id_textView = navHeaderView.findViewById<TextView>(R.id.drawer_id) if (!CustomMenuTimeLine.isMisskeyMode) { val url = "https://$Instance/api/v1/accounts/verify_credentials/?access_token=$AccessToken" //作成 val request = Request.Builder() .url(url) .get() .build() //GETリクエスト val client = OkHttpClient() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { runOnUiThread { //Toast.makeText(getContext(), R.string.error, Toast.LENGTH_SHORT).show(); } } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { if (response.isSuccessful) { //成功時 val response_string = response.body()!!.string() try { val jsonObject = JSONObject(response_string) display_name = jsonObject.getString("display_name") user_id = jsonObject.getString("username") user_avater = jsonObject.getString("avatar") user_header = jsonObject.getString("header") account_id = jsonObject.getString("id") toot_count = jsonObject.getString("statuses_count") } catch (e: JSONException) { e.printStackTrace() } } else { //失敗時 runOnUiThread { Toast.makeText(this@Home, getString(R.string.error) + "\n" + response.code().toString(), Toast.LENGTH_SHORT).show() } } } }) } /* //ローカルタイムライントースト if (pref_setting.getInt("timeline_toast_check", 0) == 1) { String channel = "Kaisendon_1"; String channel_1 = "notification_TL"; //通知 NotificationManager notificationManager = (NotificationManager) Home.this.getSystemService(Context.NOTIFICATION_SERVICE); //Android Oからは通知の仕様が変わった if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel notificationChannel = new NotificationChannel(channel, "LocalTimeline Toot", NotificationManager.IMPORTANCE_DEFAULT); notificationChannel.setDescription(getString(R.string.notification_LocalTimeline_Toast)); notificationChannel.setName(getString(R.string.app_name)); notificationManager.createNotificationChannel(notificationChannel); NotificationCompat.Builder notification_nougat = new NotificationCompat.Builder(Home.this, channel) .setSmallIcon(R.drawable.ic_rate_review_white_24dp) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.notification_LocalTimeline_Toast)); Intent resultIntent = new Intent(Home.this, Home.class); TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(Home.this); taskStackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); notification_nougat.setContentIntent(resultPendingIntent); NotificationManager notificationManager_nougat = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager_nougat.notify(R.string.app_name, notification_nougat.build()); } else { //ブロードキャストを送信 //ブロードキャスト先を指定(明示的ブロードキャスト) //マニフェストにも記入しないと動かないので注意 Intent notification_Intent = new Intent(getApplicationContext(), BroadcastRecever_Notification_Button.class); //ボタンを追加する NotificationCompat.Action action = new NotificationCompat.Action( R.drawable.ic_rate_review_black_24dp, getString(R.string.timeline_toast_disable), PendingIntent.getBroadcast(this, 0, notification_Intent, PendingIntent.FLAG_UPDATE_CURRENT) ); NotificationCompat.Builder notification_nougat = new NotificationCompat.Builder(Home.this) .setSmallIcon(R.drawable.ic_rate_review_white_24dp) .setContentTitle(getString(R.string.app_name)) .setContentText(getString(R.string.notification_LocalTimeline_Toast) ); notification_nougat.addAction(action); Intent resultIntent = new Intent(Home.this, Home.class); TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(Home.this); taskStackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent( 0, PendingIntent.FLAG_UPDATE_CURRENT ); notification_nougat.setContentIntent(resultPendingIntent); NotificationManager notificationManager_nougat = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager_nougat.notify(R.string.app_name, notification_nougat.build()); } AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... string) { MastodonClient client = new MastodonClient.Builder(finalInstance, new OkHttpClient.Builder(), new Gson()) .accessToken(finalAccessToken) .useStreamingApi() .build(); Handler handler = new Handler() { @Override public void onStatus(@NotNull com.sys1yagi.mastodon4j.api.entity.Status status) { String user_name = status.getAccount().getDisplayName(); String toot_text = status.getContent(); String user_avater_url = status.getAccount().getAvatar(); long toot_id = status.getId(); Spanned spanned = Html.fromHtml(toot_text, Html.FROM_HTML_MODE_LEGACY); runOnUiThread(new Runnable() { @Override public void run() { //トースト表示 */ /* Toast toast = new Toast(getApplicationContext()); LayoutInflater inflater = getLayoutInflater(); View layout = inflater.inflate(R.layout.notification_toast_layout, null); LinearLayout toast_linearLayout = layout.findViewById(R.id.toast_layout_root); TextView toast_text = layout.findViewById(R.id.notification_text); toast_text.setText(Html.fromHtml(user_name + "\r\n" + toot_text, Html.FROM_HTML_MODE_COMPACT)); ImageView toast_imageview = layout.findViewById(R.id.notification_icon); //toast_imageview.setImageDrawable(finalDrawable); *//* //ブロードキャストを送信 //ブロードキャスト先を指定(明示的ブロードキャスト) //途中で変更がある可能性があるので再度確認 if (pref_setting.getInt("timeline_toast_check", 0) == 1) { NotificationChannel notificationChannel = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = new NotificationChannel(channel_1, "Notification TL", NotificationManager.IMPORTANCE_HIGH); notificationChannel.setDescription(getString(R.string.notification_timeline)); notificationChannel.setName(getString(R.string.notification_timeline)); notificationManager.createNotificationChannel(notificationChannel); //トゥートようブロードキャスト String Type = "Type"; Intent notification_localtimeline_toot = new Intent(getApplicationContext(), BroadcastReceiver_Notification_Timeline.class); notification_localtimeline_toot.putExtra(Type, "Toot"); PendingIntent notification_localtimeline_pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, notification_localtimeline_toot, PendingIntent.FLAG_UPDATE_CURRENT); //マニフェストにも記入しないと動かないので注意 Intent notififation_localtimeline_favouite = new Intent(getApplicationContext(), BroadcastReceiver_Notification_Timeline.class); notififation_localtimeline_favouite.putExtra(Type, "Favourite"); notififation_localtimeline_favouite.putExtra("ID", toot_id); long[] pattern = {100}; //通知 NotificationCompat.Builder notification_localtimeline = new NotificationCompat.Builder(Home.this, channel_1) .setSmallIcon(R.drawable.ic_rate_review_white_24dp) .setContentTitle(user_name) .setContentText(spanned) .setPriority(2) .setVibrate(pattern); //お気に入りボタン NotificationCompat.Action notification_favourite_action = new NotificationCompat.Action( R.drawable.ic_star_black_24dp, getString(R.string.favoutire), PendingIntent.getBroadcast(Home.this, 0, notififation_localtimeline_favouite, PendingIntent.FLAG_UPDATE_CURRENT) ); //トゥート RemoteInput remoteInput = new RemoteInput.Builder("Toot_Text") .setLabel("今なにしてる?") .build(); NotificationCompat.Action notification_toot_action = new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_send , "今なにしてる?", notification_localtimeline_pendingIntent) .addRemoteInput(remoteInput) .build(); notification_localtimeline.addAction(notification_toot_action); notification_localtimeline.addAction(notification_favourite_action); NotificationManager notificationManager_nougat = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager_nougat.notify(R.string.notification_LocalTimeline_Notification, notification_localtimeline.build()); } else { //トゥートようブロードキャスト String Type = "Type"; Intent notification_localtimeline_toot = new Intent(getApplicationContext(), BroadcastReceiver_Notification_Timeline.class); notification_localtimeline_toot.putExtra(Type, "Toot"); PendingIntent notification_localtimeline_pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, notification_localtimeline_toot, PendingIntent.FLAG_UPDATE_CURRENT); //マニフェストにも記入しないと動かないので注意 Intent notififation_localtimeline_favouite = new Intent(getApplicationContext(), BroadcastReceiver_Notification_Timeline.class); notififation_localtimeline_favouite.putExtra(Type, "Favourite"); notififation_localtimeline_favouite.putExtra("ID", toot_id); long[] pattern = {100}; //通知 NotificationCompat.Builder notification_localtimeline = new NotificationCompat.Builder(Home.this) .setSmallIcon(R.drawable.ic_rate_review_white_24dp) .setContentTitle(user_name) .setContentText(spanned) .setPriority(1) .setVibrate(pattern); //お気に入りボタン NotificationCompat.Action notification_favourite_action = new NotificationCompat.Action( R.drawable.ic_star_black_24dp, getString(R.string.dialog_favorite), PendingIntent.getBroadcast(Home.this, 0, notififation_localtimeline_favouite, PendingIntent.FLAG_UPDATE_CURRENT) ); //トゥート RemoteInput remoteInput = new RemoteInput.Builder("Toot_Text") .setLabel("今なにしてる?") .build(); NotificationCompat.Action notification_toot_action = new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_send , "今なにしてる?", notification_localtimeline_pendingIntent) .addRemoteInput(remoteInput) .build(); notification_localtimeline.addAction(notification_toot_action); notification_localtimeline.addAction(notification_favourite_action); NotificationManager notificationManager_nougat = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager_nougat.notify(R.string.notification_LocalTimeline_Notification, notification_localtimeline.build()); } } } }); } @Override public void onNotification(@NotNull Notification notification) { } @Override public void onDelete(long l) { } }; Streaming streaming = new Streaming(client); try { if (pref_setting.getString("pref_notification_timeline", "Home").contains("Home")) { Shutdownable shutdownable = streaming.user(handler); } if (pref_setting.getString("pref_notification_timeline", "Home").contains("Local")) { Shutdownable shutdownable = streaming.localPublic(handler); } if (pref_setting.getString("pref_notification_timeline", "Home").contains("Federated")) { Shutdownable shutdownable = streaming.federatedPublic(handler); } } catch (Mastodon4jRequestException e) { e.printStackTrace(); } return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } //読み上げ TTS if (pref_setting.getBoolean("pref_speech", false)) { NotificationManager notificationManager = (NotificationManager) Home.this.getSystemService(Context.NOTIFICATION_SERVICE); NotificationChannel notificationChannel = null; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { notificationChannel = new NotificationChannel("Kaisendon_1", "LocalTimeline Toot", NotificationManager.IMPORTANCE_DEFAULT); notificationChannel.setDescription(getString(R.string.notification_timeline)); notificationChannel.setName(getString(R.string.notification_timeline)); notificationManager.createNotificationChannel(notificationChannel); NotificationCompat.Builder ttsNotification = new NotificationCompat.Builder(this, "Kaisendon_1") .setSmallIcon(R.drawable.ic_volume_up_black_24dp) .setContentTitle(getString(R.string.speech_timeline)) .setContentText(getString(R.string.notification_speech_timeline)); Intent tts_intent = new Intent(getApplicationContext(), BroadcastRecever_Notification_Button.class); tts_intent.putExtra("TTS", true); NotificationCompat.Action ttsAction = new NotificationCompat.Action( R.drawable.ic_volume_off_black_24dp, getString(R.string.timeline_toast_disable), PendingIntent.getBroadcast(getApplicationContext(), 0, tts_intent, PendingIntent.FLAG_UPDATE_CURRENT) ); ttsNotification.addAction(ttsAction); NotificationManager notificationManager_nougat = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager_nougat.notify(R.string.speech_timeline, ttsNotification.build()); } else { NotificationCompat.Builder ttsNotification = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_volume_up_black_24dp) .setContentTitle(getString(R.string.speech_timeline)) .setContentText(getString(R.string.notification_speech_timeline)); Intent tts_intent = new Intent(getApplicationContext(), BroadcastRecever_Notification_Button.class); tts_intent.putExtra("TTS", true); NotificationCompat.Action ttsAction = new NotificationCompat.Action( R.drawable.ic_volume_off_black_24dp, getString(R.string.timeline_toast_disable), PendingIntent.getBroadcast(getApplicationContext(), 0, tts_intent, PendingIntent.FLAG_UPDATE_CURRENT) ); ttsNotification.addAction(ttsAction); NotificationManager notificationManager_nougat = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager_nougat.notify(R.string.speech_timeline, ttsNotification.build()); } new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getBooleanExtra("TTS", false)) { SharedPreferences.Editor editor = pref_setting.edit(); editor.putBoolean("pref_speech", false); editor.apply(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(R.string.speech_timeline); } } }; textToSpeech = new TextToSpeech(Home.this, new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (TextToSpeech.SUCCESS == status) { //初期化 使えるよ! textToSpeech.setSpeechRate(Float.valueOf(pref_setting.getString("pref_speech_rate", "1.0f"))); Toast.makeText(Home.this, R.string.text_to_speech_preparation, Toast.LENGTH_SHORT).show(); } else { //使えないよ } } }); new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... string) { MastodonClient client = new MastodonClient.Builder(finalInstance, new OkHttpClient.Builder(), new Gson()) .accessToken(finalAccessToken) .useStreamingApi() .build(); Handler handler = new Handler() { @Override public void onStatus(@NotNull com.sys1yagi.mastodon4j.api.entity.Status status) { String toot = status.getContent(); String finaltoot = Html.fromHtml(toot, Html.FROM_HTML_MODE_COMPACT).toString(); // 正規表現 finaltoot = Html.fromHtml(finaltoot, Html.FROM_HTML_MODE_COMPACT).toString(); String final_toot_1 = finaltoot; //URL省略 if (pref_setting.getBoolean("pref_speech_url", true)) { final_toot_1 = finaltoot.replaceAll("(http://|https://){1}[\\w\\.\\-/:\\#\\?\\=\\&\\;\\%\\~\\+]+", "URL省略"); System.out.println(final_toot_1); } else { final_toot_1 = finaltoot; } if (0 < toot.length()) { textToSpeech.speak(final_toot_1, textToSpeech.QUEUE_ADD, null, "messageID"); } } @Override public void onNotification(@NotNull Notification notification) {*/ /* no op *//* } @Override public void onDelete(long id) {*/ /* no op *//* } }; Streaming streaming = new Streaming(client); try { if (pref_setting.getString("pref_speech_timeline_type", "Home").contains("Home")) { Shutdownable shutdownable = streaming.user(handler); } if (pref_setting.getString("pref_speech_timeline_type", "Home").contains("Local")) { Shutdownable shutdownable = streaming.localPublic(handler); } if (pref_setting.getString("pref_speech_timeline_type", "Home").contains("Federated")) { Shutdownable shutdownable = streaming.federatedPublic(handler); } } catch (Exception e) { e.printStackTrace(); } return null; } }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } */ /* //スリープ無効? val setting_sleep = pref_setting.getBoolean("pref_no_sleep", false) if (setting_sleep) { //常時点灯 window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } else { //常時点灯しない window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } */ } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) val pref_setting = getDefaultSharedPreferences(this@Home) if (requestCode == 1) if (resultCode == Activity.RESULT_OK) { //がぞう追加 if (data?.data != null) { tootCardView.attachMediaList.add(data.data!!) //LinearLayout作り直す tootCardView.setAttachImageLinearLayout() } } } /** * context://→file://へ変換する * いまはUriをバイト配列にしてるので使ってない() */ fun getPath(uri: Uri?): String { //uri.getLastPathSegment(); val projection = arrayOf(MediaStore.Images.Media.DATA) val cursor = contentResolver.query(uri!!, projection, null, null, null) val column_index = cursor!! .getColumnIndexOrThrow(MediaStore.Images.Media.DATA) cursor.moveToFirst() val imagePath = cursor.getString(column_index) cursor.close() //Android Q から追加された Scoped Storage に一時的に対応 //なにそれ→アプリごとにストレージサンドボックスが作られて、今まであったWRITE_EXTERNAL_STORAGEなしで扱える他 //他のアプリからはアクセスできないようになってる。 //<I>いやでも今までのfile://スキーマ変換が使えないのはクソクソクソでは</I> //今までのやつをAndroid Qで動かすと //Q /mnt/content/media ~ //Pie /storage/emulated/0 ~ //もう一回かけてようやくfile://スキーマのリンク取れた //Android Q if (Build.VERSION.CODENAME == "Q") { // /mnt/content/が邪魔なので取って、そこにcontent://スキーマをつける // Google Photoからしか動かねーわまあPixel以外にもQが配信される頃には情報がわさわさ出てくることでしょう。 val content_text = imagePath.replace("/mnt/content/", "content://") //System.out.println(imagePath); //try-catch //実機で確認できず //imagePath = getPathAndroidQ(Home.this, Uri.parse(content_text)); } //System.out.println(imagePath); return imagePath } private fun ImageViewClick() { val layoutParams = LinearLayout.LayoutParams(200, 200) media_LinearLayout.removeAllViews() //配列に入れた要素をもとにImageViewを生成する for (i in media_uri_list!!.indices) { val imageView = ImageView(this@Home) imageView.layoutParams = layoutParams imageView.setImageURI(media_uri_list!![i]) imageView.tag = i media_LinearLayout.addView(imageView) //押したとき imageView.setOnClickListener { Toast.makeText(this@Home, getString(R.string.delete_ok) + " : " + (imageView.tag as Int).toString(), Toast.LENGTH_SHORT).show() //要素の削除 //なんだこのくそgmコードは //removeにgetTagそのまま書くとなんかだめなんだけど何これ意味不 if (imageView.tag as Int == 0) { media_uri_list!!.removeAt(0) } else if (imageView.tag as Int == 1) { media_uri_list!!.removeAt(1) } else if (imageView.tag as Int == 2) { media_uri_list!!.removeAt(2) } else if (imageView.tag as Int == 3) { media_uri_list!!.removeAt(3) } //再生成 ImageViewClick() } } } /** * Misskey Driveの画像を表示させる */ private fun setMisskeyDrivePhoto() { val layoutParams = LinearLayout.LayoutParams(200, 200) media_LinearLayout.removeAllViews() //配列に入れた要素をもとにImageViewを生成する for (i in misskey_media_url.indices) { val imageView = ImageView(this@Home) //Glide Glide.with(this@Home).load(misskey_media_url[i]).into(imageView) imageView.layoutParams = layoutParams imageView.tag = i media_LinearLayout.addView(imageView) //押したとき imageView.setOnClickListener { Toast.makeText(this@Home, "位置 : " + (imageView.tag as Int).toString(), Toast.LENGTH_SHORT).show() //要素の削除 //なんだこのくそgmコードは //removeにgetTagそのまま書くとなんかだめなんだけど何これ意味不 if (imageView.tag as Int == 0) { misskey_media_url.removeAt(0) post_media_id.removeAt(0) } else if (imageView.tag as Int == 1) { misskey_media_url.removeAt(1) post_media_id.removeAt(1) } else if (imageView.tag as Int == 2) { misskey_media_url.removeAt(2) post_media_id.removeAt(2) } else if (imageView.tag as Int == 3) { misskey_media_url.removeAt(3) post_media_id.removeAt(3) } //再生成 setMisskeyDrivePhoto() } } } override fun onBackPressed() { val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else if (toot_snackbar.isShown) { toot_snackbar.dismiss() } else if (tlQuickSettingSnackber?.isShown() ?: false) { tlQuickSettingSnackber?.dismissSnackBer() } else { // 終了ダイアログ 修正(Android Qで動かないので) AlertDialog.Builder(this@Home) .setTitle(getString(R.string.close_dialog_title)) .setIcon(R.drawable.ic_local_hotel_black_12dp) .setMessage(getString(R.string.close_dialog_message)) .setPositiveButton(getString(R.string.close_dialog_ok)) { dialog, which -> finish(); super.onBackPressed() } .setNegativeButton(getString(R.string.cancel)) { dialog, which -> dialog.cancel() } .show() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { if (pref_setting.getBoolean("pref_bottom_navigation", false)) { getMenuInflater().inflate(R.menu.bottom_app_bar_menu, menu); } return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId /* //noinspection SimplifiableIfStatement FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); if (id == R.id.home_menu_quick_setting) { Bundle bundle = new Bundle(); bundle.putString("account_id", account_id); dialogFragment.setArguments(bundle); dialogFragment.show(getSupportFragmentManager(), "quick_setting"); } */ /* case R.id.home_menu_login: Intent login = new Intent(this, LoginActivity.class); startActivity(login); break; case R.id.home_menu_account_list: transaction.replace(R.id.container_container, new AccountListFragment()); transaction.commit(); break; case R.id.home_menu_account: Intent intent = new Intent(this, UserActivity.class); if (CustomMenuTimeLine.isMisskeyMode()) { intent.putExtra("Account_ID", CustomMenuTimeLine.getAccount_id()); } else { intent.putExtra("Account_ID", account_id); } intent.putExtra("my", true); startActivity(intent); break; case R.id.home_menu_desktop_mode: DesktopFragment desktopFragment = new DesktopFragment(); transaction.replace(R.id.container_container, new DesktopFragment(), "desktop"); transaction.commit(); break; case R.id.home_menu_setting: transaction.replace(R.id.container_container, new SettingFragment()); transaction.commit(); break; case R.id.home_menu_license: transaction.replace(R.id.container_container, new License_Fragment()); transaction.commit(); break; case R.id.home_menu_thisapp: Intent thisApp = new Intent(this, KonoAppNiTuite.class); startActivity(thisApp); break; case R.id.home_menu_privacy_policy: showPrivacyPolicy(); break; case R.id.home_menu_wear: transaction.replace(R.id.container_container, new WearFragment()); transaction.commit(); break; case R.id.home_menu_bookmark: transaction.replace(R.id.container_container, new Bookmark_Frament()); transaction.commit(); break; case R.id.home_menu_activity_pub_viewer: transaction.replace(R.id.container_container, new ActivityPubViewer()); transaction.commit(); break; case R.id.home_menu_reload_menu: //再読み込み navigationView.getMenu().clear(); navigationView.inflateMenu(R.menu.custom_menu); customMenuLoadSupport.loadCustomMenu(null); break; case R.id.home_menu_old_drawer: navigationView.inflateMenu(R.menu.activity_home_drawer); break; case R.id.home_menu_flowlt: Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container_container); if (fragment != null && fragment instanceof CustomMenuTimeLine) { FloatingTL floatingTL = new FloatingTL(this, fragment.getArguments().getString("json")); floatingTL.setNotification(); } break; case R.id.home_menu_quick_setting: Bundle bundle = new Bundle(); bundle.putString("account_id", account_id); dialogFragment.setArguments(bundle); dialogFragment.show(getSupportFragmentManager(), "quick_setting"); break; case R.id.home_menu_dark: //これはAndroid Qを搭載しない端末向け設定 if (Build.VERSION.SDK_INT <= 28 && !Build.VERSION.CODENAME.equals("Q")) { SharedPreferences.Editor editor = pref_setting.edit(); if (pref_setting.getBoolean("darkmode", false)) { editor.putBoolean("darkmode", false); editor.apply(); } else { editor.putBoolean("darkmode", true); editor.apply(); } //Activity再起動 startActivity(new Intent(this, Home.class)); } else { Toast.makeText(this, getString(R.string.darkmode_error_os), Toast.LENGTH_SHORT).show(); } break; } if (id == R.id.action_settings) { return true; } */ return super.onOptionsItemSelected(item) } /** * プライバシーポリシー */ private fun showPrivacyPolicy() { val githubUrl = "https://github.com/takusan23/Kaisendon/blob/master/kaisendon-privacy-policy.md" if (pref_setting.getBoolean("pref_chrome_custom_tabs", true)) { val back_icon = BitmapFactory.decodeResource([email protected], R.drawable.ic_action_arrow_back) val custom = CustomTabsHelper.getPackageNameToUse(this@Home) val builder = CustomTabsIntent.Builder().setCloseButtonIcon(back_icon).setShowTitle(true) val customTabsIntent = builder.build() customTabsIntent.intent.setPackage(custom) customTabsIntent.launchUrl(this@Home, Uri.parse(githubUrl)) } else { val uri = Uri.parse(githubUrl) val browser = Intent(Intent.ACTION_VIEW, uri) startActivity(browser) } } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. val id = item.itemId val pref_setting = getDefaultSharedPreferences(this) if (id == R.id.custom_menu_mode_menu) { //モード切替 val navigationView = findViewById<NavigationView>(R.id.nav_view) navigationView.menu.clear() val editor = pref_setting.edit() if (pref_setting.getBoolean("custom_menu", false)) { editor.putBoolean("custom_menu", false) //メニュー切り替え navigationView.inflateMenu(R.menu.activity_home_drawer) } else { editor.putBoolean("custom_menu", true) //メニュー切り替え navigationView.inflateMenu(R.menu.custom_menu) //適用処理 customMenuLoadSupport!!.loadCustomMenu(null) } editor.apply() } else if (id == R.id.custom_menu_setting_menu) { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container_container, CustomMenuSettingFragment()) transaction.commit() } val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout drawer.closeDrawer(GravityCompat.START) return true } /* //終了しますか? override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { when (keyCode) { KeyEvent.KEYCODE_BACK -> AlertDialog.Builder(this) .setIcon(R.drawable.ic_local_hotel_black_12dp) .setTitle("終了確認") .setMessage("アプリを終了しますか?") .setNegativeButton("いいえ", null) .setPositiveButton("はい" ) { dialog, which -> finish() } .show() } return super.onKeyDown(keyCode, event) } */ fun FragmentChange(fragment: Fragment) { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.container_container, fragment) transaction.commit() } override fun onStop() { super.onStop() } override fun onDestroy() { super.onDestroy() val pref_setting = getDefaultSharedPreferences(this) val editor = pref_setting.edit() editor.putBoolean("app_multipain_ui", false) editor.apply() if (pref_setting.getBoolean("pref_speech", false)) { textToSpeech!!.shutdown() } //レジーバー解除 if (pref_setting.getBoolean("pref_networkchange", false)) { if (networkChangeBroadcast != null) { unregisterReceiver(networkChangeBroadcast) } } } @SuppressLint("RestrictedApi") fun tootSnackBer() { //画像ID配列 post_media_id = ArrayList() misskey_media_url = ArrayList() val AccessToken = pref_setting.getString("main_token", "") val Instance = pref_setting.getString("main_instance", "") val view = [email protected]<View>(R.id.container_public) toot_snackbar = Snackbar.make(view, "", Snackbar.LENGTH_INDEFINITE) toot_snackbar.setBackgroundTint(Color.parseColor("#4c4c4c")) //Snackber生成 val snackBer_viewGrop = toot_snackbar.view.findViewById<View>(R.id.snackbar_text).parent as ViewGroup val progressBer_layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) progressBer_layoutParams.gravity = Gravity.CENTER //LinearLayout動的に生成 val snackber_LinearLayout = LinearLayout(this@Home) snackber_LinearLayout.orientation = LinearLayout.VERTICAL val warp = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) snackber_LinearLayout.layoutParams = warp //スワイプで消せないようにする toot_snackbar.view.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean { toot_snackbar.view.viewTreeObserver.removeOnPreDrawListener(this) (toot_snackbar.view.layoutParams as CoordinatorLayout.LayoutParams).behavior = null return true } }) //押したアニメーション val typedValue = TypedValue() theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, typedValue, true) //テキストボックス //Materialふうに val toot_textBox_LinearLayout = LinearLayout(this@Home) //レイアウト読み込み layoutInflater.inflate(R.layout.textinput_edittext, toot_textBox_LinearLayout) toot_EditText = layoutInflater.inflate(R.layout.textinput_edittext, toot_textBox_LinearLayout).findViewById(R.id.name_editText) //ヒント (layoutInflater.inflate(R.layout.textinput_edittext, toot_textBox_LinearLayout).findViewById<View>(R.id.name_TextInputLayout) as TextInputLayout).hint = getString(R.string.imananisiteru) //色 (layoutInflater.inflate(R.layout.textinput_edittext, toot_textBox_LinearLayout).findViewById<View>(R.id.name_TextInputLayout) as TextInputLayout).defaultHintTextColor = ColorStateList.valueOf(Color.parseColor("#ffffff")) (layoutInflater.inflate(R.layout.textinput_edittext, toot_textBox_LinearLayout).findViewById<View>(R.id.name_TextInputLayout) as TextInputLayout).boxStrokeColor = Color.parseColor("#ffffff") toot_EditText.setTextColor(Color.parseColor("#ffffff")) toot_EditText.setHintTextColor(Color.parseColor("#ffffff")) //ボタン追加用LinearLayout toot_Button_LinearLayout = LinearLayout(this@Home) toot_Button_LinearLayout.orientation = LinearLayout.HORIZONTAL toot_Button_LinearLayout.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) //Button //画像追加 val add_image_Button = ImageButton(this@Home) add_image_Button.setPadding(20, 20, 20, 20) add_image_Button.setBackgroundResource(typedValue.resourceId) add_image_Button.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) add_image_Button.setImageDrawable(getDrawable(R.drawable.ic_image_black_24dp)) setToolTipText(add_image_Button, getString(R.string.image_attachment)) add_image_Button.setOnClickListener { //キーボード隠す closeKeyboard() val REQUEST_PERMISSION = 1000 //ストレージ読み込みの権限があるか確認 //許可してないときは許可を求める if (ContextCompat.checkSelfPermission(this@Home, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { AlertDialog.Builder(this@Home) .setTitle(getString(R.string.permission_dialog_titile)) .setMessage(getString(R.string.image_upload_storage_permisson)) .setPositiveButton(getString(R.string.permission_ok)) { dialog, which -> //権限をリクエストする requestPermissions( arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), REQUEST_PERMISSION) } .setNegativeButton(getString(R.string.cancel), null) .show() } else { //onActivityResultで受け取れる val photoPickerIntent = Intent(Intent.ACTION_PICK) photoPickerIntent.type = "image/*" startActivityForResult(photoPickerIntent, 1) } } //公開範囲選択用Button toot_area_Button = ImageButton(this@Home) toot_area_Button.setPadding(20, 20, 20, 20) toot_area_Button.setBackgroundResource(typedValue.resourceId) toot_area_Button.setImageDrawable(getDrawable(R.drawable.ic_public_black_24dp)) toot_area_Button.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) setToolTipText(toot_area_Button, getString(R.string.visibility)) //toot_area_Button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_public_black_24dp, 0, 0, 0); //メニューセット if (CustomMenuTimeLine.isMisskeyMode) { setMisskeyVisibilityMenu(toot_area_Button) } else { setMastodonVisibilityMenu(toot_area_Button) } //投稿用LinearLayout val toot_LinearLayout = LinearLayout(this@Home) toot_LinearLayout.orientation = LinearLayout.HORIZONTAL val toot_button_LayoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT) toot_button_LayoutParams.gravity = Gravity.RIGHT toot_LinearLayout.layoutParams = toot_button_LayoutParams //投稿用Button post_button = Button(this@Home, null, 0, R.style.Widget_AppCompat_Button_Borderless) post_button.text = tootTextCount.toString() + "/" + "500 " + getString(R.string.toot_text) post_button.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT) post_button.setTextColor(Color.parseColor("#ffffff")) post_button.setBackgroundResource(typedValue.resourceId) post_button.setPadding(50, 0, 50, 0) val toot_icon = ResourcesCompat.getDrawable(resources, R.drawable.ic_create_black_24dp, null) post_button.setCompoundDrawablesWithIntrinsicBounds(toot_icon, null, null, null) //POST statuses val finalAccessToken = AccessToken val finalInstance = Instance post_button.setOnClickListener { v -> //感触フィードバックをつける? if (pref_setting.getBoolean("pref_post_haptics", false)) { post_button.performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK) } //クローズでソフトキーボード非表示 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if (imm != null) { if ([email protected] != null) { imm.hideSoftInputFromWindow([email protected]!!.windowToken, 0) } } //画像添付なしのときはここを利用して、 //画像添付トゥートは別に書くよ if (media_uri_list!!.isEmpty()) { //テキスト0文字で投稿できないようにする if (toot_EditText.text.isNotEmpty()) { //FABのアイコン戻す fab.setImageDrawable(getDrawable(R.drawable.ic_create_black_24dp)) //時間指定投稿(予約投稿)を送信するね!メッセージ val message: String if (isTimePost) { message = getString(R.string.time_post_post_button) } else { message = getString(R.string.note_create_message) } //Tootする //確認SnackBer Snackbar.make(v, message, Snackbar.LENGTH_SHORT).setAction(R.string.toot_text) { //FABのアイコン戻す fab.setImageDrawable(getDrawable(R.drawable.ic_create_black_24dp)) //Mastodon / Misskey if (CustomMenuTimeLine.isMisskeyMode) { misskeyNoteCreatePOST() } else { mastodonStatusesPOST() } }.show() } else { Toast.makeText(this@Home, getString(R.string.toot_error_empty), Toast.LENGTH_SHORT).show() } } else { //画像投稿する for (i in media_uri_list!!.indices) { //ひつようなやつ val uri = media_uri_list!![i] if (CustomMenuTimeLine.isMisskeyMode) { uploadDrivePhoto(uri) } else { uploadMastodonPhoto(uri) } } } } //端末情報とぅーと val device_Button = ImageButton(this@Home) device_Button.setPadding(20, 20, 20, 20) device_Button.setBackgroundResource(typedValue.resourceId) device_Button.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) device_Button.setImageDrawable(getDrawable(R.drawable.ic_perm_device_information_black_24dp)) setToolTipText(device_Button, getString(R.string.device_info)) //ポップアップメニュー作成 val device_menuBuilder = MenuBuilder(this@Home) val device_inflater = MenuInflater(this@Home) device_inflater.inflate(R.menu.device_info_menu, device_menuBuilder) val device_optionsMenu = MenuPopupHelper(this@Home, device_menuBuilder, device_Button) device_optionsMenu.setForceShowIcon(true) //コードネーム変換(手動 var codeName = "" if (Build.VERSION.SDK_INT == Build.VERSION_CODES.N || Build.VERSION.SDK_INT == Build.VERSION_CODES.N_MR1) { codeName = "Nougat" } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) { codeName = "Oreo" } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) { codeName = "Pie" } val finalCodeName = codeName val bm = getSystemService(Context.BATTERY_SERVICE) as BatteryManager device_Button.setOnClickListener { device_optionsMenu.show() device_menuBuilder.setCallback(object : MenuBuilder.Callback { override fun onMenuItemSelected(menuBuilder: MenuBuilder, menuItem: MenuItem): Boolean { //名前 if (menuItem.title.toString().contains(getString(R.string.device_name))) { toot_EditText.append(Build.MODEL) toot_EditText.append("\r\n") } //Androidバージョン if (menuItem.title.toString().contains(getString(R.string.android_version))) { toot_EditText.append(Build.VERSION.RELEASE) toot_EditText.append("\r\n") } //めーかー if (menuItem.title.toString().contains(getString(R.string.maker))) { toot_EditText.append(Build.BRAND) toot_EditText.append("\r\n") } //SDKバージョン if (menuItem.title.toString().contains(getString(R.string.sdk_version))) { toot_EditText.append(Build.VERSION.SDK_INT.toString()) toot_EditText.append("\r\n") } //コードネーム if (menuItem.title.toString().contains(getString(R.string.codename))) { toot_EditText.append(finalCodeName) toot_EditText.append("\r\n") } //バッテリーレベル if (menuItem.title.toString().contains(getString(R.string.battery_level))) { toot_EditText.append(bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY).toString() + "%") toot_EditText.append("\r\n") } return false } override fun onMenuModeChange(menuBuilder: MenuBuilder) { } }) } //Misskey Driveボタン misskey_drive_Button = ImageButton(this@Home) //misskey_drive_Button.setBackground(getDrawable(R.drawable.button_clear)); misskey_drive_Button.setPadding(20, 20, 20, 20) misskey_drive_Button.setBackgroundColor(Color.parseColor("#00000000")) misskey_drive_Button.setImageDrawable(getDrawable(R.drawable.ic_cloud_queue_white_24dp)) misskey_drive_Button.setOnClickListener { //Misskey Drive API を叩く val dialogFragment = MisskeyDriveBottomDialog() dialogFragment.show(supportFragmentManager, "misskey_drive_dialog") setMisskeyDrivePhoto() } //時間投稿ボタン //高さ調整 val display = windowManager.defaultDisplay val size = Point() display.getSize(size) val mastodon_time_post_LinearLayout = LinearLayout(this@Home) layoutInflater.inflate(R.layout.mastodon_time_post_layout, mastodon_time_post_LinearLayout) mastodon_time_post_LinearLayout.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) mastodon_time_post_Button = ImageButton(this@Home) mastodon_time_post_Button.setPadding(20, 20, 20, 20) mastodon_time_post_Button.setBackgroundResource(typedValue.resourceId) mastodon_time_post_Button.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) mastodon_time_post_Button.setImageDrawable(getDrawable(R.drawable.ic_timer_black_24dp)) setToolTipText(mastodon_time_post_Button, getString(R.string.scheduled_statuses_name)) mastodon_time_post_Button.setOnClickListener { //2番めに出す if (!isMastodon_time_post) { isMastodon_time_post = true snackber_LinearLayout.addView(mastodon_time_post_LinearLayout, 2) //設定ボタン等 val day_setting_Button = snackber_LinearLayout.findViewById<Button>(R.id.time_post_button) time_post_Switch = snackber_LinearLayout.findViewById(R.id.time_post_switch) val date_TextView = snackber_LinearLayout.findViewById<TextView>(R.id.time_post_textview) val time_setting_Button = snackber_LinearLayout.findViewById<Button>(R.id.time_post_time_button) val time_TextView = snackber_LinearLayout.findViewById<TextView>(R.id.time_post_time_textview) //日付設定画面 day_setting_Button.setOnClickListener { showDatePicker(date_TextView) } //時間設定画面 time_setting_Button.setOnClickListener { showTimePicker(time_TextView) } //有効無効 time_post_Switch!!.setOnCheckedChangeListener { buttonView, isChecked -> //入れておく isTimePost = isChecked //色を変えとく? if (isChecked) { post_button.text = getString(R.string.time_post_post_button) mastodon_time_post_Button.setColorFilter(Color.parseColor("#0069c0"), PorterDuff.Mode.SRC_IN) } else { post_button.text = getString(R.string.toot_text) mastodon_time_post_Button.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) } } } else { //消す isMastodon_time_post = false snackber_LinearLayout.removeView(mastodon_time_post_LinearLayout) } } //投票 //ここから val vote_LinearLayout = LinearLayout(this@Home) layoutInflater.inflate(R.layout.toot_vote_layout, vote_LinearLayout) vote_LinearLayout.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, size.y / 2) mastodon_vote_Button = ImageButton(this@Home) mastodon_vote_Button.setPadding(20, 20, 20, 20) mastodon_vote_Button.setBackgroundResource(typedValue.resourceId) mastodon_vote_Button.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) mastodon_vote_Button.setImageDrawable(getDrawable(R.drawable.ic_baseline_how_to_vote_24px)) setToolTipText(mastodon_vote_Button, getString(R.string.polls)) mastodon_vote_Button.setOnClickListener { if (!isMastodon_vote_layout) { isMastodon_vote_layout = true snackber_LinearLayout.addView(vote_LinearLayout, 2) vote_use_Switch = snackber_LinearLayout.findViewById(R.id.vote_use_switch) vote_multi_Switch = snackber_LinearLayout.findViewById(R.id.vote_multi_switch) vote_hide_Switch = snackber_LinearLayout.findViewById(R.id.vote_hide_switch) vote_1 = snackber_LinearLayout.findViewById(R.id.vote_editText_1) vote_2 = snackber_LinearLayout.findViewById(R.id.vote_editText_2) vote_3 = snackber_LinearLayout.findViewById(R.id.vote_editText_3) vote_4 = snackber_LinearLayout.findViewById(R.id.vote_editText_4) vote_time = snackber_LinearLayout.findViewById(R.id.vote_editText_time) (snackber_LinearLayout.findViewById<View>(R.id.vote_textInputLayout_1) as TextInputLayout).defaultHintTextColor = ColorStateList.valueOf(Color.parseColor("#ffffff")) (snackber_LinearLayout.findViewById<View>(R.id.vote_textInputLayout_2) as TextInputLayout).defaultHintTextColor = ColorStateList.valueOf(Color.parseColor("#ffffff")) (snackber_LinearLayout.findViewById<View>(R.id.vote_textInputLayout_3) as TextInputLayout).defaultHintTextColor = ColorStateList.valueOf(Color.parseColor("#ffffff")) (snackber_LinearLayout.findViewById<View>(R.id.vote_textInputLayout_4) as TextInputLayout).defaultHintTextColor = ColorStateList.valueOf(Color.parseColor("#ffffff")) (snackber_LinearLayout.findViewById<View>(R.id.vote_textInputLayout_time) as TextInputLayout).defaultHintTextColor = ColorStateList.valueOf(Color.parseColor("#ffffff")) //有効無効 vote_use_Switch.setOnCheckedChangeListener { buttonView, isChecked -> //入れておく isMastodon_vote = isChecked //色を変えとく? if (isChecked) { mastodon_vote_Button.setColorFilter(Color.parseColor("#0069c0"), PorterDuff.Mode.SRC_IN) } else { mastodon_vote_Button.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) } } } else { isMastodon_vote_layout = false snackber_LinearLayout.removeView(vote_LinearLayout) } } //コマンド実行ボタン val command_Button = Button(this@Home, null, 0, R.style.Widget_AppCompat_Button_Borderless) command_Button.setText(R.string.command_run) command_Button.setTextColor(Color.parseColor("#ffffff")) //EditTextを監視する toot_EditText.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { //コマンド実行メゾット? //CommandCode.commandSet(Home.this, toot_EditText, toot_LinearLayout, command_Button, "/sushi", "command_sushi"); //CommandCode.commandSet(Home.this, toot_EditText, toot_LinearLayout, command_Button, "/friends.nico", "pref_friends_nico_mode"); CommandCode.commandSetNotPreference(this@Home, this@Home, toot_EditText, toot_LinearLayout, command_Button, "/rate-limit", "rate-limit") CommandCode.commandSetNotPreference(this@Home, this@Home, toot_EditText, toot_LinearLayout, command_Button, "/fav-home", "home") CommandCode.commandSetNotPreference(this@Home, this@Home, toot_EditText, toot_LinearLayout, command_Button, "/fav-local", "local") CommandCode.commandSetNotPreference(this@Home, this@Home, toot_EditText, toot_LinearLayout, command_Button, "/じゃんけん", "じゃんけん") /* CommandCode.commandSetNotPreference(Home.this, Home.this, toot_EditText, toot_LinearLayout, command_Button, "/progress", "progress"); CommandCode.commandSetNotPreference(Home.this, Home.this, toot_EditText, toot_LinearLayout, command_Button, "/lunch_bonus", "lunch_bonus"); */ //CommandCode.commandSetNotPreference(Home.this, Home.this, toot_EditText, toot_LinearLayout, command_Button, "/life", "life"); //カウント tootTextCount = toot_EditText.text.toString().length //投稿ボタンの文字 val buttonText: String if (isTimePost) { buttonText = getString(R.string.time_post_post_button) } else { buttonText = getString(R.string.toot_text) } post_button.text = "$tootTextCount/500 $buttonText" } override fun afterTextChanged(s: Editable) { } }) //お絵かき投稿機能? paintPOSTButton = ImageButton(this@Home) paintPOSTButton.setPadding(20, 20, 20, 20) paintPOSTButton.setBackgroundResource(typedValue.resourceId) paintPOSTButton.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) paintPOSTButton.setImageDrawable(getDrawable(R.drawable.ic_gesture_black_24dp)) setToolTipText(paintPOSTButton, getString(R.string.polls)) paintPOSTButton.setOnClickListener { //キーボード隠す closeKeyboard() //開発中メッセージ val dialog = AlertDialog.Builder(this@Home) .setTitle(getString(R.string.paintPost)) .setMessage(getString(R.string.paint_post_description)) .setPositiveButton(getString(R.string.open_painit_post)) { dialogInterface, i -> //お絵かきアクティビティへ移動 val intent = Intent(this@Home, PaintPOSTActivity::class.java) startActivity(intent) } .setNegativeButton(getString(R.string.cancel), null) .show() //https://stackoverflow.com/questions/9467026/changing-position-of-the-dialog-on-screen-android val window = dialog.window val layoutParams = window?.attributes layoutParams?.gravity = Gravity.BOTTOM layoutParams?.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND window?.attributes = layoutParams } //アカウント切り替えとか account_LinearLayout = LinearLayout(this) account_LinearLayout.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) val center_layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) center_layoutParams.gravity = Gravity.CENTER //ImageView snackberAccountAvaterImageView = ImageView(this) snackberAccountAvaterImageView.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) snackberAccountAvaterImageView.layoutParams = center_layoutParams //TextView snackberAccount_TextView = TextView(this) snackberAccount_TextView.textSize = 14f snackberAccount_TextView.setTextColor(Color.parseColor("#ffffff")) snackberAccount_TextView.layoutParams = center_layoutParams //アカウント情報を取得するところにテキスト設定とか書いたで if (CustomMenuTimeLine.isMisskeyMode) { getMisskeyAccount() } else { getAccount() } //アカウント切り替えポップアップ //ポップアップメニューを展開する account_menuBuilder = MenuBuilder(this) account_optionsMenu = MenuPopupHelper(this, account_menuBuilder, account_LinearLayout) misskey_account_menuBuilder = MenuBuilder(this) misskey_account_optionMenu = MenuPopupHelper(this, misskey_account_menuBuilder, account_LinearLayout) //マルチアカウント読み込み //押したときの処理とかもこっち //カスタムメニュー時は無効() //LinearLayoutに入れる account_LinearLayout.setPadding(10, 10, 10, 10) account_LinearLayout.addView(snackberAccountAvaterImageView) account_LinearLayout.addView(snackberAccount_TextView) //画像追加用LinearLayout media_LinearLayout = LinearLayout(this@Home) media_LinearLayout.orientation = LinearLayout.HORIZONTAL media_LinearLayout.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) //LinearLayoutに追加 //メイン snackber_LinearLayout.addView(account_LinearLayout) snackber_LinearLayout.addView(toot_textBox_LinearLayout) snackber_LinearLayout.addView(toot_Button_LinearLayout) snackber_LinearLayout.addView(media_LinearLayout) snackber_LinearLayout.addView(toot_LinearLayout) if (pref_setting.getBoolean("life_mode", false)) { val linearLayout = shinchokuLayout.layout snackber_LinearLayout.addView(linearLayout, 1) } //ボタン追加 toot_Button_LinearLayout.addView(add_image_Button) toot_Button_LinearLayout.addView(toot_area_Button) toot_Button_LinearLayout.addView(device_Button) //Toot LinearLayout toot_LinearLayout.addView(post_button) //SnackBerに追加 snackBer_viewGrop.addView(snackber_LinearLayout) } fun setToolTipText(view: View, string: String) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { view.tooltipText = string } } fun closeKeyboard() { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if ([email protected] != null) { imm.hideSoftInputFromWindow([email protected]!!.windowToken, 0) } } //自分の情報を手に入れる private fun getAccount() { //Wi-Fi接続状況確認 val connectivityManager = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) //通信量節約 val setting_avater_hidden = pref_setting.getBoolean("pref_drawer_avater", false) //Wi-Fi接続時は有効? val setting_avater_wifi = pref_setting.getBoolean("pref_avater_wifi", true) //GIFを再生するか? val setting_avater_gif = pref_setting.getBoolean("pref_avater_gif", false) val AccessToken = pref_setting.getString("main_token", "") val Instance = pref_setting.getString("main_instance", "") val glideSupport = GlideSupport() val url = "https://$Instance/api/v1/accounts/verify_credentials/?access_token=$AccessToken" //作成 val request = Request.Builder() .url(url) .get() .build() //GETリクエスト val client_1 = OkHttpClient() client_1.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() try { val jsonObject = JSONObject(response_string) val display_name = jsonObject.getString("display_name") val user_id = jsonObject.getString("acct") snackber_DisplayName = display_name toot_count = jsonObject.getString("statuses_count") //カスタム絵文字適用 if (emojis_show) { //他のところでは一旦配列に入れてるけど今回はここでしか使ってないから省くね val emojis = jsonObject.getJSONArray("emojis") for (i in 0 until emojis.length()) { val emojiObject = emojis.getJSONObject(i) val emoji_name = emojiObject.getString("shortcode") val emoji_url = emojiObject.getString("url") val custom_emoji_src = "<img src=\'$emoji_url\'>" //display_name if (snackber_DisplayName.contains(emoji_name)) { //あったよ snackber_DisplayName = snackber_DisplayName.replace(":$emoji_name:", custom_emoji_src) } } if (!jsonObject.isNull("profile_emojis")) { val profile_emojis = jsonObject.getJSONArray("profile_emojis") for (i in 0 until profile_emojis.length()) { val emojiObject = profile_emojis.getJSONObject(i) val emoji_name = emojiObject.getString("shortcode") val emoji_url = emojiObject.getString("url") val custom_emoji_src = "<img src=\'$emoji_url\'>" //display_name if (snackber_DisplayName.contains(emoji_name)) { //あったよ snackber_DisplayName = snackber_DisplayName.replace(":$emoji_name:", custom_emoji_src) } } } } snackber_Name = "@$user_id@$Instance" snackber_Avatar = jsonObject.getString("avatar") snackber_Avatar_notGif = jsonObject.getString("avatar_static") //UIスレッド runOnUiThread { //画像サイズ val layoutParams = LinearLayout.LayoutParams(150, LinearLayout.LayoutParams.MATCH_PARENT) snackberAccountAvaterImageView.layoutParams = layoutParams //画像を入れる //表示設定 if (setting_avater_hidden) { snackberAccountAvaterImageView.setImageResource(R.drawable.ic_person_black_24dp) snackberAccountAvaterImageView.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) } //GIF再生するか var url = snackber_Avatar if (setting_avater_gif) { //再生しない url = snackber_Avatar_notGif } //読み込む if (setting_avater_wifi && networkCapabilities != null) { if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { //角丸設定込み glideSupport.loadGlide(url, snackberAccountAvaterImageView) } else { //キャッシュで読み込む glideSupport.loadGlideReadFromCache(url, snackberAccountAvaterImageView) } } else { //キャッシュで読み込む glideSupport.loadGlideReadFromCache(url, snackberAccountAvaterImageView) } //テキストビューに入れる val imageGetter = PicassoImageGetter(snackberAccount_TextView) snackberAccount_TextView.text = Html.fromHtml(snackber_DisplayName, Html.FROM_HTML_MODE_LEGACY, imageGetter, null) snackberAccount_TextView.append("\n" + snackber_Name) //裏機能? shinchokuLayout.setStatusProgress(toot_count) } } catch (e: JSONException) { e.printStackTrace() } } }) } @SuppressLint("RestrictedApi") private fun showMultiAccount() { //押したときの処理 account_LinearLayout.setOnClickListener { //そもそも呼ばれてない説 if (multi_account_instance == null) { //一度だけ取得する readMultiAccount() } else { //追加中に押したら落ちるから回避 if (account_menuBuilder.size() == multi_account_instance!!.size) { account_optionsMenu.show() account_menuBuilder.setCallback(object : MenuBuilder.Callback { override fun onMenuItemSelected(menuBuilder: MenuBuilder, menuItem: MenuItem): Boolean { //ItemIdにマルチアカウントのカウントを入れている val position = menuItem.itemId val multi_instance = multi_account_instance!![position] val multi_access_token = multi_account_access_token[position] AccessToken = multi_access_token Instance = multi_instance val editor = pref_setting.edit() editor.putString("main_instance", multi_instance) editor.putString("main_token", multi_access_token) editor.apply() //アカウント情報更新 getAccount() return false } override fun onMenuModeChange(menuBuilder: MenuBuilder) { } }) } else { Toast.makeText(this@Home, R.string.loading, Toast.LENGTH_SHORT).show() } } } } @SuppressLint("RestrictedApi") private fun showMisskeyMultiAccount() { //押したときの処理 account_LinearLayout.setOnClickListener { //そもそも呼ばれてない説 if (misskey_multi_account_instance == null) { //一度だけ取得する readMisskeyMultiAccount() } else { //追加中に押したら落ちるから回避 if (misskey_account_menuBuilder.size() == misskey_multi_account_instance!!.size) { misskey_account_optionMenu.show() misskey_account_menuBuilder.setCallback(object : MenuBuilder.Callback { override fun onMenuItemSelected(menuBuilder: MenuBuilder, menuItem: MenuItem): Boolean { //ItemIdにマルチアカウントのカウントを入れている val position = menuItem.itemId val multi_instance = misskey_multi_account_instance!![position] val multi_access_token = misskey_multi_account_instance!![position] AccessToken = multi_access_token Instance = multi_instance val editor = pref_setting.edit() editor.putString("misskey_main_instance", multi_instance) editor.putString("misskey_main_token", multi_access_token) editor.apply() //アカウント情報更新 getMisskeyAccount() return false } override fun onMenuModeChange(menuBuilder: MenuBuilder) { } }) } else { Toast.makeText(this@Home, R.string.loading, Toast.LENGTH_SHORT).show() } } } } @SuppressLint("RestrictedApi") private fun readMultiAccount() { multi_account_instance = ArrayList() multi_account_access_token = ArrayList() misskey_multi_account_instance = ArrayList() misskey_multi_account_access_token = ArrayList() //とりあえずPreferenceに書き込まれた値を val instance_instance_string = pref_setting.getString("instance_list", "") val account_instance_string = pref_setting.getString("access_list", "") val misskey_instance_instance_string = pref_setting.getString("misskey_instance_list", "") val misskey_account_instance_string = pref_setting.getString("misskey_access_list", "") if (instance_instance_string != "") { try { val instance_array = JSONArray(instance_instance_string) val access_array = JSONArray(account_instance_string) for (i in 0 until instance_array.length()) { multi_account_access_token.add(access_array.getString(i)) multi_account_instance!!.add(instance_array.getString(i)) } } catch (e: Exception) { e.printStackTrace() } } if (misskey_instance_instance_string != "") { try { val instance_array = JSONArray(misskey_account_instance_string) val access_array = JSONArray(misskey_account_instance_string) for (i in 0 until instance_array.length()) { misskey_multi_account_access_token.add(access_array.getString(i)) misskey_multi_account_instance!!.add(instance_array.getString(i)) } } catch (e: Exception) { e.printStackTrace() } } if (multi_account_instance!!.size >= 1) { for (count in multi_account_instance!!.indices) { val multi_instance = multi_account_instance!![count] val multi_access_token = multi_account_access_token[count] val finalCount = count //GetAccount val url = "https://$multi_instance/api/v1/accounts/verify_credentials/?access_token=$multi_access_token" //作成 val request = Request.Builder() .url(url) .get() .build() //GETリクエスト val client_1 = OkHttpClient() val finalInstance = Instance client_1.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() try { val jsonObject = JSONObject(response_string) val display_name = jsonObject.getString("display_name") val user_id = jsonObject.getString("acct") //スナックバー更新 snackber_Name = "@$user_id@$finalInstance" snackber_Avatar = jsonObject.getString("avatar") account_menuBuilder.add(0, finalCount, 0, "$display_name($user_id / $multi_instance)") } catch (e: JSONException) { e.printStackTrace() } } }) } } } /** * マルチアカウント読み込み Misskey */ @SuppressLint("RestrictedApi") private fun readMisskeyMultiAccount() { misskey_multi_account_instance = ArrayList() misskey_multi_account_access_token = ArrayList() //とりあえずPreferenceに書き込まれた値を val instance_instance_string = pref_setting.getString("misskey_instance_list", "") val account_instance_string = pref_setting.getString("misskey_access_list", "") if (instance_instance_string != "") { try { val instance_array = JSONArray(instance_instance_string) val access_array = JSONArray(account_instance_string) for (i in 0 until instance_array.length()) { misskey_multi_account_instance!!.add(instance_array.getString(i)) misskey_multi_account_access_token.add(access_array.getString(i)) } } catch (e: Exception) { e.printStackTrace() } } if (misskey_multi_account_instance!!.size >= 1) { for (count in misskey_multi_account_instance!!.indices) { val multi_instance = misskey_multi_account_instance!![count] val multi_access_token = misskey_multi_account_access_token[count] val finalCount = count //GetAccount val url = "https://$multi_instance/api/i" //JSON val jsonObject = JSONObject() try { jsonObject.put("i", multi_access_token) } catch (e: JSONException) { e.printStackTrace() } val requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString()) //作成 val request = Request.Builder() .url(url) .post(requestBody) .build() //GETリクエスト val client_1 = OkHttpClient() client_1.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() try { val jsonObject = JSONObject(response_string) val display_name = jsonObject.getString("name") val user_id = jsonObject.getString("username") misskey_account_menuBuilder.add(0, finalCount, 0, "$display_name($user_id / $multi_instance)") } catch (e: JSONException) { e.printStackTrace() } } }) } } } //自分の情報を手に入れる Misskey版 private fun getMisskeyAccount() { val instance = pref_setting.getString("misskey_main_instance", "") val token = pref_setting.getString("misskey_main_token", "") val username = pref_setting.getString("misskey_main_username", "") //Wi-Fi接続状況確認 val connectivityManager = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) //通信量節約 val setting_avater_hidden = pref_setting.getBoolean("pref_drawer_avater", false) //Wi-Fi接続時は有効? val setting_avater_wifi = pref_setting.getBoolean("pref_avater_wifi", true) //GIFを再生するか? val setting_avater_gif = pref_setting.getBoolean("pref_avater_gif", false) val url = "https://$instance/api/users/show" val jsonObject = JSONObject() try { jsonObject.put("username", username) } catch (e: JSONException) { e.printStackTrace() } val requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString()) //作成 val request = Request.Builder() .url(url) .post(requestBody) .build() //GETリクエスト val client_1 = OkHttpClient() val finalInstance = Instance client_1.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() try { val jsonObject = JSONObject(response_string) val display_name = jsonObject.getString("name") toot_count = jsonObject.getString("notesCount") snackber_DisplayName = display_name //カスタム絵文字適用 if (emojis_show) { //他のところでは一旦配列に入れてるけど今回はここでしか使ってないから省くね val emojis = jsonObject.getJSONArray("emojis") for (i in 0 until emojis.length()) { val emojiObject = emojis.getJSONObject(i) val emoji_name = emojiObject.getString("name") val emoji_url = emojiObject.getString("url") val custom_emoji_src = "<img src=\'$emoji_url\'>" //display_name if (snackber_DisplayName.contains(emoji_name)) { //あったよ snackber_DisplayName = snackber_DisplayName.replace(":$emoji_name:", custom_emoji_src) } } if (!jsonObject.isNull("profile_emojis")) { val profile_emojis = jsonObject.getJSONArray("profile_emojis") for (i in 0 until profile_emojis.length()) { val emojiObject = profile_emojis.getJSONObject(i) val emoji_name = emojiObject.getString("name") val emoji_url = emojiObject.getString("url") val custom_emoji_src = "<img src=\'$emoji_url\'>" //display_name if (snackber_DisplayName.contains(emoji_name)) { //あったよ snackber_DisplayName = snackber_DisplayName.replace(":$emoji_name:", custom_emoji_src) } } } } snackber_Name = "@$username@$instance" snackber_Avatar = jsonObject.getString("avatarUrl") //UIスレッド runOnUiThread { //画像を入れる //表示設定 if (setting_avater_hidden) { snackberAccountAvaterImageView.setImageResource(R.drawable.ic_person_black_24dp) snackberAccountAvaterImageView.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) } //Wi-Fi if (setting_avater_wifi) { if (networkCapabilities!!.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) { if (setting_avater_gif) { //GIFアニメ再生させない Picasso.get() .load(snackber_Avatar) .resize(100, 100) .placeholder(R.drawable.ic_refresh_black_24dp) .into(snackberAccountAvaterImageView) } else { //GIFアニメを再生 Glide.with(applicationContext) .load(snackber_Avatar) .apply(RequestOptions().override(100, 100).placeholder(R.drawable.ic_refresh_black_24dp)) .into(snackberAccountAvaterImageView) } } } else { snackberAccountAvaterImageView.setImageResource(R.drawable.ic_person_black_24dp) snackberAccountAvaterImageView.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) } //テキストビューに入れる val imageGetter = PicassoImageGetter(snackberAccount_TextView) snackberAccount_TextView.text = Html.fromHtml(snackber_DisplayName, Html.FROM_HTML_MODE_LEGACY, imageGetter, null) snackberAccount_TextView.append("\n" + snackber_Name) //裏機能? shinchokuLayout.setStatusProgress(toot_count) } } catch (e: JSONException) { e.printStackTrace() } } }) } /** * Misskey notes/create POST */ private fun misskeyNoteCreatePOST() { val instance = pref_setting.getString("misskey_main_instance", "") val token = pref_setting.getString("misskey_main_token", "") val username = pref_setting.getString("misskey_main_username", "") val url = "https://$instance/api/notes/create" val jsonObject = JSONObject() try { jsonObject.put("i", token) jsonObject.put("visibility", toot_area) jsonObject.put("text", toot_EditText.text.toString()) jsonObject.put("viaMobile", true)//スマホからなので一応 //添付メディア if (post_media_id.size >= 1) { val jsonArray = JSONArray() for (i in post_media_id.indices) { jsonArray.put(post_media_id[i]) } jsonObject.put("fileIds", jsonArray) } } catch (e: JSONException) { e.printStackTrace() } //System.out.println(jsonObject.toString()); val requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString()) //作成 val request = Request.Builder() .url(url) .post(requestBody) .build() //GETリクエスト val client = OkHttpClient() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() runOnUiThread { Toast.makeText(this@Home, getString(R.string.error), Toast.LENGTH_SHORT).show() } } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() //System.out.println(response_string); if (!response.isSuccessful) { //失敗 runOnUiThread { Toast.makeText(this@Home, getString(R.string.error) + "\n" + response.code().toString(), Toast.LENGTH_SHORT).show() } } else { runOnUiThread { //EditTextを空にする toot_EditText.setText("") tootTextCount = 0 //TootSnackber閉じる toot_snackbar.dismiss() //配列を空にする media_uri_list!!.clear() post_media_id.clear() media_LinearLayout.removeAllViews() } } } }) } /** * Mastodon statuses POST */ private fun mastodonStatusesPOST() { val AccessToken = pref_setting.getString("main_token", "") val Instance = pref_setting.getString("main_instance", "") val url = "https://$Instance/api/v1/statuses/?access_token=$AccessToken" val jsonObject = JSONObject() try { jsonObject.put("status", toot_EditText.text.toString()) jsonObject.put("visibility", toot_area) //時間指定 if (isTimePost) { //System.out.println(post_date + "/" + post_time); //nullCheck if (post_date != null && post_time != null) { jsonObject.put("scheduled_at", post_date!! + post_time!!) } } //画像 if (post_media_id.size != 0) { val media = JSONArray() for (i in post_media_id.indices) { media.put(post_media_id[i]) } jsonObject.put("media_ids", media) } //投票機能 if (isMastodon_vote) { jsonObject.put("poll", createMastodonVote()) } } catch (e: JSONException) { e.printStackTrace() } val requestBody_json = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString()) val request = Request.Builder() .url(url) .post(requestBody_json) .build() //POST val client = OkHttpClient() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() runOnUiThread { Toast.makeText(this@Home, getString(R.string.error), Toast.LENGTH_SHORT).show() } } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() if (!response.isSuccessful) { //失敗 runOnUiThread { Toast.makeText(this@Home, getString(R.string.error) + "\n" + response.code().toString(), Toast.LENGTH_SHORT).show() } } else { runOnUiThread { //予約投稿・通常投稿でトースト切り替え if (time_post_Switch != null) { time_post_Switch!!.isChecked = false Toast.makeText(this@Home, getString(R.string.time_post_ok), Toast.LENGTH_SHORT).show() //予約投稿を無効化 isTimePost = false mastodon_time_post_Button.setColorFilter(Color.parseColor("#ffffff"), PorterDuff.Mode.SRC_IN) } else { Toast.makeText(this@Home, getString(R.string.toot_ok), Toast.LENGTH_SHORT).show() } //投票 if (isMastodon_vote) { isMastodon_vote = false vote_use_Switch.isChecked = false } //EditTextを空にする toot_EditText.setText("") tootTextCount = 0 //TootSnackber閉じる toot_snackbar.dismiss() //配列を空にする media_uri_list!!.clear() post_media_id.clear() media_LinearLayout.removeAllViews() //目標更新 shinchokuLayout.setTootChallenge() //JSONParseしてトゥート数変更する val jsonObject = JSONObject(response_string) val toot_count = jsonObject.getJSONObject("account").getInt("statuses_count").toString() shinchokuLayout.setStatusProgress(toot_count) } } } }) } /** * Misskey 画像POST */ private fun uploadDrivePhoto(uri: Uri) { val instance = pref_setting.getString("misskey_main_instance", "") val token = pref_setting.getString("misskey_main_token", "") val username = pref_setting.getString("misskey_main_username", "") val url = "https://$instance/api/drive/files/create" //くるくる SnackberProgress.showProgressSnackber(toot_EditText, this@Home, getString(R.string.loading) + "\n" + url) //ぱらめーたー val requestBody = MultipartBody.Builder() requestBody.setType(MultipartBody.FORM) //requestBody.addFormDataPart("file", file_post.getName(), RequestBody.create(MediaType.parse("image/" + file_extn_post), file_post)); requestBody.addFormDataPart("i", token!!) requestBody.addFormDataPart("force", "true") //Android Qで動かないのでUriからBitmap変換してそれをバイトに変換してPOSTしてます val uri_byte = UriToByte(this@Home) try { val file_name = getFileNameUri(uri) val extn = contentResolver.getType(uri) System.out.println(file_name + "/" + extn) //requestBody.addFormDataPart("file", file_name, RequestBody.create(MediaType.parse("image/" + extn!!), uri_byte.getByte(uri))) } catch (e: IOException) { e.printStackTrace() } requestBody.build() //作成 val request = Request.Builder() .url(url) .post(requestBody.build()) .build() //GETリクエスト val client = OkHttpClient() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() runOnUiThread { Toast.makeText(this@Home, getString(R.string.error), Toast.LENGTH_SHORT).show() } } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() //System.out.println(response_string); if (!response.isSuccessful) { //失敗 runOnUiThread { Toast.makeText(this@Home, getString(R.string.error) + "\n" + response.code().toString(), Toast.LENGTH_SHORT).show() } } else { try { val jsonObject = JSONObject(response_string) val media_id_long = jsonObject.getString("id") //配列に格納 post_media_id.add(media_id_long) //確認SnackBer //数確認 if (media_uri_list!!.size == post_media_id.size) { val view = findViewById<View>(R.id.container_public) Snackbar.make(view, R.string.note_create_message, Snackbar.LENGTH_SHORT).setAction(R.string.toot_text) { misskeyNoteCreatePOST() }.show() } } catch (e: JSONException) { e.printStackTrace() } } } }) } /** * PNG / JPEG */ private fun getImageType(extn: String): Bitmap.CompressFormat { var format: Bitmap.CompressFormat = Bitmap.CompressFormat.PNG when (extn) { "jpg" -> format = Bitmap.CompressFormat.JPEG "jpeg" -> format = Bitmap.CompressFormat.JPEG "png" -> format = Bitmap.CompressFormat.PNG } return format } /** * Mastodon 画像POST */ private fun uploadMastodonPhoto(uri: Uri) { //えんどぽいんと val url = "https://$Instance/api/v1/media/" //ぱらめーたー val requestBody = MultipartBody.Builder() requestBody.setType(MultipartBody.FORM) //requestBody.addFormDataPart("file", file_post.getName(), RequestBody.create(MediaType.parse("image/" + file_extn_post), file_post)); requestBody.addFormDataPart("access_token", AccessToken!!) //くるくる SnackberProgress.showProgressSnackber(toot_EditText, this@Home, getString(R.string.loading) + "\n" + url) //Android Qで動かないのでUriからバイトに変換してPOSTしてます //重いから非同期処理 Thread(Runnable { val uri_byte = UriToByte(this@Home); try { // file:// と content:// でわける if (uri.scheme?.contains("file") ?: false) { val file_name = getFileSchemeFileName(uri) val extn = getFileSchemeFileExtension(uri) requestBody.addFormDataPart("file", file_name, RequestBody.create(MediaType.parse("image/" + extn!!), uri_byte.getByte(uri))) } else { val file_name = getFileNameUri(uri) val extn = contentResolver.getType(uri) requestBody.addFormDataPart("file", file_name, RequestBody.create(MediaType.parse("image/" + extn!!), uri_byte.getByte(uri))) } } catch (e: IOException) { e.printStackTrace() } //じゅんび val request = Request.Builder() .url(url) .post(requestBody.build()) .build() //画像Upload val okHttpClient = OkHttpClient() //POST実行 okHttpClient.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { //失敗 e.printStackTrace() runOnUiThread { Toast.makeText(this@Home, getString(R.string.error), Toast.LENGTH_SHORT).show() } } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val response_string = response.body()!!.string() //System.out.println("画像POST : " + response_string); if (!response.isSuccessful) { //失敗 runOnUiThread { Toast.makeText(this@Home, getString(R.string.error) + "\n" + response.code().toString(), Toast.LENGTH_SHORT).show() } } else { try { val jsonObject = JSONObject(response_string) val media_id_long = jsonObject.getString("id") //配列に格納 post_media_id.add(media_id_long) //確認SnackBer //数確認 if (media_uri_list!!.size == post_media_id.size) { val view = findViewById<View>(R.id.container_public) Snackbar.make(view, R.string.note_create_message, Snackbar.LENGTH_INDEFINITE).setAction(R.string.toot_text) { mastodonStatusesPOST() }.show() } } catch (e: JSONException) { e.printStackTrace() } } } }) }).start() } /** * Uri→FileName */ private fun getFileNameUri(uri: Uri): String? { var file_name: String? = null val projection = arrayOf(MediaStore.MediaColumns.DISPLAY_NAME) val cursor = contentResolver.query(uri, projection, null, null, null) if (cursor != null) { if (cursor.moveToFirst()) { file_name = cursor.getString(0) } } return file_name } /* * Uri→FileName * Fileスキーム限定 * */ fun getFileSchemeFileName(uri: Uri): String? { //file://なので使える val file = File(uri.path) return file.name } /* * Uri→Extension * 拡張子取得。Kotlinだと楽だね! * */ fun getFileSchemeFileExtension(uri: Uri): String? { val file = File(uri.path) return file.extension } /** * Mastodon 投票 */ private fun createMastodonVote(): JSONObject { val `object` = JSONObject() try { //配列 val jsonArray = JSONArray() if (vote_1.text.toString() != null) { jsonArray.put(vote_1.text.toString()) } if (vote_2.text.toString() != null) { jsonArray.put(vote_2.text.toString()) } if (vote_3.text.toString() != null) { jsonArray.put(vote_3.text.toString()) } if (vote_4.text.toString() != null) { jsonArray.put(vote_4.text.toString()) } `object`.put("options", jsonArray) `object`.put("expires_in", vote_time.text.toString()) `object`.put("multiple", vote_multi_Switch.isChecked) //object.put("hide_totals", vote_hide_Switch.isChecked()); } catch (e: JSONException) { e.printStackTrace() } return `object` } /** * Mastodon 公開範囲 */ @SuppressLint("RestrictedApi") private fun setMastodonVisibilityMenu(button: ImageButton) { //ポップアップメニュー作成 val menuBuilder = MenuBuilder(this@Home) val inflater = MenuInflater(this@Home) inflater.inflate(R.menu.toot_area_menu, menuBuilder) val optionsMenu = MenuPopupHelper(this@Home, menuBuilder, button) optionsMenu.setForceShowIcon(true) //ポップアップメニューを展開する button.setOnClickListener { //表示 optionsMenu.show() //押したときの反応 menuBuilder.setCallback(object : MenuBuilder.Callback { override fun onMenuItemSelected(menuBuilder: MenuBuilder, menuItem: MenuItem): Boolean { //公開(全て) if (menuItem.title.toString().contains(getString(R.string.visibility_public))) { toot_area = "public" button.setImageDrawable(getDrawable(R.drawable.ic_public_black_24dp)) } //未収載(TL公開なし・誰でも見れる) if (menuItem.title.toString().contains(getString(R.string.visibility_unlisted))) { toot_area = "unlisted" button.setImageDrawable(getDrawable(R.drawable.ic_done_all_black_24dp)) } //非公開(フォロワー限定) if (menuItem.title.toString().contains(getString(R.string.visibility_private))) { toot_area = "private" button.setImageDrawable(getDrawable(R.drawable.ic_lock_open_black_24dp)) } //ダイレクト(指定したアカウントと自分) if (menuItem.title.toString().contains(getString(R.string.visibility_direct))) { toot_area = "direct" button.setImageDrawable(getDrawable(R.drawable.ic_assignment_ind_black_24dp)) } return false } override fun onMenuModeChange(menuBuilder: MenuBuilder) { } }) } } /** * Misskey 公開範囲 */ @SuppressLint("RestrictedApi") private fun setMisskeyVisibilityMenu(button: ImageButton) { //ポップアップメニュー作成 val menuBuilder = MenuBuilder(this@Home) val inflater = MenuInflater(this@Home) inflater.inflate(R.menu.misskey_visibility_menu, menuBuilder) val optionsMenu = MenuPopupHelper(this@Home, menuBuilder, button) optionsMenu.setForceShowIcon(true) //ポップアップメニューを展開する button.setOnClickListener { //表示 optionsMenu.show() //押したときの反応 menuBuilder.setCallback(object : MenuBuilder.Callback { override fun onMenuItemSelected(menuBuilder: MenuBuilder, menuItem: MenuItem): Boolean { //公開(全て) if (menuItem.title.toString().contains(getString(R.string.misskey_public))) { toot_area = "public" button.setImageDrawable(getDrawable(R.drawable.ic_public_black_24dp)) } //ホーム if (menuItem.title.toString().contains(getString(R.string.misskey_home))) { toot_area = "home" button.setImageDrawable(getDrawable(R.drawable.ic_home_black_24dp)) } //フォロワー限定 if (menuItem.title.toString().contains(getString(R.string.misskey_followers))) { toot_area = "followers" button.setImageDrawable(getDrawable(R.drawable.ic_person_add_black_24dp)) } //ダイレクト(指定したアカウントと自分) if (menuItem.title.toString().contains(getString(R.string.misskey_specified))) { toot_area = "specified" button.setImageDrawable(getDrawable(R.drawable.ic_assignment_ind_black_24dp)) } //公開(ローカルのみ) if (menuItem.title.toString().contains(getString(R.string.misskey_private))) { toot_area = "private" button.setImageDrawable(getDrawable(R.drawable.ic_public_black_24dp)) } return false } override fun onMenuModeChange(menuBuilder: MenuBuilder) { } }) } } /** * DatePicker */ private fun showDatePicker(textView: TextView) { val date = arrayOf("") val calendar = Calendar.getInstance() val dateBuilder = DatePickerDialog(this@Home, DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth -> var month = month var month_string = "" var day_string = "" //1-9月は前に0を入れる if (month++ <= 9) { month_string = "0" + month++.toString() } else { month_string = month++.toString() } //1-9日も前に0を入れる if (dayOfMonth <= 9) { day_string = "0$dayOfMonth" } else { day_string = dayOfMonth.toString() } post_date = year.toString() + month_string + day_string + "T" textView.text = post_date }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH) ) dateBuilder.show() } /** * TimePicker */ private fun showTimePicker(textView: TextView) { val calendar = Calendar.getInstance() val hour = calendar.get(Calendar.HOUR_OF_DAY) val minute = calendar.get(Calendar.MINUTE) val dialog = TimePickerDialog(this@Home, TimePickerDialog.OnTimeSetListener { view, hourOfDay, minute -> var hourOfDay = hourOfDay var hour_string = "" var minute_string = "" //1-9月は前に0を入れる if (hourOfDay <= 9) { hour_string = "0" + hourOfDay++.toString() } else { hour_string = hourOfDay++.toString() } //1-9日も前に0を入れる if (minute <= 9) { minute_string = "0$minute" } else { minute_string = minute.toString() } post_time = hour_string + minute_string + "00" + "+0900" textView.text = post_time }, hour, minute, true) dialog.show() } /** * TootShortcutShow */ private fun showTootShortcut() { val fragment = supportFragmentManager.findFragmentById(R.id.container_container) //CustomMenuTimeLine以外で投稿画面を開かないようにする if (fragment is DesktopFragment) { //DesktopModeはPopupMenuからMastodon/Misskeyを選ぶ //Misskeyアカウントが登録されていなければ話にならない if (pref_setting.getString("misskey_instance_list", "") != "") { //ポップアップメニュー作成 val sns_PopupMenu = PopupMenu(this, fab) sns_PopupMenu.inflate(R.menu.desktop_mode_sns_menu) //クリックイベント sns_PopupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.desktop_mode_menu_mastodon -> { getAccount() setMastodonVisibilityMenu(toot_area_Button) toot_Button_LinearLayout.removeView(misskey_drive_Button) toot_Button_LinearLayout.removeView(mastodon_time_post_Button) toot_Button_LinearLayout.removeView(mastodon_vote_Button) toot_Button_LinearLayout.removeView(paintPOSTButton) toot_Button_LinearLayout.addView(mastodon_time_post_Button) toot_Button_LinearLayout.addView(mastodon_vote_Button) toot_Button_LinearLayout.addView(paintPOSTButton) //デスクトップモード利用時はマルチアカウント表示できるように if (fragment != null && fragment is DesktopFragment) { showMultiAccount() } } R.id.desktop_mode_menu_misskey -> if (pref_setting.getString("misskey_instance_list", "") != "") { getMisskeyAccount() setMisskeyVisibilityMenu(toot_area_Button) toot_Button_LinearLayout.removeView(misskey_drive_Button) toot_Button_LinearLayout.removeView(mastodon_time_post_Button) toot_Button_LinearLayout.removeView(mastodon_vote_Button) toot_Button_LinearLayout.removeView(paintPOSTButton) toot_Button_LinearLayout.addView(misskey_drive_Button) //デスクトップモード利用時はマルチアカウント表示できるように if (fragment != null && fragment is DesktopFragment) { showMisskeyMultiAccount() } } } toot_snackbar.show() //ふぉーかす toot_EditText.requestFocus() //キーボード表示 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0) false } //すでにTootSnackberが表示されている場合は消して、ポップアップメニューを表示する if (toot_snackbar.isShown) { toot_snackbar.dismiss() //キーボード非表示 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if (imm != null) { if ([email protected] != null) { imm.hideSoftInputFromWindow([email protected]!!.windowToken, 0) } } sns_PopupMenu.show() } else { sns_PopupMenu.show() } } else { //Mastodonのみ表示 getAccount() setMastodonVisibilityMenu(toot_area_Button) toot_Button_LinearLayout.removeView(misskey_drive_Button) toot_Button_LinearLayout.removeView(mastodon_time_post_Button) toot_Button_LinearLayout.removeView(mastodon_vote_Button) toot_Button_LinearLayout.removeView(paintPOSTButton) toot_Button_LinearLayout.addView(mastodon_time_post_Button) toot_Button_LinearLayout.addView(mastodon_vote_Button) toot_Button_LinearLayout.addView(paintPOSTButton) //デスクトップモード利用時はマルチアカウント表示できるように if (fragment != null && fragment is DesktopFragment) { showMultiAccount() } if (!toot_snackbar.isShown) { toot_snackbar.show() //ふぉーかす toot_EditText.requestFocus() //キーボード表示 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0) } else { toot_snackbar.dismiss() //クローズでソフトキーボード非表示 fab.setImageDrawable(getDrawable(R.drawable.ic_create_black_24dp)) val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if (imm != null) { if ([email protected] != null) { imm.hideSoftInputFromWindow([email protected]!!.windowToken, 0) } } } } } else { //ユーザー情報を取得 //カスタムメニューが読み取り専用だったら動かないようにする if (fragment is CustomMenuTimeLine) { if (!fragment.isReadOnly()) { //MisskeyモードでMisskeyアカウントが登録されれいるときのみ表示 //避けたかったけどどうしてもisMisskeyMode()必要だから使う if (CustomMenuTimeLine.isMisskeyMode && pref_setting.getString("misskey_instance_list", "") != "") { shinchokuLayout.setOnDayProgress() getMisskeyAccount() setMisskeyVisibilityMenu(toot_area_Button) toot_Button_LinearLayout.removeView(misskey_drive_Button) toot_Button_LinearLayout.removeView(mastodon_time_post_Button) toot_Button_LinearLayout.removeView(mastodon_vote_Button) toot_Button_LinearLayout.removeView(paintPOSTButton) toot_Button_LinearLayout.addView(misskey_drive_Button) } else { //FAB押すたびにAPI叩くの直す //まずFragmentがCustomMenuTimeLineかどうか if (fragment is CustomMenuTimeLine) { if (tootSnackbarCustomMenuName.isEmpty()) { //初回 tootSnackbarCustomMenuName = (fragment as CustomMenuTimeLine).getCustomMenuName() } else if (!tootSnackbarCustomMenuName.contains((fragment as CustomMenuTimeLine).getCustomMenuName())) { //名前が同じじゃなかったらAPI叩く tootSnackbarCustomMenuName = (fragment as CustomMenuTimeLine).getCustomMenuName() getAccount() } } else { //API叩く getAccount() } shinchokuLayout.setOnDayProgress() setMastodonVisibilityMenu(toot_area_Button) toot_Button_LinearLayout.removeView(misskey_drive_Button) toot_Button_LinearLayout.removeView(mastodon_time_post_Button) toot_Button_LinearLayout.removeView(mastodon_vote_Button) toot_Button_LinearLayout.removeView(paintPOSTButton) toot_Button_LinearLayout.addView(mastodon_time_post_Button) toot_Button_LinearLayout.addView(mastodon_vote_Button) toot_Button_LinearLayout.addView(paintPOSTButton) } if (!toot_snackbar.isShown) { toot_snackbar.show() //ふぉーかす toot_EditText.requestFocus() //キーボード表示 val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0) } else { toot_snackbar.dismiss() //クローズでソフトキーボード非表示 fab.setImageDrawable(getDrawable(R.drawable.ic_create_black_24dp)) val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if (imm != null) { if ([email protected] != null) { imm.hideSoftInputFromWindow([email protected]!!.windowToken, 0) } } } } else { //読み取り専用だと投稿権限ないよ! Toast.makeText(this, getString(R.string.read_only_toot), Toast.LENGTH_SHORT).show() } } } } //カスタムメニュー設定ボタン //独立させよう fun setCustomMenuEditButton(): ImageView { //押したアニメーション val typedValue = TypedValue() theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, typedValue, true) val button = ImageView(this) button.setImageResource(R.drawable.ic_check_box_black_24dp) button.setBackgroundResource(typedValue.resourceId) button.imageTintList = ColorStateList.valueOf(Color.parseColor("#ffffff")) button.setPadding(50, 10, 50, 10) button.setOnClickListener { val fragment = supportFragmentManager.findFragmentById(R.id.container_container) if (fragment is CustomMenuTimeLine) { val customMenuBottomFragment = AddCustomMenuBottomFragment() val bundle = Bundle() bundle.putBoolean("delete_button", true) bundle.putString("name", fragment.customMenuJSONParse.name) customMenuBottomFragment.arguments = bundle customMenuBottomFragment.show(supportFragmentManager, "add_custom_menu") } } return button } /*タイムラインクイック設定ボタン生成*/ @SuppressLint("RestrictedApi") private fun setTimelinQuickSettings(): ImageView { //押したアニメーション val typedValue = TypedValue() theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, typedValue, true) val qs = ImageView(this) qs.setImageResource(R.drawable.ic_more_vert_black_24dp) qs.setBackgroundResource(typedValue.resourceId) qs.imageTintList = ColorStateList.valueOf(Color.parseColor("#ffffff")) qs.setPadding(50, 10, 50, 10) //回転する val objectAnimator = ObjectAnimator.ofFloat(qs, "rotation", 360f) objectAnimator.duration = 1000 qs.setOnClickListener { /* val drawable = qs.drawable if (drawable is Animatable) { (drawable as Animatable).start() (drawable as Animatable).start() } val list = ArrayList<String>() list.add(account_id) */ //回転アニメーション // objectAnimator.start() val bundle = Bundle() bundle.putString("account", account_id) val menuBottomSheetFragment = MenuBottomSheetFragment() menuBottomSheetFragment.arguments = bundle menuBottomSheetFragment.show(supportFragmentManager, "timeline_setting") /* tlQuickSettingSnackber!!.setList(list) if (tlQuickSettingSnackber!!.snackbar.isShown) { tlQuickSettingSnackber!!.dismissSnackBer() } else { tlQuickSettingSnackber!!.showSnackBer() } */ } return qs } companion object { //添付メディア lateinit var post_media_id: ArrayList<String> lateinit var misskey_media_url: ArrayList<String> fun getPathAndroidQ(context: Context, contentUri: Uri): String { var cursor: Cursor? = null val proj = arrayOf(MediaStore.Images.Media.DATA) cursor = context.contentResolver.query(contentUri, proj, null, null, null) var column_index = 0 var path = "" if (cursor != null) { column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA) cursor.moveToFirst() path = cursor.getString(column_index) cursor.close() } return path } } fun setAppBar() { toolBer = findViewById<View>(R.id.toolbar) as Toolbar fab = findViewById<View>(R.id.fab) as FloatingActionButton drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout val darkModeSupport = DarkModeSupport(this@Home) val fragment = supportFragmentManager.findFragmentById(R.id.container_container) if (pref_setting.getBoolean("pref_bottom_navigation", false)) { // 上のバーとFabをけす container_public.removeView(toolBer.parent as AppBarLayout) container_public.removeView(fab) layoutInflater.inflate(R.layout.bottom_bar_layout, container_public) setSupportActionBar(bottomAppBar) bottomAppBar.setNavigationOnClickListener() { drawer.openDrawer(Gravity.LEFT) } bottom_fab.setOnClickListener { val fragment = supportFragmentManager.findFragmentById(R.id.container_container) if (fragment is CustomMenuTimeLine) { //読み取り専用? if (!fragment.isReadOnly()) { if (tootCardView.cardView.visibility == View.VISIBLE) { tootCardView.cardViewHide() } else { tootCardView.cardViewShow() } } else { //読み取り専用だと投稿権限ないよ! Toast.makeText(this, getString(R.string.read_only_toot), Toast.LENGTH_SHORT).show() } } else if (fragment is DesktopFragment) { //デスクトップモードでも利用可能 if (tootCardView.cardView.visibility == View.VISIBLE) { tootCardView.cardViewHide() } else { tootCardView.cardViewShow() } } //showTootShortcut() } //一応代入 fab = bottom_fab //追加されてなければ追加 bottomAppBar.addView(setTimelinQuickSettings()) bottomAppBar.addView(setCustomMenuEditButton()) tlQuickSettingSnackber = TLQuickSettingSnackber(this@Home, navigationView) // ダークモード対応 if (darkModeSupport.nightMode == Configuration.UI_MODE_NIGHT_YES) { bottomAppBar.backgroundTintList = resources.getColorStateList(android.R.color.black, theme) //ナビゲーションバーの色を動的に変える window.navigationBarColor = getColor(R.color.black) //ActionBarの色設定 bottomAppBar.backgroundTint = ColorStateList.valueOf(Color.parseColor("#000000")) } else { //ナビゲーションバーの色を動的に変える window.navigationBarColor = getColor(R.color.colorPrimary) } } else { setSupportActionBar(toolBer) val toggle = ActionBarDrawerToggle( this, drawer, toolBer, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer.addDrawerListener(toggle) toggle.syncState() fab.setOnClickListener { val fragment = supportFragmentManager.findFragmentById(R.id.container_container) if (fragment is CustomMenuTimeLine) { //読み取り専用? if (!fragment.isReadOnly()) { if (tootCardView.cardView.visibility == View.VISIBLE) { tootCardView.cardViewHide() } else { tootCardView.cardViewShow() } } else { //読み取り専用だと投稿権限ないよ! Toast.makeText(this, getString(R.string.read_only_toot), Toast.LENGTH_SHORT).show() } } else if (fragment is DesktopFragment) { //デスクトップモードでも利用可能 if (tootCardView.cardView.visibility == View.VISIBLE) { tootCardView.cardViewHide() } else { tootCardView.cardViewShow() } } } /*クイック設定*/ toolBer.addView(setTimelinQuickSettings()) toolBer.addView(setCustomMenuEditButton()) tlQuickSettingSnackber = TLQuickSettingSnackber(this@Home, navigationView) //ActionBarの色設定 if (darkModeSupport.nightMode == Configuration.UI_MODE_NIGHT_YES) { toolBer.setBackgroundColor(Color.parseColor("#000000")) } } } fun isSnackbarShow(): Boolean { return toot_snackbar.isShown } }
1
null
1
1
98f8dd88deb68d749a5c44a7fca8bce6e8f3af39
147,670
Kaisendon
Apache License 2.0
networklibrary/src/main/java/com/lkl/networklibrary/https/consts/UriConsts.kt
BlankLun
99,202,905
false
null
package com.lkl.networklibrary.https.consts /** * Created likunlun * Time 2017/8/3 11:06 * Desc URI常量 */ object UriConsts { val BASE_URL = "http://192.168.2.235:8095/" }
0
Kotlin
8
18
dcb28860203248cd793a7f43094753e656b2c380
193
RxKotlinRetrofitDemo
Apache License 2.0
app/src/main/java/com/buchi/fullentry/movie/data/cache/MoviesAppDatabase.kt
SunnyBe
370,745,596
false
null
package com.buchi.fullentry.movie.data.cache import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [ MovieData::class ], version = 1, exportSchema = false) abstract class MoviesAppDatabase: RoomDatabase() { abstract fun moviesDao(): MovieDao }
0
Kotlin
1
0
f4c1d6c8067c4149d357a4ded6e6455b60b15156
285
MovieApp
The Unlicense
layout-ui/src/main/java/com/android/tools/property/panel/impl/table/DefaultValueTableCellRenderer.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.property.panel.impl.table import com.android.tools.property.ptable.PTable import com.android.tools.property.ptable.PTableCellRenderer import com.android.tools.property.ptable.PTableColumn import com.android.tools.property.ptable.PTableItem import com.intellij.ui.SimpleColoredComponent import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import javax.swing.JComponent class DefaultValueTableCellRenderer : SimpleColoredComponent(), PTableCellRenderer { override fun getEditorComponent(table: PTable, item: PTableItem, column: PTableColumn, depth: Int, isSelected: Boolean, hasFocus: Boolean, isExpanded: Boolean): JComponent { clear() setPaintFocusBorder(hasFocus) font = table.activeFont append(item.value.orEmpty()) if (isSelected && hasFocus) { foreground = UIUtil.getTableForeground(true, true) background = UIUtil.getTableBackground(true, true) } else { foreground = table.foregroundColor background = table.backgroundColor } border = JBUI.Borders.customLine(table.gridLineColor, 0, 1, 0, 0) return this } }
5
null
230
948
10110983c7e784122d94c7467e9d243aba943bf4
1,780
android
Apache License 2.0
core-data-disk/src/main/java/de/niklasbednarczyk/nbweather/core/data/disk/mappers/OneWayMapperDisk.kt
NiklasBednarczyk
529,683,941
false
null
package de.niklasbednarczyk.nbweather.core.data.disk.mappers interface OneWayMapperDisk<Proto, Disk> { fun protoToDisk(proto: Proto): Disk }
12
Kotlin
0
0
b9894a6739d699799aa2ab49f3d9218a97cfb7bc
147
NBWeather
MIT License
okhttp/src/jvmMain/kotlin/okhttp3/internal/platform/Jdk8WithJettyBootPlatform.kt
yschimke
42,286,486
false
null
/* * Copyright (C) 2016 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.platform import okhttp3.Protocol import java.lang.reflect.InvocationHandler import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.lang.reflect.Proxy import javax.net.ssl.SSLSocket /** OpenJDK 8 with `org.mortbay.jetty.alpn:alpn-boot` in the boot class path. */ class Jdk8WithJettyBootPlatform( private val putMethod: Method, private val getMethod: Method, private val removeMethod: Method, private val clientProviderClass: Class<*>, private val serverProviderClass: Class<*> ) : Platform() { override fun configureTlsExtensions( sslSocket: SSLSocket, hostname: String?, protocols: List<Protocol> ) { val names = alpnProtocolNames(protocols) try { val alpnProvider = Proxy.newProxyInstance(Platform::class.java.classLoader, arrayOf(clientProviderClass, serverProviderClass), AlpnProvider(names)) putMethod.invoke(null, sslSocket, alpnProvider) } catch (e: InvocationTargetException) { throw AssertionError("failed to set ALPN", e) } catch (e: IllegalAccessException) { throw AssertionError("failed to set ALPN", e) } } override fun afterHandshake(sslSocket: SSLSocket) { try { removeMethod.invoke(null, sslSocket) } catch (e: IllegalAccessException) { throw AssertionError("failed to remove ALPN", e) } catch (e: InvocationTargetException) { throw AssertionError("failed to remove ALPN", e) } } override fun getSelectedProtocol(socket: SSLSocket): String? { try { val provider = Proxy.getInvocationHandler(getMethod.invoke(null, socket)) as AlpnProvider if (!provider.unsupported && provider.selected == null) { Platform.get().log(INFO, "ALPN callback dropped: HTTP/2 is disabled. " + "Is alpn-boot on the boot class path?", null) return null } return if (provider.unsupported) null else provider.selected } catch (e: InvocationTargetException) { throw AssertionError("failed to get ALPN selected protocol", e) } catch (e: IllegalAccessException) { throw AssertionError("failed to get ALPN selected protocol", e) } } /** * Handle the methods of ALPN's ClientProvider and ServerProvider without a compile-time * dependency on those interfaces. */ private class AlpnProvider internal constructor( /** This peer's supported protocols. */ private val protocols: List<String> ) : InvocationHandler { /** Set when remote peer notifies ALPN is unsupported. */ internal var unsupported: Boolean = false /** The protocol the server selected. */ internal var selected: String? = null @Throws(Throwable::class) override fun invoke(proxy: Any, method: Method, args: Array<Any>?): Any? { val callArgs = args ?: arrayOf<Any?>() val methodName = method.name val returnType = method.returnType if (methodName == "supports" && Boolean::class.javaPrimitiveType == returnType) { return true // ALPN is supported. } else if (methodName == "unsupported" && Void.TYPE == returnType) { this.unsupported = true // Peer doesn't support ALPN. return null } else if (methodName == "protocols" && callArgs.isEmpty()) { return protocols // Client advertises these protocols. } else if ((methodName == "selectProtocol" || methodName == "select") && String::class.java == returnType && callArgs.size == 1 && callArgs[0] is List<*>) { val peerProtocols = callArgs[0] as List<*> // Pick the first known protocol the peer advertises. for (i in 0..peerProtocols.size) { val protocol = peerProtocols[i] as String if (protocol in protocols) { selected = protocol return selected } } selected = protocols[0] // On no intersection, try peer's first protocol. return selected } else if ((methodName == "protocolSelected" || methodName == "selected") && callArgs.size == 1) { this.selected = callArgs[0] as String // Server selected this protocol. return null } else { return method.invoke(this, *callArgs) } } } companion object { fun buildIfSupported(): Platform? { val jvmVersion = System.getProperty("java.specification.version", "unknown") try { // 1.8, 9, 10, 11, 12 etc val version = jvmVersion.toInt() if (version >= 9) return null } catch (nfe: NumberFormatException) { // expected on >= JDK 9 } // Find Jetty's ALPN extension for OpenJDK. try { val alpnClassName = "org.eclipse.jetty.alpn.ALPN" val alpnClass = Class.forName(alpnClassName, true, null) val providerClass = Class.forName("$alpnClassName\$Provider", true, null) val clientProviderClass = Class.forName("$alpnClassName\$ClientProvider", true, null) val serverProviderClass = Class.forName("$alpnClassName\$ServerProvider", true, null) val putMethod = alpnClass.getMethod("put", SSLSocket::class.java, providerClass) val getMethod = alpnClass.getMethod("get", SSLSocket::class.java) val removeMethod = alpnClass.getMethod("remove", SSLSocket::class.java) return Jdk8WithJettyBootPlatform( putMethod, getMethod, removeMethod, clientProviderClass, serverProviderClass) } catch (ignored: ClassNotFoundException) { } catch (ignored: NoSuchMethodException) { } return null } } }
2
null
9159
6
ef459b1d8b0530c915386c527e8a141c88cd5c15
6,170
okhttp
Apache License 2.0
fir/src/org/jetbrains/kotlin/idea/fir/api/fixes/HLDiagnosticFixFactory.kt
JetBrains
278,369,660
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.api.fixes import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.idea.api.applicator.HLApplicator import org.jetbrains.kotlin.idea.api.applicator.HLApplicatorInput import org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession import org.jetbrains.kotlin.idea.frontend.api.diagnostics.KtDiagnosticWithPsi import org.jetbrains.kotlin.idea.quickfix.QuickFixActionBase import kotlin.reflect.KClass sealed class HLDiagnosticFixFactory<DIAGNOSTIC : KtDiagnosticWithPsi<*>> { abstract fun KtAnalysisSession.createQuickFixes(diagnostic: DIAGNOSTIC): List<QuickFixActionBase<*>> abstract val diagnosticClass: KClass<DIAGNOSTIC> } private class HLDiagnosticFixFactoryWithFixedApplicator<DIAGNOSTIC : KtDiagnosticWithPsi<*>, TARGET_PSI : PsiElement, INPUT : HLApplicatorInput>( override val diagnosticClass: KClass<DIAGNOSTIC>, private val applicator: HLApplicator<TARGET_PSI, INPUT>, private val createTargets: KtAnalysisSession.(DIAGNOSTIC) -> List<HLApplicatorTargetWithInput<TARGET_PSI, INPUT>>, ) : HLDiagnosticFixFactory<DIAGNOSTIC>() { override fun KtAnalysisSession.createQuickFixes(diagnostic: DIAGNOSTIC): List<HLQuickFix<TARGET_PSI, INPUT>> = createTargets.invoke(this, diagnostic).map { (target, input) -> HLQuickFix(target, input, applicator) } } private class HLDiagnosticFixFactoryUsingQuickFixActionBase<DIAGNOSTIC : KtDiagnosticWithPsi<*>>( override val diagnosticClass: KClass<DIAGNOSTIC>, private val createQuickFixes: KtAnalysisSession.(DIAGNOSTIC) -> List<QuickFixActionBase<*>> ) : HLDiagnosticFixFactory<DIAGNOSTIC>() { override fun KtAnalysisSession.createQuickFixes(diagnostic: DIAGNOSTIC): List<QuickFixActionBase<*>> = createQuickFixes.invoke(this, diagnostic) } internal fun <DIAGNOSTIC : KtDiagnosticWithPsi<PsiElement>> KtAnalysisSession.createPlatformQuickFixes( diagnostic: DIAGNOSTIC, factory: HLDiagnosticFixFactory<DIAGNOSTIC> ): List<IntentionAction> = with(factory) { createQuickFixes(diagnostic) } /** * Returns a [HLDiagnosticFixFactory] that creates targets and inputs ([HLApplicatorTargetWithInput]) from a diagnostic. * The targets and inputs are consumed by the given applicator to apply fixes. */ fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>, TARGET_PSI : PsiElement, INPUT : HLApplicatorInput> diagnosticFixFactory( diagnosticClass: KClass<DIAGNOSTIC>, applicator: HLApplicator<TARGET_PSI, INPUT>, createTargets: KtAnalysisSession.(DIAGNOSTIC) -> List<HLApplicatorTargetWithInput<TARGET_PSI, INPUT>> ): HLDiagnosticFixFactory<DIAGNOSTIC> = HLDiagnosticFixFactoryWithFixedApplicator(diagnosticClass, applicator, createTargets) /** * Returns a [HLDiagnosticFixFactory] that creates [QuickFixActionBase]s from a diagnostic. */ fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>> diagnosticFixFactory( diagnosticClass: KClass<DIAGNOSTIC>, createQuickFixes: KtAnalysisSession.(DIAGNOSTIC) -> List<QuickFixActionBase<*>> ): HLDiagnosticFixFactory<DIAGNOSTIC> = HLDiagnosticFixFactoryUsingQuickFixActionBase(diagnosticClass, createQuickFixes) /** * Returns a [Collection] of [HLDiagnosticFixFactory] that creates [QuickFixActionBase]s from diagnostics that have the same type of * [PsiElement]. */ fun <DIAGNOSTIC_PSI : PsiElement, DIAGNOSTIC : KtDiagnosticWithPsi<DIAGNOSTIC_PSI>> diagnosticFixFactories( vararg diagnosticClasses: KClass<out DIAGNOSTIC>, createQuickFixes: KtAnalysisSession.(DIAGNOSTIC) -> List<QuickFixActionBase<*>> ): Collection<HLDiagnosticFixFactory<out DIAGNOSTIC>> = diagnosticClasses.map { HLDiagnosticFixFactoryUsingQuickFixActionBase(it, createQuickFixes) } /** * Returns a [HLDiagnosticFixFactory] that creates [IntentionAction]s from a diagnostic. */ fun <DIAGNOSTIC : KtDiagnosticWithPsi<*>> diagnosticFixFactoryFromIntentionActions( diagnosticClass: KClass<DIAGNOSTIC>, createIntentionActions: KtAnalysisSession.(DIAGNOSTIC) -> List<IntentionAction> ): HLDiagnosticFixFactory<DIAGNOSTIC> { // Wrap the IntentionActions as QuickFixActionBase. This ensures all fixes are of type QuickFixActionBase. val createQuickFixes: KtAnalysisSession.(DIAGNOSTIC) -> List<QuickFixActionBase<*>> = { diagnostic -> val intentionActions = createIntentionActions.invoke(this, diagnostic) intentionActions.map { IntentionActionAsQuickFixWrapper(it, diagnostic.psi) } } return HLDiagnosticFixFactoryUsingQuickFixActionBase(diagnosticClass, createQuickFixes) } /** * Returns a [Collection] of [HLDiagnosticFixFactory] that creates [IntentionAction]s from diagnostics that have the same type of * [PsiElement]. */ fun <DIAGNOSTIC_PSI : PsiElement, DIAGNOSTIC : KtDiagnosticWithPsi<DIAGNOSTIC_PSI>> diagnosticFixFactoriesFromIntentionActions( vararg diagnosticClasses: KClass<out DIAGNOSTIC>, createIntentionActions: KtAnalysisSession.(DIAGNOSTIC) -> List<IntentionAction> ): Collection<HLDiagnosticFixFactory<out DIAGNOSTIC>> = diagnosticClasses.map { diagnosticFixFactoryFromIntentionActions(it, createIntentionActions) } private class IntentionActionAsQuickFixWrapper<T : PsiElement>(val intentionAction: IntentionAction, element: T) : QuickFixActionBase<T>(element) { override fun getText(): String = intentionAction.text override fun getFamilyName(): String = intentionAction.familyName override fun invoke(project: Project, editor: Editor?, file: PsiFile?) = intentionAction.invoke(project, editor, file) }
191
null
4372
82
cc81d7505bc3e9ad503d706998ae8026c067e838
5,861
intellij-kotlin
Apache License 2.0
app/src/main/java/com/workbook/liuwb/workbook/actions/service/bind/messengerdemo/ActivityMessenger.kt
bobo-lwenb
224,773,966
false
null
package com.workbook.liuwb.workbook.actions.service.bind.messengerdemo import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.* import android.view.View import androidx.appcompat.app.AppCompatActivity import com.workbook.liuwb.workbook.databinding.ActivityMessengerDemoBinding class ActivityMessenger : AppCompatActivity() { private val binding: ActivityMessengerDemoBinding by lazy { ActivityMessengerDemoBinding.inflate(layoutInflater) } /** Messenger for communicating with the service. */ private var mService: Messenger? = null /** Flag indicating whether we have called bind on the service. */ private var bound: Boolean = false /** * Class for interacting with the main interface of the service. */ private val mConnection = object : ServiceConnection { override fun onServiceConnected(className: ComponentName, service: IBinder) { // This is called when the connection with the service has been // established, giving us the object we can use to // interact with the service. We are communicating with the // service using a Messenger, so here we get a client-side // representation of that from the raw IBinder object. mService = Messenger(service) bound = true } override fun onServiceDisconnected(className: ComponentName) { // This is called when the connection with the service has been // unexpectedly disconnected -- that is, its process crashed. mService = null bound = false } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) } override fun onStart() { super.onStart() // Bind to the service Intent(this, MessengerService::class.java).also { intent -> bindService(intent, mConnection, Context.BIND_AUTO_CREATE) } } override fun onStop() { super.onStop() // Unbind from the service if (bound) { unbindService(mConnection) bound = false } } fun sayHello(v: View) { if (!bound) return // Create and send a message to the service, using a supported 'what' value val msg: Message = Message.obtain(null, MSG_SAY_HELLO, 0, 0) try { mService?.send(msg) } catch (e: RemoteException) { e.printStackTrace() } } }
0
Kotlin
0
0
9057c0ed87d0241a7704c7dfb9e285a378c2224e
2,642
WorkBook
Apache License 2.0
examples/codeviewer/common/src/commonMain/kotlin/org/jetbrains/codeviewer/ui/common/Theme.kt
JetBrains
293,498,508
false
null
package org.jetbrains.codeviewer.ui.common import androidx.compose.material.darkColors import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.SpanStyle object AppTheme { val colors: Colors = Colors() val code: Code = Code() class Colors( val backgroundDark: Color = Color(0xFF2B2B2B), val backgroundMedium: Color = Color(0xFF3C3F41), val backgroundLight: Color = Color(0xFF4E5254), val material: androidx.compose.material.Colors = darkColors( background = backgroundDark, surface = backgroundMedium, primary = Color.White ), ) class Code( val simple: SpanStyle = SpanStyle(Color(0xFFA9B7C6)), val value: SpanStyle = SpanStyle(Color(0xFF6897BB)), val keyword: SpanStyle = SpanStyle(Color(0xFFCC7832)), val punctuation: SpanStyle = SpanStyle(Color(0xFFA1C17E)), val annotation: SpanStyle = SpanStyle(Color(0xFFBBB529)), val comment: SpanStyle = SpanStyle(Color(0xFF808080)) ) }
668
null
645
9,090
97266a0ac8c0d7a8ad8d19ead1c925751a00ff1c
1,048
compose-jb
Apache License 2.0
demo3/app/src/main/java/com/mokelab/demo/sdldemo3/MainActivity.kt
mokelab
206,254,208
false
null
package com.mokelab.demo.sdldemo3 import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val it = Intent(this, MySDLService::class.java) startService(it) } }
0
Kotlin
0
0
2925ce2deb96f1df273743af9e5da42ec964a8f8
420
sdl-demo2019
Apache License 2.0
src/main/kotlin/elan/tweaks/thaumcraft/research/frontend/domain/model/AspectTree.kt
GTNewHorizons
415,049,798
false
null
package elan.tweaks.thaumcraft.research.frontend.domain.model import elan.tweaks.thaumcraft.research.frontend.domain.ports.provided.AspectsTreePort import thaumcraft.api.aspects.Aspect import kotlin.math.absoluteValue object AspectTree : AspectsTreePort { private val orderedBalance = findBalance() override fun toString(): String = "AspectTree: $orderedBalance" private fun findBalance(): OrderedBalance { val (aspectToOrder, affinityToOrder, affinityToEntropy) = findOrderAndAffinities() val (definiteOrder, definiteEntropy) = balance(affinityToOrder, affinityToEntropy) return OrderedBalance( aspectToOrder = aspectToOrder, orderLeaning = definiteOrder.sortedBy(aspectToOrder::getValue), entropyLeaning = definiteEntropy.sortedBy(aspectToOrder::getValue) ) } private fun findOrderAndAffinities(): Triple<MutableMap<Aspect, Int>, MutableMap<Aspect, Float>, MutableMap<Aspect, Float>> { val descendants = mutableMapOf<Aspect, MutableSet<Aspect>>() Aspect.getCompoundAspects().forEach { aspect -> descendants.getOrPut(aspect.components[0], ::mutableSetOf) += aspect descendants.getOrPut(aspect.components[1], ::mutableSetOf) += aspect } val aspectToOrder = mutableMapOf<Aspect, Int>( Aspect.ORDER to 10, Aspect.EARTH to 12, Aspect.WATER to 14, Aspect.ENTROPY to 11, Aspect.FIRE to 13, Aspect.AIR to 15, ) val affinityToOrder = mutableMapOf( Aspect.ORDER to 1f, Aspect.EARTH to 1f, Aspect.WATER to 1f, Aspect.ENTROPY to 0f, Aspect.FIRE to 0f, Aspect.AIR to 0f, ) val affinityToEntropy = mutableMapOf( Aspect.ORDER to 0f, Aspect.EARTH to 0f, Aspect.WATER to 0f, Aspect.ENTROPY to 1f, Aspect.FIRE to 1f, Aspect.AIR to 1f, ) var unorderedAspects = Aspect.getPrimalAspects().flatMap(descendants::getValue).toSet() while (unorderedAspects.isNotEmpty()) { val (orderDerivable, orderNotYetDerivable) = unorderedAspects.partition { it.components[0] in aspectToOrder && it.components[1] in aspectToOrder } aspectToOrder += orderDerivable.associateWith { aspect -> aspectToOrder.getValue(aspect.components[0]) + aspectToOrder.getValue(aspect.components[1]) } affinityToOrder += orderDerivable.associateWith { aspect -> (affinityToOrder.getValue(aspect.components[0]) + affinityToOrder.getValue(aspect.components[1])) / 2 } affinityToEntropy += orderDerivable.associateWith { aspect -> (affinityToEntropy.getValue(aspect.components[0]) + affinityToEntropy.getValue(aspect.components[1])) / 2 } unorderedAspects = orderNotYetDerivable.toSet() + orderDerivable.flatMap { descendants[it] ?: emptySet() }.filterNot { it in aspectToOrder } } return Triple(aspectToOrder, affinityToOrder, affinityToEntropy) } private fun balance( affinityToOrder: MutableMap<Aspect, Float>, affinityToEntropy: MutableMap<Aspect, Float> ): Pair<MutableSet<Aspect>, MutableSet<Aspect>> { val definiteOrder = affinityToOrder.filter { (key, orderAffinity) -> orderAffinity > affinityToEntropy.getValue(key) }.keys.toMutableSet() val definiteEntropy = affinityToEntropy.filter { (key, entropyAffinity) -> entropyAffinity > affinityToOrder.getValue(key) }.keys.toMutableSet() val balanced = affinityToOrder.filter { (key, orderAffinity) -> orderAffinity == affinityToEntropy.getValue(key) }.keys.toMutableSet() val delta = definiteOrder.size - definiteEntropy.size when { delta > 0 -> { val additionToEntropy = balanced.take(delta) definiteEntropy += additionToEntropy balanced -= additionToEntropy } delta < 0 -> { val additionToOrder = balanced.take(delta.absoluteValue) definiteOrder += additionToOrder balanced -= additionToOrder } } definiteOrder += balanced.toList().take(balanced.size / 2) definiteEntropy += balanced.toList().drop(balanced.size / 2) return Pair(definiteOrder, definiteEntropy) } override fun orderOf(aspect: Aspect): Int = orderedBalance.aspectToOrder[aspect] ?: Int.MAX_VALUE override fun allOrderLeaning(): List<Aspect> = orderedBalance.orderLeaning override fun allEntropyLeaning(): List<Aspect> = orderedBalance.entropyLeaning override fun areRelated(first: Aspect, second: Aspect): Boolean = when { first.isPrimal && second.isPrimal -> false first.isPrimal -> first in second.getComponentsOrEmpty() second.isPrimal -> second in first.getComponentsOrEmpty() else -> first in second.getComponentsOrEmpty() || second in first.getComponentsOrEmpty() } private fun Aspect.getComponentsOrEmpty() = components ?: emptyComponents private val emptyComponents = emptyArray<Aspect>() data class OrderedBalance( val aspectToOrder: Map<Aspect, Int>, val orderLeaning: List<Aspect>, val entropyLeaning: List<Aspect> ) }
0
Kotlin
3
9
13848ec93311687aeb071dcabb390fbb8fbf89ee
5,501
thaumcraft-research-tweaks
MIT License
compose/src/test/java/com/kizitonwose/calendar/compose/StateSaverTest.kt
kizitonwose
182,417,603
false
{"Kotlin": 670112, "HTML": 343, "CSS": 102}
package com.kizitonwose.calendar.compose import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.SaverScope import androidx.compose.runtime.saveable.listSaver import com.kizitonwose.calendar.compose.heatmapcalendar.HeatMapCalendarState import com.kizitonwose.calendar.compose.weekcalendar.WeekCalendarState import com.kizitonwose.calendar.compose.yearcalendar.YearCalendarState import com.kizitonwose.calendar.core.OutDateStyle import com.kizitonwose.calendar.core.Year import com.kizitonwose.calendar.core.YearMonth import com.kizitonwose.calendar.core.now import com.kizitonwose.calendar.data.VisibleItemState import kotlinx.datetime.DayOfWeek import kotlinx.datetime.LocalDate import kotlin.js.JsName import kotlin.test.Test import kotlin.test.assertEquals /** * The states use the [listSaver] type so these tests should catch when we move * things around without paying attention to the indices or the actual items * being saved. Such issues are typically not caught during development since * state restoration (e.g via rotation) will likely not happen often. */ class StateSaverTest { @Test @JsName("test1") fun `month calendar state can be restored`() { val now = YearMonth.now() val firstDayOfWeek = DayOfWeek.entries.random() val outDateStyle = OutDateStyle.entries.random() val state = CalendarState( startMonth = now, endMonth = now, firstVisibleMonth = now, outDateStyle = outDateStyle, firstDayOfWeek = firstDayOfWeek, visibleItemState = VisibleItemState(), ) val restored = restore(state, CalendarState.Saver) assertEquals(state.startMonth, restored.startMonth) assertEquals(state.endMonth, restored.endMonth) assertEquals(state.firstVisibleMonth, restored.firstVisibleMonth) assertEquals(state.outDateStyle, restored.outDateStyle) assertEquals(state.firstDayOfWeek, restored.firstDayOfWeek) } @Test @JsName("test2") fun `week calendar state can be restored`() { val now = LocalDate.now() val firstDayOfWeek = DayOfWeek.entries.random() val state = WeekCalendarState( startDate = now, endDate = now, firstVisibleWeekDate = now, firstDayOfWeek = firstDayOfWeek, visibleItemState = VisibleItemState(), ) val restored = restore(state, WeekCalendarState.Saver) assertEquals(state.startDate, restored.startDate) assertEquals(state.endDate, restored.endDate) assertEquals(state.firstVisibleWeek, restored.firstVisibleWeek) assertEquals(state.firstDayOfWeek, restored.firstDayOfWeek) } @Test @JsName("test3") fun `heatmap calendar state can be restored`() { val now = YearMonth.now() val firstDayOfWeek = DayOfWeek.entries.random() val state = HeatMapCalendarState( startMonth = now, endMonth = now, firstVisibleMonth = now, firstDayOfWeek = firstDayOfWeek, visibleItemState = VisibleItemState(), ) val restored = restore(state, HeatMapCalendarState.Saver) assertEquals(state.startMonth, restored.startMonth) assertEquals(state.endMonth, restored.endMonth) assertEquals(state.firstVisibleMonth, restored.firstVisibleMonth) assertEquals(state.firstDayOfWeek, restored.firstDayOfWeek) } @Test @JsName("test4") fun `year calendar state can be restored`() { val now = Year.now() val firstDayOfWeek = DayOfWeek.entries.random() val outDateStyle = OutDateStyle.entries.random() val state = YearCalendarState( startYear = now, endYear = now, firstVisibleYear = now, firstDayOfWeek = firstDayOfWeek, outDateStyle = outDateStyle, visibleItemState = VisibleItemState(), ) val restored = restore(state, YearCalendarState.Saver) assertEquals(state.startYear, restored.startYear) assertEquals(state.endYear, restored.endYear) assertEquals(state.firstVisibleYear, restored.firstVisibleYear) assertEquals(state.firstDayOfWeek, restored.firstDayOfWeek) } private fun <State, T : Any> restore(value: State, saver: Saver<State, T>): State { with(saver) { val saved = SaverScope { true }.save(value)!! return restore(saved)!! } } }
13
Kotlin
505
4,651
36de800a6c36a8f142f6432a0992e0ea4ae8a789
4,551
Calendar
MIT License
app/src/main/java/com/tktkokym/currencyviewer/AppApplication.kt
TktkOkym
205,659,017
false
null
package com.tktkokym.currencyviewer import android.app.Application import android.os.StrictMode import com.tktkokym.currencyviewer.di.appModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.logger.Level class AppApplication : Application() { override fun onCreate() { super.onCreate() StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()) StrictMode.setVmPolicy( StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()) startKoin { androidLogger(level = Level.DEBUG) androidContext(this@AppApplication) modules(appModule) } } }
0
Kotlin
0
0
78235ce1e09a9a93becca33232e48b49ead31e43
1,118
CurrencyViewer
Apache License 2.0
src/main/kotlin/br/com/zup/chavepix/client/BcbClient.kt
natyff
385,923,261
true
{"Kotlin": 59542}
package br.com.zup.chavepix.client import br.com.zup.chavepix.dto.ChavePixDetalhe import br.com.zup.chavepix.entities.ChavePix import br.com.zup.chavepix.entities.ContaAssociada import br.com.zup.chavepix.enums.TipoConta import br.com.zup.chavepix.enums.TipoDeChave import io.micronaut.http.HttpResponse import io.micronaut.http.MediaType import io.micronaut.http.annotation.* import io.micronaut.http.client.annotation.Client import java.time.LocalDateTime @Client(value = "http://localhost:8082/") interface BcbClient { @Post("/api/v1/pix/keys", produces = [MediaType.APPLICATION_XML], consumes = [MediaType.APPLICATION_XML] ) fun create(@Body request: CriaChavePixRequest): HttpResponse<CriaChavePixResponse> @Delete("/api/v1/pix/keys/{key}", produces = [MediaType.APPLICATION_XML], consumes = [MediaType.APPLICATION_XML] ) fun delete(@PathVariable chave: String, @Body request: DeleteChavePixRequest): HttpResponse<DeleteChavePixResponse> @Get("/api/v1/pix/keys/{key}", consumes = [MediaType.APPLICATION_XML] ) fun findByChave(@PathVariable key: String): HttpResponse<DetalhePixResponse> data class DetalhePixResponse( val keyType: PixKeyType, val key: String, val bankAccount: BankAccount, val owner: Owner, val createdAt: LocalDateTime ) { fun converter(): ChavePixDetalhe { return ChavePixDetalhe( chave = key, tipoChave = keyType.domainType!!, tipoConta = when(this.bankAccount.accountType){ BankAccount.AccountType.CACC -> TipoConta.CONTA_CORRENTE BankAccount.AccountType.SVGS -> TipoConta.CONTA_POUPANCA }, conta = ContaAssociada( instituicao = bankAccount.participant, nomeTitular = owner.name, cpf = owner.taxIdNumber, agencia = bankAccount.branch, numeroConta = bankAccount.accountNumber ), criadoEm = createdAt ) } } data class CriaChavePixRequest( val keyType: PixKeyType, val key: String, val bankAccount: BankAccount, val owner: Owner ){ companion object { fun of(chave: ChavePix): CriaChavePixRequest { return CriaChavePixRequest( keyType = PixKeyType.by(chave.tipoChave), key = chave.chave, bankAccount = BankAccount( participant = ContaAssociada.ITAU_UNIBANCO_ISPB, branch = chave.conta.agencia, accountNumber = chave.conta.numeroConta, accountType = BankAccount.AccountType.by(chave.tipoConta), ), owner = Owner( type = Owner.OwnerType.NATURAL_PERSON, name = chave.conta.nomeTitular, taxIdNumber = chave.conta.cpf ) ) } } } data class CriaChavePixResponse ( val keyType: PixKeyType, val key: String, val bankAccount: BankAccount, val owner: Owner, val createdAt: LocalDateTime ) data class DeleteChavePixRequest( val key: String, val participant: String = ContaAssociada.ITAU_UNIBANCO_ISPB, ) data class DeleteChavePixResponse( val key: String, val participant: String, val deletedAt: LocalDateTime ) data class Owner( val type: OwnerType, val name: String, val taxIdNumber: String ) { enum class OwnerType { NATURAL_PERSON, LEGAL_PERSON } } data class BankAccount( val participant: String, val branch: String, val accountNumber: String, val accountType: AccountType ) { enum class AccountType() { CACC, // conta Corrente SVGS; // conta poupanca companion object { fun by(domainType: TipoConta): AccountType { return when (domainType) { TipoConta.CONTA_CORRENTE -> CACC TipoConta.CONTA_POUPANCA -> SVGS } } } } } enum class PixKeyType(val domainType: TipoDeChave?) { CPF(TipoDeChave.CPF), CNPJ(null), PHONE(TipoDeChave.CELULAR), EMAIL(TipoDeChave.EMAIL), RANDOM(TipoDeChave.ALEATORIA); companion object { private val mapping = PixKeyType.values().associateBy(PixKeyType::domainType) fun by(domainType: TipoDeChave): PixKeyType { return mapping[domainType] ?: throw IllegalArgumentException("Tipo de chave PIX é invalido ou não foi encontrado $domainType") } } } }
0
Kotlin
0
0
27d4b34bc7d65a5e9b5045cb01505f3d9aabf75d
4,606
orange-talents-05-template-pix-keymanager-grpc
Apache License 2.0
src/main/kotlin/icu/windea/pls/config/cwt/expression/CwtLocalisationLocationExpression.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.config.cwt.expression import com.google.common.cache.* import com.intellij.openapi.project.* import icu.windea.pls.* import icu.windea.pls.config.core.* import icu.windea.pls.config.core.config.* import icu.windea.pls.core.* import icu.windea.pls.core.search.* import icu.windea.pls.core.selector.chained.* import icu.windea.pls.localisation.psi.* import icu.windea.pls.script.psi.* private val validValueTypes = arrayOf( CwtDataType.Localisation, CwtDataType.SyncedLocalisation, CwtDataType.InlineLocalisation ) /** * CWT本地化的位置表达式。 * * 用于推断定义的相关本地化(relatedLocation)的位置。 * * 示例:`"$"`, `"$_desc"`, `"#title"` * @property placeholder 占位符(表达式文本包含"$"时,为整个字符串,"$"会在解析时替换成定义的名字,如果定义是匿名的,则忽略此表达式)。 * @property propertyName 属性名(表达式文本以"#"开始时,为"#"之后的子字符串,可以为空字符串)。 */ class CwtLocalisationLocationExpression( expressionString: String, val placeholder: String? = null, val propertyName: String? = null ) : AbstractExpression(expressionString), CwtExpression { companion object Resolver { val EmptyExpression = CwtLocalisationLocationExpression("", "") val cache by lazy { CacheBuilder.newBuilder().buildCache<String, CwtLocalisationLocationExpression> { doResolve(it) } } fun resolve(expressionString: String) = cache.getUnchecked(expressionString) private fun doResolve(expressionString: String) = when { expressionString.isEmpty() -> EmptyExpression expressionString.startsWith('#') -> { val propertyName = expressionString.substring(1) CwtLocalisationLocationExpression(expressionString, null, propertyName) } else -> CwtLocalisationLocationExpression(expressionString, expressionString) } } operator fun component1() = placeholder operator fun component2() = propertyName fun resolvePlaceholder(name: String): String? { if(placeholder == null) return null return buildString { for(c in placeholder) if(c == '$') append(name) else append(c) } } data class ResolveResult( val key: String, val localisation: ParadoxLocalisationProperty?, val message: String? = null ) /** * @return (localisationKey, localisation, message) */ fun resolve(definition: ParadoxScriptDefinitionElement, definitionInfo: ParadoxDefinitionInfo, project: Project, selector: ChainedParadoxSelector<ParadoxLocalisationProperty>): ResolveResult? { if(placeholder != null) { //如果定义是匿名的,则直接忽略 if(definitionInfo.isAnonymous) return null val key = resolvePlaceholder(definitionInfo.name)!! val localisation = ParadoxLocalisationSearch.search(key, project, selector = selector).find() return ResolveResult(key, localisation) } else if(propertyName != null) { val property = definition.findProperty(propertyName, inline = true) ?: return null val propertyValue = property.propertyValue ?: return null val config = ParadoxCwtConfigHandler.resolveValueConfigs(propertyValue, orDefault = false).firstOrNull() ?: return null if(config.expression.type !in validValueTypes) { return ResolveResult("", null, PlsDocBundle.message("dynamic")) } if(config.expression.type == CwtDataType.InlineLocalisation && propertyValue.text.isLeftQuoted()) { return ResolveResult("", null, PlsDocBundle.message("inlined")) } val key = propertyValue.value val localisation = ParadoxLocalisationSearch.search(key, project, selector = selector).find() return ResolveResult(key, localisation) } else { return null //不期望的结果 } } data class ResolveAllResult( val key: String, val localisations: Set<ParadoxLocalisationProperty>, val message: String? = null ) fun resolveAll(definitionName: String, definition: ParadoxScriptDefinitionElement, project: Project, selector: ChainedParadoxSelector<ParadoxLocalisationProperty>): ResolveAllResult? { if(placeholder != null) { val key = resolvePlaceholder(definitionName)!! val localisations = ParadoxLocalisationSearch.search(key, project, selector = selector).findAll() return ResolveAllResult(key, localisations) } else if(propertyName != null) { val property = definition.findProperty(propertyName, inline = true) ?: return null val propertyValue = property.propertyValue ?: return null val config = ParadoxCwtConfigHandler.resolveValueConfigs(propertyValue, orDefault = false).firstOrNull() ?: return null if(config.expression.type !in validValueTypes) { return ResolveAllResult("", emptySet(), PlsDocBundle.message("dynamic")) } if(config.expression.type == CwtDataType.InlineLocalisation && propertyValue.text.isLeftQuoted()) { return ResolveAllResult("", emptySet(), PlsDocBundle.message("inlined")) } val key = propertyValue.value val localisations = ParadoxLocalisationSearch.search(key, project, selector = selector).findAll() return ResolveAllResult(key, localisations) } else { return null //不期望的结果 } } }
2
Kotlin
2
13
97b0df8a6c176e97d239a0a4be9a451e70a44777
5,463
Paradox-Language-Support
MIT License
app/src/main/java/com/azamovhudstc/androidkeylogger/model/LocationData.kt
professorDeveloper
776,363,791
false
{"Kotlin": 91542}
package com.azamovhudstc.androidkeylogger.model data class LocationData( val latitude: Double, val longitude: Double, val accuracy: Float )
0
Kotlin
0
1
cc5c15e76e8f8a9a256c8e7a3a6ac1f0ef207fc0
152
Android-KeyLogger
MIT License
extensions/intellij/intellij_generator_plugin/src/main/java/com/bloc/intellij_generator_plugin/generator/components/CubitGenerator.kt
felangel
151,977,818
false
null
package com.bloc.intellij_generator_plugin.generator.components import com.bloc.intellij_generator_plugin.generator.CubitGenerator class CubitGenerator( name: String, useEquatable: Boolean ) : CubitGenerator(name, useEquatable, templateName = "cubit") { override fun fileName() = "${snakeCase()}_cubit.${fileExtension()}" }
65
Dart
2481
8,582
b6c55144e6c37c57100cf5be1125dca8bcc05b48
337
bloc
MIT License
mobile_app1/module555/src/main/java/module555packageKt0/Foo73.kt
uber-common
294,831,672
false
null
package module555packageKt0; annotation class Foo73Fancy @Foo73Fancy class Foo73 { fun foo0(){ module555packageKt0.Foo72().foo2() } fun foo1(){ foo0() } fun foo2(){ foo1() } }
6
null
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
203
android-build-eval
Apache License 2.0
workflix/backend/backend/src/main/kotlin/de/se/team3/webservice/handlers/ProcessTemplatesHandler.kt
elite-se
221,695,449
false
{"JavaScript": 227922, "Kotlin": 209131, "HTML": 6665, "CSS": 238}
package de.se.team3.webservice.handlers import de.se.team3.logic.container.ProcessTemplatesContainer import de.se.team3.logic.container.UserContainer import de.se.team3.logic.container.UserRoleContainer import de.se.team3.logic.domain.ProcessTemplate import de.se.team3.logic.domain.TaskTemplate import de.se.team3.webservice.containerInterfaces.ProcessTemplateContainerInterface import de.se.team3.webservice.util.JsonHelper import de.se.team3.webservice.util.PagingHelper import io.javalin.http.Context import org.json.JSONArray import org.json.JSONObject /** * Handles requests to resources of forms: * /processTemplates * /processTemplates/:processTemplateId */ object ProcessTemplatesHandler { private val processTemplatesContainer: ProcessTemplateContainerInterface = ProcessTemplatesContainer /** * Handles requests for all process templates. */ fun getAll(ctx: Context) { val processTemplates = processTemplatesContainer.getAllProcessTemplates() val pagingContainer = PagingHelper.getPagingContainer(1, 1) val processTemplatesJsonArray = JsonHelper.toJsonArray(processTemplates) pagingContainer.put("templates", processTemplatesJsonArray) ctx.result(pagingContainer.toString()) .contentType("application/json") } /** * Handles requests for a single process template. */ fun getOne(ctx: Context, processTemplateId: Int) { val processTemplate = processTemplatesContainer.getProcessTemplate(processTemplateId) // Note that the property taskTemplates of the underlying domain object are excluded by annotation val processTemplateJsonObjectWithoutTasks = JsonHelper.toJsonObject(processTemplate) val taskTemplatesJsonArray = JSONArray() processTemplateJsonObjectWithoutTasks.put("taskTemplates", taskTemplatesJsonArray) // Builds the json representation for each task template for ((_, taskTemplate) in processTemplate.taskTemplates) { val taskTemplateObjectWithoutNeighbors = JsonHelper.toJsonObject(taskTemplate) taskTemplatesJsonArray.put(taskTemplateObjectWithoutNeighbors) // Adds the predecessors to the current task template val predecessorJsonArray = JSONArray() taskTemplateObjectWithoutNeighbors.put("predecessors", predecessorJsonArray) for (predecessor in taskTemplate.getPredecessors()) predecessorJsonArray.put(predecessor.id) } ctx.result(processTemplateJsonObjectWithoutTasks.toString()) .contentType("application/json") } /** * Is responsible for the parsing of the list of task templates while the creation or * update of a process template. */ private fun parseTaskTemplates(taskTemplatesJsonArray: JSONArray): Map<Int, TaskTemplate> { val taskTemplatesMap = HashMap<Int, TaskTemplate>() val predecessorsPerTask = HashMap<Int, JSONArray>() // Creates the task templates and collects the predecessors for each task template for (entry in taskTemplatesJsonArray) { val taskTemplateJsonObject = entry as JSONObject val id = taskTemplateJsonObject.getInt("id") val responsibleUserRoleId = taskTemplateJsonObject.getInt("responsibleUserRoleId") val name = taskTemplateJsonObject.getString("name") val description = taskTemplateJsonObject.getString("description") val estimatedDuration = taskTemplateJsonObject.getDouble("estimatedDuration") val necessaryClosings = taskTemplateJsonObject.getInt("necessaryClosings") val responsibleUserRole = UserRoleContainer.getUserRole(responsibleUserRoleId) val taskTemplate = TaskTemplate(id, responsibleUserRole, name, description, estimatedDuration, necessaryClosings) taskTemplatesMap.put(taskTemplate.id, taskTemplate) val predecessorsJsonArray = taskTemplateJsonObject.getJSONArray("predecessors") predecessorsPerTask.put(taskTemplate.id, predecessorsJsonArray) } // Builds the relationship between the task templates for ((id, taskTemplate) in taskTemplatesMap) { for (entry in predecessorsPerTask.get(id)!!) { val predecessorId = entry as Int val predecessor = taskTemplatesMap.get(predecessorId)!! taskTemplate.addPredecessor(predecessor) } } return taskTemplatesMap } /** * Builds a process template from the given context. * * @return The process template is build with different constructors of ProcessTemplate * depending on whether processTemplateId is null or not. */ private fun makeProcessTemplate(processTemplateId: Int?, ctx: Context): ProcessTemplate { val content = ctx.body() val processTemplateJsonObject = JSONObject(content) val title = processTemplateJsonObject.getString("title") val description = processTemplateJsonObject.getString("description") val durationLimit = processTemplateJsonObject.getDouble("durationLimit") val ownerId = processTemplateJsonObject.getString("ownerId") val owner = UserContainer.getUser(ownerId) val taskTemplates = parseTaskTemplates(processTemplateJsonObject.getJSONArray("taskTemplates")!!) if (processTemplateId == null) return ProcessTemplate(title, description, durationLimit, owner, taskTemplates) return ProcessTemplate(processTemplateId, title, description, durationLimit, owner, taskTemplates) } /** * Handles the request for creating a new process template. */ fun create(ctx: Context) { try { val processTemplate = makeProcessTemplate(null, ctx) val newId = processTemplatesContainer.createProcessTemplate(processTemplate) val newIdJsonObject = JSONObject() newIdJsonObject.put("newId", newId) ctx.result(newIdJsonObject.toString()) .contentType("application/json") } catch (e: Throwable) { println("" + e.message) e.printStackTrace() throw e } } /** * Handles requests for updating a process template. */ fun update(ctx: Context, processTemplateId: Int) { val processTemplate = makeProcessTemplate(processTemplateId, ctx) val newId = processTemplatesContainer.updateProcessTemplate(processTemplate) val newIdJsonObject = JSONObject() newIdJsonObject.put("newId", newId) ctx.result(newIdJsonObject.toString()) .contentType("application/json") } /** * Handles requests for deleting a process template. */ fun delete(ctx: Context, processTemplateId: Int) { processTemplatesContainer.deleteProcessTemplate(processTemplateId) } }
7
JavaScript
0
1
c3d4bf7aea5b009f36deb7a4137df3107a8923c4
6,962
workflix
MIT License
app/src/main/kotlin/de/markusfisch/android/binaryeye/activity/SplashActivity.kt
markusfisch
101,552,674
false
null
package de.markusfisch.android.binaryeye.activity import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import de.markusfisch.android.binaryeye.app.setRestartCount class SplashActivity : AppCompatActivity() { override fun onCreate(state: Bundle?) { super.onCreate(state) // It's important _not_ to inflate a layout file here // because that would happen after the app is fully // initialized what is too late. setRestartCount(intent) startActivity(Intent(applicationContext, CameraActivity::class.java)) finish() } }
83
null
97
992
e99e2d7dccba2f6ffb6d7d6d2e6428288834dcf5
586
BinaryEye
MIT License
ehr-common-model/src/main/kotlin/org/openehr/proc/taskplanning/TaskAction.kt
better-care
343,543,899
false
null
/* Copyright 2021 Better Ltd (www.better.care) * * 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.openehr.proc.taskplanning import care.better.platform.annotation.Open import care.better.platform.proc.taskplanning.visitor.TaskModelVisitor import care.better.platform.proc.taskplanning.visitor.VisitableByModelVisitor import org.openehr.base.basetypes.LocatableRef import org.openehr.rm.common.Locatable import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlSeeAlso import javax.xml.bind.annotation.XmlType /** * @author <NAME> * @since 3.1.0 */ @XmlType(name = "TASK_ACTION", propOrder = [ "subjectPreconditions", "instructionActivity", "costingData"]) @XmlSeeAlso(value = [PerformableAction::class, DispatchableAction::class ]) @Open abstract class TaskAction() : Locatable(), VisitableByModelVisitor { companion object { private const val serialVersionUID: Long = 0L } @XmlElement(name = "instruction_activity") var instructionActivity: LocatableRef? = null @XmlElement(name = "subject_preconditions") var subjectPreconditions: MutableList<SubjectPrecondition> = mutableListOf() @XmlElement(name = "costing_data") var costingData: TaskCosting? = null protected constructor(instructionActivity: LocatableRef?) : this() { this.instructionActivity = instructionActivity } protected constructor(instructionActivity: LocatableRef?, costingData: TaskCosting?) : this(instructionActivity) { this.costingData = costingData } override fun accept(visitor: TaskModelVisitor) { val visited = visitor.visit(this) visitor.afterVisit(this) if (visited) { acceptPreconditions(visitor) } visitor.afterAccept(this) } protected fun acceptPreconditions(visitor: TaskModelVisitor) { subjectPreconditions.forEach { it.accept(visitor) } } override fun toString(): String = "TaskAction{" + ", instructionActivity=$instructionActivity" + ", subjectPreconditions=$subjectPreconditions" + ", costingData=$costingData" + ", name=$name" + ", uid=$uid" + ", archetypeDetails=$archetypeDetails" + ", archetypeNodeId='$archetypeNodeId'" + '}' }
0
Kotlin
1
2
368cae4a0464dcd90cbae48a1c6b3d4615450d6f
2,874
ehr-common
Apache License 2.0
runtime-permission/src/main/java/jp/co/soramitsu/android_foundation/kotlin/coroutines/experimental/kotlin-runtimepermissions-coroutines.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.android_foundation.kotlin.coroutines.experimental import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import jp.co.soramitsu.android_foundation.core.PermissionResult import jp.co.soramitsu.android_foundation.core.RuntimePermission import jp.co.soramitsu.android_foundation.kotlin.NoActivityException import jp.co.soramitsu.android_foundation.kotlin.PermissionException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine suspend fun FragmentActivity.askPermission(vararg permissions: String): PermissionResult = suspendCoroutine { continuation -> var resumed = false RuntimePermission.askPermission(this) .request(permissions.toList()) .onResponse { result -> if (!resumed) { resumed = true when { result.isAccepted -> continuation.resume(result) else -> continuation.resumeWithException(PermissionException(result)) } } } .ask() } suspend fun Fragment.askPermission(vararg permissions: String): PermissionResult = suspendCoroutine { continuation -> var resumed = false when (activity) { null -> continuation.resumeWithException(NoActivityException()) else -> RuntimePermission.askPermission(this) .request(permissions.toList()) .onResponse { result -> if (!resumed) { resumed = true when { result.isAccepted -> continuation.resume(result) else -> continuation.resumeWithException(PermissionException(result)) } } } .ask() } }
8
null
67
89
812c6ed5465d19a0616865cbba3e946d046720a1
1,909
fearless-Android
Apache License 2.0
compiler/testData/codegen/box/controlStructures/continueInExpr.kt
JakeWharton
99,388,807
false
null
// KJS_WITH_FULL_RUNTIME // WITH_RUNTIME fun concatNonNulls(strings: List<String?>): String { var result = "" for (str in strings) { result += str?:continue } return result } fun box(): String { val test = concatNonNulls(listOf("abc", null, null, "", null, "def")) if (test != "abcdef") return "Failed: test=$test" return "OK" }
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
368
kotlin
Apache License 2.0
app/src/main/kotlin/lishiyo/kotlin_arch/view/AboutFragment.kt
taduyde
124,017,263
false
null
/** * Copyright 2017 <NAME>. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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 lishiyo.kotlin_arch.view import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.about_fragment.* import lishiyo.kotlin_arch.R class AboutFragment : Fragment() { companion object { const val PROJECT_BLOG_POST = "https://erikcaffrey.github.io/ANDROID-kotlin-arch-components/" const val PROJECT_SOURCE_CODE = "https://github.com/erikcaffrey/Android-Architecture-Components-Kotlin" fun newInstance() = AboutFragment() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.about_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initUI() } private fun initUI() { show_me_post.setOnClickListener { startActivityActionView(PROJECT_BLOG_POST) } show_me_code.setOnClickListener { startActivityActionView(PROJECT_SOURCE_CODE) } } private fun startActivityActionView(url: String) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } }
0
Kotlin
0
0
e826072322a65506871546b230c63271796bf03d
1,890
kotlin-arch-boiler
Apache License 2.0
lint-checks/src/main/java/androidx/build/lint/BanConcurrentHashMap.kt
RikkaW
389,105,112
false
null
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build.lint import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import com.intellij.psi.PsiClass import com.intellij.psi.PsiField import com.intellij.psi.PsiMethod import org.jetbrains.uast.UElement import org.jetbrains.uast.UImportStatement import org.jetbrains.uast.UQualifiedReferenceExpression import org.jetbrains.uast.USimpleNameReferenceExpression class BanConcurrentHashMap : Detector(), Detector.UastScanner { override fun getApplicableUastTypes(): List<Class<out UElement>>? = listOf( UImportStatement::class.java, UQualifiedReferenceExpression::class.java ) override fun createUastHandler(context: JavaContext): UElementHandler = object : UElementHandler() { // Detect fully qualified reference if not imported. override fun visitQualifiedReferenceExpression(node: UQualifiedReferenceExpression) { if (node.selector is USimpleNameReferenceExpression) { val name = node.selector as USimpleNameReferenceExpression if (CONCURRENT_HASHMAP.equals(name.identifier)) { context.report( ISSUE, node, context.getLocation(node), "Detected " + "ConcurrentHashMap usage." ) } } } // Detect import. override fun visitImportStatement(node: UImportStatement) { if (node.importReference != null) { var resolved = node.resolve() if (node.resolve() is PsiField) { resolved = (resolved as PsiField).containingClass } else if (resolved is PsiMethod) { resolved = resolved.containingClass } if (resolved is PsiClass && CONCURRENT_HASHMAP_QUALIFIED_NAME .equals(resolved.qualifiedName) ) { context.report( ISSUE, node, context.getLocation(node), "Detected " + "ConcurrentHashMap usage." ) } } } } companion object { val ISSUE = Issue.create( "BanConcurrentHashMap", "ConcurrentHashMap usage is not allowed", "ConcurrentHashMap has an issue on Android’s Lollipop release that can lead to lost" + " updates under thread contention.", Category.CORRECTNESS, 5, Severity.ERROR, Implementation( BanConcurrentHashMap::class.java, Scope.JAVA_FILE_SCOPE ) ) val CONCURRENT_HASHMAP_QUALIFIED_NAME = "java.util.concurrent.ConcurrentHashMap" val CONCURRENT_HASHMAP = "ConcurrentHashMap" } }
12
null
497
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
3,826
androidx
Apache License 2.0
src/main/kotlin/report/ExceptionToPngConverter.kt
yyYank
46,666,189
false
{"Gradle": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Java Properties": 1, "Kotlin": 56, "Java": 1}
package kebab.report /** * Created by yy_yank on 2016/10/05. */ class ExceptionToPngConverter(val e: Exception) { fun convert(headline: String): ByteArray? = null }
7
Kotlin
2
13
876670577bfa5537755bc793098acc3c34593ee0
171
Kebab
Apache License 2.0
filepicker/src/commonMain/kotlin/com/chirrio/filepicker/ArrayBitmap.kt
gleb-skobinsky
634,563,581
false
{"Kotlin": 250953, "Swift": 580, "HTML": 312, "Shell": 228, "Ruby": 101}
package com.chirrio.filepicker import androidx.compose.ui.graphics.ImageBitmap expect fun ByteArray.toImageBitmap(context: Any, file: MPFile<Any>): ImageBitmap expect suspend fun ImageBitmap.downscale(): ImageBitmap expect fun imageBitmapFromArgb( rawArgbImageData: ByteArray, width: Int, height: Int ): ImageBitmap fun calculateDownscale(width: Int, height: Int, target: Int = 1000): Pair<Int, Int> { val maxSide = maxOf(width, height) val ratio = target.toFloat() / maxSide val newWidth = (width * ratio).toInt() val newHeight = (height * ratio).toInt() return newWidth to newHeight }
0
Kotlin
0
10
f576586312c1d2729e1a0100a8ccc60bfaf310f7
623
compose-connect
Apache License 2.0
app/src/main/kotlin/fardavide/molecule/domain/DataError.kt
fardavide
762,810,039
false
{"Kotlin": 61529}
package fardavide.molecule.domain object DataError { }
2
Kotlin
0
0
83ae45d2dc9a73ac9d8eaeb25247eda2aadf9db4
56
League-of-Molecule
Apache License 2.0
app/src/main/java/com/bignerdranch/android/geoquiz/MainActivity.kt
lonespartan12
499,949,139
false
{"Kotlin": 6323, "Java": 429}
package com.bignerdranch.android.geoquiz import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.Toast import com.bignerdranch.android.geoquiz.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding //lateinit is used when we decalre a variable but do not assign it a value. /* private lateinit var trueButton: Button //lateinit is used when we decalre a variable but do not assign it a value. private lateinit var falseButton: Button*/ private val questionBank = listOf( // use listOf to create an immutable list of elements. same as a tuple in python. Question(R.string.question_australia, true), Question(R.string.question_oceans, true), Question(R.string.question_mideast, false), Question(R.string.question_africa, false), Question(R.string.question_americas,true), Question(R.string.question_asia, true)) private var currentIndex = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) /* findViewById is a method that we will be using a lot. the R class that is created on compile, is a a file that adds all the xml tags as objects/methods/classes that we can refer to in the kotlin */ /* trueButton = findViewById(R.id.true_button) falseButton = findViewById(R.id.false_button)*/ /* the listener is a class that constantly looks for an input event associated with the button object This code is written as a lambda function lambda functions are unnamed functions This lambda function takes the view and associates it with the view of the button object. */ //trueButton.setOnClickListener { view: View -> //we do not need to use the first view. we can replace this with a underscore since this is an anonymous function /* trueButton.setOnClickListener { _: View ->//we can use the underscore here since this is an anonymous function. we can do this because we are creating a new instance of View every time the button is clicked Toast.makeText(this,R.string.correct_toast, Toast.LENGTH_SHORT).show() }*/ // why is this not "binding.true_button."? binding.trueButton.setOnClickListener { view: View -> //Toast.makeText(this,R.string.correct_toast, Toast.LENGTH_SHORT).show() checkAnswer(true) } /* falseButton.setOnClickListener { view: View ->// we will leave this one as view:View instead of _: View. Toast.makeText(this,R.string.incorrect_toast, Toast.LENGTH_SHORT).show() }*/ binding.falseButton.setOnClickListener { view: View -> //Toast.makeText(this,R.string.incorrect_toast, Toast.LENGTH_SHORT).show() checkAnswer(false) } binding.nextButton.setOnClickListener { currentIndex = (currentIndex+1) % questionBank.size /*val questionTextResId = questionBank[currentIndex].textResId binding.questionTextView.setText(questionTextResId)*/ updateQuestion() } binding.prevButton.setOnClickListener { currentIndex = if(currentIndex == 0) questionBank.size-1 else (currentIndex-1) % questionBank.size updateQuestion() } binding.questionTextView.setOnClickListener { currentIndex = (currentIndex+1) % questionBank.size updateQuestion() } /*val questionTextResId = questionBank[currentIndex].textResId binding.questionTextView.setText(questionTextResId)*/ updateQuestion() } private fun updateQuestion(){ val questionTextResId = questionBank[currentIndex].textResId binding.questionTextView.setText(questionTextResId) } private fun checkAnswer(userAnswer: Boolean) { val correctAnswer = questionBank[currentIndex].answer val messageResId = if(userAnswer == correctAnswer) { R.string.correct_toast } else { R.string.incorrect_toast } Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show() } }
2
Kotlin
0
0
e9d254a08bb0cb101a56ecd3ec3ca9d0adbd841c
4,459
BNR_Android_GeoQuiz
The Unlicense
app/src/main/java/eu/kanade/tachiyomi/util/lang/CoroutinesExtensions.kt
az4521
176,152,541
false
null
package eu.kanade.tachiyomi.util.system import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.Job import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlin.coroutines.EmptyCoroutineContext fun launchUI(block: suspend CoroutineScope.() -> Unit): Job = GlobalScope.launch(Dispatchers.Main, CoroutineStart.DEFAULT, block) fun launchNow(block: suspend CoroutineScope.() -> Unit): Job = GlobalScope.launch(Dispatchers.Main, CoroutineStart.UNDISPATCHED, block)
22
null
18
471
a72df3df5073300e02054ee75dc990d196cd6db8
585
TachiyomiAZ
Apache License 2.0
lib/src/commonMain/kotlin/fyi/models/ConfigResponse.kt
infinitum-dev
196,228,013
false
{"Gradle": 3, "XML": 92, "INI": 4, "Shell": 1, "Text": 11, "Batchfile": 1, "Markdown": 1, "Ruby": 1, "OpenStep Property List": 4, "Kotlin": 66, "JAR Manifest": 39, "Java": 8, "JSON": 35, "Java Properties": 6, "SQL": 2, "Motorola 68K Assembly": 5, "Objective-C": 2, "HTML": 487, "CSS": 5, "JavaScript": 59, "Maven POM": 1}
package fyi.models import kotlinx.serialization.Serializable /** * Represents the response given by the Server when executing the config Request. * * @property apps List of applications available in the domain used in the config request. */ @Serializable data class ConfigResponse(val apps: List<App>) /** * Represents an App. * * @property name App name. * @property token App token. */ @Serializable data class App(val name: String="", val token: String="")
0
JavaScript
0
0
f748c127221a6d304d7d306094ea24d3088abc59
471
mobile-sdk
MIT License
app/src/main/java/com/newbiechen/nbreader/ui/component/book/text/engine/cursor/TextWordCursor.kt
newbiechen1024
239,496,581
false
null
package com.newbiechen.nbreader.ui.component.book.text.engine.cursor import com.newbiechen.nbreader.ui.component.book.text.entity.TextPosition import com.newbiechen.nbreader.ui.component.book.text.entity.element.TextWordElement /** * author : newbiechen * date : 2019-10-22 14:04 * description :文本单词光标,对 TextParagraphCursor 的进一步封装。主要,用于定位在文本中的位置 */ class TextWordCursor : TextPosition { private lateinit var mParagraphCursor: TextParagraphCursor // Word 当前指向段落中 element 的位置,支持指向 element 的末尾,即其大小 >= elementCount (需要注意的点) private var mElementIndex: Int = 0 // 指向 word 中字节的位置,支持指向 char 的末尾,即其大小 >= charCount (需要注意的点) private var mCharIndex: Int = 0 constructor(wordCursor: TextWordCursor) { updateCursor(wordCursor) } constructor(paragraphCursor: TextParagraphCursor) { updateCursor(paragraphCursor) } /** * 更新当前光标位置 */ fun updateCursor(paragraphCursor: TextParagraphCursor) { mParagraphCursor = paragraphCursor mElementIndex = 0 mCharIndex = 0 } fun updateCursor(wordCursor: TextWordCursor) { mParagraphCursor = wordCursor.getParagraphCursor() mElementIndex = wordCursor.getElementIndex() mCharIndex = wordCursor.getCharIndex() } override fun getChapterIndex(): Int { return mParagraphCursor.getChapterIndex() } override fun getParagraphIndex(): Int { return mParagraphCursor.getParagraphIndex() } /** * 返回当前光标指向的 element */ override fun getElementIndex() = mElementIndex /** * 返回当前光标指向的字节 */ override fun getCharIndex() = mCharIndex /** * 返回 Word 光标对应的 Paragraph 光标 */ fun getParagraphCursor() = mParagraphCursor /** * 移动光标到下一个单词 */ fun moveToNextWord() { // TODO:没有判断 element 的索引超出的问题。 mElementIndex++ mCharIndex = 0 } /** * 移动光标到上一个单词 */ fun moveToPrevWord() { // TODO:没有判断 element 的索引超出的问题。 mElementIndex-- mCharIndex = 0 } /** * 光标移动到下一个段落的开头位置 * @return 是否成功移动到下一个段落 */ fun moveToNextParagraph(): Boolean { return if (mParagraphCursor.isLastOfText()) { false } else { mParagraphCursor = mParagraphCursor.nextCursor()!! // 跳转到当前段落的起始 moveToParagraphStart() true } } /** * 光标移动到上一个段落,的开头位置 * @return 是否成功移动到上一个段落 */ fun moveToPrevParagraph(): Boolean { return if (mParagraphCursor.isLastOfText()) { false } else { mParagraphCursor = mParagraphCursor.prevCursor()!! // 跳转到下一段落的开头 moveToParagraphStart() true } } /** * 移动到段落的指定位置 */ fun moveTo(elementIndex: Int, charIndex: Int = 0) { if (elementIndex == 0 && charIndex == 0) { mElementIndex = 0 mCharIndex = 0 } else { var elementIndex = 0.coerceAtLeast(elementIndex) val elementCount = mParagraphCursor.getElementCount() if (elementIndex >= elementCount) { mElementIndex = elementCount mCharIndex = 0 } else { mElementIndex = elementIndex moveToCharIndex(charIndex) } } } /** * 光标移动到当前 element 中的字节位置 */ fun moveToCharIndex(charIndex: Int) { // TODO:需要检测越界 var charIndex = charIndex charIndex = 0.coerceAtLeast(charIndex) mCharIndex = 0 if (charIndex > 0) { val element = mParagraphCursor.getElement(mElementIndex) if (element is TextWordElement) { if (charIndex <= element.length) { mCharIndex = charIndex } } } } /** * 光标是否在段落的开头 */ fun isStartOfParagraph(): Boolean { return mElementIndex == 0 && mCharIndex == 0 } /** * 是否是文本的开头 */ fun isStartOfText(): Boolean { return isStartOfParagraph() && mParagraphCursor.isFirstOfText() } /** * 光标是否指向段落的末尾 */ fun isEndOfParagraph(): Boolean { return mElementIndex == mParagraphCursor.getElementCount() } /** * 光标是否指向文本的末尾 */ fun isEndOfText(): Boolean { return isEndOfParagraph() && mParagraphCursor.isLastOfText() } /** * 移动到段落的起始位置 */ fun moveToParagraphStart() { mElementIndex = 0 mCharIndex = 0 } /** * 跳转到段落的末尾位置 */ fun moveToParagraphEnd() { mElementIndex = mParagraphCursor.getElementCount() mCharIndex = 0 } }
5
Kotlin
8
37
e423b13915578ab95c1683bfa7a70e59f19f2eab
4,734
NBReader
Apache License 2.0
app/src/main/java/br/edu/puccampinas/pi3/AvaliacaoActivity.kt
Jean2505
619,002,734
false
null
package br.edu.puccampinas.pi3 import android.content.Intent import android.os.Bundle import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import br.edu.puccampinas.pi3.databinding.ActivityAndamentoBinding import br.edu.puccampinas.pi3.databinding.ActivityAvaliacaoBinding import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.Task import com.google.android.material.button.MaterialButton import com.google.common.reflect.TypeToken import com.google.firebase.auth.ktx.auth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.functions.FirebaseFunctions import com.google.firebase.functions.FirebaseFunctionsException import com.google.firebase.functions.ktx.functions import com.google.firebase.ktx.Firebase import com.google.gson.GsonBuilder import org.json.JSONObject import java.util.ArrayList class AvaliacaoActivity : AppCompatActivity() { private lateinit var binding: ActivityAvaliacaoBinding private lateinit var btnChamadas : MaterialButton private lateinit var tvComent : TextView private lateinit var functions: FirebaseFunctions private val gson = GsonBuilder().enableComplexMapKeySerialization().create() private val user = Firebase.auth.currentUser private var db = FirebaseFirestore.getInstance() private var lista: MutableList<Avaliacoes> = emptyList<Avaliacoes>().toMutableList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_avaliacao) binding = ActivityAvaliacaoBinding.inflate(layoutInflater) setContentView(binding.root) btnChamadas = findViewById(R.id.btnChamadas) functions = Firebase.functions("southamerica-east1") getMedia() .addOnCompleteListener(OnCompleteListener { task -> if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { val code = e.code val details = e.details Toast.makeText(this, "Erro ao obter media!", Toast.LENGTH_SHORT).show() } }else{ val genericResp = gson.fromJson(task.result, FunctionsGenericResponse::class.java) val insertInfo = gson.fromJson(genericResp.payload.toString(), GenericInsertResponse::class.java) println(genericResp.message) val media = String.format("%.1f", genericResp.message!!.toDouble()) if (!media.toDouble().isNaN()){ println("entrou aqui ó") binding.tvMedia.text = "sua média é : ${media}" } else{ binding.tvMedia.text = "Você não tem avaliações" } } }) db.collection("avaliacoes").whereEqualTo("uidDentista", user!!.uid) .get() .addOnSuccessListener { documents -> for(document in documents) { val avaliacao = Avaliacoes(nome = document["nome"].toString(), comentario = "\"${document["coment"].toString()}\"", estrela = document["aval"] as Long) lista.add(avaliacao) val avalAdapter = AvaliacoesAdapter(lista.asReversed()) val recyclerView: RecyclerView = findViewById(R.id.rvAvaliacoes) recyclerView.adapter = avalAdapter } } btnChamadas.setOnClickListener{ if(intent.getStringExtra("finish") == "sim"){ this.finish() } else { val iEmergencias = Intent(this, EmergenciasActivity::class.java) startActivity(iEmergencias) } } binding.btnPerfil.setOnClickListener { val iPerfil = Intent(this, PerfilActivity::class.java) startActivity(iPerfil) } binding.btnHistorico.setOnClickListener { val iHistorico = Intent(this, HistoricoActivity::class.java) startActivity(iHistorico) } } private fun getMedia(): Task<String> { val data = hashMapOf( "uid" to user!!.uid ) return functions .getHttpsCallable("getMedia") .call(data) .continueWith { task -> println(task.result?.data) val res = gson.toJson(task.result?.data) println(res[0]) res } } }
0
Kotlin
0
0
1302c6f0b19e3f3d40807301050b197e4455998d
4,833
Projeto-Integrador-3
MIT License
app/src/main/java/com/ztftrue/music/utils/Utils.kt
ZTFtrue
744,397,364
false
null
package com.ztftrue.music.utils import android.content.Context import android.content.Intent import android.content.pm.ResolveInfo import android.net.Uri import android.os.Bundle import android.support.v4.media.MediaBrowserCompat import android.text.TextUtils import android.widget.Toast import androidx.core.content.FileProvider import com.ztftrue.music.MusicViewModel import com.ztftrue.music.play.ACTION_AddPlayQueue import com.ztftrue.music.play.ACTION_GET_TRACKS import com.ztftrue.music.play.ACTION_PlayLIST_CHANGE import com.ztftrue.music.sqlData.model.DictionaryApp import com.ztftrue.music.sqlData.model.MusicItem import com.ztftrue.music.utils.model.AnyListBase import com.ztftrue.music.utils.trackManager.PlaylistManager import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException enum class OperateTypeInActivity { DeletePlayList, InsertTrackToPlaylist, RemoveTrackFromPlayList, RenamePlaylist, RemoveTrackFromStorage, EditTrackInfo, } enum class PlayListType { Songs, PlayLists, Queue, Albums, Artists, Genres, Folders, None } fun enumToStringForPlayListType(myEnum: PlayListType): String { return myEnum.name } fun stringToEnumForPlayListType(enumString: String): PlayListType { return try { PlayListType.valueOf(enumString) } catch (e: IllegalArgumentException) { PlayListType.Songs } } enum class OperateType { AddToQueue, RemoveFromQueue, PlayNext, AddToPlaylist, RemoveFromPlaylist, AddToFavorite, Artist, Album, EditMusicInfo, DeleteFromStorage, No, RenamePlayList, DeletePlayList, ShowArtist, ClearQueue, SaveQueueToPlayList } enum class ScrollDirectionType { GRID_HORIZONTAL, GRID_VERTICAL, LIST_VERTICAL, } @Suppress("deprecation") object Utils { val items = listOf("Follow System", "Light", "Dark", "Follow Music Cover") var kThirdOct = doubleArrayOf( 31.5, 63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0, 16000.0 ) var equalizerMax = 5 var equalizerMin = -8 /** * B≈2×fc Q=fc/B */ var qFactors = doubleArrayOf( 0.707, 0.707, 0.707, 0.707, 0.707, 0.707, 0.707, 0.707, 0.707, 0.707 ) fun initSettingsData(musicViewModel: MusicViewModel,context: Context) { CoroutineScope(Dispatchers.IO).launch { musicViewModel.themeSelected.intValue = context.getSharedPreferences( "SelectedTheme", Context.MODE_PRIVATE ).getInt("SelectedTheme", 0) musicViewModel.textAlign.value = SharedPreferencesUtils.getDisplayAlign(context) musicViewModel.fontSize.intValue = SharedPreferencesUtils.getFontSize(context) musicViewModel.autoScroll.value = SharedPreferencesUtils.getAutoScroll(context) musicViewModel.autoHighLight.value = SharedPreferencesUtils.getAutoHighLight(context) val dicApps = musicViewModel.getDb(context).DictionaryAppDao().findAllDictionaryApp() if (dicApps.isNullOrEmpty()) { val list = ArrayList<DictionaryApp>() getAllDictionaryActivity(context) .forEachIndexed { index, it -> list.add( DictionaryApp( index, it.activityInfo.name, it.activityInfo.packageName, it.loadLabel(context.packageManager).toString(), isShow = true, autoGo = false ) ) } musicViewModel.dictionaryAppList.addAll(list) } else { musicViewModel.dictionaryAppList.addAll(dicApps) } } } fun formatTime(millis: Long): String { val totalSeconds = millis / 1000 val seconds = totalSeconds % 60 var minutes = totalSeconds / 60 val hours = minutes / 60 minutes %= 60 return if (hours > 0) String.format( "%02d:%02d:%02d", hours, minutes, seconds ) else String.format("%02d:%02d", minutes, seconds) } fun openFile(path: String, minType: String = "text/plain", context: Context) { val fileUri: Uri val outputImage = File(path) fileUri = FileProvider.getUriForFile( context, context.packageName + ".fileprovider", outputImage ) val intent = Intent(Intent.ACTION_VIEW) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION) if (TextUtils.isEmpty(minType)) { intent.data = fileUri } else { intent.setDataAndType(fileUri, minType) } context.startActivity(intent) } @Suppress("unused") fun copyFile(sourceFile: File, destinationFile: File) { try { val inputStream = FileInputStream(sourceFile) val outputStream = FileOutputStream(destinationFile) val buffer = ByteArray(1024) var length: Int while (inputStream.read(buffer).also { length = it } > 0) { outputStream.write(buffer, 0, length) } inputStream.close() outputStream.close() } catch (e: IOException) { e.printStackTrace() } } fun openBrowser(link: String, context: Context) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link)) context.startActivity(intent) } fun sendEmail(recipient: String, subject: String, context: Context) { val intent = Intent(Intent.ACTION_SENDTO).apply { data = Uri.parse("mailto:") // only email apps should handle this putExtra(Intent.EXTRA_EMAIL, arrayOf(recipient)) putExtra(Intent.EXTRA_SUBJECT, subject) } context.startActivity(intent) } fun createPlayListAddTracks( name: String, context: Context, type: PlayListType, id: Long, musicViewModel: MusicViewModel ) { if (name.isNotEmpty()) { val idPlayList = PlaylistManager.createPlaylist(context, name) if (idPlayList != -1L) { val bundle = Bundle() bundle.putString("type", type.name) bundle.putLong("id", id) musicViewModel.mediaBrowser?.sendCustomAction( ACTION_GET_TRACKS, bundle, object : MediaBrowserCompat.CustomActionCallback() { override fun onResult( action: String?, extras: Bundle?, resultData: Bundle? ) { super.onResult(action, extras, resultData) if (ACTION_GET_TRACKS == action && resultData != null) { val tracksList = resultData.getParcelableArrayList<MusicItem>("list") if (tracksList != null) { val tIds = ArrayList(tracksList.map { item -> item.id }) PlaylistManager.addMusicsToPlaylist(context, idPlayList, tIds) musicViewModel.mediaBrowser?.sendCustomAction( ACTION_PlayLIST_CHANGE, null, object : MediaBrowserCompat.CustomActionCallback() { override fun onResult( action: String?, extras: Bundle?, resultData: Bundle? ) { super.onResult(action, extras, resultData) musicViewModel.refreshList.value = !musicViewModel.refreshList.value } } ) } } } } ) } else { Toast.makeText(context, "创建失败", Toast.LENGTH_SHORT) .show() } } } fun createPlayListAddTrack( name: String, context: Context, item: MusicItem, musicViewModel: MusicViewModel ) { if (name.isNotEmpty()) { val idPlayList = PlaylistManager.createPlaylist(context, name) if (idPlayList != -1L) { PlaylistManager.addMusicToPlaylist(context, idPlayList, item.id) musicViewModel.mediaBrowser?.sendCustomAction( ACTION_PlayLIST_CHANGE, null, null ) } else { Toast.makeText(context, "创建失败", Toast.LENGTH_SHORT) .show() } } } fun addTracksToPlayList( playListId: Long, context: Context, type: PlayListType, id: Long, musicViewModel: MusicViewModel ) { val bundle = Bundle() bundle.putString("type", type.name) bundle.putLong("id", id) musicViewModel.mediaBrowser?.sendCustomAction( ACTION_GET_TRACKS, bundle, object : MediaBrowserCompat.CustomActionCallback() { override fun onResult( action: String?, extras: Bundle?, resultData: Bundle? ) { super.onResult(action, extras, resultData) if (ACTION_GET_TRACKS == action && resultData != null) { val tracksList = resultData.getParcelableArrayList<MusicItem>("list") if (tracksList != null) { val tIds = ArrayList(tracksList.map { item -> item.id }) PlaylistManager.addMusicsToPlaylist(context, playListId, tIds) musicViewModel.mediaBrowser?.sendCustomAction( ACTION_PlayLIST_CHANGE, null, object : MediaBrowserCompat.CustomActionCallback() { override fun onResult( action: String?, extras: Bundle?, resultData: Bundle? ) { super.onResult(action, extras, resultData) musicViewModel.refreshList.value = !musicViewModel.refreshList.value } } ) } } } } ) } fun operateDialogDeal( operateType: OperateType, item: AnyListBase, musicViewModel: MusicViewModel ) { when (operateType) { OperateType.AddToQueue -> { val bundle = Bundle() bundle.putString("type", item.type.name) bundle.putLong("id", item.id) musicViewModel.mediaBrowser?.sendCustomAction( ACTION_GET_TRACKS, bundle, object : MediaBrowserCompat.CustomActionCallback() { override fun onResult( action: String?, extras: Bundle?, resultData: Bundle? ) { super.onResult(action, extras, resultData) if (ACTION_GET_TRACKS == action && resultData != null) { val tracksList = resultData.getParcelableArrayList<MusicItem>("list") if (tracksList != null) { musicViewModel.musicQueue.addAll(tracksList) val bundleAddTracks = Bundle() bundleAddTracks.putParcelableArrayList("musicItems", tracksList) musicViewModel.mediaBrowser?.sendCustomAction( ACTION_AddPlayQueue, bundleAddTracks, null ) } } } } ) } OperateType.PlayNext -> { val bundle = Bundle() bundle.putString("type", item.type.name) bundle.putLong("id", item.id) musicViewModel.mediaBrowser?.sendCustomAction( ACTION_GET_TRACKS, bundle, object : MediaBrowserCompat.CustomActionCallback() { override fun onResult( action: String?, extras: Bundle?, resultData: Bundle? ) { super.onResult(action, extras, resultData) if (ACTION_GET_TRACKS == action && resultData != null) { val tracksList = resultData.getParcelableArrayList<MusicItem>("list") if (tracksList != null) { addTracksToQueue( musicViewModel, tracksList, musicViewModel.currentPlayQueueIndex.intValue + 1 ) } } } } ) } else -> { } } } fun addTracksToQueue( musicViewModel: MusicViewModel, tracksList: ArrayList<MusicItem>, indexTemp: Int ) { var index = indexTemp if (musicViewModel.musicQueue.isEmpty()) { index = 0 } musicViewModel.musicQueue.addAll( index, tracksList ) val bundleAddTracks = Bundle() bundleAddTracks.putParcelableArrayList("musicItems", tracksList) bundleAddTracks.putInt( "index", index ) musicViewModel.mediaBrowser?.sendCustomAction( ACTION_AddPlayQueue, bundleAddTracks, null ) } fun getAllDictionaryActivity(context: Context): List<ResolveInfo> { val shareIntent = Intent(Intent.ACTION_PROCESS_TEXT) shareIntent.type = "text/plain" shareIntent.putExtra(Intent.EXTRA_TEXT, "") val resolveInfoList: List<ResolveInfo> = context.packageManager.queryIntentActivities(shareIntent, 0) for (resolveInfo in resolveInfoList) { val activityInfo = resolveInfo.activityInfo val packageName = activityInfo.packageName val className = activityInfo.name val label = resolveInfo.loadLabel(context.packageManager).toString() println("Package Name: $packageName, Class Name: $className, Label: $label") } return resolveInfoList } }
5
null
6
6
d7facf4eb4a35c3aa1667831726ecb9d82e9c029
16,498
MonsterMusic
Apache License 2.0
net.akehurst.language/agl-processor/src/commonTest/kotlin/agl/grammar/grammar/test_Agl_scan.kt
dhakehurst
197,245,665
false
{"Kotlin": 3441810, "ANTLR": 64742, "Rascal": 17698, "Java": 14285, "PEG.js": 6866, "JavaScript": 5287, "BASIC": 22}
/** * Copyright (C) 2018 Dr. David H. Akehurst (http://dr.david.h.akehurst.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.akehurst.language.agl.processor import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull internal class test_Agl_scan { @Test fun scan_literal_empty_a() { val pr = Agl.processorFromString<Any, Any>("namespace test grammar Test { a = ''; }") val tokens = pr.processor!!.scan("ab") val tokenStr = tokens.map { it.toString() }.joinToString(", ") println("tokens = ${tokenStr}") assertNotNull(tokens) assertEquals(1, tokens.size) assertEquals("a", tokens[0].matchedText) // assertEquals(1, tokens[0].identity.runtimeRuleNumber) assertEquals(0, tokens[0].location.position) assertEquals(1, tokens[0].matchedText.length) } @Test fun scan_pattern_empty_a() { val pr = Agl.processorFromString<Any, Any>("namespace test grammar Test { a = \"[x]*\"; }") val tokens = pr.processor!!.scan("ab") val tokenStr = tokens.map { it.toString() }.joinToString(", ") println("tokens = ${tokenStr}") assertNotNull(tokens) assertEquals(1, tokens.size) assertEquals("a", tokens[0].matchedText) //assertEquals(1, tokens[0].identity.runtimeRuleNumber) assertEquals(0, tokens[0].location.position) assertEquals(1, tokens[0].matchedText.length) } @Test fun scan_a_a() { val pr = Agl.processorFromStringDefault("namespace test grammar Test { a = 'a';}") val tokens = pr.processor!!.scan("a") val tokenStr = tokens.map { it.toString() }.joinToString(", ") println("tokens = ${tokenStr}") assertNotNull(tokens) assertEquals(1, tokens.size) assertEquals("a", tokens[0].matchedText) //assertEquals(1, tokens[0].identity.runtimeRuleNumber) assertEquals(0, tokens[0].location.position) assertEquals(1, tokens[0].matchedText.length) } @Test fun scan_a_aa() { val pr = Agl.processorFromString<Any, Any>("namespace test grammar Test { a = 'a';}") val tokens = pr.processor!!.scan("aa") val tokenStr = tokens.map { it.toString() }.joinToString(", ") println("tokens = ${tokenStr}") assertNotNull(tokens) assertEquals(2, tokens.size) } @Test fun scan_a_aaa() { val pr = Agl.processorFromString<Any, Any>("namespace test grammar Test { a = 'a';}") val tokens = pr.processor!!.scan("aaa") val tokenStr = tokens.map { it.toString() }.joinToString(", ") println("tokens = ${tokenStr}") assertNotNull(tokens) assertEquals(3, tokens.size) } @Test fun scan_ab_aba() { val pr = Agl.processorFromString<Any, Any>("namespace test grammar Test { a = 'a'; b = 'b'; }") val tokens = pr.processor!!.scan("aba") val tokenStr = tokens.map { it.toString() }.joinToString(", ") println("tokens = ${tokenStr}") assertNotNull(tokens) assertEquals(3, tokens.size) assertEquals("a", tokens[0].matchedText) assertEquals("b", tokens[1].matchedText) assertEquals("a", tokens[2].matchedText) } @Test fun scan_end_of_line() { val pr = Agl.processorFromString<Any, Any>( """ namespace test grammar Test { skip WHITESPACE = "\s+" ; chars = char+ ; char = "[a-z]" ; } """.trimIndent() ) var tokens = pr.processor!!.scan("a") var tokenStr = tokens.map { it.toString() }.joinToString(", ") println("tokens = ${tokenStr}") assertEquals(1, tokens.size) tokens = pr.processor!!.scan("a b") tokenStr = tokens.map { it.toString() }.joinToString(", ") println("tokens = ${tokenStr}") assertEquals(3, tokens.size) TODO("test eol") } }
2
Kotlin
7
43
b225becb87afb0577bebaeff31c256d3f8b85b63
4,552
net.akehurst.language
Apache License 2.0
plugins/hh-garcon/src/main/kotlin/ru/hh/plugins/garcon/config/editor/GarconPluginSettings.kt
hhru
159,637,875
false
null
package ru.hh.plugins.garcon.config.editor import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.util.xmlb.XmlSerializerUtil import ru.hh.plugins.garcon.config.GarconPluginConfig import ru.hh.plugins.garcon.config.extensions.isNotFullyInitialized import ru.hh.plugins.utils.yaml.YamlUtils @State( name = "ru.hh.plugins.garcon.config.editor.GarconPluginSettings", storages = [Storage("garcon_plugin_settings.xml")] ) class GarconPluginSettings : PersistentStateComponent<GarconPluginSettings> { companion object { private const val DEFAULT_PATH_TO_CONFIG_FILE = "code-cookbook/templates/garcon/garcon_config.yaml" fun getInstance(project: Project): GarconPluginSettings { return project.service<GarconPluginSettings>().let { settings -> if (project.isDefault.not() && settings.config.isNotFullyInitialized()) { settings.tryLoadFromConfigFile(DEFAULT_PATH_TO_CONFIG_FILE) } settings } } fun getConfig(project: Project): GarconPluginConfig { return getInstance(project).config } } var config: GarconPluginConfig = GarconPluginConfig() override fun getState(): GarconPluginSettings? { return this } override fun loadState(state: GarconPluginSettings) { XmlSerializerUtil.copyBean(state, this) } fun tryLoadFromConfigFile(configFilePath: String) { YamlUtils.loadFromConfigFile<GarconPluginConfig>( configFilePath = configFilePath, onError = { // todo } )?.let { configFromYaml -> this.config = configFromYaml.copy( configFilePath = configFilePath ) } } }
17
null
11
97
2d6c02fc814eff3934c17de77ef7ade91d3116f5
1,994
android-multimodule-plugin
MIT License
shared/data/network/src/commonTest/kotlin/dev/ohoussein/cryptoapp/data/network/crypto/service/mocks/MockCryptoDetailsJson.kt
OHoussein
388,247,123
false
null
@file:Suppress("MaxLineLength") package dev.ohoussein.cryptoapp.data.network.crypto.service.mocks val mockCryptoDetailsJson = """ { "id": "bitcoin", "symbol": "btc", "name": "Bitcoin", "asset_platform_id": null, "platforms": { "": "" }, "block_time_in_minutes": 10, "hashing_algorithm": "SHA-256", "categories": [ "Cryptocurrency" ], "public_notice": null, "additional_notices": [], "localization": { "en": "Bitcoin", "de": "Bitcoin", "es": "Bitcoin", "fr": "Bitcoin", "it": "Bitcoin", "pl": "Bitcoin", "ro": "Bitcoin", "hu": "Bitcoin", "nl": "Bitcoin", "pt": "Bitcoin", "sv": "Bitcoin", "vi": "Bitcoin", "tr": "Bitcoin", "ru": "биткоин", "ja": "ビットコイン", "zh": "比特币", "zh-tw": "比特幣", "ko": "비트코인", "ar": "بيتكوين", "th": "บิตคอยน์", "id": "Bitcoin" }, "description": { "en": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "de": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "es": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "fr": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "it": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "pl": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "ro": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "hu": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "nl": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "pt": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "sv": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "vi": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "tr": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "ru": "", "ja": "", "zh": "", "zh-tw": "", "ko": "비트코인은 2009년 나카모토 사토시가 만든 디지털 통화로, 통화를 발행하고 관리하는 중앙 장치가 존재하지 않는 구조를 가지고 있다. 대신, 비트코인의 거래는 P2P 기반 분산 데이터베이스에 의해 이루어지며, 공개 키 암호 방식 기반으로 거래를 수행한다. 비트코인은 공개성을 가지고 있다. 비트코인은 지갑 파일의 형태로 저장되며, 이 지갑에는 각각의 고유 주소가 부여되며, 그 주소를 기반으로 비트코인의 거래가 이루어진다. 비트코인은 1998년 웨이따이가 사이버펑크 메일링 리스트에 올린 암호통화란 구상을 최초로 구현한 것 중의 하나이다.\r\n\r\n비트코인은 최초로 구현된 가상화폐입니다. 발행 및 유통을 관리하는 중앙권력이나 중간상인 없이, P2P 네트워크 기술을 이용하여 네트워크에 참여하는 사용자들이 주체적으로 화폐를 발행하고 이체내용을 공동으로 관리합니다. 이를 가능하게 한 블록체인 기술을 처음으로 코인에 도입한 것이 바로 비트코인입니다.\r\n\r\n비트코인을 사용하는 개인과 사업자의 수는 꾸준히 증가하고 있으며, 여기에는 식당, 아파트, 법률사무소, 온라인 서비스를 비롯한 소매상들이 포함됩니다. 비트코인은 새로운 사회 현상이지만 아주 빠르게 성장하고 있습니다. 이를 바탕으로 가치 증대는 물론, 매일 수백만 달러의 비트코인이 교환되고 있습니다. \r\n\r\n비트코인은 가상화폐 시장에서 현재 유통시가총액과 코인의 가치가 가장 크고, 거래량 또한 안정적입니다. 이더리움이 빠르게 추격하고 있지만 아직은 가장 견고한 가상화폐라고 볼 수 있습니다. \r\n\r\n코인 특징\r\n1. 중앙주체 없이 사용자들에 의해 거래내용이 관리될 수 있는 비트코인의 운영 시스템은 블록체인 기술에서 기인합니다. 블록체인은 쉽게 말해 다 같이 장부를 공유하고, 항상 서로의 컴퓨터에 있는 장부 파일을 비교함으로써 같은 내용만 인정하는 방식으로 운영됩니다. 따라서 전통적인 금융기관에서 장부에 대한 접근을 튼튼하게 방어하던 것과는 정반대의 작업을 통해 보안을 달성합니다. 장부를 해킹하려면 51%의 장부를 동시에 조작해야 하는데, 이는 사실상 불가능합니다. 왜냐하면, 이를 실행하기 위해서는 컴퓨팅 파워가 어마어마하게 소요되고, 이것이 가능한 슈퍼컴퓨터는 세상에 존재하지 않기 때문입니다. 또한, 장부의 자료들은 줄글로 기록되는 것이 아니라 암호화 해시 함수형태로 블록에 저장되고, 이 블록들은 서로 연결되어 있어서 더 강력한 보안을 제공합니다. \r\n\r\n2. 비트코인은 블록발행보상을 채굴자에게 지급하는 방식으로 신규 코인을 발행합니다. 블록발행보상은 매 21만 블록(약 4년)을 기준으로 발행량이 절반으로 줄어듭니다. 처음에는 50비트코인씩 발행이 되었고, 4년마다 계속 반으로 감소하고 있습니다. 코인의 총량이 2,100만 개에 도달하면 신규 발행은 종료되고, 이후에는 거래 수수료만을 통해 시스템이 지탱될 것입니다. \r\n\r\n핵심 가치\r\n(키워드: 통화로 사용될 수 있는 보편성 및 편의성)\r\n\r\n1. 다양한 알트코인들의 등장에 앞서 비트코인은 가상화폐 시장에서 독보적이었기 때문에, 현재 가장 보편적인 결제수단으로 사용됩니다. 실생활에서 이를 활용할 수 있는 가맹점이 알트코인들보다 압도적으로 많을 뿐만 아니라, 이 또한 증가하고 있습니다. 일례로 일본 업체들이 비트코인 결제 시스템을 도입하면서 곧 비트코인을 오프라인 점포 26만 곳에서 이용할 수 있게 될 것입니다. \r\n\r\n2. 여러 나라에서 비트코인을 정식 결제 수단으로 인정하면서, 실물화폐와 가상화폐를 거래할 때 더는 부가가치세가 부과되지 않게 된다고 합니다. 실제로 일본과 호주에서는 이미 비트코인을 합법적 결제 수단으로 인정하면서 제도권 안으로 들여오고 있고, 미국에서는 비트코인 ETF 승인 노력도 진행되고 있습니다. 각국에 비트코인을 기반으로 한 ATM 기계도 설치되었다고 합니다. ", "ar": "", "th": "", "id": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, <NAME>. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>." }, "links": { "homepage": [ "http://www.bitcoin.org", "", "" ], "blockchain_site": [ "https://blockchair.com/bitcoin/", "https://btc.com/", "https://btc.tokenview.com/", "", "" ], "official_forum_url": [ "https://bitcointalk.org/", "", "" ], "chat_url": [ "", "", "" ], "announcement_url": [ "", "" ], "twitter_screen_name": "bitcoin", "facebook_username": "bitcoins", "bitcointalk_thread_identifier": null, "telegram_channel_identifier": "", "subreddit_url": "https://www.reddit.com/r/Bitcoin/", "repos_url": { "github": [ "https://github.com/bitcoin/bitcoin", "https://github.com/bitcoin/bips" ], "bitbucket": [] } }, "image": { "thumb": "https://assets.coingecko.com/coins/images/1/thumb/bitcoin.png?1547033579", "small": "https://assets.coingecko.com/coins/images/1/small/bitcoin.png?1547033579", "large": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579" }, "country_origin": "", "genesis_date": "2009-01-03", "sentiment_votes_up_percentage": 67.33, "sentiment_votes_down_percentage": 32.67, "market_cap_rank": 1, "coingecko_rank": 1, "coingecko_score": 81.721, "developer_score": 101.396, "community_score": 74.329, "liquidity_score": 100.017, "public_interest_score": 0.314, "developer_data": { "forks": 29417, "stars": 55648, "subscribers": 3828, "total_issues": 6337, "closed_issues": 5743, "pull_requests_merged": 8778, "pull_request_contributors": 733, "code_additions_deletions_4_weeks": { "additions": 3809, "deletions": -2404 }, "commit_count_4_weeks": 225, "last_4_weeks_commit_activity_series": [ 4, 3, 12, 8, 3, 3, 0, 5, 13, 1, 2, 6, 3, 0, 4, 6, 5, 2, 0, 3, 0, 0, 2, 1, 2, 1, 0, 0 ] }, "public_interest_stats": { "alexa_rank": 9440, "bing_matches": null }, "status_updates": [], "last_updated": "2021-07-18T10:40:31.413Z", "tickers": [ { "base": "BTC", "target": "USD", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 31669, "volume": 11502.07033188, "converted_last": { "btc": 0.99808807, "eth": 16.090713, "usd": 31669 }, "converted_volume": { "btc": 11480, "eth": 185077, "usd": 364259065 }, "trust_score": "green", "bid_ask_spread_percentage": 0.031566, "timestamp": "2021-07-18T10:35:31+00:00", "last_traded_at": "2021-07-18T10:35:31+00:00", "last_fetch_at": "2021-07-18T10:35:31+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCUSD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 26832.63639, "volume": 382.39958501, "converted_last": { "btc": 0.9983402, "eth": 16.094778, "usd": 31677 }, "converted_volume": { "btc": 381.765, "eth": 6155, "usd": 12113272 }, "trust_score": "green", "bid_ask_spread_percentage": 0.037272, "timestamp": "2021-07-18T10:35:31+00:00", "last_traded_at": "2021-07-18T10:35:31+00:00", "last_fetch_at": "2021-07-18T10:35:31+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCEUR", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "JPY", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 3486499.9999995, "volume": 230.78394761, "converted_last": { "btc": 0.99851333, "eth": 16.097569, "usd": 31682 }, "converted_volume": { "btc": 230.441, "eth": 3715, "usd": 7311811 }, "trust_score": "green", "bid_ask_spread_percentage": 0.028686, "timestamp": "2021-07-18T10:35:25+00:00", "last_traded_at": "2021-07-18T10:35:25+00:00", "last_fetch_at": "2021-07-18T10:35:25+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCJPY", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "GBP", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 23001, "volume": 153.39905336, "converted_last": { "btc": 0.99852093, "eth": 16.097692, "usd": 31683 }, "converted_volume": { "btc": 153.172, "eth": 2469, "usd": 4860101 }, "trust_score": "green", "bid_ask_spread_percentage": 0.086957, "timestamp": "2021-07-18T10:35:41+00:00", "last_traded_at": "2021-07-18T10:35:41+00:00", "last_fetch_at": "2021-07-18T10:35:41+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCGBP", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 31662, "volume": 124.82353618533257, "converted_last": { "btc": 1.002108, "eth": 16.197203, "usd": 31755 }, "converted_volume": { "btc": 125.087, "eth": 2022, "usd": 3963742 }, "trust_score": "green", "bid_ask_spread_percentage": 0.041042, "timestamp": "2021-07-18T10:26:18+00:00", "last_traded_at": "2021-07-18T10:26:18+00:00", "last_fetch_at": "2021-07-18T10:26:18+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/BTC/USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 31668, "volume": 150.39322968927624, "converted_last": { "btc": 0.99936939, "eth": 16.152945, "usd": 31668 }, "converted_volume": { "btc": 150.298, "eth": 2429, "usd": 4762653 }, "trust_score": "green", "bid_ask_spread_percentage": 0.031571, "timestamp": "2021-07-18T10:26:12+00:00", "last_traded_at": "2021-07-18T10:26:12+00:00", "last_fetch_at": "2021-07-18T10:26:12+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/BTC/USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 31649.99, "volume": 35206.426261271015, "converted_last": { "btc": 1.001727, "eth": 16.15695, "usd": 31774 }, "converted_volume": { "btc": 35267, "eth": 568828, "usd": 1118648209 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010032, "timestamp": "2021-07-18T10:39:13+00:00", "last_traded_at": "2021-07-18T10:39:13+00:00", "last_fetch_at": "2021-07-18T10:39:13+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/BTC_USDT?ref=37754157", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "WBTC", "target": "BTC", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 1.0003, "volume": 20.118083924822553, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 20.124119, "eth": 324.576, "usd": 638321 }, "trust_score": "green", "bid_ask_spread_percentage": 0.029991, "timestamp": "2021-07-18T10:38:02+00:00", "last_traded_at": "2021-07-18T10:38:02+00:00", "last_fetch_at": "2021-07-18T10:38:02+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/WBTC/BTC", "token_info_url": null, "coin_id": "wrapped-bitcoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDC", "market": { "name": "Serum DEX", "identifier": "serum_dex", "has_trading_incentive": false }, "last": 31611.7, "volume": 31.322400000000002, "converted_last": { "btc": 0.99895591, "eth": 16.175264, "usd": 31648 }, "converted_volume": { "btc": 31.289697, "eth": 506.648, "usd": 991291 }, "trust_score": "green", "bid_ask_spread_percentage": 0.030017, "timestamp": "2021-07-18T10:17:55+00:00", "last_traded_at": "2021-07-18T10:17:55+00:00", "last_fetch_at": "2021-07-18T10:40:10+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://dex.projectserum.com", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Serum DEX", "identifier": "serum_dex", "has_trading_incentive": false }, "last": 31597, "volume": 28.846999999999998, "converted_last": { "btc": 1.00005, "eth": 16.192985, "usd": 31683 }, "converted_volume": { "btc": 28.848452, "eth": 467.119, "usd": 913950 }, "trust_score": "green", "bid_ask_spread_percentage": 0.011693, "timestamp": "2021-07-18T10:17:53+00:00", "last_traded_at": "2021-07-18T10:17:53+00:00", "last_fetch_at": "2021-07-18T10:40:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://dex.projectserum.com", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Digifinex", "identifier": "digifinex", "has_trading_incentive": false }, "last": 31683.85, "volume": 3503.37146594, "converted_last": { "btc": 1.002799, "eth": 16.191078, "usd": 31821 }, "converted_volume": { "btc": 3513, "eth": 56723, "usd": 111482065 }, "trust_score": "green", "bid_ask_spread_percentage": 0.043008, "timestamp": "2021-07-18T10:32:13+00:00", "last_traded_at": "2021-07-18T10:32:13+00:00", "last_fetch_at": "2021-07-18T10:32:13+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.digifinex.com/en-ww/trade/USDT/BTC", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 31654, "volume": 955.9488609496431, "converted_last": { "btc": 1.001854, "eth": 16.158597, "usd": 31778 }, "converted_volume": { "btc": 957.722, "eth": 15447, "usd": 30378182 }, "trust_score": "green", "bid_ask_spread_percentage": 0.022113, "timestamp": "2021-07-18T10:38:04+00:00", "last_traded_at": "2021-07-18T10:38:04+00:00", "last_fetch_at": "2021-07-18T10:38:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/BTC/USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "BUSD", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 31669.99, "volume": 9149.213570053518, "converted_last": { "btc": 1.000196, "eth": 16.165031, "usd": 31700 }, "converted_volume": { "btc": 9151, "eth": 147897, "usd": 290028738 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010032, "timestamp": "2021-07-18T10:27:12+00:00", "last_traded_at": "2021-07-18T10:27:12+00:00", "last_fetch_at": "2021-07-18T10:27:12+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/BTC_BUSD?ref=37754157", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "binance-usd" }, { "base": "BTC", "target": "USDT", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 31661.45, "volume": 25718.26831, "converted_last": { "btc": 1.00209, "eth": 16.161968, "usd": 31787 }, "converted_volume": { "btc": 25772, "eth": 415658, "usd": 817517805 }, "trust_score": "green", "bid_ask_spread_percentage": 0.017995, "timestamp": "2021-07-18T10:37:51+00:00", "last_traded_at": "2021-07-18T10:37:51+00:00", "last_fetch_at": "2021-07-18T10:37:51+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/BTC-to-USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 31687.13, "volume": 25947.47742, "converted_last": { "btc": 0.99865653, "eth": 16.124566, "usd": 31687 }, "converted_volume": { "btc": 25913, "eth": 418392, "usd": 822201090 }, "trust_score": "green", "bid_ask_spread_percentage": 0.013789, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/BTC-to-USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "Coinbase Exchange", "identifier": "gdax", "has_trading_incentive": false }, "last": 31671.3, "volume": 5077.27630299, "converted_last": { "btc": 0.99842903, "eth": 16.10292, "usd": 31671 }, "converted_volume": { "btc": 5069, "eth": 81759, "usd": 160803941 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010032, "timestamp": "2021-07-18T10:37:23+00:00", "last_traded_at": "2021-07-18T10:37:23+00:00", "last_fetch_at": "2021-07-18T10:38:53+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://pro.coinbase.com/trade/BTC-USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "Cryptology", "identifier": "cryptology", "has_trading_incentive": false }, "last": 31719.9, "volume": 184.84924842, "converted_last": { "btc": 0.99960161, "eth": 16.139451, "usd": 31720 }, "converted_volume": { "btc": 184.776, "eth": 2983, "usd": 5863400 }, "trust_score": "green", "bid_ask_spread_percentage": 0.018297, "timestamp": "2021-07-18T10:32:04+00:00", "last_traded_at": "2021-07-18T10:32:04+00:00", "last_fetch_at": "2021-07-18T10:32:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 31653, "volume": 8516.779072697691, "converted_last": { "btc": 0.99791227, "eth": 16.095016, "usd": 31653 }, "converted_volume": { "btc": 8499, "eth": 137078, "usd": 269581608 }, "trust_score": "green", "bid_ask_spread_percentage": 0.013159, "timestamp": "2021-07-18T10:38:01+00:00", "last_traded_at": "2021-07-18T10:38:01+00:00", "last_fetch_at": "2021-07-18T10:38:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/BTC/USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 26820.18, "volume": 48.1686, "converted_last": { "btc": 0.9992379, "eth": 16.150846, "usd": 31662 }, "converted_volume": { "btc": 48.131891, "eth": 777.964, "usd": 1525128 }, "trust_score": "green", "bid_ask_spread_percentage": 0.04026, "timestamp": "2021-07-18T10:25:32+00:00", "last_traded_at": "2021-07-18T10:25:32+00:00", "last_fetch_at": "2021-07-18T10:25:32+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Wootrade", "identifier": "wootrade", "has_trading_incentive": false }, "last": 31652.52, "volume": 513.07497877, "converted_last": { "btc": 1.001808, "eth": 16.157842, "usd": 31777 }, "converted_volume": { "btc": 514.002, "eth": 8290, "usd": 16303755 }, "trust_score": "green", "bid_ask_spread_percentage": 0.019837, "timestamp": "2021-07-18T10:38:24+00:00", "last_traded_at": "2021-07-18T10:38:24+00:00", "last_fetch_at": "2021-07-18T10:38:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://x.woo.network/spot", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Bitstamp", "identifier": "bitstamp", "has_trading_incentive": false }, "last": 31697.44, "volume": 1697.60717519, "converted_last": { "btc": 1.00012, "eth": 16.1638, "usd": 31697 }, "converted_volume": { "btc": 1698, "eth": 27440, "usd": 53809802 }, "trust_score": "green", "bid_ask_spread_percentage": 0.052496, "timestamp": "2021-07-18T10:27:08+00:00", "last_traded_at": "2021-07-18T10:27:08+00:00", "last_fetch_at": "2021-07-18T10:27:08+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Cryptology", "identifier": "cryptology", "has_trading_incentive": false }, "last": 26873.33, "volume": 288.75425643, "converted_last": { "btc": 0.9997636, "eth": 16.142066, "usd": 31725 }, "converted_volume": { "btc": 288.686, "eth": 4661, "usd": 9160740 }, "trust_score": "green", "bid_ask_spread_percentage": 0.299378, "timestamp": "2021-07-18T10:32:05+00:00", "last_traded_at": "2021-07-18T10:32:05+00:00", "last_fetch_at": "2021-07-18T10:32:05+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 0.061964, "volume": 2193.14054369, "converted_last": { "btc": 1, "eth": 16.121537, "usd": 31730 }, "converted_volume": { "btc": 135.896, "eth": 2191, "usd": 4311927 }, "trust_score": "green", "bid_ask_spread_percentage": 0.048434, "timestamp": "2021-07-18T10:35:29+00:00", "last_traded_at": "2021-07-18T10:35:29+00:00", "last_fetch_at": "2021-07-18T10:35:29+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/ETHBTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "WAVES", "target": "BTC", "market": { "name": "Waves.Exchange", "identifier": "waves", "has_trading_incentive": false }, "last": 0.00041674, "volume": 31349.23848339, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 13.064482, "eth": 210.942, "usd": 414533 }, "trust_score": "green", "bid_ask_spread_percentage": 0.081586, "timestamp": "2021-07-18T10:31:51+00:00", "last_traded_at": "2021-07-18T10:31:51+00:00", "last_fetch_at": "2021-07-18T10:31:51+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "waves", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "UST", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 31668, "volume": 1448.11547116, "converted_last": { "btc": 1.002398, "eth": 16.160192, "usd": 31806 }, "converted_volume": { "btc": 1452, "eth": 23402, "usd": 46058390 }, "trust_score": "green", "bid_ask_spread_percentage": 0.031576, "timestamp": "2021-07-18T10:35:41+00:00", "last_traded_at": "2021-07-18T10:35:41+00:00", "last_fetch_at": "2021-07-18T10:35:41+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCUST", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "EUR", "market": { "name": "Kraken", "identifier": "kraken", "has_trading_incentive": false }, "last": 26867.9, "volume": 896.8823939, "converted_last": { "btc": 1.000789, "eth": 16.174606, "usd": 31719 }, "converted_volume": { "btc": 897.59, "eth": 14507, "usd": 28447881 }, "trust_score": "green", "bid_ask_spread_percentage": 0.012233, "timestamp": "2021-07-18T10:27:24+00:00", "last_traded_at": "2021-07-18T10:27:24+00:00", "last_fetch_at": "2021-07-18T10:27:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trade.kraken.com/markets/kraken/btc/eur", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BCH", "target": "BTC", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 0.014106, "volume": 484.7410701120091, "converted_last": { "btc": 1, "eth": 16.163137, "usd": 31688 }, "converted_volume": { "btc": 6.837758, "eth": 110.52, "usd": 216675 }, "trust_score": "green", "bid_ask_spread_percentage": 0.056681, "timestamp": "2021-07-18T10:26:12+00:00", "last_traded_at": "2021-07-18T10:26:12+00:00", "last_fetch_at": "2021-07-18T10:26:12+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/BCH/BTC", "token_info_url": null, "coin_id": "bitcoin-cash", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "Kraken", "identifier": "kraken", "has_trading_incentive": false }, "last": 31664.4, "volume": 1913.84051414, "converted_last": { "btc": 0.99907746, "eth": 16.146952, "usd": 31664 }, "converted_volume": { "btc": 1912, "eth": 30903, "usd": 60600612 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010316, "timestamp": "2021-07-18T10:27:22+00:00", "last_traded_at": "2021-07-18T10:27:22+00:00", "last_fetch_at": "2021-07-18T10:27:22+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trade.kraken.com/markets/kraken/btc/usd", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BNB", "target": "BTC", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 0.0096363, "volume": 1229.482507809014, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 11.847662, "eth": 191.087, "usd": 375799 }, "trust_score": "green", "bid_ask_spread_percentage": 0.130704, "timestamp": "2021-07-18T10:38:02+00:00", "last_traded_at": "2021-07-18T10:38:02+00:00", "last_fetch_at": "2021-07-18T10:38:02+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/BNB/BTC", "token_info_url": null, "coin_id": "binancecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "OKEx", "identifier": "okex", "has_trading_incentive": false }, "last": 31694, "volume": 14079.05656805, "converted_last": { "btc": 1.00312, "eth": 16.197061, "usd": 31812 }, "converted_volume": { "btc": 14123, "eth": 228039, "usd": 447879284 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010316, "timestamp": "2021-07-18T10:30:37+00:00", "last_traded_at": "2021-07-18T10:30:37+00:00", "last_fetch_at": "2021-07-18T10:30:37+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.okex.com/markets/spot-info/btc-usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "WhiteBIT", "identifier": "whitebit", "has_trading_incentive": false }, "last": 31651.72, "volume": 4287.247892, "converted_last": { "btc": 1.001782, "eth": 16.19197, "usd": 31743 }, "converted_volume": { "btc": 4295, "eth": 69419, "usd": 136089746 }, "trust_score": "green", "bid_ask_spread_percentage": 0.017532, "timestamp": "2021-07-18T10:25:38+00:00", "last_traded_at": "2021-07-18T10:25:38+00:00", "last_fetch_at": "2021-07-18T10:25:38+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://whitebit.com/trade/BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Dex-Trade", "identifier": "dextrade", "has_trading_incentive": false }, "last": 31687.68, "volume": 628.66896074, "converted_last": { "btc": 1.00292, "eth": 16.193411, "usd": 31822 }, "converted_volume": { "btc": 630.505, "eth": 10180, "usd": 20005768 }, "trust_score": "green", "bid_ask_spread_percentage": 0.288005, "timestamp": "2021-07-18T10:31:23+00:00", "last_traded_at": "2021-07-18T10:31:23+00:00", "last_fetch_at": "2021-07-18T10:31:23+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "ETH", "target": "BTC", "market": { "name": "Digifinex", "identifier": "digifinex", "has_trading_incentive": false }, "last": 0.062042, "volume": 9723.8144, "converted_last": { "btc": 1, "eth": 16.145883, "usd": 31733 }, "converted_volume": { "btc": 603.285, "eth": 9741, "usd": 19143763 }, "trust_score": "green", "bid_ask_spread_percentage": 0.195023, "timestamp": "2021-07-18T10:32:13+00:00", "last_traded_at": "2021-07-18T10:32:13+00:00", "last_fetch_at": "2021-07-18T10:32:13+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.digifinex.com/en-ww/trade/BTC/ETH", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "WBTC", "target": "BTC", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 1.00059, "volume": 200.20735651965342, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 200.325, "eth": 3235, "usd": 6356279 }, "trust_score": "green", "bid_ask_spread_percentage": 0.028983, "timestamp": "2021-07-18T10:31:19+00:00", "last_traded_at": "2021-07-18T10:31:19+00:00", "last_fetch_at": "2021-07-18T10:31:19+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/WBTC_BTC?ref=37754157", "token_info_url": null, "coin_id": "wrapped-bitcoin", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 0.061895, "volume": 108018.61603279748, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 6686, "eth": 107833, "usd": 212068758 }, "trust_score": "green", "bid_ask_spread_percentage": 0.011617, "timestamp": "2021-07-18T10:38:58+00:00", "last_traded_at": "2021-07-18T10:38:58+00:00", "last_fetch_at": "2021-07-18T10:38:58+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/ETH_BTC?ref=37754157", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 0.0619325, "volume": 914.9950722560852, "converted_last": { "btc": 1, "eth": 16.163137, "usd": 31688 }, "converted_volume": { "btc": 56.668, "eth": 915.932, "usd": 1795692 }, "trust_score": "green", "bid_ask_spread_percentage": 0.052462, "timestamp": "2021-07-18T10:26:16+00:00", "last_traded_at": "2021-07-18T10:26:16+00:00", "last_fetch_at": "2021-07-18T10:26:16+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/ETH/BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "LBank", "identifier": "lbank", "has_trading_incentive": false }, "last": 0.06193133, "volume": 9998.7452, "converted_last": { "btc": 1, "eth": 16.161861, "usd": 31694 }, "converted_volume": { "btc": 619.236, "eth": 10008, "usd": 19625829 }, "trust_score": "green", "bid_ask_spread_percentage": 0.103465, "timestamp": "2021-07-18T10:27:33+00:00", "last_traded_at": "2021-07-18T10:27:33+00:00", "last_fetch_at": "2021-07-18T10:27:33+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.lbank.info/exchange/eth/btc", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "ZB", "identifier": "zb", "has_trading_incentive": false }, "last": 31674.93, "volume": 16955.8862, "converted_last": { "btc": 1.002517, "eth": 16.162947, "usd": 31813 }, "converted_volume": { "btc": 16999, "eth": 274057, "usd": 539414290 }, "trust_score": "green", "bid_ask_spread_percentage": 0.058449, "timestamp": "2021-07-18T10:33:47+00:00", "last_traded_at": "2021-07-18T10:33:47+00:00", "last_fetch_at": "2021-07-18T10:33:47+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trans.zb.com/btcusdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "XRP", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.000018511, "volume": 25380854.8, "converted_last": { "btc": 1, "eth": 16.128257, "usd": 31721 }, "converted_volume": { "btc": 469.825, "eth": 7577, "usd": 14903381 }, "trust_score": "green", "bid_ask_spread_percentage": 0.027011, "timestamp": "2021-07-18T10:37:36+00:00", "last_traded_at": "2021-07-18T10:37:36+00:00", "last_fetch_at": "2021-07-18T10:37:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/XRP-to-BTC", "token_info_url": null, "coin_id": "ripple", "target_coin_id": "bitcoin" }, { "base": "XRP", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.000018541, "volume": 25365195.8, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 470.296, "eth": 7594, "usd": 14922381 }, "trust_score": "green", "bid_ask_spread_percentage": 0.026963, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/XRP-to-BTC", "token_info_url": null, "coin_id": "ripple", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 31693.55546, "volume": 734.43672, "converted_last": { "btc": 1.001543, "eth": 16.171165, "usd": 31779 }, "converted_volume": { "btc": 735.57, "eth": 11877, "usd": 23339448 }, "trust_score": "green", "bid_ask_spread_percentage": 0.024916, "timestamp": "2021-07-18T10:31:36+00:00", "last_traded_at": "2021-07-18T10:31:36+00:00", "last_fetch_at": "2021-07-18T10:31:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/BTC-to-USDC", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "BTC", "target": "USDC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 31661.63615, "volume": 732.93628, "converted_last": { "btc": 0.99966773, "eth": 16.123329, "usd": 31709 }, "converted_volume": { "btc": 732.693, "eth": 11817, "usd": 23240443 }, "trust_score": "green", "bid_ask_spread_percentage": 0.013154, "timestamp": "2021-07-18T10:38:10+00:00", "last_traded_at": "2021-07-18T10:38:10+00:00", "last_fetch_at": "2021-07-18T10:38:10+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/BTC-to-USDC", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "ETH", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.061884, "volume": 29717.2928, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 1839, "eth": 29661, "usd": 58332439 }, "trust_score": "green", "bid_ask_spread_percentage": 0.016159, "timestamp": "2021-07-18T10:38:30+00:00", "last_traded_at": "2021-07-18T10:38:30+00:00", "last_fetch_at": "2021-07-18T10:38:30+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/ETH-to-BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "UAH", "market": { "name": "WhiteBIT", "identifier": "whitebit", "has_trading_incentive": false }, "last": 890149.51, "volume": 11.203193, "converted_last": { "btc": 1.03218, "eth": 16.683293, "usd": 32706 }, "converted_volume": { "btc": 11.563711, "eth": 186.906, "usd": 366413 }, "trust_score": "green", "bid_ask_spread_percentage": 0.018344, "timestamp": "2021-07-18T10:25:38+00:00", "last_traded_at": "2021-07-18T10:25:38+00:00", "last_fetch_at": "2021-07-18T10:25:38+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://whitebit.com/trade/BTC_UAH", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "LBank", "identifier": "lbank", "has_trading_incentive": false }, "last": 31669.64, "volume": 6933.2841, "converted_last": { "btc": 1.002349, "eth": 16.199832, "usd": 31768 }, "converted_volume": { "btc": 6950, "eth": 112318, "usd": 220257258 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010221, "timestamp": "2021-07-18T10:27:35+00:00", "last_traded_at": "2021-07-18T10:27:35+00:00", "last_fetch_at": "2021-07-18T10:27:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.lbank.info/exchange/btc/usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "LTC", "target": "BTC", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 0.003812, "volume": 2011.4533276495279, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 7.66766, "eth": 123.669, "usd": 243212 }, "trust_score": "green", "bid_ask_spread_percentage": 0.091791, "timestamp": "2021-07-18T10:38:02+00:00", "last_traded_at": "2021-07-18T10:38:02+00:00", "last_fetch_at": "2021-07-18T10:38:02+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/LTC/BTC", "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Bitstamp", "identifier": "bitstamp", "has_trading_incentive": false }, "last": 26841.44, "volume": 808.45995818, "converted_last": { "btc": 0.9969589, "eth": 16.130124, "usd": 31687 }, "converted_volume": { "btc": 806.001, "eth": 13041, "usd": 25617988 }, "trust_score": "green", "bid_ask_spread_percentage": 0.083284, "timestamp": "2021-07-18T10:11:54+00:00", "last_traded_at": "2021-07-18T10:11:54+00:00", "last_fetch_at": "2021-07-18T10:11:54+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "JPY", "market": { "name": "bitFlyer", "identifier": "bitflyer", "has_trading_incentive": false }, "last": 3494196, "volume": 1941.50662714, "converted_last": { "btc": 1.00125, "eth": 16.166862, "usd": 31752 }, "converted_volume": { "btc": 1944, "eth": 31388, "usd": 61647550 }, "trust_score": "green", "bid_ask_spread_percentage": 0.045409, "timestamp": "2021-07-18T10:30:22+00:00", "last_traded_at": "2021-07-18T10:30:22+00:00", "last_fetch_at": "2021-07-18T10:30:22+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://bitflyer.com/en-jp/ex/simpleex", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.06198, "volume": 30048.9281, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 1862, "eth": 30071, "usd": 59094535 }, "trust_score": "green", "bid_ask_spread_percentage": 0.029039, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/ETH-to-BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "LTC", "target": "BTC", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 0.00381925, "volume": 82.51463441775218, "converted_last": { "btc": 1, "eth": 16.163137, "usd": 31688 }, "converted_volume": { "btc": 0.31514402, "eth": 5.093716, "usd": 9986.28 }, "trust_score": "green", "bid_ask_spread_percentage": 0.104623, "timestamp": "2021-07-18T10:26:14+00:00", "last_traded_at": "2021-07-18T10:26:14+00:00", "last_fetch_at": "2021-07-18T10:26:14+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/LTC/BTC", "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "JPY", "market": { "name": "GMO Japan", "identifier": "gmo_japan", "has_trading_incentive": false }, "last": 3490020, "volume": 133.5681, "converted_last": { "btc": 0.99985054, "eth": 16.126278, "usd": 31714 }, "converted_volume": { "btc": 133.548, "eth": 2154, "usd": 4236043 }, "trust_score": "green", "bid_ask_spread_percentage": 0.026455, "timestamp": "2021-07-18T10:38:11+00:00", "last_traded_at": "2021-07-18T10:38:11+00:00", "last_fetch_at": "2021-07-18T10:38:11+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://coin.z.com/jp/corp/information/btc-market/", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Huobi Global", "identifier": "huobi", "has_trading_incentive": false }, "last": 31684.73, "volume": 10514.569255059265, "converted_last": { "btc": 1.002827, "eth": 16.20883, "usd": 31778 }, "converted_volume": { "btc": 10544, "eth": 170429, "usd": 334127402 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010032, "timestamp": "2021-07-18T10:26:57+00:00", "last_traded_at": "2021-07-18T10:26:57+00:00", "last_fetch_at": "2021-07-18T10:26:57+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.huobi.com/en-us/exchange/btc_usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Okcoin", "identifier": "okcoin", "has_trading_incentive": false }, "last": 31682.45, "volume": 177.3329, "converted_last": { "btc": 0.99964698, "eth": 16.156156, "usd": 31682 }, "converted_volume": { "btc": 177.27, "eth": 2865, "usd": 5618341 }, "trust_score": "green", "bid_ask_spread_percentage": 0.017517, "timestamp": "2021-07-18T10:27:03+00:00", "last_traded_at": "2021-07-18T10:27:03+00:00", "last_fetch_at": "2021-07-18T10:27:03+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.okcoin.com/market#product=btc_usd", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Coinbase Exchange", "identifier": "gdax", "has_trading_incentive": false }, "last": 26852.7, "volume": 433.76641011, "converted_last": { "btc": 0.99935541, "eth": 16.117861, "usd": 31701 }, "converted_volume": { "btc": 433.487, "eth": 6991, "usd": 13750693 }, "trust_score": "green", "bid_ask_spread_percentage": 0.020929, "timestamp": "2021-07-18T10:37:21+00:00", "last_traded_at": "2021-07-18T10:37:21+00:00", "last_fetch_at": "2021-07-18T10:38:46+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://pro.coinbase.com/trade/BTC-EUR", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Coinsbit", "identifier": "coinsbit", "has_trading_incentive": false }, "last": 31650.02, "volume": 8775.0086578, "converted_last": { "btc": 1.001728, "eth": 16.189796, "usd": 31748 }, "converted_volume": { "btc": 8790, "eth": 142066, "usd": 278592646 }, "trust_score": "green", "bid_ask_spread_percentage": 0.039988, "timestamp": "2021-07-18T10:27:00+00:00", "last_traded_at": "2021-07-18T10:27:00+00:00", "last_fetch_at": "2021-07-18T10:27:00+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://coinsbit.io/trade/BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "BitMart", "identifier": "bitmart", "has_trading_incentive": false }, "last": 31728.23, "volume": 1567.86636, "converted_last": { "btc": 1.004204, "eth": 16.190145, "usd": 31866 }, "converted_volume": { "btc": 1574, "eth": 25384, "usd": 49962157 }, "trust_score": "green", "bid_ask_spread_percentage": 0.020511, "timestamp": "2021-07-18T10:33:04+00:00", "last_traded_at": "2021-07-18T10:33:04+00:00", "last_fetch_at": "2021-07-18T10:33:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitmart.com/trade/en?symbol=BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "BKEX", "identifier": "bkex", "has_trading_incentive": false }, "last": 31662.32, "volume": 8376.1499, "converted_last": { "btc": 1.002118, "eth": 16.197366, "usd": 31755 }, "converted_volume": { "btc": 8394, "eth": 135672, "usd": 265985384 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010442, "timestamp": "2021-07-18T10:26:05+00:00", "last_traded_at": "2021-07-18T10:26:05+00:00", "last_fetch_at": "2021-07-18T10:26:05+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bkex.com/#/trade/BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "XRP", "target": "BTC", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 0.00001853, "volume": 126136.03022126282, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 2.337301, "eth": 37.697594, "usd": 74137 }, "trust_score": "green", "bid_ask_spread_percentage": 0.108108, "timestamp": "2021-07-18T10:38:02+00:00", "last_traded_at": "2021-07-18T10:38:02+00:00", "last_fetch_at": "2021-07-18T10:38:02+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/XRP/BTC", "token_info_url": null, "coin_id": "ripple", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Hoo.com", "identifier": "hoo", "has_trading_incentive": false }, "last": 31661.12, "volume": 10968.532010435627, "converted_last": { "btc": 1.00208, "eth": 16.196752, "usd": 31754 }, "converted_volume": { "btc": 10991, "eth": 177655, "usd": 348293507 }, "trust_score": "green", "bid_ask_spread_percentage": 0.012052, "timestamp": "2021-07-18T10:26:24+00:00", "last_traded_at": "2021-07-18T10:26:24+00:00", "last_fetch_at": "2021-07-18T10:26:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hoo.com/spot/btc-usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Zipmex", "identifier": "zipmex", "has_trading_incentive": false }, "last": 31626, "volume": 0.035913, "converted_last": { "btc": 1.000968, "eth": 16.182089, "usd": 31717 }, "converted_volume": { "btc": 0.03594777, "eth": 0.58114737, "usd": 1139.06 }, "trust_score": "green", "bid_ask_spread_percentage": 0.104167, "timestamp": "2021-07-18T10:23:36+00:00", "last_traded_at": "2021-07-18T10:23:36+00:00", "last_fetch_at": "2021-07-18T10:23:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trade.zipmex.com", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BNB", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.0096118, "volume": 1916.52, "converted_last": { "btc": 1, "eth": 16.122532, "usd": 31730 }, "converted_volume": { "btc": 18.421207, "eth": 296.996, "usd": 584502 }, "trust_score": "green", "bid_ask_spread_percentage": 0.046706, "timestamp": "2021-07-18T10:34:34+00:00", "last_traded_at": "2021-07-18T10:34:34+00:00", "last_fetch_at": "2021-07-18T10:34:34+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/BNB-to-BTC", "token_info_url": null, "coin_id": "binancecoin", "target_coin_id": "bitcoin" }, { "base": "EOS", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.00011648, "volume": 2933208.06, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 341.66, "eth": 5517, "usd": 10840792 }, "trust_score": "green", "bid_ask_spread_percentage": 0.051498, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/EOS-to-BTC", "token_info_url": null, "coin_id": "eos", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 31659.655649, "volume": 51.7444, "converted_last": { "btc": 0.99915461, "eth": 16.1495, "usd": 31660 }, "converted_volume": { "btc": 51.701, "eth": 835.646, "usd": 1638210 }, "trust_score": "green", "bid_ask_spread_percentage": 0.024712, "timestamp": "2021-07-18T10:25:34+00:00", "last_traded_at": "2021-07-18T10:25:34+00:00", "last_fetch_at": "2021-07-18T10:25:34+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BNB", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.0096118, "volume": 1970.02, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 18.935438, "eth": 305.736, "usd": 600817 }, "trust_score": "green", "bid_ask_spread_percentage": 0.066518, "timestamp": "2021-07-18T10:31:34+00:00", "last_traded_at": "2021-07-18T10:31:34+00:00", "last_fetch_at": "2021-07-18T10:31:34+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/BNB-to-BTC", "token_info_url": null, "coin_id": "binancecoin", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "AlterDice", "identifier": "alterdice", "has_trading_incentive": false }, "last": 0.061889, "volume": 998.94, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 61.823, "eth": 997.13, "usd": 1960990 }, "trust_score": "green", "bid_ask_spread_percentage": 0.090448, "timestamp": "2021-07-18T10:38:09+00:00", "last_traded_at": "2021-07-18T10:38:09+00:00", "last_fetch_at": "2021-07-18T10:38:09+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Crypto.com Exchange", "identifier": "crypto_com", "has_trading_incentive": false }, "last": 31675.27, "volume": 994.279392, "converted_last": { "btc": 1.002528, "eth": 16.202712, "usd": 31774 }, "converted_volume": { "btc": 996.793, "eth": 16110, "usd": 31591982 }, "trust_score": "green", "bid_ask_spread_percentage": 0.015975, "timestamp": "2021-07-18T10:27:16+00:00", "last_traded_at": "2021-07-18T10:27:16+00:00", "last_fetch_at": "2021-07-18T10:27:16+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://crypto.com/exchange/trade/spot/BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "EOS", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.00011634, "volume": 2941934.8, "converted_last": { "btc": 1, "eth": 16.128257, "usd": 31721 }, "converted_volume": { "btc": 342.265, "eth": 5520, "usd": 10857024 }, "trust_score": "green", "bid_ask_spread_percentage": 0.068746, "timestamp": "2021-07-18T10:37:42+00:00", "last_traded_at": "2021-07-18T10:37:42+00:00", "last_fetch_at": "2021-07-18T10:37:42+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/EOS-to-BTC", "token_info_url": null, "coin_id": "eos", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "P2PB2B", "identifier": "p2pb2b", "has_trading_incentive": false }, "last": 31687.7, "volume": 6444.828543, "converted_last": { "btc": 0.99858688, "eth": 16.123067, "usd": 31688 }, "converted_volume": { "btc": 6436, "eth": 103910, "usd": 204221793 }, "trust_score": "green", "bid_ask_spread_percentage": 0.108205, "timestamp": "2021-07-18T10:32:01+00:00", "last_traded_at": "2021-07-18T10:32:01+00:00", "last_fetch_at": "2021-07-18T10:32:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "LTC", "target": "BTC", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 0.00382682, "volume": 622.65305348, "converted_last": { "btc": 1, "eth": 16.163164, "usd": 31686 }, "converted_volume": { "btc": 2.382781, "eth": 38.513283, "usd": 75502 }, "trust_score": "green", "bid_ask_spread_percentage": 0.224896, "timestamp": "2021-07-18T10:25:31+00:00", "last_traded_at": "2021-07-18T10:25:31+00:00", "last_fetch_at": "2021-07-18T10:25:31+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Coinsbit", "identifier": "coinsbit", "has_trading_incentive": false }, "last": 0.061952, "volume": 33077.36988703, "converted_last": { "btc": 1, "eth": 16.161861, "usd": 31694 }, "converted_volume": { "btc": 2049, "eth": 33119, "usd": 64946896 }, "trust_score": "green", "bid_ask_spread_percentage": 0.011622, "timestamp": "2021-07-18T10:27:01+00:00", "last_traded_at": "2021-07-18T10:27:01+00:00", "last_fetch_at": "2021-07-18T10:27:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://coinsbit.io/trade/ETH_BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 27159.2, "volume": 1270.6222043901996, "converted_last": { "btc": 1.010487, "eth": 16.315591, "usd": 32063 }, "converted_volume": { "btc": 1284, "eth": 20731, "usd": 40739352 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010037, "timestamp": "2021-07-18T10:31:33+00:00", "last_traded_at": "2021-07-18T10:31:33+00:00", "last_fetch_at": "2021-07-18T10:31:33+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/BTC_EUR?ref=37754157", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Exrates", "identifier": "exrates", "has_trading_incentive": false }, "last": 31650.31, "volume": 185.22672503, "converted_last": { "btc": 1.00001, "eth": 16.129251, "usd": 31720 }, "converted_volume": { "btc": 185.229, "eth": 2988, "usd": 5875300 }, "trust_score": "green", "bid_ask_spread_percentage": 0.221729, "timestamp": "2021-07-18T10:39:46+00:00", "last_traded_at": "2021-07-18T10:39:46+00:00", "last_fetch_at": "2021-07-18T10:39:46+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exrates.me/trading/BTCUSDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "BTSE", "identifier": "btse", "has_trading_incentive": false }, "last": 31664.5, "volume": 1725.3684215940564, "converted_last": { "btc": 0.99925894, "eth": 16.15116, "usd": 31665 }, "converted_volume": { "btc": 1724, "eth": 27867, "usd": 54632928 }, "trust_score": "green", "bid_ask_spread_percentage": 0.04419, "timestamp": "2021-07-18T10:26:27+00:00", "last_traded_at": "2021-07-18T10:26:27+00:00", "last_fetch_at": "2021-07-18T10:26:27+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.btse.com/en/trading/BTC-USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "LTC", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.0038189, "volume": 62415.044, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 238.357, "eth": 3849, "usd": 7563004 }, "trust_score": "green", "bid_ask_spread_percentage": 0.026182, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/LTC-to-BTC", "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "P2PB2B", "identifier": "p2pb2b", "has_trading_incentive": false }, "last": 31685.01, "volume": 6430.413335, "converted_last": { "btc": 1.002836, "eth": 16.191671, "usd": 31823 }, "converted_volume": { "btc": 6449, "eth": 104119, "usd": 204632026 }, "trust_score": "green", "bid_ask_spread_percentage": 0.14126, "timestamp": "2021-07-18T10:32:01+00:00", "last_traded_at": "2021-07-18T10:32:01+00:00", "last_fetch_at": "2021-07-18T10:32:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDC", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 31639.625721, "volume": 5.35795179, "converted_last": { "btc": 0.99983838, "eth": 16.160552, "usd": 31681 }, "converted_volume": { "btc": 5.357086, "eth": 86.587, "usd": 169747 }, "trust_score": "green", "bid_ask_spread_percentage": 0.075566, "timestamp": "2021-07-18T10:25:32+00:00", "last_traded_at": "2021-07-18T10:25:32+00:00", "last_fetch_at": "2021-07-18T10:25:32+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "BTC", "target": "USDC", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 31651.49, "volume": 1189.5871447627921, "converted_last": { "btc": 0.99934738, "eth": 16.118163, "usd": 31699 }, "converted_volume": { "btc": 1189, "eth": 19174, "usd": 37708153 }, "trust_score": "green", "bid_ask_spread_percentage": 0.013602, "timestamp": "2021-07-18T10:38:35+00:00", "last_traded_at": "2021-07-18T10:38:35+00:00", "last_fetch_at": "2021-07-18T10:38:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/BTC_USDC?ref=37754157", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "BCH", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.014079, "volume": 14503.3432, "converted_last": { "btc": 1, "eth": 16.128257, "usd": 31721 }, "converted_volume": { "btc": 204.193, "eth": 3293, "usd": 6477220 }, "trust_score": "green", "bid_ask_spread_percentage": 0.078086, "timestamp": "2021-07-18T10:37:54+00:00", "last_traded_at": "2021-07-18T10:37:54+00:00", "last_fetch_at": "2021-07-18T10:37:54+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/BCH-to-BTC", "token_info_url": null, "coin_id": "bitcoin-cash", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Coinbase Exchange", "identifier": "gdax", "has_trading_incentive": false }, "last": 0.0619, "volume": 7298.21030466, "converted_last": { "btc": 1, "eth": 16.128257, "usd": 31721 }, "converted_volume": { "btc": 451.759, "eth": 7286, "usd": 14330314 }, "trust_score": "green", "bid_ask_spread_percentage": 0.016155, "timestamp": "2021-07-18T10:37:24+00:00", "last_traded_at": "2021-07-18T10:37:24+00:00", "last_fetch_at": "2021-07-18T10:38:46+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://pro.coinbase.com/trade/ETH-BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "Binance US", "identifier": "binance_us", "has_trading_incentive": false }, "last": 31662.5, "volume": 760.8263284358468, "converted_last": { "btc": 0.99821177, "eth": 16.099847, "usd": 31663 }, "converted_volume": { "btc": 759.466, "eth": 12249, "usd": 24089664 }, "trust_score": "green", "bid_ask_spread_percentage": 0.0112, "timestamp": "2021-07-18T10:38:10+00:00", "last_traded_at": "2021-07-18T10:38:10+00:00", "last_fetch_at": "2021-07-18T10:38:10+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.us/en/trade/BTC_USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Coineal", "identifier": "coineal", "has_trading_incentive": false }, "last": 31668.38, "volume": 735.93523, "converted_last": { "btc": 1.00231, "eth": 16.183172, "usd": 31806 }, "converted_volume": { "btc": 737.635, "eth": 11910, "usd": 23407030 }, "trust_score": "green", "bid_ask_spread_percentage": 0.120052, "timestamp": "2021-07-18T10:32:03+00:00", "last_traded_at": "2021-07-18T10:32:03+00:00", "last_fetch_at": "2021-07-18T10:32:03+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "ADA", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.0000378, "volume": 7025835, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 265.577, "eth": 4288, "usd": 8426680 }, "trust_score": "green", "bid_ask_spread_percentage": 0.023811, "timestamp": "2021-07-18T10:31:37+00:00", "last_traded_at": "2021-07-18T10:31:37+00:00", "last_fetch_at": "2021-07-18T10:31:37+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/ADA-to-BTC", "token_info_url": null, "coin_id": "cardano", "target_coin_id": "bitcoin" }, { "base": "ADA", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.000037788, "volume": 6973384, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 263.51, "eth": 4250, "usd": 8358339 }, "trust_score": "green", "bid_ask_spread_percentage": 0.034394, "timestamp": "2021-07-18T10:38:47+00:00", "last_traded_at": "2021-07-18T10:38:47+00:00", "last_fetch_at": "2021-07-18T10:38:47+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/ADA-to-BTC", "token_info_url": null, "coin_id": "cardano", "target_coin_id": "bitcoin" }, { "base": "LINK", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.00049715, "volume": 38218.1, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 19.000128, "eth": 306.447, "usd": 602669 }, "trust_score": "green", "bid_ask_spread_percentage": 0.028185, "timestamp": "2021-07-18T10:38:36+00:00", "last_traded_at": "2021-07-18T10:38:36+00:00", "last_fetch_at": "2021-07-18T10:38:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/LINK-to-BTC", "token_info_url": null, "coin_id": "chainlink", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 31657.515435, "volume": 36.7318, "converted_last": { "btc": 1.001966, "eth": 16.194935, "usd": 31749 }, "converted_volume": { "btc": 36.804002, "eth": 594.869, "usd": 1166188 }, "trust_score": "green", "bid_ask_spread_percentage": 0.033862, "timestamp": "2021-07-18T10:25:32+00:00", "last_traded_at": "2021-07-18T10:25:32+00:00", "last_fetch_at": "2021-07-18T10:25:32+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "HIT", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.00000575, "volume": 1227543.4, "converted_last": { "btc": 1, "eth": 16.122532, "usd": 31730 }, "converted_volume": { "btc": 7.058375, "eth": 113.799, "usd": 223961 }, "trust_score": "green", "bid_ask_spread_percentage": 0.086957, "timestamp": "2021-07-18T10:34:04+00:00", "last_traded_at": "2021-07-18T10:34:04+00:00", "last_fetch_at": "2021-07-18T10:34:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/HIT-to-BTC", "token_info_url": null, "coin_id": "hitbtc-token", "target_coin_id": "bitcoin" }, { "base": "BCH", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.014092, "volume": 14505.7196, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 204.415, "eth": 3301, "usd": 6486026 }, "trust_score": "green", "bid_ask_spread_percentage": 0.141774, "timestamp": "2021-07-18T10:31:34+00:00", "last_traded_at": "2021-07-18T10:31:34+00:00", "last_fetch_at": "2021-07-18T10:31:34+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/BCH-to-BTC", "token_info_url": null, "coin_id": "bitcoin-cash", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "CoinEx", "identifier": "coinex", "has_trading_incentive": false }, "last": 31701, "volume": 466.78246029, "converted_last": { "btc": 1.003342, "eth": 16.200638, "usd": 31819 }, "converted_volume": { "btc": 468.342, "eth": 7562, "usd": 14852442 }, "trust_score": "green", "bid_ask_spread_percentage": 0.112551, "timestamp": "2021-07-18T10:30:09+00:00", "last_traded_at": "2021-07-18T10:30:09+00:00", "last_fetch_at": "2021-07-18T10:30:09+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.coinex.com/trading?currency=USDT&dest=BTC#limit", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Bitget", "identifier": "bitget", "has_trading_incentive": false }, "last": 31646.74, "volume": 9565.0049, "converted_last": { "btc": 1.001625, "eth": 16.184339, "usd": 31746 }, "converted_volume": { "btc": 9581, "eth": 154803, "usd": 303653187 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010599, "timestamp": "2021-07-18T10:28:07+00:00", "last_traded_at": "2021-07-18T10:28:07+00:00", "last_fetch_at": "2021-07-18T10:28:07+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitget.io/en/trade/btc_usdt/", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Kraken", "identifier": "kraken", "has_trading_incentive": false }, "last": 31652.2, "volume": 94.99823061, "converted_last": { "btc": 1.001797, "eth": 16.190911, "usd": 31751 }, "converted_volume": { "btc": 95.169, "eth": 1538, "usd": 3016251 }, "trust_score": "green", "bid_ask_spread_percentage": 0.03946, "timestamp": "2021-07-18T10:27:19+00:00", "last_traded_at": "2021-07-18T10:27:19+00:00", "last_fetch_at": "2021-07-18T10:27:19+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trade.kraken.com/markets/kraken/btc/usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Gemini", "identifier": "gemini", "has_trading_incentive": false }, "last": 31668.82, "volume": 700.7178640163, "converted_last": { "btc": 0.99841102, "eth": 16.10306, "usd": 31669 }, "converted_volume": { "btc": 699.604, "eth": 11284, "usd": 22190908 }, "trust_score": "green", "bid_ask_spread_percentage": 0.012463, "timestamp": "2021-07-18T10:38:24+00:00", "last_traded_at": "2021-07-18T10:38:24+00:00", "last_fetch_at": "2021-07-18T10:38:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "eToroX", "identifier": "etorox", "has_trading_incentive": false }, "last": 31846.24, "volume": 54.19121, "converted_last": { "btc": 1.003999, "eth": 16.252573, "usd": 31846 }, "converted_volume": { "btc": 54.408, "eth": 880.747, "usd": 1725786 }, "trust_score": "green", "bid_ask_spread_percentage": 0.151305, "timestamp": "2021-07-18T10:15:57+00:00", "last_traded_at": "2021-07-18T10:15:57+00:00", "last_fetch_at": "2021-07-18T10:31:56+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.etorox.com/xchange#", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "TRY", "market": { "name": "BtcTurk PRO", "identifier": "btcturk", "has_trading_incentive": false }, "last": 271709, "volume": 143.9670946, "converted_last": { "btc": 1.006093, "eth": 16.261643, "usd": 31880 }, "converted_volume": { "btc": 144.844, "eth": 2341, "usd": 4589599 }, "trust_score": "green", "bid_ask_spread_percentage": 0.158264, "timestamp": "2021-07-18T10:25:16+00:00", "last_traded_at": "2021-07-18T10:25:16+00:00", "last_fetch_at": "2021-07-18T10:25:16+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://pro.btcturk.com/pro/al-sat/BTC_TRY", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "JPY", "market": { "name": "Liquid", "identifier": "quoine", "has_trading_incentive": false }, "last": 3494171, "volume": 1747.26497094, "converted_last": { "btc": 1.001812, "eth": 16.178297, "usd": 31752 }, "converted_volume": { "btc": 1750, "eth": 28268, "usd": 55479509 }, "trust_score": "green", "bid_ask_spread_percentage": 0.036023, "timestamp": "2021-07-18T10:29:27+00:00", "last_traded_at": "2021-07-18T10:29:27+00:00", "last_fetch_at": "2021-07-18T10:29:27+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://app.liquid.com/exchange/BTCJPY?lang=en", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "TRX", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.0000017901, "volume": 84487316, "converted_last": { "btc": 1, "eth": 16.122532, "usd": 31730 }, "converted_volume": { "btc": 151.241, "eth": 2438, "usd": 4798842 }, "trust_score": "green", "bid_ask_spread_percentage": 0.094908, "timestamp": "2021-07-18T10:34:14+00:00", "last_traded_at": "2021-07-18T10:34:14+00:00", "last_fetch_at": "2021-07-18T10:34:14+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/TRX-to-BTC", "token_info_url": null, "coin_id": "tron", "target_coin_id": "bitcoin" }, { "base": "TRX", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.0000017903, "volume": 84477839, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 151.241, "eth": 2442, "usd": 4798830 }, "trust_score": "green", "bid_ask_spread_percentage": 0.111632, "timestamp": "2021-07-18T10:31:36+00:00", "last_traded_at": "2021-07-18T10:31:36+00:00", "last_fetch_at": "2021-07-18T10:31:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/TRX-to-BTC", "token_info_url": null, "coin_id": "tron", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "CoinTiger", "identifier": "cointiger", "has_trading_incentive": false }, "last": 31727.27, "volume": 1051.25723793, "converted_last": { "btc": 1.004173, "eth": 16.216433, "usd": 31827 }, "converted_volume": { "btc": 1056, "eth": 17048, "usd": 33458416 }, "trust_score": "green", "bid_ask_spread_percentage": 0.022123, "timestamp": "2021-07-18T10:29:24+00:00", "last_traded_at": "2021-07-18T10:29:24+00:00", "last_fetch_at": "2021-07-18T10:29:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Liquid", "identifier": "quoine", "has_trading_incentive": false }, "last": 31675.59, "volume": 38.97802688, "converted_last": { "btc": 0.99939472, "eth": 16.139262, "usd": 31676 }, "converted_volume": { "btc": 38.954434, "eth": 629.077, "usd": 1234652 }, "trust_score": "green", "bid_ask_spread_percentage": 0.077705, "timestamp": "2021-07-18T10:29:26+00:00", "last_traded_at": "2021-07-18T10:29:26+00:00", "last_fetch_at": "2021-07-18T10:29:26+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://app.liquid.com/exchange/BTCUSD?lang=en", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "LTC", "target": "BTC", "market": { "name": "Coinsbit", "identifier": "coinsbit", "has_trading_incentive": false }, "last": 0.003823, "volume": 3799.65316935, "converted_last": { "btc": 1, "eth": 16.161861, "usd": 31694 }, "converted_volume": { "btc": 14.526074, "eth": 234.768, "usd": 460384 }, "trust_score": "green", "bid_ask_spread_percentage": 0.036105, "timestamp": "2021-07-18T10:27:01+00:00", "last_traded_at": "2021-07-18T10:27:01+00:00", "last_fetch_at": "2021-07-18T10:27:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://coinsbit.io/trade/LTC_BTC", "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "HUSD", "market": { "name": "Huobi Global", "identifier": "huobi", "has_trading_incentive": false }, "last": 31677.05, "volume": 71.9484809329463, "converted_last": { "btc": 1.002451, "eth": 16.202746, "usd": 31766 }, "converted_volume": { "btc": 72.125, "eth": 1166, "usd": 2285489 }, "trust_score": "green", "bid_ask_spread_percentage": 0.011013, "timestamp": "2021-07-18T10:26:57+00:00", "last_traded_at": "2021-07-18T10:26:57+00:00", "last_fetch_at": "2021-07-18T10:26:57+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.huobi.com/en-us/exchange/btc_husd", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "husd" } ] } """.trim()
1
null
2
9
8f28a307d64b22fee9e40853cb67858c30b82ec3
134,784
CryptoApp
Apache License 2.0
shared/data/network/src/commonTest/kotlin/dev/ohoussein/cryptoapp/data/network/crypto/service/mocks/MockCryptoDetailsJson.kt
OHoussein
388,247,123
false
null
@file:Suppress("MaxLineLength") package dev.ohoussein.cryptoapp.data.network.crypto.service.mocks val mockCryptoDetailsJson = """ { "id": "bitcoin", "symbol": "btc", "name": "Bitcoin", "asset_platform_id": null, "platforms": { "": "" }, "block_time_in_minutes": 10, "hashing_algorithm": "SHA-256", "categories": [ "Cryptocurrency" ], "public_notice": null, "additional_notices": [], "localization": { "en": "Bitcoin", "de": "Bitcoin", "es": "Bitcoin", "fr": "Bitcoin", "it": "Bitcoin", "pl": "Bitcoin", "ro": "Bitcoin", "hu": "Bitcoin", "nl": "Bitcoin", "pt": "Bitcoin", "sv": "Bitcoin", "vi": "Bitcoin", "tr": "Bitcoin", "ru": "биткоин", "ja": "ビットコイン", "zh": "比特币", "zh-tw": "比特幣", "ko": "비트코인", "ar": "بيتكوين", "th": "บิตคอยน์", "id": "Bitcoin" }, "description": { "en": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "de": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "es": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "fr": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "it": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "pl": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "ro": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "hu": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "nl": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "pt": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "sv": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "vi": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "tr": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>.", "ru": "", "ja": "", "zh": "", "zh-tw": "", "ko": "비트코인은 2009년 나카모토 사토시가 만든 디지털 통화로, 통화를 발행하고 관리하는 중앙 장치가 존재하지 않는 구조를 가지고 있다. 대신, 비트코인의 거래는 P2P 기반 분산 데이터베이스에 의해 이루어지며, 공개 키 암호 방식 기반으로 거래를 수행한다. 비트코인은 공개성을 가지고 있다. 비트코인은 지갑 파일의 형태로 저장되며, 이 지갑에는 각각의 고유 주소가 부여되며, 그 주소를 기반으로 비트코인의 거래가 이루어진다. 비트코인은 1998년 웨이따이가 사이버펑크 메일링 리스트에 올린 암호통화란 구상을 최초로 구현한 것 중의 하나이다.\r\n\r\n비트코인은 최초로 구현된 가상화폐입니다. 발행 및 유통을 관리하는 중앙권력이나 중간상인 없이, P2P 네트워크 기술을 이용하여 네트워크에 참여하는 사용자들이 주체적으로 화폐를 발행하고 이체내용을 공동으로 관리합니다. 이를 가능하게 한 블록체인 기술을 처음으로 코인에 도입한 것이 바로 비트코인입니다.\r\n\r\n비트코인을 사용하는 개인과 사업자의 수는 꾸준히 증가하고 있으며, 여기에는 식당, 아파트, 법률사무소, 온라인 서비스를 비롯한 소매상들이 포함됩니다. 비트코인은 새로운 사회 현상이지만 아주 빠르게 성장하고 있습니다. 이를 바탕으로 가치 증대는 물론, 매일 수백만 달러의 비트코인이 교환되고 있습니다. \r\n\r\n비트코인은 가상화폐 시장에서 현재 유통시가총액과 코인의 가치가 가장 크고, 거래량 또한 안정적입니다. 이더리움이 빠르게 추격하고 있지만 아직은 가장 견고한 가상화폐라고 볼 수 있습니다. \r\n\r\n코인 특징\r\n1. 중앙주체 없이 사용자들에 의해 거래내용이 관리될 수 있는 비트코인의 운영 시스템은 블록체인 기술에서 기인합니다. 블록체인은 쉽게 말해 다 같이 장부를 공유하고, 항상 서로의 컴퓨터에 있는 장부 파일을 비교함으로써 같은 내용만 인정하는 방식으로 운영됩니다. 따라서 전통적인 금융기관에서 장부에 대한 접근을 튼튼하게 방어하던 것과는 정반대의 작업을 통해 보안을 달성합니다. 장부를 해킹하려면 51%의 장부를 동시에 조작해야 하는데, 이는 사실상 불가능합니다. 왜냐하면, 이를 실행하기 위해서는 컴퓨팅 파워가 어마어마하게 소요되고, 이것이 가능한 슈퍼컴퓨터는 세상에 존재하지 않기 때문입니다. 또한, 장부의 자료들은 줄글로 기록되는 것이 아니라 암호화 해시 함수형태로 블록에 저장되고, 이 블록들은 서로 연결되어 있어서 더 강력한 보안을 제공합니다. \r\n\r\n2. 비트코인은 블록발행보상을 채굴자에게 지급하는 방식으로 신규 코인을 발행합니다. 블록발행보상은 매 21만 블록(약 4년)을 기준으로 발행량이 절반으로 줄어듭니다. 처음에는 50비트코인씩 발행이 되었고, 4년마다 계속 반으로 감소하고 있습니다. 코인의 총량이 2,100만 개에 도달하면 신규 발행은 종료되고, 이후에는 거래 수수료만을 통해 시스템이 지탱될 것입니다. \r\n\r\n핵심 가치\r\n(키워드: 통화로 사용될 수 있는 보편성 및 편의성)\r\n\r\n1. 다양한 알트코인들의 등장에 앞서 비트코인은 가상화폐 시장에서 독보적이었기 때문에, 현재 가장 보편적인 결제수단으로 사용됩니다. 실생활에서 이를 활용할 수 있는 가맹점이 알트코인들보다 압도적으로 많을 뿐만 아니라, 이 또한 증가하고 있습니다. 일례로 일본 업체들이 비트코인 결제 시스템을 도입하면서 곧 비트코인을 오프라인 점포 26만 곳에서 이용할 수 있게 될 것입니다. \r\n\r\n2. 여러 나라에서 비트코인을 정식 결제 수단으로 인정하면서, 실물화폐와 가상화폐를 거래할 때 더는 부가가치세가 부과되지 않게 된다고 합니다. 실제로 일본과 호주에서는 이미 비트코인을 합법적 결제 수단으로 인정하면서 제도권 안으로 들여오고 있고, 미국에서는 비트코인 ETF 승인 노력도 진행되고 있습니다. 각국에 비트코인을 기반으로 한 ATM 기계도 설치되었다고 합니다. ", "ar": "", "th": "", "id": "Bitcoin is the first successful internet money based on peer-to-peer technology; whereby no central bank or authority is involved in the transaction and production of the Bitcoin currency. It was created by an anonymous individual/group under the name, Satoshi Nakamoto. The source code is available publicly as an open source project, anybody can look at it and be part of the developmental process.\r\n\r\nBitcoin is changing the way we see money as we speak. The idea was to produce a means of exchange, independent of any central authority, that could be transferred electronically in a secure, verifiable and immutable way. It is a decentralized peer-to-peer internet currency making mobile payment easy, very low transaction fees, protects your identity, and it works anywhere all the time with no central authority and banks.\r\n\r\nBitcoin is designed to have only 21 million BTC ever created, thus making it a deflationary currency. Bitcoin uses the <a href=\"https://www.coingecko.com/en?hashing_algorithm=SHA-256\">SHA-256</a> hashing algorithm with an average transaction confirmation time of 10 minutes. Miners today are mining Bitcoin using ASIC chip dedicated to only mining Bitcoin, and the hash rate has shot up to peta hashes.\r\n\r\nBeing the first successful online cryptography currency, Bitcoin has inspired other alternative currencies such as <a href=\"https://www.coingecko.com/en/coins/litecoin\">Litecoin</a>, <a href=\"https://www.coingecko.com/en/coins/peercoin\">Peercoin</a>, <a href=\"https://www.coingecko.com/en/coins/primecoin\">Primecoin</a>, and so on.\r\n\r\nThe cryptocurrency then took off with the innovation of the turing-complete smart contract by <a href=\"https://www.coingecko.com/en/coins/ethereum\">Ethereum</a> which led to the development of other amazing projects such as <a href=\"https://www.coingecko.com/en/coins/eos\">EOS</a>, <a href=\"https://www.coingecko.com/en/coins/tron\">Tron</a>, and even crypto-collectibles such as <a href=\"https://www.coingecko.com/buzz/ethereum-still-king-dapps-cryptokitties-need-1-billion-on-eos\">CryptoKitties</a>." }, "links": { "homepage": [ "http://www.bitcoin.org", "", "" ], "blockchain_site": [ "https://blockchair.com/bitcoin/", "https://btc.com/", "https://btc.tokenview.com/", "", "" ], "official_forum_url": [ "https://bitcointalk.org/", "", "" ], "chat_url": [ "", "", "" ], "announcement_url": [ "", "" ], "twitter_screen_name": "bitcoin", "facebook_username": "bitcoins", "bitcointalk_thread_identifier": null, "telegram_channel_identifier": "", "subreddit_url": "https://www.reddit.com/r/Bitcoin/", "repos_url": { "github": [ "https://github.com/bitcoin/bitcoin", "https://github.com/bitcoin/bips" ], "bitbucket": [] } }, "image": { "thumb": "https://assets.coingecko.com/coins/images/1/thumb/bitcoin.png?1547033579", "small": "https://assets.coingecko.com/coins/images/1/small/bitcoin.png?1547033579", "large": "https://assets.coingecko.com/coins/images/1/large/bitcoin.png?1547033579" }, "country_origin": "", "genesis_date": "2009-01-03", "sentiment_votes_up_percentage": 67.33, "sentiment_votes_down_percentage": 32.67, "market_cap_rank": 1, "coingecko_rank": 1, "coingecko_score": 81.721, "developer_score": 101.396, "community_score": 74.329, "liquidity_score": 100.017, "public_interest_score": 0.314, "developer_data": { "forks": 29417, "stars": 55648, "subscribers": 3828, "total_issues": 6337, "closed_issues": 5743, "pull_requests_merged": 8778, "pull_request_contributors": 733, "code_additions_deletions_4_weeks": { "additions": 3809, "deletions": -2404 }, "commit_count_4_weeks": 225, "last_4_weeks_commit_activity_series": [ 4, 3, 12, 8, 3, 3, 0, 5, 13, 1, 2, 6, 3, 0, 4, 6, 5, 2, 0, 3, 0, 0, 2, 1, 2, 1, 0, 0 ] }, "public_interest_stats": { "alexa_rank": 9440, "bing_matches": null }, "status_updates": [], "last_updated": "2021-07-18T10:40:31.413Z", "tickers": [ { "base": "BTC", "target": "USD", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 31669, "volume": 11502.07033188, "converted_last": { "btc": 0.99808807, "eth": 16.090713, "usd": 31669 }, "converted_volume": { "btc": 11480, "eth": 185077, "usd": 364259065 }, "trust_score": "green", "bid_ask_spread_percentage": 0.031566, "timestamp": "2021-07-18T10:35:31+00:00", "last_traded_at": "2021-07-18T10:35:31+00:00", "last_fetch_at": "2021-07-18T10:35:31+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCUSD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 26832.63639, "volume": 382.39958501, "converted_last": { "btc": 0.9983402, "eth": 16.094778, "usd": 31677 }, "converted_volume": { "btc": 381.765, "eth": 6155, "usd": 12113272 }, "trust_score": "green", "bid_ask_spread_percentage": 0.037272, "timestamp": "2021-07-18T10:35:31+00:00", "last_traded_at": "2021-07-18T10:35:31+00:00", "last_fetch_at": "2021-07-18T10:35:31+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCEUR", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "JPY", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 3486499.9999995, "volume": 230.78394761, "converted_last": { "btc": 0.99851333, "eth": 16.097569, "usd": 31682 }, "converted_volume": { "btc": 230.441, "eth": 3715, "usd": 7311811 }, "trust_score": "green", "bid_ask_spread_percentage": 0.028686, "timestamp": "2021-07-18T10:35:25+00:00", "last_traded_at": "2021-07-18T10:35:25+00:00", "last_fetch_at": "2021-07-18T10:35:25+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCJPY", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "GBP", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 23001, "volume": 153.39905336, "converted_last": { "btc": 0.99852093, "eth": 16.097692, "usd": 31683 }, "converted_volume": { "btc": 153.172, "eth": 2469, "usd": 4860101 }, "trust_score": "green", "bid_ask_spread_percentage": 0.086957, "timestamp": "2021-07-18T10:35:41+00:00", "last_traded_at": "2021-07-18T10:35:41+00:00", "last_fetch_at": "2021-07-18T10:35:41+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCGBP", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 31662, "volume": 124.82353618533257, "converted_last": { "btc": 1.002108, "eth": 16.197203, "usd": 31755 }, "converted_volume": { "btc": 125.087, "eth": 2022, "usd": 3963742 }, "trust_score": "green", "bid_ask_spread_percentage": 0.041042, "timestamp": "2021-07-18T10:26:18+00:00", "last_traded_at": "2021-07-18T10:26:18+00:00", "last_fetch_at": "2021-07-18T10:26:18+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/BTC/USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 31668, "volume": 150.39322968927624, "converted_last": { "btc": 0.99936939, "eth": 16.152945, "usd": 31668 }, "converted_volume": { "btc": 150.298, "eth": 2429, "usd": 4762653 }, "trust_score": "green", "bid_ask_spread_percentage": 0.031571, "timestamp": "2021-07-18T10:26:12+00:00", "last_traded_at": "2021-07-18T10:26:12+00:00", "last_fetch_at": "2021-07-18T10:26:12+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/BTC/USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 31649.99, "volume": 35206.426261271015, "converted_last": { "btc": 1.001727, "eth": 16.15695, "usd": 31774 }, "converted_volume": { "btc": 35267, "eth": 568828, "usd": 1118648209 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010032, "timestamp": "2021-07-18T10:39:13+00:00", "last_traded_at": "2021-07-18T10:39:13+00:00", "last_fetch_at": "2021-07-18T10:39:13+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/BTC_USDT?ref=37754157", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "WBTC", "target": "BTC", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 1.0003, "volume": 20.118083924822553, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 20.124119, "eth": 324.576, "usd": 638321 }, "trust_score": "green", "bid_ask_spread_percentage": 0.029991, "timestamp": "2021-07-18T10:38:02+00:00", "last_traded_at": "2021-07-18T10:38:02+00:00", "last_fetch_at": "2021-07-18T10:38:02+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/WBTC/BTC", "token_info_url": null, "coin_id": "wrapped-bitcoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDC", "market": { "name": "Serum DEX", "identifier": "serum_dex", "has_trading_incentive": false }, "last": 31611.7, "volume": 31.322400000000002, "converted_last": { "btc": 0.99895591, "eth": 16.175264, "usd": 31648 }, "converted_volume": { "btc": 31.289697, "eth": 506.648, "usd": 991291 }, "trust_score": "green", "bid_ask_spread_percentage": 0.030017, "timestamp": "2021-07-18T10:17:55+00:00", "last_traded_at": "2021-07-18T10:17:55+00:00", "last_fetch_at": "2021-07-18T10:40:10+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://dex.projectserum.com", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Serum DEX", "identifier": "serum_dex", "has_trading_incentive": false }, "last": 31597, "volume": 28.846999999999998, "converted_last": { "btc": 1.00005, "eth": 16.192985, "usd": 31683 }, "converted_volume": { "btc": 28.848452, "eth": 467.119, "usd": 913950 }, "trust_score": "green", "bid_ask_spread_percentage": 0.011693, "timestamp": "2021-07-18T10:17:53+00:00", "last_traded_at": "2021-07-18T10:17:53+00:00", "last_fetch_at": "2021-07-18T10:40:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://dex.projectserum.com", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Digifinex", "identifier": "digifinex", "has_trading_incentive": false }, "last": 31683.85, "volume": 3503.37146594, "converted_last": { "btc": 1.002799, "eth": 16.191078, "usd": 31821 }, "converted_volume": { "btc": 3513, "eth": 56723, "usd": 111482065 }, "trust_score": "green", "bid_ask_spread_percentage": 0.043008, "timestamp": "2021-07-18T10:32:13+00:00", "last_traded_at": "2021-07-18T10:32:13+00:00", "last_fetch_at": "2021-07-18T10:32:13+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.digifinex.com/en-ww/trade/USDT/BTC", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 31654, "volume": 955.9488609496431, "converted_last": { "btc": 1.001854, "eth": 16.158597, "usd": 31778 }, "converted_volume": { "btc": 957.722, "eth": 15447, "usd": 30378182 }, "trust_score": "green", "bid_ask_spread_percentage": 0.022113, "timestamp": "2021-07-18T10:38:04+00:00", "last_traded_at": "2021-07-18T10:38:04+00:00", "last_fetch_at": "2021-07-18T10:38:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/BTC/USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "BUSD", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 31669.99, "volume": 9149.213570053518, "converted_last": { "btc": 1.000196, "eth": 16.165031, "usd": 31700 }, "converted_volume": { "btc": 9151, "eth": 147897, "usd": 290028738 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010032, "timestamp": "2021-07-18T10:27:12+00:00", "last_traded_at": "2021-07-18T10:27:12+00:00", "last_fetch_at": "2021-07-18T10:27:12+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/BTC_BUSD?ref=37754157", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "binance-usd" }, { "base": "BTC", "target": "USDT", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 31661.45, "volume": 25718.26831, "converted_last": { "btc": 1.00209, "eth": 16.161968, "usd": 31787 }, "converted_volume": { "btc": 25772, "eth": 415658, "usd": 817517805 }, "trust_score": "green", "bid_ask_spread_percentage": 0.017995, "timestamp": "2021-07-18T10:37:51+00:00", "last_traded_at": "2021-07-18T10:37:51+00:00", "last_fetch_at": "2021-07-18T10:37:51+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/BTC-to-USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 31687.13, "volume": 25947.47742, "converted_last": { "btc": 0.99865653, "eth": 16.124566, "usd": 31687 }, "converted_volume": { "btc": 25913, "eth": 418392, "usd": 822201090 }, "trust_score": "green", "bid_ask_spread_percentage": 0.013789, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/BTC-to-USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "Coinbase Exchange", "identifier": "gdax", "has_trading_incentive": false }, "last": 31671.3, "volume": 5077.27630299, "converted_last": { "btc": 0.99842903, "eth": 16.10292, "usd": 31671 }, "converted_volume": { "btc": 5069, "eth": 81759, "usd": 160803941 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010032, "timestamp": "2021-07-18T10:37:23+00:00", "last_traded_at": "2021-07-18T10:37:23+00:00", "last_fetch_at": "2021-07-18T10:38:53+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://pro.coinbase.com/trade/BTC-USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "Cryptology", "identifier": "cryptology", "has_trading_incentive": false }, "last": 31719.9, "volume": 184.84924842, "converted_last": { "btc": 0.99960161, "eth": 16.139451, "usd": 31720 }, "converted_volume": { "btc": 184.776, "eth": 2983, "usd": 5863400 }, "trust_score": "green", "bid_ask_spread_percentage": 0.018297, "timestamp": "2021-07-18T10:32:04+00:00", "last_traded_at": "2021-07-18T10:32:04+00:00", "last_fetch_at": "2021-07-18T10:32:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 31653, "volume": 8516.779072697691, "converted_last": { "btc": 0.99791227, "eth": 16.095016, "usd": 31653 }, "converted_volume": { "btc": 8499, "eth": 137078, "usd": 269581608 }, "trust_score": "green", "bid_ask_spread_percentage": 0.013159, "timestamp": "2021-07-18T10:38:01+00:00", "last_traded_at": "2021-07-18T10:38:01+00:00", "last_fetch_at": "2021-07-18T10:38:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/BTC/USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 26820.18, "volume": 48.1686, "converted_last": { "btc": 0.9992379, "eth": 16.150846, "usd": 31662 }, "converted_volume": { "btc": 48.131891, "eth": 777.964, "usd": 1525128 }, "trust_score": "green", "bid_ask_spread_percentage": 0.04026, "timestamp": "2021-07-18T10:25:32+00:00", "last_traded_at": "2021-07-18T10:25:32+00:00", "last_fetch_at": "2021-07-18T10:25:32+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Wootrade", "identifier": "wootrade", "has_trading_incentive": false }, "last": 31652.52, "volume": 513.07497877, "converted_last": { "btc": 1.001808, "eth": 16.157842, "usd": 31777 }, "converted_volume": { "btc": 514.002, "eth": 8290, "usd": 16303755 }, "trust_score": "green", "bid_ask_spread_percentage": 0.019837, "timestamp": "2021-07-18T10:38:24+00:00", "last_traded_at": "2021-07-18T10:38:24+00:00", "last_fetch_at": "2021-07-18T10:38:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://x.woo.network/spot", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Bitstamp", "identifier": "bitstamp", "has_trading_incentive": false }, "last": 31697.44, "volume": 1697.60717519, "converted_last": { "btc": 1.00012, "eth": 16.1638, "usd": 31697 }, "converted_volume": { "btc": 1698, "eth": 27440, "usd": 53809802 }, "trust_score": "green", "bid_ask_spread_percentage": 0.052496, "timestamp": "2021-07-18T10:27:08+00:00", "last_traded_at": "2021-07-18T10:27:08+00:00", "last_fetch_at": "2021-07-18T10:27:08+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Cryptology", "identifier": "cryptology", "has_trading_incentive": false }, "last": 26873.33, "volume": 288.75425643, "converted_last": { "btc": 0.9997636, "eth": 16.142066, "usd": 31725 }, "converted_volume": { "btc": 288.686, "eth": 4661, "usd": 9160740 }, "trust_score": "green", "bid_ask_spread_percentage": 0.299378, "timestamp": "2021-07-18T10:32:05+00:00", "last_traded_at": "2021-07-18T10:32:05+00:00", "last_fetch_at": "2021-07-18T10:32:05+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 0.061964, "volume": 2193.14054369, "converted_last": { "btc": 1, "eth": 16.121537, "usd": 31730 }, "converted_volume": { "btc": 135.896, "eth": 2191, "usd": 4311927 }, "trust_score": "green", "bid_ask_spread_percentage": 0.048434, "timestamp": "2021-07-18T10:35:29+00:00", "last_traded_at": "2021-07-18T10:35:29+00:00", "last_fetch_at": "2021-07-18T10:35:29+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/ETHBTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "WAVES", "target": "BTC", "market": { "name": "Waves.Exchange", "identifier": "waves", "has_trading_incentive": false }, "last": 0.00041674, "volume": 31349.23848339, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 13.064482, "eth": 210.942, "usd": 414533 }, "trust_score": "green", "bid_ask_spread_percentage": 0.081586, "timestamp": "2021-07-18T10:31:51+00:00", "last_traded_at": "2021-07-18T10:31:51+00:00", "last_fetch_at": "2021-07-18T10:31:51+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "waves", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "UST", "market": { "name": "Bitfinex", "identifier": "bitfinex", "has_trading_incentive": false }, "last": 31668, "volume": 1448.11547116, "converted_last": { "btc": 1.002398, "eth": 16.160192, "usd": 31806 }, "converted_volume": { "btc": 1452, "eth": 23402, "usd": 46058390 }, "trust_score": "green", "bid_ask_spread_percentage": 0.031576, "timestamp": "2021-07-18T10:35:41+00:00", "last_traded_at": "2021-07-18T10:35:41+00:00", "last_fetch_at": "2021-07-18T10:35:41+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitfinex.com/t/BTCUST", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "EUR", "market": { "name": "Kraken", "identifier": "kraken", "has_trading_incentive": false }, "last": 26867.9, "volume": 896.8823939, "converted_last": { "btc": 1.000789, "eth": 16.174606, "usd": 31719 }, "converted_volume": { "btc": 897.59, "eth": 14507, "usd": 28447881 }, "trust_score": "green", "bid_ask_spread_percentage": 0.012233, "timestamp": "2021-07-18T10:27:24+00:00", "last_traded_at": "2021-07-18T10:27:24+00:00", "last_fetch_at": "2021-07-18T10:27:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trade.kraken.com/markets/kraken/btc/eur", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BCH", "target": "BTC", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 0.014106, "volume": 484.7410701120091, "converted_last": { "btc": 1, "eth": 16.163137, "usd": 31688 }, "converted_volume": { "btc": 6.837758, "eth": 110.52, "usd": 216675 }, "trust_score": "green", "bid_ask_spread_percentage": 0.056681, "timestamp": "2021-07-18T10:26:12+00:00", "last_traded_at": "2021-07-18T10:26:12+00:00", "last_fetch_at": "2021-07-18T10:26:12+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/BCH/BTC", "token_info_url": null, "coin_id": "bitcoin-cash", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "Kraken", "identifier": "kraken", "has_trading_incentive": false }, "last": 31664.4, "volume": 1913.84051414, "converted_last": { "btc": 0.99907746, "eth": 16.146952, "usd": 31664 }, "converted_volume": { "btc": 1912, "eth": 30903, "usd": 60600612 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010316, "timestamp": "2021-07-18T10:27:22+00:00", "last_traded_at": "2021-07-18T10:27:22+00:00", "last_fetch_at": "2021-07-18T10:27:22+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trade.kraken.com/markets/kraken/btc/usd", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BNB", "target": "BTC", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 0.0096363, "volume": 1229.482507809014, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 11.847662, "eth": 191.087, "usd": 375799 }, "trust_score": "green", "bid_ask_spread_percentage": 0.130704, "timestamp": "2021-07-18T10:38:02+00:00", "last_traded_at": "2021-07-18T10:38:02+00:00", "last_fetch_at": "2021-07-18T10:38:02+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/BNB/BTC", "token_info_url": null, "coin_id": "binancecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "OKEx", "identifier": "okex", "has_trading_incentive": false }, "last": 31694, "volume": 14079.05656805, "converted_last": { "btc": 1.00312, "eth": 16.197061, "usd": 31812 }, "converted_volume": { "btc": 14123, "eth": 228039, "usd": 447879284 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010316, "timestamp": "2021-07-18T10:30:37+00:00", "last_traded_at": "2021-07-18T10:30:37+00:00", "last_fetch_at": "2021-07-18T10:30:37+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.okex.com/markets/spot-info/btc-usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "WhiteBIT", "identifier": "whitebit", "has_trading_incentive": false }, "last": 31651.72, "volume": 4287.247892, "converted_last": { "btc": 1.001782, "eth": 16.19197, "usd": 31743 }, "converted_volume": { "btc": 4295, "eth": 69419, "usd": 136089746 }, "trust_score": "green", "bid_ask_spread_percentage": 0.017532, "timestamp": "2021-07-18T10:25:38+00:00", "last_traded_at": "2021-07-18T10:25:38+00:00", "last_fetch_at": "2021-07-18T10:25:38+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://whitebit.com/trade/BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Dex-Trade", "identifier": "dextrade", "has_trading_incentive": false }, "last": 31687.68, "volume": 628.66896074, "converted_last": { "btc": 1.00292, "eth": 16.193411, "usd": 31822 }, "converted_volume": { "btc": 630.505, "eth": 10180, "usd": 20005768 }, "trust_score": "green", "bid_ask_spread_percentage": 0.288005, "timestamp": "2021-07-18T10:31:23+00:00", "last_traded_at": "2021-07-18T10:31:23+00:00", "last_fetch_at": "2021-07-18T10:31:23+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "ETH", "target": "BTC", "market": { "name": "Digifinex", "identifier": "digifinex", "has_trading_incentive": false }, "last": 0.062042, "volume": 9723.8144, "converted_last": { "btc": 1, "eth": 16.145883, "usd": 31733 }, "converted_volume": { "btc": 603.285, "eth": 9741, "usd": 19143763 }, "trust_score": "green", "bid_ask_spread_percentage": 0.195023, "timestamp": "2021-07-18T10:32:13+00:00", "last_traded_at": "2021-07-18T10:32:13+00:00", "last_fetch_at": "2021-07-18T10:32:13+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.digifinex.com/en-ww/trade/BTC/ETH", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "WBTC", "target": "BTC", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 1.00059, "volume": 200.20735651965342, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 200.325, "eth": 3235, "usd": 6356279 }, "trust_score": "green", "bid_ask_spread_percentage": 0.028983, "timestamp": "2021-07-18T10:31:19+00:00", "last_traded_at": "2021-07-18T10:31:19+00:00", "last_fetch_at": "2021-07-18T10:31:19+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/WBTC_BTC?ref=37754157", "token_info_url": null, "coin_id": "wrapped-bitcoin", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 0.061895, "volume": 108018.61603279748, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 6686, "eth": 107833, "usd": 212068758 }, "trust_score": "green", "bid_ask_spread_percentage": 0.011617, "timestamp": "2021-07-18T10:38:58+00:00", "last_traded_at": "2021-07-18T10:38:58+00:00", "last_fetch_at": "2021-07-18T10:38:58+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/ETH_BTC?ref=37754157", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 0.0619325, "volume": 914.9950722560852, "converted_last": { "btc": 1, "eth": 16.163137, "usd": 31688 }, "converted_volume": { "btc": 56.668, "eth": 915.932, "usd": 1795692 }, "trust_score": "green", "bid_ask_spread_percentage": 0.052462, "timestamp": "2021-07-18T10:26:16+00:00", "last_traded_at": "2021-07-18T10:26:16+00:00", "last_fetch_at": "2021-07-18T10:26:16+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/ETH/BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "LBank", "identifier": "lbank", "has_trading_incentive": false }, "last": 0.06193133, "volume": 9998.7452, "converted_last": { "btc": 1, "eth": 16.161861, "usd": 31694 }, "converted_volume": { "btc": 619.236, "eth": 10008, "usd": 19625829 }, "trust_score": "green", "bid_ask_spread_percentage": 0.103465, "timestamp": "2021-07-18T10:27:33+00:00", "last_traded_at": "2021-07-18T10:27:33+00:00", "last_fetch_at": "2021-07-18T10:27:33+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.lbank.info/exchange/eth/btc", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "ZB", "identifier": "zb", "has_trading_incentive": false }, "last": 31674.93, "volume": 16955.8862, "converted_last": { "btc": 1.002517, "eth": 16.162947, "usd": 31813 }, "converted_volume": { "btc": 16999, "eth": 274057, "usd": 539414290 }, "trust_score": "green", "bid_ask_spread_percentage": 0.058449, "timestamp": "2021-07-18T10:33:47+00:00", "last_traded_at": "2021-07-18T10:33:47+00:00", "last_fetch_at": "2021-07-18T10:33:47+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trans.zb.com/btcusdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "XRP", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.000018511, "volume": 25380854.8, "converted_last": { "btc": 1, "eth": 16.128257, "usd": 31721 }, "converted_volume": { "btc": 469.825, "eth": 7577, "usd": 14903381 }, "trust_score": "green", "bid_ask_spread_percentage": 0.027011, "timestamp": "2021-07-18T10:37:36+00:00", "last_traded_at": "2021-07-18T10:37:36+00:00", "last_fetch_at": "2021-07-18T10:37:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/XRP-to-BTC", "token_info_url": null, "coin_id": "ripple", "target_coin_id": "bitcoin" }, { "base": "XRP", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.000018541, "volume": 25365195.8, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 470.296, "eth": 7594, "usd": 14922381 }, "trust_score": "green", "bid_ask_spread_percentage": 0.026963, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/XRP-to-BTC", "token_info_url": null, "coin_id": "ripple", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 31693.55546, "volume": 734.43672, "converted_last": { "btc": 1.001543, "eth": 16.171165, "usd": 31779 }, "converted_volume": { "btc": 735.57, "eth": 11877, "usd": 23339448 }, "trust_score": "green", "bid_ask_spread_percentage": 0.024916, "timestamp": "2021-07-18T10:31:36+00:00", "last_traded_at": "2021-07-18T10:31:36+00:00", "last_fetch_at": "2021-07-18T10:31:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/BTC-to-USDC", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "BTC", "target": "USDC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 31661.63615, "volume": 732.93628, "converted_last": { "btc": 0.99966773, "eth": 16.123329, "usd": 31709 }, "converted_volume": { "btc": 732.693, "eth": 11817, "usd": 23240443 }, "trust_score": "green", "bid_ask_spread_percentage": 0.013154, "timestamp": "2021-07-18T10:38:10+00:00", "last_traded_at": "2021-07-18T10:38:10+00:00", "last_fetch_at": "2021-07-18T10:38:10+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/BTC-to-USDC", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "ETH", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.061884, "volume": 29717.2928, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 1839, "eth": 29661, "usd": 58332439 }, "trust_score": "green", "bid_ask_spread_percentage": 0.016159, "timestamp": "2021-07-18T10:38:30+00:00", "last_traded_at": "2021-07-18T10:38:30+00:00", "last_fetch_at": "2021-07-18T10:38:30+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/ETH-to-BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "UAH", "market": { "name": "WhiteBIT", "identifier": "whitebit", "has_trading_incentive": false }, "last": 890149.51, "volume": 11.203193, "converted_last": { "btc": 1.03218, "eth": 16.683293, "usd": 32706 }, "converted_volume": { "btc": 11.563711, "eth": 186.906, "usd": 366413 }, "trust_score": "green", "bid_ask_spread_percentage": 0.018344, "timestamp": "2021-07-18T10:25:38+00:00", "last_traded_at": "2021-07-18T10:25:38+00:00", "last_fetch_at": "2021-07-18T10:25:38+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://whitebit.com/trade/BTC_UAH", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "LBank", "identifier": "lbank", "has_trading_incentive": false }, "last": 31669.64, "volume": 6933.2841, "converted_last": { "btc": 1.002349, "eth": 16.199832, "usd": 31768 }, "converted_volume": { "btc": 6950, "eth": 112318, "usd": 220257258 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010221, "timestamp": "2021-07-18T10:27:35+00:00", "last_traded_at": "2021-07-18T10:27:35+00:00", "last_fetch_at": "2021-07-18T10:27:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.lbank.info/exchange/btc/usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "LTC", "target": "BTC", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 0.003812, "volume": 2011.4533276495279, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 7.66766, "eth": 123.669, "usd": 243212 }, "trust_score": "green", "bid_ask_spread_percentage": 0.091791, "timestamp": "2021-07-18T10:38:02+00:00", "last_traded_at": "2021-07-18T10:38:02+00:00", "last_fetch_at": "2021-07-18T10:38:02+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/LTC/BTC", "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Bitstamp", "identifier": "bitstamp", "has_trading_incentive": false }, "last": 26841.44, "volume": 808.45995818, "converted_last": { "btc": 0.9969589, "eth": 16.130124, "usd": 31687 }, "converted_volume": { "btc": 806.001, "eth": 13041, "usd": 25617988 }, "trust_score": "green", "bid_ask_spread_percentage": 0.083284, "timestamp": "2021-07-18T10:11:54+00:00", "last_traded_at": "2021-07-18T10:11:54+00:00", "last_fetch_at": "2021-07-18T10:11:54+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "JPY", "market": { "name": "bitFlyer", "identifier": "bitflyer", "has_trading_incentive": false }, "last": 3494196, "volume": 1941.50662714, "converted_last": { "btc": 1.00125, "eth": 16.166862, "usd": 31752 }, "converted_volume": { "btc": 1944, "eth": 31388, "usd": 61647550 }, "trust_score": "green", "bid_ask_spread_percentage": 0.045409, "timestamp": "2021-07-18T10:30:22+00:00", "last_traded_at": "2021-07-18T10:30:22+00:00", "last_fetch_at": "2021-07-18T10:30:22+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://bitflyer.com/en-jp/ex/simpleex", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.06198, "volume": 30048.9281, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 1862, "eth": 30071, "usd": 59094535 }, "trust_score": "green", "bid_ask_spread_percentage": 0.029039, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/ETH-to-BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "LTC", "target": "BTC", "market": { "name": "FTX.US", "identifier": "ftx_us", "has_trading_incentive": false }, "last": 0.00381925, "volume": 82.51463441775218, "converted_last": { "btc": 1, "eth": 16.163137, "usd": 31688 }, "converted_volume": { "btc": 0.31514402, "eth": 5.093716, "usd": 9986.28 }, "trust_score": "green", "bid_ask_spread_percentage": 0.104623, "timestamp": "2021-07-18T10:26:14+00:00", "last_traded_at": "2021-07-18T10:26:14+00:00", "last_fetch_at": "2021-07-18T10:26:14+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.us/trade/LTC/BTC", "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "JPY", "market": { "name": "GMO Japan", "identifier": "gmo_japan", "has_trading_incentive": false }, "last": 3490020, "volume": 133.5681, "converted_last": { "btc": 0.99985054, "eth": 16.126278, "usd": 31714 }, "converted_volume": { "btc": 133.548, "eth": 2154, "usd": 4236043 }, "trust_score": "green", "bid_ask_spread_percentage": 0.026455, "timestamp": "2021-07-18T10:38:11+00:00", "last_traded_at": "2021-07-18T10:38:11+00:00", "last_fetch_at": "2021-07-18T10:38:11+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://coin.z.com/jp/corp/information/btc-market/", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Huobi Global", "identifier": "huobi", "has_trading_incentive": false }, "last": 31684.73, "volume": 10514.569255059265, "converted_last": { "btc": 1.002827, "eth": 16.20883, "usd": 31778 }, "converted_volume": { "btc": 10544, "eth": 170429, "usd": 334127402 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010032, "timestamp": "2021-07-18T10:26:57+00:00", "last_traded_at": "2021-07-18T10:26:57+00:00", "last_fetch_at": "2021-07-18T10:26:57+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.huobi.com/en-us/exchange/btc_usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Okcoin", "identifier": "okcoin", "has_trading_incentive": false }, "last": 31682.45, "volume": 177.3329, "converted_last": { "btc": 0.99964698, "eth": 16.156156, "usd": 31682 }, "converted_volume": { "btc": 177.27, "eth": 2865, "usd": 5618341 }, "trust_score": "green", "bid_ask_spread_percentage": 0.017517, "timestamp": "2021-07-18T10:27:03+00:00", "last_traded_at": "2021-07-18T10:27:03+00:00", "last_fetch_at": "2021-07-18T10:27:03+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.okcoin.com/market#product=btc_usd", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Coinbase Exchange", "identifier": "gdax", "has_trading_incentive": false }, "last": 26852.7, "volume": 433.76641011, "converted_last": { "btc": 0.99935541, "eth": 16.117861, "usd": 31701 }, "converted_volume": { "btc": 433.487, "eth": 6991, "usd": 13750693 }, "trust_score": "green", "bid_ask_spread_percentage": 0.020929, "timestamp": "2021-07-18T10:37:21+00:00", "last_traded_at": "2021-07-18T10:37:21+00:00", "last_fetch_at": "2021-07-18T10:38:46+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://pro.coinbase.com/trade/BTC-EUR", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Coinsbit", "identifier": "coinsbit", "has_trading_incentive": false }, "last": 31650.02, "volume": 8775.0086578, "converted_last": { "btc": 1.001728, "eth": 16.189796, "usd": 31748 }, "converted_volume": { "btc": 8790, "eth": 142066, "usd": 278592646 }, "trust_score": "green", "bid_ask_spread_percentage": 0.039988, "timestamp": "2021-07-18T10:27:00+00:00", "last_traded_at": "2021-07-18T10:27:00+00:00", "last_fetch_at": "2021-07-18T10:27:00+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://coinsbit.io/trade/BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "BitMart", "identifier": "bitmart", "has_trading_incentive": false }, "last": 31728.23, "volume": 1567.86636, "converted_last": { "btc": 1.004204, "eth": 16.190145, "usd": 31866 }, "converted_volume": { "btc": 1574, "eth": 25384, "usd": 49962157 }, "trust_score": "green", "bid_ask_spread_percentage": 0.020511, "timestamp": "2021-07-18T10:33:04+00:00", "last_traded_at": "2021-07-18T10:33:04+00:00", "last_fetch_at": "2021-07-18T10:33:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitmart.com/trade/en?symbol=BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "BKEX", "identifier": "bkex", "has_trading_incentive": false }, "last": 31662.32, "volume": 8376.1499, "converted_last": { "btc": 1.002118, "eth": 16.197366, "usd": 31755 }, "converted_volume": { "btc": 8394, "eth": 135672, "usd": 265985384 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010442, "timestamp": "2021-07-18T10:26:05+00:00", "last_traded_at": "2021-07-18T10:26:05+00:00", "last_fetch_at": "2021-07-18T10:26:05+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bkex.com/#/trade/BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "XRP", "target": "BTC", "market": { "name": "FTX", "identifier": "ftx_spot", "has_trading_incentive": false }, "last": 0.00001853, "volume": 126136.03022126282, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 2.337301, "eth": 37.697594, "usd": 74137 }, "trust_score": "green", "bid_ask_spread_percentage": 0.108108, "timestamp": "2021-07-18T10:38:02+00:00", "last_traded_at": "2021-07-18T10:38:02+00:00", "last_fetch_at": "2021-07-18T10:38:02+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://ftx.com/trade/XRP/BTC", "token_info_url": null, "coin_id": "ripple", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Hoo.com", "identifier": "hoo", "has_trading_incentive": false }, "last": 31661.12, "volume": 10968.532010435627, "converted_last": { "btc": 1.00208, "eth": 16.196752, "usd": 31754 }, "converted_volume": { "btc": 10991, "eth": 177655, "usd": 348293507 }, "trust_score": "green", "bid_ask_spread_percentage": 0.012052, "timestamp": "2021-07-18T10:26:24+00:00", "last_traded_at": "2021-07-18T10:26:24+00:00", "last_fetch_at": "2021-07-18T10:26:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hoo.com/spot/btc-usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Zipmex", "identifier": "zipmex", "has_trading_incentive": false }, "last": 31626, "volume": 0.035913, "converted_last": { "btc": 1.000968, "eth": 16.182089, "usd": 31717 }, "converted_volume": { "btc": 0.03594777, "eth": 0.58114737, "usd": 1139.06 }, "trust_score": "green", "bid_ask_spread_percentage": 0.104167, "timestamp": "2021-07-18T10:23:36+00:00", "last_traded_at": "2021-07-18T10:23:36+00:00", "last_fetch_at": "2021-07-18T10:23:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trade.zipmex.com", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BNB", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.0096118, "volume": 1916.52, "converted_last": { "btc": 1, "eth": 16.122532, "usd": 31730 }, "converted_volume": { "btc": 18.421207, "eth": 296.996, "usd": 584502 }, "trust_score": "green", "bid_ask_spread_percentage": 0.046706, "timestamp": "2021-07-18T10:34:34+00:00", "last_traded_at": "2021-07-18T10:34:34+00:00", "last_fetch_at": "2021-07-18T10:34:34+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/BNB-to-BTC", "token_info_url": null, "coin_id": "binancecoin", "target_coin_id": "bitcoin" }, { "base": "EOS", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.00011648, "volume": 2933208.06, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 341.66, "eth": 5517, "usd": 10840792 }, "trust_score": "green", "bid_ask_spread_percentage": 0.051498, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/EOS-to-BTC", "token_info_url": null, "coin_id": "eos", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 31659.655649, "volume": 51.7444, "converted_last": { "btc": 0.99915461, "eth": 16.1495, "usd": 31660 }, "converted_volume": { "btc": 51.701, "eth": 835.646, "usd": 1638210 }, "trust_score": "green", "bid_ask_spread_percentage": 0.024712, "timestamp": "2021-07-18T10:25:34+00:00", "last_traded_at": "2021-07-18T10:25:34+00:00", "last_fetch_at": "2021-07-18T10:25:34+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BNB", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.0096118, "volume": 1970.02, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 18.935438, "eth": 305.736, "usd": 600817 }, "trust_score": "green", "bid_ask_spread_percentage": 0.066518, "timestamp": "2021-07-18T10:31:34+00:00", "last_traded_at": "2021-07-18T10:31:34+00:00", "last_fetch_at": "2021-07-18T10:31:34+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/BNB-to-BTC", "token_info_url": null, "coin_id": "binancecoin", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "AlterDice", "identifier": "alterdice", "has_trading_incentive": false }, "last": 0.061889, "volume": 998.94, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 61.823, "eth": 997.13, "usd": 1960990 }, "trust_score": "green", "bid_ask_spread_percentage": 0.090448, "timestamp": "2021-07-18T10:38:09+00:00", "last_traded_at": "2021-07-18T10:38:09+00:00", "last_fetch_at": "2021-07-18T10:38:09+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Crypto.com Exchange", "identifier": "crypto_com", "has_trading_incentive": false }, "last": 31675.27, "volume": 994.279392, "converted_last": { "btc": 1.002528, "eth": 16.202712, "usd": 31774 }, "converted_volume": { "btc": 996.793, "eth": 16110, "usd": 31591982 }, "trust_score": "green", "bid_ask_spread_percentage": 0.015975, "timestamp": "2021-07-18T10:27:16+00:00", "last_traded_at": "2021-07-18T10:27:16+00:00", "last_fetch_at": "2021-07-18T10:27:16+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://crypto.com/exchange/trade/spot/BTC_USDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "EOS", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.00011634, "volume": 2941934.8, "converted_last": { "btc": 1, "eth": 16.128257, "usd": 31721 }, "converted_volume": { "btc": 342.265, "eth": 5520, "usd": 10857024 }, "trust_score": "green", "bid_ask_spread_percentage": 0.068746, "timestamp": "2021-07-18T10:37:42+00:00", "last_traded_at": "2021-07-18T10:37:42+00:00", "last_fetch_at": "2021-07-18T10:37:42+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/EOS-to-BTC", "token_info_url": null, "coin_id": "eos", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "P2PB2B", "identifier": "p2pb2b", "has_trading_incentive": false }, "last": 31687.7, "volume": 6444.828543, "converted_last": { "btc": 0.99858688, "eth": 16.123067, "usd": 31688 }, "converted_volume": { "btc": 6436, "eth": 103910, "usd": 204221793 }, "trust_score": "green", "bid_ask_spread_percentage": 0.108205, "timestamp": "2021-07-18T10:32:01+00:00", "last_traded_at": "2021-07-18T10:32:01+00:00", "last_fetch_at": "2021-07-18T10:32:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "LTC", "target": "BTC", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 0.00382682, "volume": 622.65305348, "converted_last": { "btc": 1, "eth": 16.163164, "usd": 31686 }, "converted_volume": { "btc": 2.382781, "eth": 38.513283, "usd": 75502 }, "trust_score": "green", "bid_ask_spread_percentage": 0.224896, "timestamp": "2021-07-18T10:25:31+00:00", "last_traded_at": "2021-07-18T10:25:31+00:00", "last_fetch_at": "2021-07-18T10:25:31+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Coinsbit", "identifier": "coinsbit", "has_trading_incentive": false }, "last": 0.061952, "volume": 33077.36988703, "converted_last": { "btc": 1, "eth": 16.161861, "usd": 31694 }, "converted_volume": { "btc": 2049, "eth": 33119, "usd": 64946896 }, "trust_score": "green", "bid_ask_spread_percentage": 0.011622, "timestamp": "2021-07-18T10:27:01+00:00", "last_traded_at": "2021-07-18T10:27:01+00:00", "last_fetch_at": "2021-07-18T10:27:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://coinsbit.io/trade/ETH_BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "EUR", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 27159.2, "volume": 1270.6222043901996, "converted_last": { "btc": 1.010487, "eth": 16.315591, "usd": 32063 }, "converted_volume": { "btc": 1284, "eth": 20731, "usd": 40739352 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010037, "timestamp": "2021-07-18T10:31:33+00:00", "last_traded_at": "2021-07-18T10:31:33+00:00", "last_fetch_at": "2021-07-18T10:31:33+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/BTC_EUR?ref=37754157", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Exrates", "identifier": "exrates", "has_trading_incentive": false }, "last": 31650.31, "volume": 185.22672503, "converted_last": { "btc": 1.00001, "eth": 16.129251, "usd": 31720 }, "converted_volume": { "btc": 185.229, "eth": 2988, "usd": 5875300 }, "trust_score": "green", "bid_ask_spread_percentage": 0.221729, "timestamp": "2021-07-18T10:39:46+00:00", "last_traded_at": "2021-07-18T10:39:46+00:00", "last_fetch_at": "2021-07-18T10:39:46+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exrates.me/trading/BTCUSDT", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "BTSE", "identifier": "btse", "has_trading_incentive": false }, "last": 31664.5, "volume": 1725.3684215940564, "converted_last": { "btc": 0.99925894, "eth": 16.15116, "usd": 31665 }, "converted_volume": { "btc": 1724, "eth": 27867, "usd": 54632928 }, "trust_score": "green", "bid_ask_spread_percentage": 0.04419, "timestamp": "2021-07-18T10:26:27+00:00", "last_traded_at": "2021-07-18T10:26:27+00:00", "last_fetch_at": "2021-07-18T10:26:27+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.btse.com/en/trading/BTC-USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "LTC", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.0038189, "volume": 62415.044, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 238.357, "eth": 3849, "usd": 7563004 }, "trust_score": "green", "bid_ask_spread_percentage": 0.026182, "timestamp": "2021-07-18T10:31:35+00:00", "last_traded_at": "2021-07-18T10:31:35+00:00", "last_fetch_at": "2021-07-18T10:31:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/LTC-to-BTC", "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "P2PB2B", "identifier": "p2pb2b", "has_trading_incentive": false }, "last": 31685.01, "volume": 6430.413335, "converted_last": { "btc": 1.002836, "eth": 16.191671, "usd": 31823 }, "converted_volume": { "btc": 6449, "eth": 104119, "usd": 204632026 }, "trust_score": "green", "bid_ask_spread_percentage": 0.14126, "timestamp": "2021-07-18T10:32:01+00:00", "last_traded_at": "2021-07-18T10:32:01+00:00", "last_fetch_at": "2021-07-18T10:32:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDC", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 31639.625721, "volume": 5.35795179, "converted_last": { "btc": 0.99983838, "eth": 16.160552, "usd": 31681 }, "converted_volume": { "btc": 5.357086, "eth": 86.587, "usd": 169747 }, "trust_score": "green", "bid_ask_spread_percentage": 0.075566, "timestamp": "2021-07-18T10:25:32+00:00", "last_traded_at": "2021-07-18T10:25:32+00:00", "last_fetch_at": "2021-07-18T10:25:32+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "BTC", "target": "USDC", "market": { "name": "Binance", "identifier": "binance", "has_trading_incentive": false }, "last": 31651.49, "volume": 1189.5871447627921, "converted_last": { "btc": 0.99934738, "eth": 16.118163, "usd": 31699 }, "converted_volume": { "btc": 1189, "eth": 19174, "usd": 37708153 }, "trust_score": "green", "bid_ask_spread_percentage": 0.013602, "timestamp": "2021-07-18T10:38:35+00:00", "last_traded_at": "2021-07-18T10:38:35+00:00", "last_fetch_at": "2021-07-18T10:38:35+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.com/en/trade/BTC_USDC?ref=37754157", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "usd-coin" }, { "base": "BCH", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.014079, "volume": 14503.3432, "converted_last": { "btc": 1, "eth": 16.128257, "usd": 31721 }, "converted_volume": { "btc": 204.193, "eth": 3293, "usd": 6477220 }, "trust_score": "green", "bid_ask_spread_percentage": 0.078086, "timestamp": "2021-07-18T10:37:54+00:00", "last_traded_at": "2021-07-18T10:37:54+00:00", "last_fetch_at": "2021-07-18T10:37:54+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/BCH-to-BTC", "token_info_url": null, "coin_id": "bitcoin-cash", "target_coin_id": "bitcoin" }, { "base": "ETH", "target": "BTC", "market": { "name": "Coinbase Exchange", "identifier": "gdax", "has_trading_incentive": false }, "last": 0.0619, "volume": 7298.21030466, "converted_last": { "btc": 1, "eth": 16.128257, "usd": 31721 }, "converted_volume": { "btc": 451.759, "eth": 7286, "usd": 14330314 }, "trust_score": "green", "bid_ask_spread_percentage": 0.016155, "timestamp": "2021-07-18T10:37:24+00:00", "last_traded_at": "2021-07-18T10:37:24+00:00", "last_fetch_at": "2021-07-18T10:38:46+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://pro.coinbase.com/trade/ETH-BTC", "token_info_url": null, "coin_id": "ethereum", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "Binance US", "identifier": "binance_us", "has_trading_incentive": false }, "last": 31662.5, "volume": 760.8263284358468, "converted_last": { "btc": 0.99821177, "eth": 16.099847, "usd": 31663 }, "converted_volume": { "btc": 759.466, "eth": 12249, "usd": 24089664 }, "trust_score": "green", "bid_ask_spread_percentage": 0.0112, "timestamp": "2021-07-18T10:38:10+00:00", "last_traded_at": "2021-07-18T10:38:10+00:00", "last_fetch_at": "2021-07-18T10:38:10+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.binance.us/en/trade/BTC_USD", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "Coineal", "identifier": "coineal", "has_trading_incentive": false }, "last": 31668.38, "volume": 735.93523, "converted_last": { "btc": 1.00231, "eth": 16.183172, "usd": 31806 }, "converted_volume": { "btc": 737.635, "eth": 11910, "usd": 23407030 }, "trust_score": "green", "bid_ask_spread_percentage": 0.120052, "timestamp": "2021-07-18T10:32:03+00:00", "last_traded_at": "2021-07-18T10:32:03+00:00", "last_fetch_at": "2021-07-18T10:32:03+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "ADA", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.0000378, "volume": 7025835, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 265.577, "eth": 4288, "usd": 8426680 }, "trust_score": "green", "bid_ask_spread_percentage": 0.023811, "timestamp": "2021-07-18T10:31:37+00:00", "last_traded_at": "2021-07-18T10:31:37+00:00", "last_fetch_at": "2021-07-18T10:31:37+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/ADA-to-BTC", "token_info_url": null, "coin_id": "cardano", "target_coin_id": "bitcoin" }, { "base": "ADA", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.000037788, "volume": 6973384, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 263.51, "eth": 4250, "usd": 8358339 }, "trust_score": "green", "bid_ask_spread_percentage": 0.034394, "timestamp": "2021-07-18T10:38:47+00:00", "last_traded_at": "2021-07-18T10:38:47+00:00", "last_fetch_at": "2021-07-18T10:38:47+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/ADA-to-BTC", "token_info_url": null, "coin_id": "cardano", "target_coin_id": "bitcoin" }, { "base": "LINK", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.00049715, "volume": 38218.1, "converted_last": { "btc": 1, "eth": 16.128689, "usd": 31719 }, "converted_volume": { "btc": 19.000128, "eth": 306.447, "usd": 602669 }, "trust_score": "green", "bid_ask_spread_percentage": 0.028185, "timestamp": "2021-07-18T10:38:36+00:00", "last_traded_at": "2021-07-18T10:38:36+00:00", "last_fetch_at": "2021-07-18T10:38:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/LINK-to-BTC", "token_info_url": null, "coin_id": "chainlink", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "B2BX", "identifier": "b2bx", "has_trading_incentive": false }, "last": 31657.515435, "volume": 36.7318, "converted_last": { "btc": 1.001966, "eth": 16.194935, "usd": 31749 }, "converted_volume": { "btc": 36.804002, "eth": 594.869, "usd": 1166188 }, "trust_score": "green", "bid_ask_spread_percentage": 0.033862, "timestamp": "2021-07-18T10:25:32+00:00", "last_traded_at": "2021-07-18T10:25:32+00:00", "last_fetch_at": "2021-07-18T10:25:32+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "HIT", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.00000575, "volume": 1227543.4, "converted_last": { "btc": 1, "eth": 16.122532, "usd": 31730 }, "converted_volume": { "btc": 7.058375, "eth": 113.799, "usd": 223961 }, "trust_score": "green", "bid_ask_spread_percentage": 0.086957, "timestamp": "2021-07-18T10:34:04+00:00", "last_traded_at": "2021-07-18T10:34:04+00:00", "last_fetch_at": "2021-07-18T10:34:04+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/HIT-to-BTC", "token_info_url": null, "coin_id": "hitbtc-token", "target_coin_id": "bitcoin" }, { "base": "BCH", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.014092, "volume": 14505.7196, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 204.415, "eth": 3301, "usd": 6486026 }, "trust_score": "green", "bid_ask_spread_percentage": 0.141774, "timestamp": "2021-07-18T10:31:34+00:00", "last_traded_at": "2021-07-18T10:31:34+00:00", "last_fetch_at": "2021-07-18T10:31:34+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/BCH-to-BTC", "token_info_url": null, "coin_id": "bitcoin-cash", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "CoinEx", "identifier": "coinex", "has_trading_incentive": false }, "last": 31701, "volume": 466.78246029, "converted_last": { "btc": 1.003342, "eth": 16.200638, "usd": 31819 }, "converted_volume": { "btc": 468.342, "eth": 7562, "usd": 14852442 }, "trust_score": "green", "bid_ask_spread_percentage": 0.112551, "timestamp": "2021-07-18T10:30:09+00:00", "last_traded_at": "2021-07-18T10:30:09+00:00", "last_fetch_at": "2021-07-18T10:30:09+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.coinex.com/trading?currency=USDT&dest=BTC#limit", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Bitget", "identifier": "bitget", "has_trading_incentive": false }, "last": 31646.74, "volume": 9565.0049, "converted_last": { "btc": 1.001625, "eth": 16.184339, "usd": 31746 }, "converted_volume": { "btc": 9581, "eth": 154803, "usd": 303653187 }, "trust_score": "green", "bid_ask_spread_percentage": 0.010599, "timestamp": "2021-07-18T10:28:07+00:00", "last_traded_at": "2021-07-18T10:28:07+00:00", "last_fetch_at": "2021-07-18T10:28:07+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.bitget.io/en/trade/btc_usdt/", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USDT", "market": { "name": "Kraken", "identifier": "kraken", "has_trading_incentive": false }, "last": 31652.2, "volume": 94.99823061, "converted_last": { "btc": 1.001797, "eth": 16.190911, "usd": 31751 }, "converted_volume": { "btc": 95.169, "eth": 1538, "usd": 3016251 }, "trust_score": "green", "bid_ask_spread_percentage": 0.03946, "timestamp": "2021-07-18T10:27:19+00:00", "last_traded_at": "2021-07-18T10:27:19+00:00", "last_fetch_at": "2021-07-18T10:27:19+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://trade.kraken.com/markets/kraken/btc/usdt", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Gemini", "identifier": "gemini", "has_trading_incentive": false }, "last": 31668.82, "volume": 700.7178640163, "converted_last": { "btc": 0.99841102, "eth": 16.10306, "usd": 31669 }, "converted_volume": { "btc": 699.604, "eth": 11284, "usd": 22190908 }, "trust_score": "green", "bid_ask_spread_percentage": 0.012463, "timestamp": "2021-07-18T10:38:24+00:00", "last_traded_at": "2021-07-18T10:38:24+00:00", "last_fetch_at": "2021-07-18T10:38:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "USD", "market": { "name": "eToroX", "identifier": "etorox", "has_trading_incentive": false }, "last": 31846.24, "volume": 54.19121, "converted_last": { "btc": 1.003999, "eth": 16.252573, "usd": 31846 }, "converted_volume": { "btc": 54.408, "eth": 880.747, "usd": 1725786 }, "trust_score": "green", "bid_ask_spread_percentage": 0.151305, "timestamp": "2021-07-18T10:15:57+00:00", "last_traded_at": "2021-07-18T10:15:57+00:00", "last_fetch_at": "2021-07-18T10:31:56+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.etorox.com/xchange#", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "TRY", "market": { "name": "BtcTurk PRO", "identifier": "btcturk", "has_trading_incentive": false }, "last": 271709, "volume": 143.9670946, "converted_last": { "btc": 1.006093, "eth": 16.261643, "usd": 31880 }, "converted_volume": { "btc": 144.844, "eth": 2341, "usd": 4589599 }, "trust_score": "green", "bid_ask_spread_percentage": 0.158264, "timestamp": "2021-07-18T10:25:16+00:00", "last_traded_at": "2021-07-18T10:25:16+00:00", "last_fetch_at": "2021-07-18T10:25:16+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://pro.btcturk.com/pro/al-sat/BTC_TRY", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "BTC", "target": "JPY", "market": { "name": "Liquid", "identifier": "quoine", "has_trading_incentive": false }, "last": 3494171, "volume": 1747.26497094, "converted_last": { "btc": 1.001812, "eth": 16.178297, "usd": 31752 }, "converted_volume": { "btc": 1750, "eth": 28268, "usd": 55479509 }, "trust_score": "green", "bid_ask_spread_percentage": 0.036023, "timestamp": "2021-07-18T10:29:27+00:00", "last_traded_at": "2021-07-18T10:29:27+00:00", "last_fetch_at": "2021-07-18T10:29:27+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://app.liquid.com/exchange/BTCJPY?lang=en", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "TRX", "target": "BTC", "market": { "name": "HitBTC", "identifier": "hitbtc", "has_trading_incentive": false }, "last": 0.0000017901, "volume": 84487316, "converted_last": { "btc": 1, "eth": 16.122532, "usd": 31730 }, "converted_volume": { "btc": 151.241, "eth": 2438, "usd": 4798842 }, "trust_score": "green", "bid_ask_spread_percentage": 0.094908, "timestamp": "2021-07-18T10:34:14+00:00", "last_traded_at": "2021-07-18T10:34:14+00:00", "last_fetch_at": "2021-07-18T10:34:14+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://hitbtc.com/TRX-to-BTC", "token_info_url": null, "coin_id": "tron", "target_coin_id": "bitcoin" }, { "base": "TRX", "target": "BTC", "market": { "name": "Bitcoin.com Exchange", "identifier": "bitcoin_com", "has_trading_incentive": false }, "last": 0.0000017903, "volume": 84477839, "converted_last": { "btc": 1, "eth": 16.146258, "usd": 31730 }, "converted_volume": { "btc": 151.241, "eth": 2442, "usd": 4798830 }, "trust_score": "green", "bid_ask_spread_percentage": 0.111632, "timestamp": "2021-07-18T10:31:36+00:00", "last_traded_at": "2021-07-18T10:31:36+00:00", "last_fetch_at": "2021-07-18T10:31:36+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://exchange.bitcoin.com/exchange/TRX-to-BTC", "token_info_url": null, "coin_id": "tron", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "USDT", "market": { "name": "CoinTiger", "identifier": "cointiger", "has_trading_incentive": false }, "last": 31727.27, "volume": 1051.25723793, "converted_last": { "btc": 1.004173, "eth": 16.216433, "usd": 31827 }, "converted_volume": { "btc": 1056, "eth": 17048, "usd": 33458416 }, "trust_score": "green", "bid_ask_spread_percentage": 0.022123, "timestamp": "2021-07-18T10:29:24+00:00", "last_traded_at": "2021-07-18T10:29:24+00:00", "last_fetch_at": "2021-07-18T10:29:24+00:00", "is_anomaly": false, "is_stale": false, "trade_url": null, "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "tether" }, { "base": "BTC", "target": "USD", "market": { "name": "Liquid", "identifier": "quoine", "has_trading_incentive": false }, "last": 31675.59, "volume": 38.97802688, "converted_last": { "btc": 0.99939472, "eth": 16.139262, "usd": 31676 }, "converted_volume": { "btc": 38.954434, "eth": 629.077, "usd": 1234652 }, "trust_score": "green", "bid_ask_spread_percentage": 0.077705, "timestamp": "2021-07-18T10:29:26+00:00", "last_traded_at": "2021-07-18T10:29:26+00:00", "last_fetch_at": "2021-07-18T10:29:26+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://app.liquid.com/exchange/BTCUSD?lang=en", "token_info_url": null, "coin_id": "bitcoin" }, { "base": "LTC", "target": "BTC", "market": { "name": "Coinsbit", "identifier": "coinsbit", "has_trading_incentive": false }, "last": 0.003823, "volume": 3799.65316935, "converted_last": { "btc": 1, "eth": 16.161861, "usd": 31694 }, "converted_volume": { "btc": 14.526074, "eth": 234.768, "usd": 460384 }, "trust_score": "green", "bid_ask_spread_percentage": 0.036105, "timestamp": "2021-07-18T10:27:01+00:00", "last_traded_at": "2021-07-18T10:27:01+00:00", "last_fetch_at": "2021-07-18T10:27:01+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://coinsbit.io/trade/LTC_BTC", "token_info_url": null, "coin_id": "litecoin", "target_coin_id": "bitcoin" }, { "base": "BTC", "target": "HUSD", "market": { "name": "Huobi Global", "identifier": "huobi", "has_trading_incentive": false }, "last": 31677.05, "volume": 71.9484809329463, "converted_last": { "btc": 1.002451, "eth": 16.202746, "usd": 31766 }, "converted_volume": { "btc": 72.125, "eth": 1166, "usd": 2285489 }, "trust_score": "green", "bid_ask_spread_percentage": 0.011013, "timestamp": "2021-07-18T10:26:57+00:00", "last_traded_at": "2021-07-18T10:26:57+00:00", "last_fetch_at": "2021-07-18T10:26:57+00:00", "is_anomaly": false, "is_stale": false, "trade_url": "https://www.huobi.com/en-us/exchange/btc_husd", "token_info_url": null, "coin_id": "bitcoin", "target_coin_id": "husd" } ] } """.trim()
1
null
2
9
8f28a307d64b22fee9e40853cb67858c30b82ec3
134,924
CryptoApp
Apache License 2.0
plugin-build/src/test/kotlin/io/sentry/android/gradle/integration/SentryPluginVariantTest.kt
getsentry
241,145,606
false
{"Kotlin": 797678, "Python": 6341, "Shell": 2904, "Groovy": 2407, "JavaScript": 1801, "Makefile": 702}
package io.sentry.android.gradle.integration import io.sentry.BuildConfig import org.gradle.util.GradleVersion import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test class SentryPluginVariantTest : BaseSentryPluginTest(BuildConfig.AgpVersion, GradleVersion.current().version) { override val additionalRootProjectConfig: String = // language=Groovy """ flavorDimensions "version" productFlavors { create("demo") { applicationIdSuffix = ".demo" } create("full") { applicationIdSuffix = ".full" } } """.trimIndent() @Test fun `skips variant if set with ignoredVariants`() { applyIgnores(ignoredVariants = setOf("fullRelease")) val build = runner .appendArguments(":app:assembleFullRelease", "--dry-run") .build() assertFalse(":app:uploadSentryProguardMappingsFullRelease" in build.output) } @Test fun `does not skip variant if not included in ignoredVariants`() { applyIgnores(ignoredVariants = setOf("demoRelease", "fullDebug", "demoDebug")) val build = runner .appendArguments(":app:assembleFullRelease", "--dry-run") .build() assertTrue(":app:uploadSentryProguardMappingsFullRelease" in build.output) } @Test fun `skips buildType if set with ignoredBuildTypes`() { applyIgnores(ignoredBuildTypes = setOf("debug")) val build = runner .appendArguments(":app:assembleFullDebug", "--dry-run") .build() assertFalse(":app:uploadSentryProguardMappingsFullDebug" in build.output) assertFalse(":app:uploadSentryProguardMappingsDemoDebug" in build.output) } @Test fun `does not skip buildType if not included in ignoredBuildTypes`() { applyIgnores(ignoredBuildTypes = setOf("debug")) val build = runner .appendArguments(":app:assembleFullRelease", "--dry-run") .build() assertTrue(":app:uploadSentryProguardMappingsFullRelease" in build.output) } @Test fun `skips flavor if set with ignoredFlavors`() { applyIgnores(ignoredFlavors = setOf("full")) var build = runner .appendArguments(":app:assembleFullDebug", "--dry-run") .build() assertFalse(":app:uploadSentryProguardMappingsFullDebug" in build.output) build = runner .appendArguments(":app:assembleFullRelease", "--dry-run") .build() assertFalse(":app:uploadSentryProguardMappingsFullRelease" in build.output) } @Test fun `does not skip flavor if not included in ignoredFlavors`() { applyIgnores(ignoredFlavors = setOf("full")) val build = runner .appendArguments(":app:assembleDemoRelease", "--dry-run") .build() assertTrue(":app:uploadSentryProguardMappingsDemoRelease" in build.output) } private fun applyIgnores( ignoredVariants: Set<String> = setOf(), ignoredBuildTypes: Set<String> = setOf(), ignoredFlavors: Set<String> = setOf() ) { val variants = ignoredVariants.joinToString(",") { "\"$it\"" } val buildTypes = ignoredBuildTypes.joinToString(",") { "\"$it\"" } val flavors = ignoredFlavors.joinToString(",") { "\"$it\"" } appBuildFile.appendText( // language=Groovy """ sentry { autoUploadProguardMapping = false ignoredVariants = [$variants] ignoredBuildTypes = [$buildTypes] ignoredFlavors = [$flavors] tracingInstrumentation { enabled = false } } """.trimIndent() ) } }
39
Kotlin
32
143
9c11c5e637e0900f35a66a95c7553d0616f0c15c
3,911
sentry-android-gradle-plugin
MIT License
androidApp/src/androidMain/kotlin/dev/sasikanth/rss/reader/MainActivity.kt
msasikanth
632,826,313
false
null
/* * Copyright 2023 <NAME> * * 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 dev.sasikanth.rss.reader import MainView import android.graphics.Color import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowCompat import com.arkivanov.decompose.defaultComponentContext import dev.sasikanth.rss.reader.database.DriverFactory import dev.sasikanth.rss.reader.di.AppComponent import dev.sasikanth.rss.reader.di.create import dev.sasikanth.rss.reader.ui.AndroidColorScheme class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) WindowCompat.setDecorFitsSystemWindows(window, false) window.statusBarColor = Color.TRANSPARENT window.navigationBarColor = Color.TRANSPARENT val appComponent = AppComponent::class.create( componentContext = defaultComponentContext(), driverFactory = DriverFactory(this) ) setContent { MainView( appColorScheme = AndroidColorScheme(this), homeViewModelFactory = appComponent.homeViewModelFactory ) } } }
0
Kotlin
0
6
0258e3ed2f2e9a5ea2eba91530b828e133046802
1,707
reader
Apache License 2.0
firebase-dataconnect/src/main/kotlin/com/google/firebase/dataconnect/util/ReferenceCounted.kt
firebase
146,941,185
false
{"Java": 13568535, "PureBasic": 10781995, "Kotlin": 2658699, "Python": 104323, "C++": 86300, "Makefile": 21902, "Shell": 13966, "HCL": 11091, "C": 6939, "JavaScript": 5482, "Mustache": 4729, "Ruby": 2545, "AIDL": 1486, "HTML": 215}
/* * Copyright 2024 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.dataconnect.util import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock internal class ReferenceCounted<T>(val obj: T, var refCount: Int) internal abstract class ReferenceCountedSet<K, V> { private val mutex = Mutex() private val map = mutableMapOf<K, EntryImpl<K, V>>() suspend fun acquire(key: K): Entry<K, V> { val entry = mutex.withLock { map.getOrPut(key) { EntryImpl(this, key, valueForKey(key)) }.apply { refCount++ } } if (entry.refCount == 1) { onAllocate(entry) } return entry } suspend fun release(entry: Entry<K, V>) { require(entry is EntryImpl) { "The given entry was expected to be an instance of ${EntryImpl::class.qualifiedName}, " + "but was ${entry::class.qualifiedName}" } require(entry.set === this) { "The given entry must be created by this object ($this), " + "but was created by a different object (${entry.set})" } val newRefCount = mutex.withLock { val entryFromMap = map[entry.key] requireNotNull(entryFromMap) { "The given entry was not found in this set" } require(entryFromMap === entry) { "The key from the given entry was found in this set, but it was a different object" } require(entry.refCount > 0) { "The refCount of the given entry was expected to be strictly greater than zero, " + "but was ${entry.refCount}" } entry.refCount-- if (entry.refCount == 0) { map.remove(entry.key) } entry.refCount } if (newRefCount == 0) { onFree(entry) } } protected abstract fun valueForKey(key: K): V protected open fun onAllocate(entry: Entry<K, V>) {} protected open fun onFree(entry: Entry<K, V>) {} interface Entry<K, V> { val key: K val value: V } private data class EntryImpl<K, V>( val set: ReferenceCountedSet<K, V>, override val key: K, override val value: V, var refCount: Int = 0, ) : Entry<K, V> companion object { suspend fun <K, V, R> ReferenceCountedSet<K, V>.withAcquiredValue( key: K, callback: suspend (V) -> R ): R { val entry = acquire(key) return try { callback(entry.value) } finally { release(entry) } } } }
440
Java
575
2,270
0697dd3aadd6c13d9e2d321c75173992bfbaac3b
2,974
firebase-android-sdk
Apache License 2.0
src/main/kotlin/com/vitalyk/insight/main/Tables.kt
yay
420,480,103
false
null
package com.vitalyk.insight.main // https://scs.fidelity.com/help/mmnet/help_personal_about_tickers.shtml // Tickers are mostly (up to) 5-character alpha codes, but Shenzhen Stock Exchange, // for example, has 6-character numerical codes. // Market Identifier Code (MIC), four alpha character code, ISO 10383: // https://www.iso20022.org/10383/iso-10383-market-identifier-codes // https://en.wikipedia.org/wiki/Market_Identifier_Code // From ISO 10383 FAQ: // "An operating MIC identifies the entity operating an exchange; it is the ‘parent’ MIC." // Institution description | MIC | Operating MIC // -------------------------------------------------------- // NASDAQ - ALL MARKETS | XNAS | XNAS // NYSE MKT LLC (AMEX) | XASE | XNYS // NEW YORK STOCK EXCHANGE, INC. | XNYS | XNYS // http://www.investopedia.com/terms/m/mic.asp // https://en.wikipedia.org/wiki/Straight-through_processing // International Securities Identification Number (12-character alpha-numerical code), ISO 6166: // https://en.wikipedia.org/wiki/International_Securities_Identification_Number // TODO: check this out: https://www.quandl.com/ http://eoddata.com/default.aspx // Considerations: // http://wiki.c2.com/?TimeSeriesInSql // http://jmoiron.net/blog/thoughts-on-timeseries-databases/ // https://news.ycombinator.com/item?id=9805742
0
Kotlin
0
0
3a52cbf394224755b407fc2a30856ea92d085d74
1,358
insight
MIT License
hazelnet-community/src/main/kotlin/io/hazelnet/community/data/discord/giveaways/GiveawayWinnersCannotBeDrawnException.kt
nilscodes
446,203,879
false
{"TypeScript": 1045486, "Kotlin": 810416, "Dockerfile": 4476, "Shell": 1830, "JavaScript": 1384}
package io.hazelnet.community.data.discord.giveaways class GiveawayWinnersCannotBeDrawnException(override val message: String?): Throwable(message)
0
TypeScript
4
13
79f8b096f599255acb03cc809464d0570a51d82c
148
hazelnet
Apache License 2.0
sample/web-app-compose/src/jsMain/kotlin/com/icerockdev/web/Main.kt
icerockdev
204,874,263
false
null
/* * Copyright 2022 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package com.icerockdev.web import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import com.icerockdev.library.MR import com.icerockdev.library.Testing import dev.icerock.moko.resources.ColorResource import org.jetbrains.compose.web.css.DisplayStyle import org.jetbrains.compose.web.css.FlexDirection import org.jetbrains.compose.web.css.color import org.jetbrains.compose.web.css.display import org.jetbrains.compose.web.css.flexDirection import org.jetbrains.compose.web.css.fontFamily import org.jetbrains.compose.web.css.rgba import org.jetbrains.compose.web.dom.Br import org.jetbrains.compose.web.dom.Div import org.jetbrains.compose.web.dom.Img import org.jetbrains.compose.web.dom.P import org.jetbrains.compose.web.dom.Span import org.jetbrains.compose.web.dom.Text import org.jetbrains.compose.web.renderComposable suspend fun main() { MR.fonts.addFontsToPage() val strings = MR.stringsLoader.getOrLoad() val fileText = mutableStateOf("") renderComposable(rootElementId = "root") { val rememberFileText = remember { fileText } Div( attrs = { style { display(DisplayStyle.Flex) flexDirection(FlexDirection.Column) } } ) { Span { P( attrs = { style { fontFamily(Testing.getFontTtf1().fontFamily) } } ) { Text(Testing.getStringDesc().localized(strings)) } Br() P( attrs = { style { val (r, g, b, a) = (Testing.getGradientColors().first() as ColorResource.Single).color color(rgba(r, g, b, a)) } } ) { Text("Color Test") } Br() Img(Testing.getDrawable().fileUrl) Br() Text(rememberFileText.value) } } } fileText.value = Testing.getTextFile().getText() + "\n" + Testing.getTextsFromAssets()[1].getText() + "\n" + MR.files.some.getText() println(Testing.getTextFile().fileUrl) }
85
Kotlin
55
458
df157ee999b787bf0d3628ab33747ce51b56286d
2,542
moko-resources
Apache License 2.0
plugins/ide-features-trainer/src/training/ui/MessageFactory.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package training.ui import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.text.Strings import org.intellij.lang.annotations.Language import org.jdom.Element import org.jdom.Text import org.jdom.output.XMLOutputter import training.dsl.LessonUtil import training.util.KeymapUtil import training.util.openLinkInBrowser import java.util.regex.Pattern import javax.swing.KeyStroke internal object MessageFactory { private val LOG = Logger.getInstance(MessageFactory::class.java) fun setLinksHandlers(messageParts: List<MessagePart>) { for (message in messageParts) { if (message.type == MessagePart.MessageType.LINK && message.runnable == null) { val link = message.link if (link.isNullOrEmpty()) { LOG.error("No link specified for ${message.text}") } else { message.runnable = Runnable { try { openLinkInBrowser(link) } catch (e: Exception) { LOG.warn(e) } } } } } } fun convert(@Language("HTML") text: String): List<MessagePart> { return text .splitToSequence("\n") .map { paragraph -> val wrappedText = "<root><text>$paragraph</text></root>" val textAsElement = JDOMUtil.load(wrappedText.byteInputStream()).getChild("text") ?: throw IllegalStateException("Can't parse as XML:\n$paragraph") convert(textAsElement) } .reduce { acc, item -> acc + MessagePart("\n", MessagePart.MessageType.LINE_BREAK) + item } } private fun convert(element: Element?): List<MessagePart> { if (element == null) { return emptyList() } val list = mutableListOf<MessagePart>() for (content in element.content) { if (content is Text) { var text = content.getValue() if (Pattern.matches(" *\\p{IsPunctuation}.*", text)) { val indexOfFirst = text.indexOfFirst { it != ' ' } text = "\u00A0".repeat(indexOfFirst) + text.substring(indexOfFirst) } list.add(MessagePart(text, MessagePart.MessageType.TEXT_REGULAR)) } else if (content is Element) { val outputter = XMLOutputter() var type = MessagePart.MessageType.TEXT_REGULAR val text: String = Strings.unescapeXmlEntities(outputter.outputString(content.content)) var textAndSplitFn: (() -> Pair<String, List<IntRange>?>)? = null var link: String? = null var runnable: Runnable? = null when (content.name) { "icon" -> error("Need to return reflection-based icon processing") "illustration" -> type = MessagePart.MessageType.ILLUSTRATION "icon_idx" -> type = MessagePart.MessageType.ICON_IDX "code" -> type = MessagePart.MessageType.CODE "shortcut" -> type = MessagePart.MessageType.SHORTCUT "strong" -> type = MessagePart.MessageType.TEXT_BOLD "callback" -> { type = MessagePart.MessageType.LINK val id = content.getAttributeValue("id") if (id != null) { val callback = LearningUiManager.getAndClearCallback(id.toInt()) if (callback != null) { runnable = Runnable { callback() } } else { LOG.error("Unknown callback with id $id and text $text") } } } "a" -> { type = MessagePart.MessageType.LINK link = content.getAttributeValue("href") } "action" -> { type = MessagePart.MessageType.SHORTCUT link = text textAndSplitFn = { val shortcutByActionId = KeymapUtil.getShortcutByActionId(text) if (shortcutByActionId != null) { KeymapUtil.getKeyboardShortcutData(shortcutByActionId) } else { KeymapUtil.getGotoActionData(text) } } } "raw_shortcut" -> { type = MessagePart.MessageType.SHORTCUT textAndSplitFn = { KeymapUtil.getKeyStrokeData(KeyStroke.getKeyStroke(text)) } } "ide" -> { type = MessagePart.MessageType.TEXT_REGULAR textAndSplitFn = { LessonUtil.productName to null } } } val message = MessagePart(type, textAndSplitFn ?: { text to null }) message.link = link message.runnable = runnable list.add(message) } } return list } }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
4,764
intellij-community
Apache License 2.0
app/src/main/java/com/example/newsfeedapp/Model/Article.kt
Srihitha18798
457,221,116
false
{"Kotlin": 19435}
package com.example.newsfeedapp.Model class Article { var author: String? = null var title: String? = null var description: String? = null var url: String? = null var urlToImage: String? = null var publishedAt: String? = null }
0
Kotlin
0
5
7a1621c80c518d4d82efadd2ef8cf30a77c1b79c
253
NewsFeedApp
Apache License 2.0
app/src/main/java/com/composetemplate/core/data/storage/PreferenceDataStore.kt
rafi4204
567,796,241
false
null
package com.composetemplate.core.data.storage import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import com.composetemplate.core.data.storage.PreferenceDataStore.PreferencesKeys.PREF_LOGGED_IN import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import javax.inject.Inject class PreferenceDataStore @Inject constructor( private val dataStore: DataStore<Preferences> ) { companion object { // todo change the name accordingly const val PREFS_NAME = "app_prefs" } object PreferencesKeys { val PREF_LOGGED_IN = booleanPreferencesKey("pref_logged_in") } suspend fun completeLogin(complete: Boolean) { dataStore.edit { it[PREF_LOGGED_IN] = complete } } val isLoggedIn: Flow<Boolean> = dataStore.data.map { it[PREF_LOGGED_IN] ?: false } }
0
null
3
7
e1d3bc966ac0d590a3dac0210f1442d3dc90610c
1,006
android-compose-template
MIT License
app/src/main/java/nl/jovmit/friends/domain/user/User.kt
mitrejcevski
336,415,632
false
{"Kotlin": 122711}
package nl.jovmit.friends.domain.user import android.os.Parcelable import kotlinx.parcelize.Parcelize @Parcelize data class User( val id: String, val email: String, val about: String ) : Parcelable
2
Kotlin
7
32
7fe7a87f6948e9e7590dfadcb8d1cd35c096a753
206
friends
Apache License 2.0
plugins/kotlin/j2k/new/tests/testData/newJ2k/literalExpression/stringEscaping.kt
JetBrains
2,489,216
false
null
class A { // ascii escapes var ascii1 = "\t\b\n\r\'\"\\" var ascii2 = "\u000c" var ascii3 = "\\f" var ascii4 = "\\\u000c" // backslash var backslash1 = "\u0001" var backslash2 = "\\1" var backslash3 = "\\\u0001" var backslash4 = "\\\\1" var backslash5 = "\\\\\u0001" var backslash6 = "\u0001\u0001" // dollar var dollar1 = "\$a" var dollar2 = "\$A" var dollar3 = "\${s}" var dollar4 = "$$" // octal var octal1 = "\u0001\u0000\u0001\u0001\u0001\u0002\u0001\u0003\u0001\u0004" var octal2 = "\u0001\u0000\u0001\u0001\u0001\u0002\u0001\u0003\u0001\u0004" + "\u0001\u000d\u0001\u000c\u0001\u000d\u0002\u0001\u0001" var octal3 = "\u003f0123" var octal4 = "\u00490123" var octal5 = "\u00ff0123" var octal6 = "\u0000Text" var octal7 = "\u00009" }
214
null
4829
15,129
5578c1c17d75ca03071cc95049ce260b3a43d50d
850
intellij-community
Apache License 2.0
app/src/main/java/com/muzzley/app/tiles/TilesFragment.kt
habitio
191,952,436
false
{"Java": 759418, "Kotlin": 611639, "JavaScript": 4086}
package com.muzzley.app.tiles import android.app.Activity import android.app.ProgressDialog import android.content.Intent import android.os.Bundle import androidx.fragment.app.Fragment import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.jakewharton.rxbinding2.view.RxView import com.muzzley.App import com.muzzley.Constants import com.muzzley.Navigator import com.muzzley.R import com.muzzley.app.ProfilesActivity import com.muzzley.app.workers.DevicePickerActivity import com.muzzley.app.cards.ContainerAdapter import com.muzzley.app.userprofile.UserPreferences import com.muzzley.model.tiles.ServiceSubscriptions import com.muzzley.model.tiles.TileGroup import com.muzzley.providers.BusProvider import com.muzzley.services.PreferencesRepository import com.muzzley.util.* import com.muzzley.util.rx.LogObserver import com.muzzley.util.ui.* import com.squareup.otto.Subscribe import io.reactivex.Observable import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.fragment_tiles.* import kotlinx.android.synthetic.main.services_layout_blank_states.* import kotlinx.android.synthetic.main.tiles_layout_blank_states.* import timber.log.Timber import javax.inject.Inject /** * Created by caan on 03-11-2015. */ class TilesFragment : Fragment(), SwipeRefreshLayout.OnRefreshListener, TilesGroupHolder.GroupCallBack { val CREATE_GROUP_CODE = 100 @Inject lateinit var preferencesRepository: PreferencesRepository @Inject lateinit var navigator: Navigator @Inject lateinit var userPreferences: UserPreferences @Inject lateinit var tilesController: TilesController @Inject lateinit var modelsStore: ModelsStore private var gridLayoutManager: GridLayoutManager? = null var blockUI: Boolean = false enum class ViewState { LOADING, BLANK_DEVICES, BLANK_SERVICES, DATA, ERROR } private var spanCount: Int = 0 var isVisibleToUser: Boolean = false var active = Constants.Active.PROFILES var compositeDisposable: CompositeDisposable? = null companion object { @JvmStatic fun newInstance(): TilesFragment = TilesFragment() } override fun onCreateView(inflater: LayoutInflater , container: ViewGroup?, savedInstanceState: Bundle?): View { BusProvider.getInstance().register(this) Timber.d("onCreateView") return inflater.inflate(R.layout.fragment_tiles, container, false) } override fun onActivityCreated(savedInstance: Bundle?) { super.onActivityCreated(savedInstance) App.appComponent.inject(this) val viewWidth = ScreenInspector.getScreenWidth(activity) val cardViewWidth = activity!!.resources.getDimension(R.dimen.tile_min_width) spanCount = Math.max(2, Math.floor((viewWidth / cardViewWidth).toDouble()).toInt()) Timber.d("widths: $recyclerView.width, $viewWidth, $cardViewWidth, ${this.spanCount}") gridLayoutManager = GridLayoutManager(activity, this.spanCount).apply { recycleChildrenOnDetach = true orientation = LinearLayoutManager.VERTICAL } recyclerView.layoutManager = gridLayoutManager recyclerView.setHasFixedSize(true) // agentFragment to pull to refresh swipeRefresh.setOnRefreshListener(this) listOf(buttonAdd,button_add_device,devicesButtonBlankState,servicesButtonBlankState).forEach { it.setOnClickListener { launchProfilesActivity(active) } } // if (getString(R.string.app_id).contains("vodafone")) { // if (!getString(R.string.app_id).contains("allianz")) { // segmentedGroup.hide() // } //FIXME: move this to connection tilesController.subscribeAll() if (resources.getBoolean(R.bool.disable_timeline)) { // if (getString(R.string.app_id).contains("vodafone")) { userVisibleHint = true } group.setOnClickListener(this::group) } override fun setUserVisibleHint(isVisibleToUser: Boolean) { this.isVisibleToUser = isVisibleToUser val visibleView = view != null Timber.d("isVisibleToUser: $isVisibleToUser, visbleView: $visibleView, buttonAddVisible: ${buttonAdd != null}") super.setUserVisibleHint(isVisibleToUser) fake?.let { view -> isVisibleToUser && view.postDelayed({ //is null on slow devices ?! ShowcaseBuilder.showcase(activity!!, getString(R.string.mobile_onboarding_devices_1_title), getString(R.string.mobile_onboarding_devices_1_text), getString(R.string.mobile_onboarding_devices_1_close), view, R.string.on_boarding_add_device ).subscribe(LogObserver<Boolean>("onboarding tiles1")) },500) } } fun showState(state: ViewState) { viewFlipper.displayedChild = state.ordinal } override fun onStart() { super.onStart() if (modelsStore.models == null) { showState(ViewState.LOADING) onRefresh() } else { updateControl() updateUi(modelsStore.models) } } @Subscribe fun onTilesRefresh(tilesRefresh: TilesRefresh){ activity?.supportFragmentManager?.apply { if (findFragmentByTag(Constants.FRAGMENT_GROUP) != null) { popBackStack() } } blockUI = true onRefresh() } private var progressDialog: ProgressDialog? = null fun showLoading(show: Boolean) { if (blockUI) { if (show) { progressDialog = ProgDialog.show(context!!) } else { progressDialog?.dismiss() blockUI = false } } else { if (show) { swipeRefresh.post { swipeRefresh.isRefreshing = true } } else { swipeRefresh.isRefreshing = false } } } override fun onRefresh() { val tilesCount = modelsStore.models?.tilesData?.tiles?.size showLoading(true) tilesController.getModels().subscribe({ models -> modelsStore.models = models models.preferences?.let { userPreferences.update(it) } showLoading(false) updateControl() updateUi(models) tilesController.subscribeTilesDevicesStatus(models) tilesController.getTilesDevicesStatus(models) // not the first run , which means it"s a refresh, and there"s something new if (tilesCount != null && tilesCount < models?.tilesData?.tiles?.size ?: 0) { // if (tilesCount != null ) { RxView.globalLayouts(recyclerView) .take(1) .flatMap { val v = gridLayoutManager?.findViewByPosition(1) if (v == null) Observable.just(false) else ShowcaseBuilder.showcase( activity!!, getString(R.string.mobile_onboarding_tile_added_1_title), getString(R.string.mobile_onboarding_tile_added_1_text), getString(R.string.mobile_onboarding_tile_added_1_close), v, R.string.on_boarding_new_tile ) } // .flatMap{ // if (modelsStore?.models?.anythingGroupable()) { // ShowcaseBuilder.showcase( // activity, // getString(R.string.mobile_onboarding_create_group_1_title), // getString(R.string.mobile_onboarding_create_group_1_text), // getString(R.string.mobile_onboarding_create_group_1_close), // R.id.group, // R.string.on_boarding_group_create // ) // } else { // Observable.just(true) // } // } // .flatMap{ // val firstGroup = models.tilesViewModel.findIndexOf {it is TileGroup && (it as TileGroup).parent != null} // Timber.d("first group : $firstGroup") // if (firstGroup >= 0) { // gridLayoutManager.scrollToPositionWithOffset(firstGroup, 40) // RxView.globalLayouts(recyclerView) // .take(1) //// .singleOrError() // .flatMap { // ShowcaseBuilder.showcase( // activity, // getString(R.string.mobile_onboarding_group_created_1_title), // getString(R.string.mobile_onboarding_group_created_1_text), // getString(R.string.mobile_onboarding_group_created_1_close), // gridLayoutManager.findViewByPosition(firstGroup), // R.string.on_boarding_new_group // ) // } // } else { // Observable.just(false) // } // } .subscribe(LogObserver<Boolean>("onboarding tiles2")) } }, { Timber.d(it, "Tile error") fail(it.message) showState(ViewState.ERROR) }).addTo(compositeDisposable) } fun updateControl() { val segments = mutableListOf(Constants.Active.PROFILES to getString(R.string.mobile_devices)) if (modelsStore.models?.bundlesAndServices?.bundles.isNotNullOrEmpty()) segments.add(Constants.Active.BUNDLES to getString(R.string.mobile_bundles)) if (modelsStore.models?.bundlesAndServices?.services.isNotNullOrEmpty()) segments.add(Constants.Active.SERVICES to getString(R.string.mobile_services)) if (segments.size == 1) { buttonAdd.invisible() segmentedGroup.hide() button_add_device.show() } else { segmentedGroup.show() buttonAdd.show() segmentedGroup.setContainerData(segments.map { it.second }) segmentedGroup.setSelected(segments.indexOfFirst { it.first == active }) segmentedGroup.listenSelected().subscribe { active = segments[it].first updateUi(modelsStore.models) } } } fun updateUi(models: Models?) { //FIXME: comented until we have groups again in v3 //group.setVisibility(active == R.id.devices ? View.VISIBLE: View.INVISIBLE) if (models == null) { return } if (active == Constants.Active.PROFILES) { gridLayoutManager?.spanSizeLookup = object: GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int = if (models.tilesViewModel[position] is TileGroup && (models.tilesViewModel[position] as TileGroup).parent == null ) spanCount else 1 } val tilesAdapter = TileGroupsAdapter(activity!!, this) tilesAdapter.setData(models.tilesViewModel) recyclerView.adapter = tilesAdapter showState(if (models.tilesViewModel.isNotEmpty()) ViewState.DATA else ViewState.BLANK_DEVICES) } else { gridLayoutManager?.spanSizeLookup = GridLayoutManager.DefaultSpanSizeLookup() val servicesAdapter = ContainerAdapter<ServiceSubscriptions.Subscription>(activity, R.layout.subscription) servicesAdapter.setData(models.serviceSubscriptions) recyclerView.adapter = servicesAdapter showState(if (models.serviceSubscriptions.isNotNullOrEmpty()) ViewState.DATA else ViewState.BLANK_SERVICES) } //TODO: handle bundles also ? } fun fail(reason: String?) { showLoading(false) FeedbackMessages.showError(recyclerView) } private fun launchProfilesActivity(defaultView: Constants.Active) { context?.startActivity<ProfilesActivity> { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP putExtra(Constants.DEFAULT_SEGMENT,defaultView) } } fun group(view: View) { if (modelsStore.models?.anythingGroupable() != true) FeedbackMessages.showMessage(recyclerView,getString(R.string.mobile_no_groupable_devices_text)) else { startActivityForResult<DevicePickerActivity>(CREATE_GROUP_CODE) { putExtra(Constants.EXTRA_DEVICE_PICKER_ACTIONBAR_TEXT, getString(R.string.mobile_group_create)) putExtra(Constants.EXTRA_DEVICE_PICKER_EDITTEXT_HINT, "Component name") putExtra(Constants.EXTRA_DEVICE_PICKER_CREATE_GROUP, true) } } } override fun onGroupClick(groupId: String) { if (modelsStore.models?.tileGroupsData?.tileGroups?.any {it.id == groupId} == true) { // just making sure group wasn"t removed meanwhile val fragment = TileGroupsFragment.newInstance(groupId) activity?.supportFragmentManager ?.beginTransaction() ?.setCustomAnimations(R.anim.abc_slide_in_bottom, 0, 0, R.anim.slide_out_down) ?.add(R.id.group_menu_container, fragment, Constants.FRAGMENT_GROUP) ?.addToBackStack("TileGroupsFragment") ?.commit() } } override fun onResume() { super.onResume() compositeDisposable = compositeDisposable ?: CompositeDisposable() } override fun onPause() { compositeDisposable?.dispose() compositeDisposable = null super.onPause() } override fun onDestroyView() { BusProvider.getInstance().unregister(this) super.onDestroyView() } override fun onActivityResult(requestCode: Int , resultCode: Int , data: Intent? ) { if(resultCode == Activity.RESULT_OK) { if(requestCode == CREATE_GROUP_CODE) { onRefresh() } } } }
1
null
1
1
57174e1ca5e0d72ebc01d0750e278fc493b44e42
14,887
habit-whitelabel-app-android
MIT License
app/src/main/java/com/cyh128/hikari_novel/data/repository/BookshelfRepository.kt
15dd
645,796,447
false
{"Kotlin": 332962}
package com.cyh128.hikari_novel.data.repository import com.cyh128.hikari_novel.data.model.BookshelfNovelInfo import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import javax.inject.Inject import javax.inject.Singleton @Singleton class BookshelfRepository @Inject constructor() { private val _bookshelfList = MutableStateFlow<List<BookshelfNovelInfo>>(mutableListOf()) val bookshelfList get() = _bookshelfList.asStateFlow() fun updateBookshelfList(list: List<BookshelfNovelInfo>) { _bookshelfList.value = list } }
1
Kotlin
12
400
402efc07ced528fc939d5d645e1f8a8f07636f40
578
wenku8reader
MIT License
backend/src/main/kotlin/com/willianantunes/azureb2ccustompolicydesigner/AzureB2cCustomPolicyDesignerApplication.kt
willianantunes
419,873,237
false
{"Kotlin": 22610, "JavaScript": 11846}
package com.willianantunes.azureb2ccustompolicydesigner import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class AzureB2cCustomPolicyDesignerApplication fun main(args: Array<String>) { runApplication<AzureB2cCustomPolicyDesignerApplication>(*args) }
1
Kotlin
1
7
828a25f933d3fad7137daf2160af8c57cb9e897c
342
azure-b2c-custom-policy-designer
MIT License
magick-kt/src/commonMain/kotlin/imagemagick/core/enums/ColorSpace.kt
Gounlaf
692,782,810
false
{"Kotlin": 666114}
package imagemagick.core.enums // // /!\ do not modify order: it's directly linked to the underlying C library enum/order /!\ // /** * Specifies a kind of color space. */ enum class ColorSpace { /** Undefined. */ UNDEFINED, /** CMY. */ CMY, /** CMYK. */ CMYK, /** Gray. */ GRAY, /** HCL. */ HCL, /** HCLp. */ HCLP, /** HSB. */ HSB, /** HSI. */ HSI, /** HSL. */ HSL, /** HSV. */ HSV, /** HWB. */ HWB, /** Lab. */ LAB, /** LCH. */ LCH, /** LCHab. */ LCHAB, /** LCHuv. */ LCHUV, /** Log. */ LOG, /** LMS. */ LMS, /** Luv. */ LUV, /** OHTA. */ OHTA, /** Rec601YCbCr. */ REC601YCBCR, /** Rec709YCbCr. */ REC709YCBCR, /** RGB. */ RGB, /** scRGB. */ SCRGB, /** sRGB. */ SRGB, /** Transparent. */ TRANSPARENT, /** XyY. */ XYY, /** XYZ. */ XYZ, /** YCbCr. */ YCBCR, /** YCC. */ YCC, /** YDbDr. */ YDBDR, /** YIQ. */ YIQ, /** YPbPr. */ YPBPR, /** YUV. */ YUV, /** LinearGray. */ LINEARGRAY, /** Jzazbz. */ JZAZBZ }
0
Kotlin
0
0
8454fc5e2e4b62bdb9921423d0a4c8af94fccb64
1,223
Magick.KT
MIT License
app/src/main/kotlin/com/lazysoul/kotlinwithandroid/injection/module/ApplicationModule.kt
myeonginwoo
96,596,657
false
null
package com.lazysoul.kotlinwithandroid.injection.module import android.app.Application import android.content.Context import android.content.SharedPreferences import dagger.Module import dagger.Provides import javax.inject.Singleton /** * Created by Lazysoul on 2017. 7. 17.. */ @Module class ApplicationModule(private val application: Application) { @Provides @Singleton fun provideApplication(): Application = application @Provides fun provideSharedPrefs(): SharedPreferences = application.getSharedPreferences("kotlinWithAndroid", Context.MODE_PRIVATE) @Provides fun provideEditor(pref: SharedPreferences): SharedPreferences.Editor = pref.edit() }
1
null
1
2
5601a5c890510244f12bad23e219fbe3502655b9
700
KotlinWithAndroid
MIT License
ktor-server/ktor-server-plugins/ktor-server-auth/jvm/src/io/ktor/server/auth/BasicAuth.kt
ktorio
40,136,600
false
null
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.auth import io.ktor.application.* import io.ktor.http.auth.* import io.ktor.request.* import io.ktor.response.* import io.ktor.util.* import java.nio.charset.* /** * Represents a Basic authentication provider * @property name is the name of the provider, or `null` for a default provider */ class BasicAuthenticationProvider internal constructor( configuration: Configuration ) : AuthenticationProvider(configuration) { internal val realm: String = configuration.realm internal val charset: Charset? = configuration.charset internal val authenticationFunction = configuration.authenticationFunction /** * Basic auth configuration */ class Configuration internal constructor(name: String?) : AuthenticationProvider.Configuration(name) { internal var authenticationFunction: AuthenticationFunction<UserPasswordCredential> = { null } /** * Specifies realm to be passed in `WWW-Authenticate` header */ var realm: String = "Ktor Server" /** * Specifies the charset to be used. It can be either UTF_8 or null. * Setting `null` turns legacy mode on that actually means that ISO-8859-1 is used. */ var charset: Charset? = Charsets.UTF_8 set(value) { if (value != null && value != Charsets.UTF_8) { // https://tools.ietf.org/html/rfc7617#section-2.1 // 'The only allowed value is "UTF-8"; it is to be matched case-insensitively' throw IllegalArgumentException("Basic Authentication charset can be either UTF-8 or null") } field = value } /** * Sets a validation function that will check given [UserPasswordCredential] instance and return [Principal], * or null if credential does not correspond to an authenticated principal */ fun validate(body: suspend ApplicationCall.(UserPasswordCredential) -> Principal?) { authenticationFunction = body } } } /** * Installs Basic Authentication mechanism */ fun Authentication.Configuration.basic( name: String? = null, configure: BasicAuthenticationProvider.Configuration.() -> Unit ) { val provider = BasicAuthenticationProvider(BasicAuthenticationProvider.Configuration(name).apply(configure)) val realm = provider.realm val charset = provider.charset val authenticate = provider.authenticationFunction provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context -> val credentials = call.request.basicAuthenticationCredentials(charset) val principal = credentials?.let { authenticate(call, it) } val cause = when { credentials == null -> AuthenticationFailedCause.NoCredentials principal == null -> AuthenticationFailedCause.InvalidCredentials else -> null } if (cause != null) { context.challenge(basicAuthenticationChallengeKey, cause) { call.respond(UnauthorizedResponse(HttpAuthHeader.basicAuthChallenge(realm, charset))) it.complete() } } if (principal != null) { context.principal(principal) } } register(provider) } /** * Retrieves Basic authentication credentials for this [ApplicationRequest] */ @KtorExperimentalAPI fun ApplicationRequest.basicAuthenticationCredentials(charset: Charset? = null): UserPasswordCredential? { when (val authHeader = parseAuthorizationHeader()) { is HttpAuthHeader.Single -> { // Verify the auth scheme is HTTP Basic. According to RFC 2617, the authorization scheme should not be case // sensitive; thus BASIC, or Basic, or basic are all valid. if (!authHeader.authScheme.equals("Basic", ignoreCase = true)) { return null } val userPass = try { decodeBase64(authHeader.blob).toString(charset ?: Charsets.ISO_8859_1) } catch (e: Throwable) { return null } val colonIndex = userPass.indexOf(':') if (colonIndex == -1) { return null } return UserPasswordCredential(userPass.substring(0, colonIndex), userPass.substring(colonIndex + 1)) } else -> return null } } private val basicAuthenticationChallengeKey: Any = "BasicAuth"
6
null
774
9,308
9244f9a4a406f3eca06dc05d9ca0f7d7ec74a314
4,641
ktor
Apache License 2.0
core/common-kmp/src/commonMain/kotlin/org/michaelbel/movies/common/exceptions/CreateSessionException.kt
michaelbel
115,437,864
false
{"Kotlin": 679261, "Java": 10013, "Swift": 342, "Shell": 235}
@file:Suppress( "EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING", "EXPECT_AND_ACTUAL_IN_THE_SAME_MODULE" ) package org.michaelbel.movies.common.exceptions data object CreateSessionException: Exception()
6
Kotlin
31
190
ee5c5b5dedc04666467a5bad73b72ea3fdd987b9
211
movies
Apache License 2.0
visualfsm-core/src/commonMain/kotlin/ru/kontur/mobile/visualfsm/Transition.kt
Kontur-Mobile
495,870,417
false
null
package ru.kontur.mobile.visualfsm import kotlin.reflect.KClass /** * Describes the transition rule state. Makes a transition to the same state * * In generic contains [state][State] * Defines [predicate] and [transform] functions */ abstract class SelfTransition<STATE : State> : Transition<STATE, STATE>() /** * Describes the transition rule between states. * In generic contains [initial state][fromState] and [destination state][toState]. * Defines [predicate] and [transform] functions */ abstract class Transition<FROM : State, TO : State>() { /** * @param fromState a [state][State] that FSM had on [transition][Transition] start * @param toState a [state][State] FSM would have after the [transition][Transition] completes */ @Deprecated( message = "Deprecated, because now the fromState and toState is setted in the generated code (of TransitionsFactory).\n" + "Code generation not configured or configured incorrectly.\n" + "See the quickstart file for more information on set up code generation (https://github.com/Kontur-Mobile/VisualFSM/blob/main/docs/Quickstart.md).", replaceWith = ReplaceWith("Constructor without parameters") ) constructor(fromState: KClass<FROM>, toState: KClass<TO>) : this() { this._fromState = fromState this._toState = toState } /** This property is needed to use it in the generated code. Do not use it. */ @Suppress("PropertyName") var _fromState: KClass<FROM>? = null /** This property is needed to use it in the generated code. Do not use it. */ @Suppress("PropertyName") var _toState: KClass<TO>? = null /** * A [state][State] that FSM had on [transition][Transition] start */ val fromState: KClass<FROM> get() = _fromState ?: error( "\nCode generation not configured or configured incorrectly.\n" + "See the quickstart file for more information on set up code generation (https://github.com/Kontur-Mobile/VisualFSM/blob/main/docs/Quickstart.md).\n" ) /** * A [state][State] FSM would have after the [transition][Transition] completes */ val toState: KClass<TO> get() = _toState ?: error( "\nCode generation not configured or configured incorrectly.\n" + "See the quickstart file for more information on set up code generation (https://github.com/Kontur-Mobile/VisualFSM/blob/main/docs/Quickstart.md).\n" ) /** * Defines requirements for the [transition][Transition] to perform * * @param state current [state][State] * @return true if the transition should be performed, otherwise false */ open fun predicate(state: FROM): Boolean { return true } /** * Creates a [new state][State] * * @param state current [state][State] * @return new [state][State] */ abstract fun transform(state: FROM): TO }
1
null
4
73
655a52255ce8bd69fdb39ed11a2c24b99e899d3f
2,976
VisualFSM
MIT License
purchase/src/main/java/com/yeuristic/purchase/PurchaseListAdapter.kt
yeuristic
344,393,207
false
null
package com.yeuristic.purchase import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView class PurchaseListAdapter( private val data: List<BasePurchaseData> ): RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { TODO("Not yet implemented") } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { TODO("Not yet implemented") } override fun getItemCount(): Int = data.size }
0
Kotlin
0
0
183cf2a70ce9c8f90496b6aac3c46ec21f5e2696
554
example-multi-modules-communication
Apache License 2.0