repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jameshnsears/brexitsoundboard
app/src/main/java/com/github/jameshnsears/brexitsoundboard/sound/MediaStoreHelper.kt
1
2867
package com.github.jameshnsears.brexitsoundboard.sound import android.content.ContentResolver import android.content.ContentValues import android.content.Context import android.content.res.Resources import android.os.Environment import android.provider.MediaStore import android.util.TypedValue import com.github.jameshnsears.brexitsoundboard.R import com.github.jameshnsears.brexitsoundboard.utils.ToastHelper.makeToast import org.apache.commons.io.IOUtils import timber.log.Timber import java.io.File import java.io.FileOutputStream class MediaStoreHelper { fun installSound( resources: Resources, context: Context, contentResolver: ContentResolver, resourceId: Int, soundName: String, mediaType: String ) { try { val resPathToFilename = TypedValue() resources.getValue(resourceId, resPathToFilename, true) val inputStream = context.resources.openRawResource(resourceId) val fileDestination = getFileDestination(soundName) val fileOutputStream = FileOutputStream(fileDestination) IOUtils.copy(inputStream, fileOutputStream) fileOutputStream.close() inputStream.close() contentResolver.insert( MediaStore.Audio.Media.getContentUriForPath(fileDestination.absolutePath)!!, getContentValues(soundName, mediaType, fileDestination) ) makeToast(context, context.getString(R.string.install_menu_confirmation, soundName)) } catch (e: Exception) { Timber.e(String.format("", e.message)) } } fun getFileDestination(soundName: String): File { val fileFolderDestination = getFileFolderDestination() if (!fileFolderDestination.exists()) { fileFolderDestination.mkdirs() } val fileDestination = File(fileFolderDestination.absolutePath + "/" + soundName + ".mp3") Timber.d(fileFolderDestination.absolutePath) return fileDestination } fun getFileFolderDestination(): File { return File(Environment.getExternalStorageDirectory().absolutePath + "/Music") } private fun getContentValues(soundName: String, mediaType: String, fileDestination: File): ContentValues { val contentValues = ContentValues() contentValues.put(MediaStore.MediaColumns.TITLE, soundName) contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3") contentValues.put(MediaStore.Audio.Media.IS_RINGTONE, false) contentValues.put(MediaStore.Audio.Media.IS_NOTIFICATION, false) contentValues.put(MediaStore.Audio.Media.IS_ALARM, false) contentValues.put(mediaType, true) contentValues.put(MediaStore.MediaColumns.DATA, fileDestination.absolutePath) return contentValues } }
apache-2.0
063ac8b6334824eeccce3f3d000e0100
36.233766
110
0.707011
4.994774
false
false
false
false
ThiagoGarciaAlves/intellij-community
plugins/stream-debugger/test/com/intellij/debugger/streams/exec/streamex/MappingOperationsTest.kt
4
1184
// Copyright 2000-2017 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.debugger.streams.exec.streamex /** * @author Vitaliy.Bibaev */ class MappingOperationsTest : StreamExTestCase() { override val packageName: String = "mapping" fun testElements() = doStreamExWithResultTest() fun testMapToEntry() = doStreamExWithResultTest() fun testMapKeys() = doStreamExWithResultTest() fun testMapToKey() = doStreamExWithResultTest() fun testMapValues() = doStreamExWithResultTest() fun testMapToValue() = doStreamExWithResultTest() fun testMapKeyValue() = doStreamExWithResultTest() fun testInvert() = doStreamExWithResultTest() fun testKeys() = doStreamExWithResultTest() fun testValues() = doStreamExWithResultTest() fun testJoin() = doStreamExVoidTest() fun testPairMap() = doStreamExWithResultTest() fun testMapFirst() = doStreamExWithResultTest() fun testMapLast() = doStreamExWithResultTest() fun testMapFirstOrElse() = doStreamExWithResultTest() fun testMapLastOrElse() = doStreamExWithResultTest() fun testWithFirst() = doStreamExWithResultTest() }
apache-2.0
f2fc267a7f3f011044ced357bccd4505
33.852941
140
0.769426
4.369004
false
true
false
false
sksamuel/ktest
kotest-framework/kotest-framework-api/src/commonMain/kotlin/io/kotest/core/spec/style/wordSpec.kt
1
1621
package io.kotest.core.spec.style import io.kotest.core.factory.TestFactory import io.kotest.core.factory.TestFactoryConfiguration import io.kotest.core.factory.build import io.kotest.core.spec.DslDrivenSpec import io.kotest.core.spec.resolvedDefaultConfig import io.kotest.core.spec.style.scopes.RootTestRegistration import io.kotest.core.spec.style.scopes.WordSpecRootContext import io.kotest.core.test.TestCaseConfig /** * Creates a [TestFactory] from the given block. * * The receiver of the block is a [WordSpecTestFactoryConfiguration] which allows tests * to be defined using the 'word-spec' style. */ fun wordSpec(block: WordSpecTestFactoryConfiguration.() -> Unit): TestFactory { val config = WordSpecTestFactoryConfiguration() config.block() return config.build() } /** * Decorates a [TestFactoryConfiguration] with the WordSpec DSL. */ class WordSpecTestFactoryConfiguration : TestFactoryConfiguration(), WordSpecRootContext { override fun defaultConfig(): TestCaseConfig = resolvedDefaultConfig() override fun registration(): RootTestRegistration = RootTestRegistration.from(this) } abstract class WordSpec(body: WordSpec.() -> Unit = {}) : DslDrivenSpec(), WordSpecRootContext { init { body() } override fun defaultConfig(): TestCaseConfig = resolvedDefaultConfig() override fun registration(): RootTestRegistration = RootTestRegistration.from(this) // need to overload this so that when doing "string" should haveLength(5) in a word spec, we don't // clash with the other should method //infix fun String?.should(matcher: Matcher<String?>) = TODO() }
mit
5c07836a034404b2bf4a38ddf7eb893f
35.840909
101
0.770512
4.441096
false
true
false
false
vector-im/vector-android
vector/src/main/java/im/vector/notifications/NotificationUtils.kt
2
35080
/* * Copyright 2018 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.notifications import android.annotation.SuppressLint import android.annotation.TargetApi import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.text.TextUtils import androidx.annotation.StringRes import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.app.RemoteInput import androidx.core.app.TaskStackBuilder import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import im.vector.BuildConfig import im.vector.R import im.vector.activity.JoinRoomActivity import im.vector.activity.LockScreenActivity import im.vector.activity.VectorHomeActivity import im.vector.activity.VectorRoomActivity import im.vector.receiver.NotificationBroadcastReceiver import im.vector.util.PreferencesManager import im.vector.util.startNotificationChannelSettingsIntent import org.matrix.androidsdk.core.Log import java.util.* fun supportNotificationChannels() = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) /** * Util class for creating notifications. */ object NotificationUtils { private val LOG_TAG = NotificationUtils::class.java.simpleName /* ========================================================================================== * IDs for notifications * ========================================================================================== */ /** * Identifier of the foreground notification used to keep the application alive * when it runs in background. * This notification, which is not removable by the end user, displays what * the application is doing while in background. */ const val NOTIFICATION_ID_FOREGROUND_SERVICE = 61 /* ========================================================================================== * IDs for actions * ========================================================================================== */ private const val JOIN_ACTION = "${BuildConfig.APPLICATION_ID}.NotificationActions.JOIN_ACTION" private const val REJECT_ACTION = "${BuildConfig.APPLICATION_ID}.NotificationActions.REJECT_ACTION" private const val QUICK_LAUNCH_ACTION = "${BuildConfig.APPLICATION_ID}.NotificationActions.QUICK_LAUNCH_ACTION" const val MARK_ROOM_READ_ACTION = "${BuildConfig.APPLICATION_ID}.NotificationActions.MARK_ROOM_READ_ACTION" const val SMART_REPLY_ACTION = "${BuildConfig.APPLICATION_ID}.NotificationActions.SMART_REPLY_ACTION" const val DISMISS_SUMMARY_ACTION = "${BuildConfig.APPLICATION_ID}.NotificationActions.DISMISS_SUMMARY_ACTION" const val DISMISS_ROOM_NOTIF_ACTION = "${BuildConfig.APPLICATION_ID}.NotificationActions.DISMISS_ROOM_NOTIF_ACTION" private const val TAP_TO_VIEW_ACTION = "${BuildConfig.APPLICATION_ID}.NotificationActions.TAP_TO_VIEW_ACTION" /* ========================================================================================== * IDs for channels * ========================================================================================== */ // on devices >= android O, we need to define a channel for each notifications private const val LISTENING_FOR_EVENTS_NOTIFICATION_CHANNEL_ID = "LISTEN_FOR_EVENTS_NOTIFICATION_CHANNEL_ID" private const val NOISY_NOTIFICATION_CHANNEL_ID = "DEFAULT_NOISY_NOTIFICATION_CHANNEL_ID" private const val SILENT_NOTIFICATION_CHANNEL_ID = "DEFAULT_SILENT_NOTIFICATION_CHANNEL_ID_V2" private const val CALL_NOTIFICATION_CHANNEL_ID = "CALL_NOTIFICATION_CHANNEL_ID_V2" /* ========================================================================================== * Channel names * ========================================================================================== */ /** * Create notification channels. * * @param context the context */ @TargetApi(Build.VERSION_CODES.O) fun createNotificationChannels(context: Context) { if (!supportNotificationChannels()) { return } val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val accentColor = ContextCompat.getColor(context, R.color.notification_accent_color) //Migration - the noisy channel was deleted and recreated when sound preference was changed (id was DEFAULT_NOISY_NOTIFICATION_CHANNEL_ID_BASE // + currentTimeMillis). //Now the sound can only be change directly in system settings, so for app upgrading we are deleting this former channel //Starting from this version the channel will not be dynamic for (channel in notificationManager.notificationChannels) { val channelId = channel.id val legacyBaseName = "DEFAULT_NOISY_NOTIFICATION_CHANNEL_ID_BASE" if (channelId.startsWith(legacyBaseName)) { notificationManager.deleteNotificationChannel(channelId) } } //Migration - Remove deprecated channels for (channelId in listOf("DEFAULT_SILENT_NOTIFICATION_CHANNEL_ID", "CALL_NOTIFICATION_CHANNEL_ID")) { notificationManager.getNotificationChannel(channelId)?.let { notificationManager.deleteNotificationChannel(channelId) } } /** * Default notification importance: shows everywhere, makes noise, but does not visually * intrude. */ notificationManager.createNotificationChannel(NotificationChannel(NOISY_NOTIFICATION_CHANNEL_ID, context.getString(R.string.notification_noisy_notifications), NotificationManager.IMPORTANCE_DEFAULT) .apply { description = context.getString(R.string.notification_noisy_notifications) enableVibration(true) enableLights(true) lightColor = accentColor }) /** * Low notification importance: shows everywhere, but is not intrusive. */ notificationManager.createNotificationChannel(NotificationChannel(SILENT_NOTIFICATION_CHANNEL_ID, context.getString(R.string.notification_silent_notifications), NotificationManager.IMPORTANCE_LOW) .apply { description = context.getString(R.string.notification_silent_notifications) setSound(null, null) enableLights(true) lightColor = accentColor }) notificationManager.createNotificationChannel(NotificationChannel(LISTENING_FOR_EVENTS_NOTIFICATION_CHANNEL_ID, context.getString(R.string.notification_listening_for_events), NotificationManager.IMPORTANCE_MIN) .apply { description = context.getString(R.string.notification_listening_for_events) setSound(null, null) setShowBadge(false) }) notificationManager.createNotificationChannel(NotificationChannel(CALL_NOTIFICATION_CHANNEL_ID, context.getString(R.string.call), NotificationManager.IMPORTANCE_HIGH) .apply { description = context.getString(R.string.call) setSound(null, null) enableLights(true) lightColor = accentColor }) } /** * Build a polling thread listener notification * * @param context Android context * @param subTitleResId subtitle string resource Id of the notification * @return the polling thread listener notification */ @SuppressLint("NewApi") fun buildForegroundServiceNotification(context: Context, @StringRes subTitleResId: Int, withProgress: Boolean = true): Notification { // build the pending intent go to the home screen if this is clicked. val i = Intent(context, VectorHomeActivity::class.java) i.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP val pi = PendingIntent.getActivity(context, 0, i, 0) val accentColor = ContextCompat.getColor(context, R.color.notification_accent_color) val builder = NotificationCompat.Builder(context, LISTENING_FOR_EVENTS_NOTIFICATION_CHANNEL_ID) .setContentTitle(context.getString(subTitleResId)) .setSmallIcon(R.drawable.sync) .setCategory(NotificationCompat.CATEGORY_SERVICE) .setColor(accentColor) .setContentIntent(pi) .apply { if (withProgress) { setProgress(0, 0, true) } } // PRIORITY_MIN should not be used with Service#startForeground(int, Notification) builder.priority = NotificationCompat.PRIORITY_LOW // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // builder.priority = NotificationCompat.PRIORITY_MIN // } val notification = builder.build() notification.flags = notification.flags or Notification.FLAG_NO_CLEAR if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // some devices crash if this field is not set // even if it is deprecated // setLatestEventInfo() is deprecated on Android M, so we try to use // reflection at runtime, to avoid compiler error: "Cannot resolve method.." try { val deprecatedMethod = notification.javaClass .getMethod("setLatestEventInfo", Context::class.java, CharSequence::class.java, CharSequence::class.java, PendingIntent::class.java) deprecatedMethod.invoke(notification, context, context.getString(R.string.riot_app_name), context.getString(subTitleResId), pi) } catch (ex: Exception) { Log.e(LOG_TAG, "## buildNotification(): Exception - setLatestEventInfo() Msg=" + ex.message, ex) } } return notification } /** * Build an incoming call notification. * This notification starts the VectorHomeActivity which is in charge of centralizing the incoming call flow. * * @param context the context. * @param isVideo true if this is a video call, false for voice call * @param roomName the room name in which the call is pending. * @param matrixId the matrix id * @param callId the call id. * @return the call notification. */ @SuppressLint("NewApi") fun buildIncomingCallNotification(context: Context, isVideo: Boolean, roomName: String, matrixId: String, callId: String): Notification { val accentColor = ContextCompat.getColor(context, R.color.notification_accent_color) val builder = NotificationCompat.Builder(context, CALL_NOTIFICATION_CHANNEL_ID) .setContentTitle(ensureTitleNotEmpty(context, roomName)) .apply { if (isVideo) { setContentText(context.getString(R.string.incoming_video_call)) } else { setContentText(context.getString(R.string.incoming_voice_call)) } } .setSmallIcon(R.drawable.incoming_call_notification_transparent) .setCategory(NotificationCompat.CATEGORY_CALL) .setLights(accentColor, 500, 500) //Compat: Display the incoming call notification on the lock screen builder.priority = NotificationCompat.PRIORITY_MAX // clear the activity stack to home activity val intent = Intent(context, VectorHomeActivity::class.java) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK) .putExtra(VectorHomeActivity.EXTRA_CALL_SESSION_ID, matrixId) .putExtra(VectorHomeActivity.EXTRA_CALL_ID, callId) // Recreate the back stack val stackBuilder = TaskStackBuilder.create(context) .addParentStack(VectorHomeActivity::class.java) .addNextIntent(intent) // android 4.3 issue // use a generator for the private requestCode. // When using 0, the intent is not created/launched when the user taps on the notification. // val pendingIntent = stackBuilder.getPendingIntent(Random().nextInt(1000), PendingIntent.FLAG_UPDATE_CURRENT) builder.setContentIntent(pendingIntent) return builder.build() } /** * Build a pending call notification * * @param context the context. * @param isVideo true if this is a video call, false for voice call * @param roomName the room name in which the call is pending. * @param roomId the room Id * @param matrixId the matrix id * @param callId the call id. * @return the call notification. */ @SuppressLint("NewApi") fun buildPendingCallNotification(context: Context, isVideo: Boolean, roomName: String, roomId: String, matrixId: String, callId: String): Notification { val builder = NotificationCompat.Builder(context, CALL_NOTIFICATION_CHANNEL_ID) .setContentTitle(ensureTitleNotEmpty(context, roomName)) .apply { if (isVideo) { setContentText(context.getString(R.string.video_call_in_progress)) } else { setContentText(context.getString(R.string.call_in_progress)) } } .setSmallIcon(R.drawable.incoming_call_notification_transparent) .setCategory(NotificationCompat.CATEGORY_CALL) // Display the pending call notification on the lock screen if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { builder.priority = NotificationCompat.PRIORITY_MAX } // Build the pending intent for when the notification is clicked val roomIntent = Intent(context, VectorRoomActivity::class.java) .putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomId) .putExtra(VectorRoomActivity.EXTRA_MATRIX_ID, matrixId) .putExtra(VectorRoomActivity.EXTRA_START_CALL_ID, callId) // Recreate the back stack val stackBuilder = TaskStackBuilder.create(context) .addParentStack(VectorRoomActivity::class.java) .addNextIntent(roomIntent) // android 4.3 issue // use a generator for the private requestCode. // When using 0, the intent is not created/launched when the user taps on the notification. // val pendingIntent = stackBuilder.getPendingIntent(Random().nextInt(1000), PendingIntent.FLAG_UPDATE_CURRENT) builder.setContentIntent(pendingIntent) return builder.build() } /** * Build a temporary (because service will be stopped just after) notification for the CallService, when a call is ended */ fun buildCallEndedNotification(context: Context): Notification { return NotificationCompat.Builder(context, CALL_NOTIFICATION_CHANNEL_ID) .setContentTitle(context.getString(R.string.call_ended)) .setSmallIcon(R.drawable.ic_material_call_end_grey) .setCategory(NotificationCompat.CATEGORY_CALL) .build() } /** * Build a notification for a Room */ fun buildMessagesListNotification(context: Context, messageStyle: NotificationCompat.MessagingStyle, roomInfo: RoomEventGroupInfo, largeIcon: Bitmap?, lastMessageTimestamp: Long, senderDisplayNameForReplyCompat: String?): Notification? { val accentColor = ContextCompat.getColor(context, R.color.notification_accent_color) // Build the pending intent for when the notification is clicked val openRoomIntent = buildOpenRoomIntent(context, roomInfo.roomId) val smallIcon = if (roomInfo.shouldBing) R.drawable.icon_notif_important else R.drawable.logo_transparent val channelID = if (roomInfo.shouldBing) NOISY_NOTIFICATION_CHANNEL_ID else SILENT_NOTIFICATION_CHANNEL_ID return NotificationCompat.Builder(context, channelID) .setWhen(lastMessageTimestamp) // MESSAGING_STYLE sets title and content for API 16 and above devices. .setStyle(messageStyle) // A category allows groups of notifications to be ranked and filtered – per user or system settings. // For example, alarm notifications should display before promo notifications, or message from known contact // that can be displayed in not disturb mode if white listed (the later will need compat28.x) .setCategory(NotificationCompat.CATEGORY_MESSAGE) // Title for API < 16 devices. .setContentTitle(roomInfo.roomDisplayName) // Content for API < 16 devices. .setContentText(context.getString(R.string.notification_new_messages)) // Number of new notifications for API <24 (M and below) devices. .setSubText(context .resources .getQuantityString(R.plurals.room_new_messages_notification, messageStyle.messages.size, messageStyle.messages.size) ) // Auto-bundling is enabled for 4 or more notifications on API 24+ (N+) // devices and all Wear devices. But we want a custom grouping, so we specify the groupID // TODO Group should be current user display name .setGroup(context.getString(R.string.riot_app_name)) //In order to avoid notification making sound twice (due to the summary notification) .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY) .setSmallIcon(smallIcon) // Set primary color (important for Wear 2.0 Notifications). .setColor(accentColor) // Sets priority for 25 and below. For 26 and above, 'priority' is deprecated for // 'importance' which is set in the NotificationChannel. The integers representing // 'priority' are different from 'importance', so make sure you don't mix them. .apply { priority = NotificationCompat.PRIORITY_DEFAULT if (roomInfo.shouldBing) { //Compat PreferencesManager.getNotificationRingTone(context)?.let { setSound(it) } setLights(accentColor, 500, 500) } else { priority = NotificationCompat.PRIORITY_LOW } //Add actions and notification intents // Mark room as read val markRoomReadIntent = Intent(context, NotificationBroadcastReceiver::class.java) markRoomReadIntent.action = MARK_ROOM_READ_ACTION markRoomReadIntent.data = Uri.parse("foobar://${roomInfo.roomId}") markRoomReadIntent.putExtra(NotificationBroadcastReceiver.KEY_ROOM_ID, roomInfo.roomId) val markRoomReadPendingIntent = PendingIntent.getBroadcast(context, System.currentTimeMillis().toInt(), markRoomReadIntent, PendingIntent.FLAG_UPDATE_CURRENT) addAction(NotificationCompat.Action( R.drawable.ic_material_done_all_white, context.getString(R.string.action_mark_room_read), markRoomReadPendingIntent)) // Quick reply if (!roomInfo.hasSmartReplyError) { buildQuickReplyIntent(context, roomInfo.roomId, senderDisplayNameForReplyCompat)?.let { replyPendingIntent -> val remoteInput = RemoteInput.Builder(NotificationBroadcastReceiver.KEY_TEXT_REPLY) .setLabel(context.getString(R.string.action_quick_reply)) .build() NotificationCompat.Action.Builder(R.drawable.vector_notification_quick_reply, context.getString(R.string.action_quick_reply), replyPendingIntent) .addRemoteInput(remoteInput) .build()?.let { addAction(it) } } } if (openRoomIntent != null) { setContentIntent(openRoomIntent) } if (largeIcon != null) { setLargeIcon(largeIcon) } val intent = Intent(context, NotificationBroadcastReceiver::class.java) intent.putExtra(NotificationBroadcastReceiver.KEY_ROOM_ID, roomInfo.roomId) intent.action = DISMISS_ROOM_NOTIF_ACTION val pendingIntent = PendingIntent.getBroadcast(context.applicationContext, System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT) setDeleteIntent(pendingIntent) } .build() } fun buildSimpleEventNotification(context: Context, simpleNotifiableEvent: NotifiableEvent, largeIcon: Bitmap?, matrixId: String): Notification? { val accentColor = ContextCompat.getColor(context, R.color.notification_accent_color) // Build the pending intent for when the notification is clicked val smallIcon = if (simpleNotifiableEvent.noisy) R.drawable.icon_notif_important else R.drawable.logo_transparent val channelID = if (simpleNotifiableEvent.noisy) NOISY_NOTIFICATION_CHANNEL_ID else SILENT_NOTIFICATION_CHANNEL_ID return NotificationCompat.Builder(context, channelID) .setContentTitle(context.getString(R.string.riot_app_name)) .setContentText(simpleNotifiableEvent.description) .setGroup(context.getString(R.string.riot_app_name)) .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_SUMMARY) .setSmallIcon(smallIcon) .setColor(accentColor) .apply { if (simpleNotifiableEvent is InviteNotifiableEvent) { val roomId = simpleNotifiableEvent.roomId // offer to type a quick reject button val rejectIntent = JoinRoomActivity.getRejectRoomIntent(context, roomId, matrixId) // the action must be unique else the parameters are ignored rejectIntent.action = REJECT_ACTION rejectIntent.data = Uri.parse("foobar://$roomId&$matrixId") addAction( R.drawable.vector_notification_reject_invitation, context.getString(R.string.reject), PendingIntent.getActivity(context, System.currentTimeMillis().toInt(), rejectIntent, 0)) // offer to type a quick accept button val joinIntent = JoinRoomActivity.getJoinRoomIntent(context, roomId, matrixId) // the action must be unique else the parameters are ignored joinIntent.action = JOIN_ACTION joinIntent.data = Uri.parse("foobar://$roomId&$matrixId") addAction( R.drawable.vector_notification_accept_invitation, context.getString(R.string.join), PendingIntent.getActivity(context, 0, joinIntent, 0)) } else { setAutoCancel(true) } val contentIntent = Intent(context, VectorHomeActivity::class.java) contentIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP //pending intent get reused by system, this will mess up the extra params, so put unique info to avoid that contentIntent.data = Uri.parse("foobar://" + simpleNotifiableEvent.eventId) setContentIntent(PendingIntent.getActivity(context, 0, contentIntent, 0)) if (largeIcon != null) { setLargeIcon(largeIcon) } if (simpleNotifiableEvent.noisy) { //Compat priority = NotificationCompat.PRIORITY_DEFAULT PreferencesManager.getNotificationRingTone(context)?.let { setSound(it) } setLights(accentColor, 500, 500) } else { priority = NotificationCompat.PRIORITY_LOW } setAutoCancel(true) } .build() } private fun buildOpenRoomIntent(context: Context, roomId: String): PendingIntent? { val roomIntentTap = Intent(context, VectorRoomActivity::class.java) roomIntentTap.putExtra(VectorRoomActivity.EXTRA_ROOM_ID, roomId) roomIntentTap.action = TAP_TO_VIEW_ACTION //pending intent get reused by system, this will mess up the extra params, so put unique info to avoid that roomIntentTap.data = Uri.parse("foobar://openRoom?$roomId") // Recreate the back stack return TaskStackBuilder.create(context) .addNextIntentWithParentStack(Intent(context, VectorHomeActivity::class.java)) .addNextIntent(roomIntentTap) .getPendingIntent(System.currentTimeMillis().toInt(), PendingIntent.FLAG_UPDATE_CURRENT) } private fun buildOpenHomePendingIntentForSummary(context: Context): PendingIntent { val intent = Intent(context, VectorHomeActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP intent.putExtra(VectorHomeActivity.EXTRA_CLEAR_EXISTING_NOTIFICATION, true) intent.data = Uri.parse("foobar://tapSummary") return PendingIntent.getActivity(context, Random().nextInt(1000), intent, PendingIntent.FLAG_UPDATE_CURRENT) } /* Direct reply is new in Android N, and Android already handles the UI, so the right pending intent here will ideally be a Service/IntentService (for a long running background task) or a BroadcastReceiver, which runs on the UI thread. It also works without unlocking, making the process really fluid for the user. However, for Android devices running Marshmallow and below (API level 23 and below), it will be more appropriate to use an activity. Since you have to provide your own UI. */ private fun buildQuickReplyIntent(context: Context, roomId: String, senderName: String?): PendingIntent? { val intent: Intent if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { intent = Intent(context, NotificationBroadcastReceiver::class.java) intent.action = SMART_REPLY_ACTION intent.data = Uri.parse("foobar://$roomId") intent.putExtra(NotificationBroadcastReceiver.KEY_ROOM_ID, roomId) return PendingIntent.getBroadcast(context, System.currentTimeMillis().toInt(), intent, PendingIntent.FLAG_UPDATE_CURRENT) } else { if (!LockScreenActivity.isDisplayingALockScreenActivity()) { // start your activity for Android M and below val quickReplyIntent = Intent(context, LockScreenActivity::class.java) quickReplyIntent.putExtra(LockScreenActivity.EXTRA_ROOM_ID, roomId) quickReplyIntent.putExtra(LockScreenActivity.EXTRA_SENDER_NAME, senderName ?: "") // the action must be unique else the parameters are ignored quickReplyIntent.action = QUICK_LAUNCH_ACTION quickReplyIntent.data = Uri.parse("foobar://$roomId") return PendingIntent.getActivity(context, 0, quickReplyIntent, 0) } } return null } //// Number of new notifications for API <24 (M and below) devices. /** * Build the summary notification */ fun buildSummaryListNotification(context: Context, style: NotificationCompat.Style, compatSummary: String, noisy: Boolean, lastMessageTimestamp: Long): Notification? { val accentColor = ContextCompat.getColor(context, R.color.notification_accent_color) val smallIcon = if (noisy) R.drawable.icon_notif_important else R.drawable.logo_transparent return NotificationCompat.Builder(context, if (noisy) NOISY_NOTIFICATION_CHANNEL_ID else SILENT_NOTIFICATION_CHANNEL_ID) // used in compat < N, after summary is built based on child notifications .setWhen(lastMessageTimestamp) .setStyle(style) .setContentTitle(context.getString(R.string.riot_app_name)) .setCategory(NotificationCompat.CATEGORY_MESSAGE) .setSmallIcon(smallIcon) //set content text to support devices running API level < 24 .setContentText(compatSummary) .setGroup(context.getString(R.string.riot_app_name)) //set this notification as the summary for the group .setGroupSummary(true) .setColor(accentColor) .apply { if (noisy) { //Compat priority = NotificationCompat.PRIORITY_DEFAULT PreferencesManager.getNotificationRingTone(context)?.let { setSound(it) } setLights(accentColor, 500, 500) } else { //compat priority = NotificationCompat.PRIORITY_LOW } } .setContentIntent(buildOpenHomePendingIntentForSummary(context)) .setDeleteIntent(getDismissSummaryPendingIntent(context)) .build() } private fun getDismissSummaryPendingIntent(context: Context): PendingIntent { val intent = Intent(context, NotificationBroadcastReceiver::class.java) intent.action = DISMISS_SUMMARY_ACTION intent.data = Uri.parse("foobar://deleteSummary") return PendingIntent.getBroadcast(context.applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) } fun showNotificationMessage(context: Context, tag: String?, id: Int, notification: Notification) { with(NotificationManagerCompat.from(context)) { notify(tag, id, notification) } } fun cancelNotificationMessage(context: Context, tag: String?, id: Int) { NotificationManagerCompat.from(context) .cancel(tag, id) } /** * Cancel the foreground notification service */ fun cancelNotificationForegroundService(context: Context) { NotificationManagerCompat.from(context) .cancel(NOTIFICATION_ID_FOREGROUND_SERVICE) } /** * Cancel all the notification */ fun cancelAllNotifications(context: Context) { // Keep this try catch (reported by GA) try { NotificationManagerCompat.from(context) .cancelAll() } catch (e: Exception) { Log.e(LOG_TAG, "## cancelAllNotifications() failed " + e.message, e) } } /** * Return true it the user has enabled the do not disturb mode */ fun isDoNotDisturbModeOn(context: Context): Boolean { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return false } // We cannot use NotificationManagerCompat here. val setting = (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).currentInterruptionFilter return setting == NotificationManager.INTERRUPTION_FILTER_NONE || setting == NotificationManager.INTERRUPTION_FILTER_ALARMS } private fun ensureTitleNotEmpty(context: Context, title: String?): CharSequence { if (TextUtils.isEmpty(title)) { return context.getString(R.string.app_name) } return title!! } fun openSystemSettingsForSilentCategory(fragment: Fragment) { startNotificationChannelSettingsIntent(fragment, SILENT_NOTIFICATION_CHANNEL_ID) } fun openSystemSettingsForNoisyCategory(fragment: Fragment) { startNotificationChannelSettingsIntent(fragment, NOISY_NOTIFICATION_CHANNEL_ID) } fun openSystemSettingsForCallCategory(fragment: Fragment) { startNotificationChannelSettingsIntent(fragment, CALL_NOTIFICATION_CHANNEL_ID) } }
apache-2.0
5bc0e44a24a4561a47465e3c264ef764
47.651872
150
0.60642
5.430031
false
false
false
false
JakeWharton/dex-method-list
diffuse/src/main/kotlin/com/jakewharton/diffuse/report/strings.kt
1
664
package com.jakewharton.diffuse.report import com.jakewharton.diffuse.Size internal fun Int.toUnitString(unit: String, vararg specializations: Pair<Int, String>): String { return buildString { append(this@toUnitString) append(' ') append(specializations.toMap()[this@toUnitString] ?: unit) } } internal fun Int.toDiffString(zeroSign: Char? = null) = buildString { if (this@toDiffString > 0) { append('+') } else if (this@toDiffString == 0 && zeroSign != null) { append(zeroSign) } append(this@toDiffString) } internal fun Size.toDiffString() = buildString { if (bytes > 0L) { append('+') } append(this@toDiffString) }
apache-2.0
871f941ee893a0e2680f75ed94885331
23.592593
96
0.686747
3.42268
false
false
false
false
hazuki0x0/YuzuBrowser
module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/ui/original/AdBlockItemDeleteDialog.kt
1
2389
/* * Copyright (C) 2017-2019 Hazuki * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.hazuki.yuzubrowser.adblock.ui.original import android.app.AlertDialog import android.app.Dialog import android.content.Context import android.os.Bundle import jp.hazuki.yuzubrowser.adblock.R class AdBlockItemDeleteDialog : androidx.fragment.app.DialogFragment() { private var listener: OnBlockItemDeleteListener? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val arguments = arguments ?: throw IllegalArgumentException() val builder = AlertDialog.Builder(activity) builder.setTitle(R.string.pref_delete) builder.setMessage(getString(R.string.pref_ad_block_delete_confirm, arguments.getString(ARG_ITEM))) builder.setPositiveButton(android.R.string.ok) { _, _ -> listener!!.onDelete(arguments.getInt(ARG_INDEX), arguments.getInt(ARG_ID)) } builder.setNegativeButton(android.R.string.cancel, null) return builder.create() } override fun onAttach(context: Context) { super.onAttach(context) listener = parentFragment as OnBlockItemDeleteListener } override fun onDetach() { super.onDetach() listener = null } internal interface OnBlockItemDeleteListener { fun onDelete(index: Int, id: Int) } companion object { private const val ARG_INDEX = "index" private const val ARG_ID = "id" private const val ARG_ITEM = "item" operator fun invoke(index: Int, id: Int, item: String): AdBlockItemDeleteDialog { return AdBlockItemDeleteDialog().apply { arguments = Bundle().apply { putInt(ARG_INDEX, index) putInt(ARG_ID, id) putString(ARG_ITEM, item) } } } } }
apache-2.0
f269c760ac6b7ae2588d3e6a24a212f0
34.132353
141
0.675596
4.473783
false
false
false
false
thuytrinh/KotlinPlayground
src/test/kotlin/timesheet/TimeSheetTest.kt
1
3332
package timesheet import kotlinx.datetime.* import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.junit.Test import java.io.File import java.time.DayOfWeek import java.time.YearMonth import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit class TimeSheetTest { @Test fun `generate time-sheets`() { generateFor(YearMonth.of(2020, Month.SEPTEMBER)) generateFor(YearMonth.of(2020, Month.OCTOBER)) generateFor(YearMonth.of(2020, Month.NOVEMBER)) generateFor(YearMonth.of(2020, Month.DECEMBER), holidays = (24..31).toList()) generateFor(YearMonth.of(2021, Month.JANUARY), holidays = listOf(1)) generateFor(YearMonth.of(2021, Month.FEBRUARY)) generateFor(YearMonth.of(2021, Month.MARCH)) generateFor(YearMonth.of(2021, Month.APRIL), holidays = listOf(2, 5)) generateFor(YearMonth.of(2021, Month.MAY), holidays = listOf(13, 14, 24)) generateFor(YearMonth.of(2021, Month.JUNE), holidays = listOf(3, 4)) generateFor(YearMonth.of(2021, Month.JULY), holidays = (10..23).toList()) generateFor(YearMonth.of(2021, Month.AUGUST), holidays = emptyList()) generateFor(YearMonth.of(2021, Month.SEPTEMBER), holidays = (15..30).toList()) } } private fun generateFor(yearMonth: YearMonth, holidays: List<Int> = emptyList()) { val firstDate = LocalDate(year = yearMonth.year, month = yearMonth.month, dayOfMonth = 1) val dayCount = firstDate.daysUntil(firstDate.plus(1, DateTimeUnit.MONTH)) (0 until dayCount) .map { firstDate.plus(it, DateTimeUnit.DAY) } .filterNot { it.dayOfWeek == DayOfWeek.SATURDAY || it.dayOfWeek == DayOfWeek.SUNDAY } .filterNot { it.dayOfMonth in holidays } .map { val morning = it.atTime(hour = 9, minute = 0, second = 0).toJavaLocalDateTime() val beforeLunch = it.atTime(hour = 12, minute = 0, second = 0).toJavaLocalDateTime() val afterLunch = it.atTime(hour = 12, minute = 30, second = 0).toJavaLocalDateTime() val end = it.atTime(hour = 17, minute = 30, second = 0).toJavaLocalDateTime() val totalWorkingHoursInDay = ChronoUnit.HOURS.between( morning, beforeLunch ) + ChronoUnit.HOURS.between(afterLunch, end) val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME listOf( TimeEntry( startDate = formatter.format(morning) + "Z", endDate = formatter.format(beforeLunch) + "Z", location = "Bosch eBike Digital", type = "timer", ), TimeEntry( startDate = formatter.format(afterLunch) + "Z", endDate = formatter.format(end) + "Z", location = "Bosch eBike Digital", type = "timer", ), ) to totalWorkingHoursInDay } .run { val totalWorkingHoursInMonth = map { it.second }.sum() TimeSheet(flatMap { it.first }) to totalWorkingHoursInMonth } .apply { println("Total working hours in $yearMonth: $second") File("build", "thuy-trinh-$yearMonth.json") .writeText(Json.encodeToString(first)) } } @Serializable private data class TimeSheet( val timers: List<TimeEntry>, ) @Serializable private data class TimeEntry( val location: String, val type: String, val startDate: String, val endDate: String, )
mit
94e36f44a868511928179f6943faf1e3
36.438202
91
0.684874
3.681768
false
false
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/service/SyncService.kt
1
4523
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Adrien Béraud <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.service import android.app.Notification import android.app.PendingIntent import android.app.Service import android.content.Intent import android.content.pm.ServiceInfo import android.os.Build import android.os.Handler import android.os.IBinder import androidx.core.app.NotificationCompat import cx.ring.R import cx.ring.application.JamiApplication import cx.ring.client.HomeActivity import cx.ring.services.NotificationServiceImpl import cx.ring.utils.ContentUriHandler import dagger.hilt.android.AndroidEntryPoint import net.jami.services.NotificationService import java.util.* import javax.inject.Inject @AndroidEntryPoint class SyncService : Service() { private var serviceUsers = 0 private val mRandom = Random() private var notification: Notification? = null @Inject lateinit var mNotificationService: NotificationService override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { val action = intent.action if (ACTION_START == action) { if (notification == null) { val deleteIntent = Intent(ACTION_STOP) .setClass(applicationContext, SyncService::class.java) val contentIntent = Intent(Intent.ACTION_VIEW) .setClass(applicationContext, HomeActivity::class.java) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK) notification = NotificationCompat.Builder(this, NotificationServiceImpl.NOTIF_CHANNEL_SYNC) .setContentTitle(getString(R.string.notif_sync_title)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) .setAutoCancel(false) .setVibrate(null) .setSmallIcon(R.drawable.ic_ring_logo_white) .setCategory(NotificationCompat.CATEGORY_PROGRESS) .setOnlyAlertOnce(true) .setDeleteIntent(PendingIntent.getService(applicationContext, mRandom.nextInt(), deleteIntent, ContentUriHandler.immutable())) .setContentIntent(PendingIntent.getActivity(applicationContext, mRandom.nextInt(), contentIntent, ContentUriHandler.immutable())) .build() } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) startForeground(NOTIF_SYNC_SERVICE_ID, notification!!, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC) else startForeground(NOTIF_SYNC_SERVICE_ID, notification) if (serviceUsers == 0) { JamiApplication.instance?.startDaemon() } serviceUsers++ val timeout = intent.getLongExtra(EXTRA_TIMEOUT, -1) if (timeout > 0) { Handler().postDelayed({ try { startService(Intent(ACTION_STOP).setClass(applicationContext, SyncService::class.java)) } catch (ignored: IllegalStateException) { } }, timeout) } } else if (ACTION_STOP == action) { serviceUsers-- if (serviceUsers == 0) { stopForeground(true) stopSelf() notification = null } } return START_NOT_STICKY } override fun onBind(intent: Intent): IBinder? { return null } companion object { const val NOTIF_SYNC_SERVICE_ID = 1004 const val ACTION_START = "startService" const val ACTION_STOP = "stopService" const val EXTRA_TIMEOUT = "timeout" } }
gpl-3.0
fc2185f2bc918f607d4b9a91819093b2
40.118182
149
0.646174
4.8676
false
false
false
false
ilya-g/kotlinx.collections.immutable
core/jvmTest/src/testUtilsJvm.kt
1
591
/* * Copyright 2016-2019 JetBrains s.r.o. * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. */ package tests import kotlin.test.assertEquals public actual fun assertTypeEquals(expected: Any?, actual: Any?) { assertEquals(expected?.javaClass, actual?.javaClass) } public actual val currentPlatform: TestPlatform get() = TestPlatform.JVM actual object NForAlgorithmComplexity { actual val O_N: Int = 1_000_000 actual val O_NlogN: Int = 200_000 actual val O_NN: Int = 10_000 actual val O_NNlogN: Int = 5_000 }
apache-2.0
b59712491bf4a206dd16e39d8300424f
27.190476
107
0.725888
3.560241
false
true
false
false
savoirfairelinux/ring-client-android
ring-android/app/src/main/java/cx/ring/client/ContactDetailsActivity.kt
1
18180
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Adrien Béraud <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.client import android.content.* import android.content.res.ColorStateList import android.graphics.Color import android.graphics.drawable.Drawable import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import cx.ring.R import cx.ring.application.JamiApplication import cx.ring.client.ColorChooserBottomSheet.IColorSelected import cx.ring.client.EmojiChooserBottomSheet.IEmojiSelected import cx.ring.databinding.ActivityContactDetailsBinding import cx.ring.databinding.ItemContactActionBinding import cx.ring.databinding.ItemContactHorizontalBinding import cx.ring.fragments.CallFragment import cx.ring.fragments.ConversationFragment import cx.ring.services.SharedPreferencesServiceImpl.Companion.getConversationPreferences import cx.ring.utils.ConversationPath import cx.ring.views.AvatarDrawable import cx.ring.views.AvatarFactory import dagger.hilt.android.AndroidEntryPoint import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.disposables.CompositeDisposable import net.jami.model.* import net.jami.services.ConversationFacade import net.jami.services.AccountService import net.jami.services.ContactService import net.jami.services.NotificationService import javax.inject.Inject import javax.inject.Singleton @AndroidEntryPoint class ContactDetailsActivity : AppCompatActivity() { @Inject @Singleton lateinit var mConversationFacade: ConversationFacade @Inject lateinit var mContactService: ContactService @Inject @Singleton lateinit var mAccountService: AccountService private var binding: ActivityContactDetailsBinding? = null internal class ContactAction { @DrawableRes val icon: Int val drawable: Single<Drawable>? val title: CharSequence val callback: () -> Unit var iconTint: Int var iconSymbol: CharSequence? = null constructor(@DrawableRes i: Int, tint: Int, t: CharSequence, cb: () -> Unit) { icon = i iconTint = tint title = t callback = cb drawable = null } constructor(@DrawableRes i: Int, t: CharSequence, cb: () -> Unit) { icon = i iconTint = Color.BLACK title = t callback = cb drawable = null } constructor(d: Single<Drawable>?, t: CharSequence, cb: () -> Unit) { drawable = d icon = 0 iconTint = Color.BLACK title = t callback = cb } fun setSymbol(t: CharSequence?) { iconSymbol = t } } internal class ContactActionView( val binding: ItemContactActionBinding, parentDisposable: CompositeDisposable ) : RecyclerView.ViewHolder(binding.root) { var callback: (() -> Unit)? = null val disposable = CompositeDisposable() init { parentDisposable.add(disposable) itemView.setOnClickListener { try { callback?.invoke() } catch (e: Exception) { Log.w(TAG, "Error performing action", e) } } } } private class ContactActionAdapter(private val disposable: CompositeDisposable) : RecyclerView.Adapter<ContactActionView>() { val actions = ArrayList<ContactAction>() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactActionView { val layoutInflater = LayoutInflater.from(parent.context) val itemBinding = ItemContactActionBinding.inflate(layoutInflater, parent, false) return ContactActionView(itemBinding, disposable) } override fun onBindViewHolder(holder: ContactActionView, position: Int) { val action = actions[position] holder.disposable.clear() if (action.drawable != null) { holder.disposable.add(action.drawable.subscribe { background: Drawable -> holder.binding.actionIcon.background = background }) } else { holder.binding.actionIcon.setBackgroundResource(action.icon) holder.binding.actionIcon.text = action.iconSymbol if (action.iconTint != Color.BLACK) ViewCompat.setBackgroundTintList( holder.binding.actionIcon, ColorStateList.valueOf(action.iconTint) ) } holder.binding.actionTitle.text = action.title holder.callback = action.callback } override fun onViewRecycled(holder: ContactActionView) { holder.disposable.clear() holder.binding.actionIcon.background = null } override fun getItemCount(): Int { return actions.size } } internal class ContactView(val binding: ItemContactHorizontalBinding, parentDisposable: CompositeDisposable) : RecyclerView.ViewHolder(binding.root) { var callback: (() -> Unit)? = null val disposable = CompositeDisposable() init { parentDisposable.add(disposable) itemView.setOnClickListener { try { callback?.invoke() } catch (e: Exception) { Log.w(TAG, "Error performing action", e) } } } } private class ContactViewAdapter( private val disposable: CompositeDisposable, private val contacts: List<ContactViewModel>, private val callback: (Contact) -> Unit ) : RecyclerView.Adapter<ContactView>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactView { val layoutInflater = LayoutInflater.from(parent.context) val itemBinding = ItemContactHorizontalBinding.inflate(layoutInflater, parent, false) return ContactView(itemBinding, disposable) } override fun onBindViewHolder(holder: ContactView, position: Int) { val contact = contacts[position] holder.disposable.clear() holder.disposable.add(AvatarFactory.getAvatar(holder.itemView.context, contact, false) .subscribe { drawable: Drawable -> holder.binding.photo.setImageDrawable(drawable) }) holder.binding.displayName.text = if (contact.contact.isUser) holder.itemView.context.getText(R.string.conversation_info_contact_you) else contact.displayName holder.itemView.setOnClickListener { callback.invoke(contact.contact) } } override fun onViewRecycled(holder: ContactView) { holder.disposable.clear() holder.binding.photo.setImageDrawable(null) } override fun getItemCount(): Int { return contacts.size } } private val mDisposableBag = CompositeDisposable() private val adapter = ContactActionAdapter(mDisposableBag) private var colorAction: ContactAction? = null private var symbolAction: ContactAction? = null private var colorActionPosition = 0 private var symbolActionPosition = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val path = ConversationPath.fromIntent(intent) if (path == null) { finish() return } JamiApplication.instance?.startDaemon() val conversation = try { mConversationFacade .startConversation(path.accountId, path.conversationUri) .blockingGet() } catch (e: Throwable) { finish() return } val binding = ActivityContactDetailsBinding.inflate(layoutInflater).also { this.binding = it } setContentView(binding.root) setSupportActionBar(binding.toolbar) supportActionBar?.apply { setDisplayHomeAsUpEnabled(true) setDisplayShowHomeEnabled(true) } val preferences = getConversationPreferences(this, conversation.accountId, conversation.uri) colorActionPosition = 0 symbolActionPosition = 1 mDisposableBag.add(mConversationFacade.observeConversation(conversation).subscribe { vm -> binding.contactImage.setImageDrawable(AvatarDrawable.Builder() .withViewModel(vm) .withCircleCrop(true) .build(this)) supportActionBar?.title = vm.contactName binding.contactListLayout.visibility = if (conversation.isSwarm) View.VISIBLE else View.GONE if (conversation.isSwarm) { binding.contactList.adapter = ContactViewAdapter(mDisposableBag, vm.contacts) { contact -> copyAndShow(contact.uri.rawUriString) } } binding.conversationId.text = vm.uriTitle }) /*Map<String, String> details = Ringservice.getCertificateDetails(conversation.getContact().getUri().getRawRingId()); for (Map.Entry<String, String> e : details.entrySet()) { Log.w(TAG, e.getKey() + " -> " + e.getValue()); }*/ @StringRes val infoString = if (conversation.isSwarm) if (conversation.mode.blockingFirst() == Conversation.Mode.OneToOne) R.string.conversation_type_private else R.string.conversation_type_group else R.string.conversation_type_contact /*@DrawableRes int infoIcon = conversation.isSwarm() ? (conversation.getMode() == Conversation.Mode.OneToOne ? R.drawable.baseline_person_24 : R.drawable.baseline_group_24) : R.drawable.baseline_person_24;*/ //adapter.actions.add(new ContactAction(R.drawable.baseline_info_24, getText(infoString), () -> {})); binding.conversationType.setText(infoString) //binding.conversationType.setCompoundDrawables(getDrawable(infoIcon), null, null, null); colorAction = ContactAction(R.drawable.item_color_background, 0, getText(R.string.conversation_preference_color)) { val frag = ColorChooserBottomSheet() frag.setCallback(object : IColorSelected { override fun onColorSelected(color: Int) { colorAction!!.iconTint = color adapter.notifyItemChanged(colorActionPosition) preferences.edit() .putInt(ConversationFragment.KEY_PREFERENCE_CONVERSATION_COLOR, color) .apply() } }) frag.show(supportFragmentManager, "colorChooser") } val color = preferences.getInt(ConversationFragment.KEY_PREFERENCE_CONVERSATION_COLOR, resources.getColor(R.color.color_primary_light)) colorAction!!.iconTint = color adapter.actions.add(colorAction!!) symbolAction = ContactAction(0, getText(R.string.conversation_preference_emoji)) { EmojiChooserBottomSheet().apply { setCallback(object : IEmojiSelected { override fun onEmojiSelected(emoji: String?) { symbolAction?.setSymbol(emoji) adapter.notifyItemChanged(symbolActionPosition) preferences.edit() .putString(ConversationFragment.KEY_PREFERENCE_CONVERSATION_SYMBOL, emoji) .apply() } }) show(supportFragmentManager, "colorChooser") } }.apply { setSymbol(preferences.getString(ConversationFragment.KEY_PREFERENCE_CONVERSATION_SYMBOL, resources.getString(R.string.conversation_default_emoji))) adapter.actions.add(this) } val conversationUri = conversation.uri.toString()//if (conversation.isSwarm) conversation.uri.toString() else conversation.uriTitle if (conversation.contacts.size <= 2 && conversation.contacts.isNotEmpty()) { val contact = conversation.contact!! adapter.actions.add(ContactAction(R.drawable.baseline_call_24, getText(R.string.ab_action_audio_call)) { goToCallActivity(conversation, contact.uri, true) }) adapter.actions.add(ContactAction(R.drawable.baseline_videocam_24, getText(R.string.ab_action_video_call)) { goToCallActivity(conversation, contact.uri, false) }) if (!conversation.isSwarm) { adapter.actions.add(ContactAction(R.drawable.baseline_clear_all_24, getText(R.string.conversation_action_history_clear)) { MaterialAlertDialogBuilder(this@ContactDetailsActivity) .setTitle(R.string.clear_history_dialog_title) .setMessage(R.string.clear_history_dialog_message) .setPositiveButton(R.string.conversation_action_history_clear) { _: DialogInterface?, _: Int -> mConversationFacade.clearHistory(conversation.accountId, contact.uri).subscribe() Snackbar.make(binding.root, R.string.clear_history_completed, Snackbar.LENGTH_LONG).show() } .setNegativeButton(android.R.string.cancel, null) .create() .show() }) } adapter.actions.add(ContactAction(R.drawable.baseline_block_24, getText(R.string.conversation_action_block_this)) { MaterialAlertDialogBuilder(this@ContactDetailsActivity) .setTitle(getString(R.string.block_contact_dialog_title, conversationUri)) .setMessage(getString(R.string.block_contact_dialog_message, conversationUri)) .setPositiveButton(R.string.conversation_action_block_this) { _: DialogInterface?, _: Int -> mAccountService.removeContact(conversation.accountId, contact.uri.rawRingId,true) Toast.makeText(applicationContext, getString(R.string.block_contact_completed, conversationUri), Toast.LENGTH_LONG).show() finish() } .setNegativeButton(android.R.string.cancel, null) .create() .show() }) } binding.conversationId.text = conversationUri binding.infoCard.setOnClickListener { copyAndShow(path.conversationId) } binding.contactActionList.adapter = adapter } private fun copyAndShow(toCopy: String) { val clipboard = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager clipboard.setPrimaryClip(ClipData.newPlainText(getText(R.string.clip_contact_uri), toCopy)) Snackbar.make(binding!!.root, getString(R.string.conversation_action_copied_peer_number_clipboard, toCopy), Snackbar.LENGTH_LONG).show() } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { finishAfterTransition() } return super.onOptionsItemSelected(item) } override fun onDestroy() { adapter.actions.clear() mDisposableBag.dispose() super.onDestroy() colorAction = null binding = null } private fun goToCallActivity(conversation: Conversation, contactUri: Uri, hasVideo: Boolean) { val conf = conversation.currentCall if (conf != null && conf.participants.isNotEmpty() && conf.participants[0].callStatus != Call.CallStatus.INACTIVE && conf.participants[0].callStatus != Call.CallStatus.FAILURE) { startActivity(Intent(Intent.ACTION_VIEW) .setClass(applicationContext, CallActivity::class.java) .putExtra(NotificationService.KEY_CALL_ID, conf.id)) } else { val intent = Intent(Intent.ACTION_CALL) .setClass(applicationContext, CallActivity::class.java) .putExtras(ConversationPath.toBundle(conversation)) .putExtra(Intent.EXTRA_PHONE_NUMBER, contactUri.uri) .putExtra(CallFragment.KEY_HAS_VIDEO, hasVideo) startActivityForResult(intent, HomeActivity.REQUEST_CODE_CALL) } } private fun goToConversationActivity(accountId: String, conversationUri: Uri) { startActivity(Intent(Intent.ACTION_VIEW, ConversationPath.toUri(accountId, conversationUri), applicationContext, ConversationActivity::class.java )) } companion object { private val TAG = ContactDetailsActivity::class.simpleName!! } }
gpl-3.0
51588ee96f1fe4287d309a6903639ebd
42.490431
159
0.640134
5.076515
false
false
false
false
proxer/ProxerLibAndroid
library/src/main/kotlin/me/proxer/library/entity/chat/ChatRoomUser.kt
2
839
package me.proxer.library.entity.chat import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import me.proxer.library.entity.ProxerIdItem import me.proxer.library.entity.ProxerImageItem import me.proxer.library.internal.adapter.NumberBasedBoolean /** * Entity representing a user, active in a [ChatRoom]. * * @property name The name. * @property status The status. * @property isModerator If this user is a moderator. * * @author Ruben Gees */ @JsonClass(generateAdapter = true) data class ChatRoomUser( @Json(name = "uid") override val id: String, @Json(name = "username") val name: String, @Json(name = "avatar") override val image: String, @Json(name = "status") val status: String, @field:NumberBasedBoolean @field:Json(name = "mod") val isModerator: Boolean ) : ProxerIdItem, ProxerImageItem
gpl-3.0
19aac4d32644da5ae4fb7320be59b253
32.56
80
0.741359
3.647826
false
false
false
false
Szewek/Minecraft-Flux
src/main/java/szewek/mcflux/fluxable/WorldChunkEnergy.kt
1
3071
package szewek.mcflux.fluxable import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap import it.unimi.dsi.fastutil.longs.LongArraySet import net.minecraft.nbt.NBTBase import net.minecraft.nbt.NBTTagCompound import net.minecraft.nbt.NBTTagList import net.minecraft.util.EnumFacing import net.minecraftforge.common.capabilities.Capability import net.minecraftforge.common.capabilities.ICapabilityProvider import net.minecraftforge.common.util.Constants.NBT import net.minecraftforge.common.util.INBTSerializable import szewek.fl.energy.Battery import szewek.mcflux.config.MCFluxConfig import szewek.mcflux.fluxable.FluxableCapabilities.CAP_WCE @Suppress("UNCHECKED_CAST") /** * World Chunk Energy implementation. */ class WorldChunkEnergy : ICapabilityProvider, INBTSerializable<NBTBase> { private val eChunks = Long2ObjectOpenHashMap<Battery>() override fun hasCapability(cap: Capability<*>, f: EnumFacing?): Boolean = cap === CAP_WCE override fun <T> getCapability(cap: Capability<T>, f: EnumFacing?) = if (cap === CAP_WCE) this as T else null /** * Gets energy chunk (16x16x16) if available. If not, it creates a new one. * * @param bx Block X position * @param by Block Y position * @param bz Block Z position * @return Chunk battery */ fun getEnergyChunk(bx: Int, by: Int, bz: Int): Battery { val l = packLong(bx / 16, by / 16, bz / 16) if (eChunks.containsKey(l)) { return eChunks.get(l) } val bat = Battery(MCFluxConfig.WORLDCHUNK_CAP.toLong()) eChunks[l] = bat return bat } override fun serializeNBT(): NBTBase { val nbtl = NBTTagList() val poss = LongArraySet() poss.addAll(eChunks.keys) for (l in poss) { val nbt = NBTTagCompound() nbt.setLong("cp", l) val e = eChunks.get(l) if (e != null) nbt.setTag("e", e.serializeNBT()) nbtl.appendTag(nbt) } return nbtl } override fun deserializeNBT(nbtb: NBTBase) { if (nbtb is NBTTagList) { for (i in 0 until nbtb.tagCount()) { val nbt = nbtb.getCompoundTagAt(i) var hasPos = false var l: Long = 0 if (nbt.hasKey("x", NBT.TAG_INT) && nbt.hasKey("y", NBT.TAG_INT) && nbt.hasKey("z", NBT.TAG_INT)) { l = packLong(nbt.getInteger("x"), nbt.getInteger("y"), nbt.getInteger("z")) hasPos = true } else if (nbt.hasKey("cp", NBT.TAG_LONG)) { l = nbt.getLong("cp") hasPos = true } if (hasPos) { if (nbt.hasKey("e")) { val eb = Battery(MCFluxConfig.WORLDCHUNK_CAP.toLong()) eb.deserializeNBT(nbt.getTag("e")) eChunks[l] = eb } } } } } companion object { private const val X_BITS = 22 private const val Z_BITS = 22 private const val Y_BITS = 4 private const val Y_SHIFT = Z_BITS private const val X_SHIFT = Y_SHIFT + Y_BITS private const val X_MASK = (1L shl X_BITS) - 1L private const val Y_MASK = (1L shl Y_BITS) - 1L private const val Z_MASK = (1L shl Z_BITS) - 1L private fun packLong(x: Int, y: Int, z: Int): Long { return x.toLong() and X_MASK shl X_SHIFT or (y.toLong() and Y_MASK shl Y_SHIFT) or (z.toLong() and Z_MASK) } } }
mit
cd0668d5b791b128f076b6c9a1cc7a55
29.71
110
0.685444
3.105157
false
false
false
false
tangying91/profit
src/main/java/org/profit/app/analyse/StockVolumeAnalyzer.kt
1
1480
package org.profit.app.analyse import org.profit.app.StockHall import org.profit.util.StockUtils /** * 【突】周期末,股价成交量大幅拉升 * 周期内成交量是否有异动 */ class StockVolumeAnalyzer(code: String, private val statCount: Int, private val statRate: Double) : StockAnalyzer(code) { /** * 1.周期内平均成交量(去除最低和最高) * 2.最高成交量和平均成交量的关系 * 3.周内成交量上涨天数 */ override fun analyse(results: MutableList<String>) { // 获取数据,后期可以限制天数 val list = readHistories(statCount) // 最近三天成交量出现平均成交量N倍的情况 if (list.size <= 3 || list.size != statCount) { return } val totalDay = list.size val percent = (list[0].close - list[0].open).div(list[0].open) val avgVolume = (list.filter { it != list[0] }.maxBy { it.volume }?.volume ?: 0L) / 10000 val lastVolume = list[0].volume / 10000 val rate = lastVolume.div(avgVolume.toDouble()) if (rate >= statRate && percent >= 0.03) { val content = "$code${StockHall.stockName(code)} 一共$totalDay 天,最近成交量出现异动,最新涨幅${StockUtils.twoDigits(percent * 100)}% ,快速查看: http://stockpage.10jqka.com.cn/$code/" println(content) results.add(code) } } }
apache-2.0
6e7852b607b2e4697234f560ce4f4171
30.736842
174
0.590982
2.992771
false
false
false
false
Tomlezen/FragmentBuilder
compiler/src/main/java/com/tlz/fragmentbuilder/compiler/util/SerializerHolder.kt
1
985
package com.tlz.fragmentbuilder.compiler.util import com.tlz.fragmentbuilder.annotation.Serializer import com.tlz.fragmentbuilder.compiler.asTypeMirror import javax.lang.model.element.VariableElement import javax.lang.model.type.TypeMirror /** * * Created by Tomlezen. * Date: 2017/7/19. * Time: 11:51. */ class SerializerHolder(val to: TypeMirror?, val serializer: TypeMirror?) { fun isEmpty(): Boolean { return to == null || serializer == null } companion object { fun get(param: VariableElement): SerializerHolder { val mirrors = param.annotationMirrors return mirrors?.filter { it.annotationType.toString() == Serializer::class.java.name }?.map { SerializerHolder(it.asTypeMirror("to"), it.asTypeMirror("serializer")) }?.firstOrNull() ?: empty() } fun empty(): SerializerHolder { return SerializerHolder(null, null) } } }
apache-2.0
5b3c46acc1397196448b790b7ce50074
26.388889
86
0.641624
4.358407
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/ItemMetaCommand.kt
1
4276
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.essentials.bukkit.command import com.rpkit.essentials.bukkit.RPKEssentialsBukkit import org.bukkit.ChatColor import org.bukkit.Material import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class ItemMetaCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (!sender.hasPermission("rpkit.essentials.command.itemmeta")) { sender.sendMessage(plugin.messages.noPermissionItemMeta) return true } if (sender !is Player) { sender.sendMessage(plugin.messages.notFromConsole) return true } val itemInMainHand = sender.inventory.itemInMainHand if (itemInMainHand.type == Material.AIR) { sender.sendMessage(plugin.messages.itemMetaInvalidItem) return true } if (args.size < 2) { sender.sendMessage(plugin.messages.itemMetaUsage) return true } val meta = itemInMainHand.itemMeta ?: plugin.server.itemFactory.getItemMeta(itemInMainHand.type) if (meta == null) { sender.sendMessage(plugin.messages.itemMetaFailedToCreate) return true } when (args[0].lowercase()) { "setname" -> { val name = ChatColor.translateAlternateColorCodes('&', args.drop(1).joinToString(" ")) meta.setDisplayName(name) sender.sendMessage(plugin.messages.itemMetaSetNameValid.withParameters( name = name )) } "addlore" -> { val lore = meta.lore ?: mutableListOf<String>() val loreItem = ChatColor.translateAlternateColorCodes('&', args.drop(1).joinToString(" ")) lore.add(loreItem) sender.sendMessage(plugin.messages.itemMetaAddLoreValid.withParameters( lore = loreItem )) meta.lore = lore } "removelore" -> { if (!meta.hasLore()) { sender.sendMessage(plugin.messages.itemMetaRemoveLoreInvalidLore) return true } val lore = meta.lore ?: mutableListOf<String>() val loreItem = ChatColor.translateAlternateColorCodes('&', args.drop(1).joinToString(" ")) if (!lore.contains(loreItem)) { sender.sendMessage(plugin.messages.itemMetaRemoveLoreInvalidLoreItem) return true } lore.remove(loreItem) sender.sendMessage(plugin.messages.itemMetaRemoveLoreValid.withParameters( lore = loreItem )) meta.lore = lore } "custommodeldata" -> { val customModelData = args[1].toIntOrNull() if (customModelData == null) { sender.sendMessage(plugin.messages.itemMetaCustomModelDataInvalidCustomModelData) return true } meta.setCustomModelData(customModelData) sender.sendMessage(plugin.messages.itemMetaCustomModelDataValid.withParameters( customModelData = customModelData )) } else -> { sender.sendMessage(plugin.messages.itemMetaUsage) } } itemInMainHand.itemMeta = meta return true } }
apache-2.0
fe9dc05bd8f3230b36cf669eeb644693
39.72381
114
0.602432
5.139423
false
false
false
false
kishmakov/Kitchen
server/src/io/magnaura/server/Component.kt
1
876
package io.magnaura.server sealed class ComponentStatus { object STARTING : ComponentStatus() object OK : ComponentStatus() class Failed(private val reason: String) : ComponentStatus() { override fun toString() = reason } } abstract class Component { var status: ComponentStatus = ComponentStatus.STARTING abstract val name: String protected var errorMessage: String = "" protected fun updateStatus() { status = if (errorMessage.isEmpty()) ComponentStatus.OK else ComponentStatus.Failed(errorMessage) } protected fun getProperty(propertyName: String): String { return try { System.getProperty(propertyName) } catch (e: Exception) { errorMessage = "Failed to get system property '$propertyName': " + e.message "" } } }
gpl-3.0
d12cd04d6207305af57b21f3159e660a
25.545455
88
0.634703
5.034483
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-auctions-bukkit/src/main/kotlin/com/rpkit/auctions/bukkit/database/table/RPKBidTable.kt
1
7751
/* * 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.auctions.bukkit.database.table import com.rpkit.auctions.bukkit.RPKAuctionsBukkit import com.rpkit.auctions.bukkit.auction.RPKAuction import com.rpkit.auctions.bukkit.auction.RPKAuctionId import com.rpkit.auctions.bukkit.auction.RPKAuctionService import com.rpkit.auctions.bukkit.bid.RPKBid import com.rpkit.auctions.bukkit.bid.RPKBidId import com.rpkit.auctions.bukkit.bid.RPKBidImpl import com.rpkit.auctions.bukkit.database.create import com.rpkit.auctions.bukkit.database.jooq.Tables.RPKIT_AUCTION import com.rpkit.auctions.bukkit.database.jooq.Tables.RPKIT_BID import com.rpkit.characters.bukkit.character.RPKCharacterId import com.rpkit.characters.bukkit.character.RPKCharacterService import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.core.service.Services import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletableFuture.runAsync import java.util.logging.Level /** * Represents the bid table. */ class RPKBidTable( private val database: Database, private val plugin: RPKAuctionsBukkit ) : Table { private val cache = if (plugin.config.getBoolean("caching.rpkit_bid.id.enabled")) { database.cacheManager.createCache( "rpk-auctions-bukkit.rpkit_bid.id", Int::class.javaObjectType, RPKBid::class.java, plugin.config.getLong("caching.rpkit_bid.id.size") ) } else { null } fun insert(entity: RPKBid): CompletableFuture<Void> { val auctionId = entity.auction.id ?: return CompletableFuture.completedFuture(null) val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null) return runAsync { database.create .insertInto( RPKIT_BID, RPKIT_BID.AUCTION_ID, RPKIT_BID.CHARACTER_ID, RPKIT_BID.AMOUNT ) .values( auctionId.value, characterId.value, entity.amount ) .execute() val id = database.create.lastID().toInt() entity.id = RPKBidId(id) cache?.set(id, entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to insert bid", exception) throw exception } } fun update(entity: RPKBid): CompletableFuture<Void> { val id = entity.id ?: return CompletableFuture.completedFuture(null) val auctionId = entity.auction.id ?: return CompletableFuture.completedFuture(null) val characterId = entity.character.id ?: return CompletableFuture.completedFuture(null) return runAsync { database.create .update(RPKIT_BID) .set(RPKIT_BID.AUCTION_ID, auctionId.value) .set(RPKIT_BID.CHARACTER_ID, characterId.value) .set(RPKIT_BID.AMOUNT, entity.amount) .where(RPKIT_BID.ID.eq(id.value)) .execute() cache?.set(id.value, entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to update bid", exception) throw exception } } operator fun get(id: RPKBidId): CompletableFuture<out RPKBid?> { if (cache?.containsKey(id.value) == true) { return CompletableFuture.completedFuture(cache[id.value]) } return CompletableFuture.supplyAsync { val result = database.create .select( RPKIT_BID.AUCTION_ID, RPKIT_BID.CHARACTER_ID, RPKIT_BID.AMOUNT ) .from(RPKIT_BID) .where(RPKIT_BID.ID.eq(id.value)) .fetchOne() ?: return@supplyAsync null val auctionService = Services[RPKAuctionService::class.java] ?: return@supplyAsync null val auctionId = result.get(RPKIT_BID.AUCTION_ID) val auction = auctionService.getAuction(RPKAuctionId(auctionId)).join() val characterService = Services[RPKCharacterService::class.java] ?: return@supplyAsync null val characterId = result.get(RPKIT_BID.CHARACTER_ID) val character = characterService.getCharacter(RPKCharacterId(characterId)).join() if (auction != null && character != null) { val bid = RPKBidImpl( id, auction, character, result.get(RPKIT_BID.AMOUNT) ) cache?.set(id.value, bid) return@supplyAsync bid } else { database.create .deleteFrom(RPKIT_BID) .where(RPKIT_BID.ID.eq(id.value)) .execute() return@supplyAsync null } }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get bid", exception) throw exception } } /** * Gets all bids for a particular auction. * * @return A list of the bids made on the auction */ fun get(auction: RPKAuction): CompletableFuture<List<RPKBid>> { return CompletableFuture.supplyAsync { val results = database.create .select(RPKIT_BID.ID) .from(RPKIT_BID) .where(RPKIT_BID.AUCTION_ID.eq(auction.id?.value)) .fetch() return@supplyAsync results.map { result -> get(RPKBidId(result.get(RPKIT_BID.ID))).join() }.filterNotNull() }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to retrieve bids for auction", exception) throw exception } } fun delete(entity: RPKBid): CompletableFuture<Void> { val id = entity.id ?: return CompletableFuture.completedFuture(null) return runAsync { database.create .deleteFrom(RPKIT_BID) .where(RPKIT_BID.ID.eq(id.value)) .execute() cache?.remove(id.value) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to delete bid", exception) throw exception } } fun delete(characterId: RPKCharacterId): CompletableFuture<Void> = runAsync { database.create .deleteFrom(RPKIT_BID.innerJoin(RPKIT_AUCTION).on(RPKIT_BID.AUCTION_ID.eq(RPKIT_AUCTION.ID))) .where(RPKIT_AUCTION.CHARACTER_ID.eq(characterId.value)) .execute() database.create .deleteFrom(RPKIT_BID) .where(RPKIT_BID.CHARACTER_ID.eq(characterId.value)) .execute() cache?.removeMatching { bid -> bid.character.id?.value == characterId.value || bid.auction.character.id?.value == characterId.value } }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to delete bids for character", exception) throw exception } }
apache-2.0
f7eca28aa54d2c28fccc7c794eadb5a3
39.165803
141
0.610373
4.61369
false
false
false
false
YiiGuxing/TranslationPlugin
src/main/kotlin/cn/yiiguxing/plugin/translate/update/Version.kt
1
5590
@file:Suppress("MemberVisibilityCanBePrivate") package cn.yiiguxing.plugin.translate.update import cn.yiiguxing.plugin.translate.util.Plugin import kotlin.math.min /** * Semantic versioning -> [semver.org](https://semver.org) */ class Version(val version: String = INITIAL_VERSION) : Comparable<Version> { /** The major version number. */ val major: Int /** The minor version number. */ val minor: Int /** The patch version number. */ val patch: Int /** The pre-release version number. */ val prerelease: String? /** The build metadata of this version. */ val buildMetadata: String? init { val matchResult = VERSION_REGEX.matchEntire(version) ?: throw IllegalArgumentException("Invalid version: $version") val matchGroups = matchResult.groups major = matchGroups[MAJOR]!!.value.toInt() minor = matchGroups[MINOR]!!.value.toInt() patch = matchGroups[PATCH]!!.value.toInt() prerelease = matchGroups[PRERELEASE]?.value buildMetadata = matchGroups[BUILD_METADATA]?.value } /** True if the version is a pre-release. */ val isRreRelease: Boolean = prerelease != null private val prereleaseTokens: List<Any> by lazy { prerelease?.split('.') ?.map { if (it[0] !in '0'..'9') it else (it.toIntOrNull() ?: it) } ?: emptyList() } /** Returns the version in "<[major]>.<[minor]>" form. */ fun getFeatureUpdateVersion(): String = "$major.$minor" /** Returns the version in "<[major]>.<[minor]>.<[patch]>" form. */ fun getStableVersion(): String = "$major.$minor.$patch" /** Returns the version in "<[major]>.<[minor]>.<[patch]>[-<[prerelease]>]" form. */ fun getVersionWithoutBuildMetadata(): String = "$major.$minor.$patch${prerelease?.let { "-$it" } ?: ""}" /** * Test if this version has feature updates relative to the [other] version * (Compare only [major] and [minor] versions). */ fun isFeatureUpdateFor(other: Version): Boolean { if (major > other.major) return true if (major == other.major && minor > other.minor) return true return false } /** * Tests whether this version is same as the [other] version * ([Build metadata][buildMetadata] is not compared). */ fun isSameVersion(other: Version): Boolean { if (major != other.major) return false if (minor != other.minor) return false if (patch != other.patch) return false if (prerelease != other.prerelease) return false return true } override fun compareTo(other: Version): Int { var result = major.compareTo(other.major) if (result != 0) return result result = minor.compareTo(other.minor) if (result != 0) return result result = patch.compareTo(other.patch) if (result != 0) return result return when { prerelease == other.prerelease -> 0 prerelease == null -> 1 other.prerelease == null -> -1 else -> comparePrereleaseTokens(other.prereleaseTokens) } } private fun comparePrereleaseTokens(tokens: List<Any>): Int { val myTokens = prereleaseTokens for (i in 0 until min(myTokens.size, tokens.size)) { val result = compare(myTokens[i], tokens[i]) if (result != 0) { return result } } return myTokens.size - tokens.size } private fun compare(l: Any, r: Any): Int = when { l is Int && r is Int -> l.compareTo(r) l is String && r is String -> l.compareTo(r) l is String -> 1 else -> -1 } override fun toString(): String = version override fun hashCode(): Int { var result = version.hashCode() result = 31 * result + major result = 31 * result + minor result = 31 * result + patch result = 31 * result + (prerelease?.hashCode() ?: 0) result = 31 * result + (buildMetadata?.hashCode() ?: 0) return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false return isSameVersion(other as Version) } companion object { /** * The initial version: `0.0.0` */ const val INITIAL_VERSION = "0.0.0" private const val MAJOR = "major" private const val MINOR = "minor" private const val PATCH = "patch" private const val PRERELEASE = "prerelease" private const val BUILD_METADATA = "buildMetadata" private val VERSION_REGEX = """^(?<$MAJOR>0|[1-9]\d*)\.(?<$MINOR>0|[1-9]\d*)\.(?<$PATCH>0|[1-9]\d*)(?:-(?<$PRERELEASE>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+(?<$BUILD_METADATA>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?${'$'}""".toRegex() /** * Returns current version. */ fun current(): Version = Version(Plugin.descriptor.version) /** * Returns the version for the given [version string][version], * or the result of the [defaultValue] function if the given * [version string][version] is an invalid version string. */ inline fun getOrElse(version: String, defaultValue: () -> Version): Version { return try { Version(version) } catch (e: Exception) { defaultValue() } } } }
mit
1e0dd62ae8a4bbc633ca2d6a5525a814
31.888235
271
0.574597
4.004298
false
false
false
false
Anizoptera/Aza-Kotlin-CSS
main/azagroup/kotlin/css/dimens/BoxDimensions.kt
1
904
package azagroup.kotlin.css.dimens import azagroup.kotlin.css.dimens.LinearDimension.Companion.from as dimen class BoxDimensions( var top: LinearDimension = 0.px, var right: LinearDimension = top, var bottom: LinearDimension = top, var left: LinearDimension = right ) { override fun toString(): String { return when { top == right && top == bottom && top == left -> top.toString() top == bottom && left == right -> "$top $right" left == right -> "$top $right $bottom" else -> "$top $right $bottom $left" } } companion object { fun from(vararg args: Any): BoxDimensions { return when (args.size) { 1 -> BoxDimensions(dimen(args[0])) 2 -> BoxDimensions(dimen(args[0]), dimen(args[1])) 3 -> BoxDimensions(dimen(args[0]), dimen(args[1]), dimen(args[2])) else -> BoxDimensions(dimen(args[0]), dimen(args[1]), dimen(args[2]), dimen(args[3])) } } } }
mit
f864a14369317a1861ed58886d0c074c
26.393939
89
0.643805
3.17193
false
false
false
false
android/user-interface-samples
CanonicalLayouts/feed-view/app/src/main/java/com/example/viewbasedfeedlayoutsample/ui/SweetsFeedItemDecorationInGrid.kt
1
1642
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.viewbasedfeedlayoutsample.ui import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView class SweetsFeedItemDecorationInGrid( private val horizontalSep: Int, private val verticalSep: Int, private val columnCount: Int ) : RecyclerView.ItemDecoration() { override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { val position = parent.getChildAdapterPosition(view) with(outRect) { top = if (position == 0) { 0 } else { verticalSep } left = if (position % columnCount == 0) { 0 } else { horizontalSep } right = if (position % columnCount == columnCount - 1) { 0 } else { horizontalSep } bottom = verticalSep } } }
apache-2.0
651ca3f2bf7a58968af6f3e552d6c864
28.854545
75
0.616322
4.787172
false
false
false
false
MHP-A-Porsche-Company/CDUI-Showcase-Android
app/src/main/kotlin/com/mhp/showcase/block/articlestream/ArticleStreamBlockView.kt
1
2331
package com.mhp.showcase.block.articlestream import android.annotation.SuppressLint import android.content.Context import android.widget.RelativeLayout import android.widget.TextView import com.mhp.showcase.R import com.mhp.showcase.ShowcaseApplication import com.mhp.showcase.block.BaseBlockView import com.mhp.showcase.navigation.Router import com.mhp.showcase.view.BackendImageView import com.mhp.showcase.view.UserView import org.androidannotations.annotations.AfterViews import org.androidannotations.annotations.Click import org.androidannotations.annotations.EViewGroup import org.androidannotations.annotations.ViewById import javax.inject.Inject @SuppressLint("ViewConstructor") @EViewGroup(R.layout.view_block_article_stream) open class ArticleStreamBlockView(context: Context) : RelativeLayout(context), BaseBlockView<ArticleStreamBlock> { override var block: ArticleStreamBlock? = null set(value) { field = value afterViews() } @ViewById(R.id.user) protected lateinit var userView: UserView @ViewById(R.id.article_image) protected lateinit var articleImageView: BackendImageView @ViewById(R.id.headline) protected lateinit var headline: TextView @ViewById(R.id.subheadline) protected lateinit var subHeadline: TextView @ViewById(R.id.time) protected lateinit var timeView: TextView @Inject protected lateinit var router: Router @AfterViews override fun afterViews() { ShowcaseApplication.graph.inject(this) userView.user = block?.user if (block == null) { return } articleImageView.url = block?.imageUrl headline.text = block?.title headline.text = block?.title subHeadline.text = block?.subtitle timeView.text = convertTimeToText(block?.created, context) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ArticleStreamBlockView if (block != other.block) return false return true } override fun hashCode(): Int { return block?.hashCode() ?: 0 } @Click(R.id.wrapper) protected fun containerClicked() { block?.target?.let { router.navigate(it) } } }
mit
977c5019168830540772698acb8fdf0d
28.518987
114
0.71257
4.332714
false
false
false
false
cketti/okhttp
okhttp-sse/src/main/kotlin/okhttp3/internal/sse/RealEventSource.kt
1
3051
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.sse import java.io.IOException import okhttp3.Call import okhttp3.Callback import okhttp3.EventListener import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody import okhttp3.internal.EMPTY_RESPONSE import okhttp3.internal.connection.RealCall import okhttp3.sse.EventSource import okhttp3.sse.EventSourceListener class RealEventSource( private val request: Request, private val listener: EventSourceListener ) : EventSource, ServerSentEventReader.Callback, Callback { private lateinit var call: RealCall fun connect(client: OkHttpClient) { val client = client.newBuilder() .eventListener(EventListener.NONE) .build() call = client.newCall(request) as RealCall call.enqueue(this) } override fun onResponse(call: Call, response: Response) { processResponse(response) } fun processResponse(response: Response) { response.use { if (!response.isSuccessful) { listener.onFailure(this, null, response) return } val body = response.body!! if (!body.isEventStream()) { listener.onFailure(this, IllegalStateException("Invalid content-type: ${body.contentType()}"), response) return } // This is a long-lived response. Cancel full-call timeouts. call.timeoutEarlyExit() // Replace the body with an empty one so the callbacks can't see real data. val response = response.newBuilder() .body(EMPTY_RESPONSE) .build() val reader = ServerSentEventReader(body.source(), this) try { listener.onOpen(this, response) while (reader.processNextEvent()) { } } catch (e: Exception) { listener.onFailure(this, e, response) return } listener.onClosed(this) } } private fun ResponseBody.isEventStream(): Boolean { val contentType = contentType() ?: return false return contentType.type == "text" && contentType.subtype == "event-stream" } override fun onFailure(call: Call, e: IOException) { listener.onFailure(this, e, null) } override fun request(): Request = request override fun cancel() { call.cancel() } override fun onEvent(id: String?, type: String?, data: String) { listener.onEvent(this, id, type, data) } override fun onRetryChange(timeMs: Long) { // Ignored. We do not auto-retry. } }
apache-2.0
2d8568cbe720de5a42570dc2eb4c7c50
27.514019
91
0.690921
4.249304
false
false
false
false
DevCharly/kotlin-ant-dsl
src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/move.kt
1
3009
/* * Copyright 2016 Karl Tauber * * 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.devcharly.kotlin.ant import org.apache.tools.ant.taskdefs.Move import org.apache.tools.ant.types.ResourceCollection import org.apache.tools.ant.util.FileNameMapper /****************************************************************************** DO NOT EDIT - this file was generated ******************************************************************************/ fun Ant.move( file: String? = null, tofile: String? = null, todir: String? = null, preservelastmodified: Boolean? = null, filtering: Boolean? = null, overwrite: Boolean? = null, force: Boolean? = null, flatten: Boolean? = null, verbose: Boolean? = null, includeemptydirs: Boolean? = null, quiet: Boolean? = null, enablemultiplemappings: Boolean? = null, failonerror: Boolean? = null, encoding: String? = null, outputencoding: String? = null, granularity: Long? = null, performgconfaileddelete: Boolean? = null, nested: (KMove.() -> Unit)? = null) { Move().execute("move") { task -> if (file != null) task.setFile(project.resolveFile(file)) if (tofile != null) task.setTofile(project.resolveFile(tofile)) if (todir != null) task.setTodir(project.resolveFile(todir)) if (preservelastmodified != null) task.setPreserveLastModified(preservelastmodified) if (filtering != null) task.setFiltering(filtering) if (overwrite != null) task.setOverwrite(overwrite) if (force != null) task.setForce(force) if (flatten != null) task.setFlatten(flatten) if (verbose != null) task.setVerbose(verbose) if (includeemptydirs != null) task.setIncludeEmptyDirs(includeemptydirs) if (quiet != null) task.setQuiet(quiet) if (enablemultiplemappings != null) task.setEnableMultipleMappings(enablemultiplemappings) if (failonerror != null) task.setFailOnError(failonerror) if (encoding != null) task.setEncoding(encoding) if (outputencoding != null) task.setOutputEncoding(outputencoding) if (granularity != null) task.setGranularity(granularity) if (performgconfaileddelete != null) task.setPerformGcOnFailedDelete(performgconfaileddelete) if (nested != null) nested(KMove(task)) } } class KMove(override val component: Move) : IFileNameMapperNested, IResourceCollectionNested { override fun _addFileNameMapper(value: FileNameMapper) = component.add(value) override fun _addResourceCollection(value: ResourceCollection) = component.add(value) }
apache-2.0
9b92138fc2e703d84bfc1e2ff8a02689
31.354839
86
0.694915
3.560947
false
false
false
false
ruuvi/Android_RuuvitagScanner
app/src/main/java/com/ruuvi/station/network/ui/EmailEnterFragment.kt
1
1699
package com.ruuvi.station.network.ui import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import com.ruuvi.station.util.extensions.viewModel import com.ruuvi.station.R import kotlinx.android.synthetic.main.fragment_email_enter.* import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.android.support.closestKodein class EmailEnterFragment() : Fragment(R.layout.fragment_email_enter), KodeinAware { override val kodein: Kodein by closestKodein() private val viewModel: EmailEnterViewModel by viewModel() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViewModel() setupUI() } private fun setupUI() { submitButton.setOnClickListener { viewModel.submitEmail(emailEditText.text.toString()) } skipTextView.setOnClickListener { requireActivity().finish() } } private fun setupViewModel() { viewModel.errorTextObserve.observe(viewLifecycleOwner, Observer { errorTextView.text = it }) viewModel.successfullyRegisteredObserve.observe(viewLifecycleOwner, Observer { if (it == true) { viewModel.successfullyRegisteredFinished() val action = EmailEnterFragmentDirections.actionEmailEnterFragmentToEnterCodeFragment(null) this.findNavController().navigate(action) } }) } companion object { fun newInstance() = EmailEnterFragment() } }
mit
b813793b5ed9e4c30950be94f6345740
30.481481
107
0.704532
4.982405
false
false
false
false
DadosAbertosBrasil/android-radar-politico
app/src/main/kotlin/br/edu/ifce/engcomp/francis/radarpolitico/controllers/ProposicaoVotadaActivity.kt
1
2478
package br.edu.ifce.engcomp.francis.radarpolitico.controllers import android.content.res.ColorStateList import android.os.Bundle import android.support.v4.app.FragmentTabHost import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.TabWidget import android.widget.TextView import br.edu.ifce.engcomp.francis.radarpolitico.R import br.edu.ifce.engcomp.francis.radarpolitico.models.Proposicao import kotlinx.android.synthetic.main.activity_add_politicians.* class ProposicaoVotadaActivity : AppCompatActivity() { lateinit var proposicao: Proposicao override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_proposicao_votada) proposicao = intent.getParcelableExtra<Proposicao>("PROPOSICAO_EXTRA") initToolbar(); initTabHost(); } override fun onBackPressed() { super.onBackPressed() } fun initToolbar() { if(toolbar != null) { setSupportActionBar(toolbar) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) } } private fun initTabHost() { val mainTabHost = findViewById(R.id.votacoes_tabHost) as FragmentTabHost mainTabHost.setup(this, supportFragmentManager, android.R.id.tabcontent) val detalhesTab = mainTabHost.newTabSpec("votacoes") val votosTab = mainTabHost.newTabSpec("politicos") detalhesTab.setIndicator("DETALHES") votosTab.setIndicator("LISTA DE VOTOS") mainTabHost.addTab(detalhesTab, DetalheProposicaoTabFragment::class.java, null) mainTabHost.addTab(votosTab, VotosDeputadosTabFragment::class.java, null) mainTabHost.currentTab = 0 stylizeTabs(mainTabHost) } private fun stylizeTabs(tabHost: FragmentTabHost) { val tabTextColors: ColorStateList val tabWidget: TabWidget var tabTextView: TextView var tabView: View val tabAmount: Int tabWidget = tabHost.tabWidget tabTextColors = this.resources.getColorStateList(R.color.tab_text_selector) tabAmount = tabWidget.tabCount for (i in 0..tabAmount - 1) { tabView = tabWidget.getChildTabViewAt(i) tabTextView = tabView.findViewById(android.R.id.title) as TextView tabTextView.setTextColor(tabTextColors) } } }
gpl-2.0
2b9ef30884ddd57a6a65c8900d2854fc
31.181818
87
0.70904
4.279793
false
false
false
false
diyaakanakry/Diyaa
MakeingDesssionExperission.kt
1
257
fun main(args:Array<String>){ var n1=10 var n2=20 var max= if(n1>n2) n1 else n2 println("max:$max") //When var age=30 var isYoung= when(age){ 30-> true else->false } println("isYoung:$isYoung") }
unlicense
0fabbfa84346a842cd8e911dbec37b99
10.217391
33
0.521401
3.023529
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UITableView_RowProcesser.kt
1
4055
package com.yy.codex.uikit /** * Created by cuiminghui on 2017/2/27. */ internal fun UITableView._reloadCellCaches() { _reloadCellPositionCaches() } internal fun UITableView._reloadContentSize() { if (_cellPositions.size > 0) { var maxY = _cellPositions.last().value + _cellPositions.last().height + (tableFooterView?.frame?.height ?: 0.0) if (_sectionsFooterView.size > 0) { maxY += _sectionsFooterView.last()?.viewHeight ?: 0.0 } contentSize = CGSize(0.0, maxY) } } internal fun UITableView._requestPositionWithIndexPath(indexPath: NSIndexPath): UITableViewCellPosition? { return _cellPositions.firstOrNull { it.indexPath == indexPath } } internal fun UITableView._requestVisiblePositions(): List<UITableViewCellPosition> { return _requestVisiblePositionsWithValues(contentOffset.y, contentOffset.y + frame.height) } internal fun UITableView._requestVisiblePositionsWithValues(startValue: Double, endValue: Double): List<UITableViewCellPosition> { val results: MutableList<UITableViewCellPosition> = mutableListOf() val startPosition = _requestCellPositionWithPoint(startValue) val endPosition = _requestCellPositionWithPoint(endValue) results.add(startPosition) if (endPosition !== startPosition) { _cellPositions.indexOf(startPosition)?.let { val startIndex= it _cellPositions.indexOf(endPosition)?.let { val endIndex = it (startIndex + 1 until endIndex).forEach { results.add(_cellPositions[it]) } } } results.add(endPosition) } return results } internal fun UITableView._computeVisibleHash(visiblePositions: List<UITableViewCellPosition>): String { var hash = "" visiblePositions.forEach { hash += it.indexPath.section.toString() + "_" + it.indexPath.row.toString() + "," } return hash } internal fun UITableView._requestCellPositionWithPoint(atPoint: Double): UITableViewCellPosition { var left = 0 var right = _cellPositions.size - 1 if (atPoint <= _cellPositions[left].value) { return _cellPositions[left] } else if (atPoint >= _cellPositions[right].value) { return _cellPositions[right] } while (true) { if (right - left < 2) { return _cellPositions[left] } val mid = Math.ceil((left + right) / 2.0).toInt() if (atPoint < _cellPositions[mid].value) { right = mid } else if (atPoint > _cellPositions[mid].value) { left = mid } else { return _cellPositions[mid] } } } private fun UITableView._reloadCellPositionCaches() { dataSource?.let { val cellPositions: MutableList<UITableViewCellPosition> = mutableListOf() val dataSource = it val sectionCount = dataSource.numberOfSections(this) var currentY = 0.0 currentY += tableHeaderView?.frame?.height ?: 0.0 (0 until sectionCount).forEach { val section = it val sectionHeader = _sectionsHeaderView[section] val sectionFooter = _sectionsFooterView[section] sectionHeader?.startY = currentY currentY += sectionHeader?.viewHeight ?: 0.0 sectionFooter?.startY = currentY val rowCount = dataSource.numberOfRowsInSection(this, it) (0 until rowCount).forEach { val row = it val rowHeight = delegate()?.heightForRowAtIndexPath(this, NSIndexPath(section, row)) ?: rowHeight cellPositions.add(UITableViewCellPosition(currentY, rowHeight, NSIndexPath(section, row))) currentY += rowHeight } sectionHeader?.endY = currentY currentY += sectionFooter?.viewHeight ?: 0.0 sectionFooter?.endY = currentY } this._cellPositions = cellPositions.toList() } } internal class UITableViewCellPosition(val value: Double, val height: Double, val indexPath: NSIndexPath)
gpl-3.0
3923ea356e1a7eeed24c7c2ca37a1670
36.555556
130
0.647349
4.592299
false
false
false
false
toastkidjp/Yobidashi_kt
app/src/main/java/jp/toastkid/yobidashi/browser/webview/usecase/SelectedTextUseCase.kt
1
2899
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.browser.webview.usecase import android.content.Context import android.net.Uri import androidx.core.net.toUri import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStoreOwner import jp.toastkid.lib.BrowserViewModel import jp.toastkid.lib.ContentViewModel import jp.toastkid.lib.Urls import jp.toastkid.search.SearchCategory import jp.toastkid.search.UrlFactory import jp.toastkid.yobidashi.R class SelectedTextUseCase( private val urlFactory: UrlFactory = UrlFactory(), private val stringResolver: (Int, Any) -> String, private val contentViewModel: ContentViewModel, private val browserViewModel: BrowserViewModel ) { fun countCharacters(word: String) { val codePointCount = word.codePointCount(1, word.length - 1) val message = stringResolver(R.string.message_character_count, codePointCount) contentViewModel.snackShort(message) } fun search(word: String, searchEngine: String?) { val url = calculateToUri(word, searchEngine) ?: return browserViewModel.open(url) } fun searchWithPreview(word: String, searchEngine: String?) { val url = calculateToUri(word, searchEngine) ?: return browserViewModel.preview(url) } private fun calculateToUri(word: String, searchEngine: String?): Uri? { val cleaned = if (word.startsWith("\"") && word.length > 10) word.substring(1, word.length - 2) else word return if (Urls.isValidUrl(cleaned)) cleaned.toUri() else makeUrl(word, searchEngine) } private fun makeUrl(word: String, searchEngine: String?): Uri? { if (word.isEmpty() || word == "\"\"") { contentViewModel.snackShort(R.string.message_failed_query_extraction_from_web_view) return null } return urlFactory( searchEngine ?: SearchCategory.getDefaultCategoryName(), word ) } companion object { fun make(context: Context?): SelectedTextUseCase? = (context as? ViewModelStoreOwner)?.let { activity -> val viewModelProvider = ViewModelProvider(activity) return SelectedTextUseCase( stringResolver = { resource, additional -> context.getString(resource, additional) }, contentViewModel = viewModelProvider.get(ContentViewModel::class.java), browserViewModel = viewModelProvider.get(BrowserViewModel::class.java) ) } } }
epl-1.0
2cea9590aea621eba6fe724fa0f5df3a
34.802469
105
0.67575
4.807629
false
false
false
false
SoulBeaver/kindinium
src/main/kotlin/com/sbg/vindinium/kindinium/model/Hero.kt
1
1663
/* Copyright 2014 Christian Broomfield 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.sbg.vindinium.kindinium.model import com.sbg.vindinium.kindinium data class Hero { /** * The hero's id for the current game. */ val id = 1 /** * The hero's name. */ val name = "" /** * The player's generated id. */ val userId = "" /** * The player's rating. Starts at 1200 */ val elo = 1200 /** * The hero's current position */ val pos = Position(2, 4) get() = Position($pos.y, $pos.x) /** * The hero's current life pool. 0 is a dead hero, but life cannot exceed 100. */ val life = 100 /** * The hero's current gold pool. */ val gold = 0 /** * The number of mines under the hero's control. */ val mineCount = 0 /** * Where the player spawns on death. On initialization, is the same as the position. */ val spawnPos = Position(2, 4) get() = Position($spawnPos.y, $spawnPos.x) /** * Whether or not the hero took more than the one second time to process. */ val crashed = false }
apache-2.0
333541e69bc15912aa86e15e622f79f0
22.111111
88
0.624173
4.026634
false
false
false
false
backpaper0/syobotsum
core/src/syobotsum/Syobotsum.kt
1
9724
package syobotsum import syobotsum.screen.LoadingScreen import com.badlogic.gdx.Game import com.badlogic.gdx.assets.AssetDescriptor import com.badlogic.gdx.assets.AssetManager import com.badlogic.gdx.assets.loaders.BitmapFontLoader.BitmapFontParameter import com.badlogic.gdx.assets.loaders.TextureLoader.TextureParameter import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.Texture.TextureFilter import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle import com.badlogic.gdx.scenes.scene2d.ui.Skin import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle class Syobotsum : Game() { lateinit var fontAsset: AssetDescriptor<BitmapFont> lateinit var nowloadingAsset: AssetDescriptor<Texture> lateinit var gameBackgroundAsset: AssetDescriptor<Texture> lateinit var gameHeartAsset: AssetDescriptor<Texture> lateinit var gameRedkingAsset: AssetDescriptor<Texture> lateinit var gameOtherAsset: AssetDescriptor<Texture> lateinit var gameReadyAsset: AssetDescriptor<Texture> lateinit var gameGoAsset: AssetDescriptor<Texture> lateinit var gameFinishedAsset: AssetDescriptor<Texture> lateinit var gameSnowAsset: AssetDescriptor<Texture> lateinit var resultBackgroundAsset: AssetDescriptor<Texture> lateinit var resultTitleAsset: AssetDescriptor<Texture> lateinit var resultRestartUpAsset: AssetDescriptor<Texture> lateinit var resultRestartDownAsset: AssetDescriptor<Texture> lateinit var resultExitUpAsset: AssetDescriptor<Texture> lateinit var resultExitDownAsset: AssetDescriptor<Texture> lateinit var resultHeartAsset: AssetDescriptor<Texture> lateinit var resultRedkingAsset: AssetDescriptor<Texture> lateinit var resultOtherAsset: AssetDescriptor<Texture> lateinit var resultJoshiryokuAsset: AssetDescriptor<Texture> lateinit var titleBackgroundAsset: AssetDescriptor<Texture> lateinit var titleStartUpAsset: AssetDescriptor<Texture> lateinit var titleStartDownAsset: AssetDescriptor<Texture> lateinit var titleExitUpAsset: AssetDescriptor<Texture> lateinit var titleExitDownAsset: AssetDescriptor<Texture> lateinit var exitBackgroundAsset: AssetDescriptor<Texture> lateinit var exitMessageAsset: AssetDescriptor<Texture> lateinit var exitYesUpAsset: AssetDescriptor<Texture> lateinit var exitYesDownAsset: AssetDescriptor<Texture> lateinit var exitNoUpAsset: AssetDescriptor<Texture> lateinit var exitNoDownAsset: AssetDescriptor<Texture> lateinit var exitBackground2Asset: AssetDescriptor<Texture> lateinit var exitYesUp2Asset: AssetDescriptor<Texture> lateinit var exitNoUp2Asset: AssetDescriptor<Texture> lateinit var am: AssetManager lateinit var skin: Skin override fun create() { skin = Skin() am = AssetManager() val fontParams = BitmapFontParameter().let { it.minFilter = TextureFilter.Linear it.magFilter = TextureFilter.Linear it } val params = TextureParameter().let { it.minFilter = TextureFilter.Linear it.magFilter = TextureFilter.Linear it } nowloadingAsset = AssetDescriptor<Texture>("nowloading.png", Texture::class.java, params) am.load(nowloadingAsset) am.finishLoading() skin.add("nowloading", am.get(nowloadingAsset), Texture::class.java) fontAsset = AssetDescriptor<BitmapFont>("mplus1m.fnt", BitmapFont::class.java, fontParams) fun textureDesc(s: String) = AssetDescriptor(s, Texture::class.java, params) titleBackgroundAsset = textureDesc("title/background.png") titleStartUpAsset = textureDesc("title/startUp.png") titleStartDownAsset = textureDesc("title/startDown.png") titleExitUpAsset = textureDesc("title/exitUp.png") titleExitDownAsset = textureDesc("title/exitDown.png") gameBackgroundAsset = textureDesc("game/background.png") gameHeartAsset = textureDesc("game/heart.png") gameRedkingAsset = textureDesc("game/redking.png") gameOtherAsset = textureDesc("game/other.png") gameReadyAsset = textureDesc("game/ready.png") gameGoAsset = textureDesc("game/go.png") gameFinishedAsset = textureDesc("game/finished.png") gameSnowAsset = textureDesc("game/snow.png") resultBackgroundAsset = textureDesc("result/background.png") resultTitleAsset = textureDesc("result/title.png") resultRestartUpAsset = textureDesc("result/restartUp.png") resultRestartDownAsset = textureDesc("result/restartDown.png") resultExitUpAsset = textureDesc("result/exitUp.png") resultExitDownAsset = textureDesc("result/exitDown.png") resultHeartAsset = textureDesc("game/heart.png") resultRedkingAsset = textureDesc("game/redking.png") resultOtherAsset = textureDesc("game/other.png") resultJoshiryokuAsset = textureDesc("result/joshiryoku.png") exitBackgroundAsset = textureDesc("exit/background.png") exitMessageAsset = textureDesc("exit/message.png") exitYesUpAsset = textureDesc("exit/yesUp.png") exitYesDownAsset = textureDesc("exit/yesDown.png") exitNoUpAsset = textureDesc("exit/noUp.png") exitNoDownAsset = textureDesc("exit/noDown.png") exitBackground2Asset = textureDesc("exit/background2.png") exitYesUp2Asset = textureDesc("exit/yesUp2.png") exitNoUp2Asset = textureDesc("exit/noUp2.png") listOf( fontAsset, gameBackgroundAsset, gameHeartAsset, gameRedkingAsset, gameOtherAsset, gameReadyAsset, gameGoAsset, gameFinishedAsset, gameSnowAsset, resultBackgroundAsset, resultTitleAsset, resultRestartUpAsset, resultRestartDownAsset, resultExitUpAsset, resultExitDownAsset, resultHeartAsset, resultRedkingAsset, resultOtherAsset, resultJoshiryokuAsset, titleBackgroundAsset, titleStartUpAsset, titleStartDownAsset, titleExitUpAsset, titleExitDownAsset, exitBackgroundAsset, exitMessageAsset, exitYesUpAsset, exitYesDownAsset, exitNoUpAsset, exitNoDownAsset, exitBackground2Asset, exitYesUp2Asset, exitNoUp2Asset ).forEach { am.load(it) } setScreen(LoadingScreen(this, am)) } fun createSkin() { skin.add("default", am.get(fontAsset), BitmapFont::class.java) val names = listOf( "titleBackground", "titleStartUp", "titleStartDown", "titleExitUp", "titleExitDown", "gameBackground", "gameHeart", "gameRedking", "gameOther", "gameReady", "gameGo", "gameFinished", "gameSnow", "resultBackground", "resultTitle", "resultRestartUp", "resultRestartDown", "resultExitUp", "resultExitDown", "resultHeart", "resultRedking", "resultOther", "resultJoshiryoku", "exitBackground", "exitMessage", "exitYesUp", "exitYesDown", "exitNoUp", "exitNoDown", "exitBackground2", "exitYesUp2", "exitNoUp2" ) val assets = listOf( titleBackgroundAsset, titleStartUpAsset, titleStartDownAsset, titleExitUpAsset, titleExitDownAsset, gameBackgroundAsset, gameHeartAsset, gameRedkingAsset, gameOtherAsset, gameReadyAsset, gameGoAsset, gameFinishedAsset, gameSnowAsset, resultBackgroundAsset, resultTitleAsset, resultRestartUpAsset, resultRestartDownAsset, resultExitUpAsset, resultExitDownAsset, resultHeartAsset, resultRedkingAsset, resultOtherAsset, resultJoshiryokuAsset, exitBackgroundAsset, exitMessageAsset, exitYesUpAsset, exitYesDownAsset, exitNoUpAsset, exitNoDownAsset, exitBackground2Asset, exitYesUp2Asset, exitNoUp2Asset ) names.zip(assets).forEach { val (name, asset) = it skin.add(name, am.get(asset), Texture::class.java) } val font = skin.getFont("default") LabelStyle(font, Color.WHITE).let { skin.add("counter", it, LabelStyle::class.java) } LabelStyle(font, Color.PURPLE).let { skin.add("score", it, LabelStyle::class.java) } ButtonStyle(skin.getDrawable("titleStartUp"), skin.getDrawable("titleStartDown"), null).let { skin.add("titleStart", it, ButtonStyle::class.java) } ButtonStyle(skin.getDrawable("titleExitUp"), skin.getDrawable("titleExitDown"), null).let { skin.add("titleExit", it, ButtonStyle::class.java) } ButtonStyle(skin.getDrawable("resultRestartUp"), skin.getDrawable("resultRestartDown"), null).let { skin.add("resultRestart", it, ButtonStyle::class.java) } ButtonStyle(skin.getDrawable("resultExitUp"), skin.getDrawable("resultExitDown"), null).let { skin.add("resultExit", it, ButtonStyle::class.java) } WindowStyle(font, Color.WHITE, skin.getDrawable("exitBackground")).let { skin.add("exit", it, WindowStyle::class.java) } ButtonStyle(skin.getDrawable("exitYesUp"), skin.getDrawable("exitYesDown"), null).let { skin.add("exitYes", it, ButtonStyle::class.java) } ButtonStyle(skin.getDrawable("exitNoUp"), skin.getDrawable("exitNoDown"), null).let { skin.add("exitNo", it, ButtonStyle::class.java) } WindowStyle(font, Color.WHITE, skin.getDrawable("exitBackground2")).let { skin.add("exit2", it, WindowStyle::class.java) } ButtonStyle(skin.getDrawable("exitYesUp2"), skin.getDrawable("exitYesDown"), null).let { skin.add("exit2Yes", it, ButtonStyle::class.java) } ButtonStyle(skin.getDrawable("exitNoUp2"), skin.getDrawable("exitNoDown"), null).let { skin.add("exit2No", it, ButtonStyle::class.java) } } override fun dispose() { am.dispose() } }
apache-2.0
3bad234e16686d359c1d7e0dbd79ee86
55.865497
217
0.735191
4.129087
false
false
false
false
http4k/http4k
src/docs/guide/howto/configure_an_oauth_server/example.kt
1
6294
import dev.forkhandles.result4k.Failure import dev.forkhandles.result4k.Success import org.http4k.client.OkHttp import org.http4k.core.Credentials import org.http4k.core.HttpHandler import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.OK import org.http4k.core.Uri import org.http4k.core.then import org.http4k.format.Jackson import org.http4k.routing.RoutingHttpHandler import org.http4k.routing.bind import org.http4k.routing.routes import org.http4k.security.AccessToken import org.http4k.security.InsecureCookieBasedOAuthPersistence import org.http4k.security.OAuthProvider import org.http4k.security.OAuthProviderConfig import org.http4k.security.oauth.server.AccessTokens import org.http4k.security.oauth.server.AuthRequest import org.http4k.security.oauth.server.AuthorizationCode import org.http4k.security.oauth.server.AuthorizationCodeDetails import org.http4k.security.oauth.server.AuthorizationCodes import org.http4k.security.oauth.server.ClientId import org.http4k.security.oauth.server.ClientValidator import org.http4k.security.oauth.server.InsecureCookieBasedAuthRequestTracking import org.http4k.security.oauth.server.OAuthServer import org.http4k.security.oauth.server.TokenRequest import org.http4k.security.oauth.server.UnsupportedGrantType import org.http4k.security.oauth.server.accesstoken.AuthorizationCodeAccessTokenRequest import org.http4k.server.Jetty import org.http4k.server.asServer import java.time.Clock import java.time.temporal.ChronoUnit.DAYS import java.util.UUID fun main() { fun authorizationServer(): RoutingHttpHandler { val server = OAuthServer( tokenPath = "/oauth2/token", authRequestTracking = InsecureCookieBasedAuthRequestTracking(), clientValidator = InsecureClientValidator(), authorizationCodes = InsecureAuthorizationCodes(), accessTokens = InsecureAccessTokens(), json = Jackson, clock = Clock.systemUTC(), documentationUri = "See the full API docs at https://example.com/docs/access_token" ) return routes( server.tokenRoute, "/my-login-page" bind GET to server.authenticationStart.then { Response(OK).body( """ <html> <form method="POST"> <button type="submit">Please authenticate</button> </form> </html> """.trimIndent() ) }, "/my-login-page" bind POST to server.authenticationComplete ) } fun oAuthClientApp(tokenClient: HttpHandler): RoutingHttpHandler { val persistence = InsecureCookieBasedOAuthPersistence("oauthTest") val authorizationServer = Uri.of("http://localhost:9000") val oauthProvider = OAuthProvider( OAuthProviderConfig( authorizationServer, "/my-login-page", "/oauth2/token", Credentials("my-app", "somepassword") ), tokenClient, Uri.of("http://localhost:8000/my-callback"), listOf("name", "age"), persistence ) return routes( "/my-callback" bind GET to oauthProvider.callback, "/a-protected-resource" bind GET to oauthProvider.authFilter.then { Response(OK).body( "user's protected resource" ) } ) } oAuthClientApp(OkHttp()).asServer(Jetty(8000)).start() authorizationServer().asServer(Jetty(9000)).start().block() // Go to http://localhost:8000/a-protected-resource to start the authorization flow } // This class allow you to make extra checks about the oauth client during the flow class InsecureClientValidator : ClientValidator { // the client id should be a registered one override fun validateClientId(request: Request, clientId: ClientId): Boolean = true // one should only redirect to URLs registered against a particular client override fun validateRedirection( request: Request, clientId: ClientId, redirectionUri: Uri ): Boolean = true // one should validate the scopes are correct for that client override fun validateScopes( request: Request, clientId: ClientId, scopes: List<String> ): Boolean = true // certain operations can only be performed by fully authenticated clients // e.g. generate access tokens override fun validateCredentials( request: Request, clientId: ClientId, clientSecret: String ): Boolean = true } class InsecureAuthorizationCodes : AuthorizationCodes { private val clock = Clock.systemUTC() private val codes = mutableMapOf<AuthorizationCode, AuthorizationCodeDetails>() override fun detailsFor(code: AuthorizationCode) = codes[code] ?: error("code not stored") // Authorization codes should be associated // to a particular user (who can be identified in the Response) // so they can be checked in various stages of the authorization flow override fun create(request: Request, authRequest: AuthRequest, response: Response) = Success(AuthorizationCode(UUID.randomUUID().toString()).also { codes[it] = AuthorizationCodeDetails( authRequest.client, authRequest.redirectUri!!, clock.instant().plus(1, DAYS), authRequest.state, authRequest.isOIDC() ) }) } class InsecureAccessTokens : AccessTokens { override fun create( clientId: ClientId, tokenRequest: TokenRequest ) = Failure(UnsupportedGrantType("client_credentials")) // an access token should be associated with a particular authorization flow // (i.e. limited to the requested scopes), and contain an expiration date override fun create( clientId: ClientId, tokenRequest: AuthorizationCodeAccessTokenRequest, authorizationCode: AuthorizationCode ) = Success(AccessToken(UUID.randomUUID().toString())) }
apache-2.0
bc83d788c382fe1bc0277a2835b24085
37.378049
95
0.680966
4.597516
false
false
false
false
pnemonic78/RemoveDuplicates
duplicates-android/app/src/main/java/com/github/duplicates/message/MessageComparator.kt
1
4817
/* * Copyright 2016, Moshe Waisberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.duplicates.message import android.text.format.DateUtils.SECOND_IN_MILLIS import com.github.duplicates.DuplicateComparator /** * Compare duplicate messages. * * @author moshe.w */ class MessageComparator : DuplicateComparator<MessageItem>() { override fun compare(lhs: MessageItem, rhs: MessageItem): Int { var c: Int c = compare(lhs.type, rhs.type) if (c != SAME) return c c = compare(lhs.dateReceived, rhs.dateReceived) if (c != SAME) return c c = compare(lhs.dateSent, rhs.dateSent) if (c != SAME) return c c = compare(lhs.address, rhs.address) if (c != SAME) return c c = compare(lhs.person, rhs.person) if (c != SAME) return c c = compare(lhs.body, rhs.body) if (c != SAME) return c c = compare(lhs.subject, rhs.subject) if (c != SAME) return c c = compare(lhs.threadId, rhs.threadId) if (c != SAME) return c c = compare(lhs.status, rhs.status) if (c != SAME) return c c = compare(lhs.errorCode, rhs.errorCode) if (c != SAME) return c c = compare(lhs.isLocked, rhs.isLocked) if (c != SAME) return c c = compare(lhs.protocol, rhs.protocol) if (c != SAME) return c c = compare(lhs.isRead, rhs.isRead) if (c != SAME) return c c = compare(lhs.isSeen, rhs.isSeen) return if (c != SAME) c else super.compare(lhs, rhs) } override fun difference(lhs: MessageItem, rhs: MessageItem): BooleanArray { val result = BooleanArray(14) result[ADDRESS] = isDifferentIgnoreCase(lhs.address, rhs.address) result[BODY] = isDifferent(lhs.body, rhs.body) result[DATE] = isDifferentTime(lhs.dateReceived, rhs.dateReceived, SECOND_IN_MILLIS) result[DATE_SENT] = isDifferentTime(lhs.dateSent, rhs.dateSent, SECOND_IN_MILLIS) result[ERROR_CODE] = isDifferent(lhs.errorCode, rhs.errorCode) result[LOCKED] = isDifferent(lhs.isLocked, rhs.isLocked) result[PERSON] = isDifferent(lhs.person, rhs.person) result[PROTOCOL] = isDifferent(lhs.protocol, rhs.protocol) result[READ] = isDifferent(lhs.isRead, rhs.isRead) result[SEEN] = isDifferent(lhs.isSeen, rhs.isSeen) result[STATUS] = isDifferent(lhs.status, rhs.status) result[SUBJECT] = isDifferentIgnoreCase(lhs.subject, rhs.subject) result[THREAD_ID] = isDifferent(lhs.threadId, rhs.threadId) result[TYPE] = isDifferent(lhs.type, rhs.type) return result } override fun match(lhs: MessageItem, rhs: MessageItem, difference: BooleanArray?): Float { val different = difference ?: difference(lhs, rhs) var match = MATCH_SAME if (different[DATE]) { match *= 0.7f } if (different[TYPE]) { match *= 0.8f } if (different[DATE_SENT]) { match *= 0.8f } if (different[ADDRESS]) { match *= matchTitle(lhs.address, rhs.address, 0.8f) } if (different[PERSON]) { match *= 0.8f } if (different[BODY]) { match *= 0.75f } if (different[SUBJECT]) { match *= matchTitle(lhs.subject, rhs.subject, 0.85f) } if (different[THREAD_ID]) { match *= 0.9f } if (different[STATUS]) { match *= 0.95f } if (different[ERROR_CODE]) { match *= 0.95f } if (different[LOCKED]) { match *= 0.95f } if (different[PROTOCOL]) { match *= 0.95f } if (different[READ]) { match *= 0.95f } if (different[SEEN]) { match *= 0.95f } return match } companion object { val TYPE = 0 val DATE = 1 val DATE_SENT = 2 val ADDRESS = 3 val PERSON = 4 val BODY = 5 val SUBJECT = 6 val THREAD_ID = 7 val STATUS = 8 val ERROR_CODE = 9 val LOCKED = 10 val PROTOCOL = 11 val READ = 12 val SEEN = 13 } }
apache-2.0
8437e096d9483b5b5eeb4be6c7701e7f
31.328859
94
0.580029
3.894099
false
false
false
false
jpmoreto/play-with-robots
android/app/src/main/java/jpm/android/robot/Pose.kt
1
2100
package jpm.android.robot import jpm.lib.math.power2 /** * Created by jm on 19/02/17. * @time time in millisecond when the robot has the pose * @x position in meter * @x position in mter * @angle in radian - angle between Global and Local frame. * On star we can assume that the robot is oriented with global frame, * or if we have a compass we can assume that global frame Y points to north and X to west. * Global Frame orientation = Local frame orientation + angle * (angle positive in clockwise - unlike trigonometric circle) */ data class Pose(val time: Long, val x: Double, val y: Double, val angle: Double) { // return value in millimeters fun distanceTo(endPose: Pose): Double = Math.sqrt(power2(endPose.x - x) + power2(endPose.y - y)) // return value in milli radians fun rotationTo(endPose: Pose): Double = endPose.angle - angle // return value in millimeter / millisecond fun velocityTo(endPose: Pose): Double = distanceTo(endPose) / (endPose.time - time) // return value in milli radians / millisecond fun angularVelocityTo(endPose: Pose): Double = rotationTo(endPose) / (endPose.time - time) // return value in millimeter / millisecond^2 fun accelerationTo(pose1: Pose, pose2: Pose): Double = // v = v0 + a * t => a = (v - v0) / t (pose1.velocityTo(pose2) - velocityTo(pose1)) / (pose2.time - pose1.time) // return value in milli radians / millisecond^2 fun angularAccelerationTo(pose1: Pose, pose2: Pose): Double = // v = v0 + a * t => a = (v - v0) / t (pose1.angularVelocityTo(pose2) - angularVelocityTo(pose1)) / (pose2.time - pose1.time) } fun toGlobalCoordinates(l: Pose): Pose { val cos = Math.cos(l.angle) val sin = Math.sin(l.angle) return Pose(l.time, l.x * cos - l.y * sin, l.x * sin + l.y * cos, l.angle) } fun toLocalCoordinates(g: Pose): Pose { val cos = Math.cos(g.angle) val sin = Math.sin(g.angle) return Pose(g.time, g.x * cos + g.y * sin, -g.x * sin + g.y * cos, g.angle) }
mit
f7d83785bdba1c3c880e76822a409b2d
36.5
103
0.639524
3.328051
false
false
false
false
msebire/intellij-community
platform/platform-impl/src/com/intellij/util/SingleAlarm.kt
1
2984
// Copyright 2000-2019 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.util import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState class SingleAlarm @JvmOverloads constructor(private val task: Runnable, private val delay: Int, parentDisposable: Disposable? = null, threadToUse: ThreadToUse = ThreadToUse.SWING_THREAD, private val modalityState: ModalityState? = if (threadToUse == ThreadToUse.SWING_THREAD) ModalityState.NON_MODAL else null) : Alarm(threadToUse, parentDisposable) { constructor(task: Runnable, delay: Int, modalityState: ModalityState, parentDisposable: Disposable) : this(task, delay = delay, parentDisposable = parentDisposable, threadToUse = ThreadToUse.SWING_THREAD, modalityState = modalityState) constructor(task: Runnable, delay: Int, threadToUse: Alarm.ThreadToUse, parentDisposable: Disposable) : this(task, delay = delay, parentDisposable = parentDisposable, threadToUse = threadToUse, modalityState = if (threadToUse == ThreadToUse.SWING_THREAD) ModalityState.NON_MODAL else null) init { if (threadToUse == ThreadToUse.SWING_THREAD && modalityState == null) { throw IllegalArgumentException("modalityState must be not null if threadToUse == ThreadToUse.SWING_THREAD") } } @JvmOverloads fun request(forceRun: Boolean = false, delay: Int = [email protected]) { if (isEmpty) { _addRequest(task, if (forceRun) 0 else delay.toLong(), modalityState) } } fun cancel() { cancelAllRequests() } fun cancelAndRequest() { if (!isDisposed) { cancelAllAndAddRequest(task, delay, modalityState) } } } fun pooledThreadSingleAlarm(delay: Int, parentDisposable: Disposable = ApplicationManager.getApplication(), task: () -> Unit): SingleAlarm { return SingleAlarm(Runnable(task), delay = delay, threadToUse = Alarm.ThreadToUse.POOLED_THREAD, parentDisposable = parentDisposable) }
apache-2.0
4fe417d4335e2a0dabfdf1c524b731f6
58.7
206
0.527815
6.403433
false
false
false
false
RyotaMurohoshi/KotLinq
src/main/kotlin/com/muhron/kotlinq/singleOrDefault.kt
1
1348
import com.muhron.kotlinq.where // singleOrDefault fun <TSource> Sequence<TSource>.singleOrDefault(): TSource? { val iterator = iterator() if (!iterator.hasNext()) { return null } val single = iterator.next() if (iterator.hasNext()) { throw IllegalArgumentException("Duplicate elements") } return single } fun <TSource> Iterable<TSource>.singleOrDefault(): TSource? = asSequence().singleOrDefault() fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.singleOrDefault(): Map.Entry<TSourceK, TSourceV>? = asSequence().singleOrDefault() fun <TSource> Array<TSource>.singleOrDefault(): TSource? = asSequence().singleOrDefault() // singleOrDefault with predicate fun <TSource> Sequence<TSource>.singleOrDefault(predicate: (TSource) -> Boolean): TSource? = where(predicate).singleOrDefault() fun <TSource> Iterable<TSource>.singleOrDefault(predicate: (TSource) -> Boolean): TSource? = asSequence().singleOrDefault(predicate) fun <TSourceK, TSourceV> Map<TSourceK, TSourceV>.singleOrDefault(predicate: (Map.Entry<TSourceK, TSourceV>) -> Boolean): Map.Entry<TSourceK, TSourceV>? = asSequence().singleOrDefault(predicate) fun <TSource> Array<TSource>.singleOrDefault(predicate: (TSource) -> Boolean): TSource? = asSequence().singleOrDefault(predicate)
mit
c6a854da60c6754717e09fcc7e87d13e
36.444444
153
0.709941
4.434211
false
false
false
false
google/evergreen-checker
evergreen/src/main/java/app/evergreen/ui/BigTextFragment.kt
1
1930
// 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 app.evergreen.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.DialogFragment import app.evergreen.R class BigTextFragment : DialogFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_big_text, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) arguments?.let { args -> if (args.containsKey(EXTRA_TITLE)) { view.findViewById<TextView>(R.id.big_text_title)?.text = args.getString(EXTRA_TITLE) ?: "" } if (args.containsKey(EXTRA_DESCRIPTION)) { view.findViewById<TextView>(R.id.big_text_description)?.text = args.getString(EXTRA_DESCRIPTION) ?: "" } } } companion object { const val TAG = "QrCodeFragment" private const val EXTRA_TITLE = "title" private const val EXTRA_DESCRIPTION = "description" fun withText(title: String, description: String) = BigTextFragment().apply { arguments = Bundle().apply { putString(EXTRA_TITLE, title) putString(EXTRA_DESCRIPTION, description) } } } }
apache-2.0
159511df75eba2f259383af8b001f214
34.090909
114
0.721244
4.232456
false
false
false
false
alashow/music-android
modules/ui-search/src/main/java/tm/alashow/datmusic/ui/search/Search.kt
1
11627
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.ui.search import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Animatable import androidx.compose.animation.expandIn import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkOut import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedTextField import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Clear import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.platform.LocalWindowInfo import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.capitalize import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.TransformedText import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.google.accompanist.insets.LocalWindowInsets import com.google.accompanist.insets.statusBarsPadding import com.google.accompanist.insets.ui.Scaffold import com.google.firebase.analytics.FirebaseAnalytics import kotlin.math.round import tm.alashow.base.util.click import tm.alashow.common.compose.LocalAnalytics import tm.alashow.common.compose.getNavArgument import tm.alashow.common.compose.rememberFlowWithLifecycle import tm.alashow.datmusic.data.repos.search.DatmusicSearchParams.BackendType import tm.alashow.navigation.QUERY_KEY import tm.alashow.ui.OffsetNotifyingBox import tm.alashow.ui.components.ChipsRow import tm.alashow.ui.theme.AppTheme import tm.alashow.ui.theme.borderlessTextFieldColors import tm.alashow.ui.theme.topAppBarTitleStyle import tm.alashow.ui.theme.translucentSurface @Composable fun Search() { Search(viewModel = hiltViewModel()) } @Composable internal fun Search( viewModel: SearchViewModel, ) { Search(viewModel) { action -> viewModel.submitAction(action) } } @OptIn(ExperimentalFoundationApi::class, ExperimentalAnimationApi::class) @Composable internal fun Search( viewModel: SearchViewModel, actioner: (SearchAction) -> Unit ) { val viewState by rememberFlowWithLifecycle(viewModel.state).collectAsState(initial = SearchViewState.Empty) val listState = rememberLazyListState() Search(viewState, actioner, viewModel, listState) } @Composable private fun Search( viewState: SearchViewState, actioner: (SearchAction) -> Unit, viewModel: SearchViewModel, listState: LazyListState ) { val searchBarHideThreshold = 4 val searchBarHeight = 200.dp val searchBarOffset = remember { Animatable(0f) } OffsetNotifyingBox(headerHeight = searchBarHeight) { _, progress -> Scaffold( topBar = { LaunchedEffect(progress.value, listState.firstVisibleItemIndex) { if (listState.firstVisibleItemIndex > searchBarHideThreshold) { // rounding is important here because we don't searchBar to be stuck in between transitions searchBarOffset.animateTo(round(progress.value)) } else searchBarOffset.animateTo(0f) } SearchAppBar( modifier = Modifier .graphicsLayer { alpha = 1 - searchBarOffset.value translationY = searchBarHeight.value * (-searchBarOffset.value) }, state = viewState, onQueryChange = { actioner(SearchAction.QueryChange(it)) }, onSearch = { actioner(SearchAction.Search) }, onBackendTypeSelect = { actioner(it) } ) } ) { SearchList( viewModel = viewModel, listState = listState, ) } } } @Composable @OptIn(ExperimentalAnimationApi::class, ExperimentalComposeUiApi::class) private fun SearchAppBar( state: SearchViewState, modifier: Modifier = Modifier, titleModifier: Modifier = Modifier, onQueryChange: (String) -> Unit = {}, onSearch: () -> Unit = {}, onBackendTypeSelect: (SearchAction.SelectBackendType) -> Unit = {} ) { val initialQuery = (getNavArgument(QUERY_KEY) ?: "").toString() Box( modifier = modifier .translucentSurface() .fillMaxWidth() .statusBarsPadding() .padding(bottom = AppTheme.specs.paddingTiny) ) { val keyboardController = LocalSoftwareKeyboardController.current val focusManager = LocalFocusManager.current val hasWindowFocus = LocalWindowInfo.current.isWindowFocused val keyboardVisible = LocalWindowInsets.current.ime.isVisible var focused by remember { mutableStateOf(false) } val searchActive = focused && hasWindowFocus && keyboardVisible val triggerSearch = { onSearch() keyboardController?.hide() focusManager.clearFocus() } Column( verticalArrangement = Arrangement.spacedBy(AppTheme.specs.paddingSmall), modifier = Modifier.animateContentSize() ) { // hide title bar if we can make search list not jump during transitions caused by toolbar height change // if (!searchActive) Text( text = stringResource(R.string.search_title), style = topAppBarTitleStyle(), modifier = titleModifier.padding(start = AppTheme.specs.padding, top = AppTheme.specs.padding), ) var query by rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue(initialQuery)) } SearchTextField( value = query, onValueChange = { value -> query = value onQueryChange(value.text) }, onSearch = { triggerSearch() }, hint = if (!searchActive) stringResource(R.string.search_hint) else stringResource(R.string.search_hint_query), modifier = Modifier .fillMaxWidth() .onFocusChanged { focused = it.isFocused } ) var backends = state.searchFilter.backends // this applies until default selections mean everything is chosen if (backends == SearchFilter.DefaultBackends) backends = emptySet() val filterVisible = searchActive || query.text.isNotBlank() || backends.isNotEmpty() SearchFilterPanel(visible = filterVisible, backends) { selectAction -> onBackendTypeSelect(selectAction) triggerSearch() } } } } @OptIn(ExperimentalAnimationApi::class) @Composable private fun ColumnScope.SearchFilterPanel( visible: Boolean, selectedItems: Set<BackendType>, onBackendTypeSelect: (SearchAction.SelectBackendType) -> Unit ) { AnimatedVisibility( visible = visible, enter = expandIn(Alignment.TopCenter) + fadeIn(), exit = shrinkOut(Alignment.BottomCenter) + fadeOut() ) { ChipsRow( items = BackendType.values().toList(), selectedItems = selectedItems, onItemSelect = { selected, item -> onBackendTypeSelect(SearchAction.SelectBackendType(selected, item)) }, labelMapper = { stringResource( when (it) { BackendType.AUDIOS -> R.string.search_audios BackendType.ARTISTS -> R.string.search_artists BackendType.ALBUMS -> R.string.search_albums BackendType.MINERVA -> R.string.search_minerva BackendType.FLACS -> R.string.search_flacs } ) } ) } } @OptIn(ExperimentalAnimationApi::class) @Composable fun SearchTextField( value: TextFieldValue, onValueChange: (TextFieldValue) -> Unit, modifier: Modifier = Modifier, onSearch: () -> Unit = {}, hint: String, maxLength: Int = 50, keyboardOptions: KeyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Search, keyboardType = KeyboardType.Text), keyboardActions: KeyboardActions = KeyboardActions(onSearch = { onSearch() }), analytics: FirebaseAnalytics = LocalAnalytics.current ) { OutlinedTextField( value = value, onValueChange = { if (it.text.length <= maxLength) onValueChange(it) }, placeholder = { Text(text = hint) }, trailingIcon = { AnimatedVisibility( visible = value.text.isNotEmpty(), enter = expandIn(Alignment.Center), exit = shrinkOut(Alignment.Center) ) { IconButton( onClick = { onValueChange(TextFieldValue()) analytics.click("search.clear") }, ) { Icon( tint = MaterialTheme.colors.secondary, imageVector = Icons.Default.Clear, contentDescription = stringResource(R.string.generic_clear) ) } } }, colors = borderlessTextFieldColors(), keyboardOptions = keyboardOptions, keyboardActions = keyboardActions, singleLine = true, maxLines = 1, visualTransformation = { text -> TransformedText(text.capitalize(), OffsetMapping.Identity) }, modifier = modifier .padding(horizontal = AppTheme.specs.padding) .background(AppTheme.colors.onSurfaceInputBackground, MaterialTheme.shapes.small) ) }
apache-2.0
81c0cb3bd322f9834cb02c02bcc99ecc
38.016779
132
0.670938
5.113017
false
false
false
false
icanit/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/manga/info/MangaInfoFragment.kt
1
6283
package eu.kanade.tachiyomi.ui.manga.info import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.bumptech.glide.Glide import com.bumptech.glide.load.engine.DiskCacheStrategy import com.bumptech.glide.load.model.GlideUrl import com.bumptech.glide.signature.StringSignature import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.source.base.Source import eu.kanade.tachiyomi.ui.base.fragment.BaseRxFragment import kotlinx.android.synthetic.main.fragment_manga_info.* import nucleus.factory.RequiresPresenter /** * Fragment that shows manga information. * Uses R.layout.fragment_manga_info. * UI related actions should be called from here. */ @RequiresPresenter(MangaInfoPresenter::class) class MangaInfoFragment : BaseRxFragment<MangaInfoPresenter>() { companion object { /** * Create new instance of MangaInfoFragment. * * @return MangaInfoFragment. */ fun newInstance(): MangaInfoFragment { return MangaInfoFragment() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedState: Bundle?): View? { return inflater.inflate(R.layout.fragment_manga_info, container, false) } override fun onViewCreated(view: View?, savedState: Bundle?) { // Set onclickListener to toggle favorite when FAB clicked. fab_favorite.setOnClickListener { presenter.toggleFavorite() } // Set SwipeRefresh to refresh manga data. swipe_refresh.setOnRefreshListener { fetchMangaFromSource() } } /** * Check if manga is initialized. * If true update view with manga information, * if false fetch manga information * * @param manga manga object containing information about manga. * @param source the source of the manga. */ fun onNextManga(manga: Manga, source: Source) { if (manga.initialized) { // Update view. setMangaInfo(manga, source) } else { // Initialize manga. fetchMangaFromSource() } } /** * Update the view with manga information. * * @param manga manga object containing information about manga. * @param source the source of the manga. */ private fun setMangaInfo(manga: Manga, source: Source?) { // Update artist TextView. manga_artist.text = manga.artist // Update author TextView. manga_author.text = manga.author // If manga source is known update source TextView. if (source != null) { manga_source.text = source.visibleName } // Update genres TextView. manga_genres.text = manga.genre // Update status TextView. manga_status.text = manga.getStatus(activity) // Update description TextView. manga_summary.text = manga.description // Set the favorite drawable to the correct one. setFavoriteDrawable(manga.favorite) // Initialize CoverCache and Glide headers to retrieve cover information. val coverCache = presenter.coverCache val headers = presenter.source.glideHeaders // Check if thumbnail_url is given. manga.thumbnail_url?.let { url -> if (manga.favorite) { coverCache.saveOrLoadFromCache(url, headers) { if (isResumed) { Glide.with(context) .load(it) .diskCacheStrategy(DiskCacheStrategy.RESULT) .centerCrop() .signature(StringSignature(it.lastModified().toString())) .into(manga_cover) Glide.with(context) .load(it) .diskCacheStrategy(DiskCacheStrategy.RESULT) .centerCrop() .signature(StringSignature(it.lastModified().toString())) .into(backdrop) } } } else { Glide.with(context) .load(if (headers != null) GlideUrl(url, headers) else url) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .centerCrop() .into(manga_cover) Glide.with(context) .load(if (headers != null) GlideUrl(url, headers) else url) .diskCacheStrategy(DiskCacheStrategy.SOURCE) .centerCrop() .into(backdrop) } } } /** * Update chapter count TextView. * * @param count number of chapters. */ fun setChapterCount(count: Int) { manga_chapters.text = count.toString() } /** * Update FAB with correct drawable. * * @param isFavorite determines if manga is favorite or not. */ private fun setFavoriteDrawable(isFavorite: Boolean) { // Set the Favorite drawable to the correct one. // Border drawable if false, filled drawable if true. fab_favorite.setImageResource(if (isFavorite) R.drawable.ic_bookmark_white_24dp else R.drawable.ic_bookmark_border_white_24dp) } /** * Start fetching manga information from source. */ private fun fetchMangaFromSource() { setRefreshing(true) // Call presenter and start fetching manga information presenter.fetchMangaFromSource() } /** * Update swipe refresh to stop showing refresh in progress spinner. */ fun onFetchMangaDone() { setRefreshing(false) } /** * Update swipe refresh to start showing refresh in progress spinner. */ fun onFetchMangaError() { setRefreshing(false) } /** * Set swipe refresh status. * * @param value whether it should be refreshing or not. */ private fun setRefreshing(value: Boolean) { swipe_refresh.isRefreshing = value } }
apache-2.0
bfee445f471a6020827465ec311c5058
31.554404
108
0.595098
5.030424
false
false
false
false
ratabb/Hishoot2i
app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/template/TemplateFragment.kt
1
9748
package org.illegaller.ratabb.hishoot2i.ui.template import android.annotation.SuppressLint import android.content.BroadcastReceiver import android.content.Intent import android.content.IntentFilter import android.os.Bundle import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.appcompat.view.menu.MenuBuilder import androidx.appcompat.view.menu.MenuPopupHelper import androidx.appcompat.widget.PopupMenu import androidx.core.view.isVisible import androidx.documentfile.provider.DocumentFile import androidx.fragment.app.Fragment import androidx.fragment.app.clearFragmentResult import androidx.fragment.app.setFragmentResultListener import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearSnapHelper import common.ext.hideSoftKey import common.ext.preventMultipleClick import common.ext.toFile import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview import org.illegaller.ratabb.hishoot2i.HiShootActivity import org.illegaller.ratabb.hishoot2i.R import org.illegaller.ratabb.hishoot2i.data.pref.TemplatePref import org.illegaller.ratabb.hishoot2i.data.pref.TemplateToolPref import org.illegaller.ratabb.hishoot2i.databinding.FragmentTemplateBinding import org.illegaller.ratabb.hishoot2i.ui.ARG_SORT import org.illegaller.ratabb.hishoot2i.ui.KEY_REQ_SORT import org.illegaller.ratabb.hishoot2i.ui.common.SideListDivider import org.illegaller.ratabb.hishoot2i.ui.common.broadcastReceiver import org.illegaller.ratabb.hishoot2i.ui.common.queryTextChange import org.illegaller.ratabb.hishoot2i.ui.common.registerGetContent import org.illegaller.ratabb.hishoot2i.ui.common.showSnackBar import org.illegaller.ratabb.hishoot2i.ui.common.viewObserve import org.illegaller.ratabb.hishoot2i.ui.template.TemplateFragmentDirections.Companion.actionTemplateToSortTemplate import template.Template import template.TemplateComparator import timber.log.Timber import javax.inject.Inject @ExperimentalCoroutinesApi @AndroidEntryPoint class TemplateFragment : Fragment(R.layout.fragment_template) { @Inject lateinit var templateAdapter: TemplateAdapter @Inject lateinit var templatePref: TemplatePref @Inject lateinit var templateToolPref: TemplateToolPref private val viewModel: TemplateViewModel by viewModels() private val requestHtz = registerGetContent { uri -> DocumentFile.fromSingleUri(requireContext(), uri)?.uri?.toFile(requireContext())?.let { viewModel.importFileHtz(it) } } private val receiver: BroadcastReceiver by broadcastReceiver { _, _ -> viewModel.perform() } override fun onResume() { super.onResume() requireActivity().registerReceiver( receiver, IntentFilter().apply { // addAction(Intent.ACTION_PACKAGE_INSTALL) // <-- TODO: ? addAction(Intent.ACTION_PACKAGE_ADDED) addAction(Intent.ACTION_PACKAGE_CHANGED) addAction(Intent.ACTION_PACKAGE_REMOVED) addAction(Intent.ACTION_PACKAGE_REPLACED) addDataScheme("package") } ) } override fun onPause() { super.onPause() requireActivity().unregisterReceiver(receiver) } @FlowPreview override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) FragmentTemplateBinding.bind(view).apply { setViewListener() viewObserve(viewModel.uiState) { observerView(it) } viewObserve(viewModel.htzState) { observerHtzView(it) } viewModel.search(templateSearchView.queryTextChange()) } viewModel.perform() setFragmentResultListener(KEY_REQ_SORT) { _, result -> templatePref.templateComparator = TemplateComparator.values()[result.getInt(ARG_SORT)] viewModel.perform() // TODO: handle view on Search ? } } override fun onDestroyView() { clearFragmentResult(KEY_REQ_SORT) super.onDestroyView() } private fun FragmentTemplateBinding.observerHtzView(state: HtzEventView) { when (state) { LoadingHtzEvent -> templateProgress.show() is FailHtzEvent -> { templateProgress.hide() onError(state.cause) } is SuccessHtzEvent -> { templateProgress.hide() htzNotify(state.event, state.message) } } } private fun FragmentTemplateBinding.observerView(state: TemplateView) { when (state) { Loading -> templateProgress.show() is Fail -> { templateProgress.hide() onError(state.cause) } is Success -> { templateProgress.hide() setData(state.data) } } } private fun FragmentTemplateBinding.setViewListener() { templateAdapter.clickItem = ::adapterItemClick templateAdapter.longClickItem = ::adapterItemLongClick templateRecyclerView.apply { adapter = templateAdapter SideListDivider.addItemDecorToRecyclerView(this) LinearSnapHelper().attachToRecyclerView(this) setHasFixedSize(true) } templateHtzFab.setOnClickListener { requestHtz.launch("*/*") } templateBottomAppBar.apply { setOnMenuItemClickListener(::menuItemClick) setNavigationOnClickListener(::popBack) } } private fun FragmentTemplateBinding.setData(templates: List<Template>) { val haveData = templates.isNotEmpty() if (haveData) { // TODO: val state = templateRecyclerView.layoutManager?.onSaveInstanceState() templateAdapter.submitList(templates) // templateRecyclerView.layoutManager?.onRestoreInstanceState(state) } templateRecyclerView.isVisible = haveData noContent.isVisible = !haveData } private fun htzNotify(htzEvent: HtzEvent, message: String) { val format = when (htzEvent) { HtzEvent.IMPORT -> R.string.template_htz_imported_format HtzEvent.CONVERT -> R.string.template_htz_converted_format HtzEvent.EXPORT -> R.string.template_htz_exported_format HtzEvent.REMOVE -> R.string.template_htz_removed_format } showSnackBar( view = requireView(), text = getString(format, message), anchorViewId = R.id.templateHtzFab ) } private fun onError(e: Throwable) { Toast.makeText(requireContext(), e.localizedMessage ?: "Oops", Toast.LENGTH_SHORT).show() Timber.e(e) // } private fun popBack(view: View) { if ((requireActivity() as HiShootActivity).isKeyboardShow) view.hideSoftKey() else findNavController().popBackStack() } private fun menuItemClick(menuItem: MenuItem): Boolean = menuItem.preventMultipleClick { return when (menuItem.itemId) { R.id.action_sort_template -> { findNavController().navigate( actionTemplateToSortTemplate(templatePref.templateComparator) ) true } else -> false } } @SuppressLint("RestrictedApi") // <- MenuPopupHelper || TODO: replace with something else? private inline fun popupMenu( view: View, isHtz: Boolean, crossinline menuClick: (MenuItem) -> Boolean ) = PopupMenu(view.context, view).apply { inflate(R.menu.template_popup) if (isHtz) menu.findItem(R.id.action_convert_to_htz).isEnabled = false else { menu.findItem(R.id.action_export_htz).isEnabled = false menu.findItem(R.id.action_remove_htz).isEnabled = false } setOnMenuItemClickListener { menuClick(it) } }.run { MenuPopupHelper(view.context, menu as MenuBuilder, view) .apply { setForceShowIcon(true) } .show() } private fun adapterItemLongClick(view: View, template: Template): Boolean = when (template) { is Template.Default -> false is Template.VersionHtz -> { popupMenu(view, true) { return@popupMenu when (it.itemId) { R.id.action_export_htz -> { viewModel.exportTemplateHtz(template) true } R.id.action_remove_htz -> { viewModel.removeTemplateHtz(template) true } else -> false } } true } is Template.Version1, is Template.Version2, is Template.Version3 -> { popupMenu(view, false) { return@popupMenu when (it.itemId) { R.id.action_convert_to_htz -> { viewModel.convertTemplateHtz(template) true } else -> false } } true } } private fun adapterItemClick(template: Template) { if (templateToolPref.templateCurrentId != template.id) { templateToolPref.templateCurrentId = template.id showSnackBar( view = requireView(), text = getString(R.string.apply_template_format, template.name), anchorViewId = R.id.templateHtzFab ) } } }
apache-2.0
e1998d63d9d5818a942f5cee9e7cf010
36.064639
116
0.646492
4.806706
false
false
false
false
sbhachu/kotlin-bootstrap
app/src/main/kotlin/com/sbhachu/bootstrap/extensions/listener/AnimationListener.kt
1
1012
package com.sbhachu.bootstrap.extensions.listener import android.view.animation.Animation class AnimationListener : Animation.AnimationListener { private var _onAnimationStart: ((animation: Animation) -> Unit)? = null private var _onAnimationEnd: ((animation: Animation) -> Unit)? = null private var _onAnimationRepeat: ((animation: Animation) -> Unit)? = null override fun onAnimationStart(animation: Animation) { _onAnimationStart?.invoke(animation) } override fun onAnimationEnd(animation: Animation) { _onAnimationEnd?.invoke(animation) } override fun onAnimationRepeat(animation: Animation) { _onAnimationRepeat?.invoke(animation) } fun onAnimationStart(listener: (Animation?) -> Unit) { _onAnimationStart = listener } fun onAnimationEnd(listener: (Animation?) -> Unit) { _onAnimationEnd = listener } fun onAnimationRepeat(listener: (Animation?) -> Unit) { _onAnimationRepeat = listener } }
apache-2.0
aba4c1b4a8cd8495a8a9440a71c691a5
28.794118
76
0.689723
5.06
false
false
false
false
davidwhitman/changelogs
persistence/src/test/java/com/thunderclouddev/persistence/AppInfoDatabaseTest.kt
1
2323
/* * Copyright (c) 2017. * Distributed under the GNU GPLv3 by David Whitman. * https://www.gnu.org/licenses/gpl-3.0.en.html * * This source code is made available to help others learn. Please don't clone my app. */ package com.thunderclouddev.persistence; //import com.nhaarman.mockito_kotlin.mock //import com.thunderclouddev.utils.anyKt //import io.requery.Persistable //import io.requery.kotlin.Selection //import io.requery.kotlin.WhereAndOr //import io.requery.query.Condition //import io.requery.query.Expression //import io.requery.query.Result //import io.requery.reactivex.KotlinReactiveEntityStore //import io.requery.reactivex.ReactiveResult //import org.jetbrains.spek.api.Spek //import org.jetbrains.spek.api.dsl.context //import org.jetbrains.spek.api.dsl.given //import org.junit.platform.runner.JUnitPlatform //import org.junit.runner.RunWith //import org.mockito.Mockito.`when` //@RunWith(JUnitPlatform::class) //object AppInfoDatabaseTest : Spek({ // given("a database") { // // var database: AppInfoDatabase // var requeryDb: RequeryDatabase<Persistable> // val debugMode = false // var dbStore: KotlinReactiveEntityStore<Persistable> = mock() // // beforeEachTest { // requeryDb = mock() // dbStore = mock() // database = AppInfoDatabase(requeryDb, debugMode) // // `when`(requeryDb.data).thenReturn(dbStore) // } // // context("is that there are items in the database") { // var items: ReactiveResult<Persistable> // // beforeEachTest { // items = ReactiveResult<Persistable>(Result<Persistable>(listOf(DbAppInfoEntity().apply { // packageName = "com.test.app1" // }, DbAppInfoEntity().apply { // packageName = "com.test.app2" // }))) // // val selection = mock<Selection<ReactiveResult<DbAppInfoEntity>>>() // val where = mock<WhereAndOr<ReactiveResult<DbAppInfoEntity>>>() // `when`(dbStore.select(DbAppInfoEntity::class)).thenReturn(selection) // `when`(selection.where(anyKt<Condition<Expression<String>, *>>())).thenReturn(where) // `when`(where.get()).thenReturn(items) // } // } // } //})
gpl-3.0
7ab70e4d1179db90f9e4306f30e389f8
35.3125
106
0.643564
3.917369
false
true
false
false
SimonVT/cathode
cathode-common/src/main/java/net/simonvt/cathode/common/data/BaseCursorLiveData.kt
1
2125
/* * Copyright (C) 2018 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.common.data import android.content.Context import android.database.Cursor import android.database.sqlite.SQLiteException import android.net.Uri import net.simonvt.cathode.common.database.SimpleCursor import timber.log.Timber abstract class BaseCursorLiveData<D>( context: Context, private val uri: Uri, private val projection: Array<String>, private val selection: String? = null, private val selectionArgs: Array<String>? = null, private var sortOrder: String? = null ) : ListenableLiveData<D>(context), ThrottleContentObserver.Callback { private var notificationUri: Uri? = null fun setSortOrder(sortOrder: String) { this.sortOrder = sortOrder loadData() } override fun onContentChanged() { loadData() } fun loadCursor(): Cursor? { try { val cursor = context.contentResolver.query(uri, projection, selection, selectionArgs, sortOrder) var result: SimpleCursor? = null if (cursor != null) { val oldNotificationUri = notificationUri notificationUri = cursor.notificationUri if (oldNotificationUri == null) { registerUri(notificationUri!!) } else if (oldNotificationUri != notificationUri) { unregisterUri(oldNotificationUri) registerUri(notificationUri!!) } result = SimpleCursor(cursor) cursor.close() } return result } catch (e: SQLiteException) { Timber.e(e, "Query failed") } return null } }
apache-2.0
61003def5770eddc4e1760fd9fb92cd9
28.929577
91
0.703529
4.345603
false
false
false
false
harningt/atomun-keygen
src/main/java/us/eharning/atomun/keygen/internal/spi/bip0032/BouncyCastleBIP0032NodeProcessor.kt
1
14478
/* * Copyright 2015, 2017 Thomas Harning Jr. <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package us.eharning.atomun.keygen.internal.spi.bip0032 import com.google.common.base.Charsets import com.google.common.cache.CacheBuilder import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import org.bouncycastle.asn1.sec.SECNamedCurves import us.eharning.atomun.core.ValidationException import us.eharning.atomun.core.ec.ECKey import us.eharning.atomun.core.ec.ECKeyFactory import us.eharning.atomun.core.encoding.Base58 import us.eharning.atomun.keygen.path.BIP0032Path import java.math.BigInteger import java.security.InvalidKeyException import java.security.NoSuchAlgorithmException import java.security.SecureRandom import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec /** * BIP0032 node processing implementation based on BouncyCastle. */ internal class BouncyCastleBIP0032NodeProcessor : BIP0032NodeProcessor { /** * Convert the node into a Base58+checksum encoded string. * * @param node * instance to encode. * * @return Base58+checksum encoded string. */ override fun exportNode(node: BIP0032Node): String { /* Assume production - TODO: allow custom address bases */ val production = true val master = node.master val out = ByteArray(78) if (master.hasPrivate()) { if (production) { putBytes(out, 0, xprv) } else { putBytes(out, 0, tprv) } } else { if (production) { putBytes(out, 0, xpub) } else { putBytes(out, 0, tpub) } } out[4] = (node.depth and 0xff).toByte() putInt32(out, 5, node.parent) putInt32(out, 9, node.sequence) putBytes(out, 13, node.getChainCode()) if (master.hasPrivate()) { out[45] = 0x00 val privateKey = master.exportPrivate()!! putBytes(out, 46, privateKey) } else { putBytes(out, 45, master.exportPublic()) } return Base58.encodeWithChecksum(out) } /** * Convert the Base58+checksum encoded string into a BIP0032 node. * * @param serialized * encoded string to decode. * * @return BIP0032 node represented by the serialized string. * * @throws ValidationException * if the data is not a valid encoded BIP0032 node. */ @Throws(ValidationException::class) override fun importNode(serialized: String): BIP0032Node { val data = Base58.decodeWithChecksum(serialized) if (data.size != 78) { throw ValidationException("Invalid extended key value") } val type = data.copyOf(4) val hasPrivate: Boolean if (type.contentEquals(xprv) || type.contentEquals(tprv)) { hasPrivate = true } else if (type.contentEquals(xpub) || type.contentEquals(tpub)) { hasPrivate = false } else { throw ValidationException("Invalid magic number for an extended key") } val depth = data[4].toInt() and 0xff val parent = getInt32(data, 5) val sequence = getInt32(data, 9) val chainCode = data.copyOfRange(13, 13 + 32) val pubOrPriv = data.copyOfRange(13 + 32, data.size) val key: ECKey if (hasPrivate) { key = ECKeyFactory.getInstance().fromSecretExponent(BigInteger(1, pubOrPriv), true) } else { key = ECKeyFactory.getInstance().fromEncodedPublicKey(pubOrPriv, true) } return BIP0032Node(key, chainCode, depth, parent, sequence) } /** * Generates a BIP0032 node from a seed value that is passed through a basic HMAC process. * * @param seed * value for which the node should be generated. * * @return BIP0032 node deterministically based on the seed input. * * @throws ValidationException * if either cryptography fails (unlikely) * or the seed results in an invalid EC key (unlikely). */ /* BITCOIN_SEED is not a password but instead a shared key to mask the seed input */ @SuppressFBWarnings("HARD_CODE_PASSWORD") @Throws(ValidationException::class) override fun generateNodeFromSeed(seed: ByteArray): BIP0032Node { try { val mac = Mac.getInstance("HmacSHA512") val seedkey = SecretKeySpec(BITCOIN_SEED, "HmacSHA512") mac.init(seedkey) val lr = mac.doFinal(seed) val l = lr.copyOfRange(0, 32) val r = lr.copyOfRange(32, 64) val m = BigInteger(1, l) if (m >= curve.n || m == BigInteger.ZERO) { throw ValidationException("Invalid chain value generated") } val keyPair = ECKeyFactory.getInstance().fromSecretExponent(m, true) return BIP0032Node(keyPair, r, 0, 0, 0) } catch (e: NoSuchAlgorithmException) { throw ValidationException(e) } catch (e: InvalidKeyException) { throw ValidationException(e) } } /** * Generates a random BIP0032 node. * * @return BIP0032 node randomly generated. */ override fun generateNode(): BIP0032Node { val key = ECKeyFactory.getInstance().generateRandom(true) val chainCode = ByteArray(32) rnd.nextBytes(chainCode) return BIP0032Node(key, chainCode, 0, 0, 0) } /** * Utility method to perform 'I' value derivation. * * @param node * BIP0032 base node. * @param sequence * value to use for derivation. * * @return derived BIP0032 node. * * @throws NoSuchAlgorithmException * if somehow HmacSHA512 cannot be found (unlikely). * @throws InvalidKeyException * if the chain code is somehow not a value HmacSHA512 key (unlikely). */ @Throws(NoSuchAlgorithmException::class, InvalidKeyException::class) private fun deriveI(node: BIP0032Node, sequence: Int): ByteArray { val mac = Mac.getInstance("HmacSHA512") val key = SecretKeySpec(node.getChainCode(), "HmacSHA512") mac.init(key) val extended: ByteArray if (sequence and 0x80000000.toInt() == 0) { val pub = node.master.exportPublic() extended = pub.copyOf(pub.size + 4) putInt32(extended, pub.size, sequence) } else { val priv = node.master.exportPrivate()!! extended = ByteArray(priv.size + 5) /* Offset of 1 to account for extra zero at front */ System.arraycopy(priv, 0, extended, 1, priv.size) putInt32(extended, priv.size + 1, sequence) } return mac.doFinal(extended) } /** * Derives a BIP0032 node given the input path. * * @param node * base node to derive from. * @param path * set of sequence values to use for derivation. * * @return BIP0032 node derived using the necessary algorithms per BIP0032 specification. * * @throws ValidationException * if it is impossible to generate a key using the path, * it is impossible to derive a key due to missing private bits, * or the resultant key is an invalid EC key (unlikely). */ @Throws(ValidationException::class) override fun deriveNode(node: BIP0032Node, path: BIP0032Path): BIP0032Node { var current = node /* NOTE: since relative paths aren't possible yet with path object, must derive from root */ if (current.depth != 0) { throw ValidationException("Wrong depth for root-based path") } for (sequence in path) { current = deriveNode(current, sequence) } return current } /** * Derives a BIP0032 node given the singular sequence value. * * @param node * base node to derive from. * @param sequence * value to use for derivation. * * @return BIP0032 node derived using the necessary algorithms per BIP0032 specification. * * @throws ValidationException * it is impossible to derive a key due to missing private bits, * or the resultant key is an invalid EC key (unlikely). */ @Throws(ValidationException::class) override fun deriveNode(node: BIP0032Node, sequence: Int): BIP0032Node { val nodeSequence = NodeSequence(node, sequence) return NODE_CACHE.get(nodeSequence) { val master = node.master try { if (sequence and 0x80000000.toInt() != 0 && master.exportPrivate() == null) { throw ValidationException("Need private key for private generation") } val lr = deriveI(node, sequence) val l = lr.copyOfRange(0, 32) val r = lr.copyOfRange(32, 64) val m = BigInteger(1, l) if (m >= curve.n || m == BigInteger.ZERO) { throw ValidationException("Invalid chain value generated") } if (master.hasPrivate()) { val priv = master.exportPrivate()!! val k = (m + BigInteger(1, priv)) % curve.n if (k == BigInteger.ZERO) { throw ValidationException("Invalid private node generated") } return@get BIP0032Node(ECKeyFactory.getInstance().fromSecretExponent(k, true), r, node.depth + 1, node.fingerPrint, sequence) } else { var pub = master.exportPublic() val q = curve.g.multiply(m).add(curve.curve.decodePoint(pub)) if (q.isInfinity) { throw ValidationException("Invalid public node generated") } pub = q.getEncoded(true) return@get BIP0032Node(ECKeyFactory.getInstance().fromEncodedPublicKey(pub, true), r, node.depth + 1, node.fingerPrint, sequence) } } catch (e: NoSuchAlgorithmException) { throw ValidationException(e) } catch (e: InvalidKeyException) { throw ValidationException(e) } } } /** * Obtain the BIP0032 node without its private bits (if present). * * @param node * instance to obtain a version of without private bits. * * @return BIP0032 node instance without private bits. */ override fun getPublic(node: BIP0032Node): BIP0032Node { if (!node.hasPrivate()) { return node } val master = ECKeyFactory.getInstance().fromEncodedPublicKey(node.master.exportPublic(), true) return BIP0032Node(master, node.getChainCode(), node.depth, node.parent, node.sequence) } /** * Utility class wrapping a BIP0032Node+sequence pair for cache identity entry. */ private data class NodeSequence /** * Construct a new pair. * * @param node * BIP0032 base node. * @param sequence * index into BIP0032 base node. */ (private val node: BIP0032Node, private val sequence: Int) companion object { /** * Cache for already-processed node-encodings to avoid unnecessary re-derivation. */ private val NODE_CACHE = CacheBuilder.newBuilder().maximumSize(16).recordStats().build<NodeSequence, BIP0032Node>() private val rnd = SecureRandom() private val curve = SECNamedCurves.getByName("secp256k1") private val BITCOIN_SEED = "Bitcoin seed".toByteArray(Charsets.US_ASCII) private val xprv = byteArrayOf(0x04, 0x88.toByte(), 0xAD.toByte(), 0xE4.toByte()) private val xpub = byteArrayOf(0x04, 0x88.toByte(), 0xB2.toByte(), 0x1E.toByte()) private val tprv = byteArrayOf(0x04, 0x35.toByte(), 0x83.toByte(), 0x94.toByte()) private val tpub = byteArrayOf(0x04, 0x35.toByte(), 0x87.toByte(), 0xCF.toByte()) /** * Copy the given data bytes into the output array at a given offset. * * @param out * array to write into. * @param index * offset into the array to write at. * @param data * array to write from. */ private fun putBytes(out: ByteArray, index: Int, data: ByteArray) { System.arraycopy(data, 0, out, index, data.size) } /** * Store an integer as 4 bytes in a byte array. * * @param out * array to write into. * @param index * offset into the array to write at. * @param value * value to write into the array. */ private fun putInt32(out: ByteArray, index: Int, value: Int) { out[index] = (value shr 24).toByte() out[index + 1] = (value shr 16).toByte() out[index + 2] = (value shr 8).toByte() out[index + 3] = value.toByte() } /** * Convert 4 bytes of a byte array to an integer. * * @param input * byte array to obtain the integer from. * @param index * offset into the array to start at. * * @return 32-bit integer from the input byte array. */ private fun getInt32(input: ByteArray, index: Int): Int { return input[index].toInt() and 0xff shl 24 or (input[index + 1].toInt() and 0xff shl 16) or (input[index + 2].toInt() and 0xff shl 8) or (input[index + 3].toInt() and 0xff) } } }
apache-2.0
093e65e9e82a3d7aa3d54403b7ae30cc
37.301587
149
0.590551
4.355596
false
false
false
false
RoverPlatform/rover-android
core/src/main/kotlin/io/rover/sdk/core/assets/InMemoryBitmapCacheStage.kt
1
3018
package io.rover.sdk.core.assets import android.graphics.Bitmap import android.util.LruCache import io.rover.sdk.core.logging.log import java.net.URL /** * This pipeline stage contains an in-memory cache of [Bitmap]s. If a bitmap is not cached for * the given URL, it will fault to the subsequent stage. * * This is the second layer of cache. */ class InMemoryBitmapCacheStage( private val faultTo: SynchronousPipelineStage<URL, Bitmap> ) : SynchronousPipelineStage<URL, Bitmap> { // TODO: how do we tune size? Google recommends tuning by creating a formula that uses a static // factor (here, 8) suited to your app and then a dynamic factor for the device’s available // per-app memory. For us, surrounding app is also a dynamic factor. Existing SDK just has a // tunable parameter (but this has poor DX and is still little better than a fudge-factor). Can // we dynamically tune? // TODO: at the very least expose the 8-factor as a tunable. /** * Maximum memory available to this process in kilobytes. */ private val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt() init { log.v("There are $maxMemory KiB available to the memory bitmap cache.") } /** * The LRU cache itself, set up to use one eighth of the total memory allowed for this process, * as recommended by https://developer.android.com/topic/performance/graphics/cache-bitmap.html. * * Holds onto a reference to the bitmap, but lets the reference go once evicted. Then it's up * to the GC to free the bitmap and therefore recycle it. */ private val lruCache = object : LruCache<URL, Bitmap>(maxMemory / 8) { override fun sizeOf(key: URL, value: Bitmap): Int = value.byteCount / 1024 override fun create(key: URL): Bitmap { [email protected]("Image not available in cache, faulting to next layer.") val created = faultTo.request(key) return when (created) { is PipelineStageResult.Failed -> throw UnableToCreateEntryException(created.reason) is PipelineStageResult.Successful -> created.output } } } override fun request(input: URL): PipelineStageResult<Bitmap> { return try { val value: Bitmap? = lruCache[input] if(value == null) { // this means that the LRUCache was not able to create a new value for any number // of possible reasons. If so, fault directly to next layer and skip the cache. faultTo.request(input) } else { PipelineStageResult.Successful(lruCache[input]) } } catch (e: UnableToCreateEntryException) { PipelineStageResult.Failed(e.reason) } catch (e: IllegalStateException) { PipelineStageResult.Failed(e) } } private class UnableToCreateEntryException(val reason: Throwable) : Exception(reason) }
apache-2.0
f81d0de82f6905a7fd1b715621be63a9
40.315068
104
0.662467
4.448378
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/inspections/latex/typesetting/LatexCdotInspection.kt
1
580
package nl.hannahsten.texifyidea.inspections.latex.typesetting import nl.hannahsten.texifyidea.inspections.TexifyRegexInspection import java.util.regex.Pattern /** * @author Hannah Schellekens */ open class LatexCdotInspection : TexifyRegexInspection( inspectionDisplayName = "Use of . instead of \\cdot", inspectionId = "Cdot", errorMessage = { "\\cdot expected" }, pattern = Pattern.compile("\\s+(\\.)\\s+"), mathMode = true, replacement = { _, _ -> "\\cdot" }, replacementRange = { it.groupRange(1) }, quickFixName = { "Change to \\cdot" } )
mit
900bdc36ec49af43b7e8adcd121b52a6
31.277778
65
0.682759
3.918919
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/completion/handlers/FileNameInsertionHandler.kt
1
1215
package nl.hannahsten.texifyidea.completion.handlers import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import nl.hannahsten.texifyidea.psi.LatexCommands import nl.hannahsten.texifyidea.util.files.document import nl.hannahsten.texifyidea.util.files.removeFileExtension import nl.hannahsten.texifyidea.util.magic.CommandMagic import nl.hannahsten.texifyidea.util.parentOfType /** * @author Hannah Schellekens */ open class FileNameInsertionHandler : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, element: LookupElement) { val text = element.`object` val file = context.file val document = file.document() ?: return val offset = context.startOffset val normalTextWord = file.findElementAt(offset) ?: return val command = normalTextWord.parentOfType(LatexCommands::class) ?: return if (command.name !in CommandMagic.illegalExtensions.keys) return val extensionless = text.toString().removeFileExtension() document.replaceString(offset, context.tailOffset, extensionless) } }
mit
aa1cb9c02e8a30a65a1d7c72aa1d29f7
39.533333
82
0.776132
4.821429
false
false
false
false
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/lang/SimpleBibtexEntryField.kt
1
543
package nl.hannahsten.texifyidea.lang /** * @author Hannah Schellekens */ data class SimpleBibtexEntryField(override val fieldName: String, override val description: String, override val dependency: LatexPackage = LatexPackage.DEFAULT) : BibtexEntryField { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is SimpleBibtexEntryField) return false if (fieldName != other.fieldName) return false return true } override fun hashCode() = fieldName.hashCode() }
mit
0f13f1f9adbdadff2b0e2471b9c25b52
31
182
0.710866
4.848214
false
false
false
false
PaulWoitaschek/Voice
data/src/main/kotlin/voice/data/repo/internals/migrations/Migration31to32.kt
1
2085
package voice.data.repo.internals.migrations import android.annotation.SuppressLint import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.room.migration.Migration import androidx.sqlite.db.SupportSQLiteDatabase import androidx.sqlite.db.SupportSQLiteQueryBuilder import com.squareup.anvil.annotations.ContributesMultibinding import voice.common.AppScope import voice.data.repo.internals.moveToNextLoop import javax.inject.Inject @ContributesMultibinding( scope = AppScope::class, boundType = Migration::class, ) @SuppressLint("Recycle") class Migration31to32 @Inject constructor() : IncrementalMigration(31) { private val BOOK_ID = "bookId" private val TABLE_BOOK = "tableBooks" private val TABLE_CHAPTERS = "tableChapters" private val BOOK_CURRENT_MEDIA_PATH = "bookCurrentMediaPath" private val CHAPTER_PATH = "chapterPath" override fun migrate(db: SupportSQLiteDatabase) { db.query( TABLE_BOOK, arrayOf(BOOK_ID, BOOK_CURRENT_MEDIA_PATH), ).moveToNextLoop { val bookId = getLong(0) val bookmarkCurrentMediaPath = getString(1) val chapterCursor = db.query( SupportSQLiteQueryBuilder.builder(TABLE_CHAPTERS) .columns(arrayOf(CHAPTER_PATH)) .selection("$BOOK_ID=?", arrayOf(bookId)) .create(), ) val chapterPaths = ArrayList<String>(chapterCursor.count) chapterCursor.moveToNextLoop { val chapterPath = chapterCursor.getString(0) chapterPaths.add(chapterPath) } if (chapterPaths.isEmpty()) { db.delete(TABLE_BOOK, "$BOOK_ID=?", arrayOf(bookId.toString())) } else { val mediaPathValid = chapterPaths.contains(bookmarkCurrentMediaPath) if (!mediaPathValid) { val cv = ContentValues() cv.put(BOOK_CURRENT_MEDIA_PATH, chapterPaths.first()) db.update( TABLE_BOOK, SQLiteDatabase.CONFLICT_FAIL, cv, "$BOOK_ID=?", arrayOf(bookId.toString()), ) } } } } }
gpl-3.0
89785deba479beec4cc6c36a8143faea
30.590909
76
0.686811
4.371069
false
false
false
false
colriot/anko
dsl/src/org/jetbrains/android/anko/Main.kt
1
3275
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko import org.jetbrains.android.anko.config.DefaultAnkoConfiguration import org.jetbrains.android.anko.utils.AndroidVersionDirectoryFilter import org.jetbrains.android.anko.utils.JarFileFilter import java.io.File object Launcher { @JvmStatic fun main(args: Array<String>) { if (args.isNotEmpty()) { args.forEach { taskName -> println(":: $taskName") when (taskName) { "gen", "generate" -> gen() "clean" -> clean() "versions" -> versions() else -> { println("Invalid task $taskName") return } } } println("Done.") } else gen() } } private fun clean() { deleteDirectory(File("workdir/gen/")) } private fun versions() { for (version in getVersionDirs()) { val (platformJars, versionJars) = getJars(version) println("${version.name}") (platformJars + versionJars).forEach { println(" ${it.name}") } } } private fun deleteDirectory(f: File) { if (!f.exists()) return if (f.isDirectory) { f.listFiles()?.forEach { deleteDirectory(it) } } if (!f.delete()) { throw RuntimeException("Failed to delete ${f.absolutePath}") } } private fun getVersionDirs(): Array<File> { val original = File("workdir/original/") if (!original.exists() || !original.isDirectory) { throw RuntimeException("\"workdir/original\" directory does not exist.") } return original.listFiles(AndroidVersionDirectoryFilter()) ?: arrayOf<File>() } private fun getJars(version: File) = version.listFiles(JarFileFilter()).partition { it.name.startsWith("platform.") } private fun gen() { for (versionDir in getVersionDirs()) { val (platformJars, versionJars) = getJars(versionDir) val versionName = versionDir.name if (platformJars.isNotEmpty()) { println("Processing version $versionName") println(" Platform jars: ${platformJars.joinToString()}") if (versionJars.isNotEmpty()) println(" Version jars: ${versionJars.joinToString()}") val outputDirectory = File("workdir/gen/$versionName/") val fileOutputDirectory = File(outputDirectory, "src/main/kotlin/") if (!fileOutputDirectory.exists()) { fileOutputDirectory.mkdirs() } DSLGenerator(versionDir, platformJars, versionJars, DefaultAnkoConfiguration(outputDirectory, versionName)).run() } } }
apache-2.0
8c034d62707c32151b1907184910ac09
32.428571
117
0.619847
4.671897
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/internal/publicsuffix/PublicSuffixDatabase.kt
2
11767
/* * Copyright (C) 2017 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.publicsuffix import java.io.IOException import java.io.InterruptedIOException import java.net.IDN import java.nio.charset.StandardCharsets.UTF_8 import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicBoolean import okhttp3.internal.and import okhttp3.internal.platform.Platform import okio.GzipSource import okio.buffer import okio.source /** * A database of public suffixes provided by [publicsuffix.org][publicsuffix_org]. * * [publicsuffix_org]: https://publicsuffix.org/ */ class PublicSuffixDatabase { /** True after we've attempted to read the list for the first time. */ private val listRead = AtomicBoolean(false) /** Used for concurrent threads reading the list for the first time. */ private val readCompleteLatch = CountDownLatch(1) // The lists are held as a large array of UTF-8 bytes. This is to avoid allocating lots of strings // that will likely never be used. Each rule is separated by '\n'. Please see the // PublicSuffixListGenerator class for how these lists are generated. // Guarded by this. private lateinit var publicSuffixListBytes: ByteArray private lateinit var publicSuffixExceptionListBytes: ByteArray /** * Returns the effective top-level domain plus one (eTLD+1) by referencing the public suffix list. * Returns null if the domain is a public suffix or a private address. * * Here are some examples: * * ``` * assertEquals("google.com", getEffectiveTldPlusOne("google.com")); * assertEquals("google.com", getEffectiveTldPlusOne("www.google.com")); * assertNull(getEffectiveTldPlusOne("com")); * assertNull(getEffectiveTldPlusOne("localhost")); * assertNull(getEffectiveTldPlusOne("mymacbook")); * ``` * * @param domain A canonicalized domain. An International Domain Name (IDN) should be punycode * encoded. */ fun getEffectiveTldPlusOne(domain: String): String? { // We use UTF-8 in the list so we need to convert to Unicode. val unicodeDomain = IDN.toUnicode(domain) val domainLabels = splitDomain(unicodeDomain) val rule = findMatchingRule(domainLabels) if (domainLabels.size == rule.size && rule[0][0] != EXCEPTION_MARKER) { return null // The domain is a public suffix. } val firstLabelOffset = if (rule[0][0] == EXCEPTION_MARKER) { // Exception rules hold the effective TLD plus one. domainLabels.size - rule.size } else { // Otherwise the rule is for a public suffix, so we must take one more label. domainLabels.size - (rule.size + 1) } return splitDomain(domain).asSequence().drop(firstLabelOffset).joinToString(".") } private fun splitDomain(domain: String): List<String> { val domainLabels = domain.split('.') if (domainLabels.last() == "") { // allow for domain name trailing dot return domainLabels.dropLast(1) } return domainLabels } private fun findMatchingRule(domainLabels: List<String>): List<String> { if (!listRead.get() && listRead.compareAndSet(false, true)) { readTheListUninterruptibly() } else { try { readCompleteLatch.await() } catch (_: InterruptedException) { Thread.currentThread().interrupt() // Retain interrupted status. } } check(::publicSuffixListBytes.isInitialized) { "Unable to load $PUBLIC_SUFFIX_RESOURCE resource from the classpath." } // Break apart the domain into UTF-8 labels, i.e. foo.bar.com turns into [foo, bar, com]. val domainLabelsUtf8Bytes = Array(domainLabels.size) { i -> domainLabels[i].toByteArray(UTF_8) } // Start by looking for exact matches. We start at the leftmost label. For example, foo.bar.com // will look like: [foo, bar, com], [bar, com], [com]. The longest matching rule wins. var exactMatch: String? = null for (i in domainLabelsUtf8Bytes.indices) { val rule = publicSuffixListBytes.binarySearch(domainLabelsUtf8Bytes, i) if (rule != null) { exactMatch = rule break } } // In theory, wildcard rules are not restricted to having the wildcard in the leftmost position. // In practice, wildcards are always in the leftmost position. For now, this implementation // cheats and does not attempt every possible permutation. Instead, it only considers wildcards // in the leftmost position. We assert this fact when we generate the public suffix file. If // this assertion ever fails we'll need to refactor this implementation. var wildcardMatch: String? = null if (domainLabelsUtf8Bytes.size > 1) { val labelsWithWildcard = domainLabelsUtf8Bytes.clone() for (labelIndex in 0 until labelsWithWildcard.size - 1) { labelsWithWildcard[labelIndex] = WILDCARD_LABEL val rule = publicSuffixListBytes.binarySearch(labelsWithWildcard, labelIndex) if (rule != null) { wildcardMatch = rule break } } } // Exception rules only apply to wildcard rules, so only try it if we matched a wildcard. var exception: String? = null if (wildcardMatch != null) { for (labelIndex in 0 until domainLabelsUtf8Bytes.size - 1) { val rule = publicSuffixExceptionListBytes.binarySearch( domainLabelsUtf8Bytes, labelIndex) if (rule != null) { exception = rule break } } } if (exception != null) { // Signal we've identified an exception rule. exception = "!$exception" return exception.split('.') } else if (exactMatch == null && wildcardMatch == null) { return PREVAILING_RULE } val exactRuleLabels = exactMatch?.split('.') ?: listOf() val wildcardRuleLabels = wildcardMatch?.split('.') ?: listOf() return if (exactRuleLabels.size > wildcardRuleLabels.size) { exactRuleLabels } else { wildcardRuleLabels } } /** * Reads the public suffix list treating the operation as uninterruptible. We always want to read * the list otherwise we'll be left in a bad state. If the thread was interrupted prior to this * operation, it will be re-interrupted after the list is read. */ private fun readTheListUninterruptibly() { var interrupted = false try { while (true) { try { readTheList() return } catch (_: InterruptedIOException) { Thread.interrupted() // Temporarily clear the interrupted state. interrupted = true } catch (e: IOException) { Platform.get().log("Failed to read public suffix list", Platform.WARN, e) return } } } finally { if (interrupted) { Thread.currentThread().interrupt() // Retain interrupted status. } } } @Throws(IOException::class) private fun readTheList() { var publicSuffixListBytes: ByteArray? var publicSuffixExceptionListBytes: ByteArray? val resource = PublicSuffixDatabase::class.java.getResourceAsStream(PUBLIC_SUFFIX_RESOURCE) ?: return GzipSource(resource.source()).buffer().use { bufferedSource -> val totalBytes = bufferedSource.readInt() publicSuffixListBytes = bufferedSource.readByteArray(totalBytes.toLong()) val totalExceptionBytes = bufferedSource.readInt() publicSuffixExceptionListBytes = bufferedSource.readByteArray(totalExceptionBytes.toLong()) } synchronized(this) { this.publicSuffixListBytes = publicSuffixListBytes!! this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes!! } readCompleteLatch.countDown() } /** Visible for testing. */ fun setListBytes( publicSuffixListBytes: ByteArray, publicSuffixExceptionListBytes: ByteArray ) { this.publicSuffixListBytes = publicSuffixListBytes this.publicSuffixExceptionListBytes = publicSuffixExceptionListBytes listRead.set(true) readCompleteLatch.countDown() } companion object { const val PUBLIC_SUFFIX_RESOURCE = "publicsuffixes.gz" private val WILDCARD_LABEL = byteArrayOf('*'.toByte()) private val PREVAILING_RULE = listOf("*") private const val EXCEPTION_MARKER = '!' private val instance = PublicSuffixDatabase() fun get(): PublicSuffixDatabase { return instance } private fun ByteArray.binarySearch( labels: Array<ByteArray>, labelIndex: Int ): String? { var low = 0 var high = size var match: String? = null while (low < high) { var mid = (low + high) / 2 // Search for a '\n' that marks the start of a value. Don't go back past the start of the // array. while (mid > -1 && this[mid] != '\n'.toByte()) { mid-- } mid++ // Now look for the ending '\n'. var end = 1 while (this[mid + end] != '\n'.toByte()) { end++ } val publicSuffixLength = mid + end - mid // Compare the bytes. Note that the file stores UTF-8 encoded bytes, so we must compare the // unsigned bytes. var compareResult: Int var currentLabelIndex = labelIndex var currentLabelByteIndex = 0 var publicSuffixByteIndex = 0 var expectDot = false while (true) { val byte0: Int if (expectDot) { byte0 = '.'.toInt() expectDot = false } else { byte0 = labels[currentLabelIndex][currentLabelByteIndex] and 0xff } val byte1 = this[mid + publicSuffixByteIndex] and 0xff compareResult = byte0 - byte1 if (compareResult != 0) break publicSuffixByteIndex++ currentLabelByteIndex++ if (publicSuffixByteIndex == publicSuffixLength) break if (labels[currentLabelIndex].size == currentLabelByteIndex) { // We've exhausted our current label. Either there are more labels to compare, in which // case we expect a dot as the next character. Otherwise, we've checked all our labels. if (currentLabelIndex == labels.size - 1) { break } else { currentLabelIndex++ currentLabelByteIndex = -1 expectDot = true } } } if (compareResult < 0) { high = mid - 1 } else if (compareResult > 0) { low = mid + end + 1 } else { // We found a match, but are the lengths equal? val publicSuffixBytesLeft = publicSuffixLength - publicSuffixByteIndex var labelBytesLeft = labels[currentLabelIndex].size - currentLabelByteIndex for (i in currentLabelIndex + 1 until labels.size) { labelBytesLeft += labels[i].size } if (labelBytesLeft < publicSuffixBytesLeft) { high = mid - 1 } else if (labelBytesLeft > publicSuffixBytesLeft) { low = mid + end + 1 } else { // Found a match. match = String(this, mid, publicSuffixLength, UTF_8) break } } } return match } } }
apache-2.0
4cb6491177b197b22883eaeb916c9b85
33.507331
100
0.652758
4.695531
false
false
false
false
ansman/okhttp
okhttp/src/main/kotlin/okhttp3/internal/ws/WebSocketExtensions.kt
6
8126
/* * Copyright (C) 2020 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package okhttp3.internal.ws import java.io.IOException import okhttp3.Headers import okhttp3.internal.delimiterOffset import okhttp3.internal.trimSubstring /** * Models the contents of a `Sec-WebSocket-Extensions` response header. OkHttp honors one extension * `permessage-deflate` and four parameters, `client_max_window_bits`, `client_no_context_takeover`, * `server_max_window_bits`, and `server_no_context_takeover`. * * Typically this will look like one of the following: * * ``` * Sec-WebSocket-Extensions: permessage-deflate * Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits="15" * Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits=15 * Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover * Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits="15" * Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=15 * Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover * Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; * client_no_context_takeover * Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits="15"; * client_max_window_bits="15"; server_no_context_takeover; client_no_context_takeover * ``` * * If any other extension or parameter is specified, then [unknownValues] will be true. Such * responses should be refused as their web socket extensions will not be understood. * * Note that [java.util.zip.Deflater] is hardcoded to use 15 bits (32 KiB) for * `client_max_window_bits` and [java.util.zip.Inflater] is hardcoded to use 15 bits (32 KiB) for * `server_max_window_bits`. This harms our ability to support these parameters: * * * If `client_max_window_bits` is less than 15, OkHttp must close the web socket with code 1010. * Otherwise it would compress values in a way that servers could not decompress. * * If `server_max_window_bits` is less than 15, OkHttp will waste memory on an oversized buffer. * * See [RFC 7692, 7.1][rfc_7692] for details on negotiation process. * * [rfc_7692]: https://tools.ietf.org/html/rfc7692#section-7.1 */ data class WebSocketExtensions( /** True if the agreed upon extensions includes the permessage-deflate extension. */ @JvmField val perMessageDeflate: Boolean = false, /** Should be a value in [8..15]. Only 15 is acceptable by OkHttp as Java APIs are limited. */ @JvmField val clientMaxWindowBits: Int? = null, /** True if the agreed upon extension parameters includes "client_no_context_takeover". */ @JvmField val clientNoContextTakeover: Boolean = false, /** Should be a value in [8..15]. Any value in that range is acceptable by OkHttp. */ @JvmField val serverMaxWindowBits: Int? = null, /** True if the agreed upon extension parameters includes "server_no_context_takeover". */ @JvmField val serverNoContextTakeover: Boolean = false, /** * True if the agreed upon extensions or parameters contained values unrecognized by OkHttp. * Typically this indicates that the client will need to close the web socket with code 1010. */ @JvmField val unknownValues: Boolean = false ) { fun noContextTakeover(clientOriginated: Boolean): Boolean { return if (clientOriginated) { clientNoContextTakeover // Client is deflating. } else { serverNoContextTakeover // Server is deflating. } } companion object { private const val HEADER_WEB_SOCKET_EXTENSION = "Sec-WebSocket-Extensions" @Throws(IOException::class) fun parse(responseHeaders: Headers): WebSocketExtensions { // Note that this code does case-insensitive comparisons, even though the spec doesn't specify // whether extension tokens and parameters are case-insensitive or not. var compressionEnabled = false var clientMaxWindowBits: Int? = null var clientNoContextTakeover = false var serverMaxWindowBits: Int? = null var serverNoContextTakeover = false var unexpectedValues = false // Parse each header. for (i in 0 until responseHeaders.size) { if (!responseHeaders.name(i).equals(HEADER_WEB_SOCKET_EXTENSION, ignoreCase = true)) { continue // Not a header we're interested in. } val header = responseHeaders.value(i) // Parse each extension. var pos = 0 while (pos < header.length) { val extensionEnd = header.delimiterOffset(',', pos) val extensionTokenEnd = header.delimiterOffset(';', pos, extensionEnd) val extensionToken = header.trimSubstring(pos, extensionTokenEnd) pos = extensionTokenEnd + 1 when { extensionToken.equals("permessage-deflate", ignoreCase = true) -> { if (compressionEnabled) unexpectedValues = true // Repeated extension! compressionEnabled = true // Parse each permessage-deflate parameter. while (pos < extensionEnd) { val parameterEnd = header.delimiterOffset(';', pos, extensionEnd) val equals = header.delimiterOffset('=', pos, parameterEnd) val name = header.trimSubstring(pos, equals) val value = if (equals < parameterEnd) { header.trimSubstring(equals + 1, parameterEnd).removeSurrounding("\"") } else { null } pos = parameterEnd + 1 when { name.equals("client_max_window_bits", ignoreCase = true) -> { if (clientMaxWindowBits != null) unexpectedValues = true // Repeated parameter! clientMaxWindowBits = value?.toIntOrNull() if (clientMaxWindowBits == null) unexpectedValues = true // Not an int! } name.equals("client_no_context_takeover", ignoreCase = true) -> { if (clientNoContextTakeover) unexpectedValues = true // Repeated parameter! if (value != null) unexpectedValues = true // Unexpected value! clientNoContextTakeover = true } name.equals("server_max_window_bits", ignoreCase = true) -> { if (serverMaxWindowBits != null) unexpectedValues = true // Repeated parameter! serverMaxWindowBits = value?.toIntOrNull() if (serverMaxWindowBits == null) unexpectedValues = true // Not an int! } name.equals("server_no_context_takeover", ignoreCase = true) -> { if (serverNoContextTakeover) unexpectedValues = true // Repeated parameter! if (value != null) unexpectedValues = true // Unexpected value! serverNoContextTakeover = true } else -> { unexpectedValues = true // Unexpected parameter. } } } } else -> { unexpectedValues = true // Unexpected extension. } } } } return WebSocketExtensions( perMessageDeflate = compressionEnabled, clientMaxWindowBits = clientMaxWindowBits, clientNoContextTakeover = clientNoContextTakeover, serverMaxWindowBits = serverMaxWindowBits, serverNoContextTakeover = serverNoContextTakeover, unknownValues = unexpectedValues ) } } }
apache-2.0
94c6b95b444ff909bf0a5e8ae168d17b
43.895028
100
0.657273
4.472207
false
false
false
false
songzhw/AndroidArchitecture
deprecated/Tools/DaggerPlayground/app/src/main/java/six/ca/dagger101/thirty2_test/mockito/MockitoKotinErrorDemo.kt
1
347
package six.ca.dagger101.thirty2_test.mockito import six.ca.dagger101.Mockable open class One { open fun foo() {} open fun second() {} } class Two(val one: One) { fun bar() { one.foo() } } // = = = = = = = = = = = = = = = = @Mockable class One2{ fun foo() {} fun second() {} } class Two2(val one: One2) { fun bar() { one.foo() } }
apache-2.0
7197baeb16ad471ad4ad8a22e0bca15b
11.888889
45
0.559078
2.344595
false
false
false
false
rsiebert/TVHClient
app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/recordings/RecordingListFragment.kt
1
12590
package org.tvheadend.tvhclient.ui.features.dvr.recordings import android.os.Bundle import android.view.* import android.widget.Filter import androidx.appcompat.widget.PopupMenu import androidx.fragment.app.FragmentTransaction import androidx.lifecycle.Lifecycle import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import org.tvheadend.data.entity.Recording import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.RecyclerviewFragmentBinding import org.tvheadend.tvhclient.ui.base.BaseFragment import org.tvheadend.tvhclient.ui.common.* import org.tvheadend.tvhclient.ui.common.interfaces.RecyclerViewClickInterface import org.tvheadend.tvhclient.ui.common.interfaces.SearchRequestInterface import org.tvheadend.tvhclient.ui.features.dvr.recordings.download.DownloadPermissionGrantedInterface import org.tvheadend.tvhclient.util.extensions.gone import org.tvheadend.tvhclient.util.extensions.visible import org.tvheadend.tvhclient.util.extensions.visibleOrGone import timber.log.Timber import java.util.concurrent.CopyOnWriteArrayList abstract class RecordingListFragment : BaseFragment(), RecyclerViewClickInterface, SearchRequestInterface, DownloadPermissionGrantedInterface, Filter.FilterListener { private lateinit var binding: RecyclerviewFragmentBinding lateinit var recordingViewModel: RecordingViewModel lateinit var recyclerViewAdapter: RecordingRecyclerViewAdapter override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = RecyclerviewFragmentBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recordingViewModel = ViewModelProvider(requireActivity())[RecordingViewModel::class.java] arguments?.let { recordingViewModel.selectedListPosition = it.getInt("listPosition") } recyclerViewAdapter = RecordingRecyclerViewAdapter(recordingViewModel, isDualPane, this, htspVersion) binding.recyclerView.layoutManager = LinearLayoutManager(activity) binding.recyclerView.adapter = recyclerViewAdapter binding.recyclerView.gone() binding.searchProgress.visibleOrGone(baseViewModel.isSearchActive) } private fun observeSearchQuery() { Timber.d("Observing search query") baseViewModel.searchQueryLiveData.observe(viewLifecycleOwner, { query -> if (query.isNotEmpty()) { Timber.d("View model returned search query '$query'") onSearchRequested(query) } else { Timber.d("View model returned empty search query") onSearchResultsCleared() } }) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val ctx = context ?: return super.onOptionsItemSelected(item) return when (item.itemId) { R.id.menu_add_recording -> return addNewRecording(requireActivity()) R.id.menu_remove_all_recordings -> showConfirmationToRemoveAllRecordings(ctx, CopyOnWriteArrayList(recyclerViewAdapter.items)) R.id.menu_genre_color_information -> showGenreColorDialog(ctx) else -> super.onOptionsItemSelected(item) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.recording_list_options_menu, menu) } override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) if (sharedPreferences.getBoolean("delete_all_recordings_menu_enabled", resources.getBoolean(R.bool.pref_default_delete_all_recordings_menu_enabled)) && recyclerViewAdapter.itemCount > 1 && isConnectionToServerAvailable) { menu.findItem(R.id.menu_remove_all_recordings)?.isVisible = true } // Hide the casting icon as a default. menu.findItem(R.id.media_route_menu_item)?.isVisible = false // Hide the sorting menu by default, only the completed recordings can be sorted menu.findItem(R.id.menu_recording_sort_order)?.isVisible = false // Do not show the search menu when no recordings are available menu.findItem(R.id.menu_search)?.isVisible = recyclerViewAdapter.itemCount > 0 val showGenreColors = sharedPreferences.getBoolean("genre_colors_for_recordings_enabled", resources.getBoolean(R.bool.pref_default_genre_colors_for_recordings_enabled)) if (!baseViewModel.isSearchActive) { menu.findItem(R.id.menu_genre_color_information)?.isVisible = showGenreColors } } private fun showRecordingDetails(position: Int) { recordingViewModel.selectedListPosition = position recyclerViewAdapter.setPosition(position) val recording = recyclerViewAdapter.getItem(position) if (recording == null || !isVisible) { return } val fm = activity?.supportFragmentManager if (!isDualPane) { val fragment = RecordingDetailsFragment.newInstance(recording.id) fm?.beginTransaction()?.also { it.replace(R.id.main, fragment) it.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) it.addToBackStack(null) it.commit() } } else { var fragment = activity?.supportFragmentManager?.findFragmentById(R.id.details) if (fragment !is RecordingDetailsFragment) { fragment = RecordingDetailsFragment.newInstance(recording.id) // Check the lifecycle state to avoid committing the transaction // after the onSaveInstance method was already called which would // trigger an illegal state exception. if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) { fm?.beginTransaction()?.also { it.replace(R.id.details, fragment) it.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) it.commit() } } } else if (recordingViewModel.currentIdLiveData.value != recording.id) { recordingViewModel.currentIdLiveData.value = recording.id } } } private fun showPopupMenu(view: View, position: Int) { val ctx = context ?: return val recording = recyclerViewAdapter.getItem(position) ?: return val popupMenu = PopupMenu(ctx, view) popupMenu.menuInflater.inflate(R.menu.recordings_popup_menu, popupMenu.menu) popupMenu.menuInflater.inflate(R.menu.external_search_options_menu, popupMenu.menu) preparePopupOrToolbarMiscMenu(ctx, popupMenu.menu, null, isConnectionToServerAvailable, isUnlocked) preparePopupOrToolbarRecordingMenu(ctx, popupMenu.menu, recording, isConnectionToServerAvailable, htspVersion, isUnlocked) preparePopupOrToolbarSearchMenu(popupMenu.menu, recording.title, isConnectionToServerAvailable) popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.menu_stop_recording -> return@setOnMenuItemClickListener showConfirmationToStopSelectedRecording(ctx, recording, null) R.id.menu_cancel_recording -> return@setOnMenuItemClickListener showConfirmationToCancelSelectedRecording(ctx, recording, null) R.id.menu_remove_recording -> return@setOnMenuItemClickListener showConfirmationToRemoveSelectedRecording(ctx, recording, null) R.id.menu_edit_recording -> return@setOnMenuItemClickListener editSelectedRecording(requireActivity(), recording.id) R.id.menu_share_recording -> return@setOnMenuItemClickListener shareSelectedRecording(ctx, recording.id, isUnlocked) R.id.menu_play -> return@setOnMenuItemClickListener playSelectedRecording(ctx, recording.id, isUnlocked) R.id.menu_cast -> return@setOnMenuItemClickListener castSelectedRecording(ctx, recording.id) R.id.menu_search_imdb -> return@setOnMenuItemClickListener searchTitleOnImdbWebsite(ctx, recording.title) R.id.menu_search_fileaffinity -> return@setOnMenuItemClickListener searchTitleOnFileAffinityWebsite(ctx, recording.title) R.id.menu_search_youtube -> return@setOnMenuItemClickListener searchTitleOnYoutube(ctx, recording.title) R.id.menu_search_google -> return@setOnMenuItemClickListener searchTitleOnGoogle(ctx, recording.title) R.id.menu_search_epg -> return@setOnMenuItemClickListener searchTitleInTheLocalDatabase(requireActivity(), baseViewModel, recording.title) R.id.menu_disable_recording -> return@setOnMenuItemClickListener enableScheduledRecording(recording, false) R.id.menu_enable_recording -> return@setOnMenuItemClickListener enableScheduledRecording(recording, true) R.id.menu_download_recording -> return@setOnMenuItemClickListener downloadSelectedRecording(ctx, recording.id) else -> return@setOnMenuItemClickListener false } } popupMenu.show() } override fun onClick(view: View, position: Int) { recordingViewModel.selectedListPosition = position if (view.id == R.id.icon || view.id == R.id.icon_text) { recyclerViewAdapter.getItem(position)?.let { playOrCastRecording(view.context, it.id, isUnlocked) } } else { showRecordingDetails(position) } } override fun onLongClick(view: View, position: Int): Boolean { showPopupMenu(view, position) return true } fun addRecordingsAndUpdateUI(recordings: List<Recording>?) { // Prevent updating the recording list and any calls to the filter in the adapter. // Without this the active search view would be closed before the user has a chance // to enter a complete search term or submit the query. if (baseViewModel.searchViewHasFocus || baseViewModel.isSearchActive) { Timber.d("Skipping updating UI, search view has focus or search results are already being shown") return } if (recordings != null) { recyclerViewAdapter.addItems(recordings) observeSearchQuery() } binding.recyclerView.visible() showStatusInToolbar() activity?.invalidateOptionsMenu() if (isDualPane && recyclerViewAdapter.itemCount > 0) { showRecordingDetails(recordingViewModel.selectedListPosition) } } abstract fun showStatusInToolbar() override fun downloadRecording() { //DownloadRecordingManager(activity, connection, recyclerViewAdapter.getItem(recordingViewModel.selectedListPosition)) val id = recyclerViewAdapter.getItem(recordingViewModel.selectedListPosition)?.id if (id != null) { downloadSelectedRecording(requireContext(), id) } } override fun onFilterComplete(i: Int) { binding.searchProgress.gone() showStatusInToolbar() if (isDualPane) { when { recyclerViewAdapter.itemCount > recordingViewModel.selectedListPosition -> { showRecordingDetails(recordingViewModel.selectedListPosition) } recyclerViewAdapter.itemCount <= recordingViewModel.selectedListPosition -> { showRecordingDetails(0) } recyclerViewAdapter.itemCount == 0 -> { removeDetailsFragment() } } } } override fun onSearchRequested(query: String) { recyclerViewAdapter.filter.filter(query, this) } override fun onSearchResultsCleared() { recyclerViewAdapter.filter.filter("", this) } abstract override fun getQueryHint(): String private fun enableScheduledRecording(recording: Recording, enabled: Boolean): Boolean { val intent = recordingViewModel.getIntentData(requireContext(), recording) intent.action = "updateDvrEntry" intent.putExtra("id", recording.id) intent.putExtra("enabled", if (enabled) 1 else 0) activity?.startService(intent) return true } }
gpl-3.0
43044081369d10f0551c898fe675f142
47.053435
176
0.692295
5.250209
false
false
false
false
hypercube1024/firefly
firefly-net/src/main/kotlin/com/fireflysource/net/http/client/impl/AbstractHttpClientRequestBuilder.kt
1
6317
package com.fireflysource.net.http.client.impl import com.fireflysource.net.http.client.* import com.fireflysource.net.http.client.impl.content.provider.ByteBufferContentProvider import com.fireflysource.net.http.client.impl.content.provider.MultiPartContentProvider import com.fireflysource.net.http.client.impl.content.provider.StringContentProvider import com.fireflysource.net.http.common.model.* import java.nio.ByteBuffer import java.nio.charset.Charset import java.nio.charset.StandardCharsets import java.util.function.BiConsumer import java.util.function.Supplier @Suppress("ReplacePutWithAssignment") abstract class AbstractHttpClientRequestBuilder( method: String, uri: HttpURI, httpVersion: HttpVersion ) : HttpClientRequestBuilder { private val multiPartContentProvider: MultiPartContentProvider by lazy { MultiPartContentProvider() } val httpRequest: AsyncHttpClientRequest = AsyncHttpClientRequest() init { httpRequest.method = method httpRequest.uri = uri httpRequest.httpVersion = httpVersion } override fun cookies(cookies: MutableList<Cookie>?): HttpClientRequestBuilder { httpRequest.cookies = cookies return this } override fun put(name: String, list: MutableList<String>): HttpClientRequestBuilder { httpRequest.httpFields.put(name, list) return this } override fun put(header: HttpHeader, value: String): HttpClientRequestBuilder { httpRequest.httpFields.put(header, value) return this } override fun put(name: String, value: String): HttpClientRequestBuilder { httpRequest.httpFields.put(name, value) return this } override fun put(field: HttpField): HttpClientRequestBuilder { httpRequest.httpFields.put(field) return this } override fun addAll(fields: HttpFields): HttpClientRequestBuilder { httpRequest.httpFields.addAll(fields) return this } override fun add(field: HttpField): HttpClientRequestBuilder { httpRequest.httpFields.add(field) return this } override fun addCsv(header: HttpHeader, vararg values: String): HttpClientRequestBuilder { httpRequest.httpFields.addCSV(header, *values) return this } override fun addCsv(header: String, vararg values: String): HttpClientRequestBuilder { httpRequest.httpFields.addCSV(header, *values) return this } override fun trailerSupplier(trailerSupplier: Supplier<HttpFields>?): HttpClientRequestBuilder { httpRequest.trailerSupplier = trailerSupplier return this } override fun body(content: String): HttpClientRequestBuilder = body(content, StandardCharsets.UTF_8) override fun body(content: String, charset: Charset): HttpClientRequestBuilder = contentProvider(StringContentProvider(content, charset)) override fun body(buffer: ByteBuffer): HttpClientRequestBuilder = contentProvider(ByteBufferContentProvider(buffer)) override fun contentProvider(contentProvider: HttpClientContentProvider?): HttpClientRequestBuilder { httpRequest.contentProvider = contentProvider return this } override fun addPart( name: String, content: HttpClientContentProvider, fields: HttpFields? ): HttpClientRequestBuilder { contentProvider(multiPartContentProvider) multiPartContentProvider.addPart(name, content, fields) return this } override fun addFilePart( name: String, fileName: String, content: HttpClientContentProvider, fields: HttpFields? ): HttpClientRequestBuilder { contentProvider(multiPartContentProvider) multiPartContentProvider.addFilePart(name, fileName, content, fields) return this } override fun addFormInput(name: String, value: String): HttpClientRequestBuilder { httpRequest.formInputs.add(name, value) return this } override fun addFormInputs(name: String, values: MutableList<String>): HttpClientRequestBuilder { httpRequest.formInputs.addValues(name, values) return this } override fun putFormInput(name: String, value: String): HttpClientRequestBuilder { httpRequest.formInputs.put(name, value) return this } override fun putFormInputs(name: String, values: MutableList<String>): HttpClientRequestBuilder { httpRequest.formInputs.putValues(name, values) return this } override fun removeFormInput(name: String): HttpClientRequestBuilder { httpRequest.formInputs.remove(name) return this } override fun addQueryString(name: String, value: String): HttpClientRequestBuilder { httpRequest.queryStrings.add(name, value) return this } override fun addQueryStrings(name: String, values: MutableList<String>): HttpClientRequestBuilder { httpRequest.queryStrings.addValues(name, values) return this } override fun putQueryString(name: String, value: String): HttpClientRequestBuilder { httpRequest.queryStrings.put(name, value) return this } override fun putQueryStrings(name: String, values: MutableList<String>): HttpClientRequestBuilder { httpRequest.queryStrings[name] = values return this } override fun removeQueryString(name: String): HttpClientRequestBuilder { httpRequest.queryStrings.remove(name) return this } override fun contentHandler(contentHandler: HttpClientContentHandler?): HttpClientRequestBuilder { httpRequest.contentHandler = contentHandler return this } override fun http2Settings(http2Settings: Map<Int, Int>?): HttpClientRequestBuilder { httpRequest.http2Settings = http2Settings return this } override fun upgradeHttp2(): HttpClientRequestBuilder { HttpProtocolNegotiator.addHttp2UpgradeHeader(httpRequest) return this } override fun onHeaderComplete(headerComplete: BiConsumer<HttpClientRequest, HttpClientResponse>): HttpClientRequestBuilder { httpRequest.headerComplete = headerComplete return this } override fun getHttpClientRequest(): HttpClientRequest = httpRequest }
apache-2.0
6d5ad27484fef339d360471ec15bff9b
33.151351
128
0.724236
5.194901
false
false
false
false
chimbori/crux
src/main/kotlin/com/chimbori/crux/extractors/MetadataHelpers.kt
1
5542
package com.chimbori.crux.extractors import com.chimbori.crux.common.cleanTitle import com.chimbori.crux.common.nullIfBlank import com.chimbori.crux.common.removeWhiteSpace import java.util.Locale import okhttp3.HttpUrl import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import org.jsoup.nodes.Document import org.jsoup.nodes.Element public fun Document.extractTitle(): String? = ( title().nullIfBlank() ?: select("title").text().nullIfBlank() ?: select("meta[name=title]").attr("content").nullIfBlank() ?: select("meta[property=og:title]").attr("content").nullIfBlank() ?: select("meta[name=twitter:title]").attr("content").nullIfBlank() )?.cleanTitle()?.nullIfBlank() public fun Document.extractCanonicalUrl(): String? = ( select("link[rel=canonical]").attr("abs:href").nullIfBlank() ?: select("meta[property=og:url]").attr("content").nullIfBlank() ?: select("meta[name=twitter:url]").attr("content").nullIfBlank() )?.removeWhiteSpace()?.nullIfBlank() public fun Document.extractPaginationUrl(baseUrl: HttpUrl?, nextOrPrev: String): HttpUrl? = ( select("link[rel=$nextOrPrev]").attr("abs:href").nullIfBlank() )?.removeWhiteSpace()?.nullIfBlank() ?.let { relativeUrl -> baseUrl?.resolve(relativeUrl) ?: relativeUrl.toHttpUrlOrNull() } public fun Document.extractDescription(): String? = ( select("meta[name=description]").attr("content").nullIfBlank() ?: select("meta[property=og:description]").attr("content").nullIfBlank() ?: select("meta[name=twitter:description]").attr("content").nullIfBlank() )?.removeWhiteSpace()?.nullIfBlank() public fun Document.extractSiteName(): String? = ( select("meta[property=og:site_name]").attr("content").nullIfBlank() ?: select("meta[name=application-name]").attr("content").nullIfBlank() )?.removeWhiteSpace()?.nullIfBlank() public fun Document.extractThemeColor(): String? = select("meta[name=theme-color]").attr("content").nullIfBlank() public fun Document.extractPublishedAt(): String? = ( select("meta[itemprop=dateCreated]").attr("content").nullIfBlank() ?: select("meta[property=article:published_time]").attr("content").nullIfBlank() )?.removeWhiteSpace()?.nullIfBlank() public fun Document.extractModifiedAt(): String? = ( select("meta[itemprop=dateModified]").attr("content").nullIfBlank() ?: select("meta[property=article:modified_time]").attr("content").nullIfBlank() )?.removeWhiteSpace()?.nullIfBlank() public fun Document.extractKeywords(): List<String> = select("meta[name=keywords]").attr("content") .removeWhiteSpace() .removePrefix("[") .removeSuffix("]") .split("\\s*,\\s*".toRegex()) .filter { it.isNotBlank() } public fun Document.extractFaviconUrl(baseUrl: HttpUrl?): HttpUrl? { val allPossibleIconElements = listOf( select("link[rel~=apple-touch-icon]"), select("link[rel~=apple-touch-icon-precomposed]"), select("link[rel~=icon]"), select("link[rel~=ICON]"), ) return findLargestIcon(allPossibleIconElements.flatten()) ?.let { baseUrl?.resolve(it) ?: it.toHttpUrlOrNull() } ?: baseUrl?.newBuilder()?.encodedPath("/favicon.ico")?.build() } public fun Document.extractImageUrl(baseUrl: HttpUrl?): HttpUrl? = ( // Twitter Cards and Open Graph images are usually higher quality, so rank them first. select("meta[name=twitter:image]").attr("content").nullIfBlank() ?: select("meta[property=og:image]").attr("content").nullIfBlank() // image_src or thumbnails are usually low quality, so prioritize them *after* article images. ?: select("link[rel=image_src]").attr("href").nullIfBlank() ?: select("meta[name=thumbnail]").attr("content").nullIfBlank() )?.let { baseUrl?.resolve(it) ?: it.toHttpUrlOrNull() } public fun Document.extractFeedUrl(baseUrl: HttpUrl?): HttpUrl? = ( select("link[rel=alternate]").select("link[type=application/rss+xml]").attr("href").nullIfBlank() ?: select("link[rel=alternate]").select("link[type=application/atom+xml]").attr("href").nullIfBlank() )?.let { baseUrl?.resolve(it) ?: it.toHttpUrlOrNull() } public fun Document.extractAmpUrl(baseUrl: HttpUrl?): HttpUrl? = select("link[rel=amphtml]").attr("href").nullIfBlank() ?.let { baseUrl?.resolve(it) ?: it.toHttpUrlOrNull() } public fun Document.extractVideoUrl(baseUrl: HttpUrl?): HttpUrl? = select("meta[property=og:video]").attr("content").nullIfBlank() ?.let { baseUrl?.resolve(it) ?: it.toHttpUrlOrNull() } internal fun findLargestIcon(iconElements: List<Element>): String? = iconElements.maxByOrNull { parseSize(it.attr("sizes")) }?.attr("abs:href")?.nullIfBlank() /** * Given a size represented by "WidthxHeight" or "WidthxHeight ...", will return the largest dimension found. * * Examples: "128x128" will return 128. * "128x64" will return 64. * "24x24 48x48" will return 48. * * @param sizes String representing the sizes. * @return largest dimension, or 0 if input could not be parsed. */ internal fun parseSize(sizeString: String?): Int { if (sizeString.isNullOrBlank()) return 0 val sizes = sizeString.trim(' ').lowercase(Locale.getDefault()) return when { // For multiple sizes in the same String, split and parse recursively. sizes.contains(" ") -> sizes.split(" ").maxOfOrNull { parseSize(it) } ?: 0 // For handling sizes of format 128x128 etc. sizes.contains("x") -> try { sizes.split("x").maxOf { it.trim().toInt() } } catch (e: NumberFormatException) { 0 } else -> 0 } }
apache-2.0
59e0139dd0b442a6d1f04248fb86d984
43.336
109
0.691267
4.024691
false
false
false
false
langara/MyIntent
myutils/src/main/java/pl/mareklangiewicz/myutils/MyMathUtils.kt
1
3754
package pl.mareklangiewicz.myutils import android.graphics.Color import android.graphics.Point import android.graphics.PointF import android.graphics.Rect import android.graphics.RectF import androidx.annotation.ColorInt import pl.mareklangiewicz.upue.Pullee import java.util.Random /** * Created by Marek Langiewicz on 15.07.15. */ fun Int.scale0d(oldMax: Int, newMax: Int) = (toLong() * newMax.toLong() / oldMax.toLong()).toInt() fun Float.scale0d(oldMax: Float, newMax: Float) = this * newMax / oldMax fun Double.scale0d(oldMax: Double, newMax: Double) = this * newMax / oldMax fun Int.scale1d(oldMin: Int, oldMax: Int, newMin: Int, newMax: Int) = (this - oldMin).scale0d(oldMax - oldMin, newMax - newMin) + newMin fun Float.scale1d(oldMin: Float, oldMax: Float, newMin: Float, newMax: Float) = (this - oldMin).scale0d(oldMax - oldMin, newMax - newMin) + newMin fun Double.scale1d(oldMin: Double, oldMax: Double, newMin: Double, newMax: Double) = (this - oldMin).scale0d(oldMax - oldMin, newMax - newMin) + newMin fun Point.scale2d(oldMin: Point, oldMax: Point, newMin: Point, newMax: Point) = Point( x.scale1d(oldMin.x, oldMax.x, newMin.x, newMax.x), y.scale1d(oldMin.y, oldMax.y, newMin.y, newMax.y)) fun Point.scale2d(oldRange: Rect, newRange: Rect) = scale2d( Point(oldRange.left, oldRange.top), Point(oldRange.right, oldRange.bottom), Point(newRange.left, newRange.top), Point(newRange.right, newRange.bottom)) fun PointF.scale2d(oldMin: PointF, oldMax: PointF, newMin: PointF, newMax: PointF) = PointF( x.scale1d(oldMin.x, oldMax.x, newMin.x, newMax.x), y.scale1d(oldMin.y, oldMax.y, newMin.y, newMax.y)) fun PointF.scale2d(oldRange: RectF, newRange: RectF) = scale2d( PointF(oldRange.left, oldRange.top), PointF(oldRange.right, oldRange.bottom), PointF(newRange.left, newRange.top), PointF(newRange.right, newRange.bottom)) val RANDOM = Random() // result should be in the half-open range: [min, max) fun Random.nextInt(min: Int, max: Int) = nextInt(Int.MAX_VALUE).scale1d(0, Int.MAX_VALUE, min, max) // result should be in the half-open range: [min, max) fun Random.nextFloat(min: Float, max: Float) = nextFloat().scale1d(0f, 1f, min, max) // result should be in the half-open range: [min, max) fun Random.nextDouble(min: Double, max: Double) = nextDouble().scale1d(0.0, 1.0, min, max) // result should be in the half-open range: [min, max) fun Random.nextPoint(min: Point, max: Point) = Point(nextInt(min.x, max.x), nextInt(min.y, max.y)) // result should be in the half-open range: [min, max) fun Random.nextPointF(min: PointF, max: PointF) = PointF(nextFloat(min.x, max.x), nextFloat(min.y, max.y)) // result should be in the half-open range: [min, max) @ColorInt fun Random.nextColor(@ColorInt colormin: Int, @ColorInt colormax: Int): Int = Color.argb( nextInt(Color.alpha(colormin), Color.alpha(colormax)), nextInt(Color.red(colormin), Color.red(colormax)), nextInt(Color.green(colormin), Color.green(colormax)), nextInt(Color.blue(colormin), Color.blue(colormax))) // common random pullees: fun Random.asInts(min: Int, max: Int): Pullee<Int> = Pullee { nextInt(min, max) } fun Random.asFloats(min: Float, max: Float): Pullee<Float> = Pullee { nextFloat(min, max) } fun Random.asDoubles(min: Double, max: Double): Pullee<Double> = Pullee { nextDouble(min, max) } fun Random.asPoints(min: Point, max: Point): Pullee<Point> = Pullee { nextPoint(min, max) } fun Random.asPointFs(min: PointF, max: PointF): Pullee<PointF> = Pullee { nextPointF(min, max) } fun Random.asColors(@ColorInt min: Int, @ColorInt max: Int): Pullee<Int> = Pullee { nextColor(min, max) }
apache-2.0
25d67ee8a5760a2d0ac8c75f07df3109
39.365591
136
0.700053
2.944314
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mcp/gradle/McpProjectResolverExtension.kt
1
3001
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.gradle import com.demonwav.mcdev.platform.mcp.gradle.datahandler.McpModelFG2Handler import com.demonwav.mcdev.platform.mcp.gradle.datahandler.McpModelFG3Handler import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG2 import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG3 import com.demonwav.mcdev.util.runGradleTask import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import java.nio.file.Paths import org.gradle.tooling.model.idea.IdeaModule import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension class McpProjectResolverExtension : AbstractProjectResolverExtension() { // Register our custom Gradle tooling API model in IntelliJ's project resolver override fun getExtraProjectModelClasses(): Set<Class<out Any>> = setOf(McpModelFG2::class.java, McpModelFG3::class.java) override fun getToolingExtensionsClasses() = extraProjectModelClasses override fun resolveFinished(projectDataNode: DataNode<ProjectData>) { // FG3 requires us to run a task for each module // We do it here so that we can do this one time for all modules // We do need to have a project here though val project = resolverCtx.externalSystemTaskId.findProject() ?: return val allTaskNames = findAllTaskNames(projectDataNode) if (allTaskNames.isEmpty()) { // Seems to not be FG3 return } val projectDirPath = Paths.get(projectDataNode.data.linkedExternalProjectPath) runGradleTask(project, projectDirPath) { settings -> settings.taskNames = allTaskNames } super.resolveFinished(projectDataNode) } private fun findAllTaskNames(node: DataNode<*>): List<String> { fun findAllTaskNames(node: DataNode<*>, taskNames: MutableList<String>) { val data = node.data if (data is McpModelData) { data.taskName?.let { taskName -> taskNames += taskName } } for (child in node.children) { findAllTaskNames(child, taskNames) } } val res = arrayListOf<String>() findAllTaskNames(node, res) return res } override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) { for (handler in handlers) { handler.build(gradleModule, ideModule, resolverCtx) } // Process the other resolver extensions super.populateModuleExtraModels(gradleModule, ideModule) } companion object { private val handlers = listOf(McpModelFG2Handler, McpModelFG3Handler) } }
mit
9b2a78a7109403d3dd0a818639cc8a58
34.72619
103
0.6991
4.755943
false
false
false
false
xu6148152/binea_project_for_android
SearchFilter/app/src/main/java/com/zepp/www/searchfilter/widget/CollapseView.kt
1
2874
package com.zepp.www.searchfilter.widget import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import com.zepp.www.searchfilter.R import kotlinx.android.synthetic.main.view_collapse.view.* // Created by xubinggui on 02/11/2016. // _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖镇楼 BUG辟易 class CollapseView : FrameLayout { constructor(context: Context?) : this(context, null) constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { LayoutInflater.from(context).inflate(R.layout.view_collapse, this, true) } internal fun setText(text: String) { buttonOk.text = text } internal fun setHasText(hasText: Boolean) { buttonOk.visibility = if(hasText) View.VISIBLE else GONE } internal fun rotateArrow(rotation: Float): Unit { imageArrow.rotation = rotation } internal fun turnIntoOkButton(ratio: Float) { if(buttonOk.visibility != View.VISIBLE) return scale(getDecreasingScale(ratio), getIncreasingScale(ratio)) } private fun scale(okScale: Float, arrowScale: Float) { buttonOk.scaleX = okScale buttonOk.scaleY = okScale imageArrow.scaleX = arrowScale imageArrow.scaleY = arrowScale } private fun getIncreasingScale(ratio: Float): Float = if (ratio < 0.5f) 0f else 2 * ratio - 1 private fun getDecreasingScale(ratio: Float): Float = if (ratio > 0.5f) 0f else 1 - 2 * ratio override fun setOnClickListener(l: OnClickListener?) { buttonOk.setOnClickListener(l) imageArrow.setOnClickListener(l) } internal fun turnIntoArrow(ratio: Float) { if (buttonOk.visibility != View.VISIBLE) return scale(getDecreasingScale(ratio), getIncreasingScale(ratio)) } }
mit
da221785908b92dd7f1d24184ebf7966
35.240506
115
0.484277
3.851952
false
false
false
false
material-components/material-components-android-examples
Reply/app/src/main/java/com/materialstudies/reply/ui/MenuBottomSheetDialogFragment.kt
1
2489
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.materialstudies.reply.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.MenuRes import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.google.android.material.navigation.NavigationView import com.materialstudies.reply.R /** * A bottom sheet dialog for displaying a simple list of action items. */ class MenuBottomSheetDialogFragment : BottomSheetDialogFragment() { private lateinit var navigationView: NavigationView @MenuRes private var menuResId: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) menuResId = arguments?.getInt(KEY_MENU_RES_ID, 0) ?: 0 } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate( R.layout.menu_bottom_sheet_dialog_layout, container, false ) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) navigationView = view.findViewById(R.id.navigation_view) navigationView.inflateMenu(menuResId) navigationView.setNavigationItemSelectedListener { dismiss() true } } companion object { private const val KEY_MENU_RES_ID = "MenuBottomSheetDialogFragment_menuResId" fun newInstance(@MenuRes menuResId: Int): MenuBottomSheetDialogFragment { val fragment = MenuBottomSheetDialogFragment() val bundle = Bundle().apply { putInt(KEY_MENU_RES_ID, menuResId) } fragment.arguments = bundle return fragment } } }
apache-2.0
a12c1fa5428ac1d3f07ebbb1b41d4368
31.324675
85
0.68863
4.938492
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/filter/ColorMatrixFilter.kt
1
3290
package com.soywiz.korge.view.filter import com.soywiz.korag.shader.* import com.soywiz.korge.debug.* import com.soywiz.korge.view.* import com.soywiz.korma.geom.* import com.soywiz.korui.* /** * A [Filter] applying a complex color transformation to the view. * * [colorMatrix] is a 4x4 Matrix used to multiply each color as floating points by this matrix. * [blendRatio] is the ratio that will be used to interpolate the original color with the transformed color. * * ColorMatrixFilter provides a few pre-baked matrices: * - [ColorMatrixFilter.GRAYSCALE_MATRIX] - Used to make the colors grey * - [ColorMatrixFilter.IDENTITY_MATRIX] - Doesn't modify the colors at all */ class ColorMatrixFilter(colorMatrix: Matrix3D, blendRatio: Double = 1.0) : ShaderFilter() { companion object { private val u_ColorMatrix = Uniform("colorMatrix", VarType.Mat4) private val u_BlendRatio = Uniform("blendRatio", VarType.Float1) /** A Matrix usable for [colorMatrix] that will transform any color into grayscale */ val GRAYSCALE_MATRIX = Matrix3D.fromColumns( 0.33f, 0.33f, 0.33f, 0f, 0.59f, 0.59f, 0.59f, 0f, 0.11f, 0.11f, 0.11f, 0f, 0f, 0f, 0f, 1f ) /** A Matrix usable for [colorMatrix] that will preserve the original color */ val IDENTITY_MATRIX = Matrix3D.fromColumns( 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f ) private val FRAGMENT_SHADER = FragmentShader { apply { out setTo tex(fragmentCoords) out setTo mix(out, (u_ColorMatrix * out), u_BlendRatio) } } val NAMED_MATRICES = mapOf( "IDENTITY" to IDENTITY_MATRIX, "GRAYSCALE" to GRAYSCALE_MATRIX, ) } /** The 4x4 [Matrix3D] that will be used for transforming each pixel components [r, g, b, a] */ var colorMatrix by uniforms.storageForMatrix3D(u_ColorMatrix, colorMatrix) /** * Ratio for blending the original color with the transformed color. * - 0 will return the original color * - 1 will return the transformed color * - Values between [0 and 1] would be an interpolation between those colors. * */ var blendRatio by uniforms.storageFor(u_BlendRatio).doubleDelegateX(blendRatio) override val fragment = FRAGMENT_SHADER var namedColorMatrix: String get() = NAMED_MATRICES.entries.firstOrNull { it.value == colorMatrix }?.key ?: NAMED_MATRICES.keys.first() set(value) = run { colorMatrix = (NAMED_MATRICES[value] ?: IDENTITY_MATRIX) } override fun buildDebugComponent(views: Views, container: UiContainer) { container.uiEditableValue(listOf(colorMatrix::v00, colorMatrix::v01, colorMatrix::v02, colorMatrix::v03), name = "row0") container.uiEditableValue(listOf(colorMatrix::v10, colorMatrix::v11, colorMatrix::v12, colorMatrix::v13), name = "row1") container.uiEditableValue(listOf(colorMatrix::v20, colorMatrix::v21, colorMatrix::v22, colorMatrix::v23), name = "row2") container.uiEditableValue(listOf(colorMatrix::v30, colorMatrix::v31, colorMatrix::v32, colorMatrix::v33), name = "row3") container.uiEditableValue(::namedColorMatrix, values = { NAMED_MATRICES.keys.toList() }) container.uiEditableValue(::blendRatio) } }
apache-2.0
faacf4802fc3f20229f88c57e6faa9db
41.179487
128
0.687538
3.514957
false
false
false
false
mctoyama/PixelClient
src/main/kotlin/org/pixelndice/table/pixelclient/connection/lobby/client/StateRunning04SyncCampaign.kt
1
1278
package org.pixelndice.table.pixelclient.connection.lobby.client import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelclient.ApplicationBus import org.pixelndice.table.pixelclient.ds.Account import org.pixelndice.table.pixelprotocol.Protobuf private val logger = LogManager.getLogger(StateRunning04SyncCampaign::class.java) class StateRunning04SyncCampaign: State { override fun process(ctx: Context) { val packet = ctx.channel.packet if( packet != null ){ if( packet.payloadCase == Protobuf.Packet.PayloadCase.RESOURCEFILESHASH){ val hasFiles = mutableListOf<String>() packet.resourceFilesHash.hashList.forEach { hasFiles.add(it) } val player = Account.fromProtobuf(packet.from) ApplicationBus.post(ApplicationBus.StartRunnableSyncCampaign(ctx, player, hasFiles)) ctx.state = StateRunning() logger.debug("Received ResourceFileHashList. Starting runnable sync campaign") }else{ val message = "Expecting ResourceFilesHashList instead received: $packet. IP: ${ctx.channel.address}" logger.error(message) } } } }
bsd-2-clause
b2ea8c987c5fafae2a579879c17f017a
30.975
117
0.661972
4.750929
false
false
false
false
slartus/4pdaClient-plus
app/src/main/java/org/softeg/slartus/forpdaplus/listfragments/TopicWritersListFragment.kt
1
4239
package org.softeg.slartus.forpdaplus.listfragments import android.content.Context import android.os.Bundle import android.text.Html import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.TextView import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.runBlocking import org.softeg.slartus.forpdaapi.IListItem import org.softeg.slartus.forpdaapi.OldUser import org.softeg.slartus.forpdaapi.classes.ListData import org.softeg.slartus.forpdaplus.R import org.softeg.slartus.forpdaplus.fragments.profile.ProfileFragment import ru.softeg.slartus.forum.api.TopicUsersRepository import javax.inject.Inject /* * Created by slinkin on 17.06.2015. */ @AndroidEntryPoint class TopicWritersListFragment : BaseLoaderListFragment() { private var m_TopicId: String? = null @Inject lateinit var topicUsersRepository: TopicUsersRepository override fun onResume() { super.onResume() setArrow() } override fun onPause() { super.onPause() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState != null) { m_TopicId = savedInstanceState.getString(TOPIC_ID_KEY) } else if (arguments != null) { m_TopicId = arguments!!.getString(TOPIC_ID_KEY) } setArrow() } override fun getLoadArgs(): Bundle { val args = Bundle() args.putString(TOPIC_ID_KEY, m_TopicId) return args } override fun createAdapter(): BaseAdapter { return UsersAdapter( activity, data.items ) } override fun useCache(): Boolean { return false } override fun getViewResourceId(): Int { return R.layout.list_fragment } @Throws(Throwable::class) override fun loadData( loaderId: Int, args: Bundle ): ListData { val topicId = args.getString(TopicReadersListFragment.TOPIC_ID_KEY) ?: return ListData() val writers = runBlocking { topicUsersRepository.getTopicWriters(topicId) } return ListData().apply { items.addAll(writers.map { OldUser().apply { mid = it.id nick = it.nick MessagesCount = it.postsCount.toString() } }) } } inner class UsersAdapter(context: Context?, private val mUsers: ArrayList<IListItem>) : BaseAdapter() { protected var m_Inflater: LayoutInflater init { m_Inflater = LayoutInflater.from(context) } override fun getCount(): Int { return mUsers.size } override fun getItem(position: Int): Any { return mUsers[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, view: View?, parent: ViewGroup?): View { var convertView = view val holder: ViewHolder if (convertView == null) { convertView = m_Inflater.inflate(R.layout.topic_writer_item, parent, false) holder = ViewHolder() assert(convertView != null) holder.txtCount = convertView.findViewById(R.id.txtMessagesCount) holder.txtNick = convertView.findViewById(R.id.txtNick) convertView.tag = holder } else { holder = convertView.tag as ViewHolder } val user = getItem(position) as OldUser holder.txtCount!!.text = user.MessagesCount holder.txtNick!!.text = Html.fromHtml(user.nick) convertView!!.setOnClickListener { openProfile(user) } return convertView!! } inner class ViewHolder { var txtNick: TextView? = null var txtCount: TextView? = null } } fun openProfile(user: OldUser) { ProfileFragment.showProfile(user.mid, user.mid) } companion object { const val TOPIC_ID_KEY = "TOPIC_ID_KEY" } }
apache-2.0
ad950f96304978bc6fe0a1917283a7bf
28.65035
96
0.618306
4.715239
false
false
false
false
chadrick-kwag/datalabeling_app
app/src/main/java/com/example/chadrick/datalabeling/Models/DownloadTaskManager.kt
1
1343
package com.example.chadrick.datalabeling.Models import com.example.chadrick.datalabeling.Tasks.dszipDownloadTask /** * Created by chadrick on 17. 12. 4. */ class DownloadTaskManager private constructor(){ private val hashmap : HashMap<DataSet, dszipDownloadTask> = HashMap() private object holder { val INSTANCE = DownloadTaskManager()} companion object { val instance : DownloadTaskManager = holder.INSTANCE } @Synchronized fun isAlreadyRegistered(ds : DataSet) : Boolean { if(hashmap.containsKey(ds)){ val fetchedtask = hashmap.get(ds) if( !(fetchedtask!!.isFinished())) return true } return false } @Synchronized fun addDownloadTask(ds: DataSet , param_downloadtask : dszipDownloadTask){ if(hashmap.containsKey(ds)){ // if exists and is finished, remove it. val task = hashmap.get(ds) if(task?.isFinished() ?: false){ hashmap.remove(ds) } } hashmap.put(ds,param_downloadtask) } @Synchronized fun remove(ds:DataSet){ if(hashmap.containsKey(ds)){ val task = hashmap.get(ds) if(task?.isFinished() ?: true == false){ hashmap.remove(ds) task?.cancel(true) } } } }
mit
ad0742fb081082d653e1233c880d7c4f
26.428571
92
0.599404
4.374593
false
false
false
false
AndroidX/androidx
tv/tv-foundation/src/main/java/androidx/tv/foundation/lazy/grid/TvLazyGridState.kt
3
17281
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.tv.foundation.lazy.grid import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.ScrollScope import androidx.compose.foundation.gestures.ScrollableState import androidx.compose.foundation.interaction.InteractionSource import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.lazy.layout.LazyLayoutPrefetchState import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.collection.mutableVectorOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.Saver import androidx.compose.runtime.saveable.listSaver import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.layout.Remeasurement import androidx.compose.ui.layout.RemeasurementModifier import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.IntSize import androidx.compose.ui.util.fastForEach import androidx.tv.foundation.lazy.layout.animateScrollToItem import androidx.tv.foundation.lazy.list.AwaitFirstLayoutModifier import kotlin.math.abs /** * Creates a [TvLazyGridState] that is remembered across compositions. * * Changes to the provided initial values will **not** result in the state being recreated or * changed in any way if it has already been created. * * @param initialFirstVisibleItemIndex the initial value for [TvLazyGridState.firstVisibleItemIndex] * @param initialFirstVisibleItemScrollOffset the initial value for * [TvLazyGridState.firstVisibleItemScrollOffset] */ @Composable fun rememberTvLazyGridState( initialFirstVisibleItemIndex: Int = 0, initialFirstVisibleItemScrollOffset: Int = 0 ): TvLazyGridState { return rememberSaveable(saver = TvLazyGridState.Saver) { TvLazyGridState( initialFirstVisibleItemIndex, initialFirstVisibleItemScrollOffset ) } } /** * A state object that can be hoisted to control and observe scrolling. * * In most cases, this will be created via [rememberTvLazyGridState]. * * @param firstVisibleItemIndex the initial value for [TvLazyGridState.firstVisibleItemIndex] * @param firstVisibleItemScrollOffset the initial value for * [TvLazyGridState.firstVisibleItemScrollOffset] */ @OptIn(ExperimentalFoundationApi::class) @Stable class TvLazyGridState constructor( firstVisibleItemIndex: Int = 0, firstVisibleItemScrollOffset: Int = 0 ) : ScrollableState { /** * The holder class for the current scroll position. */ private val scrollPosition = LazyGridScrollPosition(firstVisibleItemIndex, firstVisibleItemScrollOffset) /** * The index of the first item that is visible. * * Note that this property is observable and if you use it in the composable function it will * be recomposed on every change causing potential performance issues. */ val firstVisibleItemIndex: Int get() = scrollPosition.index.value /** * The scroll offset of the first visible item. Scrolling forward is positive - i.e., the * amount that the item is offset backwards */ val firstVisibleItemScrollOffset: Int get() = scrollPosition.scrollOffset /** Backing state for [layoutInfo] */ private val layoutInfoState = mutableStateOf<TvLazyGridLayoutInfo>(EmptyTvLazyGridLayoutInfo) /** * The object of [TvLazyGridLayoutInfo] calculated during the last layout pass. For example, * you can use it to calculate what items are currently visible. * * Note that this property is observable and is updated after every scroll or remeasure. * If you use it in the composable function it will be recomposed on every change causing * potential performance issues including infinity recomposition loop. * Therefore, avoid using it in the composition. */ val layoutInfo: TvLazyGridLayoutInfo get() = layoutInfoState.value /** * [InteractionSource] that will be used to dispatch drag events when this * grid is being dragged. If you want to know whether the fling (or animated scroll) is in * progress, use [isScrollInProgress]. */ val interactionSource: InteractionSource get() = internalInteractionSource internal val internalInteractionSource: MutableInteractionSource = MutableInteractionSource() /** * The amount of scroll to be consumed in the next layout pass. Scrolling forward is negative * - that is, it is the amount that the items are offset in y */ internal var scrollToBeConsumed = 0f private set /** * Needed for [animateScrollToItem]. Updated on every measure. */ internal var slotsPerLine: Int by mutableStateOf(0) /** * Needed for [animateScrollToItem]. Updated on every measure. */ internal var density: Density by mutableStateOf(Density(1f, 1f)) /** * Needed for [notifyPrefetch]. */ internal var isVertical: Boolean by mutableStateOf(true) /** * The ScrollableController instance. We keep it as we need to call stopAnimation on it once * we reached the end of the grid. */ private val scrollableState = ScrollableState { -onScroll(-it) } /** * Only used for testing to confirm that we're not making too many measure passes */ /*@VisibleForTesting*/ internal var numMeasurePasses: Int = 0 private set /** * Only used for testing to disable prefetching when needed to test the main logic. */ /*@VisibleForTesting*/ internal var prefetchingEnabled: Boolean = true /** * The index scheduled to be prefetched (or the last prefetched index if the prefetch is done). */ private var lineToPrefetch = -1 /** * The list of handles associated with the items from the [lineToPrefetch] line. */ private val currentLinePrefetchHandles = mutableVectorOf<LazyLayoutPrefetchState.PrefetchHandle>() /** * Keeps the scrolling direction during the previous calculation in order to be able to * detect the scrolling direction change. */ private var wasScrollingForward = false /** * The [Remeasurement] object associated with our layout. It allows us to remeasure * synchronously during scroll. */ private var remeasurement: Remeasurement? by mutableStateOf(null) /** * The modifier which provides [remeasurement]. */ internal val remeasurementModifier = object : RemeasurementModifier { override fun onRemeasurementAvailable(remeasurement: Remeasurement) { [email protected] = remeasurement } } /** * Provides a modifier which allows to delay some interactions (e.g. scroll) * until layout is ready. */ internal val awaitLayoutModifier = AwaitFirstLayoutModifier() /** * Finds items on a line and their measurement constraints. Used for prefetching. */ internal var prefetchInfoRetriever: (line: LineIndex) -> List<Pair<Int, Constraints>> by mutableStateOf({ emptyList() }) internal var placementAnimator by mutableStateOf<LazyGridItemPlacementAnimator?>(null) private val animateScrollScope = LazyGridAnimateScrollScope(this) /** * Instantly brings the item at [index] to the top of the viewport, offset by [scrollOffset] * pixels. * * @param index the index to which to scroll. Must be non-negative. * @param scrollOffset the offset that the item should end up after the scroll. Note that * positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will * scroll the item further upward (taking it partly offscreen). */ suspend fun scrollToItem( /*@IntRange(from = 0)*/ index: Int, scrollOffset: Int = 0 ) { scroll { snapToItemIndexInternal(index, scrollOffset) } } internal fun snapToItemIndexInternal(index: Int, scrollOffset: Int) { scrollPosition.requestPosition(ItemIndex(index), scrollOffset) // placement animation is not needed because we snap into a new position. placementAnimator?.reset() remeasurement?.forceRemeasure() } /** * Call this function to take control of scrolling and gain the ability to send scroll events * via [ScrollScope.scrollBy]. All actions that change the logical scroll position must be * performed within a [scroll] block (even if they don't call any other methods on this * object) in order to guarantee that mutual exclusion is enforced. * * If [scroll] is called from elsewhere, this will be canceled. */ override suspend fun scroll( scrollPriority: MutatePriority, block: suspend ScrollScope.() -> Unit ) { awaitLayoutModifier.waitForFirstLayout() scrollableState.scroll(scrollPriority, block) } override fun dispatchRawDelta(delta: Float): Float = scrollableState.dispatchRawDelta(delta) override val isScrollInProgress: Boolean get() = scrollableState.isScrollInProgress override var canScrollForward: Boolean by mutableStateOf(false) private set override var canScrollBackward: Boolean by mutableStateOf(false) private set // TODO: Coroutine scrolling APIs will allow this to be private again once we have more // fine-grained control over scrolling /*@VisibleForTesting*/ internal fun onScroll(distance: Float): Float { if (distance < 0 && !canScrollForward || distance > 0 && !canScrollBackward) { return 0f } check(abs(scrollToBeConsumed) <= 0.5f) { "entered drag with non-zero pending scroll: $scrollToBeConsumed" } scrollToBeConsumed += distance // scrollToBeConsumed will be consumed synchronously during the forceRemeasure invocation // inside measuring we do scrollToBeConsumed.roundToInt() so there will be no scroll if // we have less than 0.5 pixels if (abs(scrollToBeConsumed) > 0.5f) { val preScrollToBeConsumed = scrollToBeConsumed remeasurement?.forceRemeasure() if (prefetchingEnabled) { notifyPrefetch(preScrollToBeConsumed - scrollToBeConsumed) } } // here scrollToBeConsumed is already consumed during the forceRemeasure invocation if (abs(scrollToBeConsumed) <= 0.5f) { // We consumed all of it - we'll hold onto the fractional scroll for later, so report // that we consumed the whole thing return distance } else { val scrollConsumed = distance - scrollToBeConsumed // We did not consume all of it - return the rest to be consumed elsewhere (e.g., // nested scrolling) scrollToBeConsumed = 0f // We're not consuming the rest, give it back return scrollConsumed } } private fun notifyPrefetch(delta: Float) { val prefetchState = prefetchState if (!prefetchingEnabled) { return } val info = layoutInfo if (info.visibleItemsInfo.isNotEmpty()) { val scrollingForward = delta < 0 val lineToPrefetch: Int val closestNextItemToPrefetch: Int if (scrollingForward) { lineToPrefetch = 1 + info.visibleItemsInfo.last().let { if (isVertical) it.row else it.column } closestNextItemToPrefetch = info.visibleItemsInfo.last().index + 1 } else { lineToPrefetch = -1 + info.visibleItemsInfo.first().let { if (isVertical) it.row else it.column } closestNextItemToPrefetch = info.visibleItemsInfo.first().index - 1 } if (lineToPrefetch != this.lineToPrefetch && closestNextItemToPrefetch in 0 until info.totalItemsCount ) { if (wasScrollingForward != scrollingForward) { // the scrolling direction has been changed which means the last prefetched // is not going to be reached anytime soon so it is safer to dispose it. // if this line is already visible it is safe to call the method anyway // as it will be no-op currentLinePrefetchHandles.forEach { it.cancel() } } this.wasScrollingForward = scrollingForward this.lineToPrefetch = lineToPrefetch currentLinePrefetchHandles.clear() prefetchInfoRetriever(LineIndex(lineToPrefetch)).fastForEach { currentLinePrefetchHandles.add( prefetchState.schedulePrefetch(it.first, it.second) ) } } } } private fun cancelPrefetchIfVisibleItemsChanged(info: TvLazyGridLayoutInfo) { if (lineToPrefetch != -1 && info.visibleItemsInfo.isNotEmpty()) { val expectedLineToPrefetch = if (wasScrollingForward) { info.visibleItemsInfo.last().let { if (isVertical) it.row else it.column } + 1 } else { info.visibleItemsInfo.first().let { if (isVertical) it.row else it.column } - 1 } if (lineToPrefetch != expectedLineToPrefetch) { lineToPrefetch = -1 currentLinePrefetchHandles.forEach { it.cancel() } currentLinePrefetchHandles.clear() } } } internal val prefetchState = LazyLayoutPrefetchState() /** * Animate (smooth scroll) to the given item. * * @param index the index to which to scroll. Must be non-negative. * @param scrollOffset the offset that the item should end up after the scroll. Note that * positive offset refers to forward scroll, so in a top-to-bottom list, positive offset will * scroll the item further upward (taking it partly offscreen). */ suspend fun animateScrollToItem( /*@IntRange(from = 0)*/ index: Int, scrollOffset: Int = 0 ) { animateScrollScope.animateScrollToItem(index, scrollOffset) } /** * Updates the state with the new calculated scroll position and consumed scroll. */ internal fun applyMeasureResult(result: TvLazyGridMeasureResult) { scrollPosition.updateFromMeasureResult(result) scrollToBeConsumed -= result.consumedScroll layoutInfoState.value = result canScrollForward = result.canScrollForward canScrollBackward = (result.firstVisibleLine?.index?.value ?: 0) != 0 || result.firstVisibleLineScrollOffset != 0 numMeasurePasses++ cancelPrefetchIfVisibleItemsChanged(result) } /** * When the user provided custom keys for the items we can try to detect when there were * items added or removed before our current first visible item and keep this item * as the first visible one even given that its index has been changed. */ internal fun updateScrollPositionIfTheFirstItemWasMoved(itemProvider: LazyGridItemProvider) { scrollPosition.updateScrollPositionIfTheFirstItemWasMoved(itemProvider) } companion object { /** * The default [Saver] implementation for [TvLazyGridState]. */ val Saver: Saver<TvLazyGridState, *> = listSaver( save = { listOf(it.firstVisibleItemIndex, it.firstVisibleItemScrollOffset) }, restore = { TvLazyGridState( firstVisibleItemIndex = it[0], firstVisibleItemScrollOffset = it[1] ) } ) } } private object EmptyTvLazyGridLayoutInfo : TvLazyGridLayoutInfo { override val visibleItemsInfo = emptyList<TvLazyGridItemInfo>() override val viewportStartOffset = 0 override val viewportEndOffset = 0 override val totalItemsCount = 0 override val viewportSize = IntSize.Zero override val orientation = Orientation.Vertical override val reverseLayout = false override val beforeContentPadding: Int = 0 override val afterContentPadding: Int = 0 }
apache-2.0
e1b62dd91f6442d7239936fe7b818523
38.454338
100
0.681268
5.130938
false
false
false
false
exponent/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/components/gesturehandler/RotationGestureDetector.kt
2
4006
package abi44_0_0.host.exp.exponent.modules.api.components.gesturehandler import android.view.MotionEvent import kotlin.math.atan2 class RotationGestureDetector(private val gestureListener: OnRotationGestureListener?) { interface OnRotationGestureListener { fun onRotation(detector: RotationGestureDetector): Boolean fun onRotationBegin(detector: RotationGestureDetector): Boolean fun onRotationEnd(detector: RotationGestureDetector) } private var currentTime = 0L private var previousTime = 0L private var previousAngle = 0.0 /** * Returns rotation in radians since the previous rotation event. * * @return current rotation step in radians. */ var rotation = 0.0 private set /** * Returns X coordinate of the rotation anchor point relative to the view that the provided motion * event coordinates (usually relative to the view event was sent to). * * @return X coordinate of the rotation anchor point */ var anchorX = 0f private set /** * Returns Y coordinate of the rotation anchor point relative to the view that the provided motion * event coordinates (usually relative to the view event was sent to). * * @return Y coordinate of the rotation anchor point */ var anchorY = 0f private set /** * Return the time difference in milliseconds between the previous * accepted rotation event and the current rotation event. * * @return Time difference since the last rotation event in milliseconds. */ val timeDelta: Long get() = currentTime - previousTime private var isInProgress = false private val pointerIds = IntArray(2) private fun updateCurrent(event: MotionEvent) { previousTime = currentTime currentTime = event.eventTime val firstPointerIndex = event.findPointerIndex(pointerIds[0]) val secondPointerIndex = event.findPointerIndex(pointerIds[1]) val firstPtX = event.getX(firstPointerIndex) val firstPtY = event.getY(firstPointerIndex) val secondPtX = event.getX(secondPointerIndex) val secondPtY = event.getY(secondPointerIndex) val vectorX = secondPtX - firstPtX val vectorY = secondPtY - firstPtY anchorX = (firstPtX + secondPtX) * 0.5f anchorY = (firstPtY + secondPtY) * 0.5f // Angle diff should be positive when rotating in clockwise direction val angle = -atan2(vectorY.toDouble(), vectorX.toDouble()) rotation = if (previousAngle.isNaN()) { 0.0 } else previousAngle - angle previousAngle = angle if (rotation > Math.PI) { rotation -= Math.PI } else if (rotation < -Math.PI) { rotation += Math.PI } if (rotation > Math.PI / 2.0) { rotation -= Math.PI } else if (rotation < -Math.PI / 2.0) { rotation += Math.PI } } private fun finish() { if (isInProgress) { isInProgress = false gestureListener?.onRotationEnd(this) } } fun onTouchEvent(event: MotionEvent): Boolean { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { isInProgress = false pointerIds[0] = event.getPointerId(event.actionIndex) pointerIds[1] = MotionEvent.INVALID_POINTER_ID } MotionEvent.ACTION_POINTER_DOWN -> if (!isInProgress) { pointerIds[1] = event.getPointerId(event.actionIndex) isInProgress = true previousTime = event.eventTime previousAngle = Double.NaN updateCurrent(event) gestureListener?.onRotationBegin(this) } MotionEvent.ACTION_MOVE -> if (isInProgress) { updateCurrent(event) gestureListener?.onRotation(this) } MotionEvent.ACTION_POINTER_UP -> if (isInProgress) { val pointerId = event.getPointerId(event.actionIndex) if (pointerId == pointerIds[0] || pointerId == pointerIds[1]) { // One of the key pointer has been lifted up, we have to end the gesture finish() } } MotionEvent.ACTION_UP -> finish() } return true } }
bsd-3-clause
12e06c8ccc20d4e6dfe794b1f57f1430
31.048
100
0.681727
4.354348
false
false
false
false
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/modules/api/components/reactnativestripesdk/StripeSdkCardViewManager.kt
2
2595
package versioned.host.exp.exponent.modules.api.components.reactnativestripesdk import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap import com.facebook.react.common.MapBuilder import com.facebook.react.uimanager.SimpleViewManager import com.facebook.react.uimanager.ThemedReactContext import com.facebook.react.uimanager.annotations.ReactProp class StripeSdkCardViewManager : SimpleViewManager<StripeSdkCardView>() { override fun getName() = "CardField" private var reactContextRef: ThemedReactContext? = null override fun getExportedCustomDirectEventTypeConstants(): MutableMap<String, Any> { return MapBuilder.of( CardFocusEvent.EVENT_NAME, MapBuilder.of("registrationName", "onFocusChange"), CardChangedEvent.EVENT_NAME, MapBuilder.of("registrationName", "onCardChange") ) } override fun receiveCommand(root: StripeSdkCardView, commandId: String?, args: ReadableArray?) { when (commandId) { "focus" -> root.requestFocusFromJS() "blur" -> root.requestBlurFromJS() "clear" -> root.requestClearFromJS() } } @ReactProp(name = "dangerouslyGetFullCardDetails") fun setDangerouslyGetFullCardDetails(view: StripeSdkCardView, dangerouslyGetFullCardDetails: Boolean = false) { view.setDangerouslyGetFullCardDetails(dangerouslyGetFullCardDetails) } @ReactProp(name = "postalCodeEnabled") fun setPostalCodeEnabled(view: StripeSdkCardView, postalCodeEnabled: Boolean = true) { view.setPostalCodeEnabled(postalCodeEnabled) } @ReactProp(name = "autofocus") fun setAutofocus(view: StripeSdkCardView, autofocus: Boolean = false) { view.setAutofocus(autofocus) } @ReactProp(name = "cardStyle") fun setCardStyle(view: StripeSdkCardView, cardStyle: ReadableMap) { view.setCardStyle(cardStyle) } @ReactProp(name = "placeholder") fun setPlaceHolders(view: StripeSdkCardView, placeholder: ReadableMap) { view.setPlaceHolders(placeholder) } override fun createViewInstance(reactContext: ThemedReactContext): StripeSdkCardView { val stripeSdkModule: StripeSdkModule? = reactContext.getNativeModule(StripeSdkModule::class.java) val view = StripeSdkCardView(reactContext) reactContextRef = reactContext stripeSdkModule?.cardFieldView = view return view } override fun onDropViewInstance(view: StripeSdkCardView) { super.onDropViewInstance(view) val stripeSdkModule: StripeSdkModule? = reactContextRef?.getNativeModule(StripeSdkModule::class.java) stripeSdkModule?.cardFieldView = null reactContextRef = null } }
bsd-3-clause
6de39321bde23855517071e0268fefd3
35.041667
113
0.774952
4.268092
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/main/kotlin/com/teamwizardry/librarianlib/facade/layers/DragLayer.kt
1
2659
package com.teamwizardry.librarianlib.facade.layers import com.teamwizardry.librarianlib.core.util.vec import com.teamwizardry.librarianlib.etcetera.eventbus.CancelableEvent import com.teamwizardry.librarianlib.etcetera.eventbus.Hook import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.facade.layer.GuiLayerEvents import com.teamwizardry.librarianlib.facade.value.IMValueBoolean import com.teamwizardry.librarianlib.math.Vec2d /** * A layer that will move the [targetLayer] when the mouse is dragged on it. If the target is null this layer will move * itself. */ public class DragLayer : GuiLayer { public constructor(posX: Int, posY: Int, width: Int, height: Int): super(posX, posY, width, height) public constructor(posX: Int, posY: Int): super(posX, posY) public constructor(): super() /** * The button that should activate the dragging action. Defaults to the left mouse button */ public var button: Int = 0 set(value) { if(field != value) { currentlyDragging = false } field = value } /** * The layer that should be moved by this layer. The target layer should be an ancestor of this layer, otherwise * the dragging will behave oddly. If the target is null this layer will move itself. */ public var targetLayer: GuiLayer? = null /** * Whether the dragging is active. */ public var active_im: IMValueBoolean = imBoolean(true) /** * Whether the dragging is active. */ public var active: Boolean by active_im public class DragEvent(public var targetPosition: Vec2d): CancelableEvent() private var currentlyDragging: Boolean = false private var mouseDownPos: Vec2d = vec(0, 0) @Hook private fun mouseDown(e: GuiLayerEvents.MouseDown) { if(this.mouseOver && e.button == button) { currentlyDragging = true mouseDownPos = mousePos } } @Hook private fun mouseUp(e: GuiLayerEvents.MouseUp) { if(e.button == button) { currentlyDragging = false } } @Hook private fun mouseMove(e: GuiLayerEvents.MouseMove) { if(!currentlyDragging) return val localOffset = e.pos - mouseDownPos val target = this.targetLayer ?: this val targetParent = target.parent ?: return val targetPos = target.pos + this.convertOffsetTo(localOffset, targetParent) val event = DragEvent(targetPos) BUS.fire(event) if(!event.isCanceled()) { target.pos = event.targetPosition } } }
lgpl-3.0
0d7c934ba5de816a2b5ad3ecc4f1fcff
32.25
119
0.66792
4.344771
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/screens/pastry/tests/PastryTestColorPicker.kt
1
1593
package com.teamwizardry.librarianlib.facade.test.screens.pastry.tests import com.teamwizardry.librarianlib.core.util.vec import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.facade.layers.RectLayer import com.teamwizardry.librarianlib.facade.layers.StackLayout import com.teamwizardry.librarianlib.facade.layers.TextLayer import com.teamwizardry.librarianlib.facade.layers.text.TextFit import com.teamwizardry.librarianlib.facade.pastry.layers.PastryButton import com.teamwizardry.librarianlib.facade.pastry.layers.PastryColorPicker import com.teamwizardry.librarianlib.facade.pastry.layers.PastryLabel import com.teamwizardry.librarianlib.facade.test.screens.pastry.PastryTestBase import java.awt.Color class PastryTestColorPicker: PastryTestBase() { init { val colorSwatch = RectLayer(Color.WHITE, 0, 0, 10, 10) val colorLabel = PastryLabel(0, 0, "#") val container = GuiLayer(175, 150) colorLabel.textFitting = TextFit.HORIZONTAL val colorPicker = PastryColorPicker() colorPicker.pos = vec(10, 10) container.add(colorPicker) colorPicker.hook<PastryColorPicker.ColorChangeEvent> { colorSwatch.color = it.color colorLabel.text = Integer.toHexString(it.color.rgb).padStart(6, '0') } this.stack.add(StackLayout.build() .horizontal() .alignCenterY() .spacing(3) .add(colorSwatch, colorLabel) .fitBreadth() .build() ) this.stack.add(container) } }
lgpl-3.0
3fbf93bc128f9afdfcccb3dd4b1d4cca
37.878049
80
0.720653
4.225464
false
true
false
false
TeamWizardry/LibrarianLib
modules/core/src/main/kotlin/com/teamwizardry/librarianlib/core/util/kotlin/NbtBuilder.kt
1
9027
@file:Suppress("NOTHING_TO_INLINE") package com.teamwizardry.librarianlib.core.util.kotlin import net.minecraft.nbt.* import kotlin.jvm.JvmInline @DslMarker internal annotation class NbtBuilderDslMarker /** * A Kotlin DSL for creating NbtElement tags. * * ```kotlin * NbtBuilder.compound { * "key" %= string("value") * "key" %= list { * +int(3) * +int(4) * } * } * ``` */ @NbtBuilderDslMarker public object NbtBuilder { public inline fun use(tag: NbtCompound, block: NbtCompoundBuilder.() -> Unit): NbtCompound = NbtCompoundBuilder(tag).also(block).tag public inline fun compound(block: NbtCompoundBuilder.() -> Unit): NbtCompound = NbtCompoundBuilder(NbtCompound()).also(block).tag public inline fun list(block: NbtListBuilder.() -> Unit): NbtList = NbtListBuilder(NbtList()).also(block).tag public inline fun list(vararg elements: NbtElement, block: NbtListBuilder.() -> Unit): NbtList = NbtListBuilder(NbtList()).also { it.addAll(elements.toList()) it.block() }.tag public inline fun list(vararg elements: NbtElement): NbtList = NbtList().also { it.addAll(elements) } public inline fun list(elements: Collection<NbtElement>): NbtList = NbtList().also { it.addAll(elements) } public inline fun double(value: Number): NbtDouble = NbtDouble.of(value.toDouble()) public inline fun float(value: Number): NbtFloat = NbtFloat.of(value.toFloat()) public inline fun long(value: Number): NbtLong = NbtLong.of(value.toLong()) public inline fun int(value: Number): NbtInt = NbtInt.of(value.toInt()) public inline fun short(value: Number): NbtShort = NbtShort.of(value.toShort()) public inline fun byte(value: Number): NbtByte = NbtByte.of(value.toByte()) public inline fun string(value: String): NbtString = NbtString.of(value) public inline fun byteArray(vararg value: Int): NbtByteArray = NbtByteArray(ByteArray(value.size) { value[it].toByte() }) public inline fun byteArray(vararg value: Byte): NbtByteArray = NbtByteArray(value) public inline fun byteArray(): NbtByteArray = NbtByteArray(byteArrayOf()) // avoiding overload ambiguity public inline fun longArray(vararg value: Int): NbtLongArray = NbtLongArray(LongArray(value.size) { value[it].toLong() }) public inline fun longArray(vararg value: Long): NbtLongArray = NbtLongArray(value) public inline fun longArray(): NbtLongArray = NbtLongArray(longArrayOf()) // avoiding overload ambiguity public inline fun intArray(vararg value: Int): NbtIntArray = NbtIntArray(value) } @JvmInline @NbtBuilderDslMarker public value class NbtCompoundBuilder(public val tag: NbtCompound) { // configuring this tag public operator fun String.remAssign(nbt: NbtElement) { tag.put(this, nbt) } // creating new tags public inline fun compound(block: NbtCompoundBuilder.() -> Unit): NbtCompound = NbtCompoundBuilder(NbtCompound()).also { it.block() }.tag public inline fun list(block: NbtListBuilder.() -> Unit): NbtList = NbtListBuilder(NbtList()).also { it.block() }.tag public inline fun list(vararg elements: NbtElement, block: NbtListBuilder.() -> Unit): NbtList = NbtListBuilder(NbtList()).also { it.addAll(elements.toList()) it.block() }.tag public inline fun list(vararg elements: NbtElement): NbtList = NbtList().also { it.addAll(elements) } public inline fun list(elements: Collection<NbtElement>): NbtList = NbtList().also { it.addAll(elements) } public inline fun double(value: Number): NbtDouble = NbtDouble.of(value.toDouble()) public inline fun float(value: Number): NbtFloat = NbtFloat.of(value.toFloat()) public inline fun long(value: Number): NbtLong = NbtLong.of(value.toLong()) public inline fun int(value: Number): NbtInt = NbtInt.of(value.toInt()) public inline fun short(value: Number): NbtShort = NbtShort.of(value.toShort()) public inline fun byte(value: Number): NbtByte = NbtByte.of(value.toByte()) public inline fun string(value: String): NbtString = NbtString.of(value) public inline fun byteArray(vararg value: Int): NbtByteArray = NbtByteArray(ByteArray(value.size) { value[it].toByte() }) public inline fun byteArray(vararg value: Byte): NbtByteArray = NbtByteArray(value) public inline fun byteArray(): NbtByteArray = NbtByteArray(byteArrayOf()) // avoiding overload ambiguity public inline fun longArray(vararg value: Int): NbtLongArray = NbtLongArray(LongArray(value.size) { value[it].toLong() }) public inline fun longArray(vararg value: Long): NbtLongArray = NbtLongArray(value) public inline fun longArray(): NbtLongArray = NbtLongArray(longArrayOf()) // avoiding overload ambiguity public inline fun intArray(vararg value: Int): NbtIntArray = NbtIntArray(value) } @JvmInline @NbtBuilderDslMarker public value class NbtListBuilder(public val tag: NbtList) { // configuring this tag /** * Add the given NbtElement tag to this list */ public operator fun NbtElement.unaryPlus() { tag.add(this) } /** * Add the given NbtElement tags to this list */ public operator fun Collection<NbtElement>.unaryPlus() { tag.addAll(this) } /** * Add the given NbtElement tag to this list. This is explicitly defined for [NbtList] because otherwise there is overload * ambiguity between the [NbtElement] and [Collection]<[NbtElement]> methods. */ public operator fun NbtList.unaryPlus() { tag.add(this) } public fun addAll(nbt: Collection<NbtElement>) { this.tag.addAll(nbt) } public fun add(nbt: NbtElement) { this.tag.add(nbt) } // creating new tags public inline fun compound(block: NbtCompoundBuilder.() -> Unit): NbtCompound = NbtCompoundBuilder(NbtCompound()).also { it.block() }.tag public inline fun list(block: NbtListBuilder.() -> Unit): NbtList = NbtListBuilder(NbtList()).also { it.block() }.tag public inline fun list(vararg elements: NbtElement, block: NbtListBuilder.() -> Unit): NbtList = NbtListBuilder(NbtList()).also { it.addAll(elements.toList()) it.block() }.tag public inline fun list(vararg elements: NbtElement): NbtList = NbtList().also { it.addAll(elements) } public inline fun list(elements: Collection<NbtElement>): NbtList = NbtList().also { it.addAll(elements) } public inline fun double(value: Number): NbtDouble = NbtDouble.of(value.toDouble()) public inline fun float(value: Number): NbtFloat = NbtFloat.of(value.toFloat()) public inline fun long(value: Number): NbtLong = NbtLong.of(value.toLong()) public inline fun int(value: Number): NbtInt = NbtInt.of(value.toInt()) public inline fun short(value: Number): NbtShort = NbtShort.of(value.toShort()) public inline fun byte(value: Number): NbtByte = NbtByte.of(value.toByte()) public inline fun string(value: String): NbtString = NbtString.of(value) public inline fun byteArray(vararg value: Int): NbtByteArray = NbtByteArray(ByteArray(value.size) { value[it].toByte() }) public inline fun byteArray(vararg value: Byte): NbtByteArray = NbtByteArray(value) public inline fun byteArray(): NbtByteArray = NbtByteArray(byteArrayOf()) // avoiding overload ambiguity public inline fun longArray(vararg value: Int): NbtLongArray = NbtLongArray(LongArray(value.size) { value[it].toLong() }) public inline fun longArray(vararg value: Long): NbtLongArray = NbtLongArray(value) public inline fun longArray(): NbtLongArray = NbtLongArray(longArrayOf()) // avoiding overload ambiguity public inline fun intArray(vararg value: Int): NbtIntArray = NbtIntArray(value) public inline fun doubles(vararg value: Int): List<NbtDouble> = value.map { NbtDouble.of(it.toDouble()) } public inline fun doubles(vararg value: Double): List<NbtDouble> = value.map { NbtDouble.of(it) } public inline fun floats(vararg value: Int): List<NbtFloat> = value.map { NbtFloat.of(it.toFloat()) } public inline fun floats(vararg value: Float): List<NbtFloat> = value.map { NbtFloat.of(it) } public inline fun longs(vararg value: Int): List<NbtLong> = value.map { NbtLong.of(it.toLong()) } public inline fun longs(vararg value: Long): List<NbtLong> = value.map { NbtLong.of(it) } public inline fun ints(vararg value: Int): List<NbtInt> = value.map { NbtInt.of(it) } public inline fun shorts(vararg value: Int): List<NbtShort> = value.map { NbtShort.of(it.toShort()) } public inline fun shorts(vararg value: Short): List<NbtShort> = value.map { NbtShort.of(it) } public inline fun bytes(vararg value: Int): List<NbtByte> = value.map { NbtByte.of(it.toByte()) } public inline fun bytes(vararg value: Byte): List<NbtByte> = value.map { NbtByte.of(it) } public fun strings(vararg value: String): List<NbtString> = value.map { NbtString.of(it) } }
lgpl-3.0
cce5b1bb4ebb24bbde2a95ce51f3a53f
47.015957
126
0.698903
4.040734
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/inspections/fixes/DeriveCopyFix.kt
2
3372
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections.fixes import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.rust.cargo.project.workspace.PackageOrigin import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.ImplLookup import org.rust.lang.core.types.ty.TyAdt import org.rust.lang.core.types.ty.isMovesByDefault import org.rust.lang.core.types.type class DeriveCopyFix(element: RsElement) : LocalQuickFixAndIntentionActionOnPsiElement(element) { override fun getFamilyName(): String = name override fun getText(): String = "Derive Copy trait" override fun invoke(project: Project, file: PsiFile, editor: Editor?, startElement: PsiElement, endElement: PsiElement) { val pathExpr = startElement as? RsPathExpr ?: return val type = pathExpr.type as? TyAdt ?: return val item = type.item.findPreviewCopyIfNeeded(file) val implLookup = ImplLookup.relativeTo(item) val isCloneImplemented = implLookup.isClone(type) val psiFactory = RsPsiFactory(project) val existingDeriveAttr = item.findOuterAttr("derive") if (existingDeriveAttr != null) { updateDeriveAttr(psiFactory, existingDeriveAttr, isCloneImplemented) } else { createDeriveAttr(psiFactory, item, isCloneImplemented) } } private fun updateDeriveAttr(psiFactory: RsPsiFactory, deriveAttr: RsOuterAttr, isCloneImplemented: Boolean) { val oldAttrText = deriveAttr.text val newAttrText = buildString { append(oldAttrText.substringBeforeLast(")")) if (isCloneImplemented) append(", Copy)") else append(", Clone, Copy)") } val newDeriveAttr = psiFactory.createOuterAttr(newAttrText) deriveAttr.replace(newDeriveAttr) } private fun createDeriveAttr(psiFactory: RsPsiFactory, item: RsStructOrEnumItemElement, isCloneImplemented: Boolean) { val keyword = item.firstKeyword!! val newAttrText = if (isCloneImplemented) "derive(Copy)" else "derive(Clone, Copy)" val newDeriveAttr = psiFactory.createOuterAttr(newAttrText) item.addBefore(newDeriveAttr, keyword) } companion object { fun createIfCompatible(element: RsElement): DeriveCopyFix? { val pathExpr = element as? RsPathExpr ?: return null val item = (pathExpr.type as? TyAdt)?.item ?: return null if (item.containingCrate.origin != PackageOrigin.WORKSPACE) return null val implLookup = ImplLookup.relativeTo(element) when (item) { is RsStructItem -> { val fieldTypes = item.fieldTypes if (fieldTypes.any { it.isMovesByDefault(implLookup) }) return null } is RsEnumItem -> { for (variant in item.variants) { if (variant.fieldTypes.any { it.isMovesByDefault(implLookup) }) return null } } } return DeriveCopyFix(pathExpr) } } }
mit
9b887ae02c428ea6031e0dc5a9705e70
38.670588
125
0.674674
4.490013
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/service/DownloadService.kt
1
10480
package de.tum.`in`.tumcampusapp.service import android.content.Context import android.content.Intent import android.support.v4.app.JobIntentService import android.support.v4.content.LocalBroadcastManager import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.api.app.AuthenticationManager import de.tum.`in`.tumcampusapp.api.app.TUMCabeClient import de.tum.`in`.tumcampusapp.api.app.model.UploadStatus import de.tum.`in`.tumcampusapp.api.tumonline.AccessTokenManager import de.tum.`in`.tumcampusapp.component.ui.cafeteria.controller.CafeteriaMenuManager import de.tum.`in`.tumcampusapp.component.ui.cafeteria.details.CafeteriaViewModel import de.tum.`in`.tumcampusapp.component.ui.cafeteria.model.Location import de.tum.`in`.tumcampusapp.component.ui.cafeteria.repository.CafeteriaLocalRepository import de.tum.`in`.tumcampusapp.component.ui.cafeteria.repository.CafeteriaRemoteRepository import de.tum.`in`.tumcampusapp.component.ui.news.KinoViewModel import de.tum.`in`.tumcampusapp.component.ui.news.NewsController import de.tum.`in`.tumcampusapp.component.ui.news.TopNewsViewModel import de.tum.`in`.tumcampusapp.component.ui.news.repository.KinoLocalRepository import de.tum.`in`.tumcampusapp.component.ui.news.repository.KinoRemoteRepository import de.tum.`in`.tumcampusapp.component.ui.news.repository.TopNewsRemoteRepository import de.tum.`in`.tumcampusapp.component.ui.ticket.EventsController import de.tum.`in`.tumcampusapp.database.TcaDb import de.tum.`in`.tumcampusapp.utils.CacheManager import de.tum.`in`.tumcampusapp.utils.Const import de.tum.`in`.tumcampusapp.utils.NetUtils import de.tum.`in`.tumcampusapp.utils.Utils import de.tum.`in`.tumcampusapp.utils.sync.SyncManager import io.reactivex.disposables.CompositeDisposable import java.io.IOException /** * Service used to download files from external pages */ class DownloadService : JobIntentService() { private lateinit var broadcastManager: LocalBroadcastManager private lateinit var cafeteriaViewModel: CafeteriaViewModel private lateinit var kinoViewModel: KinoViewModel private lateinit var topNewsViewModel: TopNewsViewModel private lateinit var tumCabeClient: TUMCabeClient private lateinit var database: TcaDb private val disposable = CompositeDisposable() override fun onCreate() { super.onCreate() Utils.log("DownloadService service has started") broadcastManager = LocalBroadcastManager.getInstance(this) SyncManager(this) // Starts a new sync in constructor; should be moved to explicit method call tumCabeClient = TUMCabeClient.getInstance(this) database = TcaDb.getInstance(this) val remoteRepository = CafeteriaRemoteRepository remoteRepository.tumCabeClient = tumCabeClient val localRepository = CafeteriaLocalRepository localRepository.db = database cafeteriaViewModel = CafeteriaViewModel(localRepository, remoteRepository, disposable) // Init sync table KinoLocalRepository.db = database KinoRemoteRepository.tumCabeClient = tumCabeClient kinoViewModel = KinoViewModel(KinoLocalRepository, KinoRemoteRepository, disposable) TopNewsRemoteRepository.tumCabeClient = tumCabeClient topNewsViewModel = TopNewsViewModel(TopNewsRemoteRepository, disposable) } override fun onHandleWork(intent: Intent) { Thread { download(intent, this@DownloadService) }.start() } private fun broadcastDownloadSuccess() { sendServiceBroadcast(Const.COMPLETED, null) } private fun broadcastDownloadError(messageResId: Int) { sendServiceBroadcast(Const.ERROR, messageResId) } private fun sendServiceBroadcast(action: String, messageResId: Int?) { val intent = Intent(BROADCAST_NAME).apply { putExtra(Const.ACTION_EXTRA, action) putExtra(Const.MESSAGE, messageResId) } broadcastManager.sendBroadcast(intent) } /** * Download all external data and returns whether the download was successful * * @param force True to force download over normal sync period * @return if all downloads were successful */ private fun downloadAll(force: Boolean): Boolean { uploadMissingIds() val cafeSuccess = downloadCafeterias(force) val kinoSuccess = downloadKino(force) val newsSuccess = downloadNews(force) val eventsSuccess = downloadEvents() val topNewsSuccess = downloadTopNews() return cafeSuccess && kinoSuccess && newsSuccess && topNewsSuccess && eventsSuccess } /** * asks to verify private key, uploads fcm token and obfuscated ids (if missing) */ private fun uploadMissingIds() { val lrzId = Utils.getSetting(this, Const.LRZ_ID, "") val uploadStatus = tumCabeClient.getUploadStatus(lrzId) ?: return Utils.log("upload missing ids: " + uploadStatus.toString()) // upload FCM Token if not uploaded or invalid if (uploadStatus.fcmToken != UploadStatus.UPLOADED) { Utils.log("upload fcm token") AuthenticationManager(this).tryToUploadFcmToken() } if (lrzId.isEmpty()) { return // nothing else to be done } // ask server to verify our key if (uploadStatus.publicKey == UploadStatus.UPLOADED) { // uploaded but not verified Utils.log("ask server to verify key") val keyStatus = tumCabeClient.verifyKey() if (keyStatus?.status != UploadStatus.VERIFIED) { return // we can only upload obfuscated ids if we are verified } } // upload obfuscated ids AuthenticationManager(this).uploadObfuscatedIds(uploadStatus); } private fun downloadCafeterias(force: Boolean): Boolean { CafeteriaMenuManager(this).downloadMenus(force) cafeteriaViewModel.getCafeteriasFromService(force) return true } private fun downloadKino(force: Boolean): Boolean { kinoViewModel.getKinosFromService(force) return true } private fun downloadNews(force: Boolean): Boolean { NewsController(this).downloadFromExternal(force) return true } private fun downloadEvents(): Boolean { EventsController(this).downloadFromService() return true } private fun downloadTopNews() = topNewsViewModel.getNewsAlertFromService(this) /** * Import default location and opening hours from assets */ @Throws(IOException::class) private fun importLocationsDefaults() { val dao = database.locationDao() if (dao.isEmpty) { Utils.readCsv(assets.open(CSV_LOCATIONS)) .map(Location.Companion::fromCSVRow) .forEach(dao::replaceInto) } } override fun onDestroy() { super.onDestroy() disposable.clear() Utils.log("DownloadService service has stopped") } companion object { /** * Download broadcast identifier */ @JvmField val BROADCAST_NAME = "de.tum.in.newtumcampus.intent.action.BROADCAST_DOWNLOAD" private const val LAST_UPDATE = "last_update" private const val CSV_LOCATIONS = "locations.csv" /** * Gets the time when BackgroundService was called last time * * @param context Context * @return time when BackgroundService was executed last time */ @JvmStatic fun lastUpdate(context: Context): Long = Utils.getSettingLong(context, LAST_UPDATE, 0L) /** * Download the data for a specific intent * note, that only one concurrent download() is possible with a static synchronized method! */ @Synchronized private fun download(intent: Intent, service: DownloadService) { val action = intent.getStringExtra(Const.ACTION_EXTRA) ?: return var success = true val force = intent.getBooleanExtra(Const.FORCE_DOWNLOAD, false) val launch = intent.getBooleanExtra(Const.APP_LAUNCHES, false) // Check if device has a internet connection val backgroundServicePermitted = Utils.isBackgroundServicePermitted(service) if (NetUtils.isConnected(service) && (launch || backgroundServicePermitted)) { Utils.logv("Handle action <$action>") when (action) { Const.EVENTS -> success = service.downloadEvents() Const.NEWS -> success = service.downloadNews(force) Const.CAFETERIAS -> success = service.downloadCafeterias(force) Const.KINO -> success = service.downloadKino(force) Const.TOP_NEWS -> success = service.downloadTopNews() else -> { success = service.downloadAll(force) if (AccessTokenManager.hasValidAccessToken(service)) { val cacheManager = CacheManager(service) cacheManager.fillCache() } } } } // Update the last run time saved in shared prefs if (action == Const.DOWNLOAD_ALL_FROM_EXTERNAL) { try { service.importLocationsDefaults() } catch (e: IOException) { Utils.log(e) success = false } if (success) { Utils.setSetting(service, LAST_UPDATE, System.currentTimeMillis()) } success = true } // After done the job, create an broadcast intent and send it. The receivers will be // informed that the download service has finished. Utils.logv("DownloadService was " + (if (success) "" else "not ") + "successful") if (success) { service.broadcastDownloadSuccess() } else { service.broadcastDownloadError(R.string.exception_unknown) } } @JvmStatic fun enqueueWork(context: Context, work: Intent) { Utils.log("Download work enqueued") JobIntentService.enqueueWork(context, DownloadService::class.java, Const.DOWNLOAD_SERVICE_JOB_ID, work) } } }
gpl-3.0
4947b3f5868fcd148ddd614761a7b74f
37.388278
115
0.662118
4.950402
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/lang/core/psi/elements/ElmExposingList.kt
1
6172
package org.elm.lang.core.psi.elements import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.util.PsiTreeUtil import org.elm.lang.core.psi.* import org.elm.lang.core.psi.ElmTypes.* import org.elm.lang.core.stubs.ElmExposingListStub class ElmExposingList : ElmStubbedElement<ElmExposingListStub> { constructor(node: ASTNode) : super(node) constructor(stub: ElmExposingListStub, stubType: IStubElementType<*, *>) : super(stub, stubType) /** * If present, indicates that all names are exposed */ val doubleDot: PsiElement? get() = findChildByType(DOUBLE_DOT) val exposesAll: Boolean get() = stub?.exposesAll ?: (doubleDot != null) /** * Returns the opening parenthesis element. * * This will be non-null in a well-formed program. */ val openParen: PsiElement? get() = findChildByType(LEFT_PARENTHESIS) /** * Returns the closing parenthesis element. * * This will be non-null in a well-formed program. */ val closeParen: PsiElement? get() = findChildByType(RIGHT_PARENTHESIS) /* TODO consider getting rid of the individual [exposedValueList], [exposedTypeList], and [exposedOperatorList] functions in favor of [allExposedItems] */ val exposedValueList: List<ElmExposedValue> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, ElmExposedValue::class.java) val exposedTypeList: List<ElmExposedType> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, ElmExposedType::class.java) val exposedOperatorList: List<ElmExposedOperator> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, ElmExposedOperator::class.java) /** * Returns the list of explicitly exposed items. * * e.g. `a` and `b` in `module Foo exposing (a, b) * * In the case where the module/import exposes *all* names (e.g. `module Foo exposing (..)`) * the returned list will be empty. * * This is the superset of [exposedValueList], [exposedTypeList], and [exposedOperatorList] */ val allExposedItems: List<ElmExposedItemTag> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(this, ElmExposedItemTag::class.java) /** * Returns the module which the exposing list acts upon. * * An exposing list can occur in 2 different contexts: * 1. as part of an import, in which case the target module is given by the import * 2. as part of a module declaration at the top of a file, in which case the * target module is the module itself */ val targetModule: ElmModuleDeclaration? get() { val importClause = this.parentOfType<ElmImportClause>() return if (importClause != null) { importClause.reference.resolve() as? ElmModuleDeclaration } else { this.parentOfType() } } } /** * Attempt to find an [exposed item][ElmExposedItemTag] that refers to [decl]. * * Note that this will not find [union variants][ElmUnionVariant] since, as of Elm 0.19, * they are no longer exposed individually. * * If this function returns null, it doesn't mean that [decl] is not exposed; it just means * that it is not explicitly exposed by name (as opposed to `..` syntax) */ fun ElmExposingList.findMatchingItemFor(decl: ElmExposableTag): ElmExposedItemTag? = allExposedItems.find { it.reference?.isReferenceTo(decl) ?: false } /** * Returns true if [element] is exposed by the receiver, either directly by name or * indirectly by the `..` "expose-all" syntax. */ fun ElmExposingList.exposes(element: ElmExposableTag): Boolean { val module = targetModule ?: return false if (element.elmFile.getModuleDecl() != module) { // this element does not belong to the target module return false } return when { module.exposesAll -> true element is ElmUnionVariant -> exposedTypeList.any { it.exposes(element) } else -> findMatchingItemFor(element) != null } } /** * Add a function/type to the exposing list, while ensuring that the necessary comma and whitespace are also added. * * TODO does this function really belong here in this file? Or should it be moved closer to intention actions? */ fun ElmExposingList.addItem(itemName: String) { // create a dummy import with multiple exposed values so that we can also extract the preceding comma and whitespace val import = ElmPsiFactory(project).createImportExposing("FooBar", listOf("foobar", itemName)) val item = import.exposingList!!.allExposedItems.single { it.text == itemName } val prevComma = item.prevSiblings.first { it.elementType == ElmTypes.COMMA } addRangeBefore(prevComma, item, closeParen) } /** * Remove the item from the exposing list and make sure that whitespace and commas are correctly preserved. * * TODO does this function really belong here in this file? Or should it be moved closer to intention actions? */ fun ElmExposingList.removeItem(item: ElmExposedItemTag) { val nextVisibleLeaf = PsiTreeUtil.nextVisibleLeaf(item) ?: error("incomplete exposing list") require(allExposedItems.size > 1) { "Elm's parser requires that the exposing list between the parens is never empty" } if (nextVisibleLeaf.elementType == RIGHT_PARENTHESIS) { // delete any list junk that precedes the item to remove val junk = item.prevSiblings.adjacentJunk() deleteChildRange(junk.last(), junk.first()) } else { // delete any list junk that follows the item to remove val junk = item.nextSiblings.adjacentJunk() deleteChildRange(junk.first(), junk.last()) } // delete the exposed item itself item.delete() } // When removing an exposed item from the list, adjacent whitespace and comma should also be removed. private fun Sequence<PsiElement>.adjacentJunk(): Sequence<PsiElement> = takeWhile { it is PsiWhiteSpace || it.elementType == ElmTypes.COMMA }
mit
138e10314e5655728322a9af8a7a9895
35.738095
122
0.692644
4.274238
false
false
false
false
klazuka/intellij-elm
src/test/kotlin/org/elm/lang/core/resolve/ElmStdlibImportResolveTest.kt
1
6841
package org.elm.lang.core.resolve /** * Test resolving values and types provided by the elm/core package. * * Special emphasis is put on verifying that the implicit, default imports provided by the Elm compiler * are handled correctly. For the full list of default imports, see: * https://package.elm-lang.org/packages/elm/core/latest/ */ class ElmStdlibImportResolveTest : ElmResolveTestBase() { override fun getProjectDescriptor() = ElmWithStdlibDescriptor // BASICS MODULE fun `test Basics module imported`() = stubOnlyResolve( """ --@ main.elm f = Basics.toFloat 42 --^...Basics.elm """) fun `test Basics exposes all values`() = stubOnlyResolve( """ --@ main.elm f = toFloat 42 --^...Basics.elm """) fun `test Basics exposes all types`() = stubOnlyResolve( """ --@ main.elm type alias Config = { ordering : Order } --^...Basics.elm """) fun `test Basics exposes all constructors`() = stubOnlyResolve( """ --@ main.elm f = LT --^...Basics.elm """) fun `test Basics exposes binary operators`() = stubOnlyResolve( """ --@ main.elm f = 2 + 2 --^...Basics.elm """) fun `test Basics can be shadowed by local definitions`() = stubOnlyResolve( """ --@ main.elm and a b = 0 f = and 1 1 --^...main.elm """) fun `test Basics can be shadowed by explicit imports`() = stubOnlyResolve( """ --@ main.elm import Bitwise exposing (and) f = and 1 1 --^...Bitwise.elm """) // LIST MODULE fun `test List module imported`() = stubOnlyResolve( """ --@ main.elm n = List.length [0, 1, 2] --^...List.elm """) fun `test List cons op exposed`() = stubOnlyResolve( """ --@ main.elm f = 0 :: [] --^...List.elm """) fun `test List doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f = foldl (+) [0,1,2] --^unresolved """) // MAYBE MODULE fun `test Maybe module imported`() = stubOnlyResolve( """ --@ main.elm f x = Maybe.withDefault x 42 --^...Maybe.elm """) fun `test Maybe type exposed`() = stubOnlyResolve( """ --@ main.elm type alias Foo = Maybe Int --^...Maybe.elm """) fun `test Maybe Just exposed`() = stubOnlyResolve( """ --@ main.elm f = Just 42 --^...Maybe.elm """) fun `test Maybe Nothing exposed`() = stubOnlyResolve( """ --@ main.elm f = Nothing --^...Maybe.elm """) fun `test Maybe doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f = withDefault --^unresolved """) // RESULT MODULE fun `test Result module imported`() = stubOnlyResolve( """ --@ main.elm f x = Result.withDefault x 42 --^...Result.elm """) fun `test Result type exposed`() = stubOnlyResolve( """ --@ main.elm type alias Foo = Result String Int --^...Result.elm """) fun `test Result Ok exposed`() = stubOnlyResolve( """ --@ main.elm f = Ok 42 --^...Result.elm """) fun `test Result Err exposed`() = stubOnlyResolve( """ --@ main.elm f = Err "uh oh" --^...Result.elm """) fun `test Result module doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f x = toMaybe x 42 --^unresolved """) // STRING MODULE fun `test String module imported`() = stubOnlyResolve( """ --@ main.elm f x = String.length x --^...String.elm """) fun `test String type exposed`() = stubOnlyResolve( """ --@ main.elm type alias Foo = String --^...String.elm """) fun `test String module doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f = length "hello" --^unresolved """) // CHAR MODULE fun `test Char module imported`() = stubOnlyResolve( """ --@ main.elm f x = Char.isUpper x --^...Char.elm """) fun `test Char type exposed`() = stubOnlyResolve( """ --@ main.elm type alias Foo = Char --^...Char.elm """) fun `test Char module doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f = isUpper 'A' --^unresolved """) // TUPLE MODULE fun `test Tuple module imported`() = stubOnlyResolve( """ --@ main.elm f = Tuple.first (0, 0) --^...Tuple.elm """) fun `test Tuple module doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f = pair 0 0 --^unresolved """) // DEBUG MODULE fun `test Debug module imported`() = stubOnlyResolve( """ --@ main.elm f = Debug.toString --^...Debug.elm """) fun `test Debug module doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f = toString --^unresolved """) // PLATFORM MODULE fun `test Platform module imported`() = stubOnlyResolve( """ --@ main.elm f = Platform.worker --^...Platform.elm """) fun `test Platform module exposes Program type`() = stubOnlyResolve( """ --@ main.elm type alias Foo = Program --^...Platform.elm """) fun `test Platform module doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f = worker --^unresolved """) // PLATFORM.CMD MODULE fun `test Platform Cmd module imported using Cmd alias (module ref)`() = stubOnlyResolve( """ --@ main.elm f = Cmd.none --^...Platform/Cmd.elm """) fun `test Platform Cmd module imported using Cmd alias (value ref)`() = stubOnlyResolve( """ --@ main.elm f = Cmd.none --^...Platform/Cmd.elm """) fun `test Platform Cmd module exposes Cmd type`() = stubOnlyResolve( """ --@ main.elm type alias Foo = Cmd --^...Platform/Cmd.elm """) fun `test Platform Cmd module doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f = batch --^unresolved """) // PLATFORM.SUB MODULE fun `test Platform Sub module imported using Sub alias (module ref)`() = stubOnlyResolve( """ --@ main.elm f = Sub.none --^...Platform/Sub.elm """) fun `test Platform Sub module imported using Sub alias (value ref)`() = stubOnlyResolve( """ --@ main.elm f = Sub.none --^...Platform/Sub.elm """) fun `test Platform Sub module exposes Sub type`() = stubOnlyResolve( """ --@ main.elm type alias Foo = Sub --^...Platform/Sub.elm """) fun `test Platform Sub module doesn't expose anything else`() = stubOnlyResolve( """ --@ main.elm f = batch --^unresolved """) }
mit
52a4c86685faecf295eaca1b1fd3314f
16.958005
103
0.544803
4.178986
false
true
false
false
rocoty/BukkitGenericCommandSystem
src/main/kotlin/okkero/spigotutils/genericcommandsystem/CommandSystemConvenience.kt
1
6351
package okkero.spigotutils.genericcommandsystem import org.bukkit.Bukkit import org.bukkit.command.CommandSender import org.bukkit.entity.Player /** * A specific type of command that maps some or all of its arguments to instances of a given type. * * @param S the type of sender allowed to use this command * @param T the type to map arguments to * @property mapper takes an argument and returns an instance of [T] * @property elementCount the amount of elements this command will at least map. If the amount of arguments supplied by * the sender is less than this value, the command will throw an [IllegalCommandSyntaxException] upon execution. * @property optionalCount the amount of optional elements this command will try to map * @property greedy */ open class TypeCommand<S : CommandSender, T : Any>(senderClass: Class<S>, val mapper: (String) -> T?, val elementCount: Int, val optionalCount: Int = 0, val greedy: Boolean = false, handler: (TypeCommandData<S, T>) -> CommandResult) : Command<S, TypeCommandData<S, T>>(senderClass, handler) { init { if (elementCount <= 0) { throw IllegalArgumentException("elementCount must be a positive integer") } else if (optionalCount !in 0..elementCount) { throw IllegalArgumentException("optionalCount must be between 0 and elmentCount inclusive") } } override fun buildData(args: ArgumentList.MutableDepth): TypeCommandData<S, T> { return TypeCommandData(args, mapper, elementCount, optionalCount, greedy) } } /** * Convenience "constructor" with reified type parameter for TypeCommand * * @param S the type of sender allowed to use this command * @param T the type to map arguments to * @param mapper takes an argument and returns an instance of [T] * @param elementCount the amount of elements this command will at least map. If the amount of arguments supplied by * the sender is less than this value, the command will throw an [IllegalCommandSyntaxException] upon execution. * @param optionalCount the amount of optional elements this command will try to map * @param greedy */ inline fun <reified S : CommandSender, T : Any> TypeCommand(noinline mapper: (String) -> T?, elementCount: Int, optionalCount: Int = 0, greedy: Boolean = false, noinline handler: (TypeCommandData<S, T>) -> CommandResult): TypeCommand<S, T> { return TypeCommand(S::class.java, mapper, elementCount, optionalCount, greedy, handler) } //TODO Need to sit down and rethink the logic here; allow nulls or not?? open class TypeCommandData<S : CommandSender, out T : Any>(args: ArgumentList.MutableDepth, mapper: (String) -> T?, elementCount: Int, optionalCount: Int, greedy: Boolean) : CommandData<S>(args) { private val elements = Array<Any?>(elementCount) { null } val lastOptionalIndex: Int val lastOptionalElement: T get() = getElement(lastOptionalIndex) val elementCount: Int get() = lastOptionalIndex + 1 init { if (args.size < elementCount) { throw IllegalCommandSyntaxException() } val firstOptionalIndex = elementCount - optionalCount var lastOptionalIndex = elementCount - 1 for (i in elements.indices) { val element = mapper(args[0]) if (element == null && !greedy && i >= firstOptionalIndex) { lastOptionalIndex = i - 1 break } elements[i] = element args.addDepth() } this.lastOptionalIndex = lastOptionalIndex } fun getElement(index: Int): T { if (!hasElement(index)) { throw IndexOutOfBoundsException("No mapped element at given index: $index") } return getOptionalElement(index) as T } fun getOptionalElement(index: Int): T? { return elements[index] as T? } fun hasElement(index: Int): Boolean { return index in 0..lastOptionalIndex } } /** * Convenience command that maps some or all arguments to [Player] instances. */ open class TargetCommand<S : CommandSender>(senderClass: Class<S>, elementCount: Int, optionalCount: Int = 0, greedy: Boolean = false, handler: (TypeCommandData<S, Player>) -> CommandResult) : TypeCommand<S, Player>(senderClass, { Bukkit.getPlayer(it) }, elementCount, optionalCount, greedy, handler) /** * Convenience "constructor" with reified type parameter for TargetCommand */ inline fun <reified S : CommandSender> TargetCommand(elementCount: Int, optionalCount: Int = 0, greedy: Boolean = false, noinline handler: (TypeCommandData<S, Player>) -> CommandResult): TargetCommand<S> { return TargetCommand(S::class.java, elementCount, optionalCount, greedy, handler) } /** * Convenience command that maps a single argument to a [Player] instance */ class SingleTargetCommand<S : CommandSender>(senderClass: Class<S>, handler: (SingleTargetCommandData<S>) -> CommandResult) : TargetCommand<S>(senderClass, 1, handler = handler as (TypeCommandData<S, Player>) -> CommandResult) { init { withRule(ArgsSize.equal(1)) } override fun buildData(args: ArgumentList.MutableDepth): SingleTargetCommandData<S> { return SingleTargetCommandData(args) } } /** * Convenience "constructor" with reified type parameter for SingleTargetCommand */ inline fun <reified S : CommandSender> SingleTargetCommand(noinline handler: (SingleTargetCommandData<S>) -> CommandResult): SingleTargetCommand<S> { return SingleTargetCommand(S::class.java, handler) } class SingleTargetCommandData<S : CommandSender>(args: ArgumentList.MutableDepth) : TypeCommandData<S, Player>(args, { Bukkit.getPlayer(it) }, 1, 0, false) { val target: Player get() = getElement(0) }
gpl-3.0
5c3fde48cca77301274abd9589bf6e37
39.980645
119
0.638167
4.58556
false
false
false
false
oleksiyp/mockk
mockk/common/src/test/kotlin/io/mockk/it/PartialArgumentMatchingTest.kt
1
4084
package io.mockk.it import io.mockk.every import io.mockk.spyk import kotlin.test.Test import kotlin.test.assertEquals class PartialArgumentMatchingTest { class ManyArgsOpClass { fun op( a: Boolean = true, b: Boolean = true, c: Byte = 1, d: Byte = 2, e: Short = 3, f: Short = 4, g: Char = 5.toChar(), h: Char = 6.toChar(), i: Int = 7, j: Int = 8, k: Long = 9, l: Long = 10, m: Float = 10.0f, n: Float = 11.0f, o: Double = 12.0, p: Double = 13.0, q: String = "14", r: String = "15", s: IntWrapper = IntWrapper(16), t: IntWrapper = IntWrapper(17) ): Double { return a.toInt() * -1 + b.toInt() * -2 + c + d + e + f + g.toByte() + h.toByte() + i + j + k + l + m + n + o + p + q.toInt() + r.toInt() + s.data + t.data } private fun Boolean.toInt() = if (this) 1 else 0 data class IntWrapper(val data: Int) } val spy = spyk(ManyArgsOpClass()) @Test fun passThrough() { assertEquals(160.0, spy.op()) } @Test fun allAny() { every { spy.op(allAny()) } returns 1.0 assertEquals(1.0, spy.op()) } @Test fun firstBooleanArg() { every { spy.op(a = eq(false)) } returns 1.0 assertEquals(1.0, spy.op(a = false)) } @Test fun secondBooleanArg() { every { spy.op(b = eq(false)) } returns 1.0 assertEquals(1.0, spy.op(b = false)) } @Test fun firstByteArg() { every { spy.op(c = 5.toByte()) } returns 1.0 assertEquals(1.0, spy.op(c = 5.toByte())) } @Test fun secondByteArg() { every { spy.op(d = 5.toByte()) } returns 1.0 assertEquals(1.0, spy.op(d = 5.toByte())) } @Test fun firstShortArg() { every { spy.op(e = 5) } returns 1.0 assertEquals(1.0, spy.op(e = 5)) } @Test fun secondShortArg() { every { spy.op(f = 5) } returns 1.0 assertEquals(1.0, spy.op(f = 5)) } @Test fun firstCharArg() { every { spy.op(g = 3.toChar()) } returns 1.0 assertEquals(1.0, spy.op(g = 3.toChar())) } @Test fun secondCharArg() { every { spy.op(h = 3.toChar()) } returns 1.0 assertEquals(1.0, spy.op(h = 3.toChar())) } @Test fun firstIntArg() { every { spy.op(i = 5) } returns 1.0 assertEquals(1.0, spy.op(i = 5)) } @Test fun secondIntArg() { every { spy.op(j = 5) } returns 1.0 assertEquals(1.0, spy.op(j = 5)) } @Test fun firstLongArg() { every { spy.op(k = 5) } returns 1.0 assertEquals(1.0, spy.op(k = 5)) } @Test fun secondLongArg() { every { spy.op(k = 5) } returns 1.0 assertEquals(1.0, spy.op(k = 5)) } @Test fun firstFloatArg() { every { spy.op(m = 5f) } returns 1.0 assertEquals(1.0, spy.op(m = 5f)) } @Test fun secondFloatArg() { every { spy.op(n = 5f) } returns 1.0 assertEquals(1.0, spy.op(n = 5f)) } @Test fun firstDoubleArg() { every { spy.op(o = 5.0) } returns 1.0 assertEquals(1.0, spy.op(o = 5.0)) } @Test fun secondDoubleArg() { every { spy.op(p = 5.0) } returns 1.0 assertEquals(1.0, spy.op(p = 5.0)) } @Test fun firstStringArg() { every { spy.op(q = "5") } returns 1.0 assertEquals(1.0, spy.op(q = "5")) } @Test fun secondStringArg() { every { spy.op(r = "5") } returns 1.0 assertEquals(1.0, spy.op(r = "5")) } @Test fun firstIntWrapperArg() { every { spy.op(s = ManyArgsOpClass.IntWrapper(5)) } returns 1.0 assertEquals(1.0, spy.op(s = ManyArgsOpClass.IntWrapper(5))) } @Test fun secondIntWrapperArg() { every { spy.op(t = ManyArgsOpClass.IntWrapper(5)) } returns 1.0 assertEquals(1.0, spy.op(t = ManyArgsOpClass.IntWrapper(5))) } }
apache-2.0
e57457fb4e738a3b6c93f46c02ed130b
19.736041
94
0.501714
3.136713
false
true
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/debugger/LuaLineBreakpointType.kt
2
1272
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.debugger import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.xdebugger.breakpoints.XLineBreakpointTypeBase import com.tang.intellij.lua.lang.LuaFileType /** * * Created by tangzx on 2016/12/30. */ class LuaLineBreakpointType : XLineBreakpointTypeBase(ID, NAME, LuaDebuggerEditorsProvider()) { override fun canPutAt(file: VirtualFile, line: Int, project: Project): Boolean { return file.fileType === LuaFileType.INSTANCE } companion object { private const val ID = "lua-line" private const val NAME = "lua-line-breakpoint" } }
apache-2.0
0e470a9500c5f56684d975c981bcacd5
31.615385
95
0.738208
4.025316
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/author/bibliography/AuthorBibliographyFragment.kt
2
8262
package ru.fantlab.android.ui.modules.author.bibliography import android.content.Context import android.os.Bundle import androidx.annotation.StringRes import android.view.View import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.micro_grid_refresh_list.* import kotlinx.android.synthetic.main.state_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.ContextMenuBuilder import ru.fantlab.android.data.dao.model.* import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.helper.InputHelper import ru.fantlab.android.helper.PrefGetter import ru.fantlab.android.ui.adapter.viewholder.CycleViewHolder import ru.fantlab.android.ui.adapter.viewholder.CycleWorkViewHolder import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.modules.author.AuthorPagerMvp import ru.fantlab.android.ui.modules.work.WorkPagerActivity import ru.fantlab.android.ui.widgets.dialog.ContextMenuDialogView import ru.fantlab.android.ui.widgets.dialog.RatingDialogView import ru.fantlab.android.ui.widgets.treeview.TreeNode import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter import java.util.* import kotlin.collections.ArrayList class AuthorBibliographyFragment : BaseFragment<AuthorBibliographyMvp.View, AuthorBibliographyPresenter>(), AuthorBibliographyMvp.View { private var countCallback: AuthorPagerMvp.View? = null private lateinit var adapter: TreeViewAdapter private var cycles: WorksBlocks? = null private var works: WorksBlocks? = null override fun fragmentLayout() = R.layout.micro_grid_refresh_list override fun providePresenter() = AuthorBibliographyPresenter() override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) { stateLayout.setEmptyText(R.string.no_bibliography) stateLayout.setOnReloadListener(this) refresh.setOnRefreshListener(this) recycler.setEmptyView(stateLayout, refresh) presenter.onFragmentCreated(arguments!!) } override fun onInitViews(cycles: WorksBlocks?, works: WorksBlocks?) { this.cycles = cycles this.works = works val ids = ArrayList<WorksBlocks.Work>() val workIds = arrayListOf<Int>() this.cycles?.worksBlocks?.map { ids.addAll(it.list) } this.works?.worksBlocks?.map { ids.addAll(it.list) } ids.filter { it.id != null }.map { workIds.add(it.id!!) } if (isLoggedIn()) { presenter.getMarks(PrefGetter.getLoggedUser()!!.id, workIds) } else { initAdapter(this.cycles, works, null) } } override fun onGetMarks(marks: ArrayList<MarkMini>) { initAdapter(cycles, works, marks) } private fun initAdapter(bibliography: WorksBlocks?, works: WorksBlocks?, marks: ArrayList<MarkMini>?) { hideProgress() val nodes = arrayListOf<TreeNode<*>>() extractListData(bibliography, nodes, marks) extractListData(works, nodes, marks) adapter = TreeViewAdapter(nodes, Arrays.asList(CycleWorkViewHolder(), CycleViewHolder())) if (recycler.adapter != null) recycler.adapter!!.notifyDataSetChanged() else recycler.adapter = adapter adapter.setOnTreeNodeListener(object : TreeViewAdapter.OnTreeNodeListener { override fun onSelected(extra: Int, add: Boolean) { } override fun onClick(node: TreeNode<*>, holder: RecyclerView.ViewHolder): Boolean { if (!node.isLeaf) { onToggle(!node.isExpand, holder) } else { val cycleWork = (node.content as CycleWork) val title = if (cycleWork.name.isNotEmpty()) { if (cycleWork.nameOrig.isNotEmpty()) { String.format("%s / %s", cycleWork.name, cycleWork.nameOrig) } else { cycleWork.name } } else { cycleWork.nameOrig } if (cycleWork.id ?: 0 != 0 ) WorkPagerActivity.startActivity(context!!, cycleWork.id!!, title, 0) } return false } override fun onToggle(isExpand: Boolean, holder: RecyclerView.ViewHolder) { val dirViewHolder = holder as CycleViewHolder.ViewHolder val ivArrow = dirViewHolder.ivArrow val rotateDegree = if (isExpand) 90.0f else -90.0f ivArrow.animate().rotationBy(rotateDegree) .start() } }) adapter.setListener(presenter) fastScroller.attachRecyclerView(recycler) } private fun extractListData(bibliography: WorksBlocks?, nodes: ArrayList<TreeNode<*>>, marks: ArrayList<MarkMini>?) { bibliography?.worksBlocks?.sortedWith(compareBy { it.id })?.forEach { worksBlock -> val app = TreeNode(Cycle(worksBlock.title)) nodes.add(app) worksBlock.list.forEachIndexed { subIndex, work -> val name = if (!work.name.isNullOrEmpty()) { if (!work.nameOrig.isNullOrEmpty()) { String.format("%s / %s", work.name, work.nameOrig) } else { work.name } } else { work.nameOrig } if (work.children != null) { val apps = TreeNode(Cycle(name ?: "")) app.addChild(apps) work.children.forEach { item -> val mark = marks?.map { it }?.filter { it.work_id == item.id } app.childList[subIndex].addChild(TreeNode(CycleWork( item.id, item.authors.asSequence().map { it.name }.toList(), item.name, item.nameOrig, item.description, item.year, item.responses, item.votersCount, item.rating, if (mark != null && mark.isNotEmpty()) mark.first().mark else null, if (mark != null && mark.isNotEmpty()) mark.first().user_work_classif_flag else 0 )) ) } } else { val mark = marks?.map { it }?.filter { it.work_id == work.id } app.addChild(TreeNode(CycleWork( work.id, work.authors.asSequence().map { it.name }.toList(), work.name ?: "", work.nameOrig ?: "", work.description, work.year, work.responseCount, work.votersCount, work.rating, if (mark != null && mark.isNotEmpty()) mark.first().mark else null, if (mark != null && mark.isNotEmpty()) mark.first().user_work_classif_flag else 0 )) ) } } } } override fun onItemLongClicked(item: TreeNode<*>, position: Int) { if (isLoggedIn() && item.content is CycleWork) { val dialogView = ContextMenuDialogView() dialogView.initArguments("main", ContextMenuBuilder.buildForMarks(recycler.context), item.content as CycleWork, position) dialogView.show(childFragmentManager, "ContextMenuDialogView") } } override fun onItemSelected(parent: String, item: ContextMenus.MenuItem, position: Int, listItem: Any) { listItem as CycleWork when (item.id) { "revote" -> { RatingDialogView.newInstance(10, listItem.mark?.toFloat() ?: 0.0f, listItem, "${listItem.authors[0]} - ${if (!InputHelper.isEmpty(listItem.name)) listItem.name else listItem.nameOrig}", position ).show(childFragmentManager, RatingDialogView.TAG) } "delete" -> { presenter.onSendMark(listItem.id!!, 0, position) } } } override fun onRated(rating: Float, listItem: Any, position: Int) { presenter.onSendMark((listItem as CycleWork).id!!, rating.toInt(), position) } override fun onSetMark(position: Int, mark: Int) { hideProgress() (adapter.getItem(position) as CycleWork).mark = mark adapter.notifyItemChanged(position) } override fun showProgress(@StringRes resId: Int, cancelable: Boolean) { refresh.isRefreshing = true stateLayout.showProgress() } override fun hideProgress() { refresh.isRefreshing = false stateLayout.showReload(recycler.adapter?.itemCount ?: 0) } override fun showErrorMessage(msgRes: String?) { hideProgress() super.showErrorMessage(msgRes) } override fun showMessage(titleRes: Int, msgRes: Int) { hideProgress() super.showMessage(titleRes, msgRes) } companion object { fun newInstance(authorId: Int): AuthorBibliographyFragment { val view = AuthorBibliographyFragment() view.arguments = Bundler.start().put(BundleConstant.EXTRA, authorId).end() return view } } override fun onRefresh() { presenter.onFragmentCreated(arguments!!) } override fun onClick(v: View?) { onRefresh() } override fun onAttach(context: Context) { super.onAttach(context) if (context is AuthorPagerMvp.View) { countCallback = context } } override fun onDetach() { countCallback = null super.onDetach() } }
gpl-3.0
8468688400470cd20453fb83ebfb0150
30.538168
124
0.709756
3.657371
false
false
false
false
Hentioe/BloggerMini
app/src/main/kotlin/io/bluerain/tweets/data/models/CommentModel.kt
1
2049
package io.bluerain.tweets.data.models import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import java.text.SimpleDateFormat import java.util.* /** * Created by hentioe on 17-5-8. * 评论模型 */ data class CommentModel( var id: Long = 0, var content: String = "", @SerializedName("author_nickname") var nickname: String = "", @SerializedName("author_email") var email: String = "", @SerializedName("author_face") var face: String = "", var site: String = "", var top: Long = -1L, @SerializedName("cor_res_type") var resType: Int = 0, @SerializedName("cor_res_id") var resId: Long = 0, @SerializedName("reply_to") var replyTo: Long = -1L, @SerializedName("create_at") var createAt: Date = Date(), @SerializedName("update_at") var updateAt: Date = Date(), @SerializedName("resource_status") var resourceStatus: Int = 0 ) data class CommentJsonModel( var content: String = "", @SerializedName("author_nickname") var nickname: String = "", @SerializedName("author_email") var email: String = "", @SerializedName("author_face") var face: String = "", @SerializedName("reply_to") var replyTo: Long = -1L, var site: String = "" ) private val dateFormat = SimpleDateFormat("MM/dd/yyyy", Locale.CHINA) private val timeFormat = SimpleDateFormat("HH:mm", Locale.CHINA) fun CommentModel.fromToString(): String = when (this.resType) { 0 -> "发表见解" 1 -> "进行回复" 2 -> "给你指点" else -> "?未知类型" } fun CommentModel.timeToString(): String { val date = dateFormat.format(this.createAt) val time = timeFormat.format(this.createAt) return "$date $time" } fun CommentModel.statusToString(): String = when (this.resourceStatus) { 0 -> "正常" 1 -> "被隐藏" else -> "未知状态" } fun CommentModel.isTop(): Boolean = this.top > 0 fun CommentModel.isNormal(): Boolean = this.resourceStatus == 0
gpl-3.0
a6be40a4cb72d77241237aa6e6cc980a
31.655738
72
0.642391
3.770833
false
false
false
false
JakeWharton/Reagent
reagent/common/src/test/kotlin/reagent/operator/ObservableDropWhileTest.kt
1
1645
package reagent.operator import reagent.runTest import reagent.source.emptyObservable import reagent.source.observable import reagent.source.observableOf import reagent.tester.testObservable import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.fail class ObservableDropWhileTest { @Test fun empty() = runTest { emptyObservable() .dropWhile { fail() } .testObservable { complete() } } @Test fun dropAll() = runTest { var called = 0 observableOf(1, 2, 3) .dropWhile { called++; true } .testObservable { complete() } assertEquals(3, called) } @Test fun dropSome() = runTest { observableOf(1, 2, 3) .dropWhile { it < 2 } .testObservable { item(2) item(3) complete() } } @Test fun dropNone() = runTest { var called = 0 observableOf(1, 2, 3) .dropWhile { called++; false } .testObservable { item(1) item(2) item(3) complete() } assertEquals(1, called) } @Test fun dropThrowing() = runTest { val exception = RuntimeException("Oops!") observableOf(1, 2, 3) .dropWhile { throw exception } .testObservable { error(exception) } } @Test fun emitterReturnValue() = runTest { val emits = mutableListOf<Boolean>() observable<Int> { for (i in 1..4) { emits.add(it(i)) } }.dropWhile { it < 3 }.take(1).testObservable { item(3) complete() } assertEquals(listOf(true, true, true, false), emits) } }
apache-2.0
7321ab0158875ef93b5ccbe4dfcea9a8
20.933333
56
0.57386
4.122807
false
true
false
false
JavaEden/Orchid
plugins/OrchidSourceDoc/src/main/kotlin/com/eden/orchid/sourcedoc/page/SourceDocPage.kt
1
3231
package com.eden.orchid.sourcedoc.page import com.copperleaf.kodiak.common.AutoDocument import com.copperleaf.kodiak.common.RichTextComponent.Companion.TYPE_NAME import com.copperleaf.kodiak.common.DocElement import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.theme.assets.AssetManagerDelegate import com.eden.orchid.api.theme.components.ComponentHolder import com.eden.orchid.sourcedoc.functions.SourcedocAnchorFunction import com.eden.orchid.utilities.OrchidUtils class SourceDocPage<T : DocElement>( resource: SourceDocResource<*>, val element: T, key: String, title: String, moduleType: String, moduleGroup: String, module: String, moduleSlug: String ) : BaseSourceDocPage( resource, key, title, moduleType, moduleGroup, module, moduleSlug ) { override val itemIds = listOf(element.id, element.name) @Option @Description( "Components to inject into SourceDocPages to provide additional info or context about the element." ) lateinit var summaryComponents: ComponentHolder override fun getComponentHolders(): Array<ComponentHolder> { return super.getComponentHolders() + summaryComponents } override fun getTemplates(): List<String> { return listOf( "${generator.key.decapitalize()}${element.kind.capitalize()}", "sourceDocPage" ) } override fun loadAssets(delegate: AssetManagerDelegate): Unit = with(delegate) { addCss("assets/css/orchidSourceDoc.scss") } fun getRootSection(): Section { return Section(null, title, listOf(element)) } fun getSectionsData(element: DocElement): List<Section> { if (element is AutoDocument) { return element .nodes .filter { it.elements.isNotEmpty() } .map { Section(element, it.name, it.elements) } } return emptyList() } fun renderComment(element: DocElement): String { return element .comment .components .map { if (it.kind == TYPE_NAME) { SourcedocAnchorFunction.getLinkToSourcedocPage(context, this, it.text, it.value ?: "") } else { it.text } } .joinToString("") } fun sectionId(section: Section): String { return if(section.parent != null && section.parent !== element) { OrchidUtils.sha1("${unhashedElementId(section.parent)}_${section.name}") } else { section.name } } fun elementId(element: DocElement): String { return OrchidUtils.sha1(unhashedElementId(element)) } private fun unhashedElementId(element: DocElement): String { return element.signature.joinToString("_") { it.text } } data class Section( val parent: DocElement?, val name: String, val elements: List<DocElement>, val hasDescendants: Boolean = elements.any { it is AutoDocument && it.nodes.any { node -> node.elements.isNotEmpty() } } ) }
lgpl-3.0
ec0f865e9ab3508987dd4781f8ed1644
29.196262
128
0.638193
4.407913
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/dashboard/kpi/adapter/MyViewPagerAdapter.kt
1
1358
package com.intfocus.template.dashboard.kpi.adapter import android.content.Context import android.support.v4.view.PagerAdapter import android.view.View import android.view.ViewGroup /** * Created by CANC on 2017/7/28. */ class MyViewPagerAdapter(private var views: List<View>, private val context: Context) : PagerAdapter() { private var isInfiniteLoop = false fun setData(datas: List<View>) { this.views = views this.notifyDataSetChanged() } //获取真实的position fun getRealPosition(position: Int): Int = if (isInfiniteLoop) position % views.size else position override fun getCount(): Int { return if (views.isEmpty()) { 0 } else { if (isInfiniteLoop) Integer.MAX_VALUE else views.size } } override fun isViewFromObject(arg0: View, arg1: Any): Boolean = arg0 === arg1 //展示的view override fun instantiateItem(container: ViewGroup, position: Int): Any { //获得展示的view val view = views[position] //添加到容器 container.addView(view) //返回显示的view return view } //销毁view override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { //从容器中移除view container.removeView(`object` as View) } }
gpl-3.0
b17325e061c8828cb8da101e421fc3df
25.44898
104
0.643519
4.062696
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/completion/providers/XPathAtomicOrUnionTypeProvider.kt
1
6661
/* * Copyright (C) 2019 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xpath.completion.providers import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.lookup.LookupElement import com.intellij.psi.PsiElement import com.intellij.util.ProcessingContext import uk.co.reecedunn.intellij.plugin.core.completion.CompletionProviderEx import uk.co.reecedunn.intellij.plugin.intellij.lang.W3C import uk.co.reecedunn.intellij.plugin.intellij.lang.XmlSchemaSpec import uk.co.reecedunn.intellij.plugin.intellij.lang.defaultProductVersion import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpath.completion.lookup.XPathAtomicOrUnionTypeLookup import uk.co.reecedunn.intellij.plugin.xpath.completion.property.XPathCompletionProperty object XPathAtomicOrUnionTypeProvider : CompletionProviderEx { private const val XS_NAMESPACE_URI = "http://www.w3.org/2001/XMLSchema" private fun createXsd10Types(prefix: String?): List<LookupElement> = listOf( XPathAtomicOrUnionTypeLookup("anyAtomicType", prefix), // XSD 1.1 type supported in XPath/XQuery XPathAtomicOrUnionTypeLookup("anySimpleType", prefix), XPathAtomicOrUnionTypeLookup("anyURI", prefix), XPathAtomicOrUnionTypeLookup("base64Binary", prefix), XPathAtomicOrUnionTypeLookup("boolean", prefix), XPathAtomicOrUnionTypeLookup("byte", prefix), XPathAtomicOrUnionTypeLookup("date", prefix), XPathAtomicOrUnionTypeLookup("dateTime", prefix), XPathAtomicOrUnionTypeLookup("dayTimeDuration", prefix), // XSD 1.1 type supported in XPath/XQuery XPathAtomicOrUnionTypeLookup("decimal", prefix), XPathAtomicOrUnionTypeLookup("double", prefix), XPathAtomicOrUnionTypeLookup("duration", prefix), XPathAtomicOrUnionTypeLookup("ENTITY", prefix), XPathAtomicOrUnionTypeLookup("float", prefix), XPathAtomicOrUnionTypeLookup("gDay", prefix), XPathAtomicOrUnionTypeLookup("gMonth", prefix), XPathAtomicOrUnionTypeLookup("gMonthDay", prefix), XPathAtomicOrUnionTypeLookup("gYear", prefix), XPathAtomicOrUnionTypeLookup("gYearMonth", prefix), XPathAtomicOrUnionTypeLookup("hexBinary", prefix), XPathAtomicOrUnionTypeLookup("ID", prefix), XPathAtomicOrUnionTypeLookup("IDREF", prefix), XPathAtomicOrUnionTypeLookup("int", prefix), XPathAtomicOrUnionTypeLookup("integer", prefix), XPathAtomicOrUnionTypeLookup("language", prefix), XPathAtomicOrUnionTypeLookup("long", prefix), XPathAtomicOrUnionTypeLookup("Name", prefix), XPathAtomicOrUnionTypeLookup("NCName", prefix), XPathAtomicOrUnionTypeLookup("negativeInteger", prefix), XPathAtomicOrUnionTypeLookup("NMTOKEN", prefix), XPathAtomicOrUnionTypeLookup("nonNegativeInteger", prefix), XPathAtomicOrUnionTypeLookup("nonPositiveInteger", prefix), XPathAtomicOrUnionTypeLookup("normalizedString", prefix), XPathAtomicOrUnionTypeLookup("NOTATION", prefix), XPathAtomicOrUnionTypeLookup("numeric", prefix), XPathAtomicOrUnionTypeLookup("positiveInteger", prefix), XPathAtomicOrUnionTypeLookup("QName", prefix), XPathAtomicOrUnionTypeLookup("short", prefix), XPathAtomicOrUnionTypeLookup("string", prefix), XPathAtomicOrUnionTypeLookup("time", prefix), XPathAtomicOrUnionTypeLookup("token", prefix), XPathAtomicOrUnionTypeLookup("unsignedByte", prefix), XPathAtomicOrUnionTypeLookup("unsignedInt", prefix), XPathAtomicOrUnionTypeLookup("unsignedLong", prefix), XPathAtomicOrUnionTypeLookup("unsignedShort", prefix), XPathAtomicOrUnionTypeLookup("untypedAtomic", prefix), XPathAtomicOrUnionTypeLookup("yearMonthDuration", prefix) // XSD 1.1 type supported in XPath/XQuery ) private fun createXsd11Types(prefix: String?): List<LookupElement> = listOf( XPathAtomicOrUnionTypeLookup("dateTimeStamp", prefix), XPathAtomicOrUnionTypeLookup("error", prefix) ) private fun addXsdTypes(context: ProcessingContext, result: CompletionResultSet, prefix: String?) { val product = context[XPathCompletionProperty.XPATH_PRODUCT] ?: W3C.SPECIFICATIONS val version = context[XPathCompletionProperty.XPATH_PRODUCT_VERSION] ?: defaultProductVersion(product) if (product.conformsTo(version, XmlSchemaSpec.REC_1_0_20041028)) result.addAllElements(createXsd10Types(prefix)) if (product.conformsTo(version, XmlSchemaSpec.REC_1_1_20120405)) result.addAllElements(createXsd11Types(prefix)) } override fun apply(element: PsiElement, context: ProcessingContext, result: CompletionResultSet) { val namespaces = context[XPathCompletionProperty.STATICALLY_KNOWN_NAMESPACES] val prefix = namespaces.find { it.namespaceUri?.data == XS_NAMESPACE_URI } ?: return val prefixName = prefix.namespacePrefix?.data val qname = element.parent as XsQNameValue when (qname.completionType(element)) { EQNameCompletionType.QNamePrefix, EQNameCompletionType.NCName -> { addXsdTypes(context, result, prefixName) val defaultNamespace = context[XPathCompletionProperty.DEFAULT_TYPE_NAMESPACE] if (defaultNamespace?.namespaceUri?.data == XS_NAMESPACE_URI) { addXsdTypes(context, result, null) // The XMLSchema namespace is the default type namespace. } } EQNameCompletionType.QNameLocalName -> { if (qname.prefix?.data == prefixName) { addXsdTypes(context, result, null) // Prefix already specified. } } EQNameCompletionType.URIQualifiedNameLocalName -> { if (qname.namespace?.data == XS_NAMESPACE_URI) { addXsdTypes(context, result, null) // Prefix already specified. } } else -> { } } } }
apache-2.0
e503bcf613cf82944a62db93dab8e506
52.288
120
0.720763
4.645049
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xslt/main/uk/co/reecedunn/intellij/plugin/xslt/lang/XsltSpec.kt
1
2505
/* * Copyright (C) 2021 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.xslt.lang import com.intellij.navigation.ItemPresentation import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationType import uk.co.reecedunn.intellij.plugin.xpm.lang.XpmSpecificationVersion import uk.co.reecedunn.intellij.plugin.xpm.lang.impl.W3CSpecification import uk.co.reecedunn.intellij.plugin.xpm.resources.XpmIcons import javax.swing.Icon @Suppress("MemberVisibilityCanBePrivate") object XsltSpec : ItemPresentation, XpmSpecificationType { // region ItemPresentation override fun getPresentableText(): String = "XSL Transformations (XSLT)" override fun getLocationString(): String? = null override fun getIcon(unused: Boolean): Icon = XpmIcons.W3.Product // endregion // region XpmSpecificationType override val id: String = "xslt" override val presentation: ItemPresentation get() = this // endregion // region Versions val REC_1_0_19991116: XpmSpecificationVersion = W3CSpecification( this, "1.0-19991116", "1.0", "http://www.w3.org/TR/1999/REC-xslt-19991116/" ) val REC_2_0_20070123: XpmSpecificationVersion = W3CSpecification( this, "2.0-20070123", "2.0", "http://www.w3.org/TR/2007/REC-xslt20-20070123/" ) val REC_3_0_20170608: XpmSpecificationVersion = W3CSpecification( this, "3.0-20170608", "3.0", "https://www.w3.org/TR/2017/REC-xslt-30-20170608/" ) val ED_4_0_20210113: XpmSpecificationVersion = W3CSpecification( this, "4.0-20210113", "4.0 (Editor's Draft 13 January 2021)", "https://qt4cg.org/branch/master/xslt-40/Overview.html" ) val versions: List<XpmSpecificationVersion> = listOf( REC_1_0_19991116, REC_2_0_20070123, REC_3_0_20170608, ED_4_0_20210113 ) // endregion }
apache-2.0
aa69bd64d895d52225cabbf0b5a37408
29.54878
76
0.687425
3.705621
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/activities/BaseActivity.kt
1
10467
package com.habitrpg.android.habitica.ui.activities import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.res.Configuration import android.content.res.Resources import android.graphics.Bitmap import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import androidx.lifecycle.lifecycleScope import androidx.preference.PreferenceManager import com.habitrpg.android.habitica.HabiticaApplication import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.common.habitica.extensions.getThemeColor import com.habitrpg.common.habitica.extensions.isUsingNightModeResources import com.habitrpg.android.habitica.extensions.updateStatusBarColor import com.habitrpg.android.habitica.helpers.NotificationsManager import com.habitrpg.android.habitica.helpers.ExceptionHandler import com.habitrpg.android.habitica.interactors.ShowNotificationInteractor import com.habitrpg.android.habitica.proxy.AnalyticsManager import com.habitrpg.android.habitica.ui.helpers.ToolbarColorHelper import com.habitrpg.android.habitica.ui.views.dialogs.HabiticaAlertDialog import com.habitrpg.common.habitica.extensions.getThemeColor import com.habitrpg.common.habitica.extensions.isUsingNightModeResources import com.habitrpg.common.habitica.helpers.LanguageHelper import io.reactivex.rxjava3.disposables.CompositeDisposable import kotlinx.coroutines.launch import java.util.Date import java.util.Locale import javax.inject.Inject abstract class BaseActivity : AppCompatActivity() { @Inject lateinit var notificationsManager: NotificationsManager @Inject lateinit var userRepository: UserRepository @Inject internal lateinit var analyticsManager: AnalyticsManager private var currentTheme: String? = null private var isNightMode: Boolean = false internal var forcedTheme: String? = null internal var forcedIsNight: Boolean? = null private var destroyed: Boolean = false open var overrideModernHeader: Boolean? = null internal var toolbar: Toolbar? = null protected abstract fun getLayoutResId(): Int open fun getContentView(): View { return (getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(getLayoutResId(), null) } var compositeSubscription = CompositeDisposable() private val habiticaApplication: HabiticaApplication get() = application as HabiticaApplication var isActivityVisible = false override fun isDestroyed(): Boolean { return destroyed } override fun onCreate(savedInstanceState: Bundle?) { val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) val languageHelper = LanguageHelper(sharedPreferences.getString("language", "en")) resources.forceLocale(this, languageHelper.locale) delegate.localNightMode = when (sharedPreferences.getString("theme_mode", "system")) { "light" -> AppCompatDelegate.MODE_NIGHT_NO "dark" -> AppCompatDelegate.MODE_NIGHT_YES else -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM } isNightMode = isUsingNightModeResources() loadTheme(sharedPreferences) super.onCreate(savedInstanceState) habiticaApplication injectActivity(HabiticaBaseApplication.userComponent) setContentView(getContentView()) compositeSubscription = CompositeDisposable() compositeSubscription.add(notificationsManager.displayNotificationEvents.subscribe( { if (ShowNotificationInteractor(this, lifecycleScope).handleNotification(it)) { lifecycleScope.launch(ExceptionHandler.coroutine()) { userRepository.retrieveUser(false, true) } } }, ExceptionHandler.rx() )) } override fun onRestart() { super.onRestart() val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) val languageHelper = LanguageHelper(sharedPreferences.getString("language", "en")) resources.forceLocale(this, languageHelper.locale) } override fun onResume() { super.onResume() isActivityVisible = true loadTheme(PreferenceManager.getDefaultSharedPreferences(this)) } override fun onPause() { isActivityVisible = false super.onPause() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { onBackPressed() return true } } return super.onOptionsItemSelected(item) } internal open fun loadTheme(sharedPreferences: SharedPreferences, forced: Boolean = false) { val theme = forcedTheme ?: sharedPreferences.getString("theme_name", "purple") if (theme != currentTheme || forced) { if (forcedIsNight ?: isNightMode) { setTheme( when (theme) { "maroon" -> R.style.MainAppTheme_Maroon_Dark "red" -> R.style.MainAppTheme_Red_Dark "orange" -> R.style.MainAppTheme_Orange_Dark "yellow" -> R.style.MainAppTheme_Yellow_Dark "green" -> R.style.MainAppTheme_Green_Dark "teal" -> R.style.MainAppTheme_Teal_Dark "blue" -> R.style.MainAppTheme_Blue_Dark else -> R.style.MainAppTheme_Dark } ) } else { setTheme( when (theme) { "maroon" -> R.style.MainAppTheme_Maroon "red" -> R.style.MainAppTheme_Red "orange" -> R.style.MainAppTheme_Orange "yellow" -> R.style.MainAppTheme_Yellow "green" -> R.style.MainAppTheme_Green "teal" -> R.style.MainAppTheme_Teal "blue" -> R.style.MainAppTheme_Blue "taskform" -> R.style.MainAppTheme_TaskForm else -> R.style.MainAppTheme } ) } } window.navigationBarColor = if (forcedIsNight ?: isNightMode) { ContextCompat.getColor(this, R.color.system_bars) } else { getThemeColor(R.attr.colorPrimaryDark) } if (!(forcedIsNight ?: isNightMode)) { window.updateStatusBarColor(getThemeColor(R.attr.headerBackgroundColor), true) } if (currentTheme != null && theme != currentTheme) { reload() } else { currentTheme = theme } } protected abstract fun injectActivity(component: UserComponent?) protected fun setupToolbar(toolbar: Toolbar?) { this.toolbar = toolbar if (toolbar != null) { setSupportActionBar(toolbar) val actionBar = supportActionBar if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true) actionBar.setDisplayShowHomeEnabled(true) actionBar.setDisplayShowTitleEnabled(true) actionBar.setDisplayUseLogoEnabled(false) actionBar.setHomeButtonEnabled(true) } } toolbar?.let { ToolbarColorHelper.colorizeToolbar(it, this) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { val ret = super.onCreateOptionsMenu(menu) toolbar?.let { ToolbarColorHelper.colorizeToolbar(it, this) } return ret } override fun onDestroy() { destroyed = true if (!compositeSubscription.isDisposed) { compositeSubscription.dispose() } super.onDestroy() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) val newNightMode = isUsingNightModeResources() if (newNightMode != isNightMode) { isNightMode = newNightMode val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this) loadTheme(sharedPreferences, true) } } open fun showConnectionProblem(title: String?, message: String) { val alert = HabiticaAlertDialog(this) alert.setTitle(title) alert.setMessage(message) alert.addButton(android.R.string.ok, isPrimary = true, isDestructive = false, function = null) alert.enqueue() } open fun hideConnectionProblem() { } fun shareContent(identifier: String, message: String, image: Bitmap? = null) { analyticsManager.logEvent("shared", bundleOf(Pair("identifier", identifier))) val sharingIntent = Intent(Intent.ACTION_SEND) sharingIntent.type = "*/*" sharingIntent.putExtra(Intent.EXTRA_TEXT, message) if (image != null) { val path = MediaStore.Images.Media.insertImage(this.contentResolver, image, "${(Date())}", null) if (path != null) { val uri = Uri.parse(path) sharingIntent.putExtra(Intent.EXTRA_STREAM, uri) } } startActivity(Intent.createChooser(sharingIntent, getString(R.string.share_using))) } fun reload() { finish() overridePendingTransition(R.anim.activity_fade_in, R.anim.activity_fade_out) startActivity(intent) } } private fun Resources.forceLocale(activity: BaseActivity, locale: Locale) { Locale.setDefault(locale) val configuration = Configuration() configuration.setLocale(locale) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { activity.createConfigurationContext(configuration) } updateConfiguration(configuration, displayMetrics) }
gpl-3.0
cdb3e4c5a29550f9734e5339cdacf6ed
37.340659
116
0.664469
5.168889
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_list/ui/activity/CourseListCollectionActivity.kt
2
1195
package org.stepik.android.view.course_list.ui.activity import android.content.Context import android.content.Intent import android.view.MenuItem import androidx.fragment.app.Fragment import org.stepic.droid.base.SingleFragmentActivity import org.stepik.android.view.course_list.ui.fragment.CourseListCollectionFragment class CourseListCollectionActivity : SingleFragmentActivity() { companion object { private const val EXTRA_COURSE_COLLECTION = "course_collection" fun createIntent(context: Context, courseCollectionId: Long): Intent = Intent(context, CourseListCollectionActivity::class.java) .putExtra(EXTRA_COURSE_COLLECTION, courseCollectionId) } override fun createFragment(): Fragment = CourseListCollectionFragment.newInstance( courseCollectionId = intent.getLongExtra(EXTRA_COURSE_COLLECTION, -1) // 12L - ID to test course list with simialr authors and courses ) override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } }
apache-2.0
ea869c7678b913d62000ea62866d701d
37.580645
146
0.727197
4.877551
false
false
false
false
jakubveverka/SportApp
app/src/main/java/com/example/jakubveverka/sportapp/Activities/SportEventsActivity.kt
1
4621
package com.example.jakubveverka.sportapp.Activities import android.content.Context import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import com.example.jakubveverka.sportapp.R import com.google.firebase.auth.FirebaseAuth import com.firebase.ui.auth.IdpResponse import android.content.Intent import android.view.View import android.widget.TextView import com.example.jakubveverka.sportapp.FragmentDialogs.DatePickerFragmentDialog import com.example.jakubveverka.sportapp.FragmentDialogs.TimePickerFragmentDialog import com.example.jakubveverka.sportapp.Fragments.CreateEventFragment import com.example.jakubveverka.sportapp.Fragments.EventsFragment import com.example.jakubveverka.sportapp.Utils.SnackbarUtils import com.example.jakubveverka.sportapp.Utils.UsersManager import com.example.jakubveverka.sportapp.Utils.bindView import com.example.jakubveverka.sportapp.ViewModels.SportEventsActivityViewModel /** * Activity for logged users. * Shows 2 fragments,first fragment with events list, second fragments is for creating new event */ class SportEventsActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener, TimePickerFragmentDialog.OnTimeSelectedListener, DatePickerFragmentDialog.OnDateSelectedListener, CreateEventFragment.CreateEventFragmentListener { /** bind view using Kotter knife */ private val mCoorLayout: View by bindView(R.id.cl_sport_events) private val mViewModel: SportEventsActivityViewModel by lazy { SportEventsActivityViewModel(this) } companion object { fun createIntent(context: Context): Intent { val intent = Intent() intent.setClass(context, SportEventsActivity::class.java) return intent } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_sport_events) val toolbar = findViewById(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val drawer = findViewById(R.id.drawer_layout) as DrawerLayout val toggle = ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer.setDrawerListener(toggle) toggle.syncState() val navigationView = findViewById(R.id.nav_view) as NavigationView navigationView.setNavigationItemSelectedListener(this) val header = navigationView.getHeaderView(0) val twUsersEmail = header.findViewById(R.id.tw_nav_header_users_email) as TextView twUsersEmail.text = mViewModel.getLoggedInText() mViewModel.restoreAndShowFragments() } override fun onBackPressed() { val drawer = findViewById(R.id.drawer_layout) as DrawerLayout if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.sport_events, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId return super.onOptionsItemSelected(item) } override fun onNavigationItemSelected(item: MenuItem): Boolean { // Handle navigation view item clicks here. val id = item.itemId mViewModel.processNavigationItemSelected(id) val drawer = findViewById(R.id.drawer_layout) as DrawerLayout drawer.closeDrawer(GravityCompat.START) return true } override fun onDateSelected(year: Int, month: Int, day: Int) { mViewModel.onDateSelected(year, month, day) } override fun onTimeSelected(hour: Int, minute: Int) { mViewModel.onTimeSelected(hour, minute) } override fun eventCreated() { mViewModel.onEventCreated() SnackbarUtils.showSnackbar(mCoorLayout, R.string.event_created) } }
mit
7213f42082da0d20dd2209ded2796651
36.877049
105
0.73707
4.543756
false
false
false
false
jiaminglu/kotlin-native
samples/libcurl/src/main/kotlin/org/konan/libcurl/CUrl.kt
1
1644
package org.konan.libcurl import kotlinx.cinterop.* import libcurl.* class CUrl(val url: String) { val stablePtr = StableObjPtr.create(this) val curl = curl_easy_init(); init { curl_easy_setopt(curl, CURLOPT_URL, url) val header = staticCFunction(::header_callback) curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, header) curl_easy_setopt(curl, CURLOPT_HEADERDATA, stablePtr.value) } val header = Event<String>() val data = Event<String>() fun fetch() { val res = curl_easy_perform(curl) if (res != CURLE_OK) println("curl_easy_perform() failed: ${curl_easy_strerror(res)}") } fun close() { curl_easy_cleanup(curl) stablePtr.dispose() } } fun CPointer<ByteVar>.toKString(length: Int): String { val bytes = ByteArray(length) nativeMemUtils.getByteArray(pointed, bytes, length) return kotlin.text.fromUtf8Array(bytes, 0, bytes.size) } fun header_callback(buffer: CPointer<ByteVar>?, size: size_t, nitems: size_t, userdata: COpaquePointer?): size_t { if (buffer == null) return 0 val header = buffer.toKString((size * nitems).toInt()).trim() if (userdata != null) { val curl = StableObjPtr.fromValue(userdata).get() as CUrl curl.header(header) } return size * nitems } /* fun write_callback(buffer: COpaquePointer?, size: size_t, nitems: size_t, userdata: COpaquePointer?): size_t { if (buffer == null) return 0 if (userdata != null) { val curl = StableObjPtr.fromValue(userdata).get() as CUrl curl.data(buffer.) } return size * nitems } */
apache-2.0
917c23096732fdd87ed99cc63e77f4e8
27.344828
114
0.639903
3.520343
false
false
false
false
savvasdalkitsis/gameframe
control/src/main/java/com/savvasdalkitsis/gameframe/feature/control/presenter/ControlPresenter.kt
1
4837
/** * Copyright 2017 Savvas Dalkitsis * 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. * * 'Game Frame' is a registered trademark of LEDSEQ */ package com.savvasdalkitsis.gameframe.feature.control.presenter import android.util.Log import com.savvasdalkitsis.gameframe.feature.analytics.Analytics import com.savvasdalkitsis.gameframe.feature.control.view.ControlView import com.savvasdalkitsis.gameframe.feature.device.model.* import com.savvasdalkitsis.gameframe.feature.device.usecase.DeviceUseCase import com.savvasdalkitsis.gameframe.feature.ip.model.IpBaseHostMissingException import com.savvasdalkitsis.gameframe.feature.ip.repository.IpRepository import com.savvasdalkitsis.gameframe.feature.navigation.usecase.Navigator import com.savvasdalkitsis.gameframe.feature.networking.model.IpAddress import com.savvasdalkitsis.gameframe.feature.networking.model.WifiNotEnabledException import com.savvasdalkitsis.gameframe.feature.networking.usecase.WifiUseCase import com.savvasdalkitsis.gameframe.infra.base.BasePresenter import com.savvasdalkitsis.gameframe.infra.base.plusAssign import com.savvasdalkitsis.gameframe.infra.rx.RxTransformers import com.savvasdalkitsis.gameframe.infra.rx.logErrors import io.reactivex.Completable import io.reactivex.CompletableTransformer class ControlPresenter(private val deviceUseCase: DeviceUseCase, private val ipRepository: IpRepository, private val navigator: Navigator, private val wifiUseCase: WifiUseCase, private val analytics: Analytics): BasePresenter<ControlView>() { fun loadIpAddress() { managedStreams += ipRepository.ipAddress .compose<IpAddress>(RxTransformers.schedulers<IpAddress>()) .subscribe({ view?.ipAddressLoaded(it) }, { view?.ipCouldNotBeFound(it) }) } fun togglePower() = runCommandAndNotifyView(deviceUseCase.togglePower()).logEvent("toggle_power") fun menu() = runCommandAndNotifyView(deviceUseCase.menu()).logEvent("menu") fun next() = runCommandAndNotifyView(deviceUseCase.next()).logEvent("next") fun changeBrightness(brightness: Brightness) = runCommandAndIgnoreResult(deviceUseCase.setBrightness(brightness)) .logEvent("brightness", "level" to brightness.name) fun changePlaybackMode(playbackMode: PlaybackMode) = runCommandAndIgnoreResult(deviceUseCase.setPlaybackMode(playbackMode)) .logEvent("playback_mode", "mode" to playbackMode.name) fun changeCycleInterval(cycleInterval: CycleInterval) = runCommandAndIgnoreResult(deviceUseCase.setCycleInterval(cycleInterval)) .logEvent("cycle_interval", "interval" to cycleInterval.name) fun changeDisplayMode(displayMode: DisplayMode) = runCommandAndIgnoreResult(deviceUseCase.setDisplayMode(displayMode)) .logEvent("display_mode", "mode" to displayMode.name) fun changeClockFace(clockFace: ClockFace) = runCommandAndIgnoreResult(deviceUseCase.setClockFace(clockFace)) .logEvent("clock_face", "face" to clockFace.name) fun setup() = navigator.navigateToIpSetup().logEvent("setup_from_control") private fun runCommand(command: Completable) = command.compose(interceptIpMissingException()) .compose(RxTransformers.schedulers()) private fun runCommandAndNotifyView(command: Completable) { managedStreams += runCommand(command).subscribe({ view?.operationSuccess() }, { e -> when (e) { is WifiNotEnabledException -> view?.wifiNotEnabledError(e) else -> view?.operationFailure(e) } }) } private fun runCommandAndIgnoreResult(command: Completable) { managedStreams += runCommand(command).subscribe({ }, logErrors()) } fun enableWifi() { wifiUseCase.enableWifi() } private fun interceptIpMissingException() = CompletableTransformer { c -> c.doOnError { if (it is IpBaseHostMissingException) { Log.e(RxTransformers::class.java.name, "Error: ", it) navigator.navigateToIpSetup() } } } @Suppress("unused") private fun Unit.logEvent(name: String, vararg params: Pair<String, String>) { analytics.logEvent(name, *params) } }
apache-2.0
c0b0b969ac068b8ad7f91061d5054e6b
44.641509
132
0.730411
4.70068
false
false
false
false
Heiner1/AndroidAPS
rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.kt
1
5053
package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.R import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileylinkStatusGeneralBinding import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import org.joda.time.LocalDateTime import javax.inject.Inject class RileyLinkStatusGeneralFragment : DaggerFragment() { @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var rh: ResourceHelper @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rileyLinkServiceData: RileyLinkServiceData @Inject lateinit var dateUtil: DateUtil @Inject lateinit var sp: SP private var _binding: RileylinkStatusGeneralBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = RileylinkStatusGeneralBinding.inflate(inflater, container, false).also { _binding = it }.root override fun onResume() { super.onResume() refreshData() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.refresh.setOnClickListener { refreshData() } } private fun refreshData() { val targetDevice = rileyLinkServiceData.targetDevice binding.connectionStatus.text = rh.gs(rileyLinkServiceData.rileyLinkServiceState.resourceId) binding.configuredRileyLinkAddress.text = rileyLinkServiceData.rileyLinkAddress ?: EMPTY binding.configuredRileyLinkName.text = rileyLinkServiceData.rileyLinkName ?: EMPTY if (sp.getBoolean(rh.gs(R.string.key_riley_link_show_battery_level), false)) { binding.batteryLevelRow.visibility = View.VISIBLE val batteryLevel = rileyLinkServiceData.batteryLevel binding.batteryLevel.text = batteryLevel?.let { rh.gs(R.string.rileylink_battery_level_value, it) } ?: EMPTY } else binding.batteryLevelRow.visibility = View.GONE binding.connectionError.text = rileyLinkServiceData.rileyLinkError?.let { rh.gs(it.getResourceId(targetDevice)) } ?: EMPTY if (rileyLinkServiceData.isOrange && rileyLinkServiceData.versionOrangeFirmware != null) { binding.firmwareVersion.text = rh.gs( R.string.rileylink_firmware_version_value_orange, rileyLinkServiceData.versionOrangeFirmware, rileyLinkServiceData.versionOrangeHardware ?: EMPTY ) } else { binding.firmwareVersion.text = rh.gs( R.string.rileylink_firmware_version_value, rileyLinkServiceData.versionBLE113 ?: EMPTY, rileyLinkServiceData.versionCC110 ?: EMPTY ) } val rileyLinkPumpDevice = activePlugin.activePump as RileyLinkPumpDevice val rileyLinkPumpInfo = rileyLinkPumpDevice.pumpInfo targetDevice?.resourceId?.let { binding.deviceType.setText(it) } if (targetDevice == RileyLinkTargetDevice.MedtronicPump) { binding.connectedDeviceDetails.visibility = View.VISIBLE binding.configuredDeviceModel.text = activePlugin.activePump.pumpDescription.pumpType.description binding.connectedDeviceModel.text = rileyLinkPumpInfo.connectedDeviceModel } else binding.connectedDeviceDetails.visibility = View.GONE binding.serialNumber.text = rileyLinkPumpInfo.connectedDeviceSerialNumber binding.pumpFrequency.text = rileyLinkPumpInfo.pumpFrequency if (rileyLinkServiceData.lastGoodFrequency != null) { binding.lastUsedFrequency.text = rh.gs(R.string.rileylink_pump_frequency_value, rileyLinkServiceData.lastGoodFrequency) } val lastConnectionTimeMillis = rileyLinkPumpDevice.lastConnectionTimeMillis if (lastConnectionTimeMillis == 0L) binding.lastDeviceContact.text = rh.gs(R.string.riley_link_ble_config_connected_never) else binding.lastDeviceContact.text = StringUtil.toDateTimeString(dateUtil, LocalDateTime(lastConnectionTimeMillis)) } companion object { private const val EMPTY = "-" } }
agpl-3.0
f5ac91bfeb38bd83a3fd9af7955345b7
52.2
131
0.754008
5.053
false
false
false
false
k9mail/k-9
app/core/src/main/java/com/fsck/k9/notification/NotificationDataStore.kt
1
9956
package com.fsck.k9.notification import com.fsck.k9.Account import com.fsck.k9.controller.MessageReference internal const val MAX_NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS = 8 /** * Stores information about new message notifications for all accounts. * * We only use a limited number of system notifications per account (see [MAX_NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS]); * those are called active notifications. The rest are called inactive notifications. When an active notification is * removed, the latest inactive notification is promoted to an active notification. */ internal class NotificationDataStore { private val notificationDataMap = mutableMapOf<String, NotificationData>() @Synchronized fun initializeAccount( account: Account, activeNotifications: List<NotificationHolder>, inactiveNotifications: List<InactiveNotificationHolder> ): NotificationData { require(activeNotifications.size <= MAX_NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS) return NotificationData(account, activeNotifications, inactiveNotifications).also { notificationData -> notificationDataMap[account.uuid] = notificationData } } @Synchronized fun addNotification(account: Account, content: NotificationContent, timestamp: Long): AddNotificationResult? { val notificationData = getNotificationData(account) val messageReference = content.messageReference val activeNotification = notificationData.activeNotifications.firstOrNull { notificationHolder -> notificationHolder.content.messageReference == messageReference } val inactiveNotification = notificationData.inactiveNotifications.firstOrNull { inactiveNotificationHolder -> inactiveNotificationHolder.content.messageReference == messageReference } return if (activeNotification != null) { val newActiveNotification = activeNotification.copy(content = content) val notificationHolder = activeNotification.copy( content = content ) val operations = emptyList<NotificationStoreOperation>() val newActiveNotifications = notificationData.activeNotifications .replace(activeNotification, newActiveNotification) val newNotificationData = notificationData.copy( activeNotifications = newActiveNotifications ) notificationDataMap[account.uuid] = newNotificationData AddNotificationResult.newNotification(newNotificationData, operations, notificationHolder) } else if (inactiveNotification != null) { val newInactiveNotification = inactiveNotification.copy(content = content) val newInactiveNotifications = notificationData.inactiveNotifications .replace(inactiveNotification, newInactiveNotification) val newNotificationData = notificationData.copy( inactiveNotifications = newInactiveNotifications ) notificationDataMap[account.uuid] = newNotificationData null } else if (notificationData.isMaxNumberOfActiveNotificationsReached) { val lastNotificationHolder = notificationData.activeNotifications.last() val inactiveNotificationHolder = lastNotificationHolder.toInactiveNotificationHolder() val notificationId = lastNotificationHolder.notificationId val notificationHolder = NotificationHolder(notificationId, timestamp, content) val operations = listOf( NotificationStoreOperation.ChangeToInactive(lastNotificationHolder.content.messageReference), NotificationStoreOperation.Add(messageReference, notificationId, timestamp) ) val newNotificationData = notificationData.copy( activeNotifications = listOf(notificationHolder) + notificationData.activeNotifications.dropLast(1), inactiveNotifications = listOf(inactiveNotificationHolder) + notificationData.inactiveNotifications ) notificationDataMap[account.uuid] = newNotificationData AddNotificationResult.replaceNotification(newNotificationData, operations, notificationHolder) } else { val notificationId = notificationData.getNewNotificationId() val notificationHolder = NotificationHolder(notificationId, timestamp, content) val operations = listOf( NotificationStoreOperation.Add(messageReference, notificationId, timestamp) ) val newNotificationData = notificationData.copy( activeNotifications = listOf(notificationHolder) + notificationData.activeNotifications ) notificationDataMap[account.uuid] = newNotificationData AddNotificationResult.newNotification(newNotificationData, operations, notificationHolder) } } @Synchronized fun removeNotifications( account: Account, selector: (List<MessageReference>) -> List<MessageReference> ): RemoveNotificationsResult? { val notificationData = getNotificationData(account) if (notificationData.isEmpty()) return null val removeMessageReferences = selector.invoke(notificationData.messageReferences) val operations = mutableListOf<NotificationStoreOperation>() val newNotificationHolders = mutableListOf<NotificationHolder>() val cancelNotificationIds = mutableListOf<Int>() for (messageReference in removeMessageReferences) { val notificationHolder = notificationData.activeNotifications.firstOrNull { it.content.messageReference == messageReference } if (notificationHolder == null) { val inactiveNotificationHolder = notificationData.inactiveNotifications.firstOrNull { it.content.messageReference == messageReference } ?: continue operations.add(NotificationStoreOperation.Remove(messageReference)) val newNotificationData = notificationData.copy( inactiveNotifications = notificationData.inactiveNotifications - inactiveNotificationHolder ) notificationDataMap[account.uuid] = newNotificationData } else if (notificationData.inactiveNotifications.isNotEmpty()) { val newNotificationHolder = notificationData.inactiveNotifications.first() .toNotificationHolder(notificationHolder.notificationId) newNotificationHolders.add(newNotificationHolder) cancelNotificationIds.add(notificationHolder.notificationId) operations.add(NotificationStoreOperation.Remove(messageReference)) operations.add( NotificationStoreOperation.ChangeToActive( newNotificationHolder.content.messageReference, newNotificationHolder.notificationId ) ) val newNotificationData = notificationData.copy( activeNotifications = notificationData.activeNotifications - notificationHolder + newNotificationHolder, inactiveNotifications = notificationData.inactiveNotifications.drop(1) ) notificationDataMap[account.uuid] = newNotificationData } else { cancelNotificationIds.add(notificationHolder.notificationId) operations.add(NotificationStoreOperation.Remove(messageReference)) val newNotificationData = notificationData.copy( activeNotifications = notificationData.activeNotifications - notificationHolder ) notificationDataMap[account.uuid] = newNotificationData } } return if (operations.isEmpty()) { null } else { RemoveNotificationsResult( notificationData = getNotificationData(account), notificationStoreOperations = operations, notificationHolders = newNotificationHolders, cancelNotificationIds = cancelNotificationIds ) } } @Synchronized fun clearNotifications(account: Account) { notificationDataMap.remove(account.uuid) } private fun getNotificationData(account: Account): NotificationData { return notificationDataMap[account.uuid] ?: NotificationData.create(account).also { notificationData -> notificationDataMap[account.uuid] = notificationData } } private val NotificationData.isMaxNumberOfActiveNotificationsReached: Boolean get() = activeNotifications.size == MAX_NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS private fun NotificationData.getNewNotificationId(): Int { val notificationIdsInUse = activeNotifications.map { it.notificationId }.toSet() for (index in 0 until MAX_NUMBER_OF_NEW_MESSAGE_NOTIFICATIONS) { val notificationId = NotificationIds.getSingleMessageNotificationId(account, index) if (notificationId !in notificationIdsInUse) { return notificationId } } throw AssertionError("getNewNotificationId() called with no free notification ID") } private fun NotificationHolder.toInactiveNotificationHolder() = InactiveNotificationHolder(timestamp, content) private fun InactiveNotificationHolder.toNotificationHolder(notificationId: Int): NotificationHolder { return NotificationHolder(notificationId, timestamp, content) } private fun <T> List<T>.replace(old: T, new: T): List<T> { return map { element -> if (element === old) new else element } } }
apache-2.0
60cf8479267667dd9e93b15c6acfaf2c
44.669725
117
0.688429
6.333333
false
false
false
false
elsiff/MoreFish
src/main/kotlin/me/elsiff/morefish/update/UpdateChecker.kt
1
670
package me.elsiff.morefish.update import java.io.BufferedReader import java.io.InputStreamReader import java.net.URL /** * Created by elsiff on 2019-01-03. */ class UpdateChecker( projectId: Int, private val currentVersion: String ) { private val checkUrl = URL("https://api.spigotmc.org/legacy/update.php?resource=$projectId") lateinit var newVersion: String fun check() { val connection = checkUrl.openConnection() BufferedReader(InputStreamReader(connection.getInputStream())).use { newVersion = it.readLine() } } fun hasNewVersion(): Boolean { return newVersion != currentVersion } }
mit
cc17acacfe36455ed66aa8a7928b3611
22.964286
96
0.683582
4.527027
false
false
false
false
Maccimo/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToStatic/fixes.kt
3
3693
// Copyright 2000-2021 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. @file:JvmName("ConvertToStatic") package org.jetbrains.plugins.groovy.refactoring.convertToStatic import com.intellij.psi.PsiElement import com.intellij.psi.impl.light.LightElement import org.jetbrains.plugins.groovy.intentions.style.AddReturnTypeFix import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor import org.jetbrains.plugins.groovy.lang.psi.api.GroovyReference import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier.DEF import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic private const val MAX_FIX_ITERATIONS = 5 fun applyErrorFixes(element: GroovyPsiElement) { repeat(MAX_FIX_ITERATIONS) { val checker = TypeChecker() element.accept(TypeCheckVisitor(checker)) if (checker.applyFixes() == 0) { return } } } fun applyDeclarationFixes(scope: GroovyPsiElement) { repeat(MAX_FIX_ITERATIONS) { collectReferencedEmptyDeclarations(scope).forEach { element -> when (element) { is GrMethod -> AddReturnTypeFix.applyFix(scope.project, element) is GrVariable -> { val psiType = element.typeGroovy ?: return@forEach element.setType(psiType) element.modifierList?.setModifierProperty(DEF, false) } } } } } fun collectReferencedEmptyDeclarations(scope: GroovyPsiElement, recursive: Boolean = true): List<PsiElement> { val declarationsVisitor = EmptyDeclarationTypeCollector(recursive) scope.accept(declarationsVisitor) return declarationsVisitor.elements } private class TypeCheckVisitor(val checker: TypeChecker) : GroovyRecursiveElementVisitor() { override fun visitElement(element: GroovyPsiElement) { if (isCompileStatic(element)) { element.accept(checker) } super.visitElement(element) } } private class EmptyDeclarationTypeCollector(private val recursive: Boolean) : GroovyElementVisitor() { val elements = mutableListOf<PsiElement>() override fun visitReferenceExpression(referenceExpression: GrReferenceExpression) { checkReference(referenceExpression) super.visitReferenceExpression(referenceExpression) } private fun checkReference(referenceExpression: GroovyReference) { val resolveResult = referenceExpression.advancedResolve() if (!resolveResult.isValidResult) return when (val element = resolveResult.element) { is GrAccessorMethod -> { checkField(element.property) } is GrField -> { checkField(element) } is LightElement -> return is GrMethod -> { if (element.isConstructor) return element.returnTypeElementGroovy?.let { return } elements += element } } } private fun checkField(element: GrField) { element.declaredType?.let { return } val initializer = element.initializerGroovy ?: return initializer.type ?: return elements += element } override fun visitElement(element: GroovyPsiElement) { if (recursive) { element.acceptChildren(this) } } }
apache-2.0
552b74f207202a35950f29aa3e31fafa
35.215686
140
0.755754
4.498173
false
false
false
false
k9mail/k-9
app/ui/legacy/src/main/java/com/fsck/k9/ui/settings/AboutFragment.kt
1
7471
package com.fsck.k9.ui.settings import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import androidx.fragment.app.Fragment import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.fsck.k9.ui.R import timber.log.Timber class AboutFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_about, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val versionTextView = view.findViewById<TextView>(R.id.version) versionTextView.text = getVersionNumber() val versionLayout = view.findViewById<View>(R.id.versionLayout) versionLayout.setOnClickListener { displayChangeLog() } val authorsLayout = view.findViewById<View>(R.id.authorsLayout) authorsLayout.setOnClickListener { openUrl(getString(R.string.app_authors_url)) } val licenseLayout = view.findViewById<View>(R.id.licenseLayout) licenseLayout.setOnClickListener { openUrl(getString(R.string.app_license_url)) } val sourceCodeLayout = view.findViewById<View>(R.id.sourceCodeLayout) sourceCodeLayout.setOnClickListener { openUrl(getString(R.string.app_source_url)) } val websiteLayout = view.findViewById<View>(R.id.websiteLayout) websiteLayout.setOnClickListener { openUrl(getString(R.string.app_webpage_url)) } val userForumLayout = view.findViewById<View>(R.id.userForumLayout) userForumLayout.setOnClickListener { openUrl(getString(R.string.user_forum_url)) } val fediverseLayout = view.findViewById<View>(R.id.fediverseLayout) fediverseLayout.setOnClickListener { openUrl(getString(R.string.fediverse_url)) } val twitterLayout = view.findViewById<View>(R.id.twitterLayout) twitterLayout.setOnClickListener { openUrl(getString(R.string.twitter_url)) } val manager = LinearLayoutManager(view.context) val librariesRecyclerView = view.findViewById<RecyclerView>(R.id.libraries) librariesRecyclerView.apply { layoutManager = manager adapter = LibrariesAdapter(USED_LIBRARIES) isNestedScrollingEnabled = false isFocusable = false } } private fun displayChangeLog() { findNavController().navigate(R.id.action_aboutScreen_to_changelogScreen) } private fun getVersionNumber(): String { return try { val context = requireContext() val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0) packageInfo.versionName } catch (e: PackageManager.NameNotFoundException) { Timber.e(e, "Error getting PackageInfo") "?" } } companion object { private val USED_LIBRARIES = arrayOf( Library("Android Jetpack libraries", "https://developer.android.com/jetpack", "Apache License, Version 2.0"), Library("AndroidX Preference eXtended", "https://github.com/Gericop/Android-Support-Preference-V7-Fix", "Apache License, Version 2.0"), Library("CircleImageView", "https://github.com/hdodenhof/CircleImageView", "Apache License, Version 2.0"), Library("ckChangeLog", "https://github.com/cketti/ckChangeLog", "Apache License, Version 2.0"), Library("Commons IO", "https://commons.apache.org/io/", "Apache License, Version 2.0"), Library("FastAdapter", "https://github.com/mikepenz/FastAdapter", "Apache License, Version 2.0"), Library("Glide", "https://github.com/bumptech/glide", "BSD, part MIT and Apache 2.0"), Library("jsoup", "https://jsoup.org/", "MIT License"), Library("jutf7", "http://jutf7.sourceforge.net/", "MIT License"), Library("JZlib", "http://www.jcraft.com/jzlib/", "BSD-style License"), Library("Koin", "https://insert-koin.io/", "Apache License, Version 2.0"), Library("Kotlin Standard Library", "https://kotlinlang.org/api/latest/jvm/stdlib/", "Apache License, Version 2.0"), Library("KotlinX coroutines", "https://github.com/Kotlin/kotlinx.coroutines", "Apache License, Version 2.0"), Library("Material Components for Android", "https://github.com/material-components/material-components-android", "Apache License, Version 2.0"), Library("Material Drawer", "https://github.com/mikepenz/MaterialDrawer", "Apache License, Version 2.0"), Library("Mime4j", "https://james.apache.org/mime4j/", "Apache License, Version 2.0"), Library("MiniDNS", "https://github.com/MiniDNS/minidns", "Multiple, Apache License, Version 2.0"), Library("Moshi", "https://github.com/square/moshi", "Apache License, Version 2.0"), Library("OkHttp", "https://github.com/square/okhttp", "Apache License, Version 2.0"), Library("Okio", "https://github.com/square/okio", "Apache License, Version 2.0"), Library("SafeContentResolver", "https://github.com/cketti/SafeContentResolver", "Apache License, Version 2.0"), Library("SearchPreference", "https://github.com/ByteHamster/SearchPreference", "MIT License"), Library("Timber", "https://github.com/JakeWharton/timber", "Apache License, Version 2.0"), Library("TokenAutoComplete", "https://github.com/splitwise/TokenAutoComplete/", "Apache License, Version 2.0") ) } } private fun Fragment.openUrl(url: String) = requireContext().openUrl(url) private fun Context.openUrl(url: String) { try { val viewIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(viewIntent) } catch (e: ActivityNotFoundException) { Toast.makeText(this, R.string.error_activity_not_found, Toast.LENGTH_SHORT).show() } } private data class Library(val name: String, val url: String, val license: String) private class LibrariesAdapter(private val dataset: Array<Library>) : RecyclerView.Adapter<LibrariesAdapter.ViewHolder>() { class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val name: TextView = view.findViewById(R.id.name) val license: TextView = view.findViewById(R.id.license) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.about_library, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, index: Int) { val library = dataset[index] holder.name.text = library.name holder.license.text = library.license holder.itemView.setOnClickListener { holder.itemView.context.openUrl(library.url) } } override fun getItemCount() = dataset.size }
apache-2.0
a2045443985310aba07ab2741bd6b566
45.403727
156
0.680498
4.35373
false
false
false
false
k9mail/k-9
app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo17.kt
2
1987
package com.fsck.k9.preferences.migrations import android.database.sqlite.SQLiteDatabase /** * Rewrite 'led' and 'ledColor' values to 'notificationLight'. */ class StorageMigrationTo17( private val db: SQLiteDatabase, private val migrationsHelper: StorageMigrationsHelper ) { fun rewriteNotificationLightSettings() { val accountUuidsListValue = migrationsHelper.readValue(db, "accountUuids") if (accountUuidsListValue == null || accountUuidsListValue.isEmpty()) { return } val accountUuids = accountUuidsListValue.split(",") for (accountUuid in accountUuids) { rewriteNotificationLightSettings(accountUuid) } } private fun rewriteNotificationLightSettings(accountUuid: String) { val isLedEnabled = migrationsHelper.readValue(db, "$accountUuid.led").toBoolean() val ledColor = migrationsHelper.readValue(db, "$accountUuid.ledColor")?.toInt() ?: 0 val accountColor = migrationsHelper.readValue(db, "$accountUuid.chipColor")?.toInt() ?: 0 val notificationLight = convertToNotificationLightValue(isLedEnabled, ledColor, accountColor) migrationsHelper.writeValue(db, "$accountUuid.notificationLight", notificationLight) migrationsHelper.writeValue(db, "$accountUuid.led", null) migrationsHelper.writeValue(db, "$accountUuid.ledColor", null) } private fun convertToNotificationLightValue(isLedEnabled: Boolean, ledColor: Int, accountColor: Int): String { if (!isLedEnabled) return "Disabled" return when (ledColor.rgb) { accountColor.rgb -> "AccountColor" 0xFFFFFF -> "White" 0xFF0000 -> "Red" 0x00FF00 -> "Green" 0x0000FF -> "Blue" 0xFFFF00 -> "Yellow" 0x00FFFF -> "Cyan" 0xFF00FF -> "Magenta" else -> "SystemDefaultColor" } } private val Int.rgb get() = this and 0x00FFFFFF }
apache-2.0
37b0584b67f18c0daab7c7a26905ea4b
35.796296
114
0.663815
4.642523
false
false
false
false
JetBrains/ideavim
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/statements/loops/ForLoop.kt
1
5154
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.statements.loops import com.maddyhome.idea.vim.api.ExecutionContext import com.maddyhome.idea.vim.api.VimEditor import com.maddyhome.idea.vim.api.injector import com.maddyhome.idea.vim.ex.ExException import com.maddyhome.idea.vim.vimscript.model.Executable import com.maddyhome.idea.vim.vimscript.model.ExecutionResult import com.maddyhome.idea.vim.vimscript.model.VimLContext import com.maddyhome.idea.vim.vimscript.model.datatypes.VimBlob import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType import com.maddyhome.idea.vim.vimscript.model.datatypes.VimList import com.maddyhome.idea.vim.vimscript.model.datatypes.VimString import com.maddyhome.idea.vim.vimscript.model.expressions.Expression import com.maddyhome.idea.vim.vimscript.model.expressions.Variable // todo refactor us senpai :( data class ForLoop(val variable: Variable, val iterable: Expression, val body: List<Executable>) : Executable { override lateinit var vimContext: VimLContext override fun execute(editor: VimEditor, context: ExecutionContext): ExecutionResult { injector.statisticsService.setIfLoopUsed(true) var result: ExecutionResult = ExecutionResult.Success body.forEach { it.vimContext = this } var iterableValue = iterable.evaluate(editor, context, this) if (iterableValue is VimString) { for (i in iterableValue.value) { injector.variableService.storeVariable(variable, VimString(i.toString()), editor, context, this) for (statement in body) { if (result is ExecutionResult.Success) { result = statement.execute(editor, context) } else { break } } if (result is ExecutionResult.Break) { result = ExecutionResult.Success break } else if (result is ExecutionResult.Continue) { result = ExecutionResult.Success continue } else if (result is ExecutionResult.Error) { break } } } else if (iterableValue is VimList) { var index = 0 while (index < (iterableValue as VimList).values.size) { injector.variableService.storeVariable(variable, iterableValue.values[index], editor, context, this) for (statement in body) { if (result is ExecutionResult.Success) { result = statement.execute(editor, context) } else { break } } if (result is ExecutionResult.Break) { result = ExecutionResult.Success break } else if (result is ExecutionResult.Continue) { result = ExecutionResult.Success continue } else if (result is ExecutionResult.Error) { break } index += 1 iterableValue = iterable.evaluate(editor, context, this) as VimList } } else if (iterableValue is VimBlob) { TODO("Not yet implemented") } else { throw ExException("E1098: String, List or Blob required") } return result } } data class ForLoopWithList(val variables: List<String>, val iterable: Expression, val body: List<Executable>) : Executable { override lateinit var vimContext: VimLContext override fun execute(editor: VimEditor, context: ExecutionContext): ExecutionResult { var result: ExecutionResult = ExecutionResult.Success body.forEach { it.vimContext = this } var iterableValue = iterable.evaluate(editor, context, this) if (iterableValue is VimList) { var index = 0 while (index < (iterableValue as VimList).values.size) { storeListVariables(iterableValue.values[index], editor, context) for (statement in body) { if (result is ExecutionResult.Success) { result = statement.execute(editor, context) } else { break } } if (result is ExecutionResult.Break) { result = ExecutionResult.Success break } else if (result is ExecutionResult.Continue) { result = ExecutionResult.Success continue } else if (result is ExecutionResult.Error) { break } index += 1 iterableValue = iterable.evaluate(editor, context, this) as VimList } } else { throw ExException("E714: List required") } return result } private fun storeListVariables(list: VimDataType, editor: VimEditor, context: ExecutionContext) { if (list !is VimList) { throw ExException("E714: List required") } if (list.values.size < variables.size) { throw ExException("E688: More targets than List items") } if (list.values.size > variables.size) { throw ExException("E684: Less targets than List items") } for (item in list.values.withIndex()) { injector.variableService.storeVariable(Variable(null, variables[item.index]), item.value, editor, context, this) } } }
mit
494116e9efeb909200c1bd33f1fe5f4e
35.553191
118
0.673652
4.454624
false
false
false
false
TomsUsername/Phoenix
src/main/kotlin/phoenix/bot/pogo/nRnMK9r/services/BotService.kt
1
2543
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package phoenix.bot.pogo.nRnMK9r.services import phoenix.bot.pogo.nRnMK9r.Bot import phoenix.bot.pogo.nRnMK9r.Context import phoenix.bot.pogo.nRnMK9r.Settings import phoenix.bot.pogo.nRnMK9r.startBot import phoenix.bot.pogo.nRnMK9r.util.Log import phoenix.bot.pogo.nRnMK9r.util.credentials.GoogleAutoCredentials import phoenix.bot.pogo.nRnMK9r.util.io.SettingsJSONWriter import okhttp3.OkHttpClient import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.io.File import java.util.concurrent.CountDownLatch import javax.annotation.PreDestroy import kotlin.concurrent.thread @Service class BotService { @Autowired lateinit var http: OkHttpClient private val bots: MutableList<Bot> = mutableListOf() val settingsJSONWriter = SettingsJSONWriter() fun submitBot(name: String): Settings { val settings = settingsJSONWriter.load(name) addBot(startBot(settings, http)) settingsJSONWriter.save(settings) // Is this needed after starting? return settings } @Synchronized fun addBot(bot: Bot) { bots.add(bot) } @Synchronized fun removeBot(bot: Bot) { bots.remove(bot) } fun getJSONConfigBotNames(): List<String> { return settingsJSONWriter.getJSONConfigBotNames() } fun getBotContext(name: String): Context { val bot = bots.find { it.settings.name == name } bot ?: throw IllegalArgumentException("Bot $name doesn't exists !") return bot.ctx } @Synchronized fun getAllBotSettings(): List<Settings> { return bots.map { it.settings.copy(credentials = GoogleAutoCredentials(), restApiPassword = "") } } @Synchronized fun doWithBot(name: String, action: (bot: Bot) -> Unit): Boolean { val bot = bots.find { it.settings.name == name } ?: return false action(bot) return true } @PreDestroy @Synchronized fun stopAllBots() { val latch = CountDownLatch(bots.size) bots.forEach { thread { it.stop() latch.countDown() } } latch.await() } }
gpl-3.0
7e33a81f20c21319b3840b1e232ac2ca
26.641304
105
0.686591
4.081862
false
false
false
false
benjamin-bader/thrifty
thrifty-schema/src/main/kotlin/com/microsoft/thrifty/schema/SchemaFunctionalEquality.kt
1
16897
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ @file:JvmName("SchemaFunctionalEquality") package com.microsoft.thrifty.schema /* * Functional ABI equality checking for Thrifty elements and Schemas. This exists because we can't * compare raw element types together due to misc metadata that their AutoValue representations * would report as differing but are not relevant to the actual ABI (location, formatting, etc). */ /** * For comparing docs, we remove stars as things get weird in the parser. */ private fun String.cleanedDoc(): String { return trim().replace("*", "").split("\n").joinToString("\n") { it.trimEnd() } } /** * A fully qualified class name of a given [UserType], used for equality checking. */ private inline val UserType.fqcn: String get() = "$javaPackage.$name" /** * The java package name from the spec. We always assume its there because we don't support specs that don't. */ private inline val UserType.javaPackage: String get() = getNamespaceFor(NamespaceScope.JAVA)!! /** * The java package name from the spec. We always assume its there because we don't support specs that don't. */ private inline val Constant.javaPackage: String get() { return getNamespaceFor(NamespaceScope.JAVA)!! } /** * Checks that this [ThriftType] is equal to a given [other] [ThriftType]. * * The following properties are checked: * - [ThriftType.annotations] * - [SetType.elementType] * - [ListType.elementType] * - [MapType.keyType] * - [MapType.valueType] * - [BuiltinType] are compared by equality * - [UserType] are compared by type checks, then fully qualified class name for linking. Set * [deepCheck] to enable deep comparisons on UserTypes too. * * @param other the other [ThriftType] to check * @param deepCheck a flag to signal whether or not the check should be deep. By default this is * `false` and UserTypes will only be compared by their fully qualified names (basically a linking * check). * @param lazyMessage a message to report if a check fails */ fun ThriftType.checkFunctionallyEquals( other: ThriftType, deepCheck: Boolean = false, lazyMessage: () -> String ) { check(annotations == other.annotations, lazyMessage) when (this) { is BuiltinType -> { check(this == other, lazyMessage) } is SetType -> { check(other is SetType) elementType.checkFunctionallyEquals(other.elementType, deepCheck, lazyMessage) } is ListType -> { check(other is ListType) elementType.checkFunctionallyEquals(other.elementType, deepCheck, lazyMessage) } is MapType -> { check(other is MapType) keyType.checkFunctionallyEquals(other.keyType, deepCheck, lazyMessage) valueType.checkFunctionallyEquals(other.valueType, deepCheck, lazyMessage) } is UserType -> { when (this) { is StructType -> { check(other is StructType, lazyMessage) check(fqcn == other.fqcn, lazyMessage) if (deepCheck) { checkFunctionallyEquals(other) } } is EnumType -> { check(other is EnumType, lazyMessage) check(fqcn == other.fqcn, lazyMessage) if (deepCheck) { checkFunctionallyEquals(other) } } is TypedefType -> { check(other is TypedefType, lazyMessage) check(fqcn == other.fqcn, lazyMessage) if (deepCheck) { checkFunctionallyEquals(other) } } is ServiceType -> { check(other is ServiceType, lazyMessage) check(fqcn == other.fqcn, lazyMessage) if (deepCheck) { checkFunctionallyEquals(other) } } } } } } /** * Checks that this [Field] is equal to a given [other] [Field]. * * The following properties are checked: * - [Field.documentation] * - [Field.name] * - [Field.annotations] * - [Field.type] * - [Field.required] * - [Field.optional] * * @param other the other [Field] to check * @param prefix a contextual prefix to use in error messaging, as [Field]s can be used in * [StructType.fields], [ServiceMethod.parameters], and [ServiceMethod.exceptions]. */ fun Field.checkFunctionallyEquals(other: Field, prefix: String) { check(documentation.cleanedDoc() == other.documentation.cleanedDoc()) { "$prefix documentation mismatch at $location. Found ${documentation.cleanedDoc()} but expected ${other.documentation.cleanedDoc()}" } check(name == other.name) { "$prefix name mismatch at $location. Found $name but expected ${other.name}" } check(annotations == other.annotations) { "$prefix annotations mismatch at $location. Found $annotations but expected ${other.annotations}" } type.checkFunctionallyEquals(other.type) { "$prefix type mismatch at $location. Found $type but expected ${other.type}" } check(required == other.required) { "$prefix required mismatch at $location. Found $required but expected ${other.required}" } check(optional == other.optional) { "$prefix optional mismatch at $location. Found $optional but expected ${other.optional}" } } /** * Checks that this [ServiceMethod] is equal to a given [other] [ServiceMethod]. * * The following properties are checked: * - [ServiceMethod.documentation] * - [ServiceMethod.name] * - [ServiceMethod.annotations] * - [ServiceMethod.returnType] * - [ServiceMethod.parameters] * - [ServiceMethod.exceptions] * * @param other the other [StructType] to check */ fun ServiceMethod.checkFunctionallyEquals(other: ServiceMethod) { check(documentation.cleanedDoc() == other.documentation.cleanedDoc()) { "Service method documentation mismatch at $location. Found ${documentation.cleanedDoc()} but expected ${other.documentation.cleanedDoc()}" } check(name == other.name) { "Service method name mismatch at $location. Found $name but expected ${other.name}" } check(annotations == other.annotations) { "Service method annotations mismatch at $location. Found $annotations but expected ${other.annotations}" } returnType.checkFunctionallyEquals(other.returnType) { "Service method return type mismatch at $location. Found $returnType but expected ${other.returnType}" } parameters.zip(other.parameters) .forEach { (parameter1, parameter2) -> parameter1.checkFunctionallyEquals(parameter2, "Service method parameter") } exceptions.zip(other.exceptions) .forEach { (exception1, exception2) -> exception1.checkFunctionallyEquals(exception2, "Service method exception") } } /** * Checks that this [StructType] is equal to a given [other] [StructType]. * * The following properties are checked: * - [StructType.documentation] * - [StructType.name] * - [StructType.namespaces] * - [StructType.annotations] * - [StructType.isUnion] * - [StructType.isException] * - [StructType.isStruct] * - [StructType.fields] * * @param other the other [StructType] to check */ fun StructType.checkFunctionallyEquals(other: StructType) { check(documentation.cleanedDoc() == other.documentation.cleanedDoc()) { "Struct documentation mismatch at $location. Found ${documentation.cleanedDoc()} but expected ${other.documentation.cleanedDoc()}" } check(name == other.name) { "Struct name mismatch at $location. Found $name but expected ${other.name}" } check(namespaces == other.namespaces) { "Struct namespaces mismatch at $location. Found $namespaces but expected ${other.namespaces}" } check(annotations == other.annotations) { "Struct annotations mismatch at $location. Found $annotations but expected ${other.annotations}" } check(isUnion == other.isUnion) { "Struct isUnion mismatch at $location. Found $isUnion but expected ${other.isUnion}" } check(isException == other.isException) { "Struct isException mismatch at $location. Found $isException but expected ${other.isException}" } check(isStruct == other.isStruct) { "Struct isStruct mismatch at $location. Found $isStruct but expected ${other.isStruct}" } fields.zip(other.fields) .forEach { (field1, field2) -> field1.checkFunctionallyEquals(field2, "Struct field") } } /** * Checks that this [ServiceType] is equal to a given [other] [ServiceType]. * * The following properties are checked: * - [ServiceType.documentation] * - [ServiceType.name] * - [ServiceType.namespaces] * - [ServiceType.annotations] * - [ServiceType.methods] * * @param other the other [ServiceType] to check */ fun ServiceType.checkFunctionallyEquals(other: ServiceType) { check(documentation.cleanedDoc() == other.documentation.cleanedDoc()) { "Service documentation mismatch at $location. Found ${documentation.cleanedDoc()} but expected ${other.documentation.cleanedDoc()}" } check(name == other.name) { "Service name mismatch at $location. Found $name but expected ${other.name}" } check(namespaces == other.namespaces) { "Service namespaces mismatch at $location. Found $namespaces but expected ${other.namespaces}" } check(annotations == other.annotations) { "Service annotations mismatch at $location. Found $annotations but expected ${other.annotations}" } methods.zip(other.methods) .forEach { (method1, method2) -> method1.checkFunctionallyEquals(method2) } } /** * Checks that this [Constant] is equal to a given [other] [Constant]. * * The following properties are checked: * - [Constant.documentation] * - [Constant.name] * - [Constant.namespaces] * - [Constant.annotations] * - [Constant.value] * * @param other the other [Constant] to check */ fun Constant.checkFunctionallyEquals(other: Constant) { check(documentation.cleanedDoc() == other.documentation.cleanedDoc()) { "Constant documentation mismatch at $location. Found ${documentation.cleanedDoc()} but expected ${other.documentation.cleanedDoc()}" } check(name == other.name) { "Constant name mismatch at $location. Found $name but expected ${other.name}" } check(namespaces == other.namespaces) { "Constant namespaces mismatch at $location. Found $namespaces but expected ${other.namespaces}" } check(annotations == other.annotations) { "Constant annotations mismatch at $location. Found $annotations but expected ${other.annotations}" } check(value == other.value) { "Constant value mismatch at $location. Found $value but expected ${other.value}" } } /** * Checks that this [EnumMember] is equal to a given [other] [EnumMember]. * * The following properties are checked: * - [EnumMember.documentation] * - [EnumMember.name] * - [EnumMember.annotations] * - [EnumMember.value] * * @param other the other [EnumMember] to check */ fun EnumMember.checkFunctionallyEquals(other: EnumMember) { check(documentation.cleanedDoc() == other.documentation.cleanedDoc()) { "Enum member documentation mismatch at $location. Found ${documentation.cleanedDoc()} but expected ${other.documentation.cleanedDoc()}" } check(name == other.name) { "Enum member name mismatch at $location. Found $name but expected ${other.name}" } check(annotations == other.annotations) { "Enum member annotations mismatch at $location. Found $annotations but expected ${other.annotations}" } check(value == other.value) { "Enum member value mismatch at $location. Found $value but expected ${other.value}" } } /** * Checks that this [EnumType] is equal to a given [other] [EnumType]. * * The following properties are checked: * - [EnumType.documentation] * - [EnumType.name] * - [EnumType.namespaces] * - [EnumType.annotations] * - [EnumType.members] * * @param other the other [EnumType] to check */ fun EnumType.checkFunctionallyEquals(other: EnumType) { check(documentation.cleanedDoc() == other.documentation.cleanedDoc()) { "Enum documentation mismatch at $location. Found ${documentation.cleanedDoc()} but expected ${other.documentation.cleanedDoc()}" } check(name == other.name) { "Enum name mismatch at $location. Found $name but expected ${other.name}" } check(namespaces == other.namespaces) { "Enum namespaces mismatch at $location. Found $namespaces but expected ${other.namespaces}" } check(annotations == other.annotations) { "Enum annotations mismatch at $location. Found $annotations but expected ${other.annotations}" } members.zip(other.members) .forEach { (member1, member2) -> member1.checkFunctionallyEquals(member2) } } /** * Checks that this [TypedefType] is equal to a given [other] [TypedefType]. * * The following properties are checked: * - [TypedefType.documentation] * - [TypedefType.name] * - [TypedefType.namespaces] * - [TypedefType.annotations] * - [TypedefType.oldType] * * @param other the other [TypedefType] to check */ fun TypedefType.checkFunctionallyEquals(other: TypedefType) { check(documentation.cleanedDoc() == other.documentation.cleanedDoc()) { "Typedef documentation mismatch at $location. Found ${documentation.cleanedDoc()} but expected ${other.documentation.cleanedDoc()}" } check(name == other.name) { "Typedef name mismatch at $location. Found $name but expected ${other.name}" } check(namespaces == other.namespaces) { "Typedef namespaces mismatch at $location. Found $namespaces but expected ${other.namespaces}" } check(annotations == other.annotations) { "Typedef annotations mismatch at $location. Found $annotations but expected ${other.annotations}" } oldType.checkFunctionallyEquals(other.oldType) { "Typedef oldType mismatch at $location. Found $oldType but expected ${other.oldType}" } } /** * Checks that this [Schema] is equal to a given [other] [Schema]. Note that since elements are * effectively sets, they're sorted by their fully qualified class names and zipped with [other] for * consistency and matching. * * @param other the other [Schema] to check */ fun Schema.checkFunctionallyEquals(other: Schema) { structs.sortedBy(StructType::fqcn) .zip(other.structs.sortedBy(StructType::fqcn)) .forEach { (struct1, struct2) -> struct1.checkFunctionallyEquals(struct2) } unions.sortedBy(StructType::fqcn) .zip(other.unions.sortedBy(StructType::fqcn)) .forEach { (union1, union2) -> union1.checkFunctionallyEquals(union2) } enums.sortedBy(EnumType::fqcn) .zip(other.enums.sortedBy(EnumType::fqcn)) .forEach { (enum1, enum2) -> enum1.checkFunctionallyEquals(enum2) } services.sortedBy(ServiceType::fqcn) .zip(other.services.sortedBy(ServiceType::fqcn)) .forEach { (service1, service2) -> service1.checkFunctionallyEquals(service2) } typedefs.sortedBy(TypedefType::fqcn) .zip(other.typedefs.sortedBy(TypedefType::fqcn)) .forEach { (typedef1, typedef2) -> typedef1.checkFunctionallyEquals(typedef2) } exceptions.sortedBy(StructType::fqcn) .zip(other.exceptions.sortedBy(StructType::fqcn)) .forEach { (exception1, exception2) -> exception1.checkFunctionallyEquals(exception2) } constants.sortedBy { "${it.javaPackage}${it.name}" } .zip(other.constants.sortedBy { "${it.javaPackage}${it.name}" }) .forEach { (constant1, constant2) -> constant1.checkFunctionallyEquals(constant2) } }
apache-2.0
a7e0d6eb2b7692f94e0b0ad860074649
37.315193
146
0.66355
4.215818
false
false
false
false
benjamin-bader/thrifty
thrifty-java-codegen/src/main/kotlin/com/microsoft.thrifty.gen/ConstantBuilder.kt
1
15546
/* * Thrifty * * Copyright (c) Microsoft Corporation * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the License); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING * WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, * FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ package com.microsoft.thrifty.gen import com.microsoft.thrifty.schema.BuiltinType import com.microsoft.thrifty.schema.EnumType import com.microsoft.thrifty.schema.ListType import com.microsoft.thrifty.schema.MapType import com.microsoft.thrifty.schema.NamespaceScope import com.microsoft.thrifty.schema.Schema import com.microsoft.thrifty.schema.ServiceType import com.microsoft.thrifty.schema.SetType import com.microsoft.thrifty.schema.StructType import com.microsoft.thrifty.schema.ThriftType import com.microsoft.thrifty.schema.TypedefType import com.microsoft.thrifty.schema.parser.ConstValueElement import com.microsoft.thrifty.schema.parser.DoubleValueElement import com.microsoft.thrifty.schema.parser.IdentifierValueElement import com.microsoft.thrifty.schema.parser.IntValueElement import com.microsoft.thrifty.schema.parser.ListValueElement import com.microsoft.thrifty.schema.parser.LiteralValueElement import com.microsoft.thrifty.schema.parser.MapValueElement import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.NameAllocator import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName import java.util.NoSuchElementException import java.util.concurrent.atomic.AtomicInteger internal class ConstantBuilder( private val typeResolver: TypeResolver, private val schema: Schema ) { fun generateFieldInitializer( initializer: CodeBlock.Builder, allocator: NameAllocator, scope: AtomicInteger, name: String, tt: ThriftType, value: ConstValueElement, needsDeclaration: Boolean) { tt.trueType.accept(object : SimpleVisitor<Unit>() { override fun visitBuiltin(builtinType: ThriftType) { val init = renderConstValue(initializer, allocator, scope, tt, value) initializer.addStatement("\$L = \$L", name, init) } override fun visitEnum(enumType: EnumType) { val item = renderConstValue(initializer, allocator, scope, tt, value) initializer.addStatement("\$L = \$L", name, item) } override fun visitList(listType: ListType) { val list = (value as ListValueElement).value val elementType = listType.elementType.trueType val elementTypeName = typeResolver.getJavaClass(elementType) val genericName = ParameterizedTypeName.get(TypeNames.LIST, elementTypeName) val listImplName = typeResolver.listOf(elementTypeName) generateSingleElementCollection(elementType, genericName, listImplName, list) } override fun visitSet(setType: SetType) { val set = (value as ListValueElement).value val elementType = setType.elementType.trueType val elementTypeName = typeResolver.getJavaClass(elementType) val genericName = ParameterizedTypeName.get(TypeNames.SET, elementTypeName) val setImplName = typeResolver.setOf(elementTypeName) generateSingleElementCollection(elementType, genericName, setImplName, set) } private fun generateSingleElementCollection( elementType: ThriftType, genericName: TypeName, collectionImplName: TypeName, values: List<ConstValueElement>) { if (needsDeclaration) { initializer.addStatement("\$T \$N = new \$T()", genericName, name, collectionImplName) } else { initializer.addStatement("\$N = new \$T()", name, collectionImplName) } for (element in values) { val elementName = renderConstValue(initializer, allocator, scope, elementType, element) initializer.addStatement("\$N.add(\$L)", name, elementName) } } override fun visitMap(mapType: MapType) { val map = (value as MapValueElement).value val keyType = mapType.keyType.trueType val valueType = mapType.valueType.trueType val keyTypeName = typeResolver.getJavaClass(keyType) val valueTypeName = typeResolver.getJavaClass(valueType) val mapImplName = typeResolver.mapOf(keyTypeName, valueTypeName) if (needsDeclaration) { initializer.addStatement("\$T \$N = new \$T()", ParameterizedTypeName.get(TypeNames.MAP, keyTypeName, valueTypeName), name, mapImplName) } else { initializer.addStatement("\$N = new \$T()", name, mapImplName) } for ((key, value1) in map) { val keyName = renderConstValue(initializer, allocator, scope, keyType, key) val valueName = renderConstValue(initializer, allocator, scope, valueType, value1) initializer.addStatement("\$N.put(\$L, \$L)", name, keyName, valueName) } } override fun visitStruct(structType: StructType) { // TODO: this throw UnsupportedOperationException("struct-type default values are not yet implemented") } override fun visitTypedef(typedefType: TypedefType) { throw AssertionError("Should not be possible!") } override fun visitService(serviceType: ServiceType) { throw AssertionError("Should not be possible!") } override fun visitVoid(voidType: BuiltinType) { throw AssertionError("Should not be possible!") } }) } fun renderConstValue( block: CodeBlock.Builder, allocator: NameAllocator, scope: AtomicInteger, type: ThriftType, value: ConstValueElement): CodeBlock { return type.accept(ConstRenderingVisitor(block, allocator, scope, type, value)) } private inner class ConstRenderingVisitor( internal val block: CodeBlock.Builder, internal val allocator: NameAllocator, internal val scope: AtomicInteger, internal val type: ThriftType, internal val value: ConstValueElement ) : ThriftType.Visitor<CodeBlock> { private fun getNumberLiteral(element: ConstValueElement): Any { if (element !is IntValueElement) { throw AssertionError("Expected an int or double, got: " + element) } return if (element.thriftText.startsWith("0x") || element.thriftText.startsWith("0X")) { element.thriftText } else { element.value } } override fun visitBool(boolType: BuiltinType): CodeBlock { val name = if (value is IdentifierValueElement && value.value in setOf("true", "false")) { value.value } else if (value is IntValueElement) { if (value.value == 0L) "false" else "true" } else { return constantOrError("Invalid boolean constant") } return CodeBlock.builder().add(name).build() } override fun visitByte(byteType: BuiltinType): CodeBlock { return if (value is IntValueElement) { CodeBlock.builder().add("(byte) \$L", getNumberLiteral(value)).build() } else { constantOrError("Invalid byte constant") } } override fun visitI16(i16Type: BuiltinType): CodeBlock { return if (value is IntValueElement) { CodeBlock.builder().add("(short) \$L", getNumberLiteral(value)).build() } else { constantOrError("Invalid i16 constant") } } override fun visitI32(i32Type: BuiltinType): CodeBlock { return if (value is IntValueElement) { CodeBlock.builder().add("\$L", getNumberLiteral(value)).build() } else { constantOrError("Invalid i32 constant") } } override fun visitI64(i64Type: BuiltinType): CodeBlock { return if (value is IntValueElement) { CodeBlock.builder().add("\$LL", getNumberLiteral(value)).build() } else { constantOrError("Invalid i64 constant") } } override fun visitDouble(doubleType: BuiltinType): CodeBlock { return when (value) { is IntValueElement -> CodeBlock.of("(double) \$L", value.value) is DoubleValueElement -> CodeBlock.of("\$L", value.value) else -> constantOrError("Invalid double constant") } } override fun visitString(stringType: BuiltinType): CodeBlock { return if (value is LiteralValueElement) { CodeBlock.builder().add("\$S", value.value).build() } else { constantOrError("Invalid string constant") } } override fun visitBinary(binaryType: BuiltinType): CodeBlock { throw UnsupportedOperationException("Binary literals are not supported") } override fun visitVoid(voidType: BuiltinType): CodeBlock { throw AssertionError("Void literals are meaningless, what are you even doing") } override fun visitEnum(enumType: EnumType): CodeBlock { val member = try { when (value) { is IntValueElement -> enumType.findMemberById(value.value.toInt()) is IdentifierValueElement -> { // TODO(ben): Figure out how to handle const references // Remove the enum name prefix, assuming it is present val name = value.value.split(".").last() enumType.findMemberByName(name) } else -> throw AssertionError("Constant value $value is not possibly an enum; validation bug") } } catch (e: NoSuchElementException) { throw IllegalStateException( "No enum member in ${enumType.name} with value $value") } return CodeBlock.builder() .add("\$T.\$L", typeResolver.getJavaClass(enumType), member.name) .build() } override fun visitList(listType: ListType): CodeBlock { return if (value is ListValueElement) { if (value.value.isEmpty()) { val elementType = typeResolver.getJavaClass(listType.elementType) CodeBlock.builder() .add("\$T.<\$T>emptyList()", TypeNames.COLLECTIONS, elementType) .build() } else { visitCollection(listType, "list", "unmodifiableList") } } else { constantOrError("Invalid list constant") } } override fun visitSet(setType: SetType): CodeBlock { return if (value is ListValueElement) { // not a typo; ListValueElement covers lists and sets. if (value.value.isEmpty()) { val elementType = typeResolver.getJavaClass(setType.elementType) CodeBlock.builder() .add("\$T.<\$T>emptySet()", TypeNames.COLLECTIONS, elementType) .build() } else { visitCollection(setType, "set", "unmodifiableSet") } } else { constantOrError("Invalid set constant") } } override fun visitMap(mapType: MapType): CodeBlock { return if (value is MapValueElement) { if (value.value.isEmpty()) { val keyType = typeResolver.getJavaClass(mapType.keyType) val valueType = typeResolver.getJavaClass(mapType.valueType) CodeBlock.builder() .add("\$T.<\$T, \$T>emptyMap()", TypeNames.COLLECTIONS, keyType, valueType) .build() } else { visitCollection(mapType, "map", "unmodifiableMap") } } else { constantOrError("Invalid map constant") } } private fun visitCollection( type: ThriftType, tempName: String, method: String): CodeBlock { val name = allocator.newName(tempName, scope.getAndIncrement()) generateFieldInitializer(block, allocator, scope, name, type, value, true) return CodeBlock.builder().add("\$T.\$L(\$N)", TypeNames.COLLECTIONS, method, name).build() } override fun visitStruct(structType: StructType): CodeBlock { throw IllegalStateException("nested structs not implemented") } override fun visitTypedef(typedefType: TypedefType): CodeBlock { return typedefType.oldType.accept(this) } override fun visitService(serviceType: ServiceType): CodeBlock { throw IllegalStateException("constants cannot be services") } private fun constantOrError(error: String): CodeBlock { val message = "$error: $value + at ${value.location}" if (value !is IdentifierValueElement) { throw IllegalStateException(message) } val expectedType = type.trueType var name = value.value val ix = name.indexOf('.') var expectedProgram: String? = null if (ix != -1) { expectedProgram = name.substring(0, ix) name = name.substring(ix + 1) } // TODO(ben): Think of a more systematic way to know what [Program] owns a thrift element val c = schema.constants .asSequence() .filter { it.name == name } .filter { it.type.trueType == expectedType } .filter { expectedProgram == null || it.location.programName == expectedProgram } .firstOrNull() ?: throw IllegalStateException(message) val packageName = c.getNamespaceFor(NamespaceScope.JAVA) return CodeBlock.builder().add("$packageName.Constants.$name").build() } } }
apache-2.0
917d1cfb08049a70d7c76cce809a841b
41.130081
116
0.58343
5.353306
false
false
false
false
micolous/metrodroid
src/main/java/au/id/micolous/metrodroid/util/ExportHelper.kt
1
6970
/* * ExportHelper.kt * * Copyright (C) 2011 Eric Butler <[email protected]> * Copyright 2018 Michael Farrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package au.id.micolous.metrodroid.util import android.content.ContentValues import android.content.Context import android.database.Cursor import android.net.Uri import android.os.Build import au.id.micolous.metrodroid.card.* import au.id.micolous.metrodroid.multi.Localizer import au.id.micolous.metrodroid.multi.R import au.id.micolous.metrodroid.serializers.* import au.id.micolous.metrodroid.time.MetroTimeZone import au.id.micolous.metrodroid.time.TimestampFull import org.jetbrains.annotations.NonNls import java.io.InputStream import java.io.OutputStream import java.security.MessageDigest import java.util.zip.ZipEntry import java.util.zip.ZipOutputStream import au.id.micolous.metrodroid.provider.CardDBHelper import au.id.micolous.metrodroid.provider.CardProvider import au.id.micolous.metrodroid.provider.CardsTableColumns import kotlin.text.Charsets object ExportHelper { fun copyXmlToClipboard(context: Context, xml: String) { Utils.copyTextToClipboard(context, "metrodroid card", xml) } @NonNls private fun strongHash(cursor: Cursor): String { @NonNls val serial = cursor.getString(cursor.getColumnIndex(CardsTableColumns.TAG_SERIAL)).trim { it <= ' ' } @NonNls val data = XmlUtils.cutXmlDef( cursor.getString(cursor.getColumnIndex(CardsTableColumns.DATA)).trim { it <= ' ' }) val md = MessageDigest.getInstance("SHA-512") md.update(("(${serial.length}, ${data.length})").toByteArray(Charsets.UTF_8)) md.update(serial.toByteArray(Charsets.UTF_8)) md.update(data.toByteArray(Charsets.UTF_8)) return ImmutableByteArray.getHexString(md.digest()) } fun findDuplicates(context: Context): Set<Long> { val cursor = CardDBHelper.createCursor(context) ?: return setOf() val hashes: MutableSet<String> = HashSet() val res = HashSet<Long>() while (cursor.moveToNext()) { @NonNls val hash = strongHash(cursor) if (hash in hashes) { res.add(cursor.getLong(cursor.getColumnIndex(CardsTableColumns._ID))) continue } hashes += hash } return res } /** * Adds a file from a [String] to a ZIP file ([ZipOutputStream]). * * @param zo The ZIP file to write to * @param ts The timestamp to set on the file * @param name A filename for the new ZIP entry * @param contents The contents of the file to write. This will be encoded in UTF-8. */ private fun zipFileFromString(zo: ZipOutputStream, ts: TimestampFull?, name: String, contents: String) { ZipEntry(name).let { ze -> if (ts != null) ze.time = ts.timeInMillis zo.putNextEntry(ze) } zo.write(ImmutableByteArray.fromUTF8(contents).dataCopy) zo.closeEntry() } fun exportCardsZip(os: OutputStream, context: Context) { val cursor = CardDBHelper.createCursor(context) ?: return val zo = ZipOutputStream(os) val used: MutableSet<String> = HashSet() val now = TimestampFull.now() zipFileFromString(zo, now, "README.${Preferences.language}.txt", Localizer.localizeString(R.string.exported_at, now.format()) + "\n" + Utils.deviceInfoString) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) zipFileFromString(zo, now, "README.txt", Localizer.englishString(R.string.exported_at, now.isoDateTimeFormat()) + "\n" + Utils.deviceInfoStringEnglish) while (cursor.moveToNext()) { val content = cursor.getString(cursor.getColumnIndex(CardsTableColumns.DATA)).trim { it <= ' ' } val scannedAt = cursor.getLong(cursor.getColumnIndex(CardsTableColumns.SCANNED_AT)) val tagId = cursor.getString(cursor.getColumnIndex(CardsTableColumns.TAG_SERIAL)) val scannedAtTs = TimestampFull(scannedAt, MetroTimeZone.LOCAL) val ext = if (content[0] == '<') "xml" else "json" var name: String var gen = 0 do name = makeFilename(tagId, scannedAtTs, ext, gen++) while (used.contains(name)) used.add(name) zipFileFromString(zo, scannedAtTs, name, content) } zo.close() } fun importCards(istream: InputStream, importer: CardImporter, context: Context): Collection<Uri> { val it = importer.readCards(istream) ?: return emptyList() return importCards(it, context) } fun importCards(s: String, importer: CardImporter, context: Context): Collection<Uri> { val it = importer.readCards(s) ?: return emptyList() return importCards(it, context) } private fun importCards(it: Iterator<Card>, context: Context): Collection<Uri> = it.asSequence().mapNotNull { c -> importCard(c, context) }.toList() private fun importCard(c: Card, context: Context): Uri? { val cv = ContentValues() cv.put(CardsTableColumns.TYPE, c.cardType.toInteger()) cv.put(CardsTableColumns.TAG_SERIAL, c.tagId.toHexString()) cv.put(CardsTableColumns.DATA, CardSerializer.toPersist(c)) cv.put(CardsTableColumns.SCANNED_AT, c.scannedAt.timeInMillis) if (c.label != null) { cv.put(CardsTableColumns.LABEL, c.label) } return context.contentResolver.insert(CardProvider.CONTENT_URI_CARD, cv) } private fun readCardDataFromCursor(cursor: Cursor): String = cursor.getString(cursor.getColumnIndex(CardsTableColumns.DATA)) private fun readCardsXml(cursor: Cursor): Iterator<String> = IteratorTransformer(CursorIterator(cursor), this::readCardDataFromCursor) fun deleteSet(context: Context, tf: Iterable<Long>): Int { @NonNls val s = "(" + tf.joinToString(", ") + ")" return context.contentResolver.delete(CardProvider.CONTENT_URI_CARD, "${CardsTableColumns._ID} in $s", null) } }
gpl-3.0
61cbc5f634c2649e62e03258fb540ae1
37.722222
130
0.657676
4.297164
false
false
false
false
GunoH/intellij-community
platform/projectModel-impl/src/com/intellij/openapi/components/service.kt
2
3067
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.components import com.intellij.codeWithMe.ClientId import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.impl.stores.IComponentStore import org.jetbrains.annotations.ApiStatus /** * This is primarily intended to be used by the service implementation. When introducing a new service, * please add a static `getInstance()` method. For better tooling performance, it is always advised * to keep an explicit method return type. * * @Service * class MyApplicationService { * companion object { * @JvmStatic * fun getInstance(): MyApplicationService = service() * } * } * * Using a `getInstance()` method is preferred over a property, because: * * - It makes it more clear on the call site that it can involve loading the service, which might not be cheap. * * - Loading the service can throw an exception, and having an exception thrown by a method call is less surprising * than if it was caused by property access. * * - (Over-)using properties may be error-prone in a way that it might be accidentally changed to a property with an initializer * instead of the correct (but more verbose) property with a getter, and that change can easily be overlooked. * * - Using the method instead of a property keeps `MyApplicationService.getInstance()` calls consistent * when used both in Kotlin, and Java. * * - Using the method keeps `MyApplicationService.getInstance()` consistent with `MyProjectService.getInstance(project)`, * both on the declaration and call sites. */ inline fun <reified T : Any> service(): T { val serviceClass = T::class.java return ApplicationManager.getApplication().getService(serviceClass) ?: throw RuntimeException("Cannot find service ${serviceClass.name} (classloader=${serviceClass.classLoader}, client=${ClientId.currentOrNull})") } /** * Contrary to [serviceIfCreated], tries to initialize the service if not yet initialized */ inline fun <reified T : Any> serviceOrNull(): T? = ApplicationManager.getApplication().getService(T::class.java) /** * Contrary to [serviceOrNull], doesn't try to initialize the service if not yet initialized */ inline fun <reified T : Any> serviceIfCreated(): T? = ApplicationManager.getApplication()?.getServiceIfCreated(T::class.java) /** * @deprecated Use override accepting {@link ClientKind} for better control over kinds of clients the services are requested for. */ @ApiStatus.Experimental @Deprecated("Use override accepting {@link ClientKind} for better control over kinds of clients the services are requested for") inline fun <reified T : Any> services(includeLocal: Boolean): List<T> = ApplicationManager.getApplication().getServices(T::class.java, includeLocal) val ComponentManager.stateStore: IComponentStore get() = if (this is ComponentStoreOwner) this.componentStore else service()
apache-2.0
d47c15cb51047b444c577ff7a0a3aa37
48.483871
154
0.748614
4.516937
false
false
false
false