content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/** * Created by artur on 05.08.2017. */ fun main (args: Array<String>) { println("Hello, World!") }
src/main/kotlin/HelloWorldFile.kt
3710863771
package com.tonyodev.fetch2fileserver import com.tonyodev.fetch2core.server.FileRequest /** Used to authenticate clients trying to connect to the Fetch File Server * instance this authenticator instance is attached to.*/ interface FetchFileServerAuthenticator { /** Method called when a client is attempting to connect to the Fetch File Server. * This method is called on a background thread. * @param sessionId sessionId * @param authorization the authorization token * @param fileRequest the fileRequest the client sent. * @return true if the authorize token is accepted. False otherwise. * */ fun accept(sessionId: String, authorization: String, fileRequest: FileRequest): Boolean }
fetch2fileserver/src/main/java/com/tonyodev/fetch2fileserver/FetchFileServerAuthenticator.kt
1187722400
package com.brentpanther.bitcoinwidget import android.content.Context import android.net.ConnectivityManager import android.os.Build import android.os.PowerManager /** * Check if anything is restricted preventing the widget from downloading an update. */ object NetworkStatusHelper { private fun checkBattery(context: Context): Int { val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager if (powerManager.isPowerSaveMode && !powerManager.isIgnoringBatteryOptimizations(context.packageName)) { return R.string.error_restricted_battery_saver } return 0 } private fun checkBackgroundData(context: Context): Int { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager if (connectivityManager.restrictBackgroundStatus == ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED && connectivityManager.isActiveNetworkMetered) { return R.string.error_restricted_data_saver } } return 0 } fun getRestriction(context: Context): Int { val checkBattery = checkBattery(context) if (checkBattery > 0) return checkBattery return checkBackgroundData(context) } }
bitcoin/src/main/java/com/brentpanther/bitcoinwidget/NetworkStatusHelper.kt
3339068863
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.libraries.pcc.chronicle.api.remote.client import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.android.libraries.pcc.chronicle.api.policy.builder.policy import com.google.android.libraries.pcc.chronicle.api.remote.RemoteEntity import com.google.android.libraries.pcc.chronicle.api.remote.RemoteRequest import com.google.android.libraries.pcc.chronicle.api.remote.RemoteResponse import com.google.android.libraries.pcc.chronicle.api.remote.RemoteResponseMetadata import com.google.android.libraries.pcc.chronicle.api.remote.StreamRequest import com.google.android.libraries.pcc.chronicle.api.remote.serialization.Serializer import com.google.android.libraries.pcc.chronicle.api.storage.EntityMetadata import com.google.android.libraries.pcc.chronicle.api.storage.WrappedEntity import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.argumentCaptor import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class DefaultRemoteStreamClientTest { private val transport = mock<Transport>() private val serializer = mock<Serializer<Foo>>() @Test fun publish_collectsTransportResponseFlow(): Unit = runBlocking { var collected = false whenever(transport.serve(any())).thenAnswer { flow<RemoteResponse> { collected = true } } whenever(serializer.serialize<Foo>(any())) .thenReturn(RemoteEntity(EntityMetadata.getDefaultInstance())) val client = DefaultRemoteStreamClient("Foo", serializer, transport) client.publish( POLICY, listOf( WrappedEntity(metadata = EntityMetadata.getDefaultInstance(), entity = Foo("one")), WrappedEntity(metadata = EntityMetadata.getDefaultInstance(), entity = Foo("two")), ) ) assertThat(collected).isTrue() } @Test fun publish_buildsRemoteRequest(): Unit = runBlocking { val requestCaptor = argumentCaptor<RemoteRequest>() whenever(transport.serve(requestCaptor.capture())).thenAnswer { emptyFlow<RemoteResponse>() } whenever(serializer.serialize<Foo>(any())) .thenReturn(RemoteEntity(EntityMetadata.getDefaultInstance())) val client = DefaultRemoteStreamClient("Foo", serializer, transport) client.publish( POLICY, listOf( WrappedEntity(metadata = EntityMetadata.getDefaultInstance(), entity = Foo("one")), WrappedEntity(metadata = EntityMetadata.getDefaultInstance(), entity = Foo("two")), ) ) verify(serializer, times(2)).serialize<Foo>(any()) val request = requestCaptor.firstValue assertThat(request.metadata.stream.dataTypeName).isEqualTo("Foo") assertThat(request.metadata.stream.operation).isEqualTo(StreamRequest.Operation.PUBLISH) assertThat(request.entities).hasSize(2) } @Test fun subscribe_buildsRemoteRequest(): Unit = runBlocking { val requestCaptor = argumentCaptor<RemoteRequest>() whenever(transport.serve(requestCaptor.capture())).thenAnswer { emptyFlow<RemoteResponse>() } whenever(serializer.serialize<Foo>(any())) .thenReturn(RemoteEntity(EntityMetadata.getDefaultInstance())) val client = DefaultRemoteStreamClient("Foo", serializer, transport) client.subscribe(POLICY).collect {} val request = requestCaptor.firstValue assertThat(request.metadata.stream.dataTypeName).isEqualTo("Foo") assertThat(request.metadata.stream.operation).isEqualTo(StreamRequest.Operation.SUBSCRIBE) assertThat(request.entities).isEmpty() } @Test fun subscribe_servesItemsNotPages(): Unit = runBlocking { var calls = 0 val responses = listOf( RemoteResponse( metadata = RemoteResponseMetadata.getDefaultInstance(), entities = listOf(RemoteEntity(EntityMetadata.getDefaultInstance())) ), RemoteResponse( metadata = RemoteResponseMetadata.getDefaultInstance(), entities = listOf( RemoteEntity(EntityMetadata.getDefaultInstance()), RemoteEntity(EntityMetadata.getDefaultInstance()), RemoteEntity(EntityMetadata.getDefaultInstance()), ) ) ) whenever(transport.serve(any())).thenAnswer { responses.asFlow() } whenever(serializer.deserialize<Foo>(any())).thenAnswer { WrappedEntity(EntityMetadata.getDefaultInstance(), Foo("${calls++}")) } val client = DefaultRemoteStreamClient("Foo", serializer, transport) val received = client.subscribe(POLICY).toList() assertThat(received) .containsExactly( WrappedEntity(EntityMetadata.getDefaultInstance(), Foo("0")), WrappedEntity(EntityMetadata.getDefaultInstance(), Foo("1")), WrappedEntity(EntityMetadata.getDefaultInstance(), Foo("2")), WrappedEntity(EntityMetadata.getDefaultInstance(), Foo("3")), ) .inOrder() } data class Foo(val name: String) companion object { private val POLICY = policy("Foos", "Testing") {} } }
javatests/com/google/android/libraries/pcc/chronicle/api/remote/client/DefaultRemoteStreamClientTest.kt
2907869077
package com.s16.engmyan.fragments import android.graphics.Point import android.os.Bundle import android.util.DisplayMetrics import android.view.* import androidx.appcompat.app.AlertDialog import androidx.core.os.bundleOf import androidx.core.view.GravityCompat import androidx.fragment.app.DialogFragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.s16.engmyan.Constants import com.s16.engmyan.R import com.s16.engmyan.adapters.FavoriteListAdapter import com.s16.engmyan.data.DbManager import com.s16.engmyan.data.FavoriteItem import com.s16.engmyan.data.FavoriteModel import com.s16.engmyan.utils.UIManager import com.s16.utils.gone import com.s16.utils.visible import com.s16.view.Adapter import kotlinx.android.synthetic.main.fragment_favorite.* import kotlinx.coroutines.* import java.lang.Exception class FavoriteFragment : DialogFragment(), FavoriteListAdapter.OnItemClickListener, FavoriteListAdapter.OnItemSelectListener { private lateinit var adapter: FavoriteListAdapter private var onItemClickListener: Adapter.OnItemClickListener? = null private var backgroundScope = CoroutineScope(Dispatchers.IO) private var job: Job? = null private val isTwoPane: Boolean get() = arguments?.getBoolean(Constants.ARG_PARAM_TWO_PANE) ?: false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_favorite, container, false) dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog?.window?.let { if (isTwoPane) { it.setGravity(Gravity.TOP or GravityCompat.START) val metrics = requireContext().resources.displayMetrics val px = 16 * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) val layoutParams = it.attributes layoutParams.x = px.toInt() it.attributes = layoutParams } } return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) favoriteList.layoutManager = LinearLayoutManager(requireContext()) favoriteList.addItemDecoration(DividerItemDecoration(requireContext(), LinearLayoutManager.VERTICAL)) dataBind(favoriteList) adapter.setItemClickListener(this) adapter.setItemSelectListener(this) actionClose.setOnClickListener { dialog?.dismiss() } actionEdit.setOnClickListener { changeEditMode(true) } actionDone.setOnClickListener { changeEditMode(false) } actionDelete.setOnClickListener { performDelete() } } override fun onStart() { super.onStart() dialog?.window?.let { val size = Point() requireActivity().windowManager.defaultDisplay.getSize(size) if (isTwoPane) { val height = (size.y * 0.94).toInt() val width = (size.x * 0.35).toInt() it.setLayout(width, height) } else { val height = (size.y * 0.9).toInt() it.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, height) } } } override fun onDestroy() { job?.cancel() super.onDestroy() } private fun changeEditMode(edit: Boolean) { if (::adapter.isInitialized) { if (edit) { adapter.setSelectMode(true) actionsNormalMode.gone() actionsEditMode.visible() } else { adapter.endSelection() actionsNormalMode.visible() actionsEditMode.gone() } } } private fun dataBind(recyclerView: RecyclerView) { adapter = FavoriteListAdapter() recyclerView.adapter = adapter val model : FavoriteModel by viewModels() model.data.observe(viewLifecycleOwner, Observer<List<FavoriteItem>> { adapter.submitList(it) }) } private fun performDelete() { if (!adapter.hasSelectedItems) return val dialogBuilder = AlertDialog.Builder(requireContext()).apply { setIcon(android.R.drawable.ic_dialog_info) setTitle(R.string.favorites_edit_title) setMessage(R.string.favorites_delete_message) setNegativeButton(android.R.string.cancel) { di, _ -> di.cancel() } setPositiveButton(android.R.string.ok) { di, _ -> removeSelected() di.dismiss() } } dialogBuilder.show() } private fun removeSelected() { val selectedItems = adapter.getSelectedItems().map { it.refId } job = backgroundScope.launch { try { val provider = DbManager(requireContext()).provider() provider.deleteFavoriteAll(selectedItems) val topFav = provider.queryTopFavorites() UIManager.createShortcuts(requireContext(), topFav) } catch (e: Exception) { e.printStackTrace() } } } override fun onItemSelectStart() { changeEditMode(true) } override fun onItemSelectionChange(position: Int, count: Int) { } override fun onItemClick(view: View, id: Long, position: Int) { dialog?.dismiss() onItemClickListener?.onItemClick(null, view, position, id) } companion object { @JvmStatic fun newInstance(isTwoPane: Boolean, itemClickListener: Adapter.OnItemClickListener? = null) = FavoriteFragment().apply { arguments = bundleOf(Constants.ARG_PARAM_TWO_PANE to isTwoPane) onItemClickListener = itemClickListener } } }
app/src/main/java/com/s16/engmyan/fragments/FavoriteFragment.kt
2342641292
package edu.kit.iti.formal.automation.rvt.pragma import edu.kit.iti.formal.automation.st.ast.Pragma /** * */ class SmvBody(val it: Pragma.Attribute) { }
symbex/src/main/kotlin/edu/kit/iti/formal/automation/rvt/pragma/SmvBody.kt
3144602698
/* * Copyright 2020 Andrey Mukamolov * * 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.bookcrossing.mobile.util import com.bookcrossing.mobile.models.BookUri interface BookUriProvider { fun provideBookUri(rawUri: String): BookUri fun buildBookUri(bookCode: String): String }
app/src/main/java/com/bookcrossing/mobile/util/BookUriProvider.kt
2319705055
package com.github.premnirmal.ticker import android.content.SharedPreferences import android.os.Build import androidx.annotation.VisibleForTesting import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDelegate.NightMode import com.github.premnirmal.ticker.components.AppClock import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import org.threeten.bp.DayOfWeek import org.threeten.bp.format.DateTimeFormatter import org.threeten.bp.format.FormatStyle.MEDIUM import java.text.DecimalFormat import java.text.Format import javax.inject.Inject import javax.inject.Singleton import kotlin.random.Random /** * Created by premnirmal on 2/26/16. */ @Singleton class AppPreferences @Inject constructor( @VisibleForTesting internal val sharedPreferences: SharedPreferences, private val clock: AppClock ) { init { INSTANCE = this } fun getLastSavedVersionCode(): Int = sharedPreferences.getInt(APP_VERSION_CODE, -1) fun saveVersionCode(code: Int) { sharedPreferences.edit() .putInt(APP_VERSION_CODE, code) .apply() } val updateIntervalMs: Long get() { return when(sharedPreferences.getInt(UPDATE_INTERVAL, 1)) { 0 -> 5 * 60 * 1000L 1 -> 15 * 60 * 1000L 2 -> 30 * 60 * 1000L 3 -> 45 * 60 * 1000L 4 -> 60 * 60 * 1000L else -> 15 * 60 * 1000L } } val selectedDecimalFormat: Format get() = if (roundToTwoDecimalPlaces()) { DECIMAL_FORMAT_2DP } else { DECIMAL_FORMAT } fun parseTime(time: String): Time { val split = time.split(":".toRegex()) .dropLastWhile { it.isEmpty() } .toTypedArray() val times = intArrayOf(split[0].toInt(), split[1].toInt()) return Time(times[0], times[1]) } fun startTime(): Time { val startTimeString = sharedPreferences.getString(START_TIME, "09:30")!! return parseTime(startTimeString) } fun endTime(): Time { val endTimeString = sharedPreferences.getString(END_TIME, "16:00")!! return parseTime(endTimeString) } fun updateDaysRaw(): Set<String> { val defaultSet = setOf("1", "2", "3", "4", "5") var selectedDays = sharedPreferences.getStringSet(UPDATE_DAYS, defaultSet)!! if (selectedDays.isEmpty()) { selectedDays = defaultSet } return selectedDays } fun setUpdateDays(selected: Set<String>) { sharedPreferences.edit() .putStringSet(UPDATE_DAYS, selected) .apply() } fun updateDays(): Set<DayOfWeek> { val selectedDays = updateDaysRaw() return selectedDays.map { DayOfWeek.of(it.toInt()) } .toSet() } val isRefreshing: StateFlow<Boolean> get() = _isRefreshing private val _isRefreshing = MutableStateFlow(sharedPreferences.getBoolean(WIDGET_REFRESHING, false)) fun setRefreshing(refreshing: Boolean) { _isRefreshing.value = refreshing sharedPreferences.edit() .putBoolean(WIDGET_REFRESHING, refreshing) .apply() } fun tutorialShown(): Boolean { return sharedPreferences.getBoolean(TUTORIAL_SHOWN, false) } fun setTutorialShown(shown: Boolean) { sharedPreferences.edit() .putBoolean(TUTORIAL_SHOWN, shown) .apply() } fun shouldPromptRate(): Boolean = Random.nextInt() % 5 == 0 fun backOffAttemptCount(): Int = sharedPreferences.getInt(BACKOFF_ATTEMPTS, 1) fun setBackOffAttemptCount(count: Int) { sharedPreferences.edit() .putInt(BACKOFF_ATTEMPTS, count) .apply() } fun roundToTwoDecimalPlaces(): Boolean = sharedPreferences.getBoolean(SETTING_ROUND_TWO_DP, true) fun setRoundToTwoDecimalPlaces(round: Boolean) { sharedPreferences.edit() .putBoolean(SETTING_ROUND_TWO_DP, round) .apply() } fun notificationAlerts(): Boolean = sharedPreferences.getBoolean(SETTING_NOTIFICATION_ALERTS, true) fun setNotificationAlerts(set: Boolean) { sharedPreferences.edit() .putBoolean(SETTING_NOTIFICATION_ALERTS, set) .apply() } var themePref: Int get() = sharedPreferences.getInt(APP_THEME, FOLLOW_SYSTEM_THEME) set(value) = sharedPreferences.edit().putInt(APP_THEME, value).apply() @NightMode val nightMode: Int get() = when (themePref) { LIGHT_THEME -> AppCompatDelegate.MODE_NIGHT_NO DARK_THEME, JUST_BLACK_THEME -> AppCompatDelegate.MODE_NIGHT_YES FOLLOW_SYSTEM_THEME -> { if (supportSystemNightMode) AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM else AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY } else -> AppCompatDelegate.MODE_NIGHT_YES } private val supportSystemNightMode: Boolean get() { return (Build.VERSION.SDK_INT > Build.VERSION_CODES.P || Build.VERSION.SDK_INT == Build.VERSION_CODES.P && "xiaomi".equals(Build.MANUFACTURER, ignoreCase = true) || Build.VERSION.SDK_INT == Build.VERSION_CODES.P && "samsung".equals(Build.MANUFACTURER, ignoreCase = true)) } data class Time( val hour: Int, val minute: Int ) companion object { private lateinit var INSTANCE: AppPreferences fun List<String>.toCommaSeparatedString(): String { val builder = StringBuilder() for (string in this) { builder.append(string) builder.append(",") } val length = builder.length if (length > 1) { builder.deleteCharAt(length - 1) } return builder.toString() } const val UPDATE_FILTER = "com.github.premnirmal.ticker.UPDATE" const val SETTING_APP_THEME = "com.github.premnirmal.ticker.theme" const val SORTED_STOCK_LIST = "SORTED_STOCK_LIST" const val PREFS_NAME = "com.github.premnirmal.ticker" const val FONT_SIZE = "com.github.premnirmal.ticker.textsize" const val START_TIME = "START_TIME" const val END_TIME = "END_TIME" const val UPDATE_DAYS = "UPDATE_DAYS" const val TUTORIAL_SHOWN = "TUTORIAL_SHOWN" const val SETTING_WHATS_NEW = "SETTING_WHATS_NEW" const val SETTING_TUTORIAL = "SETTING_TUTORIAL" const val SETTING_AUTOSORT = "SETTING_AUTOSORT" const val SETTING_HIDE_HEADER = "SETTING_HIDE_HEADER" const val SETTING_EXPORT = "SETTING_EXPORT" const val SETTING_IMPORT = "SETTING_IMPORT" const val SETTING_SHARE = "SETTING_SHARE" const val SETTING_NUKE = "SETTING_NUKE" const val SETTING_PRIVACY_POLICY = "SETTING_PRIVACY_POLICY" const val SETTING_ROUND_TWO_DP = "SETTING_ROUND_TWO_DP" const val SETTING_NOTIFICATION_ALERTS = "SETTING_NOTIFICATION_ALERTS" const val WIDGET_BG = "WIDGET_BG" const val WIDGET_REFRESHING = "WIDGET_REFRESHING" const val TEXT_COLOR = "TEXT_COLOR" const val UPDATE_INTERVAL = "UPDATE_INTERVAL" const val LAYOUT_TYPE = "LAYOUT_TYPE" const val WIDGET_SIZE = "WIDGET_SIZE" const val BOLD_CHANGE = "BOLD_CHANGE" const val SHOW_CURRENCY = "SHOW_CURRENCY" const val PERCENT = "PERCENT" const val DID_RATE = "USER_DID_RATE" const val BACKOFF_ATTEMPTS = "BACKOFF_ATTEMPTS" const val APP_VERSION_CODE = "APP_VERSION_CODE" const val APP_THEME = "APP_THEME" const val SYSTEM = 0 const val TRANSPARENT = 1 const val TRANSLUCENT = 2 const val LIGHT = 1 const val DARK = 2 const val LIGHT_THEME = 0 const val DARK_THEME = 1 const val FOLLOW_SYSTEM_THEME = 2 const val JUST_BLACK_THEME = 3 val TIME_FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm") val DATE_FORMATTER: DateTimeFormatter = DateTimeFormatter.ofLocalizedDate(MEDIUM) val AXIS_DATE_FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("LLL dd-yyyy") val DECIMAL_FORMAT: Format = DecimalFormat("#,##0.00##") val DECIMAL_FORMAT_2DP: Format = DecimalFormat("#,##0.00") val SELECTED_DECIMAL_FORMAT: Format get() = INSTANCE.selectedDecimalFormat } }
app/src/main/kotlin/com/github/premnirmal/ticker/AppPreferences.kt
609874186
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.constraintlayout.demos import android.util.Log import androidx.compose.foundation.Canvas import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.layout.layoutId import androidx.compose.ui.tooling.preview.Preview import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.MotionLayout import androidx.constraintlayout.compose.MotionScene @Preview(group = "new", device = "spec:shape=Normal,width=480,height=800,unit=dp,dpi=440") @Composable fun DemoCompose3() { var scene = """ { ConstraintSets: { start: { title: { bottom: ['box2', 'top', 10], start: [ 'box2', 'start',10 ], end: ['box2','end',10], custom: { sliderValue: 0.0, }, }, box1: { width: 50, height: 50, centerVertically: 'parent', start: ['parent','start', 10 ], }, box2: { width: 50, height: 50, centerVertically: 'parent', start: [ 'parent','start', 50], }, }, end: { title: { bottom: ['box2','top',10 ], start: ['box2', 'start',10], end: ['box2','end',10], custom: { sliderValue: 100.0, }, }, box1: { width: 'spread', height: 20, centerVertically: 'parent', end: ['parent','end',10 ], start: ['parent','start', 10 ], }, box2: { width: 50, height: 50, centerVertically: 'parent', end: [ 'parent', 'end',0], rotationZ: 720, }, }, }, Transitions: { default: { from: 'start', to: 'end', onSwipe: { anchor: 'box1', maxVelocity: 4.2, maxAccel: 3, direction: 'end', side: 'end', mode: 'spring', }, }, }, } """ MotionLayout( modifier = Modifier.fillMaxSize().background(Color.DarkGray), motionScene = MotionScene(content = scene) ) { val value = motionProperties(id = "title").value.float("sliderValue").toInt() / 10f; Text( text = value.toString(), modifier = Modifier.layoutId("title"), color = Color.Magenta ) val gradColors = listOf(Color.White, Color.Gray, Color.Magenta) Canvas( modifier = Modifier .layoutId("box1") ) { val spring = Path().apply { moveTo(0f, 0f); for (i in 1..9) { lineTo( i * size.width / 10f, if (i % 2 == 0) 0f else size.height ) } lineTo(size.width, size.height / 2) } drawPath( spring, brush = Brush.linearGradient(colors = gradColors), style = Stroke(width = 15f, cap = StrokeCap.Butt) ) } Canvas(modifier = Modifier.layoutId("box2")) { drawCircle(brush = Brush.linearGradient(colors = gradColors)) } } } // //@Composable // fun Simple() { // ConstraintLayout(modifier = Modifier.fillMaxSize()) { // Button(modifier = Modifier.constrainAs(createRef()) { // centerTo(parent) // }) { // Text(text = "hello") // } // } //} // //
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/demos/Demo3.kt
4285111473
package io.github.restioson.kettle.api.serialization import com.badlogic.ashley.core.Component /** * Interface for components which can be serialized */ @Deprecated("Protobuf + Kryo") interface SerializableComponent : KettleSerializable, Component { /** * Whether to sync the component with the client/server */ var sync: Boolean /** * Whether to save the component to the save file */ var save: Boolean }
api/src/main/kotlin/io/github/restioson/kettle/api/serialization/SerializableComponent.kt
2186676931
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.irc import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.irc.command.IRCListCommand import com.rpkit.chat.bukkit.irc.command.IRCRegisterCommand import com.rpkit.chat.bukkit.irc.command.IRCVerifyCommand import com.rpkit.chat.bukkit.irc.listener.* import com.rpkit.players.bukkit.profile.irc.RPKIRCNick import com.rpkit.players.bukkit.profile.irc.RPKIRCProfile import org.pircbotx.Configuration import org.pircbotx.PircBotX import org.pircbotx.delay.StaticDelay import java.util.concurrent.CompletableFuture import java.util.concurrent.CopyOnWriteArrayList import java.util.logging.Level import kotlin.concurrent.thread /** * IRC service implementation. */ class RPKIRCServiceImpl(override val plugin: RPKChatBukkit) : RPKIRCService { private var ircBotThread: Thread? = null private val ircBot: PircBotX private val onlineUsers = CopyOnWriteArrayList<String>() init { val whitelistValidator = IRCWhitelistValidator(plugin) val configuration = Configuration.Builder() .setAutoNickChange(true) .setCapEnabled(true) .addListener(IRCChannelJoinListener(whitelistValidator)) .addListener(IRCChannelQuitListener()) .addListener(IRCConnectListener()) .addListener(IRCMessageListener(plugin)) .addListener(IRCUserListListener(whitelistValidator)) .addListener(IRCRegisterCommand(plugin)) .addListener(IRCVerifyCommand(plugin)) .addListener(IRCListCommand(plugin)) .setAutoReconnect(true) if (plugin.config.get("irc.name") != null) { val name = plugin.config.getString("irc.name") configuration.name = name } if (plugin.config.get("irc.real-name") != null) { val realName = plugin.config.getString("irc.real-name") configuration.realName = realName } if (plugin.config.get("irc.login") != null) { val login = plugin.config.getString("irc.login") configuration.login = login } if (plugin.config.get("irc.cap-enabled") != null) { val capEnabled = plugin.config.getBoolean("irc.cap-enabled") configuration.isCapEnabled = capEnabled } if (plugin.config.get("irc.auto-nick-change-enabled") != null) { val autoNickChange = plugin.config.getBoolean("irc.auto-nick-change-enabled") configuration.isAutoNickChange = autoNickChange } if (plugin.config.get("irc.auto-split-message-enabled") != null) { val autoSplitMessage = plugin.config.getBoolean("irc.auto-split-message-enabled") configuration.isAutoSplitMessage = autoSplitMessage } if (plugin.config.getString("irc.server")?.contains(":") == true) { val serverAddress = plugin.config.getString("irc.server")?.split(":")?.get(0) val serverPort = plugin.config.getString("irc.server")?.split(":")?.get(1)?.toIntOrNull() if (serverAddress != null && serverPort != null) { configuration.addServer( serverAddress, serverPort ) } } else { val serverAddress = plugin.config.getString("irc.server") if (serverAddress != null) { configuration.addServer(serverAddress) } } if (plugin.config.get("irc.max-line-length") != null) { val maxLineLength = plugin.config.getInt("irc.max-line-length") configuration.maxLineLength = maxLineLength } if (plugin.config.get("irc.message-delay") != null) { val messageDelay = plugin.config.getLong("irc.message-delay") configuration.messageDelay = StaticDelay(messageDelay) } if (plugin.config.get("irc.password") != null) { val password = plugin.config.getString("irc.password") configuration.nickservPassword = password } ircBot = PircBotX(configuration.buildConfiguration()) connect() } override val isConnected: Boolean get() = ircBot.isConnected override val nick: RPKIRCNick get() = RPKIRCNick(ircBot.nick) override fun sendMessage(channel: IRCChannel, message: String): CompletableFuture<Void> { return CompletableFuture.runAsync { ircBot.sendIRC().message(channel.name, message) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to send IRC message", exception) throw exception } } override fun sendMessage(user: RPKIRCProfile, message: String): CompletableFuture<Void> { return sendMessage(user.nick, message) } override fun sendMessage(nick: RPKIRCNick, message: String): CompletableFuture<Void> { return CompletableFuture.runAsync { ircBot.sendIRC().message(nick.value, message) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to send IRC message", exception) throw exception } } override fun isOnline(nick: RPKIRCNick): Boolean { return onlineUsers.contains(nick.value) } override fun setOnline(nick: RPKIRCNick, isOnline: Boolean) { if (isOnline) { if (!onlineUsers.contains(nick.value)) { onlineUsers.add(nick.value) } } else { if (onlineUsers.contains(nick.value)) { onlineUsers.remove(nick.value) } } } override fun joinChannel(ircChannel: IRCChannel) { ircBot.sendIRC().joinChannel(ircChannel.name) } override fun connect() { if (ircBotThread == null) { ircBotThread = thread(name = "RPKit Chat IRC Bot") { ircBot.startBot() } } } override fun disconnect() { ircBot.stopBotReconnect() ircBot.sendIRC()?.quitServer(plugin.messages["irc-quit"]) if (ircBot.isConnected) { ircBot.close() } ircBotThread?.join() } }
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/irc/RPKIRCServiceImpl.kt
1562088910
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.discord import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.players.bukkit.profile.RPKProfileId import com.rpkit.players.bukkit.profile.RPKProfileService import com.rpkit.players.bukkit.profile.discord.DiscordUserId import com.rpkit.players.bukkit.profile.discord.RPKDiscordProfile import net.dv8tion.jda.api.entities.Emoji import net.dv8tion.jda.api.interactions.components.ActionRow import net.dv8tion.jda.api.interactions.components.buttons.Button import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle import java.util.concurrent.CompletableFuture class RPKDiscordServiceImpl(override val plugin: RPKChatBukkit) : RPKDiscordService { private val serverName = plugin.config.getString("discord.server-name") val discordServer = if (serverName != null) DiscordServer(plugin, serverName) else null private val profileLinkMessages = mutableMapOf<Long, Int>() override fun sendMessage(channel: DiscordChannel, message: String, callback: DiscordMessageCallback?) { discordServer?.sendMessage(channel, message) } override fun sendMessage( profile: RPKDiscordProfile, message: String, callback: DiscordMessageCallback? ) { discordServer?.getUser(profile.discordId)?.openPrivateChannel()?.queue { channel -> channel.sendMessage(message).queue { callback?.invoke(DiscordMessageImpl(it)) } } } override fun sendMessage( profile: RPKDiscordProfile, message: String, vararg buttons: DiscordButton ) { discordServer ?.getUser(profile.discordId) ?.openPrivateChannel()?.queue { channel -> channel.sendMessage(message).setActionRows(ActionRow.of(buttons.map { button -> val style = when (button.variant) { DiscordButton.Variant.PRIMARY -> ButtonStyle.PRIMARY DiscordButton.Variant.SUCCESS -> ButtonStyle.SUCCESS DiscordButton.Variant.SECONDARY -> ButtonStyle.SECONDARY DiscordButton.Variant.DANGER -> ButtonStyle.DANGER DiscordButton.Variant.LINK -> ButtonStyle.LINK } discordServer.addButtonListener(button.id, button.onClick) when (button) { is DiscordTextButton -> Button.of(style, button.id, button.text) is DiscordEmojiButton -> Button.of(style, button.id, Emoji.fromUnicode(button.emoji)) } })).queue() } } override fun getUserName(discordId: DiscordUserId): String? { return discordServer?.getUser(discordId)?.name } override fun getUserId(discordUserName: String): DiscordUserId? { return discordServer?.getUser(discordUserName)?.idLong?.let(::DiscordUserId) } override fun setMessageAsProfileLinkRequest(messageId: Long, profile: RPKProfile) { val profileId = profile.id ?: return profileLinkMessages[messageId] = profileId.value } override fun setMessageAsProfileLinkRequest(message: DiscordMessage, profile: RPKProfile) { setMessageAsProfileLinkRequest(message.id, profile) } override fun getMessageProfileLink(messageId: Long): CompletableFuture<out RPKProfile?> { val profileService = Services[RPKProfileService::class.java] ?: return CompletableFuture.completedFuture(null) val profileId = profileLinkMessages[messageId] ?: return CompletableFuture.completedFuture(null) return profileService.getProfile(RPKProfileId(profileId)) } override fun getMessageProfileLink(message: DiscordMessage): CompletableFuture<out RPKProfile?> { return getMessageProfileLink(message.id) } override fun getDiscordChannel(name: String): DiscordChannel? { return discordServer?.getChannel(name) } override fun disconnect() { discordServer?.disconnect() } }
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/discord/RPKDiscordServiceImpl.kt
348848123
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.character.field import com.rpkit.characters.bukkit.character.RPKCharacter import java.util.concurrent.CompletableFuture /** * A character card field for dead. */ class DeadField : CharacterCardField { override val name = "dead" override fun get(character: RPKCharacter): CompletableFuture<String> { return CompletableFuture.completedFuture(character.isDead.toString()) } }
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/character/field/DeadField.kt
3426170223
package net.sarangnamu.common.permission import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 11. 23.. <p/> * * ```kotlin * context.mainRuntimePermission(arrayListOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), { res -> Log.e("PERMISSION", "res = $res") } * ``` * ```kotlin * context.runtimePermission(arrayListOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), { res -> Log.e("PERMISSION", "res = $res") } * ``` */ private val KEY_PERMISSION: String get() = "permission" private val KEY_PERMISSION_SHOW_DIALOG: String get() = "permission_show_dialog" //////////////////////////////////////////////////////////////////////////////////// // // PermissionActivity // //////////////////////////////////////////////////////////////////////////////////// class PermissionActivity : AppCompatActivity() { companion object { lateinit var listener: (Boolean) -> Unit var userDialog: AlertDialog? = null } var permissions: ArrayList<String>? = null var requestCode = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) permissions = intent.getStringArrayListExtra(KEY_PERMISSION) if (!intent.getBooleanExtra(KEY_PERMISSION_SHOW_DIALOG, false)) { requestCode = 0 } permissions?.let { checkPermission() } ?: finish() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { var grantRes = true for (result in grantResults) { if (result == PackageManager.PERMISSION_DENIED) { grantRes = false break } } listener(grantRes) if (!grantRes && requestCode == 1) { showDialog() } else { finish() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { listener(checkRuntimePermissions(permissions!!)) when (requestCode) { 1 -> showDialog() else -> finish() } } fun checkPermission() { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) { ActivityCompat.requestPermissions(this@PermissionActivity, permissions!!.toTypedArray(), requestCode) } } fun showDialog() { userDialog?.run { show() } ?: dialog() } fun dialog() { AlertDialog.Builder(this@PermissionActivity).apply { setTitle(R.string.permission_title) setMessage(R.string.permission_message) setCancelable(false) setPositiveButton(android.R.string.ok, { d, w -> d.dismiss() finish() }) setNegativeButton(R.string.permission_setting, { d, w -> startActivityForResult(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply { setData(Uri.parse("package:$packageName")) }, 0) d.dismiss() finish() }) }.show() } } //////////////////////////////////////////////////////////////////////////////////// // // METHODS // //////////////////////////////////////////////////////////////////////////////////// fun Context.mainRuntimePermission(permissions: ArrayList<String>, listener: (Boolean) -> Unit) { runtimePermissions(false, permissions, listener) } fun Context.runtimePermission(permissions: ArrayList<String>, listener: (Boolean) -> Unit) { runtimePermissions(true, permissions, listener) } private fun Context.runtimePermissions(showDialog: Boolean, permissions: ArrayList<String>, listener: (Boolean) -> Unit) { if (!checkRuntimePermissions(permissions)) { PermissionActivity.listener = listener startActivity(Intent(this, PermissionActivity::class.java).apply { putStringArrayListExtra(KEY_PERMISSION, permissions) putExtra(KEY_PERMISSION_SHOW_DIALOG, showDialog) }) } else { listener(true) } } private fun Context.checkRuntimePermissions(permissions: ArrayList<String>): Boolean { var result = true if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) { for (permission in permissions) { if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { result = false break; } } } return result }
library/src/main/java/net/sarangnamu/common/permission/BkPermission.kt
2657652659
package com.incentive.yellowpages.ui.main import android.app.SearchManager import android.app.SharedElementCallback import android.content.Intent import android.graphics.Typeface import android.os.Bundle import android.text.InputType import android.text.SpannableStringBuilder import android.text.Spanned import android.text.TextUtils import android.text.style.StyleSpan import android.transition.AutoTransition import android.view.View import android.view.inputmethod.EditorInfo import com.incentive.yellowpages.R import com.incentive.yellowpages.data.DataManager import com.incentive.yellowpages.data.model.SearchResponse import com.incentive.yellowpages.data.remote.ApiContract import com.incentive.yellowpages.injection.ConfigPersistent import com.incentive.yellowpages.misc.LoadMoreListener import com.incentive.yellowpages.misc.isConnected import com.incentive.yellowpages.ui.base.BaseApplication.Companion.context import com.incentive.yellowpages.ui.base.BaseContract import com.incentive.yellowpages.ui.detail.DetailPresenter import com.incentive.yellowpages.utils.LogUtils import rx.functions.Action1 import java.util.* import javax.inject.Inject @ConfigPersistent class MainPresenter @Inject constructor(val dataManager: DataManager) : BaseContract.BasePresenter<MainView>() { companion object { val IME_OPTIONS = EditorInfo.IME_ACTION_SEARCH or EditorInfo.IME_FLAG_NO_EXTRACT_UI or EditorInfo.IME_FLAG_NO_FULLSCREEN /** * The number of items remaining before more info should be loaded */ private val THRESHOLD_LOAD_MORE = 10 } private var searchedPageIndex = ApiContract.SearchApi.INITIAL_SEARCH_PAGE - 1 private var isDataLoading = false private var hasNextPage = true private var adapter: MainAdapter? = null private val transition = AutoTransition() private val loadMoreListener = object : LoadMoreListener { override fun isDataLoading(): Boolean { return isDataLoading } } private var reenterBundle: Bundle? = null /** * If [clearResults] has been called recently and no other changes have * been made, there's no point to perform that operation again. */ private var cleanedRecently: Boolean = false private var previousQuery: String? = null override fun create(view: MainView, savedInstanceState: Bundle?, intent: Intent?, arguments: Bundle?, isPortrait: Boolean) { super.create(view, savedInstanceState, intent, arguments, isPortrait) if (null == adapter) { adapter = MainAdapter(loadMoreListener, if (view is MainAdapter.ISearchItemClicked) view else throw IllegalArgumentException("MainContract.View does not implement " + "MainAdapter.ISearchItemClicked")) } else this.view?.showResults(true) this.view?.apply { setupSearchView(context.getString(R.string.hint_search), InputType.TYPE_TEXT_FLAG_CAP_WORDS, IME_OPTIONS, Action1 { val currentQuery = it.queryText().toString() if (it.isSubmitted) { if (!TextUtils.isEmpty(currentQuery) && !Objects.equals(previousQuery, currentQuery)) { cleanedRecently = false previousQuery = currentQuery clearResults() performSearch() } else if (!cleanedRecently) clearResults() clearSearchViewFocus() hideKeyboard() } else if (!cleanedRecently || TextUtils.isEmpty(currentQuery)) { previousQuery = "" clearResults() } }) focusSearchView() hideKeyboard() setupRecyclerView(adapter!!, loadMoreListener, THRESHOLD_LOAD_MORE) } } override fun activityReenter(resultCode: Int, data: Intent?) { if (null != data) { reenterBundle = Bundle(data.extras) view?.apply { postponeTransition() layoutRecyclerScrollIfNeededAndContinueTransition(reenterBundle!!. getInt(DetailPresenter.EXTRA_SEARCH_ITEM_POSITION)) } } } fun onDataSuccess(searchResponse: SearchResponse?) { isDataLoading = false view?.showProgress(false) if (null != searchResponse) { val data = searchResponse.searchItems hasNextPage = searchResponse.hasNext if (!data.isEmpty()) { ++searchedPageIndex view?.apply { if (adapter!!.isEmpty) { beginTransition(transition) showResults(true) adapter!!.data = data } else adapter!!.addData(data) adapter!!.notifyDataSetChanged() } } else { view?.apply { showNoResultText(View.OnClickListener { setSearchViewQuery("", false) focusSearchView() showKeyboard() }, constructNoInternetString()) } adapter!!.data = data adapter!!.notifyDataSetChanged() } } } fun onDataFailure(e: Throwable) { isDataLoading = false clearResults() if (!context.isConnected()) view?.showNoInternetMessage(true) LogUtils.e(e.message as String) } fun performSearch(showProgressBar: Boolean = true) { val isConnected: Boolean = context.isConnected() val query = view?.getQuery() if (isConnected && hasNextPage && !TextUtils.isEmpty(query)) { view?.apply { // if we are currently performing a search - unsubscribe from it if (isDataLoading) unsubscribe() isDataLoading = true addDisposable(dataManager.search(searchedPageIndex + 1, getQuery()) .subscribe({ onDataSuccess(it) }, { onDataFailure(it) })) showProgress(showProgressBar) } } else if (!isConnected) view?.showNoInternetMessage(true) } fun onBackPressed(): Boolean { if (isDataLoading) unsubscribe() else if (adapter!!.isEmpty) return false clearResults() view?.apply { setSearchViewQuery("", false) focusSearchView() showKeyboard() } return true } fun clearResults() { cleanedRecently = true searchedPageIndex = ApiContract.SearchApi.INITIAL_SEARCH_PAGE - 1 hasNextPage = true val size = adapter!!.data.size adapter!!.clear() adapter!!.notifyItemRangeRemoved(0, size) previousQuery = "" view?.apply { beginTransition(transition) showResults(false) showProgress(false) hideNoResultText() } } fun newIntent(intent: Intent) { if (intent.hasExtra(SearchManager.QUERY)) { val query = intent.getStringExtra(SearchManager.QUERY) if (!TextUtils.isEmpty(query)) { view?.apply { setSearchViewQuery(query, false) clearResults() performSearch() } } } } fun dispatchItemClicked(logo: View, searchItem: SearchResponse.SearchItem, position: Int) { view?.apply { hideKeyboard() clearSearchViewFocus() launchListing(logo, searchItem, position) } } fun getSharedElementCallback(): SharedElementCallback { return object : SharedElementCallback() { override fun onMapSharedElements(names: MutableList<String>?, sharedElements: MutableMap<String, View>?) { if (null != reenterBundle && reenterBundle!!.containsKey(DetailPresenter.EXTRA_SEARCH_ITEM_POSITION) && null != view) { val newSharedElement = view!!.findViewByTag(reenterBundle!!. getInt(DetailPresenter.EXTRA_SEARCH_ITEM_POSITION)) val newTransitionName = context.getString(R.string.transition_logo) names?.clear() names?.add(newTransitionName) sharedElements?.clear() sharedElements?.put(newTransitionName, newSharedElement) reenterBundle = null } else { // The activity is exiting } } } } override fun destroy(isFinishing: Boolean) { if (isFinishing) unsubscribe() } private fun constructNoInternetString(): SpannableStringBuilder { view?.apply { val message = String.format(context.getString(R.string.message_no_search_results), getQuery()) val ssb = SpannableStringBuilder(message) ssb.setSpan(StyleSpan(Typeface.ITALIC), message.indexOf('“') + 1, message.length - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return ssb } return SpannableStringBuilder() } }
app/src/main/kotlin/com/incentive/yellowpages/ui/main/MainPresenter.kt
1431543262
package com.beust.kobalt import java.util.* /** * Make Kobalt's output awesome and unique. * * I spend so much time staring at build outputs I decided I might as well make them pretty. * Note that I also experimented with colors but it's hard to come up with a color scheme that * will work with all the various backgrounds developers use, so I decided to be conservative * and stick to simple red/yellow for errors and warnings. * * @author Cedric Beust <[email protected]> * @since 10/1/2015 */ class AsciiArt { companion object { private val BANNERS = arrayOf( " __ __ __ __ __ \n" + " / //_/ ____ / /_ ____ _ / / / /_\n" + " / ,< / __ \\ / __ \\ / __ `/ / / / __/\n" + " / /| | / /_/ / / /_/ // /_/ / / / / /_ \n" + " /_/ |_| \\____/ /_.___/ \\__,_/ /_/ \\__/ ", " _ __ _ _ _ \n" + " | |/ / ___ | |__ __ _ | | | |_ \n" + " | ' / / _ \\ | '_ \\ / _` | | | | __|\n" + " | . \\ | (_) | | |_) | | (_| | | | | |_ \n" + " |_|\\_\\ \\___/ |_.__/ \\__,_| |_| \\__| " ) val banner : String get() = BANNERS[Random().nextInt(BANNERS.size)] // fun box(s: String) : List<String> = box(listOf(s)) val horizontalSingleLine = "\u2500\u2500\u2500\u2500\u2500" val horizontalDoubleLine = "\u2550\u2550\u2550\u2550\u2550" val verticalBar = "\u2551" // fun horizontalLine(n: Int) = StringBuffer().apply { // repeat(n, { append("\u2500") }) // }.toString() // Repeat fun r(n: Int, w: String) : String { with(StringBuffer()) { repeat(n, { append(w) }) return toString() } } val h = "\u2550" val ul = "\u2554" val ur = "\u2557" val bottomLeft = "\u255a" val bottomRight = "\u255d" // Bottom left with continuation val bottomLeft2 = "\u2560" // Bottom right with continuation val bottomRight2 = "\u2563" fun upperBox(max: Int) = ul + r(max + 2, h) + ur fun lowerBox(max: Int, bl: String = bottomLeft, br : String = bottomRight) = bl + r(max + 2, h) + br private fun box(strings: List<String>, bl: String = bottomLeft, br: String = bottomRight) : List<String> { val v = verticalBar val maxString: String = strings.maxBy { it.length } ?: "" val max = maxString.length val result = arrayListOf(upperBox(max)) result.addAll(strings.map { "$v ${center(it, max - 2)} $v" }) result.add(lowerBox(max, bl, br)) return result } fun logBox(strings: List<String>, bl: String = bottomLeft, br: String = bottomRight, indent: Int = 0): String { return buildString { val boxLines = box(strings, bl, br) boxLines.withIndex().forEach { iv -> append(fill(indent)).append(iv.value) if (iv.index < boxLines.size - 1) append("\n") } } } fun logBox(s: String, bl: String = bottomLeft, br: String = bottomRight, indent: Int = 0) = logBox(listOf(s), bl, br, indent) fun fill(n: Int) = buildString { repeat(n, { append(" ")})}.toString() fun center(s: String, width: Int) : String { val diff = width - s.length val spaces = diff / 2 + 1 return fill(spaces) + s + fill(spaces + if (diff % 2 == 1) 1 else 0) } const val RESET = "\u001B[0m" const val BLACK = "\u001B[30m" const val RED = "\u001B[31m" const val GREEN = "\u001B[32m" const val YELLOW = "\u001B[33m"; const val BLUE = "\u001B[34m" const val PURPLE = "\u001B[35m" const val CYAN = "\u001B[36m" const val WHITE = "\u001B[37m" fun wrap(s: CharSequence, color: String) = color + s + RESET private fun blue(s: CharSequence) = wrap(s, BLUE) private fun red(s: CharSequence) = wrap(s, RED) private fun yellow(s: CharSequence) = wrap(s, YELLOW) fun taskColor(s: CharSequence) = s fun errorColor(s: CharSequence) = red(s) fun warnColor(s: CharSequence) = red(s) } } class AsciiTable { class Builder { private val headers = arrayListOf<String>() fun header(name: String) = headers.add(name) fun headers(vararg names: String) = headers.addAll(names) private val widths = arrayListOf<Int>() fun columnWidth(w: Int) : Builder { widths.add(w) return this } private val rows = arrayListOf<List<String>>() fun addRow(row: List<String>) = rows.add(row) private fun col(width: Int, s: String) : String { val format = " %1\$-${width.toString()}s" val result = String.format(format, s) return result } val vb = AsciiArt.verticalBar fun build() : String { val formattedHeaders = headers.mapIndexed { index, s -> val s2 = col(widths[index], s) s2 }.joinToString(vb) val result = StringBuffer().apply { append(AsciiArt.logBox(formattedHeaders, AsciiArt.bottomLeft2, AsciiArt.bottomRight2)) append("\n") } var lineLength = 0 rows.forEachIndexed { _, row -> val formattedRow = row.mapIndexed { i, s -> col(widths[i], s) }.joinToString(vb) val line = "$vb $formattedRow $vb" result.append(line).append("\n") lineLength = line.length } result.append(AsciiArt.lowerBox(lineLength - 4)) return result.toString() } } }
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/AsciiArt.kt
1259506630
package com.github.paolorotolo.appintro.internal import org.junit.Assert.assertEquals import org.junit.Test class LogHelperTest { @Test fun testMakeLogTag_withJavaClass() { val logTag = LogHelper.makeLogTag(Object::class.java) assertEquals("Log: Object", logTag) } @Test fun testMakeLogTag_withKClass() { val logTag = LogHelper.makeLogTag(KotlinVersion::class) assertEquals("Log: KotlinVersion", logTag) } @Test fun testMakeLogTag_withLongName_nameIsCropped() { val logTag = LogHelper.makeLogTag(KotlinReflectionNotSupportedError::class.java) assertEquals("Log: KotlinReflectionN", logTag) } }
appintro/src/test/java/com/github/paolorotolo/internal/LogHelperTest.kt
153673548
package br.com.wakim.eslpodclient.util.extensions import br.com.wakim.eslpodclient.Application import br.com.wakim.eslpodclient.android.receiver.ConnectivityException import rx.Observable import rx.Single import rx.SingleSubscriber import rx.Subscriber import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers fun <T> Observable<T>.ofIOToMainThread(): Observable<T> = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) fun <T> Single<T>.ofIOToMainThread(): Single<T> = subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) fun <T> Single<T>.ofComputationToMainThread(): Single<T> = subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()) fun <T> Observable<T>.ofComputationToMainThread(): Observable<T> = subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()) fun <T> Single<T>.connected(): Single<T> { return Single.defer { -> if (Application.INSTANCE?.connected ?: false) { return@defer this } return@defer Single.error<T>(ConnectivityException.INSTANCE) } } fun <T> Observable<T>.connected(): Observable<T> { return Observable.defer { -> if (Application.INSTANCE?.connected ?: false) { return@defer this } return@defer Observable.error<T>(ConnectivityException.INSTANCE) } } fun <T> SingleSubscriber<T>.onSuccessIfSubscribed(t: T) { if (!isUnsubscribed) { onSuccess(t) } } fun <T> Subscriber<T>.onNextIfSubscribed(t: T) { if (!isUnsubscribed) { onNext(t) } }
app/src/main/java/br/com/wakim/eslpodclient/util/extensions/RxExtensions.kt
1696667766
package jp.shiguredo.sora.sdk.channel.option import java.util.Locale /** * チャネルの役割を示します. */ enum class SoraChannelRole { /** 送信のみ */ SENDONLY, /** 受信のみ */ RECVONLY, /** 送受信 */ SENDRECV; internal val signaling: String get() = this.toString().toLowerCase(Locale.getDefault()) }
sora-android-sdk/src/main/kotlin/jp/shiguredo/sora/sdk/channel/option/SoraChannelRole.kt
2016257506
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.vanilla.images.base.GabrielaImageServerCommandBase class RipTvCommand(m: LorittaBot) : GabrielaImageServerCommandBase( m, listOf("riptv"), 1, "commands.command.riptv.description", "/api/v1/images/rip-tv", "rip_tv.png", slashCommandName = "riptv" )
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/RipTvCommand.kt
2358488634
package com.etesync.syncadapter.ui.etebase import android.content.Context import android.os.Bundle import android.provider.CalendarContract import android.provider.ContactsContract import android.text.format.DateFormat import android.text.format.DateUtils import android.view.* import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import androidx.fragment.app.activityViewModels import androidx.viewpager.widget.ViewPager import at.bitfire.ical4android.Event import at.bitfire.ical4android.InvalidCalendarException import at.bitfire.ical4android.Task import at.bitfire.ical4android.TaskProvider import at.bitfire.vcard4android.Contact import com.etesync.syncadapter.CachedCollection import com.etesync.syncadapter.CachedItem import com.etesync.syncadapter.Constants import com.etesync.syncadapter.R import com.etesync.syncadapter.resource.* import com.etesync.syncadapter.ui.BaseActivity import com.etesync.syncadapter.utils.EventEmailInvitation import com.etesync.syncadapter.utils.TaskProviderHandling import com.google.android.material.tabs.TabLayout import ezvcard.util.PartialDate import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import java.io.IOException import java.io.StringReader import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.Future class CollectionItemFragment : Fragment() { private val model: AccountViewModel by activityViewModels() private val collectionModel: CollectionViewModel by activityViewModels() private lateinit var cachedItem: CachedItem private var emailInvitationEvent: Event? = null private var emailInvitationEventString: String? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val ret = inflater.inflate(R.layout.journal_item_activity, container, false) setHasOptionsMenu(true) if (savedInstanceState == null) { collectionModel.observe(this) { (activity as? BaseActivity?)?.supportActionBar?.title = it.meta.name if (container != null) { initUi(inflater, ret, it) } } } return ret } private fun initUi(inflater: LayoutInflater, v: View, cachedCollection: CachedCollection) { val viewPager = v.findViewById<ViewPager>(R.id.viewpager) viewPager.adapter = TabsAdapter(childFragmentManager, this, requireContext(), cachedCollection, cachedItem) val tabLayout = v.findViewById<TabLayout>(R.id.tabs) tabLayout.setupWithViewPager(viewPager) v.findViewById<View>(R.id.journal_list_item).visibility = View.GONE } fun allowSendEmail(event: Event?, icsContent: String) { emailInvitationEvent = event emailInvitationEventString = icsContent activity?.invalidateOptionsMenu() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.collection_item_fragment, menu) menu.setGroupVisible(R.id.journal_item_menu_event_invite, emailInvitationEvent != null) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val accountHolder = model.value!! when (item.itemId) { R.id.on_send_event_invite -> { val account = accountHolder.account val intent = EventEmailInvitation(requireContext(), account).createIntent(emailInvitationEvent!!, emailInvitationEventString!!) startActivity(intent) } R.id.on_restore_item -> { restoreItem(accountHolder) } } return super.onOptionsItemSelected(item) } fun restoreItem(accountHolder: AccountHolder) { // FIXME: This code makes the assumption that providers are all available. May not be true for tasks, and potentially others too. val context = requireContext() val account = accountHolder.account val cachedCol = collectionModel.value!! when (cachedCol.collectionType) { Constants.ETEBASE_TYPE_CALENDAR -> { val provider = context.contentResolver.acquireContentProviderClient(CalendarContract.CONTENT_URI)!! val localCalendar = LocalCalendar.findByName(account, provider, LocalCalendar.Factory, cachedCol.col.uid)!! val event = Event.eventsFromReader(StringReader(cachedItem.content))[0] var localEvent = localCalendar.findByUid(event.uid!!) if (localEvent != null) { localEvent.updateAsDirty(event) } else { localEvent = LocalEvent(localCalendar, event, event.uid, null) localEvent.addAsDirty() } } Constants.ETEBASE_TYPE_TASKS -> { TaskProviderHandling.getWantedTaskSyncProvider(context)?.let { val provider = TaskProvider.acquire(context, it)!! val localTaskList = LocalTaskList.findByName(account, provider, LocalTaskList.Factory, cachedCol.col.uid)!! val task = Task.tasksFromReader(StringReader(cachedItem.content))[0] var localTask = localTaskList.findByUid(task.uid!!) if (localTask != null) { localTask.updateAsDirty(task) } else { localTask = LocalTask(localTaskList, task, task.uid, null) localTask.addAsDirty() } } } Constants.ETEBASE_TYPE_ADDRESS_BOOK -> { val provider = context.contentResolver.acquireContentProviderClient(ContactsContract.RawContacts.CONTENT_URI)!! val localAddressBook = LocalAddressBook.findByUid(context, provider, account, cachedCol.col.uid)!! val contact = Contact.fromReader(StringReader(cachedItem.content), null)[0] if (contact.group) { // FIXME: not currently supported } else { var localContact = localAddressBook.findByUid(contact.uid!!) as LocalContact? if (localContact != null) { localContact.updateAsDirty(contact) } else { localContact = LocalContact(localAddressBook, contact, contact.uid, null) localContact.createAsDirty() } } } } val dialog = AlertDialog.Builder(context) .setTitle(R.string.journal_item_restore_action) .setIcon(R.drawable.ic_restore_black) .setMessage(R.string.journal_item_restore_dialog_body) .setPositiveButton(android.R.string.ok) { dialog, which -> // dismiss } .create() dialog.show() } companion object { fun newInstance(cachedItem: CachedItem): CollectionItemFragment { val ret = CollectionItemFragment() ret.cachedItem = cachedItem return ret } } } private class TabsAdapter(fm: FragmentManager, private val mainFragment: CollectionItemFragment, private val context: Context, private val cachedCollection: CachedCollection, private val cachedItem: CachedItem) : FragmentPagerAdapter(fm) { override fun getCount(): Int { // FIXME: Make it depend on info enumType (only have non-raw for known types) return 3 } override fun getPageTitle(position: Int): CharSequence? { return if (position == 0) { context.getString(R.string.journal_item_tab_main) } else if (position == 1) { context.getString(R.string.journal_item_tab_raw) } else { context.getString(R.string.journal_item_tab_revisions) } } override fun getItem(position: Int): Fragment { return if (position == 0) { PrettyFragment.newInstance(mainFragment, cachedCollection, cachedItem.content) } else if (position == 1) { TextFragment.newInstance(cachedItem.content) } else { ItemRevisionsListFragment.newInstance(cachedCollection, cachedItem) } } } class TextFragment : Fragment() { private lateinit var content: String override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val v = inflater.inflate(R.layout.text_fragment, container, false) val tv = v.findViewById<View>(R.id.content) as TextView tv.text = content return v } companion object { fun newInstance(content: String): TextFragment { val ret = TextFragment() ret.content = content return ret } } } class PrettyFragment : Fragment() { private var asyncTask: Future<Unit>? = null private lateinit var mainFragment: CollectionItemFragment private lateinit var cachedCollection: CachedCollection private lateinit var content: String override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { var v: View? = null when (cachedCollection.collectionType) { Constants.ETEBASE_TYPE_ADDRESS_BOOK -> { v = inflater.inflate(R.layout.contact_info, container, false) asyncTask = loadContactTask(v) } Constants.ETEBASE_TYPE_CALENDAR -> { v = inflater.inflate(R.layout.event_info, container, false) asyncTask = loadEventTask(v) } Constants.ETEBASE_TYPE_TASKS -> { v = inflater.inflate(R.layout.task_info, container, false) asyncTask = loadTaskTask(v) } } return v } override fun onDestroyView() { super.onDestroyView() if (asyncTask != null) asyncTask!!.cancel(true) } private fun loadEventTask(view: View): Future<Unit> { return doAsync { var event: Event? = null val inputReader = StringReader(content) try { event = Event.eventsFromReader(inputReader, null)[0] } catch (e: InvalidCalendarException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } if (event != null) { uiThread { val loader = view.findViewById<View>(R.id.event_info_loading_msg) loader.visibility = View.GONE val contentContainer = view.findViewById<View>(R.id.event_info_scroll_view) contentContainer.visibility = View.VISIBLE setTextViewText(view, R.id.title, event.summary) val dtStart = event.dtStart?.date?.time val dtEnd = event.dtEnd?.date?.time if ((dtStart == null) || (dtEnd == null)) { setTextViewText(view, R.id.when_datetime, getString(R.string.loading_error_title)) } else { setTextViewText(view, R.id.when_datetime, getDisplayedDatetime(dtStart, dtEnd, event.isAllDay(), context)) } setTextViewText(view, R.id.where, event.location) val organizer = event.organizer if (organizer != null) { val tv = view.findViewById<View>(R.id.organizer) as TextView tv.text = organizer.calAddress.toString().replaceFirst("mailto:".toRegex(), "") } else { val organizerView = view.findViewById<View>(R.id.organizer_container) organizerView.visibility = View.GONE } setTextViewText(view, R.id.description, event.description) var first = true var sb = StringBuilder() for (attendee in event.attendees) { if (first) { first = false sb.append(getString(R.string.journal_item_attendees)).append(": ") } else { sb.append(", ") } sb.append(attendee.calAddress.toString().replaceFirst("mailto:".toRegex(), "")) } setTextViewText(view, R.id.attendees, sb.toString()) first = true sb = StringBuilder() for (alarm in event.alarms) { if (first) { first = false sb.append(getString(R.string.journal_item_reminders)).append(": ") } else { sb.append(", ") } sb.append(alarm.trigger.value) } setTextViewText(view, R.id.reminders, sb.toString()) if (event.attendees.isNotEmpty()) { mainFragment.allowSendEmail(event, content) } } } } } private fun loadTaskTask(view: View): Future<Unit> { return doAsync { var task: Task? = null val inputReader = StringReader(content) try { task = Task.tasksFromReader(inputReader)[0] } catch (e: InvalidCalendarException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } if (task != null) { uiThread { val loader = view.findViewById<View>(R.id.task_info_loading_msg) loader.visibility = View.GONE val contentContainer = view.findViewById<View>(R.id.task_info_scroll_view) contentContainer.visibility = View.VISIBLE setTextViewText(view, R.id.title, task.summary) setTextViewText(view, R.id.where, task.location) val organizer = task.organizer if (organizer != null) { val tv = view.findViewById<View>(R.id.organizer) as TextView tv.text = organizer.calAddress.toString().replaceFirst("mailto:".toRegex(), "") } else { val organizerView = view.findViewById<View>(R.id.organizer_container) organizerView.visibility = View.GONE } setTextViewText(view, R.id.description, task.description) } } } } private fun loadContactTask(view: View): Future<Unit> { return doAsync { var contact: Contact? = null val reader = StringReader(content) try { contact = Contact.fromReader(reader, null)[0] } catch (e: IOException) { e.printStackTrace() } if (contact != null) { uiThread { val loader = view.findViewById<View>(R.id.loading_msg) loader.visibility = View.GONE val contentContainer = view.findViewById<View>(R.id.content_container) contentContainer.visibility = View.VISIBLE val tv = view.findViewById<View>(R.id.display_name) as TextView tv.text = contact.displayName if (contact.group) { showGroup(contact) } else { showContact(contact) } } } } } private fun showGroup(contact: Contact) { val view = requireView() val mainCard = view.findViewById<View>(R.id.main_card) as ViewGroup addInfoItem(view.context, mainCard, getString(R.string.journal_item_member_count), null, contact.members.size.toString()) for (member in contact.members) { addInfoItem(view.context, mainCard, getString(R.string.journal_item_member), null, member) } } private fun showContact(contact: Contact) { val view = requireView() val mainCard = view.findViewById<View>(R.id.main_card) as ViewGroup val aboutCard = view.findViewById<View>(R.id.about_card) as ViewGroup aboutCard.findViewById<View>(R.id.title_container).visibility = View.VISIBLE // TEL for (labeledPhone in contact.phoneNumbers) { val types = labeledPhone.property.types val type = if (types.size > 0) types[0].value else null addInfoItem(view.context, mainCard, getString(R.string.journal_item_phone), type, labeledPhone.property.text) } // EMAIL for (labeledEmail in contact.emails) { val types = labeledEmail.property.types val type = if (types.size > 0) types[0].value else null addInfoItem(view.context, mainCard, getString(R.string.journal_item_email), type, labeledEmail.property.value) } // ORG, TITLE, ROLE if (contact.organization != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_organization), contact.jobTitle, contact.organization?.values!![0]) } if (contact.jobDescription != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_job_description), null, contact.jobTitle) } // IMPP for (labeledImpp in contact.impps) { addInfoItem(view.context, mainCard, getString(R.string.journal_item_impp), labeledImpp.property.protocol, labeledImpp.property.handle) } // NICKNAME if (contact.nickName != null && !contact.nickName?.values?.isEmpty()!!) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_nickname), null, contact.nickName?.values!![0]) } // ADR for (labeledAddress in contact.addresses) { val types = labeledAddress.property.types val type = if (types.size > 0) types[0].value else null addInfoItem(view.context, mainCard, getString(R.string.journal_item_address), type, labeledAddress.property.label) } // NOTE if (contact.note != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_note), null, contact.note) } // URL for (labeledUrl in contact.urls) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_website), null, labeledUrl.property.value) } // ANNIVERSARY if (contact.anniversary != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_anniversary), null, getDisplayedDate(contact.anniversary?.date, contact.anniversary?.partialDate)) } // BDAY if (contact.birthDay != null) { addInfoItem(view.context, aboutCard, getString(R.string.journal_item_birthday), null, getDisplayedDate(contact.birthDay?.date, contact.birthDay?.partialDate)) } // RELATED for (related in contact.relations) { val types = related.types val type = if (types.size > 0) types[0].value else null addInfoItem(view.context, aboutCard, getString(R.string.journal_item_relation), type, related.text) } // PHOTO // if (contact.photo != null) } private fun getDisplayedDate(date: Date?, partialDate: PartialDate?): String? { if (date != null) { val epochDate = date.time return getDisplayedDatetime(epochDate, epochDate, true, context) } else if (partialDate != null){ val formatter = SimpleDateFormat("d MMMM", Locale.getDefault()) val calendar = GregorianCalendar() calendar.set(Calendar.DAY_OF_MONTH, partialDate.date!!) calendar.set(Calendar.MONTH, partialDate.month!! - 1) return formatter.format(calendar.time) } return null } companion object { fun newInstance(mainFragment: CollectionItemFragment, cachedCollection: CachedCollection, content: String): PrettyFragment { val ret = PrettyFragment() ret.mainFragment= mainFragment ret.cachedCollection = cachedCollection ret.content = content return ret } private fun addInfoItem(context: Context, parent: ViewGroup, type: String, label: String?, value: String?): View { val layout = parent.findViewById<View>(R.id.container) as ViewGroup val infoItem = LayoutInflater.from(context).inflate(R.layout.contact_info_item, layout, false) layout.addView(infoItem) setTextViewText(infoItem, R.id.type, type) setTextViewText(infoItem, R.id.title, label) setTextViewText(infoItem, R.id.content, value) parent.visibility = View.VISIBLE return infoItem } private fun setTextViewText(parent: View, id: Int, text: String?) { val tv = parent.findViewById<View>(id) as TextView if (text == null) { tv.visibility = View.GONE } else { tv.text = text } } fun getDisplayedDatetime(startMillis: Long, endMillis: Long, allDay: Boolean, context: Context?): String? { // Configure date/time formatting. val flagsDate = DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_WEEKDAY var flagsTime = DateUtils.FORMAT_SHOW_TIME if (DateFormat.is24HourFormat(context)) { flagsTime = flagsTime or DateUtils.FORMAT_24HOUR } val datetimeString: String if (allDay) { // For multi-day allday events or single-day all-day events that are not // today or tomorrow, use framework formatter. // We need to remove 24hrs because full day events are from the start of a day until the start of the next var adjustedEnd = endMillis - 24 * 60 * 60 * 1000; if (adjustedEnd < startMillis) { adjustedEnd = startMillis; } val f = Formatter(StringBuilder(50), Locale.getDefault()) datetimeString = DateUtils.formatDateRange(context, f, startMillis, adjustedEnd, flagsDate).toString() } else { // For multiday events, shorten day/month names. // Example format: "Fri Apr 6, 5:00pm - Sun, Apr 8, 6:00pm" val flagsDatetime = flagsDate or flagsTime or DateUtils.FORMAT_ABBREV_MONTH or DateUtils.FORMAT_ABBREV_WEEKDAY datetimeString = DateUtils.formatDateRange(context, startMillis, endMillis, flagsDatetime) } return datetimeString } } }
app/src/main/java/com/etesync/syncadapter/ui/etebase/CollectionItemFragment.kt
859444969
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.transactions.transactiontransformers import net.perfectdreams.i18nhelper.core.I18nContext import net.perfectdreams.loritta.common.utils.SparklyPowerLSXTransactionEntryAction import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.SonhosCommand import net.perfectdreams.loritta.cinnamon.pudding.data.CachedUserInfo import net.perfectdreams.loritta.cinnamon.pudding.data.SparklyPowerLSXSonhosTransaction import net.perfectdreams.loritta.cinnamon.pudding.data.UserId object SparklyPowerLSXSonhosTransactionTransformer : SonhosTransactionTransformer<SparklyPowerLSXSonhosTransaction> { override suspend fun transform( loritta: LorittaBot, i18nContext: I18nContext, cachedUserInfo: CachedUserInfo, cachedUserInfos: MutableMap<UserId, CachedUserInfo?>, transaction: SparklyPowerLSXSonhosTransaction ): suspend StringBuilder.() -> (Unit) = { when (transaction.action) { SparklyPowerLSXTransactionEntryAction.EXCHANGED_TO_SPARKLYPOWER -> { appendMoneyLostEmoji() append( i18nContext.get( SonhosCommand.TRANSACTIONS_I18N_PREFIX.Types.SparklyPowerLsx.ExchangedToSparklyPower( transaction.sonhos, transaction.playerName, transaction.sparklyPowerSonhos, "mc.sparklypower.net" ) ) ) } SparklyPowerLSXTransactionEntryAction.EXCHANGED_FROM_SPARKLYPOWER -> { appendMoneyEarnedEmoji() append( i18nContext.get( SonhosCommand.TRANSACTIONS_I18N_PREFIX.Types.SparklyPowerLsx.ExchangedFromSparklyPower( transaction.sparklyPowerSonhos, transaction.playerName, transaction.sonhos, "mc.sparklypower.net" ) ) ) } } } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/transactions/transactiontransformers/SparklyPowerLSXSonhosTransactionTransformer.kt
3079464237
package com.thunderclouddev.deeplink.ui import android.net.Uri import com.google.gson.* import java.lang.reflect.Type import javax.inject.Inject /** * Created by David Whitman on 01 Feb, 2017. */ interface JsonSerializer { fun toJson(obj: Any?): String fun <T> fromJson(jsonString: String?, clazz: Class<T>): T? } class GsonSerializer @Inject constructor() : JsonSerializer { private val gson = GsonBuilder() .registerTypeAdapter(Uri::class.java, UriGsonAdapter()).create() override fun toJson(obj: Any?): String = gson.toJson(obj) override fun <T> fromJson(jsonString: String?, clazz: Class<T>): T? { try { return gson.fromJson(jsonString, clazz) } catch (exception: Exception) { return null } } /** * [https://gist.github.com/logcat/3399e60132c1f2f9c261] */ private class UriGsonAdapter : com.google.gson.JsonSerializer<Uri>, JsonDeserializer<Uri> { @Throws(JsonParseException::class) override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): Uri { return Uri.parse(json.asString) } override fun serialize(src: Uri, typeOfSrc: Type, context: JsonSerializationContext): JsonElement { return JsonPrimitive(src.toString()) } } }
app/src/main/kotlin/com/thunderclouddev/deeplink/ui/JsonSerializer.kt
522139647
package minetime.model data class User(var email: String = "", var password: String = "")
src/main/kotlin/minetime/model/User.kt
2217000401
/* * ------------------------------------------------------------------------------ * ** Author: René de Groot * ** Copyright: (c) 2016 René de Groot All Rights Reserved. * **------------------------------------------------------------------------------ * ** No part of this file may be reproduced * ** or transmitted in any form or by any * ** means, electronic or mechanical, for the * ** purpose, without the express written * ** permission of the copyright holder. * *------------------------------------------------------------------------------ * * * * This file is part of "Open GPS Tracker - Exporter". * * * * "Open GPS Tracker - Exporter" is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * "Open GPS Tracker - Exporter" is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with "Open GPS Tracker - Exporter". If not, see <http://www.gnu.org/licenses/>. * * * */ package nl.renedegroot.android.opengpstracker.exporter.export import android.databinding.ObservableBoolean import android.databinding.ObservableInt import nl.renedegroot.android.opengpstracker.exporter.exporting.exporterManager /** * View model for the export preparation fragment */ class ExportModel : exporterManager.ProgressListener { val isDriveConnected = ObservableBoolean(false); val isTrackerConnected = ObservableBoolean(false); val isRunning = ObservableBoolean(false) val isFinished = ObservableBoolean(false) val completedTracks = ObservableInt(0) val totalTracks = ObservableInt(0) val totalWaypoints = ObservableInt(0) val completedWaypoints = ObservableInt(0) override fun updateExportProgress(isRunning: Boolean?, isFinished: Boolean?, completedTracks: Int?, totalTracks: Int?, completedWaypoints: Int?, totalWaypoints: Int?) { this.isRunning.set(isRunning ?: this.isRunning.get()) this.isFinished.set(isFinished ?: this.isFinished.get()) this.completedTracks.set(completedTracks ?: this.completedTracks.get()) this.totalTracks.set(totalTracks ?: this.totalTracks.get()) this.completedWaypoints.set(completedWaypoints ?: this.completedWaypoints.get()) this.totalWaypoints.set(totalWaypoints ?: this.totalWaypoints.get()) } }
studio/app/src/main/java/nl/renedegroot/android/opengpstracker/exporter/export/ExportModel.kt
4106303436
package com.rartworks.ChangeMe import com.badlogic.gdx.Game import com.badlogic.gdx.physics.box2d.Box2D import com.rartworks.engine.apis.MobileServices import com.rartworks.ChangeMe.screens.SplashScreen import com.rartworks.engine.rendering.Dimensions /** * The main class of the game. */ class GameCore(override val mobileServices: MobileServices?) : Game(), GameContext { override val dimensions = Dimensions(1280f, 720f) /** * Loads everything and sets the SplashScreen. */ override fun create() { Box2D.init() GamePreferences.initialize() AssetsLoader.load() this.setScreen(SplashScreen(this)) } /** * Disposes everything. */ override fun dispose() { super.dispose() AssetsLoader.dispose() } }
core/src/com/rartworks/ChangeMe/GameCore.kt
3833309169
package com.esafirm.imagepicker.helper import android.util.Log object IpLogger { private const val TAG = "ImagePicker" private var isEnable = true fun setEnable(enable: Boolean) { isEnable = enable } fun d(message: String?) { if (isEnable && message != null) { Log.d(TAG, message) } } fun e(message: String?) { if (isEnable && message != null) { Log.e(TAG, message) } } fun w(message: String?) { if (isEnable && message != null) { Log.w(TAG, message) } } }
imagepicker/src/main/java/com/esafirm/imagepicker/helper/IpLogger.kt
2256235483
data class Tuple108<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50, T51, T52, T53, T54, T55, T56, T57, T58, T59, T60, T61, T62, T63, T64, T65, T66, T67, T68, T69, T70, T71, T72, T73, T74, T75, T76, T77, T78, T79, T80, T81, T82, T83, T84, T85, T86, T87, T88, T89, T90, T91, T92, T93, T94, T95, T96, T97, T98, T99, T100, T101, T102, T103, T104, T105, T106, T107, T108>(val item1: T1, val item2: T2, val item3: T3, val item4: T4, val item5: T5, val item6: T6, val item7: T7, val item8: T8, val item9: T9, val item10: T10, val item11: T11, val item12: T12, val item13: T13, val item14: T14, val item15: T15, val item16: T16, val item17: T17, val item18: T18, val item19: T19, val item20: T20, val item21: T21, val item22: T22, val item23: T23, val item24: T24, val item25: T25, val item26: T26, val item27: T27, val item28: T28, val item29: T29, val item30: T30, val item31: T31, val item32: T32, val item33: T33, val item34: T34, val item35: T35, val item36: T36, val item37: T37, val item38: T38, val item39: T39, val item40: T40, val item41: T41, val item42: T42, val item43: T43, val item44: T44, val item45: T45, val item46: T46, val item47: T47, val item48: T48, val item49: T49, val item50: T50, val item51: T51, val item52: T52, val item53: T53, val item54: T54, val item55: T55, val item56: T56, val item57: T57, val item58: T58, val item59: T59, val item60: T60, val item61: T61, val item62: T62, val item63: T63, val item64: T64, val item65: T65, val item66: T66, val item67: T67, val item68: T68, val item69: T69, val item70: T70, val item71: T71, val item72: T72, val item73: T73, val item74: T74, val item75: T75, val item76: T76, val item77: T77, val item78: T78, val item79: T79, val item80: T80, val item81: T81, val item82: T82, val item83: T83, val item84: T84, val item85: T85, val item86: T86, val item87: T87, val item88: T88, val item89: T89, val item90: T90, val item91: T91, val item92: T92, val item93: T93, val item94: T94, val item95: T95, val item96: T96, val item97: T97, val item98: T98, val item99: T99, val item100: T100, val item101: T101, val item102: T102, val item103: T103, val item104: T104, val item105: T105, val item106: T106, val item107: T107, val item108: T108) { }
src/main/kotlin/com/github/kmizu/kollection/tuples/Tuple108.kt
952146450
package me.giacoppo.examples.kotlin.mvp.data.source.tmdb import io.reactivex.Observable import me.giacoppo.examples.kotlin.mvp.data.source.tmdb.model.TVResults import me.giacoppo.examples.kotlin.mvp.data.source.tmdb.model.TVShow import retrofit2.http.GET import retrofit2.http.Path /** * TMDB Api Interface * * @author Giuseppe Giacoppo */ interface TMDBDataSource { @GET("tv/popular") fun getPopularShows(): Observable<TVResults> @GET("tv/{tv_id}") fun getShow(@Path("tv_id") id: Int): Observable<TVShow> }
data/src/main/java/me/giacoppo/examples/kotlin/mvp/data/source/tmdb/TMDBDataSource.kt
2877605963
package net.pterodactylus.sone.core import com.google.inject.Guice.createInjector import net.pterodactylus.sone.test.bindMock import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.notNullValue import org.junit.Test /** * Unit test for [ElementLoader]. */ class ElementLoaderTest { @Test fun `default image loader can be loaded by guice`() { val injector = createInjector(bindMock<FreenetInterface>()) assertThat(injector.getInstance(ElementLoader::class.java), notNullValue()) } }
src/test/kotlin/net/pterodactylus/sone/core/ElementLoaderTest.kt
1481515360
package org.eyeseetea.malariacare.domain.usecase import org.eyeseetea.malariacare.domain.boundary.repositories.IProgramRepository import org.eyeseetea.malariacare.domain.entity.Program class GetProgramsUseCase(private val programRepository: IProgramRepository) { @Throws(Exception::class) fun execute(): List<Program> { return programRepository.getAll() } }
app/src/main/java/org/eyeseetea/malariacare/domain/usecase/GetProgramsUseCase.kt
1451927196
package reactivecircus.flowbinding.android.widget import android.widget.SearchView import androidx.annotation.CheckResult import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate import reactivecircus.flowbinding.common.InitialValueFlow import reactivecircus.flowbinding.common.asInitialValueFlow import reactivecircus.flowbinding.common.checkMainThread /** * Create a [InitialValueFlow] of query text changes on the [SearchView] instance * where the value emitted is latest query text. * * Note: Created flow keeps a strong reference to the [SearchView] instance * until the coroutine that launched the flow collector is cancelled. * * Example of usage: * * ``` * searchView.queryTextChanges() * .onEach { queryText -> * // handle queryText * } * .launchIn(uiScope) * ``` */ @CheckResult @OptIn(ExperimentalCoroutinesApi::class) public fun SearchView.queryTextChanges(): InitialValueFlow<CharSequence> = callbackFlow { checkMainThread() val listener = object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String): Boolean { trySend(newText) return true } override fun onQueryTextSubmit(query: String): Boolean = false } setOnQueryTextListener(listener) awaitClose { setOnQueryTextListener(null) } } .conflate() .asInitialValueFlow { query }
flowbinding-android/src/main/java/reactivecircus/flowbinding/android/widget/SearchViewQueryTextChangeFlow.kt
2376326926
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.activity import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner import okhttp3.mockwebserver.MockWebServer import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mozilla.focus.activity.robots.homeScreen import org.mozilla.focus.helpers.FeatureSettingsHelper import org.mozilla.focus.helpers.MainActivityFirstrunTestRule import org.mozilla.focus.helpers.MockWebServerHelper import org.mozilla.focus.helpers.TestHelper.restartApp import org.mozilla.focus.testAnnotations.SmokeTest // Tests the First run onboarding screens @RunWith(AndroidJUnit4ClassRunner::class) class FirstRunTest { private lateinit var webServer: MockWebServer private val featureSettingsHelper = FeatureSettingsHelper() @get: Rule val mActivityTestRule = MainActivityFirstrunTestRule(showFirstRun = true) @Before fun startWebServer() { webServer = MockWebServer().apply { dispatcher = MockWebServerHelper.AndroidAssetDispatcher() start() } featureSettingsHelper.setCfrForTrackingProtectionEnabled(false) } @After fun stopWebServer() { webServer.shutdown() featureSettingsHelper.resetAllFeatureFlags() } @SmokeTest @Test fun onboardingScreensTest() { homeScreen { verifyFirstOnboardingScreenItems() restartApp(mActivityTestRule) verifyFirstOnboardingScreenItems() clickGetStartedButton() verifySecondOnboardingScreenItems() restartApp(mActivityTestRule) verifySecondOnboardingScreenItems() } } }
app/src/androidTest/java/org/mozilla/focus/activity/FirstRunTest.kt
3878583391
package you.devknights.minimalweather.network.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName internal class Clouds { @SerializedName("all") @Expose var all: Int = 0 } internal class Coord { @SerializedName("lon") @Expose var lon: Double = 0.toDouble() @SerializedName("lat") @Expose var lat: Double = 0.toDouble() } internal class Main { @SerializedName("temp") @Expose var temp: Float = 0.toFloat() @SerializedName("pressure") @Expose var pressure: Float = 0.toFloat() @SerializedName("humidity") @Expose var humidity: Float = 0.toFloat() @SerializedName("temp_min") @Expose var tempMin: Double = 0.toDouble() @SerializedName("temp_max") @Expose var tempMax: Double = 0.toDouble() } internal class Sys { @SerializedName("type") @Expose var type: Int = 0 @SerializedName("id") @Expose var id: Int = 0 @SerializedName("message") @Expose var message: Double = 0.toDouble() @SerializedName("country") @Expose var country: String? = null @SerializedName("sunrise") @Expose var sunrise: Long = 0 @SerializedName("sunset") @Expose var sunset: Long = 0 } internal class Wind { @SerializedName("speed") @Expose var speed: Double = 0.toDouble() @SerializedName("deg") @Expose var deg: Float = 0.toFloat() } internal class Weather { @SerializedName("id") @Expose var id: Int = 0 @SerializedName("main") @Expose var main: String? = null @SerializedName("description") @Expose var description: String? = null @SerializedName("icon") @Expose var icon: String? = null }
app/src/main/java/you/devknights/minimalweather/network/model/model.kt
2394423913
package com.wenhaiz.himusic.utils import android.content.Context import com.wenhaiz.himusic.MyApp import io.objectbox.BoxStore object BoxUtil { const val TAG = "BoxUtil" fun getBoxStore(context: Context): BoxStore { return MyApp.getBoxStore() } }
app/src/main/java/com/wenhaiz/himusic/utils/BoxUtil.kt
1309458255
package com.google.chip.chiptool.setuppayloadscanner import android.os.Parcelable import chip.setuppayload.OptionalQRCodeInfo.OptionalQRCodeInfoType import kotlinx.android.parcel.Parcelize @Parcelize data class QrCodeInfo( val tag: Int, val type: OptionalQRCodeInfoType, val data: String, val intDataValue: Int ) : Parcelable
src/android/CHIPTool/app/src/main/java/com/google/chip/chiptool/setuppayloadscanner/QrCodeInfo.kt
130554891
package ktsearch import org.junit.Assert.assertEquals import org.junit.Test import java.io.File import java.util.* /** * @author cary on 7/30/16. */ class SearchResultTest { @Test fun testSingleLineSearchResult() { val settings = getDefaultSettings().copy(colorize = false) val formatter = SearchResultFormatter(settings) val pattern = Regex("Search") val path = "~/src/xsearch/csharp/CsSearch/CsSearch/Searcher.cs" val file = File(path) val searchFile = SearchFile(file, FileType.CODE) val lineNum = 10 val matchStartIndex = 15 val matchEndIndex = 23 val line = "\tpublic class Searcher\n" val searchResult = SearchResult(pattern, searchFile, lineNum, matchStartIndex, matchEndIndex, line) val expectedOutput = String.format("%s: %d: [%d:%d]: %s", path, lineNum, matchStartIndex, matchEndIndex, line.trim { it <= ' ' }) val output = formatter.format(searchResult) assertEquals(expectedOutput, output) } @Test fun testSingleLineLongerThanMaxLineLengthSearchResult() { val settings = getDefaultSettings().copy(colorize = false, maxLineLength = 100) val formatter = SearchResultFormatter(settings) val pattern = Regex("maxlen") val file = File("./maxlen.txt") val searchFile = SearchFile(file, FileType.TEXT) val lineNum = 1 val matchStartIndex = 53 val matchEndIndex = 59 val line = "0123456789012345678901234567890123456789012345678901maxlen8901234567890123456789012345678901234567890123456789" val linesBeforeAfter: List<String> = ArrayList() val searchResult = SearchResult(pattern, searchFile, lineNum, matchStartIndex, matchEndIndex, line, linesBeforeAfter, linesBeforeAfter) val expectedPath = "." + File.separator + "maxlen.txt" val expectedLine = "...89012345678901234567890123456789012345678901maxlen89012345678901234567890123456789012345678901..." val expectedOutput = String.format("%s: %d: [%d:%d]: %s", expectedPath, lineNum, matchStartIndex, matchEndIndex, expectedLine) val output = formatter.format(searchResult) assertEquals(expectedOutput, output) } @Test fun testSingleLineLongerColorizeSearchResult() { val settings = getDefaultSettings().copy(colorize = true, maxLineLength = 100) val formatter = SearchResultFormatter(settings) val pattern = Regex("maxlen") val file = File("./maxlen.txt") val searchFile = SearchFile(file, FileType.TEXT) val lineNum = 1 val matchStartIndex = 53 val matchEndIndex = 59 val line = "0123456789012345678901234567890123456789012345678901maxlen8901234567890123456789012345678901234567890123456789" val linesBeforeAfter: List<String> = ArrayList() val searchResult = SearchResult(pattern, searchFile, lineNum, matchStartIndex, matchEndIndex, line, linesBeforeAfter, linesBeforeAfter) val expectedPath = "." + File.separator + "maxlen.txt" val expectedLine = "...89012345678901234567890123456789012345678901" + Color.GREEN + "maxlen" + Color.RESET + "89012345678901234567890123456789012345678901..." val expectedOutput = String.format("%s: %d: [%d:%d]: %s", expectedPath, lineNum, matchStartIndex, matchEndIndex, expectedLine) val output = formatter.format(searchResult) assertEquals(expectedOutput, output) } @Test fun testBinaryFileSearchResult() { val settings = getDefaultSettings() val formatter = SearchResultFormatter(settings) val pattern = Regex("Search") val file = File("~/src/xsearch/csharp/CsSearch/CsSearch/Searcher.exe") val searchFile = SearchFile(file, FileType.BINARY) val lineNum = 0 val matchStartIndex = 0 val matchEndIndex = 0 val searchResult = SearchResult(pattern, searchFile, lineNum, matchStartIndex, matchEndIndex, "") val expectedPath = "~/src/xsearch/csharp/CsSearch/CsSearch/Searcher.exe" val expectedOutput = String.format("%s matches at [0:0]", expectedPath) val output = formatter.format(searchResult) assertEquals(expectedOutput, output) } @Test fun testMultiLineSearchResult() { val settings = getDefaultSettings().copy(colorize = false, linesBefore = 2, linesAfter = 2) val formatter = SearchResultFormatter(settings) val pattern = Regex("Searcher") val path = "~/src/xsearch/csharp/CsSearch/CsSearch/Searcher.cs" val file = File(path) val searchFile = SearchFile(file, FileType.CODE) val lineNum = 10 val matchStartIndex = 15 val matchEndIndex = 23 val line = "\tpublic class Searcher" val linesBefore = listOf("namespace CsSearch", "{") val linesAfter = listOf("\t{", "\t\tprivate readonly FileTypes _fileTypes;") val searchResult = SearchResult(pattern, searchFile, lineNum, matchStartIndex, matchEndIndex, line, linesBefore, linesAfter) val expectedOutput = """================================================================================ |$path: $lineNum: [$matchStartIndex:$matchEndIndex] |-------------------------------------------------------------------------------- | 8 | namespace CsSearch | 9 | { |> 10 | public class Searcher | 11 | { | 12 | private readonly FileTypes _fileTypes; |""".trimMargin() val output = formatter.format(searchResult) assertEquals(expectedOutput, output) } }
kotlin/ktsearch/src/test/kotlin/ktsearch/SearchResultTest.kt
3017558926
package hr.caellian.math.matrix import hr.caellian.math.vector.VectorF import kotlin.math.tan /** * Utility object containing initializers for basic 4x4 matrices. * These functions should be used instead of any provided by [MatrixF] wherever possible as they generally perform faster. * * @author Caellian */ object Matrix4F { /** * Initializes perspective transformation matrix. * * @param fov field of view. * @param aspectRatio aspect ration. * @param clipNear front clipping position. * @param clipFar back clipping position. * @return perspective transformation matrix. */ @JvmStatic fun initPerspectiveMatrix(fov: Float, aspectRatio: Float, clipNear: Float, clipFar: Float): MatrixF { val fowAngle = tan(fov / 2) val clipRange = clipNear - clipFar return MatrixF(Array(4) { row -> Array(4) { column -> when { row == 0 && column == 0 -> 1f / (fowAngle * aspectRatio) row == 1 && column == 1 -> 1f / fowAngle row == 2 && column == 2 -> (-clipNear - clipFar) / clipRange row == 2 && column == 3 -> 2 * clipFar * clipNear / clipRange row == 3 && column == 2 -> 1f else -> 0f } } }) } /** * Initializes orthographic transformation matrix. * * @param left left clipping position. * @param right right clipping position. * @param bottom bottom clipping position. * @param top top clipping position. * @param clipNear front clipping position. * @param clipFar back clipping position. * @return orthographic transformation matrix */ @JvmStatic fun initOrthographicMatrix(left: Float, right: Float, bottom: Float, top: Float, clipNear: Float, clipFar: Float): MatrixF { val width = right - left val height = top - bottom val depth = clipFar - clipNear return MatrixF(Array(4) { row -> Array(4) { column -> when { row == 0 && column == 0 -> 2 / width row == 0 && column == 3 -> -(right + left) / width row == 1 && column == 1 -> 2 / height row == 1 && column == 3 -> -(top + bottom) / height row == 2 && column == 2 -> -2 / depth row == 2 && column == 3 -> -(clipFar + clipNear) / depth row == 3 && column == 3 -> 1f else -> 0f } } }) } /** * Initializes rotation matrix using forward and up vector by calculating * right vector. * * @param forward forward 3f vector. * @param up up 3f vector. * @return rotation matrix. */ @JvmStatic fun initRotationMatrix(forward: VectorF, up: VectorF): MatrixF { require(forward.size == 3) { "Invalid forward vector size (${forward.size}), expected size of 3!" } require(up.size == 3) { "Invalid up vector size (${up.size}), expected size of 3!" } val f = forward.normalized() val r = up.normalized().cross(f) val u = f.cross(r) return Matrix4F.initRotationMatrix(f, u, r) } /** * Initializes rotation matrix using a rotation quaternion. * * @param quaternion quaternion to use for initialization. * @return rotation matrix. */ @JvmStatic fun initRotationMatrix(quaternion: VectorF): MatrixF { require(quaternion.size == 4) { "Invalid quaternion size (${quaternion.size}), expected size of 4!" } val forward = VectorF(2f * (quaternion[0] * quaternion[2] - quaternion[3] * quaternion[1]), 2f * (quaternion[1] * quaternion[2] + quaternion[3] * quaternion[0]), 1f - 2f * (quaternion[0] * quaternion[0] + quaternion[1] * quaternion[1])) val up = VectorF(2f * (quaternion[0] * quaternion[1] + quaternion[3] * quaternion[2]), 1f - 2f * (quaternion[0] * quaternion[0] + quaternion[2] * quaternion[2]), 2f * (quaternion[1] * quaternion[2] - quaternion[3] * quaternion[0])) val right = VectorF(1f - 2f * (quaternion[1] * quaternion[1] + quaternion[2] * quaternion[2]), 2f * (quaternion[0] * quaternion[1] - quaternion[3] * quaternion[2]), 2f * (quaternion[0] * quaternion[2] + quaternion[3] * quaternion[1])) return Matrix4F.initRotationMatrix(forward, up, right) } /** * Initializes rotation matrix using forward, up and right vector. * * @param forward forward 3f vector. * @param up up 3f vector. * @param right right 3f vector. * @return rotation matrix. */ @JvmStatic fun initRotationMatrix(forward: VectorF, up: VectorF, right: VectorF): MatrixF { require(forward.size == 3) { "Invalid forward vector size (${forward.size}), expected size of 3!" } require(up.size == 3) { "Invalid up vector size (${up.size}), expected size of 3!" } require(right.size == 3) { "Invalid right vector size (${right.size}), expected size of 3!" } return MatrixF(Array(4) { row -> Array(4) { column -> when { row == 0 && column != 3 -> right[column] row == 1 && column != 3 -> up[column] row == 2 && column != 3 -> forward[column] row == 3 && column == 3 -> 1f else -> 0f } } }) } /** * Utility method that combines translation and rotation directly and returns world transformation matrix. * * @since 3.0.0 * * @param eye camera position 3f vector. * @param center position to look at. * @param up up 3f vector. * @return world transformation matrix. */ @JvmStatic fun lookAt(eye: VectorF, center: VectorF, up: VectorF): MatrixF { require(eye.size == 3) { "Invalid eye position vector size (${eye.size}), expected size of 3!" } require(center.size == 3) { "Invalid center position vector size (${center.size}), expected size of 3!" } require(up.size == 3) { "Invalid up vector size (${up.size}), expected size of 3!" } val forward = (eye - center).normalized() return MatrixF.initTranslationMatrix(eye - center) * initRotationMatrix(forward, up) } }
src/main/kotlin/hr/caellian/math/matrix/Matrix4F.kt
2472110241
/* Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mapsplatform.transportation.sample.kotlindriver import com.google.android.gms.maps.model.LatLng import com.google.android.libraries.navigation.Navigator import com.google.android.libraries.navigation.SimulationOptions import com.google.android.libraries.navigation.Simulator import com.google.mapsplatform.transportation.sample.kotlindriver.provider.response.Waypoint /** * Commands to simulate the vehicle driving along a route. It interacts with the [Navigator] to make * the vehicle move along its route to a specified location. * * @property simulator the actual simulator object obtained from [Navigator] that will update * locations. * @propery localSettings settings that are aware of the simulation enabling. */ internal class VehicleSimulator( private val simulator: Simulator, private val localSettings: LocalSettings, ) { /** Sets the user location to be used for simulation. */ fun setLocation(location: Waypoint.Point): Unit = simulator.setUserLocation(LatLng(location.latitude, location.longitude)) /** * Starts a simulation to the location defined by [.setLocation] along a route calculated by the * [Navigator]. */ fun start(speedMultiplier: Float) { if (localSettings.getIsSimulationEnabled()) { simulator.simulateLocationsAlongExistingRoute( SimulationOptions().speedMultiplier(speedMultiplier) ) } } /** Pauses a simulation that can later be resumed. */ fun pause() { simulator.pause() } /** Resets the position of the [Navigator] and pauses navigation. */ fun unsetLocation() { simulator.unsetUserLocation() } }
kotlin/kotlin-driver/src/main/kotlin/com/google/mapsplatform/transportation/sample/kotlindriver/VehicleSimulator.kt
3031726200
package eu.kanade.tachiyomi.ui.library import android.os.Bundle import com.jakewharton.rxrelay.BehaviorRelay import eu.kanade.tachiyomi.data.cache.CoverCache import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.data.database.models.Chapter import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaCategory import eu.kanade.tachiyomi.data.download.DownloadManager import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.source.SourceManager import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.HttpSource import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.ui.library.setting.SortDirectionSetting import eu.kanade.tachiyomi.ui.library.setting.SortModeSetting import eu.kanade.tachiyomi.util.isLocal import eu.kanade.tachiyomi.util.lang.combineLatest import eu.kanade.tachiyomi.util.lang.isNullOrUnsubscribed import eu.kanade.tachiyomi.util.lang.launchIO import eu.kanade.tachiyomi.util.removeCovers import eu.kanade.tachiyomi.widget.ExtendedNavigationView.Item.TriStateGroup.State import rx.Observable import rx.Subscription import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import java.text.Collator import java.util.Collections import java.util.Comparator import java.util.Locale /** * Class containing library information. */ private data class Library(val categories: List<Category>, val mangaMap: LibraryMap) /** * Typealias for the library manga, using the category as keys, and list of manga as values. */ private typealias LibraryMap = Map<Int, List<LibraryItem>> /** * Presenter of [LibraryController]. */ class LibraryPresenter( private val db: DatabaseHelper = Injekt.get(), private val preferences: PreferencesHelper = Injekt.get(), private val coverCache: CoverCache = Injekt.get(), private val sourceManager: SourceManager = Injekt.get(), private val downloadManager: DownloadManager = Injekt.get(), private val trackManager: TrackManager = Injekt.get() ) : BasePresenter<LibraryController>() { private val context = preferences.context /** * Categories of the library. */ var categories: List<Category> = emptyList() private set /** * Relay used to apply the UI filters to the last emission of the library. */ private val filterTriggerRelay = BehaviorRelay.create(Unit) /** * Relay used to apply the UI update to the last emission of the library. */ private val badgeTriggerRelay = BehaviorRelay.create(Unit) /** * Relay used to apply the selected sorting method to the last emission of the library. */ private val sortTriggerRelay = BehaviorRelay.create(Unit) /** * Library subscription. */ private var librarySubscription: Subscription? = null override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) subscribeLibrary() } /** * Subscribes to library if needed. */ fun subscribeLibrary() { if (librarySubscription.isNullOrUnsubscribed()) { librarySubscription = getLibraryObservable() .combineLatest(badgeTriggerRelay.observeOn(Schedulers.io())) { lib, _ -> lib.apply { setBadges(mangaMap) } } .combineLatest(getFilterObservable()) { lib, tracks -> lib.copy(mangaMap = applyFilters(lib.mangaMap, tracks)) } .combineLatest(sortTriggerRelay.observeOn(Schedulers.io())) { lib, _ -> lib.copy(mangaMap = applySort(lib.categories, lib.mangaMap)) } .observeOn(AndroidSchedulers.mainThread()) .subscribeLatestCache({ view, (categories, mangaMap) -> view.onNextLibraryUpdate(categories, mangaMap) }) } } /** * Applies library filters to the given map of manga. * * @param map the map to filter. */ private fun applyFilters(map: LibraryMap, trackMap: Map<Long, Map<Int, Boolean>>): LibraryMap { val downloadedOnly = preferences.downloadedOnly().get() val filterDownloaded = preferences.filterDownloaded().get() val filterUnread = preferences.filterUnread().get() val filterCompleted = preferences.filterCompleted().get() val loggedInServices = trackManager.services.filter { trackService -> trackService.isLogged } .associate { trackService -> Pair(trackService.id, preferences.filterTracking(trackService.id).get()) } val isNotAnyLoggedIn = !loggedInServices.values.any() val filterFnUnread: (LibraryItem) -> Boolean = unread@{ item -> if (filterUnread == State.IGNORE.value) return@unread true val isUnread = item.manga.unread != 0 return@unread if (filterUnread == State.INCLUDE.value) isUnread else !isUnread } val filterFnCompleted: (LibraryItem) -> Boolean = completed@{ item -> if (filterCompleted == State.IGNORE.value) return@completed true val isCompleted = item.manga.status == SManga.COMPLETED return@completed if (filterCompleted == State.INCLUDE.value) isCompleted else !isCompleted } val filterFnDownloaded: (LibraryItem) -> Boolean = downloaded@{ item -> if (!downloadedOnly && filterDownloaded == State.IGNORE.value) return@downloaded true val isDownloaded = when { item.manga.isLocal() -> true item.downloadCount != -1 -> item.downloadCount > 0 else -> downloadManager.getDownloadCount(item.manga) > 0 } return@downloaded if (downloadedOnly || filterDownloaded == State.INCLUDE.value) isDownloaded else !isDownloaded } val filterFnTracking: (LibraryItem) -> Boolean = tracking@{ item -> if (isNotAnyLoggedIn) return@tracking true val trackedManga = trackMap[item.manga.id ?: -1] val containsExclude = loggedInServices.filterValues { it == State.EXCLUDE.value } val containsInclude = loggedInServices.filterValues { it == State.INCLUDE.value } if (!containsExclude.any() && !containsInclude.any()) return@tracking true val exclude = trackedManga?.filterKeys { containsExclude.containsKey(it) }?.values ?: emptyList() val include = trackedManga?.filterKeys { containsInclude.containsKey(it) }?.values ?: emptyList() if (containsInclude.any() && containsExclude.any()) { return@tracking if (exclude.isNotEmpty()) !exclude.any() else include.any() } if (containsExclude.any()) return@tracking !exclude.any() if (containsInclude.any()) return@tracking include.any() return@tracking false } val filterFn: (LibraryItem) -> Boolean = filter@{ item -> return@filter !( !filterFnUnread(item) || !filterFnCompleted(item) || !filterFnDownloaded(item) || !filterFnTracking(item) ) } return map.mapValues { entry -> entry.value.filter(filterFn) } } /** * Sets downloaded chapter count to each manga. * * @param map the map of manga. */ private fun setBadges(map: LibraryMap) { val showDownloadBadges = preferences.downloadBadge().get() val showUnreadBadges = preferences.unreadBadge().get() val showLocalBadges = preferences.localBadge().get() val showLanguageBadges = preferences.languageBadge().get() for ((_, itemList) in map) { for (item in itemList) { item.downloadCount = if (showDownloadBadges) { downloadManager.getDownloadCount(item.manga) } else { // Unset download count if not enabled -1 } item.unreadCount = if (showUnreadBadges) { item.manga.unread } else { // Unset unread count if not enabled -1 } item.isLocal = if (showLocalBadges) { item.manga.isLocal() } else { // Hide / Unset local badge if not enabled false } item.sourceLanguage = if (showLanguageBadges) { sourceManager.getOrStub(item.manga.source).lang.uppercase() } else { // Unset source language if not enabled "" } } } } /** * Applies library sorting to the given map of manga. * * @param map the map to sort. */ private fun applySort(categories: List<Category>, map: LibraryMap): LibraryMap { val lastReadManga by lazy { var counter = 0 db.getLastReadManga().executeAsBlocking().associate { it.id!! to counter++ } } val totalChapterManga by lazy { var counter = 0 db.getTotalChapterManga().executeAsBlocking().associate { it.id!! to counter++ } } val latestChapterManga by lazy { var counter = 0 db.getLatestChapterManga().executeAsBlocking().associate { it.id!! to counter++ } } val chapterFetchDateManga by lazy { var counter = 0 db.getChapterFetchDateManga().executeAsBlocking().associate { it.id!! to counter++ } } val sortingModes = categories.associate { category -> (category.id ?: 0) to SortModeSetting.get(preferences, category) } val sortAscending = categories.associate { category -> (category.id ?: 0) to SortDirectionSetting.get(preferences, category) } val locale = Locale.getDefault() val collator = Collator.getInstance(locale).apply { strength = Collator.PRIMARY } val sortFn: (LibraryItem, LibraryItem) -> Int = { i1, i2 -> val sortingMode = sortingModes[i1.manga.category]!! val sortAscending = sortAscending[i1.manga.category]!! == SortDirectionSetting.ASCENDING when (sortingMode) { SortModeSetting.ALPHABETICAL -> { collator.compare(i1.manga.title.lowercase(locale), i2.manga.title.lowercase(locale)) } SortModeSetting.LAST_READ -> { // Get index of manga, set equal to list if size unknown. val manga1LastRead = lastReadManga[i1.manga.id!!] ?: lastReadManga.size val manga2LastRead = lastReadManga[i2.manga.id!!] ?: lastReadManga.size manga1LastRead.compareTo(manga2LastRead) } SortModeSetting.LAST_CHECKED -> i2.manga.last_update.compareTo(i1.manga.last_update) SortModeSetting.UNREAD -> when { // Ensure unread content comes first i1.manga.unread == i2.manga.unread -> 0 i1.manga.unread == 0 -> if (sortAscending) 1 else -1 i2.manga.unread == 0 -> if (sortAscending) -1 else 1 else -> i1.manga.unread.compareTo(i2.manga.unread) } SortModeSetting.TOTAL_CHAPTERS -> { val manga1TotalChapter = totalChapterManga[i1.manga.id!!] ?: 0 val mange2TotalChapter = totalChapterManga[i2.manga.id!!] ?: 0 manga1TotalChapter.compareTo(mange2TotalChapter) } SortModeSetting.LATEST_CHAPTER -> { val manga1latestChapter = latestChapterManga[i1.manga.id!!] ?: latestChapterManga.size val manga2latestChapter = latestChapterManga[i2.manga.id!!] ?: latestChapterManga.size manga1latestChapter.compareTo(manga2latestChapter) } SortModeSetting.DATE_FETCHED -> { val manga1chapterFetchDate = chapterFetchDateManga[i1.manga.id!!] ?: chapterFetchDateManga.size val manga2chapterFetchDate = chapterFetchDateManga[i2.manga.id!!] ?: chapterFetchDateManga.size manga1chapterFetchDate.compareTo(manga2chapterFetchDate) } SortModeSetting.DATE_ADDED -> i2.manga.date_added.compareTo(i1.manga.date_added) } } return map.mapValues { entry -> val sortAscending = sortAscending[entry.key]!! == SortDirectionSetting.ASCENDING val comparator = if (sortAscending) { Comparator(sortFn) } else { Collections.reverseOrder(sortFn) } entry.value.sortedWith(comparator) } } /** * Get the categories and all its manga from the database. * * @return an observable of the categories and its manga. */ private fun getLibraryObservable(): Observable<Library> { return Observable.combineLatest(getCategoriesObservable(), getLibraryMangasObservable()) { dbCategories, libraryManga -> val categories = if (libraryManga.containsKey(0)) { arrayListOf(Category.createDefault(context)) + dbCategories } else { dbCategories } libraryManga.forEach { (categoryId, libraryManga) -> val category = categories.first { category -> category.id == categoryId } libraryManga.forEach { libraryItem -> libraryItem.displayMode = category.displayMode } } this.categories = categories Library(categories, libraryManga) } } /** * Get the categories from the database. * * @return an observable of the categories. */ private fun getCategoriesObservable(): Observable<List<Category>> { return db.getCategories().asRxObservable() } /** * Get the manga grouped by categories. * * @return an observable containing a map with the category id as key and a list of manga as the * value. */ private fun getLibraryMangasObservable(): Observable<LibraryMap> { val defaultLibraryDisplayMode = preferences.libraryDisplayMode() val shouldSetFromCategory = preferences.categorizedDisplaySettings() return db.getLibraryMangas().asRxObservable() .map { list -> list.map { libraryManga -> // Display mode based on user preference: take it from global library setting or category LibraryItem( libraryManga, shouldSetFromCategory, defaultLibraryDisplayMode ) }.groupBy { it.manga.category } } } /** * Get the tracked manga from the database and checks if the filter gets changed * * @return an observable of tracked manga. */ private fun getFilterObservable(): Observable<Map<Long, Map<Int, Boolean>>> { return getTracksObservable().combineLatest(filterTriggerRelay.observeOn(Schedulers.io())) { tracks, _ -> tracks } } /** * Get the tracked manga from the database * * @return an observable of tracked manga. */ private fun getTracksObservable(): Observable<Map<Long, Map<Int, Boolean>>> { return db.getTracks().asRxObservable().map { tracks -> tracks.groupBy { it.manga_id } .mapValues { tracksForMangaId -> // Check if any of the trackers is logged in for the current manga id tracksForMangaId.value.associate { Pair(it.sync_id, trackManager.getService(it.sync_id)?.isLogged ?: false) } } }.observeOn(Schedulers.io()) } /** * Requests the library to be filtered. */ fun requestFilterUpdate() { filterTriggerRelay.call(Unit) } /** * Requests the library to have download badges added. */ fun requestBadgesUpdate() { badgeTriggerRelay.call(Unit) } /** * Requests the library to be sorted. */ fun requestSortUpdate() { sortTriggerRelay.call(Unit) } /** * Called when a manga is opened. */ fun onOpenManga() { // Avoid further db updates for the library when it's not needed librarySubscription?.let { remove(it) } } /** * Returns the common categories for the given list of manga. * * @param mangas the list of manga. */ fun getCommonCategories(mangas: List<Manga>): Collection<Category> { if (mangas.isEmpty()) return emptyList() return mangas.toSet() .map { db.getCategoriesForManga(it).executeAsBlocking() } .reduce { set1: Iterable<Category>, set2 -> set1.intersect(set2).toMutableList() } } /** * Returns the mix (non-common) categories for the given list of manga. * * @param mangas the list of manga. */ fun getMixCategories(mangas: List<Manga>): Collection<Category> { if (mangas.isEmpty()) return emptyList() val mangaCategories = mangas.toSet().map { db.getCategoriesForManga(it).executeAsBlocking() } val common = mangaCategories.reduce { set1, set2 -> set1.intersect(set2).toMutableList() } return mangaCategories.flatten().distinct().subtract(common).toMutableList() } /** * Queues all unread chapters from the given list of manga. * * @param mangas the list of manga. */ fun downloadUnreadChapters(mangas: List<Manga>) { mangas.forEach { manga -> launchIO { val chapters = db.getChapters(manga).executeAsBlocking() .filter { !it.read } downloadManager.downloadChapters(manga, chapters) } } } /** * Marks mangas' chapters read status. * * @param mangas the list of manga. */ fun markReadStatus(mangas: List<Manga>, read: Boolean) { mangas.forEach { manga -> launchIO { val chapters = db.getChapters(manga).executeAsBlocking() chapters.forEach { it.read = read if (!read) { it.last_page_read = 0 } } db.updateChaptersProgress(chapters).executeAsBlocking() if (read && preferences.removeAfterMarkedAsRead()) { deleteChapters(manga, chapters) } } } } private fun deleteChapters(manga: Manga, chapters: List<Chapter>) { sourceManager.get(manga.source)?.let { source -> downloadManager.deleteChapters(chapters, manga, source) } } /** * Remove the selected manga. * * @param mangas the list of manga to delete. * @param deleteFromLibrary whether to delete manga from library. * @param deleteChapters whether to delete downloaded chapters. */ fun removeMangas(mangas: List<Manga>, deleteFromLibrary: Boolean, deleteChapters: Boolean) { launchIO { val mangaToDelete = mangas.distinctBy { it.id } if (deleteFromLibrary) { mangaToDelete.forEach { it.favorite = false it.removeCovers(coverCache) } db.insertMangas(mangaToDelete).executeAsBlocking() } if (deleteChapters) { mangaToDelete.forEach { manga -> val source = sourceManager.get(manga.source) as? HttpSource if (source != null) { downloadManager.deleteManga(manga, source) } } } } } /** * Move the given list of manga to categories. * * @param categories the selected categories. * @param mangas the list of manga to move. */ fun moveMangasToCategories(categories: List<Category>, mangas: List<Manga>) { val mc = mutableListOf<MangaCategory>() for (manga in mangas) { categories.mapTo(mc) { MangaCategory.create(manga, it) } } db.setMangaCategories(mc, mangas) } /** * Bulk update categories of mangas using old and new common categories. * * @param mangas the list of manga to move. * @param addCategories the categories to add for all mangas. * @param removeCategories the categories to remove in all mangas. */ fun updateMangasToCategories(mangas: List<Manga>, addCategories: List<Category>, removeCategories: List<Category>) { val mangaCategories = mangas.map { manga -> val categories = db.getCategoriesForManga(manga).executeAsBlocking() .subtract(removeCategories).plus(addCategories).distinct() categories.map { MangaCategory.create(manga, it) } }.flatten() db.setMangaCategories(mangaCategories, mangas) } }
app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryPresenter.kt
3938723559
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.maps.utils.kotlin import android.content.Context import android.graphics.Color import android.widget.Toast import androidx.annotation.RawRes import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.TileOverlayOptions import com.google.maps.android.heatmaps.Gradient import com.google.maps.android.heatmaps.HeatmapTileProvider import com.google.maps.android.heatmaps.WeightedLatLng import com.google.maps.example.R import org.json.JSONArray import org.json.JSONException import java.util.* import kotlin.jvm.Throws internal class Heatmaps { private lateinit var context: Context private lateinit var map: GoogleMap // [START maps_android_utils_heatmap_simple] private fun addHeatMap() { var latLngs: List<LatLng?>? = null // Get the data: latitude/longitude positions of police stations. try { latLngs = readItems(R.raw.police_stations) } catch (e: JSONException) { Toast.makeText(context, "Problem reading list of locations.", Toast.LENGTH_LONG) .show() } // Create a heat map tile provider, passing it the latlngs of the police stations. val provider = HeatmapTileProvider.Builder() .data(latLngs) .build() // Add a tile overlay to the map, using the heat map tile provider. val overlay = map.addTileOverlay(TileOverlayOptions().tileProvider(provider)) } @Throws(JSONException::class) private fun readItems(@RawRes resource: Int): List<LatLng?> { val result: MutableList<LatLng?> = ArrayList() val inputStream = context.resources.openRawResource(resource) val json = Scanner(inputStream).useDelimiter("\\A").next() val array = JSONArray(json) for (i in 0 until array.length()) { val `object` = array.getJSONObject(i) val lat = `object`.getDouble("lat") val lng = `object`.getDouble("lng") result.add(LatLng(lat, lng)) } return result } // [END maps_android_utils_heatmap_simple] private fun customizeHeatmap(latLngs: List<LatLng>) { // [START maps_android_utils_heatmap_customize] // Create the gradient. val colors = intArrayOf( Color.rgb(102, 225, 0), // green Color.rgb(255, 0, 0) // red ) val startPoints = floatArrayOf(0.2f, 1f) val gradient = Gradient(colors, startPoints) // Create the tile provider. val provider = HeatmapTileProvider.Builder() .data(latLngs) .gradient(gradient) .build() // Add the tile overlay to the map. val tileOverlay = map.addTileOverlay( TileOverlayOptions() .tileProvider(provider) ) // [END maps_android_utils_heatmap_customize] // [START maps_android_utils_heatmap_customize_opacity] provider.setOpacity(0.7) tileOverlay?.clearTileCache() // [END maps_android_utils_heatmap_customize_opacity] // [START maps_android_utils_heatmap_customize_dataset] val data: List<WeightedLatLng> = ArrayList() provider.setWeightedData(data) tileOverlay?.clearTileCache() // [END maps_android_utils_heatmap_customize_dataset] // [START maps_android_utils_heatmap_remove] tileOverlay?.remove() // [END maps_android_utils_heatmap_remove] } }
snippets/app/src/gms/java/com/google/maps/utils/kotlin/Heatmaps.kt
485364359
package org.wordpress.android.fluxc.tools import com.google.gson.Gson import com.google.gson.annotations.SerializedName import com.google.gson.reflect.TypeToken import javax.inject.Inject class FormattableContentMapper @Inject constructor(val gson: Gson) { fun mapToFormattableContent(json: String): FormattableContent = gson.fromJson(json, FormattableContent::class.java) fun mapToFormattableContentList(json: String): List<FormattableContent> = gson.fromJson(json, object : TypeToken<List<FormattableContent>>() {}.type) fun mapToFormattableMeta(json: String): FormattableMeta = gson.fromJson(json, FormattableMeta::class.java) fun mapFormattableContentToJson(formattableContent: FormattableContent): String = gson.toJson(formattableContent) fun mapFormattableContentListToJson(formattableList: List<FormattableContent>): String = gson.toJson(formattableList) fun mapFormattableMetaToJson(formattableMeta: FormattableMeta): String = gson.toJson(formattableMeta) } data class FormattableContent( @SerializedName("actions") val actions: Map<String, Boolean>? = null, @SerializedName("media") val media: List<FormattableMedia>? = null, @SerializedName("meta") val meta: FormattableMeta? = null, @SerializedName("text") val text: String? = null, @SerializedName("type") val type: String? = null, @SerializedName("nest_level") val nestLevel: Int? = null, @SerializedName("ranges") val ranges: List<FormattableRange>? = null ) data class FormattableMedia( @SerializedName("height") val height: String? = null, @SerializedName("width") val width: String? = null, @SerializedName("type") val type: String? = null, @SerializedName("url") val url: String? = null, @SerializedName("indices") val indices: List<Int>? = null ) data class FormattableMeta( @SerializedName("ids") val ids: Ids? = null, @SerializedName("links") val links: Links? = null, @SerializedName("titles") val titles: Titles? = null, @SerializedName("is_mobile_button") val isMobileButton: Boolean? = null ) { data class Ids( @SerializedName("site") val site: Long? = null, @SerializedName("user") val user: Long? = null, @SerializedName("comment") val comment: Long? = null, @SerializedName("post") val post: Long? = null, @SerializedName("order") val order: Long? = null ) data class Links( @SerializedName("site") val site: String? = null, @SerializedName("user") val user: String? = null, @SerializedName("comment") val comment: String? = null, @SerializedName("post") val post: String? = null, @SerializedName("email") val email: String? = null, @SerializedName("home") val home: String? = null, @SerializedName("order") val order: String? = null ) data class Titles( @SerializedName("home") val home: String? = null, @SerializedName("tagline") val tagline: String? = null ) } data class FormattableRange( @SerializedName("id") private val stringId: String? = null, @SerializedName("site_id") val siteId: Long? = null, @SerializedName("post_id") val postId: Long? = null, @SerializedName("root_id") val rootId: Long? = null, @SerializedName("type") val type: String? = null, @SerializedName("url") val url: String? = null, @SerializedName("section") val section: String? = null, @SerializedName("intent") val intent: String? = null, @SerializedName("context") val context: String? = null, @SerializedName("value") val value: String? = null, @SerializedName("indices") val indices: List<Int>? = null ) { // ID in json response is string, and can be non numerical. // we only use numerical ID at the moment, and can safely ignore non-numerical values val id: Long? get() = try { stringId?.toLong() } catch (e: NumberFormatException) { null } fun rangeType(): FormattableRangeType { return if (type != null) FormattableRangeType.fromString(type) else FormattableRangeType.fromString(section) } } enum class FormattableRangeType { POST, SITE, PAGE, COMMENT, USER, STAT, SCAN, BLOCKQUOTE, FOLLOW, NOTICON, LIKE, MATCH, MEDIA, B, REWIND_DOWNLOAD_READY, UNKNOWN; companion object { @Suppress("ComplexMethod") fun fromString(value: String?): FormattableRangeType { return when (value) { "post" -> POST "site" -> SITE "page" -> PAGE "comment" -> COMMENT "user" -> USER "stat" -> STAT "scan" -> SCAN "blockquote" -> BLOCKQUOTE "follow" -> FOLLOW "noticon" -> NOTICON "like" -> LIKE "match" -> MATCH "media" -> MEDIA "b" -> B "rewind_download_ready" -> REWIND_DOWNLOAD_READY else -> UNKNOWN } } } }
fluxc/src/main/java/org/wordpress/android/fluxc/tools/FormattableContentMapper.kt
2513308978
package org.wordpress.android.fluxc.persistence.bloggingprompts import androidx.room.Dao import androidx.room.Entity import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.TypeConverters import kotlinx.coroutines.flow.Flow import org.wordpress.android.fluxc.model.bloggingprompts.BloggingPromptModel import org.wordpress.android.fluxc.persistence.coverters.BloggingPromptDateConverter import java.util.Date @Dao @TypeConverters(BloggingPromptDateConverter::class) abstract class BloggingPromptsDao { @Query("SELECT * FROM BloggingPrompts WHERE id = :promptId AND siteLocalId = :siteLocalId") abstract fun getPrompt(siteLocalId: Int, promptId: Int): Flow<List<BloggingPromptEntity>> @Query("SELECT * FROM BloggingPrompts WHERE date = :date AND siteLocalId = :siteLocalId") @TypeConverters(BloggingPromptDateConverter::class) abstract fun getPromptForDate(siteLocalId: Int, date: Date): Flow<List<BloggingPromptEntity>> @Query("SELECT * FROM BloggingPrompts WHERE siteLocalId = :siteLocalId") abstract fun getAllPrompts(siteLocalId: Int): Flow<List<BloggingPromptEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) abstract suspend fun insert(prompts: List<BloggingPromptEntity>) suspend fun insertForSite(siteLocalId: Int, prompts: List<BloggingPromptModel>) { insert(prompts.map { BloggingPromptEntity.from(siteLocalId, it) }) } @Query("DELETE FROM BloggingPrompts") abstract fun clear() @Entity( tableName = "BloggingPrompts", primaryKeys = ["id"] ) @TypeConverters(BloggingPromptDateConverter::class) data class BloggingPromptEntity( val id: Int, val siteLocalId: Int, val text: String, val title: String, val content: String, val date: Date, val isAnswered: Boolean, val respondentsCount: Int, val attribution: String, val respondentsAvatars: List<String> ) { fun toBloggingPrompt() = BloggingPromptModel( id = id, text = text, title = title, content = content, date = date, isAnswered = isAnswered, attribution = attribution, respondentsCount = respondentsCount, respondentsAvatarUrls = respondentsAvatars ) companion object { fun from( siteLocalId: Int, prompt: BloggingPromptModel ) = BloggingPromptEntity( id = prompt.id, siteLocalId = siteLocalId, text = prompt.text, title = prompt.title, content = prompt.content, date = prompt.date, isAnswered = prompt.isAnswered, attribution = prompt.attribution, respondentsCount = prompt.respondentsCount, respondentsAvatars = prompt.respondentsAvatarUrls ) } } }
fluxc/src/main/java/org/wordpress/android/fluxc/persistence/bloggingprompts/BloggingPromptsDao.kt
938533736
package com.zhuinden.simplestacktutorials.steps.step_7 import android.content.Context import android.preference.PreferenceManager object AuthenticationManager { @Suppress("DEPRECATION") // w/e androidx-chan fun isAuthenticated(appContext: Context): Boolean { val sharedPref = PreferenceManager.getDefaultSharedPreferences(appContext) return sharedPref.getBoolean("isRegistered", false) } @Suppress("DEPRECATION") // w/e androidx-chan fun saveRegistration(appContext: Context) { val sharedPref = PreferenceManager.getDefaultSharedPreferences(appContext) sharedPref.edit().putBoolean("isRegistered", true).apply() } @Suppress("DEPRECATION") // w/e androidx-chan fun clearRegistration(appContext: Context) { val sharedPref = PreferenceManager.getDefaultSharedPreferences(appContext) sharedPref.edit().remove("isRegistered").apply() } var authToken: String = "" // why would this be in the viewModel? }
tutorials/tutorial-sample/src/main/java/com/zhuinden/simplestacktutorials/steps/step_7/AuthenticationManager.kt
2660644060
package org.wordpress.android.fluxc.wc.data import com.yarolegovich.wellsql.WellSql import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import org.wordpress.android.fluxc.SingleStoreWellSqlConfigForTests import org.wordpress.android.fluxc.TestSiteSqlUtils import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.data.WCCountryMapper import org.wordpress.android.fluxc.model.data.WCLocationModel import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult import org.wordpress.android.fluxc.network.rest.wpcom.wc.data.WCDataRestClient import org.wordpress.android.fluxc.persistence.WellSqlConfig import org.wordpress.android.fluxc.store.WCDataStore import org.wordpress.android.fluxc.test import org.wordpress.android.fluxc.tools.initCoroutineEngine @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner::class) class WCDataStoreTest { private val restClient = mock<WCDataRestClient>() private val site = SiteModel().apply { id = 321 } private val mapper = WCCountryMapper() private lateinit var store: WCDataStore private val sampleData = CountryTestUtils.generateCountries().sortedBy { it.code } private val sampleResponse = CountryTestUtils.generateCountryApiResponse() @Before fun setUp() { val appContext = RuntimeEnvironment.application.applicationContext val config = SingleStoreWellSqlConfigForTests( appContext, listOf(SiteModel::class.java, WCLocationModel::class.java), WellSqlConfig.ADDON_WOOCOMMERCE ) WellSql.init(config) config.reset() store = WCDataStore( restClient, initCoroutineEngine(), mapper ) TestSiteSqlUtils.siteSqlUtils.insertOrUpdateSite(site) } @Test fun `fetch countries`() = test { val result = fetchCountries() assertThat(result.model?.size).isEqualTo(sampleData.size) val first = mapper.map(sampleResponse.first()).first() assertThat(result.model?.first()?.name).isEqualTo(first.name) assertThat(result.model?.first()?.code).isEqualTo(first.code) assertThat(result.model?.first()?.parentCode).isEqualTo(first.parentCode) } @Test fun `get countries`() = test { fetchCountries() val sampleCountries = sampleData.filter { it.parentCode == "" } val countries = store.getCountries().sortedBy { it.code } assertThat(countries.size).isEqualTo(sampleCountries.size) countries.forEachIndexed { i, country -> assertThat(country.code).isEqualTo(sampleCountries[i].code) assertThat(country.name).isEqualTo(sampleCountries[i].name) assertThat(country.parentCode).isEqualTo(sampleCountries[i].parentCode) } } @Test fun `get non-empty states`() = test { fetchCountries() val sampleStates = sampleData.filter { it.parentCode == "CA" }.sortedBy { it.code } val states = store.getStates("CA").sortedBy { it.code } assertThat(states.size).isEqualTo(sampleStates.size) states.forEachIndexed { i, state -> assertThat(state.code).isEqualTo(sampleStates[i].code) assertThat(state.name).isEqualTo(sampleStates[i].name) assertThat(state.parentCode).isEqualTo(sampleStates[i].parentCode) } } @Test fun `get empty states`() = test { fetchCountries() val states = store.getStates("CZ") assertThat(states).isEqualTo(emptyList<WCLocationModel>()) } @Test fun `when empty country code is passed, then empty list is returned when getting states`() = test { fetchCountries() val states = store.getStates("") assertThat(states).isEqualTo(emptyList<WCLocationModel>()) } private suspend fun fetchCountries(): WooResult<List<WCLocationModel>> { val payload = WooPayload(sampleResponse.toTypedArray()) whenever(restClient.fetchCountries(site)).thenReturn(payload) return store.fetchCountriesAndStates(site) } }
example/src/test/java/org/wordpress/android/fluxc/wc/data/WCDataStoreTest.kt
1964873810
package com.commit451.youtubeextractor import org.mozilla.javascript.Context import org.mozilla.javascript.Function /** * Runs JavaScripty things */ internal object JavaScriptUtil { private const val DECRYPTION_FUNC_NAME = "decrypt" private const val DECRYPTION_SIGNATURE_FUNCTION_REGEX = "([\\w$]+)\\s*=\\s*function\\((\\w+)\\)\\{\\s*\\2=\\s*\\2\\.split\\(\"\"\\)\\s*;" private const val DECRYPTION_SIGNATURE_FUNCTION_REGEX_2 = "\\b([\\w$]{2})\\s*=\\s*function\\((\\w+)\\)\\{\\s*\\2=\\s*\\2\\.split\\(\"\"\\)\\s*;" private const val DECRYPTION_AKAMAIZED_STRING_REGEX = "yt\\.akamaized\\.net/\\)\\s*\\|\\|\\s*.*?\\s*c\\s*&&\\s*d\\.set\\([^,]+\\s*,\\s*([a-zA-Z0-9$]+)\\(" private const val DECRYPTION_AKAMAIZED_SHORT_STRING_REGEX = "\\bc\\s*&&\\s*d\\.set\\([^,]+\\s*,\\s*([a-zA-Z0-9$]+)\\(" private val decryptionFunctions = listOf( DECRYPTION_SIGNATURE_FUNCTION_REGEX_2, DECRYPTION_SIGNATURE_FUNCTION_REGEX, DECRYPTION_AKAMAIZED_SHORT_STRING_REGEX, DECRYPTION_AKAMAIZED_STRING_REGEX ) fun loadDecryptionCode(playerCode: String): String { val decryptionFunctionName = decryptionFunctionName(playerCode) val functionPattern = "(" + decryptionFunctionName.replace("$", "\\$") + "=function\\([a-zA-Z0-9_]+\\)\\{.+?\\})" val decryptionFunction = "var " + Util.matchGroup1(functionPattern, playerCode) + ";" val helperObjectName = Util.matchGroup1(";([A-Za-z0-9_\\$]{2})\\...\\(", decryptionFunction) val helperPattern = "(var " + helperObjectName.replace("$", "\\$") + "=\\{.+?\\}\\};)" val helperObject = Util.matchGroup1(helperPattern, playerCode.replace("\n", "")) val callerFunction = "function $DECRYPTION_FUNC_NAME(a){return $decryptionFunctionName(a);}" return helperObject + decryptionFunction + callerFunction } private fun decryptionFunctionName(playerCode: String): String { decryptionFunctions.forEach { try { return Util.matchGroup1(it, playerCode) } catch (e: Exception) { } } throw IllegalStateException("Could not find decryption function with any of the patterns. Please open a new issue") } fun decryptSignature(encryptedSig: String, decryptionCode: String): String { val context = Context.enter() context.optimizationLevel = -1 val result: Any? try { val scope = context.initStandardObjects() context.evaluateString(scope, decryptionCode, "decryptionCode", 1, null) val decryptionFunc = scope.get("decrypt", scope) as Function result = decryptionFunc.call(context, scope, scope, arrayOf<Any>(encryptedSig)) } catch (e: Exception) { throw e } finally { Context.exit() } return result?.toString() ?: "" } }
youtubeextractor/src/main/java/com/commit451/youtubeextractor/JavaScriptUtil.kt
58809141
package com.eden.orchid.impl.themes.tags import com.eden.orchid.api.compilers.TemplateTag import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.impl.themes.breadcrumbs.Breadcrumb import com.eden.orchid.impl.themes.breadcrumbs.BreadcrumbStrategy import javax.inject.Inject @Description(value = "Generate the page's breadcrumbs.", name = "Breadcrumbs") class BreadcrumbsTag @Inject constructor( val strategy: BreadcrumbStrategy ) : TemplateTag("breadcrumbs", TemplateTag.Type.Simple, true) { override fun parameters(): Array<String> = emptyArray() val breadcrumbs: List<Breadcrumb> get() = strategy.getBreadcrumbs(page) }
OrchidCore/src/main/kotlin/com/eden/orchid/impl/themes/tags/BreadcrumbsTag.kt
875986228
package com.hosshan.android.salad.component.scene.splash import android.os.Bundle import com.hosshan.android.salad.R import com.hosshan.android.salad.component.scene.login.LoginActivity import com.hosshan.android.salad.component.scene.login.createIntent import com.hosshan.android.salad.component.scene.top.TopActivity import com.hosshan.android.salad.component.scene.top.createIntent import com.hosshan.android.salad.ext.start import com.trello.rxlifecycle.ActivityLifecycleProvider import com.trello.rxlifecycle.components.support.RxAppCompatActivity import javax.inject.Inject /** * SplashActivity */ class SplashActivity : RxAppCompatActivity(), SplashView { companion object {} @Inject internal lateinit var presenter: SplashPresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) SplashComponent.Initializer.init(this).inject(this) presenter.initialize(this) } override fun provideLifecycle(): ActivityLifecycleProvider = this override fun onError(throwable: Throwable) { } override fun onPostIntent(isLogin: Boolean) { if (isLogin) { LoginActivity.createIntent(this) } else { TopActivity.createIntent(this) }.start(this) finish() } }
app/src/main/kotlin/com/hosshan/android/salad/component/scene/splash/SplashActivity.kt
2775306861
package com.inaka.killertask import android.os.AsyncTask import android.util.Log class KillerTask<T>(val task: () -> T, val onSuccess: (T) -> Any = {}, val onFailed: (Exception?) -> Any = {}) : AsyncTask<Void, Void, T>() { private var exception: Exception? = null companion object { private val TAG = "KillerTask" } /** * Override AsyncTask's function doInBackground */ override fun doInBackground(vararg params: Void): T? { try { Log.wtf(TAG, "Enter to doInBackground") return run { task() } } catch (e: Exception) { Log.wtf(TAG, "Error in background task") exception = e return null } } /** * Override AsyncTask's function onPostExecute */ override fun onPostExecute(result: T) { Log.wtf(TAG, "Enter to onPostExecute") if (!isCancelled) { // task not cancelled if (exception != null) { // fail Log.wtf(TAG, "Failure with Exception") run { onFailed(exception) } } else { // success Log.wtf(TAG, "Success") run { onSuccess(result) } } } else { // task cancelled Log.wtf(TAG, "Failure with RuntimeException caused by task cancelled") run { onFailed(RuntimeException("Task was cancelled")) } } } /** * Execute AsyncTask */ fun go() { execute() } /** * Cancel AsyncTask */ fun cancel() { cancel(true) } }
library/src/main/java/com/inaka/killertask/KillerTask.kt
1434498058
package com.automation.remarks.kirk.core import org.openqa.selenium.JavascriptExecutor import org.openqa.selenium.WebDriver /** * Created by sergey on 04.07.17. */ class JsExecutor(private val driver: WebDriver) { @JvmOverloads fun execute(vararg args: Any, async: Boolean=false, script: () -> String): Any? { if (driver is JavascriptExecutor) { return when (async) { false -> driver.executeScript(script(), *args) else -> driver.executeAsyncScript(script(), *args) } } throw UnsupportedOperationException() } }
kirk-core/src/main/kotlin/com/automation/remarks/kirk/core/JsExecutor.kt
3514892150
package nu.peg.discord.command.handler.internal import nu.peg.discord.command.Command import nu.peg.discord.command.handler.CommandHandler import nu.peg.discord.service.OnlineStatus import nu.peg.discord.service.StatusService import org.springframework.stereotype.Component import javax.inject.Inject @Component class StatusMessageCommand @Inject constructor( private val statusService: StatusService ) : CommandHandler { override fun isAdminCommand() = true override fun getNames() = listOf("sm", "statusmessage") override fun getDescription() = "Sets the bot's status and message" override fun handle(command: Command) { val args = command.args val channel = command.message.channel val status = if (args.isNotEmpty()) { OnlineStatus.fromText(args.first()) } else null if (status == null) { channel.sendMessage("Usage: ${command.name} <online | afk | dnd> [message]") return } val message = if (args.size > 1) { args.sliceArray(1 until args.size).joinToString(" ") } else null statusService.setStatus(status, message) } }
discord-bot/src/main/kotlin/nu/peg/discord/command/handler/internal/StatusMessageCommand.kt
2305071095
package org.ctfcracktools.fuction class CodeMode { companion object{ const val CRYPTO_FENCE = "Fence" const val CRYPTO_CAESAR = "CaesarCode" const val CRYPTO_PIG = "PigCode" const val CRYPTO_ROT13 = "ROT13" const val CRYPTO_HEX_2_STRING = "Hex2String" const val CRYPTO_STRING_2_HEX = "String2Hex" const val CRYPTO_UNICODE_2_ASCII = "Unicode2Ascii" const val CRYPTO_ASCII_2_UNICODE = "Ascii2Unicode" const val CRYPTO_REVERSE = "Reverse" const val DECODE_MORSE = "MorseDecode" const val DECODE_BACON = "BaconDecode" const val DECODE_BASE64 = "Base64Decode" const val DECODE_BASE32 = "BASE32Decode" const val DECODE_URL = "UrlDecode" const val DECODE_UNICODE = "UnicodeDecode" const val DECODE_HTML = "HtmlDecode" const val DECODE_VIGENERE = "VigenereDeCode" const val ENCODE_MORSE = "MorseEncode" const val ENCODE_BACON = "BaconEncode" const val ENCODE_BASE64 = "Base64Encode" const val ENCODE_BASE32 = "Base32Encode" const val ENCODE_URL = "UrlEncode" const val ENCODE_UNICODE = "UnicodeEncode" const val ENCODE_HTML = "HtmlEncode" const val ENCODE_VIGENERE = "VigenereEnCode" } }
src/org/ctfcracktools/fuction/CodeMode.kt
3143143392
package com.gchoy.weatherfetcher.zipcode import android.os.Parcel import android.os.Parcelable /** * Representation of a zipcode per OpenWeatherMap. * Most analogous to a City. */ data class Zipcode(val name: String, val zipcode: String, val longitutde: Double, val latitude: Double) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString(), parcel.readString(), parcel.readDouble(), parcel.readDouble()) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(name) parcel.writeString(zipcode) parcel.writeDouble(longitutde) parcel.writeDouble(latitude) } override fun describeContents(): Int { return 0 } override fun equals(other: Any?): Boolean { if (other is Zipcode) { return this.zipcode == other.zipcode } return false } override fun hashCode(): Int = this.zipcode.hashCode() companion object CREATOR : Parcelable.Creator<Zipcode> { override fun createFromParcel(parcel: Parcel): Zipcode { return Zipcode(parcel) } override fun newArray(size: Int): Array<Zipcode?> { return arrayOfNulls(size) } } }
app/src/main/java/com/gchoy/weatherfetcher/zipcode/Zipcode.kt
3075875696
package test import org.assertj.core.api.Assertions.assertThat import org.testng.* import org.testng.annotations.ITestAnnotation import org.testng.internal.annotations.AnnotationHelper import org.testng.internal.annotations.DefaultAnnotationTransformer import org.testng.internal.annotations.IAnnotationFinder import org.testng.internal.annotations.JDK15AnnotationFinder import org.testng.xml.* import org.testng.xml.internal.Parser import java.io.* import java.nio.file.FileVisitResult import java.nio.file.Files import java.nio.file.Path import java.nio.file.SimpleFileVisitor import java.util.* import java.util.concurrent.atomic.AtomicInteger import java.util.regex.Pattern import java.util.stream.Collectors open class SimpleBaseTest { companion object { private const val TEST_RESOURCES_DIR = "test.resources.dir" @JvmStatic fun run(vararg testClasses: Class<*>) = run(false, *testClasses) @JvmStatic fun run(skipConfiguration: Boolean, tng: TestNG) = InvokedMethodNameListener(skipConfiguration).apply { tng.addListener(this) tng.run() } @JvmStatic fun run(skipConfiguration: Boolean, vararg testClasses: Class<*>) = run(skipConfiguration, create(*testClasses)) @JvmStatic fun create(vararg testClasses: Class<*>) = create().apply { setTestClasses(testClasses) } @JvmStatic fun create() = TestNG().apply { setUseDefaultListeners(false) } @JvmStatic fun create(xmlSuite: XmlSuite) = create().apply { setXmlSuites(listOf(xmlSuite)) } @JvmStatic fun run(vararg suites: XmlSuite): InvokedMethodNameListener = run(false, *suites) @JvmStatic fun run(skipConfiguration: Boolean, vararg suites: XmlSuite) = run(skipConfiguration, create(*suites)) @JvmStatic protected fun create(outputDir: Path, vararg testClasses: Class<*>) = create(*testClasses).apply { outputDirectory = outputDir.toAbsolutePath().toString() } @JvmStatic protected fun create(vararg suites: XmlSuite) = create(listOf(*suites)) @JvmStatic protected fun create(suites: List<XmlSuite>) = create().apply { setXmlSuites(suites) } @JvmStatic protected fun create(outputDir: Path, vararg suites: XmlSuite) = create(outputDir, listOf(*suites)) @JvmStatic protected fun create(outputDir: Path, suites: List<XmlSuite>) = create(suites).apply { outputDirectory = outputDir.toAbsolutePath().toString() } @JvmStatic protected fun createTests(suiteName: String, vararg testClasses: Class<*>) = createTests(null, suiteName, *testClasses) @JvmStatic protected fun createTests( outDir: Path?, suiteName: String, vararg testClasses: Class<*> ) = createXmlSuite(suiteName).let { suite -> for ((i, testClass) in testClasses.withIndex()) { createXmlTest(suite, testClass.name + i, testClass) } //if outDir is not null then create suite with outDir, else create suite without it. outDir?.let { create(it, suite) } ?: create(suite) } @JvmStatic protected fun createDummySuiteWithTestNamesAs(vararg tests: String) = XmlSuite().apply { name = "random_suite" tests.forEach { XmlTest(this).apply { name = it } } } @JvmStatic protected fun createXmlSuite(name: String) = XmlSuite().apply { this.name = name } @JvmStatic protected fun createXmlSuite(params: Map<String, String>) = createXmlSuite(UUID.randomUUID().toString()).apply { parameters = params } @JvmStatic protected fun createXmlSuite( suiteName: String, testName: String, vararg classes: Class<*> ) = createXmlSuite(suiteName).apply { createXmlTest(this, testName, *classes) } @JvmStatic protected fun createXmlSuite(suiteName: String, params: Map<String, String>) = createXmlSuite(suiteName).apply { parameters = params } @JvmStatic protected fun createXmlTestWithPackages( suite: XmlSuite, name: String, vararg packageName: String ) = createXmlTest(suite, name).apply { packages = packageName.map { XmlPackage().apply { this.name = it } }.toMutableList() } @JvmStatic protected fun createXmlTestWithPackages( suite: XmlSuite, name: String, vararg packageName: Class<*> ) = createXmlTest(suite, name).apply { packages = packageName.map { XmlPackage().apply { this.name = it.`package`.name } }.toMutableList() } @JvmStatic protected fun createXmlTest(suiteName: String, testName: String) = createXmlTest(createXmlSuite(suiteName), testName) @JvmStatic protected fun createXmlTest( suiteName: String, testName: String, vararg classes: Class<*> ) = createXmlTest(createXmlSuite(suiteName), testName).apply { classes.forEach { xmlClasses.add(XmlClass(it)) } } @JvmStatic protected fun createXmlTest(suite: XmlSuite, name: String) = XmlTest(suite).apply { this.name = name } @JvmStatic protected fun createXmlTest( suite: XmlSuite, name: String, params: Map<String, String> ) = XmlTest(suite).apply { this.name = name setParameters(params) } @JvmStatic protected fun createXmlTest( suite: XmlSuite, name: String, vararg classes: Class<*> ) = createXmlTest(suite, name).apply { for ((index, c) in classes.withIndex()) { val xc = XmlClass(c.name, index, true /* load classes */) xmlClasses.add(xc) } } @JvmStatic protected fun createXmlClass(test: XmlTest, testClass: Class<*>) = XmlClass(testClass).apply { test.xmlClasses.add(this) } @JvmStatic protected fun createXmlClass( test: XmlTest, testClass: Class<*>, params: Map<String, String> ) = createXmlClass(test, testClass).apply { setParameters(params) } @JvmStatic protected fun createXmlInclude(clazz: XmlClass, method: String) = XmlInclude(method).apply { setXmlClass(clazz) clazz.includedMethods.add(this) } @JvmStatic protected fun createXmlInclude( clazz: XmlClass, method: String, params: Map<String, String> ) = createXmlInclude(clazz, method).apply { setParameters(params) } @JvmStatic protected fun createXmlInclude( clazz: XmlClass, method: String, index: Int, vararg list: Int ) = XmlInclude(method, list.asList(), index).apply { setXmlClass(clazz) clazz.includedMethods.add(this) } @JvmStatic protected fun createXmlGroups( suite: XmlSuite, vararg includedGroupNames: String ) = createGroupIncluding(*includedGroupNames).apply { suite.groups = this } @JvmStatic protected fun createXmlGroups( test: XmlTest, vararg includedGroupNames: String ) = createGroupIncluding(*includedGroupNames).apply { test.setGroups(this) } @JvmStatic private fun createGroupIncluding(vararg groupNames: String) = XmlGroups().apply { run = XmlRun().apply { groupNames.forEach { onInclude(it) } } } @JvmStatic protected fun createXmlTest( suite: XmlSuite, name: String, vararg classes: String ) = createXmlTest(suite, name).apply { for ((index, c) in classes.withIndex()) { val xc = XmlClass(c, index, true /* load classes */) xmlClasses.add(xc) } } @JvmStatic protected fun addMethods(cls: XmlClass, vararg methods: String) { for ((index, method) in methods.withIndex()) { cls.includedMethods.add(XmlInclude(method, index)) } } @JvmStatic fun getPathToResource(fileName: String): String { val result = System.getProperty(TEST_RESOURCES_DIR, "src/test/resources") ?: throw IllegalArgumentException( "System property $TEST_RESOURCES_DIR was not defined." ) return result + File.separatorChar + fileName } @JvmStatic fun extractTestNGMethods(vararg classes: Class<*>): List<ITestNGMethod> = XmlSuite().let { xmlSuite -> xmlSuite.name = "suite" val xmlTest = createXmlTest(xmlSuite, "tests", *classes) val annotationFinder: IAnnotationFinder = JDK15AnnotationFinder(DefaultAnnotationTransformer()) classes.flatMap { clazz -> AnnotationHelper.findMethodsWithAnnotation( object : ITestObjectFactory {}, clazz, ITestAnnotation::class.java, annotationFinder, xmlTest ).toMutableList() } } /** Compare a list of ITestResult with a list of String method names, */ @JvmStatic protected fun assertTestResultsEqual(results: List<ITestResult>, methods: List<String>) { results.map { it.method.methodName } .toList() .run { assertThat(this).containsAll(methods) } } /** Deletes all files and subdirectories under dir. */ @JvmStatic protected fun deleteDir(dir: File): Path = Files.walkFileTree(dir.toPath(), TestNGFileVisitor()) @JvmStatic protected fun createDirInTempDir(dir: String): File = Files.createTempDirectory(dir) .toFile().apply { deleteOnExit() } /** * @param fileName The filename to parse * @param regexp The regular expression * @param resultLines An out parameter that will contain all the lines that matched the regexp * @return A List<Integer> containing the lines of all the matches * * Note that the size() of the returned valuewill always be equal to result.size() at the * end of this function. </Integer> */ @JvmStatic protected fun grep( fileName: File, regexp: String, resultLines: MutableList<String> ) = grep(FileReader(fileName), regexp, resultLines) @JvmStatic protected fun grep( reader: Reader, regexp: String, resultLines: MutableList<String> ): List<Int> { val resultLineNumbers = mutableListOf<Int>() val p = Pattern.compile(".*$regexp.*") val counter = AtomicInteger(-1) BufferedReader(reader).lines() .peek { counter.getAndIncrement() } .filter { line -> p.matcher(line).matches() } .forEach { resultLines.add(it) resultLineNumbers.add(counter.get()) } return resultLineNumbers } @JvmStatic protected fun getSuites(vararg suiteFiles: String) = suiteFiles.map { Parser(it) } .flatMap { it.parseToList() } .toList() @JvmStatic protected fun getFailedResultMessage(testResultList: List<ITestResult>): String { val methods = testResultList.stream() .map { r: ITestResult -> AbstractMap.SimpleEntry( r.method.qualifiedName, r.throwable ) } .map { (key, value): AbstractMap.SimpleEntry<String?, Throwable?> -> "$key: $value" } .collect(Collectors.joining("\n")) return "Failed methods should pass: \n $methods" } } class TestNGFileVisitor : SimpleFileVisitor<Path>() { @Throws(IOException::class) override fun postVisitDirectory( dir: Path, exc: IOException? ): FileVisitResult { dir.toFile().deleteRecursively() return FileVisitResult.CONTINUE } } }
testng-core/src/test/kotlin/test/SimpleBaseTest.kt
4285227744
package vi_generics.generics import java.util.ArrayList import java.util.HashSet import util.TODO fun task28() = TODO( """ Task28. Add a 'partitionTo' function that splits a collection into two collections according to a predicate. Uncomment the commented invocations of 'partitionTo' below and make them compile. There is a 'partition()' function in the standard library that always returns two newly created lists. You should write a function that splits the collection into two collections given as arguments. The signature of the 'toCollection()' function from the standard library may help you. """, references = { l: List<Int> -> l.partition { it > 0 } l.toCollection(HashSet<Int>()) } ) fun List<String>.partitionWordsAndLines(): Pair<List<String>, List<String>> { task28() // return partitionTo(ArrayList<String>(), ArrayList()) { s -> !s.contains(" ") } } fun Set<Char>.partitionLettersAndOtherSymbols(): Pair<Set<Char>, Set<Char>> { task28() // return partitionTo(HashSet<Char>(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z'} }
src/vi_generics/_28_GenericFunctions.kt
1449162536
package de.devmil.muzei.bingimageoftheday import android.app.PendingIntent import android.content.ClipData import android.content.ContentResolver import android.content.ContentUris import android.content.Context import android.content.Intent import android.net.Uri import android.util.Log import androidx.core.app.RemoteActionCompat import androidx.core.graphics.drawable.IconCompat import com.google.android.apps.muzei.api.provider.Artwork import com.google.android.apps.muzei.api.provider.MuzeiArtProvider import de.devmil.common.utils.LogUtil import de.devmil.muzei.bingimageoftheday.events.RequestMarketSettingChangedEvent import de.devmil.muzei.bingimageoftheday.events.RequestPortraitSettingChangedEvent import de.devmil.muzei.bingimageoftheday.worker.BingImageOfTheDayWorker import de.greenrobot.event.EventBus import java.io.InputStream class BingImageOfTheDayArtProvider : MuzeiArtProvider() { /** * This class is used to get EventBus events even if there is no instance of BingImageOfTheDayArtSource */ class EventCatcher { init { EventBus.getDefault().register(this) } fun onEventBackgroundThread(e: RequestPortraitSettingChangedEvent) { requestUpdate(e.context) } fun onEventBackgroundThread(e: RequestMarketSettingChangedEvent) { requestUpdate(e.context) } private fun requestUpdate(context: Context) { doUpdate() } } companion object { private const val TAG = "BingImageOfTheDayArtPro" private val COMMAND_ID_SHARE = 2 private var CatcherInstance: BingImageOfTheDayArtProvider.EventCatcher? = null init { //instantiate the EventCatcher when BingImageOfTheDayArtSource is loaded CatcherInstance = BingImageOfTheDayArtProvider.EventCatcher() } private var _isActive: Boolean? = null var isActive: Boolean? get() = _isActive private set(value) { _isActive = value } fun doUpdate() { BingImageOfTheDayWorker.enqueueLoad() } } /* kept for backward compatibility with Muzei 3.3 */ @Suppress("OverridingDeprecatedMember", "DEPRECATION") override fun getCommands(artwork: Artwork) = listOf( com.google.android.apps.muzei.api.UserCommand(COMMAND_ID_SHARE, context?.getString(R.string.command_share_title) ?: "Share")) /* kept for backward compatibility with Muzei 3.3 */ @Suppress("OverridingDeprecatedMember") override fun onCommand(artwork: Artwork, id: Int) { val context = context ?: return if(id == COMMAND_ID_SHARE) { shareCurrentImage(context, artwork) } } override fun onLoadRequested(initial: Boolean) { isActive = true BingImageOfTheDayWorker.enqueueLoad() } override fun openFile(artwork: Artwork): InputStream { Log.d(TAG, "Loading artwork: ${artwork.title} (${artwork.persistentUri})") return super.openFile(artwork) } private fun createShareIntent(context: Context, artwork: Artwork): Intent { LogUtil.LOGD(TAG, "got share request") val shareIntent = Intent(Intent.ACTION_SEND).apply { val shareMessage = context.getString(R.string.command_share_message, artwork.byline) putExtra(Intent.EXTRA_TEXT, "$shareMessage - ${artwork.webUri.toString()}") val contentUri = Uri.Builder() .scheme(ContentResolver.SCHEME_CONTENT) .authority("de.devmil.muzei.bingimageoftheday.provider.BingImages") .build() val uri = ContentUris.withAppendedId(contentUri, artwork.id) putExtra(Intent.EXTRA_TITLE, artwork.byline) putExtra(Intent.EXTRA_STREAM, uri) type = context.contentResolver.getType(uri) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) clipData = ClipData.newUri(context.contentResolver, artwork.byline, uri) } return Intent.createChooser(shareIntent, context.getString(R.string.command_share_title)) } private fun shareCurrentImage(context: Context, artwork: Artwork) { LogUtil.LOGD(TAG, "Sharing ${artwork.webUri}") val shareIntent = createShareIntent(context, artwork) shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(shareIntent) } /* Used by Muzei 3.4+ */ override fun getCommandActions(artwork: Artwork): List<RemoteActionCompat> { val context = context ?: return super.getCommandActions(artwork) return listOf( RemoteActionCompat( IconCompat.createWithResource(context, R.drawable.ic_share), context.getString(R.string.command_share_title), context.getString(R.string.command_share_title), PendingIntent.getActivity(context, artwork.id.toInt(), createShareIntent(context, artwork), PendingIntent.FLAG_UPDATE_CURRENT)) ) } override fun getArtworkInfo(artwork: Artwork): PendingIntent? { LogUtil.LOGD(TAG, "Opening ${artwork.webUri}") return super.getArtworkInfo(artwork) } }
app/src/main/java/de/devmil/muzei/bingimageoftheday/BingImageOfTheDayArtProvider.kt
352090354
package com.neva.javarel.gradle.internal.file import net.schmizz.sshj.SSHClient import net.schmizz.sshj.sftp.OpenMode import net.schmizz.sshj.sftp.SFTPClient import org.apache.http.client.utils.URIBuilder import org.gradle.api.Project import org.gradle.api.logging.Logger import java.io.File class SftpFileDownloader(val project: Project) { companion object { fun handles(sourceUrl: String): Boolean { return !sourceUrl.isNullOrBlank() && sourceUrl.startsWith("sftp://") } } var username: String? = null var password: String? = null var hostChecking: Boolean = false val logger: Logger = project.logger fun download(sourceUrl: String, targetFile: File) { try { val url = URIBuilder(sourceUrl) val downloader = ProgressFileDownloader(project) downloader.headerSourceTarget(sourceUrl, targetFile) connect(url, { sftp -> val size = sftp.stat(url.path).size val input = sftp.open(url.path, setOf(OpenMode.READ)).RemoteFileInputStream() downloader.size = size downloader.download(input, targetFile) }) } catch (e: Exception) { throw FileDownloadException("Cannot download URL '$sourceUrl' to file '$targetFile' using SFTP. Check connection.", e) } } private fun connect(url: URIBuilder, action: (SFTPClient) -> Unit) { val ssh = SSHClient() ssh.loadKnownHosts() if (!hostChecking) { ssh.addHostKeyVerifier({ _, _, _ -> true }) } val user = if (!username.isNullOrBlank()) username else url.userInfo val port = if (url.port >= 0) url.port else 22 ssh.connect(url.host, port) try { authenticate(mapOf( "public key" to { ssh.authPublickey(user) }, "password" to { ssh.authPassword(user, password) } )) ssh.newSFTPClient().use(action) } finally { ssh.disconnect() } } private fun authenticate(methods: Map<String, () -> Unit>) { for ((name, method) in methods) { try { method() logger.info("Authenticated using method: $name") return } catch (e: Exception) { logger.debug("Cannot authenticate using method: $name", e) } } } }
tooling/gradle-plugin/src/main/kotlin/com/neva/javarel/gradle/internal/file/SftpFileDownloader.kt
3171633559
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.manager import android.Manifest import android.app.role.RoleManager import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.provider.Telephony import androidx.core.content.ContextCompat import javax.inject.Inject class PermissionManagerImpl @Inject constructor(private val context: Context) : PermissionManager { override fun isDefaultSms(): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { context.getSystemService(RoleManager::class.java)?.isRoleHeld(RoleManager.ROLE_SMS) == true } else { Telephony.Sms.getDefaultSmsPackage(context) == context.packageName } } override fun hasReadSms(): Boolean { return hasPermission(Manifest.permission.READ_SMS) } override fun hasSendSms(): Boolean { return hasPermission(Manifest.permission.SEND_SMS) } override fun hasContacts(): Boolean { return hasPermission(Manifest.permission.READ_CONTACTS) } override fun hasPhone(): Boolean { return hasPermission(Manifest.permission.READ_PHONE_STATE) } override fun hasCalling(): Boolean { return hasPermission(Manifest.permission.CALL_PHONE) } override fun hasStorage(): Boolean { return hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) } private fun hasPermission(permission: String): Boolean { return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED } }
data/src/main/java/com/moez/QKSMS/manager/PermissionManagerImpl.kt
1805622650
package com.openlattice.hazelcast.processors import com.kryptnostic.rhizome.hazelcast.processors.AbstractRhizomeEntryProcessor import com.openlattice.edm.EntitySet import java.util.UUID class RemoveEntitySetsFromLinkingEntitySetProcessor(val entitySetIds: Set<UUID>) : AbstractRhizomeEntryProcessor<UUID, EntitySet, EntitySet>() { companion object { private const val serialVersionUID = -6602384557982347L } override fun process(entry: MutableMap.MutableEntry<UUID, EntitySet?>): EntitySet { val entitySet = entry.value entitySet!!.linkedEntitySets.removeAll(entitySetIds) // shouldn't be null at this point entry.setValue(entitySet) return entitySet } override fun hashCode(): Int { val prime = 53 return prime + entitySetIds.hashCode() } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class.java != other::class.java) return false val otherProcessor = other as (RemoveEntitySetsFromLinkingEntitySetProcessor) if (entitySetIds != otherProcessor.entitySetIds) return false return true } }
src/main/kotlin/com/openlattice/hazelcast/processors/RemoveEntitySetsFromLinkingEntitySetProcessor.kt
1457449547
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.MultiRule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.rules.SubRule import io.gitlab.arturbosch.detekt.rules.reportFindings import org.jetbrains.kotlin.psi.KtFile class FileParsingRule(val config: Config = Config.empty) : MultiRule() { override val rules = listOf(MaxLineLength(config)) override fun visitKtFile(file: KtFile) { val lines = file.text.splitToSequence("\n") val fileContents = KtFileContent(file, lines) fileContents.reportFindings(context, rules) } } abstract class File(open val file: KtFile) data class KtFileContent(override val file: KtFile, val content: Sequence<String>) : File(file) class MaxLineLength(config: Config = Config.empty) : SubRule<KtFileContent>(config) { override val issue = Issue(javaClass.simpleName, Severity.Style, "Line detected that is longer than the defined maximum line length in the code style.", Debt.FIVE_MINS) private val maxLineLength: Int = valueOrDefault(MaxLineLength.MAX_LINE_LENGTH, MaxLineLength.DEFAULT_IDEA_LINE_LENGTH) private val excludePackageStatements: Boolean = valueOrDefault(MaxLineLength.EXCLUDE_PACKAGE_STATEMENTS, MaxLineLength.DEFAULT_VALUE_PACKAGE_EXCLUDE) private val excludeImportStatements: Boolean = valueOrDefault(MaxLineLength.EXCLUDE_IMPORT_STATEMENTS, MaxLineLength.DEFAULT_VALUE_IMPORTS_EXCLUDE) override fun apply(element: KtFileContent) { var offset = 0 val lines = element.content val file = element.file lines.filter { filterPackageStatements(it) } .filter { filterImportStatements(it) } .map { it.length } .forEach { offset += it if (it > maxLineLength) { report(CodeSmell(issue, Entity.from(file, offset))) } } } private fun filterPackageStatements(line: String): Boolean { if (excludePackageStatements) { return !line.trim().startsWith("package ") } return true } private fun filterImportStatements(line: String): Boolean { if (excludeImportStatements) { return !line.trim().startsWith("import ") } return true } companion object { const val MAX_LINE_LENGTH = "maxLineLength" const val DEFAULT_IDEA_LINE_LENGTH = 120 const val EXCLUDE_PACKAGE_STATEMENTS = "excludePackageStatements" const val DEFAULT_VALUE_PACKAGE_EXCLUDE = false const val EXCLUDE_IMPORT_STATEMENTS = "excludeImportStatements" const val DEFAULT_VALUE_IMPORTS_EXCLUDE = false } }
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/FileParsingRule.kt
3673157032
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.common.util.extensions import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView fun RecyclerView.Adapter<*>.autoScrollToStart(recyclerView: RecyclerView) { registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return if (layoutManager.stackFromEnd) { if (positionStart > 0) { notifyItemChanged(positionStart - 1) } val lastPosition = layoutManager.findLastVisibleItemPosition() if (positionStart >= getItemCount() - 1 && lastPosition == positionStart - 1) { recyclerView.scrollToPosition(positionStart) } } else { val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition() if (firstVisiblePosition == 0) { recyclerView.scrollToPosition(positionStart) } } } override fun onItemRangeChanged(positionStart: Int, itemCount: Int) { val layoutManager = recyclerView.layoutManager as? LinearLayoutManager ?: return if (!layoutManager.stackFromEnd) { onItemRangeInserted(positionStart, itemCount) } } }) }
presentation/src/main/java/com/moez/QKSMS/common/util/extensions/AdapterExtensions.kt
3278194360
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.feature.main import androidx.recyclerview.widget.ItemTouchHelper import com.moez.QKSMS.R import com.moez.QKSMS.common.Navigator import com.moez.QKSMS.common.base.QkViewModel import com.moez.QKSMS.extensions.mapNotNull import com.moez.QKSMS.interactor.DeleteConversations import com.moez.QKSMS.interactor.MarkAllSeen import com.moez.QKSMS.interactor.MarkArchived import com.moez.QKSMS.interactor.MarkPinned import com.moez.QKSMS.interactor.MarkRead import com.moez.QKSMS.interactor.MarkUnarchived import com.moez.QKSMS.interactor.MarkUnpinned import com.moez.QKSMS.interactor.MarkUnread import com.moez.QKSMS.interactor.MigratePreferences import com.moez.QKSMS.interactor.SyncContacts import com.moez.QKSMS.interactor.SyncMessages import com.moez.QKSMS.listener.ContactAddedListener import com.moez.QKSMS.manager.BillingManager import com.moez.QKSMS.manager.ChangelogManager import com.moez.QKSMS.manager.PermissionManager import com.moez.QKSMS.manager.RatingManager import com.moez.QKSMS.model.SyncLog import com.moez.QKSMS.repository.ConversationRepository import com.moez.QKSMS.repository.SyncRepository import com.moez.QKSMS.util.Preferences import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.autoDisposable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.withLatestFrom import io.reactivex.schedulers.Schedulers import io.realm.Realm import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject class MainViewModel @Inject constructor( billingManager: BillingManager, contactAddedListener: ContactAddedListener, markAllSeen: MarkAllSeen, migratePreferences: MigratePreferences, syncRepository: SyncRepository, private val changelogManager: ChangelogManager, private val conversationRepo: ConversationRepository, private val deleteConversations: DeleteConversations, private val markArchived: MarkArchived, private val markPinned: MarkPinned, private val markRead: MarkRead, private val markUnarchived: MarkUnarchived, private val markUnpinned: MarkUnpinned, private val markUnread: MarkUnread, private val navigator: Navigator, private val permissionManager: PermissionManager, private val prefs: Preferences, private val ratingManager: RatingManager, private val syncContacts: SyncContacts, private val syncMessages: SyncMessages ) : QkViewModel<MainView, MainState>(MainState(page = Inbox(data = conversationRepo.getConversations()))) { init { disposables += deleteConversations disposables += markAllSeen disposables += markArchived disposables += markUnarchived disposables += migratePreferences disposables += syncContacts disposables += syncMessages // Show the syncing UI disposables += syncRepository.syncProgress .sample(16, TimeUnit.MILLISECONDS) .distinctUntilChanged() .subscribe { syncing -> newState { copy(syncing = syncing) } } // Update the upgraded status disposables += billingManager.upgradeStatus .subscribe { upgraded -> newState { copy(upgraded = upgraded) } } // Show the rating UI disposables += ratingManager.shouldShowRating .subscribe { show -> newState { copy(showRating = show) } } // Migrate the preferences from 2.7.3 migratePreferences.execute(Unit) // If we have all permissions and we've never run a sync, run a sync. This will be the case // when upgrading from 2.7.3, or if the app's data was cleared val lastSync = Realm.getDefaultInstance().use { realm -> realm.where(SyncLog::class.java)?.max("date") ?: 0 } if (lastSync == 0 && permissionManager.isDefaultSms() && permissionManager.hasReadSms() && permissionManager.hasContacts()) { syncMessages.execute(Unit) } // Sync contacts when we detect a change if (permissionManager.hasContacts()) { disposables += contactAddedListener.listen() .debounce(1, TimeUnit.SECONDS) .subscribeOn(Schedulers.io()) .subscribe { syncContacts.execute(Unit) } } ratingManager.addSession() markAllSeen.execute(Unit) } override fun bindView(view: MainView) { super.bindView(view) when { !permissionManager.isDefaultSms() -> view.requestDefaultSms() !permissionManager.hasReadSms() || !permissionManager.hasContacts() -> view.requestPermissions() } val permissions = view.activityResumedIntent .filter { resumed -> resumed } .observeOn(Schedulers.io()) .map { Triple(permissionManager.isDefaultSms(), permissionManager.hasReadSms(), permissionManager.hasContacts()) } .distinctUntilChanged() .share() // If the default SMS state or permission states change, update the ViewState permissions .doOnNext { (defaultSms, smsPermission, contactPermission) -> newState { copy(defaultSms = defaultSms, smsPermission = smsPermission, contactPermission = contactPermission) } } .autoDisposable(view.scope()) .subscribe() // If we go from not having all permissions to having them, sync messages permissions .skip(1) .filter { it.first && it.second && it.third } .take(1) .autoDisposable(view.scope()) .subscribe { syncMessages.execute(Unit) } // Launch screen from intent view.onNewIntentIntent .autoDisposable(view.scope()) .subscribe { intent -> when (intent.getStringExtra("screen")) { "compose" -> navigator.showConversation(intent.getLongExtra("threadId", 0)) "blocking" -> navigator.showBlockedConversations() } } // Show changelog if (changelogManager.didUpdate()) { if (Locale.getDefault().language.startsWith("en")) { GlobalScope.launch(Dispatchers.Main) { val changelog = changelogManager.getChangelog() changelogManager.markChangelogSeen() view.showChangelog(changelog) } } else { changelogManager.markChangelogSeen() } } else { changelogManager.markChangelogSeen() } view.changelogMoreIntent .autoDisposable(view.scope()) .subscribe { navigator.showChangelog() } view.queryChangedIntent .debounce(200, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .withLatestFrom(state) { query, state -> if (query.isEmpty() && state.page is Searching) { newState { copy(page = Inbox(data = conversationRepo.getConversations())) } } query } .filter { query -> query.length >= 2 } .map { query -> query.trim() } .distinctUntilChanged() .doOnNext { newState { val page = (page as? Searching) ?: Searching() copy(page = page.copy(loading = true)) } } .observeOn(Schedulers.io()) .map(conversationRepo::searchConversations) .autoDisposable(view.scope()) .subscribe { data -> newState { copy(page = Searching(loading = false, data = data)) } } view.activityResumedIntent .filter { resumed -> !resumed } .switchMap { // Take until the activity is resumed prefs.keyChanges .filter { key -> key.contains("theme") } .map { true } .mergeWith(prefs.autoColor.asObservable().skip(1)) .doOnNext { view.themeChanged() } .takeUntil(view.activityResumedIntent.filter { resumed -> resumed }) } .autoDisposable(view.scope()) .subscribe() view.composeIntent .autoDisposable(view.scope()) .subscribe { navigator.showCompose() } view.homeIntent .withLatestFrom(state) { _, state -> when { state.page is Searching -> view.clearSearch() state.page is Inbox && state.page.selected > 0 -> view.clearSelection() state.page is Archived && state.page.selected > 0 -> view.clearSelection() else -> newState { copy(drawerOpen = true) } } } .autoDisposable(view.scope()) .subscribe() view.drawerOpenIntent .autoDisposable(view.scope()) .subscribe { open -> newState { copy(drawerOpen = open) } } view.navigationIntent .withLatestFrom(state) { drawerItem, state -> newState { copy(drawerOpen = false) } when (drawerItem) { NavItem.BACK -> when { state.drawerOpen -> Unit state.page is Searching -> view.clearSearch() state.page is Inbox && state.page.selected > 0 -> view.clearSelection() state.page is Archived && state.page.selected > 0 -> view.clearSelection() state.page !is Inbox -> { newState { copy(page = Inbox(data = conversationRepo.getConversations())) } } else -> newState { copy(hasError = true) } } NavItem.BACKUP -> navigator.showBackup() NavItem.SCHEDULED -> navigator.showScheduled() NavItem.BLOCKING -> navigator.showBlockedConversations() NavItem.SETTINGS -> navigator.showSettings() NavItem.PLUS -> navigator.showQksmsPlusActivity("main_menu") NavItem.HELP -> navigator.showSupport() NavItem.INVITE -> navigator.showInvite() else -> Unit } drawerItem } .distinctUntilChanged() .doOnNext { drawerItem -> when (drawerItem) { NavItem.INBOX -> newState { copy(page = Inbox(data = conversationRepo.getConversations())) } NavItem.ARCHIVED -> newState { copy(page = Archived(data = conversationRepo.getConversations(true))) } else -> Unit } } .autoDisposable(view.scope()) .subscribe() view.optionsItemIntent .filter { itemId -> itemId == R.id.archive } .withLatestFrom(view.conversationsSelectedIntent) { _, conversations -> markArchived.execute(conversations) view.clearSelection() } .autoDisposable(view.scope()) .subscribe() view.optionsItemIntent .filter { itemId -> itemId == R.id.unarchive } .withLatestFrom(view.conversationsSelectedIntent) { _, conversations -> markUnarchived.execute(conversations) view.clearSelection() } .autoDisposable(view.scope()) .subscribe() view.optionsItemIntent .filter { itemId -> itemId == R.id.delete } .filter { permissionManager.isDefaultSms().also { if (!it) view.requestDefaultSms() } } .withLatestFrom(view.conversationsSelectedIntent) { _, conversations -> view.showDeleteDialog(conversations) } .autoDisposable(view.scope()) .subscribe() view.optionsItemIntent .filter { itemId -> itemId == R.id.add } .withLatestFrom(view.conversationsSelectedIntent) { _, conversations -> conversations } .doOnNext { view.clearSelection() } .filter { conversations -> conversations.size == 1 } .map { conversations -> conversations.first() } .mapNotNull(conversationRepo::getConversation) .map { conversation -> conversation.recipients } .mapNotNull { recipients -> recipients[0]?.address?.takeIf { recipients.size == 1 } } .doOnNext(navigator::addContact) .autoDisposable(view.scope()) .subscribe() view.optionsItemIntent .filter { itemId -> itemId == R.id.pin } .withLatestFrom(view.conversationsSelectedIntent) { _, conversations -> markPinned.execute(conversations) view.clearSelection() } .autoDisposable(view.scope()) .subscribe() view.optionsItemIntent .filter { itemId -> itemId == R.id.unpin } .withLatestFrom(view.conversationsSelectedIntent) { _, conversations -> markUnpinned.execute(conversations) view.clearSelection() } .autoDisposable(view.scope()) .subscribe() view.optionsItemIntent .filter { itemId -> itemId == R.id.read } .filter { permissionManager.isDefaultSms().also { if (!it) view.requestDefaultSms() } } .withLatestFrom(view.conversationsSelectedIntent) { _, conversations -> markRead.execute(conversations) view.clearSelection() } .autoDisposable(view.scope()) .subscribe() view.optionsItemIntent .filter { itemId -> itemId == R.id.unread } .filter { permissionManager.isDefaultSms().also { if (!it) view.requestDefaultSms() } } .withLatestFrom(view.conversationsSelectedIntent) { _, conversations -> markUnread.execute(conversations) view.clearSelection() } .autoDisposable(view.scope()) .subscribe() view.optionsItemIntent .filter { itemId -> itemId == R.id.block } .withLatestFrom(view.conversationsSelectedIntent) { _, conversations -> view.showBlockingDialog(conversations, true) view.clearSelection() } .autoDisposable(view.scope()) .subscribe() view.plusBannerIntent .autoDisposable(view.scope()) .subscribe { newState { copy(drawerOpen = false) } navigator.showQksmsPlusActivity("main_banner") } view.rateIntent .autoDisposable(view.scope()) .subscribe { navigator.showRating() ratingManager.rate() } view.dismissRatingIntent .autoDisposable(view.scope()) .subscribe { ratingManager.dismiss() } view.conversationsSelectedIntent .withLatestFrom(state) { selection, state -> val conversations = selection.mapNotNull(conversationRepo::getConversation) val add = conversations.firstOrNull() ?.takeIf { conversations.size == 1 } ?.takeIf { conversation -> conversation.recipients.size == 1 } ?.recipients?.first() ?.takeIf { recipient -> recipient.contact == null } != null val pin = conversations.sumBy { if (it.pinned) -1 else 1 } >= 0 val read = conversations.sumBy { if (!it.unread) -1 else 1 } >= 0 val selected = selection.size when (state.page) { is Inbox -> { val page = state.page.copy(addContact = add, markPinned = pin, markRead = read, selected = selected) newState { copy(page = page) } } is Archived -> { val page = state.page.copy(addContact = add, markPinned = pin, markRead = read, selected = selected) newState { copy(page = page) } } } } .autoDisposable(view.scope()) .subscribe() // Delete the conversation view.confirmDeleteIntent .autoDisposable(view.scope()) .subscribe { conversations -> deleteConversations.execute(conversations) view.clearSelection() } view.swipeConversationIntent .autoDisposable(view.scope()) .subscribe { (threadId, direction) -> val action = if (direction == ItemTouchHelper.RIGHT) prefs.swipeRight.get() else prefs.swipeLeft.get() when (action) { Preferences.SWIPE_ACTION_ARCHIVE -> markArchived.execute(listOf(threadId)) { view.showArchivedSnackbar() } Preferences.SWIPE_ACTION_DELETE -> view.showDeleteDialog(listOf(threadId)) Preferences.SWIPE_ACTION_BLOCK -> view.showBlockingDialog(listOf(threadId), true) Preferences.SWIPE_ACTION_CALL -> conversationRepo.getConversation(threadId)?.recipients?.firstOrNull()?.address?.let(navigator::makePhoneCall) Preferences.SWIPE_ACTION_READ -> markRead.execute(listOf(threadId)) Preferences.SWIPE_ACTION_UNREAD -> markUnread.execute(listOf(threadId)) } } view.undoArchiveIntent .withLatestFrom(view.swipeConversationIntent) { _, pair -> pair.first } .autoDisposable(view.scope()) .subscribe { threadId -> markUnarchived.execute(listOf(threadId)) } view.snackbarButtonIntent .withLatestFrom(state) { _, state -> when { !state.defaultSms -> view.requestDefaultSms() !state.smsPermission -> view.requestPermissions() !state.contactPermission -> view.requestPermissions() } } .autoDisposable(view.scope()) .subscribe() } }
presentation/src/main/java/com/moez/QKSMS/feature/main/MainViewModel.kt
2084121491
/* * Copyright (C) 2019. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.hazelcast.serializers import com.hazelcast.nio.ObjectDataInput import com.hazelcast.nio.ObjectDataOutput import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer import com.openlattice.assembler.processors.AddFlagsToOrganizationMaterializedEntitySetProcessor import com.openlattice.hazelcast.StreamSerializerTypeIds import com.openlattice.organization.OrganizationEntitySetFlag import org.springframework.stereotype.Component @Component class AddFlagsToOrganizationMaterializedEntitySetProcessorStreamSerializer : SelfRegisteringStreamSerializer<AddFlagsToOrganizationMaterializedEntitySetProcessor> { private val entitySetFlags = OrganizationEntitySetFlag.values() override fun getTypeId(): Int { return StreamSerializerTypeIds.ADD_FLAGS_TO_ORGANIZATION_MATERIALIZED_ENTITY_SET_PROCESSOR.ordinal } override fun getClazz(): Class<out AddFlagsToOrganizationMaterializedEntitySetProcessor> { return AddFlagsToOrganizationMaterializedEntitySetProcessor::class.java } override fun write(out: ObjectDataOutput, obj: AddFlagsToOrganizationMaterializedEntitySetProcessor) { UUIDStreamSerializerUtils.serialize(out, obj.entitySetId) out.writeInt(obj.flags.size) obj.flags.forEach { out.writeInt(it.ordinal) } } override fun read(input: ObjectDataInput): AddFlagsToOrganizationMaterializedEntitySetProcessor { val entitySetId = UUIDStreamSerializerUtils.deserialize(input) val size = input.readInt() val flags = LinkedHashSet<OrganizationEntitySetFlag>(size) (0 until size).forEach { _ -> flags.add(entitySetFlags[input.readInt()]) } return AddFlagsToOrganizationMaterializedEntitySetProcessor(entitySetId, flags) } }
src/main/kotlin/com/openlattice/hazelcast/serializers/AddFlagsToOrganizationMaterializedEntitySetProcessorStreamSerializer.kt
2739230408
package models import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable import java.time.LocalDateTime @DynamoDBTable(tableName = "ModerationResult") data class ModerationResult( @get:DynamoDBHashKey(attributeName = "hostname") val hostname: String, @get:DynamoDBRangeKey(attributeName = "imageUrl") val imageUrl: String, @get:DynamoDBAttribute val hasLabels: Int = 0, @get:DynamoDBAttribute val hasError: Int = 0, @get:DynamoDBAttribute val errorMessage: String? = null, @get:DynamoDBAttribute val createTime: String = LocalDateTime.now().toString(), @get:DynamoDBAttribute val explicitNudity: Float? = null, @get:DynamoDBAttribute val graphicMaleNudity: Float? = null, @get:DynamoDBAttribute val graphicFemaleNudity: Float? = null, @get:DynamoDBAttribute val sexualActivity: Float? = null, @get:DynamoDBAttribute val partialNudity: Float? = null, @get:DynamoDBAttribute val suggestive: Float? = null, @get:DynamoDBAttribute val maleSwimwearOrUnderwear: Float? = null, @get:DynamoDBAttribute val femaleSwimwearOrUnderwear: Float? = null, @get:DynamoDBAttribute val revealingClothes: Float? = null)
src/main/kotlin/models/ModerationResult.kt
2230884993
/* * Copyright (c) 2020. Rei Matsushita * * 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 me.rei_m.hyakuninisshu.state.material.store import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import me.rei_m.hyakuninisshu.state.core.Dispatcher import me.rei_m.hyakuninisshu.state.core.Store import me.rei_m.hyakuninisshu.state.material.action.EditMaterialAction import me.rei_m.hyakuninisshu.state.material.action.FetchMaterialListAction import me.rei_m.hyakuninisshu.state.material.model.Material import javax.inject.Inject /** * 資料の状態を管理する. */ class MaterialStore @Inject constructor(dispatcher: Dispatcher) : Store() { private val _materialList = MutableLiveData<List<Material>?>() val materialList: LiveData<List<Material>?> = _materialList private val _isFailure = MutableLiveData(false) val isFailure: LiveData<Boolean> = _isFailure init { register(dispatcher.on(FetchMaterialListAction::class.java).subscribe { when (it) { is FetchMaterialListAction.Success -> { _materialList.value = it.materialList _isFailure.value = false } is FetchMaterialListAction.Failure -> { _isFailure.value = true } } }, dispatcher.on(EditMaterialAction::class.java).subscribe { when (it) { is EditMaterialAction.Success -> { _isFailure.value = false val currentValue = materialList.value ?: return@subscribe _materialList.value = currentValue.map { m -> if (m.no == it.material.no) it.material else m } } is EditMaterialAction.Failure -> { _isFailure.value = true } } }) } }
state/src/main/java/me/rei_m/hyakuninisshu/state/material/store/MaterialStore.kt
1588309305
/* * XStopwatch / XTimer * Copyright (C) 2014 by Dan Wallach * Home page: http://www.cs.rice.edu/~dwallach/xstopwatch/ * Licensing: http://www.cs.rice.edu/~dwallach/xstopwatch/licensing.html */ package org.dwallach.xstopwatch import android.app.Activity import android.content.pm.PackageManager import android.os.Bundle import android.util.Log import android.view.View import android.widget.ImageButton import java.util.Observable import java.util.Observer import kotlinx.android.synthetic.main.activity_stopwatch.* import org.jetbrains.anko.* class StopwatchActivity : Activity(), Observer { private var playButton: ImageButton? = null private var notificationHelper: NotificationHelper? = null private var stopwatchText: StopwatchText? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.v(TAG, "onCreate") try { val pinfo = packageManager.getPackageInfo(packageName, 0) val versionNumber = pinfo.versionCode val versionName = pinfo.versionName Log.i(TAG, "Version: $versionName ($versionNumber)") } catch (e: PackageManager.NameNotFoundException) { Log.e(TAG, "couldn't read version", e) } intent.log(TAG) // dumps info from the intent into the log // if the user said "OK Google, start stopwatch", then this is how we can tell if(intent.action == "com.google.android.wearable.action.STOPWATCH") { Log.v(TAG, "user voice action detected: starting the stopwatch") StopwatchState.run(this@StopwatchActivity) PreferencesHelper.savePreferences(this@StopwatchActivity) PreferencesHelper.broadcastPreferences(this@StopwatchActivity, Constants.stopwatchUpdateIntent) } setContentView(R.layout.activity_stopwatch) watch_view_stub.setOnLayoutInflatedListener { Log.v(TAG, "onLayoutInflated") val resetButton = it.find<ImageButton>(R.id.resetButton) playButton = it.find<ImageButton>(R.id.playButton) stopwatchText = it.find<StopwatchText>(R.id.elapsedTime) stopwatchText?.setSharedState(StopwatchState) // bring in saved preferences PreferencesHelper.loadPreferences(this@StopwatchActivity) // now that we've loaded the state, we know whether we're playing or paused setPlayButtonIcon() // set up notification helper, and use this as a proxy for whether // or not we need to set up everybody who pays attention to the stopwatchState if (notificationHelper == null) { notificationHelper = NotificationHelper(this@StopwatchActivity, R.drawable.stopwatch_trans, resources.getString(R.string.stopwatch_app_name), StopwatchState) setStopwatchObservers(true) } // get the notification service running as well; it will stick around to make sure // the broadcast receiver is alive NotificationService.kickStart(this@StopwatchActivity) resetButton.setOnClickListener { StopwatchState.reset(this@StopwatchActivity) PreferencesHelper.savePreferences(this@StopwatchActivity) PreferencesHelper.broadcastPreferences(this@StopwatchActivity, Constants.stopwatchUpdateIntent) } playButton?.setOnClickListener { StopwatchState.click(this@StopwatchActivity) PreferencesHelper.savePreferences(this@StopwatchActivity) PreferencesHelper.broadcastPreferences(this@StopwatchActivity, Constants.stopwatchUpdateIntent) } } } // call to this specified in the layout xml files fun launchTimer(view: View) = startActivity<TimerActivity>() /** * install the observers that care about the stopwatchState: "this", which updates the * visible UI parts of the activity, and the notificationHelper, which deals with the popup * notifications elsewhere * @param includeActivity If the current activity isn't visible, then make this false and it won't be notified */ private fun setStopwatchObservers(includeActivity: Boolean) { StopwatchState.deleteObservers() if (notificationHelper != null) StopwatchState.addObserver(notificationHelper) if (includeActivity) { StopwatchState.addObserver(this) if (stopwatchText != null) StopwatchState.addObserver(stopwatchText) } } override fun onStart() { super.onStart() Log.v(TAG, "onStart") StopwatchState.isVisible = true setStopwatchObservers(true) } override fun onResume() { super.onResume() Log.v(TAG, "onResume") StopwatchState.isVisible = true setStopwatchObservers(true) } override fun onPause() { super.onPause() Log.v(TAG, "onPause") StopwatchState.isVisible = false setStopwatchObservers(false) } override fun update(observable: Observable?, data: Any?) { Log.v(TAG, "activity update") setPlayButtonIcon() } private fun setPlayButtonIcon() = playButton?.setImageResource( if(StopwatchState.isRunning) android.R.drawable.ic_media_pause else android.R.drawable.ic_media_play) companion object { private val TAG = "StopwatchActivity" } }
wear/src/main/kotlin/org/dwallach/xstopwatch/StopwatchActivity.kt
3752184868
package kodando.mobx.react import kodando.react.Component import kodando.react.ReactProps import kodando.react.Renderer import kotlin.reflect.KClass fun <T : Component<*, *>> makeObserver(type: JsClass<T>): JsClass<T> = MobxReact.observer(type) inline fun <reified T : Component<*, *>> makeObserver(type: KClass<T>): JsClass<T> = MobxReact.observer(type.js) fun <TProps : ReactProps> makeObserver(renderer: Renderer<TProps>): Renderer<TProps> = MobxReact.observer(renderer)
kodando-mobx-react/src/main/kotlin/kodando/mobx/react/MakeObserver.kt
1812878675
package com.atc.planner.di import com.atc.planner.App import com.atc.planner.di.modules.* import dagger.Component import dagger.android.AndroidInjector import dagger.android.support.AndroidSupportInjectionModule import javax.inject.Singleton @Singleton @Component(modules = arrayOf(AppModule::class, CommonModule::class, RepositoryModule::class, RemoteServiceModule::class, ActivityBindingModule::class, FragmentBindingModule::class, ServiceBindingModule::class, AndroidSupportInjectionModule::class)) interface AppComponent : AndroidInjector<App> { @Component.Builder abstract class Builder : AndroidInjector.Builder<App>() }
app/src/main/java/com/atc/planner/di/AppComponent.kt
1085634567
package com.github.b3er.idea.plugins.arc.browser.base.nest import com.github.b3er.idea.plugins.arc.browser.base.BaseArchiveHandler import com.intellij.openapi.vfs.VirtualFile interface SupportsNestedArchives { fun getHandlerForFile(file: VirtualFile): BaseArchiveHandler<*> }
src/main/kotlin/com/github/b3er/idea/plugins/arc/browser/base/nest/SupportsNestedArchives.kt
483146151
import org.apache.tools.ant.taskdefs.condition.Os import org.gradle.BuildAdapter import org.gradle.BuildResult import org.gradle.api.GradleException import org.gradle.StartParameter import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.execution.TaskExecutionListener import org.gradle.api.invocation.Gradle import org.gradle.api.tasks.TaskState import org.gradle.internal.service.ServiceRegistry import java.io.File import java.lang.reflect.Field import java.util.* fun Gradle.logTasks(tasks: List<Task>) = logTasks(*tasks.toTypedArray()) fun Gradle.logTasks(vararg task: Task) { task.forEach { targetTask -> addListener(object : TaskExecutionListener { var startTime: Long = 0 override fun beforeExecute(task: Task) { if (task == targetTask) { startTime = System.currentTimeMillis() } } override fun afterExecute(task: Task, state: TaskState) { if (task == targetTask && task.didWork) { val finishTime = System.currentTimeMillis() buildFinished { val taskName = if (task.isMirakleTask()) task.name else task.path.drop(1) println("Task $taskName took : ${prettyTime(finishTime - startTime)}") } } } }) } } fun Gradle.logBuild(startTime: Long, mirakle: Task) { // override default logger as soon as mirakle starts mirakle.doFirst { useLogger(object : BuildAdapter() {}) } buildFinished { println("Total time : ${prettyTime(System.currentTimeMillis() - startTime)}") } } fun Gradle.assertNonSupportedFeatures() { if (startParameter.isContinuous) throw MirakleException("--continuous is not supported yet") if (startParameter.includedBuilds.isNotEmpty()) throw MirakleException("Included builds is not supported yet") } private const val MS_PER_MINUTE: Long = 60000 private const val MS_PER_HOUR = MS_PER_MINUTE * 60 fun prettyTime(timeInMs: Long): String { val result = StringBuffer() if (timeInMs > MS_PER_HOUR) { result.append(timeInMs / MS_PER_HOUR).append(" hrs ") } if (timeInMs > MS_PER_MINUTE) { result.append(timeInMs % MS_PER_HOUR / MS_PER_MINUTE).append(" mins ") } result.append(timeInMs % MS_PER_MINUTE / 1000.0).append(" secs") return result.toString() } class MirakleException(message: String? = null) : GradleException(message) inline fun <reified T : Task> Project.task(name: String, noinline configuration: T.() -> Unit) = tasks.create(name, T::class.java, configuration) val Task.services: ServiceRegistry get() { try { fun findField(java: Class<*>, field: String): Field { return try { java.getDeclaredField(field) } catch (e: NoSuchFieldException) { java.superclass?.let { findField(it, field) } ?: throw e } } val field = findField(DefaultTask::class.java, "services") field.isAccessible = true return field.get(this) as ServiceRegistry } catch (e: Throwable) { e.printStackTrace() throw e } } fun Task.isMirakleTask() = name == "mirakle" || name == "uploadToRemote" || name == "executeOnRemote" || name == "downloadFromRemote" || name == "downloadInParallel" || name == "fallback" /* * On Windows rsync is used under Cygwin environment * and classical Windows path "C:\Users" must be replaced by "/cygdrive/c/Users" * */ fun fixPathForWindows(path: String) = if (Os.isFamily(Os.FAMILY_WINDOWS)) { val windowsDisk = path.first().toLowerCase() val windowsPath = path.substringAfter(":\\").replace('\\', '/') "/cygdrive/$windowsDisk/$windowsPath" } else path fun StartParameter.copy() = newInstance().also { copy -> copy.isBuildScan = this.isBuildScan copy.isNoBuildScan = this.isNoBuildScan } fun findGradlewRoot(root: File): File? { val gradlew = File(root, "gradlew") return if (gradlew.exists()) { gradlew.parentFile } else { root.parentFile?.let(::findGradlewRoot) } } fun loadProperties(file: File) = file.takeIf(File::exists)?.let { Properties().apply { load(it.inputStream()) }.toMap() as Map<String, String> } ?: emptyMap() fun Gradle.afterMirakleEvaluate(callback: () -> Unit) { var wasCallback = false gradle.rootProject { it.afterEvaluate { if (!wasCallback) { wasCallback = true callback() } } } // in case if build failed before project evaluation addBuildListener(object : BuildAdapter() { override fun buildFinished(p0: BuildResult) { if (p0.failure != null && !wasCallback) { wasCallback = true callback() } } }) } fun Gradle.containsIjTestInit() = startParameter.initScripts.any { it.name.contains("ijtestinit") }
plugin/src/main/kotlin/utils.kt
3670083759
package com.example.aleckstina.wespeakandroid.http import com.example.aleckstina.wespeakandroid.model.AccessTokenModel import com.example.aleckstina.wespeakandroid.model.User import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query /** * Created by aleckstina on 11/15/17. */ interface ApiInterface { @GET("/api/v1/login") fun getGeneratedAccessToken(@Query("accessToken") apiKey: String) : Call<AccessTokenModel> }
app/src/main/java/com/example/aleckstina/wespeakandroid/http/ApiInterface.kt
2293634988
package game.robotm.gamesys import com.badlogic.gdx.assets.AssetManager import com.badlogic.gdx.audio.Sound object SoundPlayer { var readySound: Sound? = null var goSound: Sound? = null var gameOverSound: Sound? = null var damagedSound: Sound? = null var explodeSound: Sound? = null var jumpSound: Sound? = null var springSound: Sound? = null var cantJumpSound: Sound? = null var engineSound: Sound? = null var powerUpSound: Sound? = null fun load(assetManager: AssetManager) { readySound = assetManager.get("sounds/ready.ogg", Sound::class.java) goSound = assetManager.get("sounds/go.ogg", Sound::class.java) gameOverSound = assetManager.get("sounds/game_over.ogg", Sound::class.java) damagedSound = assetManager.get("sounds/damaged.ogg", Sound::class.java) explodeSound = assetManager.get("sounds/explode.ogg", Sound::class.java) jumpSound = assetManager.get("sounds/jump.ogg", Sound::class.java) springSound = assetManager.get("sounds/spring.ogg", Sound::class.java) cantJumpSound = assetManager.get("sounds/cant_jump.ogg", Sound::class.java) engineSound = assetManager.get("sounds/engine.ogg", Sound::class.java) powerUpSound = assetManager.get("sounds/power_up.ogg", Sound::class.java) } fun getSound(sound: String): Sound { when (sound) { "ready" -> return readySound!! "go" -> return goSound!! "game_over" -> return gameOverSound!! "damaged" -> return damagedSound!! "explode" -> return explodeSound!! "jump" -> return jumpSound!! "spring" -> return springSound!! "cant_jump" -> return cantJumpSound!! "engine" -> return engineSound!! "power_up" -> return powerUpSound!! else -> return readySound!! } } fun play(sound: String): Long { when (sound) { "ready" -> return readySound!!.play(GM.sfxVolume) "go" -> return goSound!!.play(GM.sfxVolume) "game_over" -> return gameOverSound!!.play(GM.sfxVolume) "damaged" -> return damagedSound!!.play(GM.sfxVolume) "explode" -> return explodeSound!!.play(GM.sfxVolume) "jump" -> return jumpSound!!.play(GM.sfxVolume) "spring" -> return springSound!!.play(GM.sfxVolume) "cant_jump" -> return cantJumpSound!!.play(GM.sfxVolume) "engine" -> return engineSound!!.play(GM.sfxVolume) "power_up" -> return powerUpSound!!.play(GM.sfxVolume) else -> return -1L } } }
core/src/game/robotm/gamesys/SoundPlayer.kt
3437664620
/* * Westford Wayland Compositor. * Copyright (C) 2016 Erik De Rijcke * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.westford.nativ.libpng import org.freedesktop.jaccall.Functor import org.freedesktop.jaccall.Ptr @Functor interface png_flush_ptr { operator fun invoke(@Ptr png_structp: Long) }
compositor/src/main/kotlin/org/westford/nativ/libpng/png_flush_ptr.kt
77386877
/* * Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.features import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking import kotlinx.serialization.* import kotlinx.serialization.builtins.serializer import kotlinx.serialization.features.sealed.SealedChild import kotlinx.serialization.features.sealed.SealedParent import kotlinx.serialization.json.* import kotlinx.serialization.test.assertFailsWithMessage import kotlinx.serialization.test.assertFailsWithSerial import org.junit.Test import java.io.* import kotlin.test.* class JsonLazySequenceTest { val json = Json private suspend inline fun <reified T> Flow<T>.writeToStream(os: OutputStream) { collect { json.encodeToStream(it, os) } } private suspend inline fun <reified T> Json.readFromStream(iss: InputStream): Flow<T> = flow { val serial = serializer<T>() val iter = iterateOverStream(iss, serial) while (iter.hasNext()) { emit(iter.next()) } }.flowOn(Dispatchers.IO) private val inputStringWsSeparated = """{"data":"a"}{"data":"b"}{"data":"c"}""" private val inputStringWrapped = """[{"data":"a"},{"data":"b"},{"data":"c"}]""" private val inputList = listOf(StringData("a"), StringData("b"), StringData("c")) @Test fun testEncodeSeveralItems() { val items = inputList val os = ByteArrayOutputStream() runBlocking { val f = flow<StringData> { items.forEach { emit(it) } } f.writeToStream(os) } assertEquals(inputStringWsSeparated, os.toString(Charsets.UTF_8.name())) } @Test fun testDecodeSeveralItems() { val ins = ByteArrayInputStream(inputStringWsSeparated.encodeToByteArray()) assertFailsWithMessage<SerializationException>("EOF") { json.decodeFromStream<StringData>(ins) } } private inline fun <reified T> Iterator<T>.assertNext(expected: T) { assertTrue(hasNext()) assertEquals(expected, next()) } private fun <T> Json.iterateOverStream(stream: InputStream, deserializer: DeserializationStrategy<T>): Iterator<T> = decodeToSequence(stream, deserializer).iterator() private fun withInputs(vararg inputs: String = arrayOf(inputStringWsSeparated, inputStringWrapped), block: (InputStream) -> Unit) { for (input in inputs) { val res = runCatching { block(input.asInputStream()) } if (res.isFailure) throw AssertionError("Failed test with input $input", res.exceptionOrNull()) } } private fun String.asInputStream() = ByteArrayInputStream(this.encodeToByteArray()) @Test fun testIterateSeveralItems() = withInputs { ins -> val iter = json.iterateOverStream(ins, StringData.serializer()) iter.assertNext(StringData("a")) iter.assertNext(StringData("b")) iter.assertNext(StringData("c")) assertFalse(iter.hasNext()) assertFailsWithMessage<SerializationException>("EOF") { iter.next() } } @Test fun testDecodeToSequence() = withInputs { ins -> val sequence = json.decodeToSequence(ins, StringData.serializer()) assertEquals(inputList, sequence.toList(), "For input $inputStringWsSeparated") assertFailsWith<IllegalStateException> { sequence.toList() } // assert constrained once } @Test fun testDecodeAsFlow() = withInputs { ins -> val list = runBlocking { buildList { json.readFromStream<StringData>(ins).toCollection(this) } } assertEquals(inputList, list) } @Test fun testItemsSeparatedByWs() { val input = "{\"data\":\"a\"} {\"data\":\"b\"}\n\t{\"data\":\"c\"}" val ins = ByteArrayInputStream(input.encodeToByteArray()) assertEquals(inputList, json.decodeToSequence(ins, StringData.serializer()).toList()) } @Test fun testJsonElement() { val list = listOf<JsonElement>( buildJsonObject { put("foo", "bar") }, buildJsonObject { put("foo", "baz") }, JsonPrimitive(10), JsonPrimitive("abacaba"), buildJsonObject { put("foo", "qux") } ) val inputWs = """${list[0]} ${list[1]} ${list[2]} ${list[3]} ${list[4]}""" val decodedWs = json.decodeToSequence<JsonElement>(inputWs.asInputStream()).toList() assertEquals(list, decodedWs, "Failed whitespace-separated test") val inputArray = """[${list[0]}, ${list[1]},${list[2]} , ${list[3]} ,${list[4]}]""" val decodedArrayWrap = json.decodeToSequence<JsonElement>(inputArray.asInputStream()).toList() assertEquals(list, decodedArrayWrap, "Failed array-wrapped test") } @Test fun testSealedClasses() { val input = """{"type":"first child","i":1,"j":10} {"type":"first child","i":1,"j":11}""" val iter = json.iterateOverStream(input.asInputStream(), SealedParent.serializer()) iter.assertNext(SealedChild(10)) iter.assertNext(SealedChild(11)) } @Test fun testMalformedArray() { val input1 = """[1, 2, 3""" val input2 = """[1, 2, 3]qwert""" val input3 = """[1,2 3]""" withInputs(input1, input2, input3) { assertFailsWithSerial("JsonDecodingException") { json.decodeToSequence(it, Int.serializer()).toList() } } } @Test fun testMultilineArrays() { val input = "[1,2,3]\n[4,5,6]\n[7,8,9]" assertFailsWithSerial("JsonDecodingException") { json.decodeToSequence<List<Int>>(input.asInputStream(), DecodeSequenceMode.AUTO_DETECT).toList() } assertFailsWithSerial("JsonDecodingException") { json.decodeToSequence<Int>(input.asInputStream(), DecodeSequenceMode.AUTO_DETECT).toList() } assertFailsWithSerial("JsonDecodingException") { // we do not merge lists json.decodeToSequence<Int>(input.asInputStream(), DecodeSequenceMode.ARRAY_WRAPPED).toList() } val parsed = json.decodeToSequence<List<Int>>(input.asInputStream(), DecodeSequenceMode.WHITESPACE_SEPARATED).toList() val expected = listOf(listOf(1,2,3), listOf(4,5,6), listOf(7,8,9)) assertEquals(expected, parsed) } @Test fun testStrictArrayCheck() { assertFailsWithSerial("JsonDecodingException") { json.decodeToSequence<StringData>(inputStringWsSeparated.asInputStream(), DecodeSequenceMode.ARRAY_WRAPPED) } } @Test fun testPaddedWs() { val paddedWs = " $inputStringWsSeparated " assertEquals(inputList, json.decodeToSequence(paddedWs.asInputStream(), StringData.serializer()).toList()) assertEquals(inputList, json.decodeToSequence(paddedWs.asInputStream(), StringData.serializer(), DecodeSequenceMode.WHITESPACE_SEPARATED).toList()) } @Test fun testPaddedArray() { val paddedWs = " $inputStringWrapped " assertEquals(inputList, json.decodeToSequence(paddedWs.asInputStream(), StringData.serializer()).toList()) assertEquals(inputList, json.decodeToSequence(paddedWs.asInputStream(), StringData.serializer(), DecodeSequenceMode.ARRAY_WRAPPED).toList()) } }
formats/json-tests/jvmTest/src/kotlinx/serialization/features/JsonLazySequenceTest.kt
2537074613
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.api.item.potion import org.lanternpowered.api.effect.potion.PotionEffect import org.lanternpowered.api.effect.potion.PotionEffectType import org.lanternpowered.api.effect.potion.potionEffectOf import org.lanternpowered.api.registry.CatalogBuilder import java.util.function.Supplier /** * A builder to construct [PotionType]s. */ interface PotionTypeBuilder : CatalogBuilder<PotionType, PotionTypeBuilder> { /** * Adds a [PotionEffect]. * * @param potionEffect The potion effect to add */ fun addEffect(potionEffect: PotionEffect): PotionTypeBuilder /** * Adds a potion effect. */ fun addEffect(type: PotionEffectType, amplifier: Int, duration: Int, ambient: Boolean = false, particles: Boolean = true) = addEffect(potionEffectOf(type, amplifier, duration, ambient, particles)) /** * Adds a potion effect. */ fun addEffect(type: Supplier<out PotionEffectType>, amplifier: Int, duration: Int, ambient: Boolean = false, particles: Boolean = true) = addEffect(potionEffectOf(type, amplifier, duration, ambient, particles)) /** * Sets the (partial) translation key that is used to provide * translations based on the built potion type. * * For example, setting `weakness` becomes * `item.minecraft.splash_potion.effect.weakness` when * used to translate a splash potion item. * * Defaults to the catalog key value. * * @param key The (partial) translation key * @return This builder, for chaining */ fun translationKey(key: String): PotionTypeBuilder }
src/main/kotlin/org/lanternpowered/api/item/potion/PotionTypeBuilder.kt
3927649991
package com.deanveloper.overcraft.util import org.bukkit.Material import org.bukkit.inventory.ItemStack /** * @author Dean */ class OcItem(mat: Material, count: Int, damage: Short) : ItemStack(mat, count, damage) { constructor( mat: Material, name: String = "", lore: List<String> = emptyList(), isUnbreakable: Boolean = true ) : this(mat, 1, 0) { this.name = name this.lore = lore this.isUnbreakable = isUnbreakable } constructor(mat: Material, damage: Short) : this(mat, 1, damage) var name: String get() = itemMeta?.displayName ?: "" set(value) { itemMeta = itemMeta?.apply { displayName = if(value.isEmpty()) null else value } } var lore: List<String> get() = itemMeta?.lore ?: emptyList() set(value) { itemMeta = itemMeta?.apply { lore = value } } var isUnbreakable: Boolean get() = itemMeta?.spigot()?.isUnbreakable ?: false set(value) { itemMeta = itemMeta?.apply { spigot()?.isUnbreakable = value } } }
src/main/java/com/deanveloper/overcraft/util/OcItem.kt
2878394987
/** * File : MigrationInfoImpl.kt * License : * Original - Copyright (c) 2010 - 2016 Boxfuse GmbH * Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte 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 com.builtamont.cassandra.migration.internal.info import com.builtamont.cassandra.migration.api.MigrationInfo import com.builtamont.cassandra.migration.api.MigrationState import com.builtamont.cassandra.migration.api.MigrationType import com.builtamont.cassandra.migration.api.MigrationVersion import com.builtamont.cassandra.migration.api.resolver.ResolvedMigration import com.builtamont.cassandra.migration.internal.metadatatable.AppliedMigration import java.util.* /** * Default implementation of MigrationInfoService. * * @param resolvedMigration The resolved migration to aggregate the info from. * @param appliedMigration The applied migration to aggregate the info from. * @param context The current context. */ class MigrationInfoImpl( val resolvedMigration: ResolvedMigration?, val appliedMigration: AppliedMigration?, private val context: MigrationInfoContext ) : MigrationInfo { /** * The type of migration (CQL, Java, ...) */ override val type: MigrationType get() { if (appliedMigration != null) { return appliedMigration.type!! } return resolvedMigration?.type!! } /** * The target version of this migration. */ override val checksum: Int? get() { if (appliedMigration != null) { return appliedMigration.checksum } return resolvedMigration!!.checksum } /** * The schema version after the migration is complete. */ override val version: MigrationVersion get() { if (appliedMigration != null) { return appliedMigration.version!! } return resolvedMigration!!.version!! } /** * The description of the migration. */ override val description: String get() { if (appliedMigration != null) { return appliedMigration.description!! } return resolvedMigration!!.description!! } /** * The name of the script to execute for this migration, relative to its classpath or filesystem location. */ override val script: String get() { if (appliedMigration != null) { return appliedMigration.script!! } return resolvedMigration!!.script!! } /** * The state of the migration (PENDING, SUCCESS, ...) */ override val state: MigrationState get() { if (appliedMigration == null) { if (resolvedMigration!!.version!!.compareTo(context.baseline) < 0) { return MigrationState.BELOW_BASELINE } if (resolvedMigration.version!!.compareTo(context.target) > 0) { return MigrationState.ABOVE_TARGET } if (resolvedMigration.version!!.compareTo(context.lastApplied) < 0 && !context.outOfOrder) { return MigrationState.IGNORED } return MigrationState.PENDING } if (resolvedMigration == null) { if (MigrationType.SCHEMA === appliedMigration.type) { return MigrationState.SUCCESS } if (MigrationType.BASELINE === appliedMigration.type) { return MigrationState.BASELINE } if (version.compareTo(context.lastResolved) < 0) { if (appliedMigration.isSuccess) { return MigrationState.MISSING_SUCCESS } return MigrationState.MISSING_FAILED } if (version.compareTo(context.lastResolved) > 0) { if (appliedMigration.isSuccess) { return MigrationState.FUTURE_SUCCESS } return MigrationState.FUTURE_FAILED } } if (appliedMigration.isSuccess) { if (appliedMigration.versionRank == appliedMigration.installedRank) { return MigrationState.SUCCESS } return MigrationState.OUT_OF_ORDER } return MigrationState.FAILED } /** * The timestamp when this migration was installed. (Only for applied migrations) */ override val installedOn: Date? get() { if (appliedMigration != null) { return appliedMigration.installedOn } return null } /** * The execution time (in millis) of this migration. (Only for applied migrations) */ override val executionTime: Int? get() { if (appliedMigration != null) { return appliedMigration.executionTime } return null } /** * Validates this migrationInfo for consistency. * * @return The error message, or {@code null} if everything is fine. */ fun validate(): String? { if (!context.pendingOrFuture && resolvedMigration == null && appliedMigration!!.type !== MigrationType.SCHEMA && appliedMigration!!.type !== MigrationType.BASELINE) { return "Detected applied migration not resolved locally: " + version } if (!context.pendingOrFuture && MigrationState.PENDING === state || MigrationState.IGNORED === state) { return "Detected resolved migration not applied to database: " + version } if (resolvedMigration != null && appliedMigration != null) { if (version.compareTo(context.baseline) > 0) { if (resolvedMigration.type !== appliedMigration.type) { return createMismatchMessage("Type", appliedMigration.version!!, appliedMigration.type!!, resolvedMigration.type!!) } if (!com.builtamont.cassandra.migration.internal.util.ObjectUtils.nullSafeEquals(resolvedMigration.checksum, appliedMigration.checksum)) { return createMismatchMessage("Checksum", appliedMigration.version!!, appliedMigration.checksum!!, resolvedMigration.checksum!!) } if (resolvedMigration.description != appliedMigration.description) { return createMismatchMessage("Description", appliedMigration.version!!, appliedMigration.description!!, resolvedMigration.description!!) } } } return null } /** * Creates a message for a mismatch. * * @param mismatch The type of mismatch. * @param version The offending version. * @param applied The applied value. * @param resolved The resolved value. * @return The message. */ private fun createMismatchMessage(mismatch: String, version: MigrationVersion, applied: Any, resolved: Any): String { val message = "Migration $mismatch mismatch for migration $version\n-> Applied to database : $applied\n-> Resolved locally : $resolved" return String.format(message) } /** * @return The computed info instance hash value. */ override fun hashCode(): Int { var result = resolvedMigration?.hashCode() ?: 0 result = 31 * result + (appliedMigration?.hashCode() ?: 0) result = 31 * result + context.hashCode() return result } /** * @return {@code true} if this info instance is the same as the given object. */ @SuppressWarnings("SimplifiableIfStatement") override fun equals(other: Any?): Boolean { /** * @return {@code true} if this version instance is not the same as the given object. */ fun isNotSame(): Boolean { return other == null || javaClass != other.javaClass } /** * @return {@code true} if this context instance applied migration property is not the same as the given object applied migration property. */ fun isNotSameAppliedMigration(that: MigrationInfoImpl): Boolean { return if (appliedMigration != null) appliedMigration != that.appliedMigration else that.appliedMigration != null } /** * @return {@code true} if this context instance resolved migration property is not the same as the given object resolved migration property. */ fun isNotSameResolvedMigration(that: MigrationInfoImpl): Boolean { return if (resolvedMigration != null) resolvedMigration != that.resolvedMigration else that.resolvedMigration != null } val that = other as MigrationInfoImpl? ?: return false return when { this === other -> true isNotSame() -> false isNotSameAppliedMigration(that) -> false context != that.context -> false else -> !isNotSameResolvedMigration(that) // Note the double negative } } /** * @return {@code true} if this info instance is comparable to the given object. */ @SuppressWarnings("NullableProblems") override fun compareTo(other: MigrationInfo): Int { return version.compareTo(other.version) } }
src/main/java/com/builtamont/cassandra/migration/internal/info/MigrationInfoImpl.kt
2325102314
package lighthouse.files import com.sun.nio.file.SensitivityWatchEventModifier import lighthouse.threading.AffinityExecutor import lighthouse.utils.ThreadBox import org.slf4j.LoggerFactory import java.io.IOException import java.nio.file.FileSystems import java.nio.file.Path import java.nio.file.StandardWatchEventKinds.ENTRY_CREATE import java.nio.file.StandardWatchEventKinds.ENTRY_DELETE import java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY import java.nio.file.StandardWatchEventKinds.OVERFLOW import java.nio.file.WatchEvent import java.time.Duration import java.util.concurrent.ScheduledFuture import kotlin.concurrent.thread /** * The Java directory watching API is very low level, almost a direct translation of the underlying OS API's, so we * wrap it here to make it more digestable. One of the things this does is buffer up rapid sequences of notifications * that can be caused by file copy tools like scp. */ public object DirectoryWatcher { private val log = LoggerFactory.getLogger(DirectoryWatcher::class.java) @Suppress("UNCHECKED_CAST") @JvmStatic public fun watch(directory: Path, executor: AffinityExecutor.ServiceAffinityExecutor, onChanged: (Path, WatchEvent.Kind<Path>) -> Unit): Thread { return thread(start = true, daemon = true, name = "Directory watcher for $directory") { log.info("Starting directory watch service for $directory") // Apply a short delay to collapse rapid sequences of notifications together. class Pending(val kind: WatchEvent.Kind<Path>, val future: ScheduledFuture<*>) val dupeMap = ThreadBox(hashMapOf<Path, Pending>()) try { val watcher = FileSystems.getDefault().newWatchService() directory.register(watcher, arrayOf(ENTRY_DELETE, ENTRY_CREATE, ENTRY_MODIFY), SensitivityWatchEventModifier.HIGH) while (!Thread.currentThread().isInterrupted) { val key = watcher.take() for (event in key.pollEvents()) { val kind = event.kind() if (kind === OVERFLOW) { continue } val ev = event as WatchEvent<Path> val filename = (key.watchable() as Path).resolve(ev.context()) val handler = { dupeMap.useWith { remove(filename) } onChanged(filename, ev.kind()) } dupeMap.use { map -> val pending: Pending? = map[filename] fun addToMap() { map[filename] = Pending(ev.kind(), executor.executeIn(Duration.ofSeconds(1), handler)) } if (pending == null) { addToMap() } else { if (ev.kind() == ENTRY_MODIFY && pending.kind == ENTRY_CREATE) { // We do nothing here, as the onChanged event will prefer to see a CREATE and not // the subsequent modifies. } else if (ev.kind() == ENTRY_DELETE && pending.kind == ENTRY_CREATE) { // A file created and deleted so fast can just be ignored. pending.future.cancel(false) } else { // Otherwise let it override the previous pending event. pending.future.cancel(false) addToMap() } } } } if (!key.reset()) break } } catch (e: IOException) { e.printStackTrace() } catch (e: InterruptedException) { // Shutting down ... } } } }
common/src/main/java/lighthouse/files/DirectoryWatcher.kt
1838392609
package com.after10years.blog.service import com.after10years.blog.mapper.ModuleMapper import com.after10years.blog.model.ModuleModel import org.springframework.stereotype.Service @Service class ModuleService(val moduleMapper: ModuleMapper) { fun getModuleList(pid : Int) : List<ModuleModel>{ return moduleMapper.getListByPid(pid) } //根据评论热度获取模块列表 fun getModuleListByCommentHot(limit : Int):List<ModuleModel>{ return moduleMapper.getListByCommentHot(limit) } }
src/main/kotlin/com/after10years/blog/service/ModuleService.kt
3059225056
package nl.hannahsten.texifyidea.reference import com.intellij.psi.* import com.intellij.util.containers.toArray import nl.hannahsten.texifyidea.index.LatexGlossaryEntryIndex import nl.hannahsten.texifyidea.lang.commands.LatexGlossariesCommand import nl.hannahsten.texifyidea.psi.LatexParameterText /** * This reference allows refactoring of glossary entries. A glossary reference command (e.g. \gls) references the label * parameter of a glossary entry command (e.g. \newglossaryentry). */ class LatexGlossaryReference(element: LatexParameterText) : PsiReferenceBase<LatexParameterText>(element), PsiPolyVariantReference { init { rangeInElement = ElementManipulators.getValueTextRange(element) } override fun isReferenceTo(element: PsiElement): Boolean { return multiResolve(false).any { it.element == element } } override fun resolve(): PsiElement? { val resolveResults = multiResolve(false) return if (resolveResults.size == 1) resolveResults[0].element else null } override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> { val glossaryEntries = LatexGlossaryEntryIndex.getItemsInFileSet(myElement.containingFile.originalFile) return glossaryEntries .filter { LatexGlossariesCommand.extractGlossaryLabel(it) == myElement.name } .toSet() .mapNotNull { PsiElementResolveResult( LatexGlossariesCommand.extractGlossaryLabelElement(it) ?: return@mapNotNull null ) } .toList() .toArray(emptyArray()) } override fun handleElementRename(newElementName: String): PsiElement { myElement.setName(newElementName) return myElement } }
src/nl/hannahsten/texifyidea/reference/LatexGlossaryReference.kt
4219364914
package org.worshipsongs.preference; import android.app.AlertDialog import android.content.Context import android.content.SharedPreferences import android.util.AttributeSet import android.view.LayoutInflater import android.widget.EditText import androidx.preference.DialogPreference import androidx.preference.PreferenceManager import org.worshipsongs.CommonConstants import org.worshipsongs.R /** * @author Madasamy * @since 3.3 */ class LiveSharePreference(context: Context, attrs: AttributeSet) : DialogPreference(context, attrs) { private var defaultSharedPreferences: SharedPreferences? = null private var liveSharePath: String? = null init { defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) liveSharePath = defaultSharedPreferences!!.getString(CommonConstants.LIVE_SHARE_PATH_KEY, "") } override fun onClick() { val customDialogView = LayoutInflater.from(context).inflate(R.layout.live_share_preference, null) val liveSharePathEditText = customDialogView.findViewById<EditText>(R.id.live_share_path_edit_text) liveSharePathEditText.setText(liveSharePath) val dialogBuilder = AlertDialog.Builder(context) .setView(customDialogView) .setTitle(context.getString(R.string.live_share_title)); dialogBuilder.setPositiveButton(R.string.ok) { dialog, which -> setLiveSharePath(liveSharePathEditText) dialog.cancel() } dialogBuilder.show() } private fun setLiveSharePath(liveSharePathEditText: EditText) { liveSharePath = liveSharePathEditText.text.toString() defaultSharedPreferences!!.edit().putString(CommonConstants.LIVE_SHARE_PATH_KEY, liveSharePathEditText.text.toString()).apply() } }
app/src/main/java/org/worshipsongs/preference/LiveSharePreference.kt
2648908476
@file:Suppress("unused", "RedundantOverride") package cases data class ValidDataClass(val i: Int) data class DataClassWithOverriddenMethods(val i: Int) { override fun hashCode(): Int { return super.hashCode() } override fun equals(other: Any?): Boolean { return super.equals(other) } override fun toString(): String { return super.toString() } } class ClassWithRegularFunctions { fun f1() {} fun f2() {} }
detekt-rules/src/test/resources/cases/DataClassContainsFunctionsNegative.kt
514777958
package swak.body.reader.provider.request import swak.http.request.UpdatableRequest import swak.body.reader.BodyReader interface PotentialBodyReaderChooser<out B> { fun forRequest(request: UpdatableRequest<String>): BodyReader<B>? }
core/src/main/kotlin/swak/body/reader/provider/request/PotentialBodyReaderChooser.kt
2394512868
import khttp.responses.Response import org.json.JSONArray import org.json.JSONObject // TODO: We currently aren't using GitLab as a container registry, but for our publishing rules and cleanup to work // properly, we will need to work out the details here and conditionally call these methods instead of DockerHub. // We would also need to ensure the same `git` commands (to retrieve active branches, for example) are also working class GitLabAPI : ContainerRegistryInterface { override val url: String get() = "https://gitlab.com/api/v4" override fun tags(publish: Publish): JSONArray { val (projectId, repositoryId) = this.projectAndRepositoryIds(publish) if(projectId > -1 && repositoryId > -1) { val urlTags = "${this.url}/projects/$projectId/registry/repositories/${repositoryId}/tags" val responseTags: Response = khttp.get(urlTags) val jsonResponse: JSONArray = responseTags.jsonArray return this.tagNamesFromResponseArray(jsonResponse, "name") } return JSONArray() } override fun token(publish: Publish): String? { return System.getenv("GITLAB_ACCESS_TOKEN") } override fun deleteTags(publish: Publish, tagsToDelete: List<String>): Boolean { val successes = mutableListOf<String>() val failures = mutableListOf<String>() val (projectId, repositoryId) = this.projectAndRepositoryIds(publish) if(projectId > -1 && repositoryId > -1) { val accessToken: String? = this.token(publish) tagsToDelete.forEach { tagToDelete -> val urlDelete = "${this.url}/projects/${projectId}/registry/repositories/${repositoryId}/tags/${tagToDelete}" val response: Response = khttp.delete( url = urlDelete, headers = mapOf(Pair("PRIVATE-TOKEN", "${accessToken ?: ""}")) ) val successfulDelete = response.statusCode == 200 if (successfulDelete) successes.add(tagToDelete) else failures.add(tagToDelete) } } else { println("Failed to retrieve project ID and repository ID from GitLab API!") } println("Cleaning GitLab -> Successfully deleted tags:${successes.joinToString(prefix = "\n- ", separator = "\n- ", postfix = "\n")}") println("Cleaning GitLab -> Failed to delete tags:${failures.joinToString(prefix = "\n- ", separator = "\n- ", postfix = "\n")}") return failures.size == 0 } data class GitLabIds(val projectId: Int, val repositoryId: Int) private fun projectAndRepositoryIds(publish: Publish): GitLabIds { // retrieve project ID by project name var projectId: Int = -1 val urlProject = "${this.url}/users/${publish.vendor}/projects?search=${publish.project}" val responseProject: Response = khttp.get(urlProject) val jsonProjects: JSONArray = responseProject.jsonArray if (jsonProjects.length() > 0) { val jsonProject: JSONObject = jsonProjects.getJSONObject(0) projectId = jsonProject.getInt("id") } // retrieve repository ID with knowledge of project ID var repositoryId: Int = -1 if(projectId > -1) { val urlRepositories = "${this.url}/projects/${projectId}/registry/repositories" val responseRepositories: Response = khttp.get(urlRepositories) val jsonRepositories: JSONArray = responseRepositories.jsonArray val jsonRepository: JSONObject? = jsonRepositories.find { r -> val repo: JSONObject = r as JSONObject repo.get("name") == publish.title } as JSONObject if (jsonRepository !== null) { repositoryId = jsonRepository.getInt("id") } } return GitLabIds(projectId, repositoryId) } }
buildSrc/src/main/kotlin/GitLabAPI.kt
3684382383
package de.thm.arsnova.service.httpgateway.filter import de.thm.arsnova.service.httpgateway.config.HttpGatewayProperties import io.github.bucket4j.Bandwidth import io.github.bucket4j.Bucket import io.github.bucket4j.Bucket4j import io.github.bucket4j.ConsumptionProbe import io.github.bucket4j.Refill import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.cloud.gateway.filter.ratelimit.AbstractRateLimiter import org.springframework.cloud.gateway.filter.ratelimit.RateLimiter import org.springframework.cloud.gateway.support.ConfigurationService import org.springframework.stereotype.Component import reactor.core.publisher.Mono import java.time.Duration import java.util.concurrent.ConcurrentHashMap @Component class RequestRateLimiter( private val httpGatewayProperties: HttpGatewayProperties, private val configurationService: ConfigurationService ) : AbstractRateLimiter<RequestRateLimiter.Config>(Config::class.java, CONFIGURATION_PROPERTY_NAME, configurationService) { companion object { private const val CONFIGURATION_PROPERTY_NAME = "rate-limiter" private const val QUERY_BUCKET_PREFIX = "QUERY_" private const val COMMAND_BUCKET_PREFIX = "COMMAND_" private val queryMethods = arrayOf("GET", "OPTIONS") } private val logger: Logger = LoggerFactory.getLogger(this::class.java) private val defaultConfig = Config(httpGatewayProperties) private val ipBucketMap: MutableMap<String, Bucket> = ConcurrentHashMap() /* The id is the key extracted from the KeyResolver configured in GatewayConfig. Format: <HTTPMethod>,<IP> Example: GET,172.18.0.18 */ override fun isAllowed(routeId: String, id: String): Mono<RateLimiter.Response> { logger.trace("Checking rate limit for {} from {}.", routeId, id) var routeConfig: Config? = config[routeId] if (routeConfig == null) { routeConfig = defaultConfig } val httpMethod = id.split(",")[0] val ipAddr = id.split(",")[1] val isQuery = queryMethods.any { it == httpMethod } if (ipAddr in httpGatewayProperties.gateway.rateLimit.whitelistedIps) { return Mono.just(RateLimiter.Response(true, mapOf("RateLimit-Remaining" to "infinite"))) } val bucket: Bucket = if (isQuery) { ipBucketMap.computeIfAbsent(QUERY_BUCKET_PREFIX + ipAddr) { _: String -> val refill: Refill = Refill.intervally(routeConfig.queryTokensPerTimeframe, routeConfig.duration) val limit: Bandwidth = Bandwidth.classic(routeConfig.queryBurstCapacity, refill) Bucket4j.builder().addLimit(limit).build() } } else { ipBucketMap.computeIfAbsent(COMMAND_BUCKET_PREFIX + ipAddr) { _: String -> val refill: Refill = Refill.intervally(routeConfig.commandTokensPerTimeframe, routeConfig.duration) val limit: Bandwidth = Bandwidth.classic(routeConfig.commandBurstCapacity, refill) Bucket4j.builder().addLimit(limit).build() } } if (bucket.availableTokens in 1..10) { // Check early so logs don't get spammed logger.info("Rate limit nearly exceeded for {} by {}.", routeId, id) } // tryConsume returns false immediately if no tokens available with the bucket val probe: ConsumptionProbe = bucket.tryConsumeAndReturnRemaining(1) return if (probe.isConsumed) { // the limit is not exceeded Mono.just(RateLimiter.Response(true, mapOf("RateLimit-Remaining" to probe.remainingTokens.toString()))) } else { // limit is exceeded Mono.just(RateLimiter.Response(false, mapOf("RateLimit-Remaining" to "none"))) } } class Config( private val httpGatewayProperties: HttpGatewayProperties ) { val queryTokensPerTimeframe: Long = httpGatewayProperties.gateway.rateLimit.queryTokensPerTimeframe val queryBurstCapacity: Long = httpGatewayProperties.gateway.rateLimit.queryBurstCapacity val commandTokensPerTimeframe: Long = httpGatewayProperties.gateway.rateLimit.commandTokensPerTimeframe val commandBurstCapacity: Long = httpGatewayProperties.gateway.rateLimit.commandBurstCapacity // the time window val duration: Duration = httpGatewayProperties.gateway.rateLimit.duration } }
gateway/src/main/kotlin/de/thm/arsnova/service/httpgateway/filter/RequestRateLimiter.kt
938145522
package cc.aoeiuv020.panovel.api.site import org.junit.Test /** * Created by AoEiuV020 on 2018.06.02-20:18:20. */ class FenghuajuTest : BaseNovelContextText(Fenghuaju::class) { @Test fun search() { search("都市") search("一念永恒", "耳根", "4_4282") search("我真是大明星", "尝谕", "3_3426") } @Test fun detail() { detail("18_18819", "18_18819", "天道图书馆", "横扫天涯", "http://www.fenghuaju.cc/image/18/18819/18819s.jpg", "张悬穿越异界,成了一名光荣的教师,脑海中多出了一个神秘的图书馆。\n" + "只要他看过的东西,无论人还是物,都能自动形成书籍,记录下对方各种各样的缺点,于是,他牛大了!\n" + "“昊天大帝,你怎么不喜欢穿内裤啊?堂堂大帝,能不能注意点形象?”\n" + "“玲珑仙子,你如果晚上再失眠,可以找我嘛,我这个人唱安眠曲很有一套的!”\n" + "“还有你,乾坤魔君,能不能少吃点大葱,想把老子熏死吗?”\n" + "……\n" + "这是一个师道传承,培养、指点世界最强者的牛逼拉风故事。", "2018-06-02 19:38:40") } @Test fun chapters() { chapters("18_18819", "第一章 骗子", "18_18819/2", null, "第一千二百五十章 张悬传授的绝招(上)", "18_18819/1267", "2018-06-02 19:38:40", 1263) } @Test fun content() { content("18_18819/1338", "“你……”", "张悬微微一笑。", 64) } }
api/src/test/java/cc/aoeiuv020/panovel/api/site/FenghuajuTest.kt
2341488495
package com.hotpodata.blockelganger import android.content.Context import com.google.android.gms.analytics.GoogleAnalytics import com.google.android.gms.analytics.Tracker import com.hotpodata.common.interfaces.IAnalyticsProvider /** * Created by jdrotos on 11/18/15. */ object AnalyticsMaster : IAnalyticsProvider{ //SCREENS val SCREEN_SINGLE_PLAYER = "SinglePlayerGameScreen" val SCREEN_LANDING = "LandingScreen" //CATEGORIES val CATEGORY_ACTION = "Action" //ACTIONS val ACTION_START_GAME = "StartGame" val ACTION_GAME_OVER = "GameOver" val ACTION_PAUSE = "Pause" val ACTION_RESUME = "Resume" val ACTION_START_OVER = "StartOver" val ACTION_HELP = "Help" val ACTION_UPDATE_FRAG = "UpdateFragment" val ACTION_OPEN_DRAWER = "OpenDrawer" val ACTION_SIGN_IN = "SignInClicked" val ACTION_ACHIEVEMENTS = "AchievementsClicked" val ACTION_LEADERBOARD = "LeaderBoardClicked" val ACTION_LEVEL_COMPLETE = "LevelComplete" val ACTION_EARLY_SMASH = "EarlySmash" //Labels val LABEL_LEVEL = "Level" val LABEL_LAUNCH_COUNT = "LaunchCount" val LABEL_SECONDS_REMAINING = "SecondsRemaining" private var tracker: Tracker? = null public override fun getTracker(context: Context): Tracker { val t = tracker ?: GoogleAnalytics.getInstance(context).newTracker(R.xml.global_tracker).apply { enableExceptionReporting(true) enableAdvertisingIdCollection(true) } tracker = t return t } }
app/src/main/java/com/hotpodata/blockelganger/AnalyticsMaster.kt
2481368291
package ca.six.demo.cleanviper.entity data class BookDetail(var chapters: List<BookChapter>) data class BookChapter(var name: String, var audio: String, var notebook: String)
CleanViper/app/src/main/java/ca/six/demo/cleanviper/entity/BookModel.kt
527608519
package org.ygl import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class TestFunctions { @Test fun testDuplicateFunction() { val program = """ fn foo() { print("foo1"); } fn foo() { print("foo2"); } fn main() { foo(); print(" bar"); } """ Assertions.assertThrows(CompilationException::class.java) { val result = compileAndEval(program) assertEquals("foo bar", result.trim()) } } @Test fun testVoidCall() { val program = """ fn foo() { print("foo"); } fn main() { foo(); print(" bar"); } """ val result = compileAndEval(program) assertEquals("foo bar", result.trim()) } @Test fun testComplexCall() { val program = """ fn bar(z) { readInt(x); return x + z; } fn foo() { x = 3 + bar(2); return x; } fn main() { x = foo() + bar(5); print(x); } """ val result = compileAndEval(program, userInput = "44") assertEquals("18", result.trim()) } @Test fun testNestedCall() { val program = """ fn bar() { return 3; } fn foo() { x = bar(); return x; } fn main() { x = foo(); print(x); } """ val result = compileAndEval(program) assertEquals("3", result.trim()) } @Test fun testSimpleParams() { val program = """ fn foo(x, y) { return x * y; } fn main() { x = foo(3, 4); print(x); } """ val result = compileAndEval(program) assertEquals("12", result.trim()) } @Test fun testSimpleReturn() { val program = """ fn foo() { return 5; } fn main() { x = 3 + foo(); print(x); } """ val result = compileAndEval(program) assertEquals("8", result.trim()) } @Test fun testLoopParams() { val program = """ fn isEven(x) { ret = 0; if ((x % 2) == 0) { ret = 1; } else { ret = 0; } return ret; } fn main() { i = 1; while (i <= 6) { if (isEven(i)) { print(i); } i += 1; } } """ val result = compileAndEval(program) assertEquals("246", result.trim()) } }
src/test/java/org/ygl/TestFunctions.kt
3690947125
package io.gitlab.arturbosch.detekt.rules.bugs import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.config import io.gitlab.arturbosch.detekt.api.internal.Configuration import io.gitlab.arturbosch.detekt.api.internal.RequiresTypeResolution import io.gitlab.arturbosch.detekt.api.simplePatternToRegex import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.types.typeUtil.isUnit /** * This rule warns on instances where a function, annotated with either `@CheckReturnValue` or `@CheckResult`, * returns a value but that value is not used in any way. The Kotlin compiler gives no warning for this scenario * normally so that's the rationale behind this rule. * * fun returnsValue() = 42 * fun returnsNoValue() {} * * <noncompliant> * returnsValue() * </noncompliant> * * <compliant> * if (42 == returnsValue()) {} * val x = returnsValue() * </compliant> */ @RequiresTypeResolution class IgnoredReturnValue(config: Config = Config.empty) : Rule(config) { override val issue: Issue = Issue( "IgnoredReturnValue", Severity.Defect, "This call returns a value which is ignored", Debt.TWENTY_MINS ) @Configuration("if the rule should check only annotated methods") private val restrictToAnnotatedMethods: Boolean by config(defaultValue = true) @Configuration("List of glob patterns to be used as inspection annotation") private val returnValueAnnotations: List<Regex> by config(listOf("*.CheckResult", "*.CheckReturnValue")) { it.map(String::simplePatternToRegex) } @Configuration("Annotations to skip this inspection") private val ignoreReturnValueAnnotations: List<Regex> by config(listOf("*.CanIgnoreReturnValue")) { it.map(String::simplePatternToRegex) } @Suppress("ReturnCount") override fun visitCallExpression(expression: KtCallExpression) { super.visitCallExpression(expression) if (bindingContext == BindingContext.EMPTY) return if (expression.isUsedAsExpression(bindingContext)) return val resultingDescriptor = expression.getResolvedCall(bindingContext)?.resultingDescriptor ?: return if (resultingDescriptor.returnType?.isUnit() == true) return val annotations = resultingDescriptor.annotations if (annotations.any { it in ignoreReturnValueAnnotations }) return if (restrictToAnnotatedMethods && (annotations + resultingDescriptor.containingDeclaration.annotations).none { it in returnValueAnnotations } ) return val messageText = expression.calleeExpression?.text ?: expression.text report( CodeSmell( issue, Entity.from(expression), message = "The call $messageText is returning a value that is ignored." ) ) } @Suppress("UnusedPrivateMember") private operator fun List<Regex>.contains(annotation: AnnotationDescriptor): Boolean { val fqName = annotation.fqName?.asString() ?: return false return any { it.matches(fqName) } } }
detekt-rules-errorprone/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/bugs/IgnoredReturnValue.kt
3414090274
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.ng.features.trackdelete import android.content.ContentResolver import android.net.Uri import androidx.annotation.WorkerThread import nl.sogeti.android.gpstracker.ng.features.FeatureConfiguration import nl.sogeti.android.gpstracker.ng.features.summary.SummaryManager import nl.sogeti.android.gpstracker.ng.features.util.AbstractTrackPresenter import nl.sogeti.android.gpstracker.service.util.readName import javax.inject.Inject class TrackDeletePresenter : AbstractTrackPresenter() { internal val viewModel = TrackDeleteModel() @Inject lateinit var contentResolver: ContentResolver @Inject lateinit var summaryManager: SummaryManager init { FeatureConfiguration.featureComponent.inject(this) } @WorkerThread override fun onChange() { trackUri?.let { loadTrackName(it) } } fun ok() { trackUri?.let { deleteTrack(it) summaryManager.removeFromCache(it) viewModel.dismiss.set(true) } } fun cancel() { viewModel.dismiss.set(true) } private fun loadTrackName(trackUri: Uri) { val trackName = trackUri.readName() viewModel.trackUri.set(trackUri) viewModel.name.set(trackName) } private fun deleteTrack(trackUri: Uri) { contentResolver.delete(trackUri, null, null) } }
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/trackdelete/TrackDeletePresenter.kt
106224811
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) 2016 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenGPSTracker is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.ng.features.trackedit import android.net.Uri import androidx.annotation.WorkerThread import android.view.View import android.widget.AdapterView import android.widget.AdapterView.INVALID_POSITION import android.widget.ImageView import android.widget.TextView import nl.sogeti.android.gpstracker.ng.features.FeatureConfiguration import nl.sogeti.android.gpstracker.ng.features.summary.SummaryManager import nl.sogeti.android.gpstracker.ng.features.util.AbstractTrackPresenter import nl.sogeti.android.gpstracker.service.util.readName import nl.sogeti.android.gpstracker.service.util.updateName import javax.inject.Inject class TrackEditPresenter : AbstractTrackPresenter() { @Inject lateinit var summaryManager: SummaryManager val viewModel = TrackEditModel() val onItemSelectedListener: AdapterView.OnItemSelectedListener by lazy { object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { viewModel.selectedPosition.set(position) } override fun onNothingSelected(parent: AdapterView<*>?) { viewModel.selectedPosition.set(INVALID_POSITION) } } } init { FeatureConfiguration.featureComponent.inject(this) } @WorkerThread override fun onChange() { viewModel.trackUri.set(trackUri) loadTrackTypePosition(trackUri) loadTrackName(trackUri) } fun ok(trackUri: Uri, trackName: String) { saveTrackName(trackUri, trackName) saveTrackTypePosition(trackUri) summaryManager.removeFromCache(trackUri) viewModel.dismissed.set(true) } fun cancel() { viewModel.dismissed.set(true) } private fun loadTrackName(trackUri: Uri?) { if (trackUri != null) { val trackName = trackUri.readName() viewModel.name.set(trackName) } else { viewModel.name.set("") } } private fun loadTrackTypePosition(trackUri: Uri?) { if (trackUri != null) { val trackType = trackUri.readTrackType() val position = viewModel.trackTypes.indexOfFirst { it == trackType } viewModel.selectedPosition.set(position) } else { viewModel.selectedPosition.set(INVALID_POSITION) } } private fun saveTrackName(trackUri: Uri, trackName: String) { trackUri.updateName(trackName) } private fun saveTrackTypePosition(trackUri: Uri) { val trackType = viewModel.trackTypes[viewModel.selectedPosition.get()] trackUri.saveTrackType(trackType) } data class ViewHolder(val imageView: ImageView, val textView: TextView) }
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/trackedit/TrackEditPresenter.kt
756195043
package com.jraska.github.client.android.test import androidx.lifecycle.ViewModel import androidx.test.espresso.IdlingRegistry import com.jraska.github.client.core.android.ServiceModel import com.jraska.github.client.coroutines.AppDispatchers import dagger.Module import dagger.Provides import dagger.multibindings.ClassKey import dagger.multibindings.IntoMap import kotlinx.coroutines.Dispatchers import javax.inject.Singleton @Module object FakeAndroidCoreModule { @Provides @IntoMap @ClassKey(ServiceModel::class) internal fun provideServiceModel(): ServiceModel { return object : ServiceModel {} // Make sure the collection is not empty } @Provides @IntoMap @ClassKey(ViewModel::class) internal fun provideViewModel(): ViewModel { return object : ViewModel() {} // Make sure the collection is not empty } @Provides @Singleton fun appDispatchers(): AppDispatchers { val idlingDispatcher = IdlingDispatcher(Dispatchers.IO) IdlingRegistry.getInstance().register(idlingDispatcher) return AppDispatchers(Dispatchers.Main, idlingDispatcher) } }
core-android-testing/src/main/java/com/jraska/github/client/android/test/FakeAndroidCoreModule.kt
1743605767
package com.antyzero.mpk.transit.database import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class MpkDatabaseTest { val mpkDatabase = MpkDatabase(MpkDatabaseDownloader().get()) @Test internal fun lines() { mpkDatabase.lines() .generalTest() .presentResults() } @Test internal fun points() { mpkDatabase.points() .generalTest() .presentResults() } @Test internal fun shedules() { mpkDatabase.schedules() .generalTest() .presentResults() } @Test internal fun routes() { mpkDatabase.routes() .generalTest() .presentResults() } @Test internal fun stopDepartures() { mpkDatabase.stopDepartures() .generalTest() .presentResults() } @Test internal fun stops() { mpkDatabase.stops() .generalTest() .presentResults() } @Test internal fun streets() { mpkDatabase.streets() .generalTest() .presentResults() } @Test internal fun variants() { mpkDatabase.variants() .generalTest() .presentResults() } private fun Collection<Any>.generalTest() = this.apply { assertThat(this).isNotEmpty } private fun Collection<Any>.presentResults() = this.apply { // print(this.joinToString(separator = "\n")) } }
sqlite/src/test/kotlin/com/antyzero/mpk/transit/database/MpkDatabaseTest.kt
1887598328
package gg.octave.bot.music.filters import com.sedmelluq.discord.lavaplayer.filter.FloatPcmAudioFilter import com.sedmelluq.discord.lavaplayer.filter.equalizer.Equalizer import com.sedmelluq.discord.lavaplayer.format.AudioDataFormat class EqualizerFilter : FilterConfig<Equalizer> { private var config: Equalizer.() -> Unit = {} override fun configure(transformer: Equalizer.() -> Unit): EqualizerFilter { config = transformer return this } override fun build(downstream: FloatPcmAudioFilter, format: AudioDataFormat): FloatPcmAudioFilter { return Equalizer(format.channelCount, downstream, zero) .also(config) } companion object { private val zero = (0..14).map { 0.0f }.toFloatArray() } }
src/main/kotlin/gg/octave/bot/music/filters/EqualizerFilter.kt
4047246462
package treehou.se.habit.dagger.fragment import dagger.Module import dagger.Provides import treehou.se.habit.dagger.ViewModule import treehou.se.habit.ui.servers.sitemaps.sitemapsettings.SitemapSettingsContract import treehou.se.habit.ui.servers.sitemaps.sitemapsettings.SitemapSettingsFragment import treehou.se.habit.ui.servers.sitemaps.sitemapsettings.SitemapSettingsPresenter @Module class SitemapSettingsModule(fragment: SitemapSettingsFragment) : ViewModule<SitemapSettingsFragment>(fragment) { @Provides fun provideView(): SitemapSettingsContract.View { return view } @Provides fun providePresenter(presenter: SitemapSettingsPresenter): SitemapSettingsContract.Presenter { return presenter } }
mobile/src/main/java/treehou/se/habit/dagger/fragment/SitemapSettingsModule.kt
3981881722
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.browsers import com.intellij.execution.BeforeRunTask import com.intellij.execution.BeforeRunTaskProvider import com.intellij.execution.ExecutionListener import com.intellij.execution.ExecutionManager import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.process.ProcessHandler import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.components.BaseState import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.Key import com.intellij.ui.components.CheckBox import com.intellij.ui.components.dialog import com.intellij.ui.layout.* import com.intellij.util.ui.UIUtil import com.intellij.util.xmlb.annotations.Attribute import com.intellij.xml.XmlBundle import org.jetbrains.concurrency.Promise import javax.swing.Icon import javax.swing.border.EmptyBorder internal class LaunchBrowserBeforeRunTaskProvider : BeforeRunTaskProvider<LaunchBrowserBeforeRunTask>() { companion object { val ID = Key.create<LaunchBrowserBeforeRunTask>("LaunchBrowser.Before.Run") } override fun getName() = "Launch Web Browser" override fun getId() = ID override fun getIcon(): Icon = AllIcons.Nodes.PpWeb override fun isConfigurable() = true override fun createTask(runConfiguration: RunConfiguration) = LaunchBrowserBeforeRunTask() override fun configureTask(context: DataContext, runConfiguration: RunConfiguration, task: LaunchBrowserBeforeRunTask): Promise<Boolean> { val state = task.state val modificationCount = state.modificationCount val browserSelector = BrowserSelector() val browserComboBox = browserSelector.mainComponent if (UIUtil.isUnderAquaLookAndFeel()) { browserComboBox.border = EmptyBorder(3, 0, 0, 0) } state.browser?.let { browserSelector.selected = it } val url = TextFieldWithBrowseButton() state.url?.let { url.text = it } StartBrowserPanel.setupUrlField(url, runConfiguration.project) val startJavaScriptDebuggerCheckBox = if (JavaScriptDebuggerStarter.Util.hasStarters()) CheckBox(XmlBundle.message("start.browser.with.js.debugger"), state.withDebugger) else null val panel = panel { row("Browser:") { browserComboBox() startJavaScriptDebuggerCheckBox?.invoke() } row("Url:") { url(growPolicy = GrowPolicy.MEDIUM_TEXT) } } dialog("Launch Web Browser", panel = panel, resizable = true, focusedComponent = url) .show() state.browser = browserSelector.selected state.url = url.text if (startJavaScriptDebuggerCheckBox != null) { state.withDebugger = startJavaScriptDebuggerCheckBox.isSelected } return Promise.resolve(modificationCount != state.modificationCount) } override fun executeTask(context: DataContext?, configuration: RunConfiguration, env: ExecutionEnvironment, task: LaunchBrowserBeforeRunTask): Boolean { val disposable = Disposer.newDisposable() Disposer.register(env.project, disposable) val executionId = env.executionId env.project.messageBus.connect(disposable).subscribe(ExecutionManager.EXECUTION_TOPIC, object: ExecutionListener { override fun processNotStarted(executorId: String, env: ExecutionEnvironment) { Disposer.dispose(disposable) } override fun processStarted(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler) { if (env.executionId != executionId) { return } Disposer.dispose(disposable) val settings = StartBrowserSettings() settings.browser = task.state.browser settings.isStartJavaScriptDebugger = task.state.withDebugger settings.url = task.state.url settings.isSelected = true BrowserStarter(configuration, settings, handler).start() } }) return true } } internal class LaunchBrowserBeforeRunTaskState : BaseState() { @get:Attribute(value = "browser", converter = WebBrowserReferenceConverter::class) var browser by property<WebBrowser>() @get:Attribute() var url by string() @get:Attribute() var withDebugger by property(false) } internal class LaunchBrowserBeforeRunTask : BeforeRunTask<LaunchBrowserBeforeRunTask>(LaunchBrowserBeforeRunTaskProvider.ID), PersistentStateComponent<LaunchBrowserBeforeRunTaskState> { private var state = LaunchBrowserBeforeRunTaskState() override fun loadState(state: LaunchBrowserBeforeRunTaskState) { state.resetModificationCount() this.state = state } override fun getState() = state }
xml/impl/src/com/intellij/ide/browsers/LaunchBrowserBeforeRunTaskProvider.kt
3085437109
package com.beust.kobalt.api import com.beust.kobalt.IncrementalTaskInfo /** * Plug-ins that will be invoked during the "assemble" task and wish to return an incremental task instead * of a regular one. */ interface IIncrementalAssemblyContributor : IContributor { fun assemble(project: Project, context: KobaltContext) : IncrementalTaskInfo }
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/api/IIncrementalAssemblyContributor.kt
1862321759
package cat.pantsu.nyaapantsu.util import android.Manifest import android.app.Activity import android.app.DownloadManager import android.content.Context import android.content.pm.PackageManager import android.media.MediaPlayer import android.net.Uri import android.os.Build import android.os.Environment import android.support.design.widget.Snackbar import android.util.Log import android.view.View import cat.pantsu.nyaapantsu.R import org.jetbrains.anko.toast /** * Created by ltype on 2017/7/16. */ class Utils { companion object { fun download(activity: Activity, parent: View, url: String, name: String) { if (!mayRequestPermission(activity, parent, Manifest.permission.WRITE_EXTERNAL_STORAGE, 10)) { if (isExternalStorageWritable()) { Log.d("download", "URL: " + url) val request = DownloadManager.Request(Uri.parse(url)) request.setDescription("Download a torrent file") request.setTitle(name + " - NyaaPantsu") // in order for this if to run, you must use the android 3.2 to compile your app request.allowScanningByMediaScanner() request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, name + ".torrent") Log.d("download", "request") // get download service and enqueue file val manager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager manager.enqueue(request) } else { activity.toast(activity.getString(R.string.external_storage_not_available)) } } } fun mayRequestPermission(activity: Activity, parent: View, permission: String, code: Int): Boolean { val c = parent.context if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return false } if (c.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) { return false } if (activity.shouldShowRequestPermissionRationale(permission)) { Snackbar.make(parent, R.string.permission_required, Snackbar.LENGTH_INDEFINITE) .setAction(android.R.string.ok, { _ -> activity.requestPermissions(arrayOf(permission), code) }) .show() } else { activity.requestPermissions(arrayOf(permission), code) } return true } fun isExternalStorageWritable(): Boolean { val state = Environment.getExternalStorageState() if (Environment.MEDIA_MOUNTED == state) { return true } return false } fun playVoice(c: Context) { //TODO support sukebei mode, maybe need a application context for hold player val player = MediaPlayer.create(c, R.raw.nyanpass) player.setOnCompletionListener { player.release() } player.start() } } }
app/src/main/java/cat/pantsu/nyaapantsu/util/Utils.kt
460188416
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.parser import svnserver.parser.token.* import java.io.BufferedOutputStream import java.io.Closeable import java.io.IOException import java.io.OutputStream import java.nio.charset.StandardCharsets /** * Интерфейс для записи данных в поток. * * @author Artem V. Navrotskiy <[email protected]> */ class SvnServerWriter constructor(stream: OutputStream) : Closeable { private val stream: OutputStream private var depth: Int = 0 @Throws(IOException::class) fun listBegin(): SvnServerWriter { return write(ListBeginToken.instance) } @Throws(IOException::class) fun listEnd(): SvnServerWriter { return write(ListEndToken.instance) } @Throws(IOException::class) fun word(c: Char): SvnServerWriter { return word(c.toString()) } @Throws(IOException::class) fun word(word: String): SvnServerWriter { WordToken.write(stream, word) if (depth == 0) stream.flush() return this } @Throws(IOException::class) fun stringNullable(text: String?): SvnServerWriter { listBegin() if (text != null) string(text) listEnd() return this } @Throws(IOException::class) fun string(text: String): SvnServerWriter { return binary(text.toByteArray(StandardCharsets.UTF_8)) } @Throws(IOException::class) fun binary(data: ByteArray, offset: Int = 0, length: Int = data.size): SvnServerWriter { StringToken.write(stream, data, offset, length) if (depth == 0) stream.flush() return this } @Throws(IOException::class) fun number(number: Long): SvnServerWriter { NumberToken.write(stream, number) if (depth == 0) stream.flush() return this } @Throws(IOException::class) fun separator(): SvnServerWriter { stream.write('\n'.code) return this } @Throws(IOException::class) fun bool(value: Boolean): SvnServerWriter { return word(if (value) "true" else "false") } @Throws(IOException::class) fun write(token: SvnServerToken): SvnServerWriter { token.write(stream) if ((token == ListBeginToken.instance)) { depth++ } else if ((token == ListEndToken.instance)) { depth-- if (depth < 0) { throw IllegalStateException("Too many closed lists.") } } if (depth == 0) { separator() stream.flush() } return this } @JvmOverloads @Throws(IOException::class) fun writeMap(properties: Map<String, String?>?, nullableValues: Boolean = false): SvnServerWriter { listBegin() if (properties != null) { for (entry: Map.Entry<String, String?> in properties.entries) { listBegin() string(entry.key) if (nullableValues) { stringNullable(entry.value) } else { string(entry.value!!) } listEnd() } } listEnd() return this } @Throws(IOException::class) override fun close() { stream.use { if (depth != 0) throw IllegalStateException("Unmatched parentheses") } } init { this.stream = BufferedOutputStream(stream) } }
src/main/kotlin/svnserver/parser/SvnServerWriter.kt
3317923305