Datasets:
repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/instance/tasks/InstanceReload.kt | 1 | 1052 | package com.cognifide.gradle.aem.instance.tasks
import com.cognifide.gradle.aem.common.instance.action.AwaitUpAction
import com.cognifide.gradle.aem.common.instance.action.ReloadAction
import com.cognifide.gradle.aem.common.instance.names
import com.cognifide.gradle.aem.common.tasks.Instance
import org.gradle.api.tasks.TaskAction
open class InstanceReload : Instance() {
private var reloadOptions: ReloadAction.() -> Unit = {}
fun reload(options: ReloadAction.() -> Unit) {
this.reloadOptions = options
}
private var awaitUpOptions: AwaitUpAction.() -> Unit = {}
fun awaitUp(options: AwaitUpAction.() -> Unit) {
this.awaitUpOptions = options
}
@TaskAction
fun reload() {
instanceManager.awaitReloaded(anyInstances, reloadOptions, awaitUpOptions)
common.notifier.lifecycle("Instance(s) reloaded", "Which: ${anyInstances.names}")
}
init {
description = "Reloads all AEM instance(s)."
}
companion object {
const val NAME = "instanceReload"
}
}
| apache-2.0 | 58e4760293fa5e3870e9b9a12efdab8f | 28.222222 | 89 | 0.70057 | 4.109375 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/status/StatusView.kt | 1 | 8490 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.ui.status
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewTreeObserver
import cn.dreamtobe.kpswitch.util.KeyboardUtil
import com.linkedin.android.spyglass.suggestions.SuggestionsResult
import com.linkedin.android.spyglass.suggestions.interfaces.Suggestible
import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsResultListener
import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsVisibilityManager
import com.linkedin.android.spyglass.tokenization.QueryToken
import com.linkedin.android.spyglass.tokenization.impl.WordTokenizer
import com.linkedin.android.spyglass.tokenization.impl.WordTokenizerConfig
import com.linkedin.android.spyglass.tokenization.interfaces.QueryTokenReceiver
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.base.AbstractActivity
import com.sinyuk.fanfou.base.AbstractFragment
import com.sinyuk.fanfou.di.Injectable
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.domain.DO.Status
import com.sinyuk.fanfou.domain.STATUS_LIMIT
import com.sinyuk.fanfou.domain.StatusCreation
import com.sinyuk.fanfou.domain.TIMELINE_CONTEXT
import com.sinyuk.fanfou.ui.editor.EditorView
import com.sinyuk.fanfou.ui.editor.MentionListView
import com.sinyuk.fanfou.ui.timeline.TimelineView
import com.sinyuk.fanfou.util.obtainViewModelFromActivity
import com.sinyuk.fanfou.viewmodel.FanfouViewModelFactory
import com.sinyuk.fanfou.viewmodel.PlayerViewModel
import kotlinx.android.synthetic.main.status_view.*
import kotlinx.android.synthetic.main.status_view_footer.*
import kotlinx.android.synthetic.main.status_view_reply_actionbar.*
import javax.inject.Inject
/**
* Created by sinyuk on 2018/1/12.
*
*/
class StatusView : AbstractFragment(), Injectable, QueryTokenReceiver, SuggestionsResultListener, SuggestionsVisibilityManager {
companion object {
fun newInstance(status: Status, photoExtra: Bundle? = null) = StatusView().apply {
arguments = Bundle().apply {
putParcelable("status", status)
putBundle("photoExtra", photoExtra)
}
}
}
override fun layoutId() = R.layout.status_view
@Inject
lateinit var factory: FanfouViewModelFactory
private val playerViewModel by lazy { obtainViewModelFromActivity(factory, PlayerViewModel::class.java) }
override fun onEnterAnimationEnd(savedInstanceState: Bundle?) {
super.onEnterAnimationEnd(savedInstanceState)
navBack.setOnClickListener { onBackPressedSupport() }
setupEditor()
setupKeyboard()
onTextChanged(0)
setupViewPager()
val status = arguments!!.getParcelable<Status>("status")
fullscreenButton.setOnClickListener {
(activity as AbstractActivity).start(EditorView.newInstance(status.id,
replyEt.mentionsText,
StatusCreation.REPOST_STATUS))
replyEt.text = null
}
}
private fun setupViewPager() {
val status = arguments!!.getParcelable<Status>("status")
val bundle = arguments!!.getBundle("photoExtra")
val fragments: List<Fragment> = if (findChildFragment(TimelineView::class.java) == null) {
val mentionView = MentionListView()
mentionView.onItemClickListener = onSuggestionSelectListener
mutableListOf(TimelineView.contextTimeline(TIMELINE_CONTEXT, status, bundle), mentionView)
} else {
mutableListOf(findChildFragment(TimelineView::class.java), MentionListView())
}
viewPager.setPagingEnabled(false)
viewPager.offscreenPageLimit = 1
viewPager.adapter = object : FragmentPagerAdapter(childFragmentManager) {
override fun getItem(position: Int) = fragments[position]
override fun getCount() = fragments.size
}
}
private var keyboardListener: ViewTreeObserver.OnGlobalLayoutListener? = null
private fun setupKeyboard() {
keyboardListener = KeyboardUtil.attach(activity, panelRoot, {
// TODO: how comes the Exception: panelRootContainer must not be null
panelRootContainer?.visibility =
if (it) {
if (replyEt.requestFocus()) replyEt.setSelection(replyEt.text.length)
View.VISIBLE
} else {
replyEt.clearFocus()
View.GONE
}
})
}
private val config = WordTokenizerConfig.Builder()
.setExplicitChars("@")
.setThreshold(3)
.setMaxNumKeywords(5)
.setWordBreakChars(" ").build()
private fun setupEditor() {
replyEt.tokenizer = WordTokenizer(config)
replyEt.setAvoidPrefixOnTap(true)
replyEt.setQueryTokenReceiver(this)
replyEt.setSuggestionsVisibilityManager(this)
replyEt.setAvoidPrefixOnTap(true)
replyCommitButton.setOnClickListener { }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
textCountProgress.min = 0
textCountProgress.max = STATUS_LIMIT
replyEt.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
onTextChanged(s?.length ?: 0)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
/**
* @param count 字数
*/
private fun onTextChanged(count: Int) {
textCountProgress.progress = count
replyCommitButton.isEnabled = count in 1..STATUS_LIMIT
}
private val onSuggestionSelectListener = object : MentionListView.OnItemClickListener {
override fun onItemClick(position: Int, item: Suggestible) {
(item as Player).let {
replyEt.insertMention(it)
displaySuggestions(false)
playerViewModel.updateMentionedAt(it) //
onTextChanged(replyEt.text.length)
replyEt.requestFocus()
replyEt.setSelection(replyEt.text.length)
}
}
}
@Suppress("PrivatePropertyName")
private val BUCKET = "player-mentioned"
override fun onQueryReceived(queryToken: QueryToken): MutableList<String> {
val data = playerViewModel.filter(queryToken.keywords)
onReceiveSuggestionsResult(SuggestionsResult(queryToken, data), BUCKET)
return arrayOf(BUCKET).toMutableList()
}
override fun onReceiveSuggestionsResult(result: SuggestionsResult, bucket: String) {
val data = result.suggestions
if (data?.isEmpty() != false) return
displaySuggestions(true)
findChildFragment(MentionListView::class.java).setData(data)
}
override fun displaySuggestions(display: Boolean) {
viewPager.setCurrentItem(if (display) 1 else 0, true)
}
override fun isDisplayingSuggestions() = viewPager.currentItem == 1
override fun onBackPressedSupport(): Boolean {
when {
panelRootContainer.visibility == View.VISIBLE -> KeyboardUtil.hideKeyboard(panelRootContainer)
isDisplayingSuggestions -> displaySuggestions(false)
else -> pop()
}
return true
}
override fun onDestroy() {
keyboardListener?.let { KeyboardUtil.detach(activity, it) }
activity?.currentFocus?.let { KeyboardUtil.hideKeyboard(it) }
super.onDestroy()
}
} | mit | 5af36f349b9d956a8978f0e89d209a86 | 35.9 | 128 | 0.686071 | 4.762065 | false | false | false | false |
TimePath/java-vfs | src/main/kotlin/com/timepath/vfs/provider/jdbc/JDBCTable.kt | 1 | 1410 | package com.timepath.vfs.provider.jdbc
import com.timepath.vfs.MockFile
import com.timepath.vfs.SimpleVFile
import com.timepath.vfs.provider.ProviderStub
import org.jetbrains.annotations.NonNls
import java.sql.SQLException
import java.text.MessageFormat
import java.util.LinkedList
import java.util.logging.Level
/**
* @author TimePath
*/
class JDBCTable(private val jdbcProvider: JDBCProvider, name: String) : ProviderStub(name) {
override fun get(NonNls name: String) = list().firstOrNull { name == it.name }
SuppressWarnings("NestedTryStatement")
override fun list(): Collection<SimpleVFile> {
val rows = LinkedList<MockFile>()
try {
jdbcProvider.conn.prepareStatement("SELECT * FROM ${name}").let { st ->
st.executeQuery().let { rs ->
val len = rs.getMetaData().getColumnCount()
while (rs.next()) {
val sb = StringBuilder()
for (i in 0..len - 1) {
sb.append('\t').append(rs.getString(i + 1))
}
rows.add(MockFile(rs.getString(1), sb.substring(1)))
}
}
}
} catch (e: SQLException) {
JDBCProvider.LOG.log(Level.SEVERE, MessageFormat.format("Reading from table {0}", name), e)
}
return rows
}
}
| artistic-2.0 | 0f28077c74af286debbd9eba0d5de3ef | 33.390244 | 103 | 0.580142 | 4.40625 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/preference/RoomAvatarPreference.kt | 2 | 1639 | /*
* 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.preference
import android.content.Context
import android.util.AttributeSet
import im.vector.util.VectorUtils
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.data.Room
/**
* Specialized class to target a Room avatar preference.
* Based don the avatar preference class it redefines refreshAvatar() and
* add the new method setConfiguration().
*/
class RoomAvatarPreference : UserAvatarPreference {
private var mRoom: Room? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
override fun refreshAvatar() {
if (null != mAvatarView && null != mRoom) {
VectorUtils.loadRoomAvatar(context, mSession, mAvatarView, mRoom)
}
}
fun setConfiguration(aSession: MXSession, aRoom: Room) {
mSession = aSession
mRoom = aRoom
refreshAvatar()
}
} | apache-2.0 | ed599f3608c83ea8cc0a4af370b5893a | 31.156863 | 103 | 0.723002 | 4.235142 | false | false | false | false |
mikepenz/MaterialDrawer | materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/AbstractToggleableDrawerItem.kt | 1 | 3288 | package com.mikepenz.materialdrawer.model
import android.view.View
import android.widget.CompoundButton
import android.widget.ToggleButton
import androidx.annotation.LayoutRes
import com.mikepenz.materialdrawer.R
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener
import com.mikepenz.materialdrawer.model.interfaces.Checkable
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem
/**
* An abstract [IDrawerItem] implementation describing a drawerItem with support for a toggle
*/
open class AbstractToggleableDrawerItem<Item : AbstractToggleableDrawerItem<Item>> : Checkable, BaseDescribeableDrawerItem<Item, AbstractToggleableDrawerItem.ViewHolder>() {
var isToggleEnabled = true
override var isChecked = false
var onCheckedChangeListener: OnCheckedChangeListener? = null
override val type: Int
get() = R.id.material_drawer_item_primary_toggle
override val layoutRes: Int
@LayoutRes
get() = R.layout.material_drawer_item_toggle
private val checkedChangeListener = object : CompoundButton.OnCheckedChangeListener {
override fun onCheckedChanged(buttonView: CompoundButton, ic: Boolean) {
if (isEnabled) {
isChecked = ic
onCheckedChangeListener?.onCheckedChanged(this@AbstractToggleableDrawerItem, buttonView, ic)
} else {
buttonView.setOnCheckedChangeListener(null)
buttonView.isChecked = !ic
buttonView.setOnCheckedChangeListener(this)
}
}
}
@Deprecated("Please consider to replace with the actual property setter")
fun withToggleEnabled(toggleEnabled: Boolean): Item {
this.isToggleEnabled = toggleEnabled
return this as Item
}
@Deprecated("Please consider to replace with the actual property setter")
fun withOnCheckedChangeListener(onCheckedChangeListener: OnCheckedChangeListener): Item {
this.onCheckedChangeListener = onCheckedChangeListener
return this as Item
}
override fun bindView(holder: ViewHolder, payloads: List<Any>) {
super.bindView(holder, payloads)
//bind the basic view parts
bindViewHelper(holder)
//handle the toggle
holder.toggle.setOnCheckedChangeListener(null)
holder.toggle.isChecked = isChecked
holder.toggle.setOnCheckedChangeListener(checkedChangeListener)
holder.toggle.isEnabled = isToggleEnabled
//add a onDrawerItemClickListener here to be able to check / uncheck if the drawerItem can't be selected
withOnDrawerItemClickListener { v, item, position ->
if (!isSelectable) {
isChecked = !isChecked
holder.toggle.isChecked = isChecked
}
false
}
//call the onPostBindView method to trigger post bind view actions (like the listener to modify the item if required)
onPostBindView(this, holder.itemView)
}
override fun getViewHolder(v: View): ViewHolder {
return ViewHolder(v)
}
open class ViewHolder internal constructor(view: View) : BaseViewHolder(view) {
internal val toggle: ToggleButton = view.findViewById<ToggleButton>(R.id.material_drawer_toggle)
}
}
| apache-2.0 | 6aa352fe5951c4b3b9be36e335b1b810 | 37.232558 | 173 | 0.70955 | 5.452736 | false | false | false | false |
deltadak/plep | src/main/kotlin/nl/deltadak/plep/ui/taskcell/TaskLayout.kt | 1 | 4729 | package nl.deltadak.plep.ui.taskcell
import javafx.geometry.Pos
import javafx.scene.control.CheckBox
import javafx.scene.control.ComboBox
import javafx.scene.control.Label
import javafx.scene.control.TreeItem
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.layout.Region
import javafx.scene.text.TextAlignment
import nl.deltadak.plep.HomeworkTask
import nl.deltadak.plep.database.tables.Colors
import nl.deltadak.plep.ui.taskcell.components.textlabel.TextLabelStyle
import nl.deltadak.plep.ui.taskcell.util.blockerlisteners.ChangeListenerWithBlocker
import nl.deltadak.plep.ui.taskcell.util.blockerlisteners.InvalidationListenerWithBlocker
import nl.deltadak.plep.ui.util.LABEL_MAGIK
/**
* Manages the layout of a TreeCell. Always contains a CheckBox and a Label (text). Also contains a ComboBox (dropdown menu) if the Cell is the root of a task.
* The given components are updated with the correct layout.
*
* @property taskCell Cell to set layout on.
* @property doneChangeListener Should provide the ability to temporarily block the listener of the checkbox.
* @property checkBox Checkbox of the task.
* @property label Text of the task.
* @property labelChangeListener Should provide the ability to temporarily block the listener of the combobox.
* @property root Root item of the TreeView in which the task is.
* @property comboBox Combobox of the task.
*/
class TaskLayout(private val taskCell: TaskCell, private val doneChangeListener: ChangeListenerWithBlocker<Boolean>, private val checkBox: CheckBox, val label: Label, private val labelChangeListener: InvalidationListenerWithBlocker, val root: TreeItem<HomeworkTask>, private val comboBox: ComboBox<String>) {
/**
* Updates the layout.
* The homeworktask could be null, since updating is initiated by JavaFX.
*
* @param homeworkTask The Homework task to be displayed in the Cell.
*/
fun update(homeworkTask: HomeworkTask?) {
if (taskCell.isEmpty) {
taskCell.graphic = null
taskCell.text = null
} else {
if (homeworkTask != null) {
setLayout(homeworkTask)
}
}
}
private fun setLayout(homeworkTask: HomeworkTask) {
// Create the container for components.
val cellBox = HBox(10.0)
cellBox.alignment = Pos.CENTER_LEFT
setCheckBox(homeworkTask)
setTextLabel(homeworkTask)
// Get style from the database and apply to the item.
val color = Colors.get(homeworkTask.colorID)
taskCell.style = "-fx-control-inner-background: #$color"
TextLabelStyle().setDoneStyle(homeworkTask.done, label, comboBox)
// If the item is top level, a parent task, it has to show a course label (ComboBox), and it has to have a context menu.
if (taskCell.treeItem.parent == root) {
val region = setComboBox(homeworkTask)
cellBox.children.addAll(checkBox, label, region, comboBox)
taskCell.graphic = cellBox
taskCell.text = null
} else {
// Set up subtask, with context menu disabled.
with(taskCell) {
contextMenu = null
graphic = cellBox.apply { children.addAll(checkBox, label) }
text = null
}
}
}
/**
* Setup checkbox.
*/
private fun setCheckBox(homeworkTask: HomeworkTask) {
// Block the listener on the checkbox when we manually toggle it, so it corresponds to the value in the database.
doneChangeListener.block = true
val done = homeworkTask.done
// Manually toggle, if necessary.
checkBox.isSelected = done
doneChangeListener.block = false
}
/**
* Setup text label.
*/
private fun setTextLabel(homeworkTask: HomeworkTask) {
with(label) {
text = homeworkTask.text
prefWidthProperty().bind(taskCell.treeView.widthProperty().subtract(LABEL_MAGIK))
isWrapText = true
textAlignment = TextAlignment.JUSTIFY
}
}
/**
* Setup combobox.
*/
private fun setComboBox(homeworkTask: HomeworkTask): Region {
// Before setting value, we need to temporarily disable the listener, otherwise it fires and goes unnecessarily updating the database, which takes a lot of time.
labelChangeListener.block = true
comboBox.value = homeworkTask.label
labelChangeListener.block = false
// Create a region to make sure that the ComboBox is aligned on the right.
val region = Region()
HBox.setHgrow(region, Priority.ALWAYS)
return region
}
}
| mit | 55703359bf4aa0d1e4effebbfc1dc383 | 36.832 | 308 | 0.683866 | 4.705473 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/query/QueryTokenizer.kt | 1 | 2478 | package com.orgzly.android.query
class QueryTokenizer(val str: String, private val groupOpen: String, private val groupClose: String) {
val tokens = tokanize(str)
var nextToken = 0
fun hasMoreTokens(): Boolean = nextToken < tokens.size
fun nextToken() = tokens[nextToken++]
private fun tokanize(str: String): List<String> {
return tokenRegex.findAll(str).map { it.value }.toList()
}
companion object {
val TAG: String = QueryTokenizer::class.java.name
private const val char = """[^")(\s]"""
private const val doubleQuoted = """"[^"\\]*(?:\\.[^"\\]*)*""""
private const val doubleQuotedWithPrefix = """$char*$doubleQuoted"""
private const val groupOpener = """\("""
private const val groupCloser = """\)"""
private const val rest = """$char+"""
private val tokenRegex =
listOf(doubleQuotedWithPrefix, groupOpener, groupCloser, rest)
.joinToString("|").toRegex()
fun unquote(s: String): String {
if (s.length < 2) {
return s
}
val first = s[0]
val last = s[s.length - 1]
if (first != last || first != '"') {
return s
}
val b = StringBuilder(s.length - 2)
var quote = false
for (i in 1 until s.length - 1) {
val c = s[i]
if (c == '\\' && !quote) {
quote = true
continue
}
quote = false
b.append(c)
}
return b.toString()
}
fun quote(s: String, delim: String): String {
if (s.isEmpty()) {
return "\"\""
}
for (element in s) {
if (element == '"' || element == '\\' || delim.indexOf(element) >= 0) {
return quoteUnconditionally(s)
}
}
return s
}
fun quoteUnconditionally(s: String): String {
val builder = StringBuilder(s.length + 8)
builder.append('"')
for (element in s) {
if (element == '"') {
builder.append('\\')
}
builder.append(element)
continue
}
builder.append('"')
return builder.toString()
}
}
} | gpl-3.0 | 1fde97a2f66940fc14668d1837d9747f | 28.164706 | 102 | 0.45682 | 4.783784 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/drawer/DrawerNavigationView.kt | 1 | 5383 | package com.orgzly.android.ui.drawer
import android.content.Intent
import android.content.res.Resources
import android.view.Menu
import androidx.lifecycle.Observer
import com.google.android.material.navigation.NavigationView
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.AppIntent
import com.orgzly.android.db.entity.BookAction
import com.orgzly.android.db.entity.BookView
import com.orgzly.android.db.entity.SavedSearch
import com.orgzly.android.ui.books.BooksFragment
import com.orgzly.android.ui.main.MainActivity
import com.orgzly.android.ui.main.MainActivityViewModel
import com.orgzly.android.ui.notes.book.BookFragment
import com.orgzly.android.ui.notes.query.QueryFragment
import com.orgzly.android.ui.savedsearches.SavedSearchesFragment
import com.orgzly.android.util.LogUtils
import java.util.*
internal class DrawerNavigationView(
private val activity: MainActivity,
viewModel: MainActivityViewModel,
navView: NavigationView) {
private val menu: Menu = navView.menu
private val menuItemIdMap = hashMapOf<String, Int>()
private var activeFragmentTag: String? = null
init {
// Add mapping for groups
menuItemIdMap[BooksFragment.drawerItemId] = R.id.books
menuItemIdMap[SavedSearchesFragment.getDrawerItemId()] = R.id.searches
// Setup intents
menu.findItem(R.id.searches).intent = Intent(AppIntent.ACTION_OPEN_SAVED_SEARCHES)
menu.findItem(R.id.books).intent = Intent(AppIntent.ACTION_OPEN_BOOKS)
menu.findItem(R.id.settings).intent = Intent(AppIntent.ACTION_OPEN_SETTINGS)
viewModel.books().observe(activity, Observer {
refreshFromBooks(it)
})
viewModel.savedSearches().observe(activity, Observer {
refreshFromSavedSearches(it)
})
}
fun updateActiveFragment(fragmentTag: String) {
this.activeFragmentTag = fragmentTag
setActiveItem(fragmentTag)
}
private fun setActiveItem(fragmentTag: String) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, fragmentTag)
this.activeFragmentTag = fragmentTag
val fragment = activity.supportFragmentManager.findFragmentByTag(activeFragmentTag)
// Uncheck all
for (i in 0 until menu.size()) {
menu.getItem(i).isChecked = false
}
if (fragment != null && fragment is DrawerItem) {
val fragmentMenuItemId = fragment.getCurrentDrawerItemId()
val itemId = menuItemIdMap[fragmentMenuItemId]
if (itemId != null) {
menu.findItem(itemId)?.isChecked = true
}
}
}
private fun refreshFromSavedSearches(savedSearches: List<SavedSearch>) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, savedSearches.size)
removeItemsWithOrder(1)
savedSearches.forEach { savedSearch ->
val intent = Intent(AppIntent.ACTION_OPEN_QUERY)
intent.putExtra(AppIntent.EXTRA_QUERY_STRING, savedSearch.query)
val id = generateRandomUniqueId()
val item = menu.add(R.id.drawer_group, id, 1, savedSearch.name)
menuItemIdMap[QueryFragment.getDrawerItemId(savedSearch.query)] = id
item.intent = intent
item.isCheckable = true
}
activeFragmentTag?.let {
setActiveItem(it)
}
}
private fun refreshFromBooks(books: List<BookView>) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, books.size)
removeItemsWithOrder(3)
books.forEach { book ->
val intent = Intent(AppIntent.ACTION_OPEN_BOOK)
intent.putExtra(AppIntent.EXTRA_BOOK_ID, book.book.id)
val id = generateRandomUniqueId()
val name = book.book.run { title ?: name }
val item = menu.add(R.id.drawer_group, id, 3, name)
item.isEnabled = !book.book.isDummy
item.intent = intent
item.isCheckable = true
if (book.book.lastAction?.type == BookAction.Type.ERROR) {
item.setActionView(R.layout.drawer_item_sync_failed)
} else if (book.isOutOfSync()) {
item.setActionView(R.layout.drawer_item_sync_needed)
}
menuItemIdMap[BookFragment.getDrawerItemId(book.book.id)] = id
}
activeFragmentTag?.let {
setActiveItem(it)
}
}
private fun generateRandomUniqueId(): Int {
val rand = Random()
while (true) {
val id = rand.nextInt(Integer.MAX_VALUE) + 1
try {
activity.resources.getResourceName(id)
} catch (e: Resources.NotFoundException) {
return id
}
}
}
private fun removeItemsWithOrder(orderToDelete: Int) {
val itemIdsToRemove = HashSet<Int>()
var i = 0
while (true) {
val item = menu.getItem(i++) ?: break
val order = item.order
if (order > orderToDelete) {
break
} else if (order == orderToDelete) {
itemIdsToRemove.add(item.itemId)
}
}
for (id in itemIdsToRemove) {
menu.removeItem(id)
}
}
companion object {
private val TAG = DrawerNavigationView::class.java.name
}
}
| gpl-3.0 | 23bd78f0ea78f40355777d5e6379a664 | 29.241573 | 91 | 0.636448 | 4.474647 | false | false | false | false |
whym/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/TestCommonsApplication.kt | 1 | 3762 | package fr.free.nrw.commons
import android.content.ContentProviderClient
import android.content.Context
import android.content.SharedPreferences
import android.support.v4.util.LruCache
import com.nhaarman.mockito_kotlin.mock
import com.squareup.leakcanary.RefWatcher
import fr.free.nrw.commons.auth.AccountUtil
import fr.free.nrw.commons.auth.SessionManager
import fr.free.nrw.commons.data.DBOpenHelper
import fr.free.nrw.commons.di.CommonsApplicationComponent
import fr.free.nrw.commons.di.CommonsApplicationModule
import fr.free.nrw.commons.di.DaggerCommonsApplicationComponent
import fr.free.nrw.commons.location.LocationServiceManager
import fr.free.nrw.commons.mwapi.MediaWikiApi
import fr.free.nrw.commons.nearby.NearbyPlaces
import fr.free.nrw.commons.upload.UploadController
class TestCommonsApplication : CommonsApplication() {
private var mockApplicationComponent: CommonsApplicationComponent? = null
override fun onCreate() {
if (mockApplicationComponent == null) {
mockApplicationComponent = DaggerCommonsApplicationComponent.builder()
.appModule(MockCommonsApplicationModule(this)).build()
}
super.onCreate()
}
// No leakcanary in unit tests.
override fun setupLeakCanary(): RefWatcher = RefWatcher.DISABLED
}
@Suppress("MemberVisibilityCanBePrivate")
class MockCommonsApplicationModule(appContext: Context) : CommonsApplicationModule(appContext) {
val accountUtil: AccountUtil = mock()
val appSharedPreferences: SharedPreferences = mock()
val defaultSharedPreferences: SharedPreferences = mock()
val otherSharedPreferences: SharedPreferences = mock()
val uploadController: UploadController = mock()
val mockSessionManager: SessionManager = mock()
val locationServiceManager: LocationServiceManager = mock()
val mockDbOpenHelper: DBOpenHelper = mock()
val nearbyPlaces: NearbyPlaces = mock()
val lruCache: LruCache<String, String> = mock()
val categoryClient: ContentProviderClient = mock()
val contributionClient: ContentProviderClient = mock()
val modificationClient: ContentProviderClient = mock()
val uploadPrefs: SharedPreferences = mock()
override fun provideCategoryContentProviderClient(context: Context?): ContentProviderClient = categoryClient
override fun provideContributionContentProviderClient(context: Context?): ContentProviderClient = contributionClient
override fun provideModificationContentProviderClient(context: Context?): ContentProviderClient = modificationClient
override fun providesDirectNearbyUploadPreferences(context: Context?): SharedPreferences = uploadPrefs
override fun providesAccountUtil(context: Context): AccountUtil = accountUtil
override fun providesApplicationSharedPreferences(context: Context): SharedPreferences = appSharedPreferences
override fun providesDefaultSharedPreferences(context: Context): SharedPreferences = defaultSharedPreferences
override fun providesOtherSharedPreferences(context: Context): SharedPreferences = otherSharedPreferences
override fun providesUploadController(sessionManager: SessionManager, sharedPreferences: SharedPreferences, context: Context): UploadController = uploadController
override fun providesSessionManager(context: Context, mediaWikiApi: MediaWikiApi, sharedPreferences: SharedPreferences): SessionManager = mockSessionManager
override fun provideLocationServiceManager(context: Context): LocationServiceManager = locationServiceManager
override fun provideDBOpenHelper(context: Context): DBOpenHelper = mockDbOpenHelper
override fun provideNearbyPlaces(): NearbyPlaces = nearbyPlaces
override fun provideLruCache(): LruCache<String, String> = lruCache
} | apache-2.0 | b17ee99f85f8731510a4c274d4677b20 | 46.632911 | 166 | 0.805954 | 5.614925 | false | false | false | false |
kmruiz/sonata | frontend/src/main/kotlin/io/sonatalang/snc/frontend/domain/token/NewLineToken.kt | 1 | 324 | package io.sonatalang.snc.frontend.domain.token
object NewLineToken : BasicToken(false), TokenFactory<NewLineToken> {
override fun with(character: Char) = this
override fun toString() = "\n"
override fun isSuitable(character: Char) = character == '\n'
override fun create(character: Char) = NewLineToken
}
| gpl-2.0 | 41dcacab5368a98018db38e1105170de | 35 | 69 | 0.728395 | 4.05 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/sessiondetails/presentationmodel/SessionDetailsPresentationModelTransformer.kt | 1 | 2271 | package com.openconference.sessiondetails.presentationmodel
import com.openconference.model.Session
import org.threeten.bp.LocalDateTime
import org.threeten.bp.ZoneId
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.format.FormatStyle
import java.util.*
/**
* Responsible to transform a Session to [SessionDetailItem]
*
* @author Hannes Dorfmann
*/
interface SessionDetailsPresentationModelTransformer {
fun transform(session: Session): SessionDetail
}
/**
* Phone Session Details Presentation Model Transformer
* @author Hannes Dorfmann
*/
// TODO Tablet
class PhoneSessionDetailsPresentationModelTransformer : SessionDetailsPresentationModelTransformer {
private val dateFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
override fun transform(session: Session): SessionDetail {
val items = ArrayList<SessionDetailItem>()
// TODO use settings for time zone (users preferences)
val zoneId = ZoneId.systemDefault()
val start = session.startTime()
val localStart = if (start == null) null else LocalDateTime.ofInstant(start, zoneId)
val end = session.endTime()
val localEnd = if (end == null) null else LocalDateTime.ofInstant(end, zoneId)
if (start != null) {
val dateStr = if (end != null) {
"${dateFormatter.format(localStart)} - ${dateFormatter.format(localEnd)}"
} else {
dateFormatter.format(localStart)
}
items.add(SessionDateTimeItem(dateStr))
}
// Location
val locationName = session.locationName()
if (locationName != null) items.add(SessionLocationItem(locationName))
// Description
val description = session.description()
if (description != null) {
if (items.isNotEmpty()) items.add(SessionSeparatorItem())
items.add(SessionDescriptionItem(description))
}
// TODO TAGS
// Tags
/*
val tags = session.tags()
if (tags != null) items.add(SessionTagsItem(tags))
*/
// Speakers
if (session.speakers().isNotEmpty()) {
items.add(SessionSeparatorItem())
}
session.speakers().forEach { items.add(SessionSpeakerItem(it)) }
// TODO refactor
return SessionDetail(session.id(), session.title(), session, items, session.favorite())
}
} | apache-2.0 | 82de0443dfb89a114e7cea847cdc68d1 | 27.4 | 100 | 0.713342 | 4.560241 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/traktapi/CheckInDialogFragment.kt | 1 | 1942 | package com.battlelancer.seriesguide.traktapi
import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import com.battlelancer.seriesguide.provider.SgRoomDatabase.Companion.getInstance
import com.battlelancer.seriesguide.util.TextTools
import com.battlelancer.seriesguide.util.safeShow
/**
* Allows to check into an episode. Launching activities should subscribe to
* [TraktTask.TraktActionCompleteEvent] to display status toasts.
*/
class CheckInDialogFragment : GenericCheckInDialogFragment() {
override fun checkInTrakt(message: String) {
TraktTask(requireContext()).checkInEpisode(
requireArguments().getLong(ARG_EPISODE_ID),
requireArguments().getString(ARG_ITEM_TITLE),
message
).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
}
companion object {
/**
* Builds and shows a new [CheckInDialogFragment] setting all values based on the given
* episode row ID.
*
* @return `false` if the fragment was not shown.
*/
fun show(context: Context, fragmentManager: FragmentManager, episodeId: Long): Boolean {
val episode = getInstance(context).sgEpisode2Helper().getEpisodeWithShow(episodeId)
?: return false
val f = CheckInDialogFragment()
val args = Bundle()
args.putLong(ARG_EPISODE_ID, episodeId)
val episodeTitleWithNumbers = (episode.seriestitle
+ " "
+ TextTools.getNextEpisodeString(
context,
episode.season,
episode.episodenumber,
episode.episodetitle
))
args.putString(ARG_ITEM_TITLE, episodeTitleWithNumbers)
f.arguments = args
return f.safeShow(fragmentManager, "checkInDialog")
}
}
} | apache-2.0 | 8d8c7fd133c47abfc729684673c1adc7 | 35.660377 | 96 | 0.656025 | 5.044156 | false | false | false | false |
redpen-cc/redpen-intellij-plugin | src/cc/redpen/intellij/StatusWidget.kt | 1 | 5697 | package cc.redpen.intellij
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.LangDataKeys.PSI_FILE
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.CustomStatusBarWidget
import com.intellij.openapi.wm.StatusBarWidget
import com.intellij.openapi.wm.StatusBarWidget.WidgetBorder.WIDE
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.status.EditorBasedWidget
import com.intellij.openapi.wm.impl.status.TextPanel
import com.intellij.psi.PsiManager
import com.intellij.ui.ClickListener
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.ui.UIUtil
import java.awt.Component
import java.awt.Graphics
import java.awt.Point
import java.awt.event.MouseEvent
open class StatusWidget constructor(project: Project) : EditorBasedWidget(project), CustomStatusBarWidget, ProjectComponent {
val provider = RedPenProvider.forProject(project)
var enabled: Boolean = false
val actionGroupId = "RedPen " + project.basePath
companion object {
fun forProject(project: Project) = project.getComponent(StatusWidget::class.java)!!
}
var actionGroup: DefaultActionGroup? = null
private val component = object: TextPanel.ExtraSize() {
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (enabled && text != null) {
val arrows = AllIcons.Ide.Statusbar_arrows
arrows.paintIcon(this, g, bounds.width - insets.right - arrows.iconWidth - 2,
bounds.height / 2 - arrows.iconHeight / 2)
}
}
}
override fun projectOpened() {
install(WindowManager.getInstance().getStatusBar(project))
myStatusBar.addWidget(this, "before Encoding")
object : ClickListener() {
override fun onClick(e: MouseEvent, clickCount: Int): Boolean {
showPopup(e)
return true
}
}.installOn(component)
component.border = WIDE
component.toolTipText = "RedPen language"
registerActions()
}
override fun projectClosed() {
myStatusBar.removeWidget(ID())
unregisterActions()
}
override fun getComponentName(): String = "StatusWidget"
override fun initComponent() {}
override fun disposeComponent() {}
open fun registerActions() {
val actionManager = ActionManager.getInstance() ?: return
actionGroup = DefaultActionGroup()
provider.configs.keys.forEach { key ->
actionGroup!!.add(object : AnAction() {
init { templatePresentation.text = key }
override fun actionPerformed(e: AnActionEvent) {
provider.setConfigFor(e.getData(PSI_FILE)!!, key)
DaemonCodeAnalyzer.getInstance(e.project).restart()
}
})
}
actionManager.registerAction(actionGroupId, actionGroup!!)
}
open internal fun unregisterActions() {
ActionManager.getInstance()?.unregisterAction(actionGroupId)
}
override fun ID(): String {
return "RedPen"
}
override fun getPresentation(platformType: StatusBarWidget.PlatformType): StatusBarWidget.WidgetPresentation? {
return null
}
open fun update(configKey: String) {
if (isDisposed) return
ApplicationManager.getApplication().invokeLater {
component.text = configKey
component.foreground = if (enabled) UIUtil.getActiveTextColor() else UIUtil.getInactiveTextColor()
}
}
override fun selectionChanged(event: FileEditorManagerEvent) {
val file = if (event.newFile == null) null else PsiManager.getInstance(project!!).findFile(event.newFile!!)
if (file != null && provider.getParser(file) != null) {
enabled = true
update(provider.getConfigKeyFor(file))
}
else {
enabled = false
update("n/a")
}
}
override fun getComponent(): TextPanel {
return component
}
internal fun showPopup(e: MouseEvent) {
if (!enabled) return
val popup = JBPopupFactory.getInstance().createActionGroupPopup(
"RedPen", actionGroup!!, getContext(), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false)
val dimension = popup.content.preferredSize
val at = Point(0, -dimension.height)
popup.show(RelativePoint(e.component, at))
Disposer.register(this, popup)
}
private fun getContext(): DataContext {
val editor = editor
val parent = DataManager.getInstance().getDataContext(myStatusBar as Component)
return SimpleDataContext.getSimpleContext(
CommonDataKeys.VIRTUAL_FILE_ARRAY.name,
arrayOf(selectedFile!!),
SimpleDataContext.getSimpleContext(CommonDataKeys.PROJECT.name,
project,
SimpleDataContext.getSimpleContext(PlatformDataKeys.CONTEXT_COMPONENT.name,
editor?.component, parent)))
}
fun rebuild() {
unregisterActions()
registerActions()
}
}
| apache-2.0 | 2b4053ba36d846e90b27bb160e47611f | 35.754839 | 125 | 0.672284 | 5.07754 | false | false | false | false |
ColaGom/KtGitCloner | src/main/kotlin/net/ProjectExtractor.kt | 1 | 1848 | package net
import SearchResponse
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import data.Repository
import java.io.PrintWriter
import java.nio.file.Path
class ProjectExtractor(val savePath: Path, val start:String, val end:String)
{
fun extract(page : Int = 0)
{
var results = HashMap<String, Repository>()
var totalCount = 0
val requestBuilder = RequestBuilder(start, end)
if(savePath.toFile().exists())
results = Gson().fromJson(savePath.toFile().readText(), object : TypeToken<HashMap<String, Repository>>() {}.type)
requestBuilder.page = page;
while(true)
{
val (request, response, result) = requestBuilder.build().responseObject(SearchResponse.Deserializer());
val (search, err) = result
println(request.url)
search?.let {
search.items.forEach({
if(it.full_name.isNullOrEmpty() || it.language.isNullOrEmpty())
return@forEach
if(!results.containsKey(it.full_name) && it.size < 2048000 && it.language.equals("Java")) {
results.put(it.full_name, it);
println("added ${it.full_name}")
}
})
totalCount += search.items.size;
}
if(requestBuilder.page > 34)
break
else if(err != null) {
Thread.sleep(10000)
}else if(search!!.items.isEmpty())
break
else
requestBuilder.page++;
}
savePath.toFile().printWriter().use { out: PrintWriter ->
out.print(GsonBuilder().setPrettyPrinting().create().toJson(results))
}
}
}
| apache-2.0 | 3513c1b5dd0c5a0b9408d758f58f142a | 30.322034 | 126 | 0.555195 | 4.738462 | false | false | false | false |
duftler/orca | orca-queue-tck/src/main/kotlin/com/netflix/spinnaker/orca/q/ExecutionLatch.kt | 1 | 3713 | /*
* Copyright 2017 Netflix, 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 com.netflix.spinnaker.orca.q
import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.events.ExecutionComplete
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import org.springframework.context.ApplicationListener
import org.springframework.context.ConfigurableApplicationContext
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.function.Predicate
/**
* An [ApplicationListener] implementation you can use to wait for an execution
* to complete. Much better than `Thread.sleep(whatever)` in your tests.
*/
class ExecutionLatch(private val predicate: Predicate<ExecutionComplete>) :
ApplicationListener<ExecutionComplete> {
private val latch = CountDownLatch(1)
override fun onApplicationEvent(event: ExecutionComplete) {
if (predicate.test(event)) {
latch.countDown()
}
}
fun await() = latch.await(10, TimeUnit.SECONDS)
}
fun ConfigurableApplicationContext.runToCompletion(execution: Execution, launcher: (Execution) -> Unit, repository: ExecutionRepository) {
val latch = ExecutionLatch(Predicate {
it.executionId == execution.id
})
addApplicationListener(latch)
launcher.invoke(execution)
assert(latch.await()) { "Pipeline did not complete" }
repository.waitForAllStagesToComplete(execution)
}
/**
* Given parent and child pipelines:
* 1) Start child pipeline
* 2) Invoke parent pipeline and continue until completion
*
* Useful for testing failure interactions between pipelines. Child pipeline can be inspected prior to
* completion, and subsequently completed via [runToCompletion].
*/
fun ConfigurableApplicationContext.runParentToCompletion(
parent: Execution,
child: Execution,
launcher: (Execution) -> Unit,
repository: ExecutionRepository
) {
val latch = ExecutionLatch(Predicate {
it.executionId == parent.id
})
addApplicationListener(latch)
launcher.invoke(child)
launcher.invoke(parent)
assert(latch.await()) { "Pipeline did not complete" }
repository.waitForAllStagesToComplete(parent)
}
fun ConfigurableApplicationContext.restartAndRunToCompletion(stage: Stage, launcher: (Execution, String) -> Unit, repository: ExecutionRepository) {
val execution = stage.execution
val latch = ExecutionLatch(Predicate {
it.executionId == execution.id
})
addApplicationListener(latch)
launcher.invoke(execution, stage.id)
assert(latch.await()) { "Pipeline did not complete after restarting" }
repository.waitForAllStagesToComplete(execution)
}
private fun ExecutionRepository.waitForAllStagesToComplete(execution: Execution) {
var complete = false
while (!complete) {
Thread.sleep(100)
complete = retrieve(PIPELINE, execution.id)
.run {
status.isComplete && stages
.map(Stage::getStatus)
.all { it.isComplete || it == NOT_STARTED }
}
}
}
| apache-2.0 | 9f7e49b478f4afae4843f98df40e083b | 33.06422 | 148 | 0.764611 | 4.425507 | false | false | false | false |
willowtreeapps/assertk | assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt | 1 | 8247 | package test.assertk.assertions
import assertk.assertThat
import assertk.assertions.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class MapTest {
//region contains
@Test fun contains_element_present_passes() {
assertThat(mapOf("one" to 1, "two" to 2)).contains("two" to 2)
}
@Test fun contains_element_missing_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int>()).contains("one" to 1)
}
assertEquals("expected to contain:<{\"one\"=1}> but was:<{}>", error.message)
}
@Test fun contains_element_with_nullable_value_missing_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int?>()).contains("one" to null)
}
assertEquals("expected to contain:<{\"one\"=null}> but was:<{}>", error.message)
}
//endregion
//region doesNotContain
@Test fun doesNotContain_element_missing_passes() {
assertThat(emptyMap<String, Int>()).doesNotContain("one" to 1)
}
@Test fun doesNotContain_element_with_missing_nullable_value_passes() {
assertThat(emptyMap<String, Int?>()).doesNotContain("one" to null)
}
@Test fun doesNotContain_element_present_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).doesNotContain("two" to 2)
}
assertEquals("expected to not contain:<{\"two\"=2}> but was:<{\"one\"=1, \"two\"=2}>", error.message)
}
//endregion
//region containsNone
@Test fun containsNone_missing_elements_passes() {
assertThat(emptyMap<String, Int>()).containsNone("one" to 1)
}
@Test fun containsNone_missing_elements_with_nullable_value_passes() {
assertThat(emptyMap<String, Int?>()).containsNone("one" to null)
}
@Test fun containsNone_present_element_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).containsNone("two" to 2, "three" to 3)
}
assertEquals(
"""expected to contain none of:<{"two"=2, "three"=3}> but was:<{"one"=1, "two"=2}>
| elements not expected:<{"two"=2}>
""".trimMargin(),
error.message
)
}
//region
//region containsAll
@Test fun containsAll_all_elements_passes() {
assertThat(mapOf("one" to 1, "two" to 2)).containsAll("two" to 2, "one" to 1)
}
@Test fun containsAll_extra_elements_passes() {
assertThat(mapOf("one" to 1, "two" to 2, "three" to 3)).containsAll("one" to 1, "two" to 2)
}
@Test fun containsAll_swapped_keys_and_values_fails() {
val error = assertFails {
assertThat(mapOf("one" to 2, "two" to 1)).containsAll("two" to 2, "one" to 1)
}
assertEquals(
"""expected to contain all:<{"two"=2, "one"=1}> but was:<{"one"=2, "two"=1}>
| elements not found:<{"two"=2, "one"=1}>
""".trimMargin(), error.message
)
}
@Test fun containsAll_nullable_values_fails() {
val error = assertFails {
assertThat(mapOf<String, Any?>()).containsAll("key" to null)
}
assertEquals(
"""expected to contain all:<{"key"=null}> but was:<{}>
| elements not found:<{"key"=null}>
""".trimMargin(), error.message
)
}
@Test fun containsAll_some_elements_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1)).containsAll("one" to 1, "two" to 2)
}
assertEquals(
"""expected to contain all:<{"one"=1, "two"=2}> but was:<{"one"=1}>
| elements not found:<{"two"=2}>
""".trimMargin(),
error.message
)
}
//endregion
//region containsOnly
@Test fun containsOnly_all_elements_passes() {
assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("two" to 2, "one" to 1)
}
@Test fun containsOnly_swapped_keys_and_values_fails() {
val error = assertFails {
assertThat(mapOf("one" to 2, "two" to 1)).containsOnly("two" to 2, "one" to 1)
}
assertEquals(
"""expected to contain only:<{"two"=2, "one"=1}> but was:<{"one"=2, "two"=1}>
| elements not found:<{"two"=2, "one"=1}>
| extra elements found:<{"one"=2, "two"=1}>
""".trimMargin(), error.message
)
}
@Test fun containsOnly_missing_element_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("three" to 3)
}
assertEquals(
"""expected to contain only:<{"three"=3}> but was:<{"one"=1, "two"=2}>
| elements not found:<{"three"=3}>
| extra elements found:<{"one"=1, "two"=2}>
""".trimMargin(), error.message
)
}
@Test fun containsOnly_extra_element_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("one" to 1)
}
assertEquals(
"""expected to contain only:<{"one"=1}> but was:<{"one"=1, "two"=2}>
| extra elements found:<{"two"=2}>
""".trimMargin(), error.message
)
}
//endregion
//region isEmpty
@Test fun isEmpty_empty_passes() {
assertThat(emptyMap<Any?, Any?>()).isEmpty()
}
@Test fun isEmpty_non_empty_fails() {
val error = assertFails {
assertThat(mapOf<Any?, Any?>(null to null)).isEmpty()
}
assertEquals("expected to be empty but was:<{null=null}>", error.message)
}
//endregion
//region isNotEmpty
@Test fun isNotEmpty_non_empty_passes() {
assertThat(mapOf<Any?, Any?>(null to null)).isNotEmpty()
}
@Test fun isNotEmpty_empty_fails() {
val error = assertFails {
assertThat(mapOf<Any?, Any?>()).isNotEmpty()
}
assertEquals("expected to not be empty", error.message)
}
//endregion
//region isNullOrEmpty
@Test fun isNullOrEmpty_null_passes() {
assertThat(null as Map<Any?, Any?>?).isNullOrEmpty()
}
@Test fun isNullOrEmpty_empty_passes() {
assertThat(emptyMap<Any?, Any?>()).isNullOrEmpty()
}
@Test fun isNullOrEmpty_non_empty_fails() {
val error = assertFails {
assertThat(mapOf<Any?, Any?>(null to null)).isNullOrEmpty()
}
assertEquals("expected to be null or empty but was:<{null=null}>", error.message)
}
//endregion
//region hasSize
@Test fun hasSize_correct_size_passes() {
assertThat(emptyMap<String, Int>()).hasSize(0)
}
@Test fun hasSize_wrong_size_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int>()).hasSize(1)
}
assertEquals("expected [size]:<[1]> but was:<[0]> ({})", error.message)
}
//endregion
//region hasSameSizeAs
@Test fun hasSameSizeAs_equal_sizes_passes() {
assertThat(emptyMap<String, Int>()).hasSameSizeAs(emptyMap<String, Int>())
}
@Test fun hasSameSizeAs_non_equal_sizes_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int>()).hasSameSizeAs(mapOf("one" to 1))
}
assertEquals("expected to have same size as:<{\"one\"=1}> (1) but was size:(0)", error.message)
}
//endregion
//region key
@Test fun index_successful_assertion_passes() {
assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("one").isEqualTo(1)
}
@Test fun index_unsuccessful_assertion_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("one").isEqualTo(2)
}
assertEquals("expected [subject[\"one\"]]:<[2]> but was:<[1]> ({\"one\"=1, \"two\"=2})", error.message)
}
@Test fun index_missing_key_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("wrong").isEqualTo(1)
}
assertEquals("expected [subject] to have key:<\"wrong\">", error.message)
}
//endregion
}
| mit | 238aac7563b9417f7e567504e005dad5 | 32.79918 | 111 | 0.56566 | 4.127628 | false | true | false | false |
cketti/k-9 | app/storage/src/main/java/com/fsck/k9/storage/messages/RetrieveFolderOperations.kt | 1 | 7702 | package com.fsck.k9.storage.messages
import android.database.Cursor
import androidx.core.database.getLongOrNull
import com.fsck.k9.Account.FolderMode
import com.fsck.k9.helper.map
import com.fsck.k9.mail.FolderClass
import com.fsck.k9.mail.FolderType
import com.fsck.k9.mailstore.FolderDetailsAccessor
import com.fsck.k9.mailstore.FolderMapper
import com.fsck.k9.mailstore.FolderNotFoundException
import com.fsck.k9.mailstore.LockableDatabase
import com.fsck.k9.mailstore.MoreMessages
import com.fsck.k9.mailstore.toFolderType
internal class RetrieveFolderOperations(private val lockableDatabase: LockableDatabase) {
fun <T> getFolder(folderId: Long, mapper: FolderMapper<T>): T? {
return getFolder(
selection = "id = ?",
selectionArguments = arrayOf(folderId.toString()),
mapper = mapper
)
}
fun <T> getFolder(folderServerId: String, mapper: FolderMapper<T>): T? {
return getFolder(
selection = "server_id = ?",
selectionArguments = arrayOf(folderServerId),
mapper = mapper
)
}
private fun <T> getFolder(selection: String, selectionArguments: Array<String>, mapper: FolderMapper<T>): T? {
return lockableDatabase.execute(false) { db ->
db.query(
"folders",
FOLDER_COLUMNS,
selection,
selectionArguments,
null,
null,
null
).use { cursor ->
if (cursor.moveToFirst()) {
val cursorFolderAccessor = CursorFolderAccessor(cursor)
mapper.map(cursorFolderAccessor)
} else {
null
}
}
}
}
fun <T> getFolders(excludeLocalOnly: Boolean = false, mapper: FolderMapper<T>): List<T> {
val selection = if (excludeLocalOnly) "local_only = 0" else null
return lockableDatabase.execute(false) { db ->
db.query("folders", FOLDER_COLUMNS, selection, null, null, null, "id").use { cursor ->
val cursorFolderAccessor = CursorFolderAccessor(cursor)
cursor.map {
mapper.map(cursorFolderAccessor)
}
}
}
}
fun <T> getDisplayFolders(displayMode: FolderMode, outboxFolderId: Long?, mapper: FolderMapper<T>): List<T> {
return lockableDatabase.execute(false) { db ->
val displayModeSelection = getDisplayModeSelection(displayMode)
val outboxFolderIdOrZero = outboxFolderId ?: 0
val query =
"""
SELECT ${FOLDER_COLUMNS.joinToString()}, (
SELECT COUNT(messages.id)
FROM messages
WHERE messages.folder_id = folders.id
AND messages.empty = 0 AND messages.deleted = 0
AND (messages.read = 0 OR folders.id = ?)
), (
SELECT COUNT(messages.id)
FROM messages
WHERE messages.folder_id = folders.id
AND messages.empty = 0 AND messages.deleted = 0
AND messages.flagged = 1
)
FROM folders
$displayModeSelection
"""
db.rawQuery(query, arrayOf(outboxFolderIdOrZero.toString())).use { cursor ->
val cursorFolderAccessor = CursorFolderAccessor(cursor)
cursor.map {
mapper.map(cursorFolderAccessor)
}
}
}
}
private fun getDisplayModeSelection(displayMode: FolderMode): String {
return when (displayMode) {
FolderMode.ALL -> {
""
}
FolderMode.FIRST_CLASS -> {
"WHERE display_class = '${FolderClass.FIRST_CLASS.name}'"
}
FolderMode.FIRST_AND_SECOND_CLASS -> {
"WHERE display_class IN ('${FolderClass.FIRST_CLASS.name}', '${FolderClass.SECOND_CLASS.name}')"
}
FolderMode.NOT_SECOND_CLASS -> {
"WHERE display_class != '${FolderClass.SECOND_CLASS.name}'"
}
FolderMode.NONE -> {
throw AssertionError("Invalid folder display mode: $displayMode")
}
}
}
fun getFolderId(folderServerId: String): Long? {
return lockableDatabase.execute(false) { db ->
db.query(
"folders",
arrayOf("id"),
"server_id = ?",
arrayOf(folderServerId),
null,
null,
null
).use { cursor ->
if (cursor.moveToFirst()) cursor.getLong(0) else null
}
}
}
fun getFolderServerId(folderId: Long): String? {
return lockableDatabase.execute(false) { db ->
db.query(
"folders",
arrayOf("server_id"),
"id = ?",
arrayOf(folderId.toString()),
null,
null,
null
).use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0) else null
}
}
}
fun getMessageCount(folderId: Long): Int {
return lockableDatabase.execute(false) { db ->
db.rawQuery(
"SELECT COUNT(id) FROM messages WHERE empty = 0 AND deleted = 0 AND folder_id = ?",
arrayOf(folderId.toString())
).use { cursor ->
if (cursor.moveToFirst()) cursor.getInt(0) else 0
}
}
}
fun hasMoreMessages(folderId: Long): MoreMessages {
return getFolder(folderId) { it.moreMessages } ?: throw FolderNotFoundException(folderId)
}
}
private class CursorFolderAccessor(val cursor: Cursor) : FolderDetailsAccessor {
override val id: Long
get() = cursor.getLong(0)
override val name: String
get() = cursor.getString(1)
override val type: FolderType
get() = cursor.getString(2).toFolderType()
override val serverId: String?
get() = cursor.getString(3)
override val isLocalOnly: Boolean
get() = cursor.getInt(4) == 1
override val isInTopGroup: Boolean
get() = cursor.getInt(5) == 1
override val isIntegrate: Boolean
get() = cursor.getInt(6) == 1
override val syncClass: FolderClass
get() = cursor.getString(7).toFolderClass(FolderClass.INHERITED)
override val displayClass: FolderClass
get() = cursor.getString(8).toFolderClass(FolderClass.NO_CLASS)
override val notifyClass: FolderClass
get() = cursor.getString(9).toFolderClass(FolderClass.INHERITED)
override val pushClass: FolderClass
get() = cursor.getString(10).toFolderClass(FolderClass.SECOND_CLASS)
override val visibleLimit: Int
get() = cursor.getInt(11)
override val moreMessages: MoreMessages
get() = MoreMessages.fromDatabaseName(cursor.getString(12))
override val lastChecked: Long?
get() = cursor.getLongOrNull(13)
override val unreadMessageCount: Int
get() = cursor.getInt(14)
override val starredMessageCount: Int
get() = cursor.getInt(15)
override fun serverIdOrThrow(): String {
return serverId ?: error("No server ID found for folder '$name' ($id)")
}
}
private fun String?.toFolderClass(defaultValue: FolderClass): FolderClass {
return if (this == null) defaultValue else FolderClass.valueOf(this)
}
private val FOLDER_COLUMNS = arrayOf(
"id",
"name",
"type",
"server_id",
"local_only",
"top_group",
"integrate",
"poll_class",
"display_class",
"notify_class",
"push_class",
"visible_limit",
"more_messages",
"last_updated"
)
| apache-2.0 | 8e5c09a2f2e22358a2e8571792545009 | 31.091667 | 114 | 0.583615 | 4.702076 | false | false | false | false |
Naliwe/IntelliJ_WowAddOnSupport | src/org/squarecell/wow/addon_support/builders/AddOnModuleBuilder.kt | 1 | 3241 | package org.squarecell.wow.addon_support.builders
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.ide.util.projectWizard.ModuleBuilder
import com.intellij.ide.util.projectWizard.ModuleBuilderListener
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFileManager
import org.squarecell.wow.addon_support.config.MainFile
import org.squarecell.wow.addon_support.config.ProjectSettingsKeys
import org.squarecell.wow.addon_support.modules.AddOnModuleType
import org.squarecell.wow.addon_support.wizard_steps.AddOnWizardStep
import java.io.File
class AddOnModuleBuilder : ModuleBuilder(), ModuleBuilderListener {
init {
addListener(this)
}
override fun moduleCreated(module: Module) {
val tocFilePath = contentEntryPath + File.separator + module.name + ".toc"
var mainFilePath = contentEntryPath + File.separator + PropertiesComponent
.getInstance().getValue(ProjectSettingsKeys.AddOnMainFileName)
if (!mainFilePath.endsWith(".lua"))
mainFilePath += ".lua"
File(tocFilePath).writeText(PropertiesComponent.getInstance().getValue("tocFile")!!)
val file = File(mainFilePath)
file.createNewFile()
file.appendText(MainFile.initAce3AddOn)
file.appendText(MainFile.defaultInitFunc)
file.appendText(MainFile.defaultLoadFunc)
file.appendText(MainFile.defaultUnloadFunc)
}
override fun setupRootModel(modifiableRootModel: ModifiableRootModel) {
val path = contentEntryPath + File.separator + "Libs"
File(path).mkdirs()
val sourceRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(path)!!
val jarUtil = JarFileSystem.getInstance()
val desc = PluginManager.getPlugin(PluginId.getId("org.squarecell.wow.addon_support"))!!
val pluginPath = desc.path.absolutePath
val realPath = VfsUtil.pathToUrl(pluginPath)
val pluginVD = VirtualFileManager.getInstance().findFileByUrl(realPath)!!
val file = jarUtil.refreshAndFindFileByPath(pluginVD.path + "!/Wow_sdk")!!
// val classesDir = pluginVD.findChild("classes")?: pluginVD
// val deps = classesDir.findChild("Wow_sdk")!!
file.children.forEach {
VfsUtil.copy(this, it, sourceRoot)
}
super.doAddContentEntry(modifiableRootModel)?.addSourceFolder(sourceRoot, false)
}
override fun getModuleType(): ModuleType<*> {
return AddOnModuleType.instance
}
override fun getCustomOptionsStep(context: WizardContext,
parentDisposable: Disposable?): ModuleWizardStep? {
return AddOnWizardStep()
}
}
| mit | ed67ccabfcb285c00c2dd178fc383999 | 40.025316 | 96 | 0.740512 | 4.794379 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/ui/money/SettlementTypeActivity.kt | 1 | 9245 | package com.fuyoul.sanwenseller.ui.money
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.csl.refresh.SmartRefreshLayout
import com.csl.refresh.api.RefreshLayout
import com.csl.refresh.listener.OnRefreshLoadmoreListener
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseActivity
import com.fuyoul.sanwenseller.base.BaseAdapter
import com.fuyoul.sanwenseller.base.BaseViewHolder
import com.fuyoul.sanwenseller.bean.AdapterMultiItem
import com.fuyoul.sanwenseller.bean.MultBaseBean
import com.fuyoul.sanwenseller.bean.reqhttp.ReqInCome
import com.fuyoul.sanwenseller.bean.reshttp.ResMoneyItem
import com.fuyoul.sanwenseller.configs.Code
import com.fuyoul.sanwenseller.configs.Data
import com.fuyoul.sanwenseller.configs.TopBarOption
import com.fuyoul.sanwenseller.listener.AppBarStateChangeListener
import com.fuyoul.sanwenseller.structure.model.MoneyInComeM
import com.fuyoul.sanwenseller.structure.presenter.MoneyInComeP
import com.fuyoul.sanwenseller.structure.view.MoneyInComeV
import com.fuyoul.sanwenseller.utils.GlideUtils
import com.fuyoul.sanwenseller.utils.TimeDateUtils
import com.netease.nim.uikit.NimUIKit
import com.netease.nim.uikit.StatusBarUtils
import kotlinx.android.synthetic.main.moneyinfolayout.*
import kotlinx.android.synthetic.main.waitforsettlementlayout.*
import java.util.*
/**
* @author: chen
* @CreatDate: 2017\10\31 0031
* @Desc:待结算
*/
class SettlementTypeActivity : BaseActivity<MoneyInComeM, MoneyInComeV, MoneyInComeP>() {
companion object {
fun start(context: Context, isHistoryType: Boolean, year: String?, month: String?) {
val intent = Intent(context, SettlementTypeActivity::class.java)
intent.putExtra("isHistoryType", isHistoryType)
if (isHistoryType) {
intent.putExtra("year", year)
intent.putExtra("month", month)
}
context.startActivity(intent)
}
}
private val req = ReqInCome()
private var index = 0
private var defaultState = AppBarStateChangeListener.State.EXPANDED//默认是展开状态
private var adapter: ThisAdapter? = null
override fun setLayoutRes(): Int = R.layout.waitforsettlementlayout
override fun initData(savedInstanceState: Bundle?) {
StatusBarUtils.setTranslucentForCoordinatorLayout(this, 30)
setSupportActionBar(toolbar)
//如果是结算历史
if (intent.getBooleanExtra("isHistoryType", false)) {
req.ordersDate = "${intent.getStringExtra("year")}${intent.getStringExtra("month")}"
}
getPresenter().viewImpl?.initAdapter(this)
getPresenter().getData(this, req, true)
}
override fun setListener() {
waitForSettlementRefreshLayout.setOnRefreshLoadmoreListener(object : OnRefreshLoadmoreListener {
override fun onRefresh(refreshlayout: RefreshLayout?) {
index = 0
req.index = "$index"
getPresenter().getData(this@SettlementTypeActivity, req, true)
}
override fun onLoadmore(refreshlayout: RefreshLayout?) {
index++
req.index = "$index"
getPresenter().getData(this@SettlementTypeActivity, req, false)
}
})
appBarLayoutOfWaitSettlement.addOnOffsetChangedListener(listener)
toolbar.setNavigationOnClickListener {
finish()
}
}
override fun onResume() {
super.onResume()
appBarLayoutOfWaitSettlement.removeOnOffsetChangedListener(listener)
}
override fun onPause() {
super.onPause()
appBarLayoutOfWaitSettlement.removeOnOffsetChangedListener(listener)
}
override fun getPresenter(): MoneyInComeP = MoneyInComeP(initViewImpl())
override fun initViewImpl(): MoneyInComeV = object : MoneyInComeV() {
override fun getAdapter(): BaseAdapter {
if (adapter == null) {
adapter = ThisAdapter()
}
return adapter!!
}
override fun initAdapter(context: Context) {
val manager = LinearLayoutManager(this@SettlementTypeActivity)
manager.orientation = LinearLayoutManager.VERTICAL
waitForSettlementDataList.layoutManager = manager
waitForSettlementDataList.adapter = getAdapter()
}
override fun setViewInfo(data: ResMoneyItem) {
priceCount.text = "${data.countPrice}"
orderCount.text = "${data.countOrders}"
}
}
override fun initTopBar(): TopBarOption = TopBarOption()
inner class ThisAdapter : BaseAdapter(this) {
override fun convert(holder: BaseViewHolder, position: Int, datas: List<MultBaseBean>) {
val item = datas[position] as ResMoneyItem.IncomeListBean
GlideUtils.loadNormalImg(this@SettlementTypeActivity, JSON.parseArray(item.imgs).getJSONObject(0).getString("url"), holder.itemView.findViewById(R.id.orderItemIcon))
GlideUtils.loadNormalImg(this@SettlementTypeActivity, item.avatar, holder.itemView.findViewById(R.id.orderItemHead))
holder.itemView.findViewById<TextView>(R.id.orderItemPrice).text = "¥${item.totalPrice}"
holder.itemView.findViewById<TextView>(R.id.orderItemTitle).text = "${item.name}"
holder.itemView.findViewById<TextView>(R.id.orderItemDes).text = "${item.introduce}"
holder.itemView.findViewById<TextView>(R.id.orderItemTime).text = "${TimeDateUtils.stampToDate(item.ordersDate)}"
holder.itemView.findViewById<TextView>(R.id.orderItemNick).text = "${item.nickname}"
var typeIcon: Drawable? = null
if (item.type == Data.QUICKTESTBABY) {
typeIcon = resources.getDrawable(R.mipmap.icon_quicktesttype)
typeIcon.setBounds(0, 0, typeIcon.minimumWidth, typeIcon.minimumHeight)
}
holder.itemView.findViewById<TextView>(R.id.orderItemTitle).setCompoundDrawables(null, null, typeIcon, null)
val orderItemState = holder.itemView.findViewById<TextView>(R.id.orderItemState)
orderItemState.text = "交易完成"
val orderItemFuncLayout = holder.itemView.findViewById<LinearLayout>(R.id.orderItemFuncLayout)
orderItemFuncLayout.visibility = View.VISIBLE
val orderItemReleaseTime = holder.itemView.findViewById<LinearLayout>(R.id.orderItemReleaseTime)
orderItemReleaseTime.visibility = View.GONE
val orderItemFuncRight = holder.itemView.findViewById<TextView>(R.id.orderItem_Func_Right)
orderItemFuncRight.text = "联系买家"
orderItemFuncRight.setOnClickListener {
NimUIKit.startP2PSession(this@SettlementTypeActivity, "user_${item.user_info_id}")
}
}
override fun addMultiType(multiItems: ArrayList<AdapterMultiItem>) {
multiItems.add(AdapterMultiItem(Code.VIEWTYPE_MONEY, R.layout.orderitem))
}
override fun onItemClicked(view: View, position: Int) {
}
override fun onEmpryLayou(view: View, layoutResId: Int) {
}
override fun getSmartRefreshLayout(): SmartRefreshLayout = waitForSettlementRefreshLayout
override fun getRecyclerView(): RecyclerView = waitForSettlementDataList
}
private val listener = object : AppBarStateChangeListener() {
override fun onStateChanged(appBarLayout: AppBarLayout?, state: State) {
when (state) {
State.EXPANDED -> {
//展开状态
StatusBarUtils.StatusBarDarkMode(this@SettlementTypeActivity)
StatusBarUtils.setTranslucentForCoordinatorLayout(this@SettlementTypeActivity, 30)
toolbar.setBackgroundColor(resources.getColor(R.color.transparent))
}
State.COLLAPSED -> {
//折叠状态
toolbarOfMoneyInfo.setNavigationIcon(R.mipmap.ic_yb_top_back)
StatusBarUtils.StatusBarLightMode(this@SettlementTypeActivity, R.color.color_white)
toolbar.setBackgroundResource(R.drawable.back_titlebar)
}
else -> {
//中间状态
//如果之前是折叠状态,则表示在向下滑动
if (defaultState == State.COLLAPSED) {
StatusBarUtils.StatusBarDarkMode(this@SettlementTypeActivity)
StatusBarUtils.setTranslucentForCoordinatorLayout(this@SettlementTypeActivity, 30)
toolbar.setBackgroundColor(resources.getColor(R.color.transparent))
}
}
}
defaultState = state
}
}
} | apache-2.0 | 67aad4b9b3464eee0113aff45dec2b67 | 36.138211 | 177 | 0.678818 | 4.932505 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/actions/PageEditInterface.kt | 5 | 3876 | package fr.free.nrw.commons.actions
import io.reactivex.Observable
import io.reactivex.Single
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.mwapi.MwQueryResponse
import org.wikipedia.edit.Edit
import org.wikipedia.wikidata.Entities
import retrofit2.http.*
/**
* This interface facilitates wiki commons page editing services to the Networking module
* which provides all network related services used by the app.
*
* This interface posts a form encoded request to the wikimedia API
* with editing action as argument to edit a particular page
*/
interface PageEditInterface {
/**
* This method posts such that the Content which the page
* has will be completely replaced by the value being passed to the
* "text" field of the encoded form data
* @param title Title of the page to edit. Cannot be used together with pageid.
* @param summary Edit summary. Also section title when section=new and sectiontitle is not set
* @param text Holds the page content
* @param token A "csrf" token
*/
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=edit")
fun postEdit(
@Field("title") title: String,
@Field("summary") summary: String,
@Field("text") text: String,
// NOTE: This csrf shold always be sent as the last field of form data
@Field("token") token: String
): Observable<Edit>
/**
* This method posts such that the Content which the page
* has will be appended with the value being passed to the
* "appendText" field of the encoded form data
* @param title Title of the page to edit. Cannot be used together with pageid.
* @param summary Edit summary. Also section title when section=new and sectiontitle is not set
* @param appendText Text to add to the end of the page
* @param token A "csrf" token
*/
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=edit")
fun postAppendEdit(
@Field("title") title: String,
@Field("summary") summary: String,
@Field("appendtext") appendText: String,
@Field("token") token: String
): Observable<Edit>
/**
* This method posts such that the Content which the page
* has will be prepended with the value being passed to the
* "prependText" field of the encoded form data
* @param title Title of the page to edit. Cannot be used together with pageid.
* @param summary Edit summary. Also section title when section=new and sectiontitle is not set
* @param prependText Text to add to the beginning of the page
* @param token A "csrf" token
*/
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=edit")
fun postPrependEdit(
@Field("title") title: String,
@Field("summary") summary: String,
@Field("prependtext") prependText: String,
@Field("token") token: String
): Observable<Edit>
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=wbsetlabel&format=json&site=commonswiki&formatversion=2")
fun postCaptions(
@Field("summary") summary: String,
@Field("title") title: String,
@Field("language") language: String,
@Field("value") value: String,
@Field("token") token: String
): Observable<Entities>
/**
* Get wiki text for provided file names
* @param titles : Name of the file
* @return Single<MwQueryResult>
*/
@GET(
Service.MW_API_PREFIX +
"action=query&prop=revisions&rvprop=content|timestamp&rvlimit=1&converttitles="
)
fun getWikiText(
@Query("titles") title: String
): Single<MwQueryResponse?>
} | apache-2.0 | 2dad9b77f9fa30fc35f6e13ccf9b55ef | 37.386139 | 100 | 0.668215 | 4.176724 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-support-v4/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v4/widget/SwipeRefreshLayoutProperty.kt | 1 | 959 | package com.github.kittinunf.reactiveandroid.support.v4.widget
import android.support.v4.widget.SwipeRefreshLayout
import com.github.kittinunf.reactiveandroid.MutableProperty
import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty
//================================================================================
// Property
//================================================================================
val SwipeRefreshLayout.rx_refreshing: MutableProperty<Boolean>
get() {
val getter = { isRefreshing }
val setter: (Boolean) -> Unit = { isRefreshing = it }
return createMainThreadMutableProperty(getter, setter)
}
val SwipeRefreshLayout.rx_nestedScrollingEnabled: MutableProperty<Boolean>
get() {
val getter = { isNestedScrollingEnabled }
val setter: (Boolean) -> Unit = { isNestedScrollingEnabled = it }
return createMainThreadMutableProperty(getter, setter)
}
| mit | 9ca709be2942535aef9b98cbf19c1d92 | 37.36 | 82 | 0.618352 | 6.031447 | false | false | false | false |
JayNewstrom/Concrete | concrete/src/main/java/com/jaynewstrom/concrete/ConcreteWallContext.kt | 1 | 732 | package com.jaynewstrom.concrete
import android.content.Context
import android.content.ContextWrapper
import android.view.LayoutInflater
internal class ConcreteWallContext<C>(
baseContext: Context,
private val wall: ConcreteWall<C>
) : ContextWrapper(baseContext) {
private var inflater: LayoutInflater? = null
override fun getSystemService(name: String): Any? {
if (Concrete.isService(name)) {
return wall
}
if (Context.LAYOUT_INFLATER_SERVICE == name) {
if (inflater == null) {
inflater = LayoutInflater.from(baseContext).cloneInContext(this)
}
return inflater
}
return super.getSystemService(name)
}
}
| apache-2.0 | 91fa178009178e8b5c03d9f05df34541 | 28.28 | 80 | 0.657104 | 4.815789 | false | false | false | false |
NuclearCoder/nuclear-bot | src/nuclearbot/gui/components/chat/LimitedStringList.kt | 1 | 2690 | package nuclearbot.gui.components.chat
import java.util.*
import javax.swing.AbstractListModel
import javax.swing.JList
/*
* Copyright (C) 2017 NuclearCoder
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Custom JList that uses a custom model which only keeps the last lines.<br></br>
* <br></br>
* NuclearBot (https://github.com/NuclearCoder/nuclear-bot/)<br></br>
* @author NuclearCoder (contact on the GitHub repo)
*/
class LimitedStringList(capacity: Int = 50) : JList<String>() {
private val listModel = LimitedStringList.Model(capacity).also { model = it }
/**
* Adds an element to the model. If the size of the list
* will exceed the maximum capacity, the first element
* is removed before adding the new element to the end
* of the list.
*
* @param text the line to add to the list
*/
fun add(text: String) {
listModel.add(text)
}
/**
* The ListModel used by the LimitedStringList class
*/
class Model(private val capacity: Int) : AbstractListModel<String>() {
private val arrayList = ArrayList<String>(capacity)
/**
* Adds an element to the model. If the size of the list
* will exceed the maximum capacity, the first element
* is removed before adding the new element to the end
* of the list.
*
* @param text the line to add to the list
*/
fun add(text: String) {
val index0: Int
val index1: Int
if (arrayList.size == capacity) {
index0 = 0
index1 = capacity - 1
arrayList.removeAt(0)
} else {
index1 = arrayList.size
index0 = index1
}
arrayList.add(text)
fireContentsChanged(this, index0, index1)
}
override fun getSize(): Int {
return arrayList.size
}
override fun getElementAt(index: Int): String {
return arrayList[index]
}
}
}
| agpl-3.0 | f9ba378006bf76466fafc9152088c819 | 29.91954 | 82 | 0.624535 | 4.373984 | false | false | false | false |
lanhuaguizha/Christian | app/src/main/java/com/christian/nav/me/HidingGospelFragment.kt | 1 | 7641 | package com.christian.nav.me
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.christian.R
import com.christian.common.GOSPEL_EN
import com.christian.common.GOSPEL_ZH
import com.christian.common.auth
import com.christian.common.data.Gospel
import com.christian.common.firestore
import com.christian.databinding.ItemChatBinding
import com.christian.databinding.ItemGospelBinding
import com.christian.nav.disciple.ChatItemView
import com.christian.nav.gospel.GospelItemView
import com.christian.nav.gospel.HidingGospelItemView
import com.christian.nav.home.VIEW_TYPE_CHAT
import com.christian.nav.home.VIEW_TYPE_GOSPEL
import com.christian.swipe.SwipeBackActivity
import com.christian.util.ChristianUtil
import com.christian.view.ItemDecoration
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.Query
import kotlinx.android.synthetic.main.fragment_detail_me.view.*
import kotlinx.android.synthetic.main.fragment_nav_rv.view.*
import kotlinx.android.synthetic.main.activity_tb_immersive.*
class HidingGospelFragment: Fragment() {
var meDetailTabId: Int = -1
private lateinit var v: View
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
v = inflater.inflate(R.layout.fragment_detail_me, container, false)
initView()
return v
}
private lateinit var gospelAdapter: FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder>
private lateinit var query: Query
var mPosition = -1
private fun initView() {
initRv()
v.me_detail_pb.isIndeterminate = true
v.fragment_nav_rv.setProgressBar(v.me_detail_pb)
}
private fun initRv() {
v.fragment_nav_rv.addItemDecoration(ItemDecoration(top = ChristianUtil.dpToPx(64)))
getMeFromSettingId()
if (::gospelAdapter.isInitialized) {gospelAdapter.startListening()
v.fragment_nav_rv.adapter = gospelAdapter} // 我的-门徒-喜欢 崩溃处理
}
override fun onDestroy() {
super.onDestroy()
if (::gospelAdapter.isInitialized) gospelAdapter.stopListening() // 我的-门徒-喜欢 崩溃处理
}
/**
* tabId = 0, settingId = 0, history gospels
* tabId = 0, settingId = 1, favorite gospels
* tabId = 0, settingId = 2, published gospels
*
*
* tabId = 1, settingId = 0, history disciples
* tabId = 1, settingId = 1, following disciples
* tabId = 1, settingId = 2, followed disciples
*/
private fun getMeFromSettingId() {
(requireActivity() as HidingGospelActivity).tb_immersive_toolbar.title =
getString(R.string.hidden_gospel)
query = if (meDetailTabId == 0) {
firestore.collection(GOSPEL_EN).orderBy("createTime", Query.Direction.DESCENDING)
.whereEqualTo("show", 0)
} else {
firestore.collection(GOSPEL_ZH).orderBy("createTime", Query.Direction.DESCENDING)
.whereEqualTo("show", 0)
}
val options = FirestoreRecyclerOptions.Builder<Gospel>()
// .setLifecycleOwner(this@NavFragment)
.setQuery(query, Gospel::class.java)
.build()
gospelAdapter = object : FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder>(options) {
override fun getItemViewType(position: Int): Int {
return when {
getItem(position).title.isEmpty() -> {
VIEW_TYPE_CHAT
}
else -> {
VIEW_TYPE_GOSPEL
}
}
}
@NonNull
override fun onCreateViewHolder(@NonNull parent: ViewGroup,
viewType: Int): RecyclerView.ViewHolder {
when(viewType) {
0 -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_gospel, parent, false)
val binding = ItemGospelBinding.bind(view)
return HidingGospelItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId)
}
1 -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_chat, parent, false)
val binding = ItemChatBinding.bind(view)
return ChatItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId)
}
else -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_gospel, parent, false)
val binding = ItemGospelBinding.bind(view)
return HidingGospelItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId)
}
}
}
override fun onBindViewHolder(@NonNull holder: RecyclerView.ViewHolder,
position: Int,
@NonNull model: Gospel
) {
when {
model.title.isEmpty() -> {
applyViewHolderAnimation(holder as ChatItemView)
holder.bind(meDetailTabId, model)
}
else -> {
applyViewHolderAnimation(holder as HidingGospelItemView)
holder.bind(meDetailTabId, model)
}
}
}
override fun onDataChanged() {
super.onDataChanged()
v.me_detail_pb.visibility = View.GONE
v.me_detail_pb.isIndeterminate = false
if (itemCount == 0) {
} else {
v.fragment_nav_rv.scheduleLayoutAnimation()
}
}
override fun onError(e: FirebaseFirestoreException) {
super.onError(e)
Log.d("MeDetailFragment", e.toString())
}
}
v.fragment_nav_rv.adapter = gospelAdapter
}
fun applyViewHolderAnimation(holder: HidingGospelItemView) {
if (holder.adapterPosition > mPosition) {
holder.animateItemView(holder.itemView)
mPosition = holder.adapterPosition
}
}
fun applyViewHolderAnimation(holder: GospelItemView) {
if (holder.adapterPosition > mPosition) {
holder.animateItemView(holder.itemView)
mPosition = holder.adapterPosition
}
}
fun applyViewHolderAnimation(holder: ChatItemView) {
if (holder.adapterPosition > mPosition) {
holder.animateItemView(holder.itemView)
mPosition = holder.adapterPosition
}
}
} | gpl-3.0 | c7a9636999f4701376e2115199f79a27 | 37.01 | 119 | 0.576503 | 5.177793 | false | false | false | false |
AlmasB/FXGLGames | OutRun/src/main/kotlin/com/almasb/fxglgames/outrun/PlayerComponent.kt | 1 | 2726 | /*
* The MIT License (MIT)
*
* FXGL - JavaFX Game Library
*
* Copyright (c) 2015-2016 AlmasB (almaslvl@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.almasb.fxglgames.outrun
import com.almasb.fxgl.entity.component.Component
import javafx.beans.property.SimpleDoubleProperty
import java.lang.Math.min
/**
*
*
* @author Almas Baimagambetov (almaslvl@gmail.com)
*/
class PlayerComponent : Component() {
private var speed = 0.0
private var dy = 0.0
val boost = SimpleDoubleProperty(100.0)
override fun onUpdate(tpf: Double) {
speed = tpf * 200
dy += tpf / 4;
if (entity.x < 80 || entity.rightX > 600 - 80) {
if (dy > 0.017) {
dy -= tpf
}
}
entity.y -= dy
boost.set(min(boost.get() + tpf * 5, 100.0))
}
fun getSpeed() = dy
fun up() {
entity.translateY(-speed)
}
fun down() {
entity.translateY(speed)
}
fun left() {
if (entity.x >= speed)
entity.translateX(-speed)
}
fun right() {
if (entity.rightX + speed <= 600)
entity.translateX(speed)
}
fun boost() {
if (boost.get() <= speed * 2)
return
boost.set(Math.max(boost.get() - speed / 2, 0.0))
entity.y -= speed
}
fun applyExtraBoost() {
dy += 10
}
fun removeExtraBoost() {
dy = Math.max(0.0, dy - 10)
}
fun reset() {
dy = 0.0
// val anim = fadeOutIn(entity.view, Duration.seconds(1.5))
// anim.animatedValue.interpolator = Interpolators.BOUNCE.EASE_IN()
// anim.startInPlayState()
}
} | mit | a0d1242ecc3216f1bc4e31b99552d765 | 25.221154 | 80 | 0.629127 | 3.967977 | false | false | false | false |
brunordg/ctanywhere | app/src/main/java/br/com/codeteam/ctanywhere/ext/ContextExt.kt | 1 | 991 | package br.com.codeteam.ctanywhere.ext
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
/**
* Created by Bruno Rodrigues e Rodrigues on 21/05/2018.
*/
fun Context.hasPermissions(vararg permissions: String): Boolean {
for (permission in permissions) {
if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) {
return false
}
}
return true
}
@Suppress("unused")
fun Context.checkSelfPermissions(permission: String) = ContextCompat.checkSelfPermission(this, permission)
fun Context.getColorCompat(@ColorRes res: Int): Int = ContextCompat.getColor(this, res)
@Suppress("unused")
fun Context.getDrawableCompat(@DrawableRes res: Int): Drawable = ContextCompat.getDrawable(this, res)!!
| mit | 335c185ec4e2caf1405a8cf6142528e1 | 29.030303 | 106 | 0.774975 | 4.463964 | false | false | false | false |
westoncb/HNDesktop | src/main/java/App.kt | 1 | 17053 | import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.google.gson.JsonPrimitive
import javafx.application.Platform
import javafx.embed.swing.JFXPanel
import javafx.scene.Scene
import javafx.scene.web.WebView
import javax.swing.*
import java.net.URL
import javax.net.ssl.HttpsURLConnection
import java.io.InputStreamReader
import javax.swing.UIManager
import java.awt.*
import javax.swing.event.ListSelectionEvent
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.JTree
import javax.swing.event.TreeModelEvent
import javax.swing.event.TreeModelListener
import javax.swing.plaf.metal.DefaultMetalTheme
import javax.swing.plaf.metal.MetalLookAndFeel
import javax.swing.tree.DefaultTreeCellRenderer
import javax.swing.tree.DefaultTreeModel
import kotlin.collections.ArrayList
import javax.swing.text.html.HTMLDocument
import javax.swing.text.html.HTMLEditorKit
/**
* Created by weston on 8/26/17.
*/
/**
* TODO:
* +Webview toggling
* User profiles
* (periodic?) Refresh
*/
class App : PubSub.Subscriber {
companion object {
init {
// MetalLookAndFeel.setCurrentTheme(DefaultMetalTheme())
// UIManager.setLookAndFeel(MetalLookAndFeel())
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel")
}
}
val progressBar = JProgressBar(0, 30)
var contentPane = JPanel()
var storyControlPanel = JPanel()
var storyPanel: JPanel = JPanel()
var mainRightPane = JPanel()
val listModel = DefaultListModel<Story>()
val storyList = JList(listModel)
val userLabel = JLabel()
val pointsLabel = JLabel()
val storyTimeLabel = JLabel()
val storyURLLabel = JLabel()
val commentCountLabel = JLabel()
val contentToggleButton = JButton("View Page")
var headlinePanel = JPanel()
var storyIconPanel = JLabel()
var commentTree = JTree()
var commentTreeRoot = DefaultMutableTreeNode()
var commentsProgressBar = JProgressBar()
var loadedCommentCount = 0
val jfxPanel = JFXPanel()
var activeStory: Story? = null
var viewingComments = true
init {
val frame = JFrame("Hacker News")
val screenSize = Toolkit.getDefaultToolkit().screenSize
val frameSize = Dimension((screenSize.width*0.90f).toInt(), (screenSize.height*0.85f).toInt())
frame.size = frameSize
frame.contentPane = contentPane
contentPane.preferredSize = frameSize
contentPane.layout = GridBagLayout()
val c = GridBagConstraints()
c.anchor = GridBagConstraints.CENTER
progressBar.preferredSize = Dimension(400, 25)
progressBar.isStringPainted = true
//Just add so the display updates. Not sure why, but
//it delays showing the progress bar if we don't do this.
contentPane.add(JLabel(""), c)
c.gridy = 1
contentPane.add(progressBar, c)
progressBar.value = 0
frame.setLocation(screenSize.width / 2 - frame.size.width / 2, screenSize.height / 2 - frame.size.height / 2)
frame.pack()
frame.isVisible = true
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
val stories = getFrontPageStories()
contentPane = JPanel(BorderLayout())
frame.contentPane = contentPane
val mainPanel = getMainPanel(stories)
contentPane.add(mainPanel)
storyList.selectedIndex = 0
storyList.setCellRenderer(StoryCellRenderer())
contentToggleButton.addActionListener {
if (activeStory != null) {
if (viewingComments) {
showPage(activeStory)
} else {
showComments(activeStory)
}
}
}
frame.revalidate()
PubSub.subscribe(PubSub.STORY_ICON_LOADED, this)
styleComponents()
}
fun styleComponents() {
this.storyURLLabel.foreground = Color(100, 100, 100)
this.storyList.background = Color(242, 242, 242)
//Dimensions here are somewhat arbitrary, but if we want
//equal priority given to both splitpane panels, they each
//need minimum sizes
mainRightPane.minimumSize = Dimension(300, 200)
}
fun getMainPanel(storyNodes: ArrayList<JsonObject>) : JComponent {
val stories = storyNodes
.filter { it.get("type").asString.equals("story", true) }
.map { Story(it) }
val def = DefaultListCellRenderer()
val renderer = ListCellRenderer<Story> { list, value, index, isSelected, cellHasFocus ->
def.getListCellRendererComponent(list, value.title, index, isSelected, cellHasFocus)
}
storyList.cellRenderer = renderer
storyList.addListSelectionListener { e: ListSelectionEvent? ->
if (e != null) {
if (!e.valueIsAdjusting) {
changeActiveStory(stories[storyList.selectedIndex])
}
}
}
for (story in stories) {
listModel.addElement(story)
}
mainRightPane = buildMainRightPanel()
val storyScroller = JScrollPane(storyList)
storyScroller.minimumSize = Dimension(200, 200)
storyScroller.verticalScrollBar.unitIncrement = 16
val splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, storyScroller, mainRightPane)
splitPane.isOneTouchExpandable = true
return splitPane
}
fun changeActiveStory(story: Story) {
activeStory = story
userLabel.text = "Posted by: ${story.user}"
pointsLabel.text = "Points: ${story.points}"
storyTimeLabel.text = "Time: ${story.time}"
commentCountLabel.text = "Comments: ${story.totalComments}"
if (story.url != null) {
storyURLLabel.text = story.url
}
showComments(activeStory)
}
fun showComments(story: Story?) {
if (story != null) {
viewingComments = true
contentToggleButton.text = "View Page"
storyPanel.removeAll()
storyPanel.add(getCommentsPanel(story))
if (story.bigIcon != null) {
storyIconPanel.icon = ImageIcon(story.bigIcon)
} else {
storyIconPanel.icon = story.favicon
}
storyIconPanel.preferredSize = Dimension(storyIconPanel.icon.iconWidth+6, storyIconPanel.icon.iconHeight)
storyIconPanel.border = BorderFactory.createEmptyBorder(0, 3, 0, 3)
headlinePanel.preferredSize = Dimension(storyControlPanel.size.width, Math.max(32, storyIconPanel.icon.iconHeight))
loadComments(story)
}
}
fun showPage(story: Story?) {
if (story != null) {
viewingComments = false
contentToggleButton.text = "View Comments"
cancelCommentLoading()
storyPanel.removeAll()
storyPanel.add(jfxPanel)
Platform.runLater {
val webView = WebView()
jfxPanel.scene = Scene(webView)
webView!!.engine.load(story.url)
}
storyPanel.revalidate()
} else {
println("Tried showing page but story was null")
}
}
override fun messageArrived(eventName: String, data: Any?) {
if (eventName == PubSub.STORY_ICON_LOADED) {
storyList.repaint()
storyControlPanel.repaint()
}
}
fun loadComments(story: Story) {
if (story.totalComments == 0)
return
Thread(Runnable {
if (story.kids != null) {
var index = 0
val iter = story.kids.iterator()
while(iter.hasNext() && viewingComments) {
val commentId = iter.next().asInt
val address = "$index"
loadCommentAux(Comment(getItem(commentId), address), address)
index++
}
} }).start()
}
fun loadCommentAux(comment: Comment, treeAddress: String) {
commentArrived(comment, treeAddress)
if (comment.kids != null) {
var index = 0
val iter = comment.kids.iterator()
while(iter.hasNext() && viewingComments) {
val commentId = iter.next().asInt
val address = treeAddress+";$index"
loadCommentAux(Comment(getItem(commentId), address), address)
index++
}
}
}
fun commentArrived(comment: Comment, treeAddress: String) {
if (!viewingComments)
return
addNodeAtAddress(DefaultMutableTreeNode(comment), comment.treeAddress)
commentsProgressBar.value = ++loadedCommentCount
if (loadedCommentCount >= commentsProgressBar.maximum) {
val parent = commentsProgressBar.parent
if (parent != null) {
parent.remove(commentsProgressBar)
parent.revalidate()
}
}
}
fun cancelCommentLoading() {
loadedCommentCount = commentsProgressBar.maximum
}
fun addNodeAtAddress(node: DefaultMutableTreeNode, address: String) {
if (!viewingComments)
return
val addressArray = address.split(";")
var parentNode = commentTreeRoot
for ((index, addressComponent) in addressArray.withIndex()) {
// Don't use the last component in the addressArray since that's the index
// which the child should be added at
if (index < addressArray.size - 1) {
val childIndex = Integer.parseInt("$addressComponent")
if (childIndex < parentNode.childCount) {
parentNode = parentNode.getChildAt(childIndex) as DefaultMutableTreeNode
}
}
}
val childIndex = Integer.parseInt(addressArray[addressArray.size-1])
(commentTree.model as DefaultTreeModel).insertNodeInto(node, parentNode, childIndex)
}
fun getCommentsPanel(story: Story) : JPanel {
loadedCommentCount = 0
val panel = JPanel(BorderLayout())
commentTreeRoot = DefaultMutableTreeNode("Comments")
commentTree = JTree(commentTreeRoot)
commentTree.toggleClickCount = 1
commentTree.cellRenderer = CommentCellRenderer()
commentTree.model.addTreeModelListener(ExpandTreeListener(commentTree))
val treeScroller = JScrollPane(commentTree)
treeScroller.verticalScrollBar.unitIncrement = 16
treeScroller.horizontalScrollBar.unitIncrement = 16
if (!(UIManager.getLookAndFeel() is MetalLookAndFeel)) {
treeScroller.background = Color(242, 242, 242)
commentTree.background = Color(242, 242, 242)
}
panel.add(treeScroller, BorderLayout.CENTER)
var totalComments = 0
if (story.totalComments != null) {
totalComments = story.totalComments
}
commentsProgressBar = JProgressBar()
commentsProgressBar.minimum = 0
commentsProgressBar.maximum = totalComments
panel.add(commentsProgressBar, BorderLayout.NORTH)
return panel
}
fun buildMainRightPanel() : JPanel {
val root = JPanel()
root.layout = BorderLayout()
storyControlPanel = JPanel(GridLayout(1, 1))
storyPanel = JPanel(BorderLayout())
root.add(storyControlPanel, BorderLayout.NORTH)
headlinePanel = JPanel(BorderLayout())
headlinePanel.border = BorderFactory.createEmptyBorder(3, 3, 3, 3)
headlinePanel.add(storyIconPanel, BorderLayout.WEST)
headlinePanel.add(storyURLLabel, BorderLayout.CENTER)
headlinePanel.add(contentToggleButton, BorderLayout.EAST)
storyControlPanel.add(headlinePanel)
root.add(storyPanel, BorderLayout.CENTER)
return root
}
fun getFrontPageStories() : ArrayList<JsonObject> {
val storyIDs = treeFromURL("https://hacker-news.firebaseio.com/v0/topstories.json")
val iter = storyIDs.asJsonArray.iterator()
val stories = ArrayList<JsonObject>()
var count = 0
while (iter.hasNext()) {
val id = (iter.next() as JsonPrimitive).asInt
val story = getItem(id)
stories.add(story.asJsonObject)
count++
progressBar.value = count
if (count > 29)
break
}
return stories
}
fun getItem(id: Int) : JsonObject {
val item = treeFromURL("https://hacker-news.firebaseio.com/v0/item/$id.json")
return item.asJsonObject
}
fun treeFromURL(url: String) : JsonElement {
val url = URL(url)
val connection = (url.openConnection()) as HttpsURLConnection
val reader = InputStreamReader(connection?.inputStream)
val parser = JsonParser()
val element = parser.parse(reader)
reader.close()
return element
}
class StoryCellRenderer : DefaultListCellRenderer() {
override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) as JComponent
this.border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(3, 3, 3, 3))
if (!isSelected && !cellHasFocus) {
this.background = Color(242, 242, 242)
}
this.icon = (value as Story).favicon
this.text = "<html><span style=\"color: #333333; font-size: 10px\">${value.title}</span><br><span style=\"color: #777777; font-size:8px;\"> ${value.points} points by ${value.user} ${value.time} | ${value.totalComments} comments</span></html>"
return this
}
}
class CommentCellRenderer : DefaultTreeCellRenderer() {
override fun getTreeCellRendererComponent(tree: JTree?, value: Any?, sel: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component? {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus)
if ((value as DefaultMutableTreeNode).userObject !is Comment) {
return JLabel()
}
val comment = value.userObject as Comment
var originalCommentText = comment.text
if (originalCommentText == null)
originalCommentText = ""
val panel = JPanel()
panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS)
panel.background = Color(225, 225, 235)
val metaDataLabel = JLabel(comment.user + " " + comment.time)
metaDataLabel.foreground = Color(60, 60, 60)
metaDataLabel.font = Font("Arial", Font.PLAIN, 11)
metaDataLabel.border = BorderFactory.createEmptyBorder(3, 3, 3, 3)
panel.add(metaDataLabel)
//Insert linebreaks periodically since this seems to be the only way to limit
//the width of the html rendering JTextPane without also limiting the height
var text = ""
var index = 0
val words = originalCommentText.split(" ")
for (word in words) {
if (word.indexOf("<br>") != -1 || word.indexOf("</p>") != -1 || word.indexOf("</pre>") != -1) {
index = 0
} else if (index > 20) {
index = 0
text += "<br>"
}
text += " " + word
index++
}
val textPane = JTextPane()
textPane.contentType = "text/html"
textPane.isEditable = false
val doc = textPane.document as HTMLDocument
val editorKit = textPane.editorKit as HTMLEditorKit
editorKit.insertHTML(doc, doc.length, text, 0, 0, null)
textPane.background = Color(242, 242, 255)
textPane.border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5))
textPane.minimumSize = Dimension(textPane.size.width, textPane.size.height)
panel.add(textPane)
return panel
}
}
class ExpandTreeListener(theTree: JTree) : TreeModelListener {
val tree = theTree
override fun treeStructureChanged(e: TreeModelEvent?) {
}
override fun treeNodesChanged(e: TreeModelEvent?) {
}
override fun treeNodesRemoved(e: TreeModelEvent?) {
}
override fun treeNodesInserted(e: TreeModelEvent?) {
if (e != null) {
if (e.treePath.pathCount == 1) {
this.tree.expandPath(e.treePath)
}
}
}
}
}
fun main(args: Array<String>) {
App()
}
| mit | 1f900d1051def469acfb5e875158ffd4 | 32.177043 | 254 | 0.615552 | 4.905926 | false | false | false | false |
talhacohen/android | app/src/main/java/com/etesync/syncadapter/log/PlainTextFormatter.kt | 1 | 1903 | /*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.log
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import org.apache.commons.lang3.time.DateFormatUtils
import java.util.logging.Formatter
import java.util.logging.LogRecord
class PlainTextFormatter private constructor(private val logcat: Boolean) : Formatter() {
override fun format(r: LogRecord): String {
val builder = StringBuilder()
if (!logcat)
builder.append(DateFormatUtils.format(r.millis, "yyyy-MM-dd HH:mm:ss"))
.append(" ").append(r.threadID).append(" ")
if (r.sourceClassName.replaceFirst("\\$.*".toRegex(), "") != r.loggerName)
builder.append("[").append(shortClassName(r.sourceClassName)).append("] ")
builder.append(r.message)
if (r.thrown != null)
builder.append("\nEXCEPTION ")
.append(ExceptionUtils.getStackTrace(r.thrown))
if (r.parameters != null) {
var idx = 1
for (param in r.parameters)
builder.append("\n\tPARAMETER #").append(idx++).append(" = ").append(param)
}
if (!logcat)
builder.append("\n")
return builder.toString()
}
private fun shortClassName(className: String): String? {
val s = StringUtils.replace(className, "com.etesync.syncadapter.", "")
return StringUtils.replace(s, "at.bitfire.", "")
}
companion object {
val LOGCAT = PlainTextFormatter(true)
val DEFAULT = PlainTextFormatter(false)
}
}
| gpl-3.0 | 78d679d25643810875d7816dee049fab | 31.758621 | 91 | 0.644737 | 4.269663 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/java/KSClassDeclarationJavaImpl.kt | 1 | 6743 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.symbol.impl.java
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.isConstructor
import com.google.devtools.ksp.memoized
import com.google.devtools.ksp.processing.impl.ResolverImpl
import com.google.devtools.ksp.processing.impl.workaroundForNested
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.symbol.impl.*
import com.google.devtools.ksp.symbol.impl.binary.getAllFunctions
import com.google.devtools.ksp.symbol.impl.binary.getAllProperties
import com.google.devtools.ksp.symbol.impl.kotlin.KSErrorType
import com.google.devtools.ksp.symbol.impl.kotlin.KSExpectActualNoImpl
import com.google.devtools.ksp.symbol.impl.kotlin.KSNameImpl
import com.google.devtools.ksp.symbol.impl.kotlin.getKSTypeCached
import com.google.devtools.ksp.symbol.impl.replaceTypeArguments
import com.google.devtools.ksp.symbol.impl.synthetic.KSConstructorSyntheticImpl
import com.google.devtools.ksp.toKSModifiers
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiJavaFile
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl
import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithStarProjections
class KSClassDeclarationJavaImpl private constructor(val psi: PsiClass) :
KSClassDeclaration,
KSDeclarationJavaImpl(psi),
KSExpectActual by KSExpectActualNoImpl() {
companion object : KSObjectCache<PsiClass, KSClassDeclarationJavaImpl>() {
fun getCached(psi: PsiClass) = cache.getOrPut(psi) { KSClassDeclarationJavaImpl(psi) }
}
override val origin = Origin.JAVA
override val location: Location by lazy {
psi.toLocation()
}
override val annotations: Sequence<KSAnnotation> by lazy {
psi.annotations.asSequence().map { KSAnnotationJavaImpl.getCached(it) }.memoized()
}
override val classKind: ClassKind by lazy {
when {
psi.isAnnotationType -> ClassKind.ANNOTATION_CLASS
psi.isInterface -> ClassKind.INTERFACE
psi.isEnum -> ClassKind.ENUM_CLASS
else -> ClassKind.CLASS
}
}
override val containingFile: KSFile? by lazy {
KSFileJavaImpl.getCached(psi.containingFile as PsiJavaFile)
}
override val isCompanionObject = false
// Could the resolution ever fail?
private val descriptor: ClassDescriptor? by lazy {
ResolverImpl.instance!!.moduleClassResolver.resolveClass(JavaClassImpl(psi).apply { workaroundForNested() })
}
// TODO in 1.5 + jvmTarget 15, will we return Java permitted types?
override fun getSealedSubclasses(): Sequence<KSClassDeclaration> = emptySequence()
override fun getAllFunctions(): Sequence<KSFunctionDeclaration> =
descriptor?.getAllFunctions() ?: emptySequence()
override fun getAllProperties(): Sequence<KSPropertyDeclaration> =
descriptor?.getAllProperties() ?: emptySequence()
override val declarations: Sequence<KSDeclaration> by lazy {
val allDeclarations = (
psi.fields.asSequence().map {
when (it) {
is PsiEnumConstant -> KSClassDeclarationJavaEnumEntryImpl.getCached(it)
else -> KSPropertyDeclarationJavaImpl.getCached(it)
}
} +
psi.innerClasses.map { KSClassDeclarationJavaImpl.getCached(it) } +
psi.constructors.map { KSFunctionDeclarationJavaImpl.getCached(it) } +
psi.methods.map { KSFunctionDeclarationJavaImpl.getCached(it) }
)
.distinct()
// java annotation classes are interface. they get a constructor in .class
// hence they should get one here.
if (classKind == ClassKind.ANNOTATION_CLASS || !psi.isInterface) {
val hasConstructor = allDeclarations.any {
it is KSFunctionDeclaration && it.isConstructor()
}
if (hasConstructor) {
allDeclarations.memoized()
} else {
(allDeclarations + KSConstructorSyntheticImpl.getCached(this)).memoized()
}
} else {
allDeclarations.memoized()
}
}
override val modifiers: Set<Modifier> by lazy {
val modifiers = mutableSetOf<Modifier>()
modifiers.addAll(psi.toKSModifiers())
if (psi.isAnnotationType) {
modifiers.add(Modifier.ANNOTATION)
}
if (psi.isEnum) {
modifiers.add(Modifier.ENUM)
}
modifiers
}
override val primaryConstructor: KSFunctionDeclaration? = null
override val qualifiedName: KSName by lazy {
KSNameImpl.getCached(psi.qualifiedName!!)
}
override val simpleName: KSName by lazy {
KSNameImpl.getCached(psi.name!!)
}
override val superTypes: Sequence<KSTypeReference> by lazy {
val adjusted = if (!psi.isInterface && psi.superTypes.size > 1) {
psi.superTypes.filterNot {
it.className == "Object" && it.canonicalText == "java.lang.Object"
}
} else {
psi.superTypes.toList()
}
adjusted.asSequence().map { KSTypeReferenceJavaImpl.getCached(it, this) }.memoized()
}
override val typeParameters: List<KSTypeParameter> by lazy {
psi.typeParameters.map { KSTypeParameterJavaImpl.getCached(it) }
}
override fun asType(typeArguments: List<KSTypeArgument>): KSType {
return descriptor?.let {
it.defaultType.replaceTypeArguments(typeArguments)?.let {
getKSTypeCached(it, typeArguments)
}
} ?: KSErrorType
}
override fun asStarProjectedType(): KSType {
return descriptor?.let {
getKSTypeCached(it.defaultType.replaceArgumentsWithStarProjections())
} ?: KSErrorType
}
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitClassDeclaration(this, data)
}
}
| apache-2.0 | c989627a8e542a240d1cb9a6b9a869d5 | 37.976879 | 116 | 0.689901 | 4.772116 | false | false | false | false |
macleod2486/AndroidSwissKnife | app/src/main/java/com/macleod2486/androidswissknife/components/Flashlight.kt | 1 | 3071 | /*
AndroidSwissKnife
Copyright (C) 2016 macleod2486
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see [http://www.gnu.org/licenses/].
*/
package com.macleod2486.androidswissknife.components
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.Camera
import androidx.core.app.ActivityCompat
import androidx.fragment.app.FragmentActivity
import androidx.core.content.ContextCompat
import android.util.Log
import android.view.View
import android.widget.Toast
class Flashlight(var activity: FragmentActivity, var requestCode: Int) : View.OnClickListener {
var torchOn = false
lateinit var cam: Camera
lateinit var p: Camera.Parameters
override fun onClick(view: View) {
Log.i("Flashlight", "Current toggle $torchOn")
if (checkPermissions()) {
if (torchOn) {
turnOffLight()
} else {
turnOnLight()
}
}
}
fun toggleLight() {
if (torchOn) {
turnOffLight()
} else {
turnOnLight()
}
}
private fun turnOnLight() {
Log.i("Flashlight", "Toggling on light")
try {
cam = Camera.open()
p = cam.getParameters()
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH)
cam.setParameters(p)
val mPreviewTexture = SurfaceTexture(0)
cam.setPreviewTexture(mPreviewTexture)
cam.startPreview()
torchOn = true
} catch (ex: Exception) {
torchOn = false
Log.e("Flashlight", ex.toString())
}
}
private fun turnOffLight() {
Log.i("Flashlight", "Toggling off light")
torchOn = false
cam.stopPreview()
cam.release()
}
private fun checkPermissions(): Boolean {
var allowed = false
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
Toast.makeText(activity.applicationContext, "Need to enable camera permissions", Toast.LENGTH_SHORT).show()
} else {
ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.CAMERA), requestCode)
}
} else {
allowed = true
}
return allowed
}
} | gpl-3.0 | 15ecbd0d2f1ba51c5b00356febdc2483 | 32.758242 | 123 | 0.647021 | 4.783489 | false | false | false | false |
wuseal/JsonToKotlinClass | src/main/kotlin/wu/seal/jsontokotlin/InsertKotlinClassAction.kt | 1 | 8218 | package wu.seal.jsontokotlin
import com.google.gson.Gson
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import wu.seal.jsontokotlin.feedback.StartAction
import wu.seal.jsontokotlin.feedback.SuccessCompleteAction
import wu.seal.jsontokotlin.feedback.dealWithException
import wu.seal.jsontokotlin.feedback.sendActionInfo
import wu.seal.jsontokotlin.model.UnSupportJsonException
import wu.seal.jsontokotlin.ui.JsonInputDialog
import wu.seal.jsontokotlin.utils.*
import java.net.URL
import java.util.*
import kotlin.math.max
/**
* Plugin action
* Created by Seal.Wu on 2017/8/18.
*/
class InsertKotlinClassAction : AnAction("Kotlin data classes from JSON") {
private val gson = Gson()
override fun actionPerformed(event: AnActionEvent) {
var jsonString = ""
try {
actionStart()
val project = event.getData(PlatformDataKeys.PROJECT)
val caret = event.getData(PlatformDataKeys.CARET)
val editor = event.getData(PlatformDataKeys.EDITOR_EVEN_IF_INACTIVE)
if (couldNotInsertCode(editor)) return
val document = editor?.document ?: return
val editorText = document.text
/**
* temp class name for insert
*/
var tempClassName = ""
val couldGetAndReuseClassNameInCurrentEditFileForInsertCode =
couldGetAndReuseClassNameInCurrentEditFileForInsertCode(editorText)
if (couldGetAndReuseClassNameInCurrentEditFileForInsertCode) {
/**
* auto obtain the current class name
*/
tempClassName = getCurrentEditFileTemClassName(editorText)
}
val inputDialog = JsonInputDialog(tempClassName, project!!)
inputDialog.show()
val className = inputDialog.getClassName()
val inputString = inputDialog.inputString
val json = if (inputString.startsWith("http")) {
URL(inputString).readText()
} else inputString
if (json.isEmpty()) {
return
}
jsonString = json
if (reuseClassName(couldGetAndReuseClassNameInCurrentEditFileForInsertCode, className, tempClassName)) {
executeCouldRollBackAction(project) {
/**
* if you don't clean then we will trick a conflict with two same class name error
*/
cleanCurrentEditFile(document)
}
}
if (insertKotlinCode(project, document, className, jsonString, caret)) {
actionComplete()
}
} catch (e: UnSupportJsonException) {
val advice = e.advice
Messages.showInfoMessage(dealWithHtmlConvert(advice), "Tip")
} catch (e: Throwable) {
dealWithException(jsonString, e)
throw e
}
}
private fun dealWithHtmlConvert(advice: String) = advice.replace("<", "<").replace(">", ">")
private fun reuseClassName(
couldGetAndReuseClassNameInCurrentEditFileForInserCode: Boolean,
className: String,
tempClassName: String
) = couldGetAndReuseClassNameInCurrentEditFileForInserCode && className == tempClassName
private fun couldNotInsertCode(editor: Editor?): Boolean {
if (editor == null || editor.document.isWritable.not()) {
Messages.showWarningDialog("Please open a file in edited state for inserting Kotlin code!", "No Edited File")
return true
}
return false
}
private fun actionComplete() {
Thread {
sendActionInfo(gson.toJson(SuccessCompleteAction()))
}.start()
}
private fun actionStart() {
Thread {
sendActionInfo(gson.toJson(StartAction()))
}.start()
}
private fun insertKotlinCode(
project: Project?,
document: Document,
className: String,
jsonString: String,
caret: Caret?
): Boolean {
ClassImportDeclarationWriter.insertImportClassCode(project, document)
val codeMaker: KotlinClassCodeMaker
try {
//passing current file directory along with className and json
val kotlinClass = KotlinClassMaker(className, jsonString).makeKotlinClass()
codeMaker = KotlinClassCodeMaker(kotlinClass, jsonString.isJSONSchema())
} catch (e: IllegalFormatFlagsException) {
e.printStackTrace()
Messages.showErrorDialog(e.message, "UnSupport Json")
return false
}
val generateClassesString = codeMaker.makeKotlinClassCode()
executeCouldRollBackAction(project) {
var offset: Int
if (caret != null) {
offset = caret.offset
if (offset == 0) {
offset = document.textLength
}
val lastPackageKeywordLineEndIndex = try {
"^[\\s]*package\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.last
} catch (e: Exception) {
-1
}
val lastImportKeywordLineEndIndex = try {
"^[\\s]*import\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.last
} catch (e: Exception) {
-1
}
if (offset < lastPackageKeywordLineEndIndex) {
offset = lastPackageKeywordLineEndIndex + 1
}
if (offset < lastImportKeywordLineEndIndex) {
offset = lastImportKeywordLineEndIndex + 1
}
} else {
offset = document.textLength
}
document.insertString(
max(offset, 0),
ClassCodeFilter.removeDuplicateClassCode(generateClassesString)
)
}
return true
}
private fun cleanCurrentEditFile(document: Document, editorText: String = document.text) {
val cleanText = getCleanText(editorText)
document.setText(cleanText)
}
fun getCleanText(editorText: String): String {
val tempCleanText = editorText.substringBeforeLast("class")
return if (tempCleanText.trim().endsWith("data")) tempCleanText.trim().removeSuffix("data") else tempCleanText
}
fun getCurrentEditFileTemClassName(editorText: String) = editorText.substringAfterLast("class")
.substringBefore("(").substringBefore("{").trim()
/**
* whether we could reuse current class name declared in the edit file for inserting data class code
* if we could use it,then we would clean the kotlin file as it was new file without any class code .
*/
fun couldGetAndReuseClassNameInCurrentEditFileForInsertCode(editorText: String): Boolean {
try {
val removeDocComment = editorText.replace(Regex("/\\*\\*(.|\n)*\\*/", RegexOption.MULTILINE), "")
val removeDocCommentAndPackageDeclareText = removeDocComment
.replace(Regex("^(?:\\s*package |\\s*import ).*$", RegexOption.MULTILINE), "")
removeDocCommentAndPackageDeclareText.run {
if (numberOf("class") == 1 &&
(substringAfter("class").containsAnyOf(listOf("(", ":", "=")).not()
|| substringAfter("class").substringAfter("(").replace(
Regex("\\s"),
""
).let { it == ")" || it == "){}" })
) {
return true
}
}
} catch (e: Throwable) {
e.printStackTrace()
}
return false
}
}
| gpl-3.0 | 331878500b49281dd63d70b1612b276f | 37.401869 | 121 | 0.597834 | 5.460465 | false | false | false | false |
jtransc/jtransc | benchmark_kotlin_mpp/wip/jzlib/GZIPInputStream.kt | 1 | 4000 | /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jtransc.compression.jzlib
import com.jtransc.annotation.JTranscInvisible
import java.io.IOException
@JTranscInvisible
class GZIPInputStream(
`in`: java.io.InputStream?,
inflater: Inflater?,
size: Int,
close_in: Boolean
) : InflaterInputStream(`in`, inflater, size, close_in) {
@JvmOverloads
constructor(
`in`: java.io.InputStream?,
size: Int = DEFAULT_BUFSIZE,
close_in: Boolean = true
) : this(`in`, Inflater(15 + 16), size, close_in) {
myinflater = true
}
val modifiedtime: Long
get() = inflater.istate.getGZIPHeader().getModifiedTime()
val oS: Int
get() = inflater.istate.getGZIPHeader().getOS()
val name: String
get() = inflater.istate.getGZIPHeader().getName()
val comment: String
get() = inflater.istate.getGZIPHeader().getComment()
/*DONE*/
@get:Throws(GZIPException::class)
val cRC: Long
get() {
if (inflater.istate.mode !== 12 /*DONE*/) throw GZIPException("checksum is not calculated yet.")
return inflater.istate.getGZIPHeader().getCRC()
}
@Throws(IOException::class)
override fun readHeader() {
val empty: ByteArray = "".toByteArray()
inflater.setOutput(empty, 0, 0)
inflater.setInput(empty, 0, 0, false)
val b = ByteArray(10)
var n = fill(b)
if (n != 10) {
if (n > 0) {
inflater.setInput(b, 0, n, false)
//inflater.next_in_index = n;
inflater.next_in_index = 0
inflater.avail_in = n
}
throw IOException("no input")
}
inflater.setInput(b, 0, n, false)
val b1 = ByteArray(1)
do {
if (inflater.avail_in <= 0) {
val i: Int = `in`.read(b1)
if (i <= 0) throw IOException("no input")
inflater.setInput(b1, 0, 1, true)
}
val err: Int = inflater.inflate(JZlib.Z_NO_FLUSH)
if (err != 0 /*Z_OK*/) {
val len: Int = 2048 - inflater.next_in.length
if (len > 0) {
val tmp = ByteArray(len)
n = fill(tmp)
if (n > 0) {
inflater.avail_in += inflater.next_in_index
inflater.next_in_index = 0
inflater.setInput(tmp, 0, n, true)
}
}
//inflater.next_in_index = inflater.next_in.length;
inflater.avail_in += inflater.next_in_index
inflater.next_in_index = 0
throw IOException(inflater.msg)
}
} while (inflater.istate.inParsingHeader())
}
private fun fill(buf: ByteArray): Int {
val len = buf.size
var n = 0
do {
var i = -1
try {
i = `in`.read(buf, n, buf.size - n)
} catch (e: IOException) {
}
if (i == -1) {
break
}
n += i
} while (n < len)
return n
}
} | apache-2.0 | 3520d2983fe6c587932c68ae53584650 | 30.753968 | 99 | 0.68975 | 3.433476 | false | false | false | false |
Fitbit/MvRx | mock_generation/ShellAccess.kt | 1 | 5910 | #!/usr/bin/env kscript
/**
* Functions for executing shell commands and receiving the result.
*/
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.lang.ProcessBuilder.Redirect
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess
/**
* Executes the receiving string and returns the stdOut as a single line.
* If the result is more than one line an exception is thrown.
* @throws IOException if an I/O error occurs
*/
fun String.executeForSingleLine(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS,
suppressStderr: Boolean = false,
redactedTokens: List<String> = emptyList(),
throwOnFailure: Boolean = false
): String {
val lines = executeForLines(
workingDir,
timeoutAmount,
timeoutUnit,
suppressStderr = suppressStderr,
redactedTokens = redactedTokens,
throwOnFailure = throwOnFailure
)
.filter { it.isNotBlank() }
return lines.singleOrNull() ?: throw IllegalStateException("Expected single line but got: $lines")
}
/**
* Executes the receiving string and returns the stdOut as a list of all lines outputted.
* @throws IOException if an I/O error occurs
* @param clearQuotes If true, double quotes will be removed if they wrap the line
*/
fun String.executeForLines(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS,
clearQuotes: Boolean = false,
suppressStderr: Boolean = false,
redactedTokens: List<String> = emptyList(),
throwOnFailure: Boolean = false
): List<String> {
return executeForBufferedReader(
workingDir,
timeoutAmount,
timeoutUnit,
suppressStderr = suppressStderr,
redactedTokens = redactedTokens,
throwOnFailure = throwOnFailure
)
.readLines()
.map { if (clearQuotes) it.removePrefix("\"").removeSuffix("\"") else it }
}
/**
* Executes the receiving string and returns the stdOut as a BufferedReader.
* @throws IOException if an I/O error occurs
*/
fun String.executeForBufferedReader(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS,
suppressStderr: Boolean = false,
redactedTokens: List<String> = emptyList(),
throwOnFailure: Boolean = false
): BufferedReader {
val stderrRedirectBehavior = if (suppressStderr) Redirect.PIPE else Redirect.INHERIT
return execute(
workingDir,
timeoutAmount,
timeoutUnit,
stderrRedirectBehavior = stderrRedirectBehavior,
redactedTokens = redactedTokens,
throwOnFailure = throwOnFailure
).stdOut
}
/**
* Executes the receiving string and returns the result,
* including exit code, stdOut, and stdErr streams.
* Some commands do not work if the command is redirected to PIPE.
* Use ProcessBuilder.Redirect.INHERIT in those cases.
*
* @throws IOException if an I/O error occurs
*/
fun String.execute(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS,
timeoutMessage: String? = null,
stdoutRedirectBehavior: Redirect = Redirect.PIPE,
stderrRedirectBehavior: Redirect = Redirect.PIPE,
redactedTokens: List<String> = emptyList(),
throwOnFailure: Boolean = false
): ProcessResult {
var commandToLog = this
redactedTokens.forEach { commandToLog = commandToLog.replace(it, "<redacted>") }
// The command is disabled by default on local run to avoid cluttering people's consoles;
// Only printed on CI or if KSCRIPT_SHELL_ACCESS_DEBUG is set
if (!isMacOs() || !System.getenv("KSCRIPT_SHELL_ACCESS_DEBUG").isNullOrEmpty()) {
System.err.println("Executing command [workingDir: '$workingDir']: $commandToLog")
}
return ProcessBuilder("/bin/sh", "-c", this)
.directory(workingDir)
.redirectOutput(stdoutRedirectBehavior)
.redirectError(stderrRedirectBehavior)
.start()
.apply {
waitFor(timeoutAmount, timeoutUnit)
if (isAlive) {
destroyForcibly()
println("Command timed out after ${timeoutUnit.toSeconds(timeoutAmount)} seconds: '$commandToLog'")
if (
stdoutRedirectBehavior.type() == Redirect.Type.PIPE ||
stderrRedirectBehavior.type() == Redirect.Type.PIPE
) {
println(
listOf(
"Note: Timeout can potentially be due to deadlock when using stdout=PIPE and/or stderr=PIPE",
" and the child process (subpocess running the command) generates enough output to a pipe",
" (~50 KB) such that it blocks waiting for the OS pipe buffer to accept more data.",
"Please consider writing to a stdout/stderr to temp-file instead in such situations!"
).joinToString("")
)
}
timeoutMessage?.let { println(it) }
exitProcess(1)
}
}
.let { process ->
val result = ProcessResult(process.exitValue(), process.inputStream.bufferedReader(), process.errorStream.bufferedReader())
check(!(throwOnFailure && result.failed)) {
"Command failed with exit-code(${process.exitValue()}): '$commandToLog'"
}
result
}
}
fun isMacOs(): Boolean = System.getProperty("os.name").contains("mac", ignoreCase = true)
data class ProcessResult(val exitCode: Int, val stdOut: BufferedReader, val stdErr: BufferedReader) {
val succeeded: Boolean = exitCode == 0
val failed: Boolean = !succeeded
}
fun BufferedReader.print() {
lineSequence().forEach { println(it) }
}
| apache-2.0 | 448e3f92b126235d54663dec7631d407 | 36.405063 | 135 | 0.651777 | 4.974747 | false | false | false | false |
jtransc/jtransc | jtransc-core/src/com/jtransc/ast/dependency/analyzer.kt | 1 | 7670 | /*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.jtransc.ast.dependency
import com.jtransc.ast.*
import com.jtransc.error.noImpl
// @TODO: Use generic visitor!
object AstDependencyAnalyzer {
enum class Reason { UNKNWON, STATIC }
class Config(
val reason: Reason = Reason.UNKNWON,
val methodHandler: (AstExpr.CALL_BASE, AstDependencyAnalyzerGen) -> Unit = { b, d -> }
)
@JvmStatic fun analyze(program: AstProgram, body: AstBody?, name: String? = null, config: Config): AstReferences {
return AstDependencyAnalyzerGen(program, body, name, config = config).references
}
class AstDependencyAnalyzerGen(program: AstProgram, val body: AstBody?, val name: String? = null, val config: Config) {
val methodHandler = config.methodHandler
val ignoreExploring = hashSetOf<AstRef>()
val allSortedRefs = linkedSetOf<AstRef>()
val allSortedRefsStaticInit = linkedSetOf<AstRef>()
val types = hashSetOf<FqName>()
val fields = hashSetOf<AstFieldRef>()
val methods = hashSetOf<AstMethodRef>()
fun ignoreExploring(ref: AstRef) {
ignoreExploring += ref
}
fun flow() {
if (config.reason == Reason.STATIC) {
//println("Conditional execution in ${body?.methodRef ?: $name}")
}
}
fun ana(method: AstMethodRef) {
if (method in ignoreExploring) return
allSortedRefs.add(method)
methods.add(method)
}
fun ana(field: AstFieldRef) {
if (field in ignoreExploring) return
allSortedRefs.add(field)
fields.add(field)
}
fun ana(type: AstType) {
//if (type in ignoreExploring) return
allSortedRefs.addAll(type.getRefTypes())
types.addAll(type.getRefTypesFqName())
}
fun ana(types: List<AstType>) = types.forEach { ana(it) }
fun ana(expr: AstExpr.Box?) = ana(expr?.value)
fun ana(stm: AstStm.Box?) = ana(stm?.value)
fun ana(expr: AstExpr?) {
if (expr == null) return
when (expr) {
is AstExpr.BaseCast -> {
//is AstExpr.CAST -> {
ana(expr.from)
ana(expr.to)
ana(expr.subject)
}
is AstExpr.NEW_ARRAY -> {
for (c in expr.counts) ana(c)
ana(expr.arrayType)
allSortedRefsStaticInit += expr.arrayType.getRefClasses()
}
is AstExpr.INTARRAY_LITERAL -> {
//for (c in expr.values) ana(c)
ana(expr.arrayType)
}
is AstExpr.OBJECTARRAY_LITERAL -> {
//for (c in expr.values) ana(c)
ana(expr.arrayType)
allSortedRefsStaticInit += AstType.STRING
}
is AstExpr.ARRAY_ACCESS -> {
ana(expr.type)
ana(expr.array)
ana(expr.index)
}
is AstExpr.ARRAY_LENGTH -> {
ana(expr.array)
}
is AstExpr.TERNARY -> {
ana(expr.cond)
ana(expr.etrue)
ana(expr.efalse)
}
is AstExpr.BINOP -> {
ana(expr.left)
ana(expr.right)
}
is AstExpr.CALL_BASE -> {
methodHandler(expr, this)
ana(expr.method.type)
for (arg in expr.args) ana(arg)
ana(expr.method)
if (expr is AstExpr.CALL_STATIC) ana(expr.clazz)
if (expr is AstExpr.CALL_INSTANCE) ana(expr.obj)
if (expr is AstExpr.CALL_SUPER) ana(expr.obj)
allSortedRefsStaticInit += expr.method
}
is AstExpr.CONCAT_STRING -> {
ana(expr.original)
}
is AstExpr.CAUGHT_EXCEPTION -> {
ana(expr.type)
}
is AstExpr.FIELD_INSTANCE_ACCESS -> {
ana(expr.expr)
ana(expr.field)
}
is AstExpr.FIELD_STATIC_ACCESS -> {
ana(expr.clazzName)
ana(expr.field)
allSortedRefsStaticInit += expr.field.containingTypeRef
}
is AstExpr.INSTANCE_OF -> {
ana(expr.expr)
ana(expr.checkType)
}
is AstExpr.UNOP -> ana(expr.right)
is AstExpr.THIS -> ana(expr.type)
is AstExpr.LITERAL -> {
val value = expr.value
when (value) {
is AstType -> {
ana(value)
allSortedRefsStaticInit += value.getRefClasses()
}
//null -> Unit
//is Void, is String -> Unit
//is Boolean, is Byte, is Char, is Short, is Int, is Long -> Unit
//is Float, is Double -> Unit
is AstMethodHandle -> {
ana(value.type)
ana(value.methodRef)
allSortedRefsStaticInit += value.methodRef
}
//else -> invalidOp("Literal: ${expr.value}")
}
}
is AstExpr.LOCAL -> Unit
is AstExpr.TYPED_LOCAL -> Unit
is AstExpr.PARAM -> ana(expr.type)
is AstExpr.INVOKE_DYNAMIC_METHOD -> {
ana(expr.type)
ana(expr.methodInInterfaceRef)
ana(expr.methodToConvertRef)
ana(expr.methodInInterfaceRef.allClassRefs)
ana(expr.methodToConvertRef.allClassRefs)
allSortedRefsStaticInit += expr.methodInInterfaceRef
allSortedRefsStaticInit += expr.methodToConvertRef
}
is AstExpr.NEW_WITH_CONSTRUCTOR -> {
ana(expr.target)
allSortedRefsStaticInit += expr.target
for (arg in expr.args) ana(arg)
ana(AstExpr.CALL_STATIC(expr.constructor, expr.args.unbox, isSpecial = true))
}
//is AstExpr.REF -> ana(expr.expr)
is AstExpr.LITERAL_REFNAME -> {
ana(expr.type)
}
else -> noImpl("Not implemented $expr")
}
}
fun ana(stm: AstStm?) {
if (stm == null) return
when (stm) {
is AstStm.STMS -> for (s in stm.stms) ana(s)
is AstStm.STM_EXPR -> ana(stm.expr)
is AstStm.STM_LABEL -> Unit
is AstStm.MONITOR_ENTER -> ana(stm.expr)
is AstStm.MONITOR_EXIT -> ana(stm.expr)
is AstStm.SET_LOCAL -> ana(stm.expr)
is AstStm.SET_ARRAY -> {
ana(stm.array);
ana(stm.expr); ana(stm.index)
}
is AstStm.SET_ARRAY_LITERALS -> {
ana(stm.array)
for (v in stm.values) ana(v)
}
is AstStm.SET_FIELD_INSTANCE -> {
ana(stm.field); ana(stm.left); ana(stm.expr)
}
is AstStm.SET_FIELD_STATIC -> {
ana(stm.field); ana(stm.expr)
allSortedRefsStaticInit += stm.field.containingTypeRef
}
is AstStm.RETURN -> ana(stm.retval)
is AstStm.RETURN_VOID -> Unit
is AstStm.THROW -> {
ana(stm.exception)
}
is AstStm.CONTINUE -> Unit
is AstStm.BREAK -> Unit
is AstStm.TRY_CATCH -> {
ana(stm.trystm);
ana(stm.catch)
}
is AstStm.LINE -> Unit
is AstStm.NOP -> Unit
is AstStm.SWITCH_GOTO -> {
flow()
ana(stm.subject)
}
is AstStm.SWITCH -> {
flow()
ana(stm.subject); ana(stm.default)
for (catch in stm.cases) ana(catch.second)
}
is AstStm.IF_GOTO -> {
flow()
ana(stm.cond)
}
is AstStm.GOTO -> {
flow()
}
is AstStm.IF -> {
flow()
ana(stm.cond); ana(stm.strue);
}
is AstStm.IF_ELSE -> {
flow()
ana(stm.cond); ana(stm.strue); ana(stm.sfalse)
}
is AstStm.WHILE -> {
flow()
ana(stm.cond); ana(stm.iter)
}
else -> noImpl("Not implemented STM $stm")
}
}
init {
if (body != null) {
for (local in body.locals) ana(local.type)
ana(body.stm)
for (trap in body.traps) ana(trap.exception)
}
}
val references = AstReferences(
program = program,
allSortedRefs = allSortedRefs,
allSortedRefsStaticInit = allSortedRefsStaticInit,
classes = types.map { AstType.REF(it) }.toSet(),
fields = fields.toSet(),
methods = methods.toSet()
)
}
}
| apache-2.0 | 14cf0a519011e11202c21b01d7705ca9 | 25.912281 | 120 | 0.633246 | 3.244501 | false | false | false | false |
premisedata/cameraview | demo/src/main/kotlin/com/otaliastudios/cameraview/demo/MessageView.kt | 1 | 1057 | package com.otaliastudios.cameraview.demo
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
class MessageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
init {
orientation = VERTICAL
View.inflate(context, R.layout.option_view, this)
val content = findViewById<ViewGroup>(R.id.content)
View.inflate(context, R.layout.spinner_text, content)
}
private val message: TextView = findViewById<ViewGroup>(R.id.content).getChildAt(0) as TextView
private val title: TextView = findViewById(R.id.title)
fun setMessage(message: String) { this.message.text = message }
fun setTitle(title: String) { this.title.text = title }
fun setTitleAndMessage(title: String, message: String) {
setTitle(title)
setMessage(message)
}
}
| apache-2.0 | 5fdd56a4f33825eed84c9400a8c1d548 | 30.088235 | 99 | 0.712394 | 4.24498 | false | false | false | false |
msebire/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GrCodeReferenceResolver.kt | 1 | 10648 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.parentOfType
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrExtendsClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrImplementsClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement
import org.jetbrains.plugins.groovy.lang.psi.api.types.CodeReferenceKind.*
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameter
import org.jetbrains.plugins.groovy.lang.psi.impl.explicitTypeArguments
import org.jetbrains.plugins.groovy.lang.psi.util.contexts
import org.jetbrains.plugins.groovy.lang.psi.util.skipSameTypeParents
import org.jetbrains.plugins.groovy.lang.psi.util.treeWalkUp
import org.jetbrains.plugins.groovy.lang.resolve.imports.GroovyImport
import org.jetbrains.plugins.groovy.lang.resolve.imports.StarImport
import org.jetbrains.plugins.groovy.lang.resolve.imports.StaticImport
import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.CollectElementsProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.TypeParameterProcessor
// https://issues.apache.org/jira/browse/GROOVY-8358
// https://issues.apache.org/jira/browse/GROOVY-8359
// https://issues.apache.org/jira/browse/GROOVY-8361
// https://issues.apache.org/jira/browse/GROOVY-8362
// https://issues.apache.org/jira/browse/GROOVY-8364
// https://issues.apache.org/jira/browse/GROOVY-8365
internal object GrCodeReferenceResolver : GroovyResolver<GrCodeReferenceElement> {
override fun resolve(ref: GrCodeReferenceElement, incomplete: Boolean): Collection<GroovyResolveResult> {
return when (ref.kind) {
PACKAGE_REFERENCE -> ref.resolveAsPackageReference()
IMPORT_REFERENCE -> ref.resolveAsImportReference()
REFERENCE -> ref.resolveReference()
}
}
}
private fun GrCodeReferenceElement.resolveAsPackageReference(): Collection<GroovyResolveResult> {
val aPackage = resolvePackageFqn() ?: return emptyList()
return listOf(ElementResolveResult(aPackage))
}
private fun GrCodeReferenceElement.resolveAsImportReference(): Collection<GroovyResolveResult> {
val file = containingFile as? GroovyFile ?: return emptyList()
val statement = parentOfType<GrImportStatement>() ?: return emptyList()
val topLevelReference = statement.importReference ?: return emptyList()
val import = statement.import ?: return emptyList()
if (this === topLevelReference) {
return if (import is StaticImport) {
resolveStaticImportReference(file, import)
}
else {
resolveImportReference(file, import)
}
}
if (parent === topLevelReference && import is StaticImport) {
return resolveImportReference(file, import)
}
if (import is StarImport) {
// reference inside star import
return resolveAsPackageReference()
}
val clazz = import.resolveImport(file) as? PsiClass
val classReference = if (import is StaticImport) topLevelReference.qualifier else topLevelReference
if (clazz == null || classReference == null) return resolveAsPackageReference()
return resolveAsPartOfFqn(classReference, clazz)
}
private fun resolveStaticImportReference(file: GroovyFile, import: StaticImport): Collection<GroovyResolveResult> {
val processor = CollectElementsProcessor()
import.processDeclarations(processor, ResolveState.initial(), file, file)
return processor.results.collapseReflectedMethods().collapseAccessors().map(::ElementResolveResult)
}
private fun resolveImportReference(file: GroovyFile, import: GroovyImport): Collection<GroovyResolveResult> {
val resolved = import.resolveImport(file) ?: return emptyList()
return listOf(ElementResolveResult(resolved))
}
private fun GrCodeReferenceElement.resolveReference(): Collection<GroovyResolveResult> {
val name = referenceName ?: return emptyList()
if (canResolveToTypeParameter()) {
val typeParameters = resolveToTypeParameter(this, name)
if (typeParameters.isNotEmpty()) return typeParameters
}
val (_, outerMostReference) = skipSameTypeParents()
if (outerMostReference !== this) {
val fqnReferencedClass = outerMostReference.resolveClassFqn()
if (fqnReferencedClass != null) {
return resolveAsPartOfFqn(outerMostReference, fqnReferencedClass)
}
}
else if (isQualified) {
val clazz = resolveClassFqn()
if (clazz != null) {
return listOf(ClassProcessor.createResult(clazz, this, ResolveState.initial(), explicitTypeArguments))
}
}
val processor = ClassProcessor(name, this, explicitTypeArguments, isAnnotationReference())
val state = ResolveState.initial()
processClasses(processor, state)
val classes = processor.results
if (classes.isNotEmpty()) return classes
if (canResolveToPackage()) {
val packages = resolveAsPackageReference()
if (packages.isNotEmpty()) return packages
}
return emptyList()
}
private fun GrReferenceElement<*>.canResolveToTypeParameter(): Boolean {
if (isQualified) return false
val parent = parent
return when (parent) {
is GrReferenceElement<*>,
is GrExtendsClause,
is GrImplementsClause,
is GrAnnotation,
is GrImportStatement,
is GrNewExpression,
is GrAnonymousClassDefinition,
is GrCodeReferenceElement -> false
else -> true
}
}
private fun resolveToTypeParameter(place: PsiElement, name: String): Collection<GroovyResolveResult> {
val processor = TypeParameterProcessor(name)
place.treeWalkUp(processor)
return processor.results
}
private fun GrReferenceElement<*>.canResolveToPackage(): Boolean = parent is GrReferenceElement<*>
private fun GrCodeReferenceElement.resolveAsPartOfFqn(reference: GrCodeReferenceElement, clazz: PsiClass): Collection<GroovyResolveResult> {
var currentReference = reference
var currentElement: PsiNamedElement = clazz
while (currentReference !== this) {
currentReference = currentReference.qualifier ?: return emptyList()
val e: PsiNamedElement? = when (currentElement) {
is PsiClass -> currentElement.containingClass ?: currentElement.getPackage()
is PsiPackage -> currentElement.parentPackage
else -> null
}
currentElement = e ?: return emptyList()
}
return listOf(BaseGroovyResolveResult(currentElement, this))
}
private fun PsiClass.getPackage(): PsiPackage? {
val file = containingFile
val name = (file as? PsiClassOwner)?.packageName ?: return null
return JavaPsiFacade.getInstance(file.project).findPackage(name)
}
fun GrCodeReferenceElement.processClasses(processor: PsiScopeProcessor, state: ResolveState): Boolean {
val qualifier = qualifier
if (qualifier == null) {
return processUnqualified(processor, state)
}
else {
return processQualifier(qualifier, processor, state)
}
}
fun PsiElement.processUnqualified(processor: PsiScopeProcessor, state: ResolveState): Boolean {
return processInnerClasses(processor, state) &&
processFileLevelDeclarations(processor, state)
}
/**
* @see org.codehaus.groovy.control.ResolveVisitor.resolveNestedClass
*/
private fun PsiElement.processInnerClasses(processor: PsiScopeProcessor, state: ResolveState): Boolean {
val currentClass = getCurrentClass() ?: return true
if (this !is GrCodeReferenceElement || canResolveToInnerClassOfCurrentClass()) {
if (!currentClass.processInnerInHierarchy(processor, state, this)) return false
}
return currentClass.processInnersInOuters(processor, state, this)
}
/**
* @see org.codehaus.groovy.control.ResolveVisitor.resolveFromModule
* @see org.codehaus.groovy.control.ResolveVisitor.resolveFromDefaultImports
*/
private fun PsiElement.processFileLevelDeclarations(processor: PsiScopeProcessor, state: ResolveState): Boolean {
// There is no point in processing imports in dummy files.
val file = containingFile.skipDummies() ?: return true
return file.treeWalkUp(processor, state, this)
}
private fun GrCodeReferenceElement.processQualifier(qualifier: GrCodeReferenceElement,
processor: PsiScopeProcessor,
state: ResolveState): Boolean {
for (result in qualifier.multiResolve(false)) {
val clazz = result.element as? PsiClass ?: continue
if (!clazz.processDeclarations(processor, state.put(PsiSubstitutor.KEY, result.substitutor), null, this)) return false
}
return true
}
private fun GrCodeReferenceElement.canResolveToInnerClassOfCurrentClass(): Boolean {
val (_, outerMostReference) = skipSameTypeParents()
val parent = outerMostReference.getActualParent()
return parent !is GrExtendsClause &&
parent !is GrImplementsClause &&
(parent !is GrAnnotation || parent.classReference != this) // annotation's can't be inner classes of current class
}
/**
* Reference element may be created from stub. In this case containing file will be dummy, and its context will be reference parent
*/
private fun GrCodeReferenceElement.getActualParent(): PsiElement? = containingFile.context ?: parent
/**
* @see org.codehaus.groovy.control.ResolveVisitor.currentClass
*/
private fun PsiElement.getCurrentClass(): GrTypeDefinition? {
for (context in contexts()) {
if (context !is GrTypeDefinition) {
continue
}
else if (context is GrTypeParameter) {
continue
}
else if (context is GrAnonymousClassDefinition && this === context.baseClassReferenceGroovy) {
continue
}
else {
return context
}
}
return null
}
private fun PsiFile?.skipDummies(): PsiFile? {
var file: PsiFile? = this
while (file != null && !file.isPhysical) {
val context = file.context
if (context == null) return file
file = context.containingFile
}
return file
}
| apache-2.0 | 839efefb2945d31d77a5e1e9216aa8d0 | 39.181132 | 140 | 0.766529 | 4.796396 | false | false | false | false |
square/duktape-android | zipline-loader/src/commonTest/kotlin/app/cash/zipline/loader/internal/fetcher/HttpFetcherTest.kt | 1 | 3505 | /*
* Copyright (C) 2022 Block, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline.loader.internal.fetcher
import app.cash.zipline.EventListener
import app.cash.zipline.loader.FakeZiplineHttpClient
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
class HttpFetcherTest {
private val httpFetcher = HttpFetcher(FakeZiplineHttpClient(), EventListener.NONE)
private val json = Json {
prettyPrint = true
}
@Test
fun happyPath() {
val manifestWithRelativeUrls =
"""
|{
| "modules": {
| "./hello.js": {
| "url": "hello.zipline",
| "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab"
| },
| "./jello.js": {
| "url": "jello.zipline",
| "sha256": "7af37185091e22463ff627686aedfec3528376eb745026fae1d6153688885e73"
| }
| }
|}
""".trimMargin()
val manifestWithBaseUrl = httpFetcher.withBaseUrl(
manifest = json.parseToJsonElement(manifestWithRelativeUrls),
baseUrl = "https://example.com/path/",
)
assertEquals(
"""
|{
| "unsigned": {
| "baseUrl": "https://example.com/path/"
| },
| "modules": {
| "./hello.js": {
| "url": "hello.zipline",
| "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab"
| },
| "./jello.js": {
| "url": "jello.zipline",
| "sha256": "7af37185091e22463ff627686aedfec3528376eb745026fae1d6153688885e73"
| }
| }
|}
""".trimMargin(),
json.encodeToString(JsonElement.serializer(), manifestWithBaseUrl),
)
}
@Test
fun withBaseUrlRetainsUnknownFields() {
val manifestWithRelativeUrls =
"""
|{
| "unknown string": "hello",
| "modules": {
| "./hello.js": {
| "url": "hello.zipline",
| "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab"
| }
| }
|}
""".trimMargin()
val manifestWithResolvedUrls = httpFetcher.withBaseUrl(
manifest = json.parseToJsonElement(manifestWithRelativeUrls),
baseUrl = "https://example.com/path/",
)
assertEquals(
"""
|{
| "unsigned": {
| "baseUrl": "https://example.com/path/"
| },
| "unknown string": "hello",
| "modules": {
| "./hello.js": {
| "url": "hello.zipline",
| "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab"
| }
| }
|}
""".trimMargin(),
json.encodeToString(JsonElement.serializer(), manifestWithResolvedUrls),
)
}
}
| apache-2.0 | 504e17d33dfea18f287c3e4dfbf0fb60 | 29.745614 | 95 | 0.580884 | 3.651042 | false | true | false | false |
IVA Kotlin GitHub Code Dataset
Dataset Description
This is the curated train split of IVA Kotlin dataset extracted from GitHub. It contains curated Kotlin files gathered with the purpose to train a code generation model.
The dataset consists of 383380 Kotlin code files from GitHub. Here is the unsliced curated dataset and here is the raw dataset.
How to use it
To download the full dataset:
from datasets import load_dataset
dataset = load_dataset('mvasiliniuc/iva-kotlin-codeint-clean-train', split='train'))
Data Structure
Data Fields
Field | Type | Description |
---|---|---|
repo_name | string | name of the GitHub repository |
path | string | path of the file in GitHub repository |
copies | string | number of occurrences in dataset |
content | string | content of source file |
size | string | size of the source file in bytes |
license | string | license of GitHub repository |
hash | string | Hash of content field. |
line_mean | number | Mean line length of the content. |
line_max | number | Max line length of the content. |
alpha_frac | number | Fraction between mean and max line length of content. |
ratio | number | Character/token ratio of the file with tokenizer. |
autogenerated | boolean | True if the content is autogenerated by looking for keywords in the first few lines of the file. |
config_or_test | boolean | True if the content is a configuration file or a unit test. |
has_no_keywords | boolean | True if a file has none of the keywords for Kotlin Programming Language. |
has_few_assignments | boolean | True if file uses symbol '=' less than minimum times. |
Instance
{
"repo_name":"oboenikui/UnivCoopFeliCaReader",
"path":"app/src/main/java/com/oboenikui/campusfelica/ScannerActivity.kt",
"copies":"1",
"size":"5635",
"content":"....",
"license":"apache-2.0",
"hash":"e88cfd99346cbef640fc540aac3bf20b",
"line_mean":37.8620689655,
"line_max":199,
"alpha_frac":0.5724933452,
"ratio":5.0222816399,
"autogenerated":false,
"config_or_test":false,
"has_no_keywords":false,
"has_few_assignments":false
}
Languages
The dataset contains only Kotlin files.
{
"Kotlin": [".kt"]
}
Licenses
Each entry in the dataset contains the associated license. The following is a list of licenses involved and their occurrences.
{
"agpl-3.0":3209,
"apache-2.0":90782,
"artistic-2.0":130,
"bsd-2-clause":380,
"bsd-3-clause":3584,
"cc0-1.0":155,
"epl-1.0":792,
"gpl-2.0":4432,
"gpl-3.0":19816,
"isc":345,
"lgpl-2.1":118,
"lgpl-3.0":2689,
"mit":31470,
"mpl-2.0":1444,
"unlicense":654
}
Dataset Statistics
{
"Total size": "~207 MB",
"Number of files": 160000,
"Number of files under 500 bytes": 2957,
"Average file size in bytes": 5199,
}
Curation Process
See the unsliced curated dataset for mode details.
Data Splits
The dataset only contains a train split focused only on training data. For validation and unspliced versions, please check the following links:
- Clean Version Unsliced: https://huggingface.co/datasets/mvasiliniuc/iva-kotlin-codeint-clean
- Clean Version Valid: https://huggingface.co/datasets/mvasiliniuc/iva-kotlin-codeint-clean-valid
Considerations for Using the Data
The dataset comprises source code from various repositories, potentially containing harmful or biased code, along with sensitive information such as passwords or usernames.
- Downloads last month
- 44