code
stringlengths
5
1M
repo_name
stringlengths
5
109
path
stringlengths
6
208
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
5
1M
/** * The MIT License (MIT) * * Copyright (c) 2013 Lorand Szakacs * * 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 behavioral.parse import scala.collection.mutable import util.IO class Violation(val project: Project, val child: ClassInfo, val parent: ClassInfo, val childMethod: MethodInfo, val parentMethod: MethodInfo) { override def toString: String = { "[ %s ][ %s ===> %s ][ %s ]".format(project.pid, child.fqn, parent.fqn, childMethod.name) } } object Compare { private var allViolations: mutable.ListBuffer[Violation] = mutable.ListBuffer.empty[Violation] private var allOverridenMethods: mutable.ListBuffer[(MethodInfo, MethodInfo)] = mutable.ListBuffer.empty[(MethodInfo, MethodInfo)] def loadData(classes: String, effects: String) { Data.loadClasses(classes); Data.loadEffects(effects); } private def compare() { val seenBefore: mutable.Set[String] = mutable.HashSet.empty for (pair <- Data.sts) { val childClass = Data.getClassForName(pair._1) val parentClass = Data.getClassForName(pair._2) val project = parentClass.project for ( cM <- childClass.methods; pM <- parentClass.methods ) { if (cM.name == pM.name) { allOverridenMethods += ((cM, pM)) if (cM.isViolation(pM)) { val violation = new Violation(project, childClass, parentClass, cM, pM) allViolations += violation } } } //end of combinatorial for } } var totalNumberOfProjects: Int = 0; var nrOfProjectsContainingViolations: Int = 0; var totalNumberOfSubtypingPairs: Int = 0; var totalNrOfClassLevelViolations: Int = 0; var totalNrOfOverridenMethods: Int = 0; var totalNrOfMethodLevelViolations: Int = 0; private var violationsByProject: Map[String, mutable.ListBuffer[Violation]] = Map.empty[String, mutable.ListBuffer[Violation]] private var nrOfMethodLevelViolationsPerProject: Map[String, Int] = Map.empty[String, Int] private var nrOfClassLevelViolationsPerProject: Map[String, Int] = Map.empty[String, Int] def computeResults() { compare(); totalNumberOfProjects = Data.projects.size violationsByProject = allViolations.groupBy(v => v.project.pid) nrOfProjectsContainingViolations = violationsByProject.size totalNumberOfSubtypingPairs = Data.sts.size val violationsByPairsOfClasses = allViolations.groupBy(v => (v.child.fqn, v.parent.fqn)) totalNrOfClassLevelViolations = violationsByPairsOfClasses.size totalNrOfOverridenMethods = allOverridenMethods.size totalNrOfMethodLevelViolations = allViolations.size nrOfMethodLevelViolationsPerProject = violationsByProject map (v => (v._1 -> v._2.size)) val temp = violationsByProject map (v => (v._1 -> v._2.groupBy(f => (f.child.fqn, f.parent.fqn)))) nrOfClassLevelViolationsPerProject = temp map (v => (v._1 -> v._2.size)) } private lazy val generateReport: String = { var report = "" report += "total number of projects: " + totalNumberOfProjects + "\\n" report += "total number of projects with violations: " + nrOfProjectsContainingViolations + "\\n" report += "total number of class pairs: " + totalNumberOfSubtypingPairs + "\\n" report += "total number of class level violations: " + totalNrOfClassLevelViolations + "\\n" report += "total number of overriden methods: " + totalNrOfOverridenMethods + "\\n" report += "total number of method level violations: " + totalNrOfMethodLevelViolations + "\\n" report += "Class level violations per project: " + "\\n" report += nrOfClassLevelViolationsPerProject.map(p => " %s -> %s".format(p._1, p._2)).mkString("\\n") + "\\n"; report += "Method level violations per project: " + "\\n" report += nrOfMethodLevelViolationsPerProject.map(p => " %s -> %s".format(p._1, p._2)).mkString("\\n") + "\\n"; report += "All violations: \\n" val temp = violationsByProject map (pair => { val pid = pair._1 val violations = pair._2 val header = "%s\\n".format(pid) val violationString = violations.map(v => " %s".format(v.toString)).mkString("\\n") header + violationString + "\\n" }) report += temp.mkString("\\n") report += "\\n===============\\nProject Lengend\\n===============\\n" report += Data.projectLegend report } def report() { println(generateReport) } def report(filePath: String) { IO.writeToFile(generateReport.getBytes(), filePath); } }
lorandszakacs/fall2013-610-project-blackfyre
scala-data-aggregator/src/main/scala/behavioral/parse/Compare.scala
Scala
mit
5,514
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 hydrograph.engine.spark.datasource.utils import java.io.File import java.util.PriorityQueue import org.apache.hadoop.fs.FileSystem import scala.util.Try /** * The Object ShutdownHookManager. * * @author Bitwise * */ object ShutdownHookManager { val DEFAULT_SHUTDOWN_PRIORITY = 100 /** * The shutdown priority of the SparkContext instance. This is lower than the default * priority, so that by default hooks are run before the context is shut down. */ val SPARK_CONTEXT_SHUTDOWN_PRIORITY = 50 /** * The shutdown priority of temp directory must be lower than the SparkContext shutdown * priority. Otherwise cleaning the temp directories while Spark jobs are running can * throw undesirable errors at the time of shutdown. */ val TEMP_DIR_SHUTDOWN_PRIORITY = 25 private lazy val shutdownHooks = { val manager = new SparkShutdownHookManager() manager.install() manager } private val shutdownDeletePaths = new scala.collection.mutable.HashSet[String]() // Add a shutdown hook to delete the temp dirs when the JVM exits addShutdownHook(TEMP_DIR_SHUTDOWN_PRIORITY) { () => // logInfo("Shutdown hook called") // we need to materialize the paths to delete because deleteRecursively removes items from // shutdownDeletePaths as we are traversing through it. shutdownDeletePaths.toArray.foreach { dirPath => try { // logInfo("Deleting directory " + dirPath) Utils.deleteRecursively(new File(dirPath)) } catch { case e: Exception => //logError(s"Exception while deleting Spark temp dir: $dirPath", e) } } } // Register the path to be deleted via shutdown hook def registerShutdownDeleteDir(file: File) { val absolutePath = file.getAbsolutePath() shutdownDeletePaths.synchronized { shutdownDeletePaths += absolutePath } } // Remove the path to be deleted via shutdown hook def removeShutdownDeleteDir(file: File) { val absolutePath = file.getAbsolutePath() shutdownDeletePaths.synchronized { shutdownDeletePaths.remove(absolutePath) } } // Is the path already registered to be deleted via a shutdown hook ? def hasShutdownDeleteDir(file: File): Boolean = { val absolutePath = file.getAbsolutePath() shutdownDeletePaths.synchronized { shutdownDeletePaths.contains(absolutePath) } } // Note: if file is child of some registered path, while not equal to it, then return true; // else false. This is to ensure that two shutdown hooks do not try to delete each others // paths - resulting in IOException and incomplete cleanup. def hasRootAsShutdownDeleteDir(file: File): Boolean = { val absolutePath = file.getAbsolutePath() val retval = shutdownDeletePaths.synchronized { shutdownDeletePaths.exists { path => !absolutePath.equals(path) && absolutePath.startsWith(path) } } if (retval) { // logInfo("path = " + file + ", already present as root for deletion.") } retval } /** * Detect whether this thread might be executing a shutdown hook. Will always return true if * the current thread is a running a shutdown hook but may spuriously return true otherwise (e.g. * if System.exit was just called by a concurrent thread). * * Currently, this detects whether the JVM is shutting down by Runtime#addShutdownHook throwing * an IllegalStateException. */ def inShutdown(): Boolean = { try { val hook = new Thread { override def run() {} } // scalastyle:off runtimeaddshutdownhook Runtime.getRuntime.addShutdownHook(hook) // scalastyle:on runtimeaddshutdownhook Runtime.getRuntime.removeShutdownHook(hook) } catch { case ise: IllegalStateException => return true } false } /** * Adds a shutdown hook with default priority. * * @param hook The code to run during shutdown. * @return A handle that can be used to unregister the shutdown hook. */ def addShutdownHook(hook: () => Unit): AnyRef = { addShutdownHook(DEFAULT_SHUTDOWN_PRIORITY)(hook) } /** * Adds a shutdown hook with the given priority. Hooks with lower priority values run * first. * * @param hook The code to run during shutdown. * @return A handle that can be used to unregister the shutdown hook. */ def addShutdownHook(priority: Int)(hook: () => Unit): AnyRef = { shutdownHooks.add(priority, hook) } /** * Remove a previously installed shutdown hook. * * @param ref A handle returned by `addShutdownHook`. * @return Whether the hook was removed. */ def removeShutdownHook(ref: AnyRef): Boolean = { shutdownHooks.remove(ref) } } private class SparkShutdownHookManager { private val hooks = new PriorityQueue[SparkShutdownHook]() @volatile private var shuttingDown = false /** * Install a hook to run at shutdown and run all registered hooks in order. */ def install(): Unit = { val hookTask = new Runnable() { override def run(): Unit = runAll() } org.apache.hadoop.util.ShutdownHookManager.get().addShutdownHook( hookTask, FileSystem.SHUTDOWN_HOOK_PRIORITY + 30) } def runAll(): Unit = { shuttingDown = true var nextHook: SparkShutdownHook = null while ({ nextHook = hooks.synchronized { hooks.poll() }; nextHook != null }) { Try(Utils.logUncaughtExceptions(nextHook.run())) } } def add(priority: Int, hook: () => Unit): AnyRef = { hooks.synchronized { if (shuttingDown) { throw new IllegalStateException("Shutdown hooks cannot be modified during shutdown.") } val hookRef = new SparkShutdownHook(priority, hook) hooks.add(hookRef) hookRef } } def remove(ref: AnyRef): Boolean = { hooks.synchronized { hooks.remove(ref) } } } private class SparkShutdownHook(private val priority: Int, hook: () => Unit) extends Comparable[SparkShutdownHook] { override def compareTo(other: SparkShutdownHook): Int = { other.priority - priority } def run(): Unit = hook() }
capitalone/Hydrograph
hydrograph.engine/hydrograph.engine.spark/src/main/scala/hydrograph/engine/spark/datasource/utils/ShutdownHookManager.scala
Scala
apache-2.0
6,907
package gitbucket.core.service import gitbucket.core.model.{Collaborator, Repository, Account} import gitbucket.core.model.Profile._ import gitbucket.core.util.JGitUtil import profile.simple._ trait RepositoryService { self: AccountService => import RepositoryService._ /** * Creates a new repository. * * @param repositoryName the repository name * @param userName the user name of the repository owner * @param description the repository description * @param isPrivate the repository type (private is true, otherwise false) * @param originRepositoryName specify for the forked repository. (default is None) * @param originUserName specify for the forked repository. (default is None) */ def createRepository(repositoryName: String, userName: String, description: Option[String], isPrivate: Boolean, originRepositoryName: Option[String] = None, originUserName: Option[String] = None, parentRepositoryName: Option[String] = None, parentUserName: Option[String] = None) (implicit s: Session): Unit = { Repositories insert Repository( userName = userName, repositoryName = repositoryName, isPrivate = isPrivate, description = description, defaultBranch = "master", registeredDate = currentDate, updatedDate = currentDate, lastActivityDate = currentDate, originUserName = originUserName, originRepositoryName = originRepositoryName, parentUserName = parentUserName, parentRepositoryName = parentRepositoryName) IssueId insert (userName, repositoryName, 0) } def renameRepository(oldUserName: String, oldRepositoryName: String, newUserName: String, newRepositoryName: String) (implicit s: Session): Unit = { getAccountByUserName(newUserName).foreach { account => (Repositories filter { t => t.byRepository(oldUserName, oldRepositoryName) } firstOption).map { repository => Repositories insert repository.copy(userName = newUserName, repositoryName = newRepositoryName) val webHooks = WebHooks .filter(_.byRepository(oldUserName, oldRepositoryName)).list val milestones = Milestones .filter(_.byRepository(oldUserName, oldRepositoryName)).list val issueId = IssueId .filter(_.byRepository(oldUserName, oldRepositoryName)).list val issues = Issues .filter(_.byRepository(oldUserName, oldRepositoryName)).list val pullRequests = PullRequests .filter(_.byRepository(oldUserName, oldRepositoryName)).list val labels = Labels .filter(_.byRepository(oldUserName, oldRepositoryName)).list val issueComments = IssueComments .filter(_.byRepository(oldUserName, oldRepositoryName)).list val issueLabels = IssueLabels .filter(_.byRepository(oldUserName, oldRepositoryName)).list val commitComments = CommitComments.filter(_.byRepository(oldUserName, oldRepositoryName)).list val commitStatuses = CommitStatuses.filter(_.byRepository(oldUserName, oldRepositoryName)).list val collaborators = Collaborators .filter(_.byRepository(oldUserName, oldRepositoryName)).list Repositories.filter { t => (t.originUserName === oldUserName.bind) && (t.originRepositoryName === oldRepositoryName.bind) }.map { t => t.originUserName -> t.originRepositoryName }.update(newUserName, newRepositoryName) Repositories.filter { t => (t.parentUserName === oldUserName.bind) && (t.parentRepositoryName === oldRepositoryName.bind) }.map { t => t.originUserName -> t.originRepositoryName }.update(newUserName, newRepositoryName) // Updates activity fk before deleting repository because activity is sorted by activityId // and it can't be changed by deleting-and-inserting record. Activities.filter(_.byRepository(oldUserName, oldRepositoryName)).list.foreach { activity => Activities.filter(_.activityId === activity.activityId.bind) .map(x => (x.userName, x.repositoryName)).update(newUserName, newRepositoryName) } deleteRepository(oldUserName, oldRepositoryName) WebHooks .insertAll(webHooks .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) Milestones.insertAll(milestones .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) IssueId .insertAll(issueId .map(_.copy(_1 = newUserName, _2 = newRepositoryName)) :_*) val newMilestones = Milestones.filter(_.byRepository(newUserName, newRepositoryName)).list Issues.insertAll(issues.map { x => x.copy( userName = newUserName, repositoryName = newRepositoryName, milestoneId = x.milestoneId.map { id => newMilestones.find(_.title == milestones.find(_.milestoneId == id).get.title).get.milestoneId } )} :_*) PullRequests .insertAll(pullRequests .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) IssueComments .insertAll(issueComments .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) Labels .insertAll(labels .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) CommitComments.insertAll(commitComments.map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) CommitStatuses.insertAll(commitStatuses.map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) // Update source repository of pull requests PullRequests.filter { t => (t.requestUserName === oldUserName.bind) && (t.requestRepositoryName === oldRepositoryName.bind) }.map { t => t.requestUserName -> t.requestRepositoryName }.update(newUserName, newRepositoryName) // Convert labelId val oldLabelMap = labels.map(x => (x.labelId, x.labelName)).toMap val newLabelMap = Labels.filter(_.byRepository(newUserName, newRepositoryName)).map(x => (x.labelName, x.labelId)).list.toMap IssueLabels.insertAll(issueLabels.map(x => x.copy( labelId = newLabelMap(oldLabelMap(x.labelId)), userName = newUserName, repositoryName = newRepositoryName )) :_*) if(account.isGroupAccount){ Collaborators.insertAll(getGroupMembers(newUserName).map(m => Collaborator(newUserName, newRepositoryName, m.userName)) :_*) } else { Collaborators.insertAll(collaborators.map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) } // Update activity messages Activities.filter { t => (t.message like s"%:${oldUserName}/${oldRepositoryName}]%") || (t.message like s"%:${oldUserName}/${oldRepositoryName}#%") || (t.message like s"%:${oldUserName}/${oldRepositoryName}@%") }.map { t => t.activityId -> t.message }.list.foreach { case (activityId, message) => Activities.filter(_.activityId === activityId.bind).map(_.message).update( message .replace(s"[repo:${oldUserName}/${oldRepositoryName}]" ,s"[repo:${newUserName}/${newRepositoryName}]") .replace(s"[branch:${oldUserName}/${oldRepositoryName}#" ,s"[branch:${newUserName}/${newRepositoryName}#") .replace(s"[tag:${oldUserName}/${oldRepositoryName}#" ,s"[tag:${newUserName}/${newRepositoryName}#") .replace(s"[pullreq:${oldUserName}/${oldRepositoryName}#",s"[pullreq:${newUserName}/${newRepositoryName}#") .replace(s"[issue:${oldUserName}/${oldRepositoryName}#" ,s"[issue:${newUserName}/${newRepositoryName}#") .replace(s"[commit:${oldUserName}/${oldRepositoryName}@" ,s"[commit:${newUserName}/${newRepositoryName}@") ) } } } } def deleteRepository(userName: String, repositoryName: String)(implicit s: Session): Unit = { Activities .filter(_.byRepository(userName, repositoryName)).delete Collaborators .filter(_.byRepository(userName, repositoryName)).delete CommitComments.filter(_.byRepository(userName, repositoryName)).delete IssueLabels .filter(_.byRepository(userName, repositoryName)).delete Labels .filter(_.byRepository(userName, repositoryName)).delete IssueComments .filter(_.byRepository(userName, repositoryName)).delete PullRequests .filter(_.byRepository(userName, repositoryName)).delete Issues .filter(_.byRepository(userName, repositoryName)).delete IssueId .filter(_.byRepository(userName, repositoryName)).delete Milestones .filter(_.byRepository(userName, repositoryName)).delete WebHooks .filter(_.byRepository(userName, repositoryName)).delete Repositories .filter(_.byRepository(userName, repositoryName)).delete // Update ORIGIN_USER_NAME and ORIGIN_REPOSITORY_NAME Repositories .filter { x => (x.originUserName === userName.bind) && (x.originRepositoryName === repositoryName.bind) } .map { x => (x.userName, x.repositoryName) } .list .foreach { case (userName, repositoryName) => Repositories .filter(_.byRepository(userName, repositoryName)) .map(x => (x.originUserName?, x.originRepositoryName?)) .update(None, None) } // Update PARENT_USER_NAME and PARENT_REPOSITORY_NAME Repositories .filter { x => (x.parentUserName === userName.bind) && (x.parentRepositoryName === repositoryName.bind) } .map { x => (x.userName, x.repositoryName) } .list .foreach { case (userName, repositoryName) => Repositories .filter(_.byRepository(userName, repositoryName)) .map(x => (x.parentUserName?, x.parentRepositoryName?)) .update(None, None) } } /** * Returns the repository names of the specified user. * * @param userName the user name of repository owner * @return the list of repository names */ def getRepositoryNamesOfUser(userName: String)(implicit s: Session): List[String] = Repositories filter(_.userName === userName.bind) map (_.repositoryName) list /** * Returns the specified repository information. * * @param userName the user name of the repository owner * @param repositoryName the repository name * @param baseUrl the base url of this application * @return the repository information */ def getRepository(userName: String, repositoryName: String, baseUrl: String)(implicit s: Session): Option[RepositoryInfo] = { (Repositories filter { t => t.byRepository(userName, repositoryName) } firstOption) map { repository => // for getting issue count and pull request count val issues = Issues.filter { t => t.byRepository(repository.userName, repository.repositoryName) && (t.closed === false.bind) }.map(_.pullRequest).list new RepositoryInfo( JGitUtil.getRepositoryInfo(repository.userName, repository.repositoryName, baseUrl), repository, issues.count(_ == false), issues.count(_ == true), getForkedCount( repository.originUserName.getOrElse(repository.userName), repository.originRepositoryName.getOrElse(repository.repositoryName) ), getRepositoryManagers(repository.userName)) } } /** * Returns the repositories without private repository that user does not have access right. * Include public repository, private own repository and private but collaborator repository. * * @param userName the user name of collaborator * @return the repository infomation list */ def getAllRepositories(userName: String)(implicit s: Session): List[(String, String)] = { Repositories.filter { t1 => (t1.isPrivate === false.bind) || (t1.userName === userName.bind) || (Collaborators.filter { t2 => t2.byRepository(t1.userName, t1.repositoryName) && (t2.collaboratorName === userName.bind)} exists) }.sortBy(_.lastActivityDate desc).map{ t => (t.userName, t.repositoryName) }.list } def getUserRepositories(userName: String, baseUrl: String, withoutPhysicalInfo: Boolean = false) (implicit s: Session): List[RepositoryInfo] = { Repositories.filter { t1 => (t1.userName === userName.bind) || (Collaborators.filter { t2 => t2.byRepository(t1.userName, t1.repositoryName) && (t2.collaboratorName === userName.bind)} exists) }.sortBy(_.lastActivityDate desc).list.map{ repository => new RepositoryInfo( if(withoutPhysicalInfo){ new JGitUtil.RepositoryInfo(repository.userName, repository.repositoryName, baseUrl) } else { JGitUtil.getRepositoryInfo(repository.userName, repository.repositoryName, baseUrl) }, repository, getForkedCount( repository.originUserName.getOrElse(repository.userName), repository.originRepositoryName.getOrElse(repository.repositoryName) ), getRepositoryManagers(repository.userName)) } } /** * Returns the list of visible repositories for the specified user. * If repositoryUserName is given then filters results by repository owner. * * @param loginAccount the logged in account * @param baseUrl the base url of this application * @param repositoryUserName the repository owner (if None then returns all repositories which are visible for logged in user) * @param withoutPhysicalInfo if true then the result does not include physical repository information such as commit count, * branches and tags * @return the repository information which is sorted in descending order of lastActivityDate. */ def getVisibleRepositories(loginAccount: Option[Account], baseUrl: String, repositoryUserName: Option[String] = None, withoutPhysicalInfo: Boolean = false) (implicit s: Session): List[RepositoryInfo] = { (loginAccount match { // for Administrators case Some(x) if(x.isAdmin) => Repositories // for Normal Users case Some(x) if(!x.isAdmin) => Repositories filter { t => (t.isPrivate === false.bind) || (t.userName === x.userName) || (Collaborators.filter { t2 => t2.byRepository(t.userName, t.repositoryName) && (t2.collaboratorName === x.userName.bind)} exists) } // for Guests case None => Repositories filter(_.isPrivate === false.bind) }).filter { t => repositoryUserName.map { userName => t.userName === userName.bind } getOrElse LiteralColumn(true) }.sortBy(_.lastActivityDate desc).list.map{ repository => new RepositoryInfo( if(withoutPhysicalInfo){ new JGitUtil.RepositoryInfo(repository.userName, repository.repositoryName, baseUrl) } else { JGitUtil.getRepositoryInfo(repository.userName, repository.repositoryName, baseUrl) }, repository, getForkedCount( repository.originUserName.getOrElse(repository.userName), repository.originRepositoryName.getOrElse(repository.repositoryName) ), getRepositoryManagers(repository.userName)) } } private def getRepositoryManagers(userName: String)(implicit s: Session): Seq[String] = if(getAccountByUserName(userName).exists(_.isGroupAccount)){ getGroupMembers(userName).collect { case x if(x.isManager) => x.userName } } else { Seq(userName) } /** * Updates the last activity date of the repository. */ def updateLastActivityDate(userName: String, repositoryName: String)(implicit s: Session): Unit = Repositories.filter(_.byRepository(userName, repositoryName)).map(_.lastActivityDate).update(currentDate) /** * Save repository options. */ def saveRepositoryOptions(userName: String, repositoryName: String, description: Option[String], defaultBranch: String, isPrivate: Boolean)(implicit s: Session): Unit = Repositories.filter(_.byRepository(userName, repositoryName)) .map { r => (r.description.?, r.defaultBranch, r.isPrivate, r.updatedDate) } .update (description, defaultBranch, isPrivate, currentDate) /** * Add collaborator to the repository. * * @param userName the user name of the repository owner * @param repositoryName the repository name * @param collaboratorName the collaborator name */ def addCollaborator(userName: String, repositoryName: String, collaboratorName: String)(implicit s: Session): Unit = Collaborators insert Collaborator(userName, repositoryName, collaboratorName) /** * Remove collaborator from the repository. * * @param userName the user name of the repository owner * @param repositoryName the repository name * @param collaboratorName the collaborator name */ def removeCollaborator(userName: String, repositoryName: String, collaboratorName: String)(implicit s: Session): Unit = Collaborators.filter(_.byPrimaryKey(userName, repositoryName, collaboratorName)).delete /** * Remove all collaborators from the repository. * * @param userName the user name of the repository owner * @param repositoryName the repository name */ def removeCollaborators(userName: String, repositoryName: String)(implicit s: Session): Unit = Collaborators.filter(_.byRepository(userName, repositoryName)).delete /** * Returns the list of collaborators name which is sorted with ascending order. * * @param userName the user name of the repository owner * @param repositoryName the repository name * @return the list of collaborators name */ def getCollaborators(userName: String, repositoryName: String)(implicit s: Session): List[String] = Collaborators.filter(_.byRepository(userName, repositoryName)).sortBy(_.collaboratorName).map(_.collaboratorName).list def hasWritePermission(owner: String, repository: String, loginAccount: Option[Account])(implicit s: Session): Boolean = { loginAccount match { case Some(a) if(a.isAdmin) => true case Some(a) if(a.userName == owner) => true case Some(a) if(getCollaborators(owner, repository).contains(a.userName)) => true case _ => false } } private def getForkedCount(userName: String, repositoryName: String)(implicit s: Session): Int = Query(Repositories.filter { t => (t.originUserName === userName.bind) && (t.originRepositoryName === repositoryName.bind) }.length).first def getForkedRepositories(userName: String, repositoryName: String)(implicit s: Session): List[(String, String)] = Repositories.filter { t => (t.originUserName === userName.bind) && (t.originRepositoryName === repositoryName.bind) } .sortBy(_.userName asc).map(t => t.userName -> t.repositoryName).list } object RepositoryService { case class RepositoryInfo(owner: String, name: String, httpUrl: String, repository: Repository, issueCount: Int, pullCount: Int, commitCount: Int, forkedCount: Int, branchList: Seq[String], tags: Seq[JGitUtil.TagInfo], managers: Seq[String]){ lazy val host = """^https?://(.+?)(:\d+)?/""".r.findFirstMatchIn(httpUrl).get.group(1) def sshUrl(port: Int, userName: String) = s"ssh://${userName}@${host}:${port}/${owner}/${name}.git" def sshOpenRepoUrl(platform: String, port: Int, userName: String) = openRepoUrl(platform, sshUrl(port, userName)) def httpOpenRepoUrl(platform: String) = openRepoUrl(platform, httpUrl) def openRepoUrl(platform: String, openUrl: String) = s"github-${platform}://openRepo/${openUrl}" /** * Creates instance with issue count and pull request count. */ def this(repo: JGitUtil.RepositoryInfo, model: Repository, issueCount: Int, pullCount: Int, forkedCount: Int, managers: Seq[String]) = this(repo.owner, repo.name, repo.url, model, issueCount, pullCount, repo.commitCount, forkedCount, repo.branchList, repo.tags, managers) /** * Creates instance without issue count and pull request count. */ def this(repo: JGitUtil.RepositoryInfo, model: Repository, forkedCount: Int, managers: Seq[String]) = this(repo.owner, repo.name, repo.url, model, 0, 0, repo.commitCount, forkedCount, repo.branchList, repo.tags, managers) } case class RepositoryTreeNode(owner: String, name: String, children: List[RepositoryTreeNode]) }
uli-heller/gitbucket
src/main/scala/gitbucket/core/service/RepositoryService.scala
Scala
apache-2.0
20,655
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.execution import scala.collection.immutable.IndexedSeq import org.apache.hadoop.fs.{FileSystem, Path} import org.apache.spark.internal.Logging import org.apache.spark.internal.config.ConfigEntry import org.apache.spark.sql.{Dataset, SparkSession} import org.apache.spark.sql.catalyst.expressions.{Attribute, SubqueryExpression} import org.apache.spark.sql.catalyst.optimizer.EliminateResolvedHint import org.apache.spark.sql.catalyst.plans.logical.{IgnoreCachedData, LogicalPlan, ResolvedHint} import org.apache.spark.sql.execution.adaptive.AdaptiveSparkPlanHelper import org.apache.spark.sql.execution.columnar.InMemoryRelation import org.apache.spark.sql.execution.command.CommandUtils import org.apache.spark.sql.execution.datasources.{FileIndex, HadoopFsRelation, LogicalRelation} import org.apache.spark.sql.execution.datasources.v2.{DataSourceV2Relation, FileTable} import org.apache.spark.sql.internal.SQLConf import org.apache.spark.storage.StorageLevel import org.apache.spark.storage.StorageLevel.MEMORY_AND_DISK /** Holds a cached logical plan and its data */ case class CachedData(plan: LogicalPlan, cachedRepresentation: InMemoryRelation) /** * Provides support in a SQLContext for caching query results and automatically using these cached * results when subsequent queries are executed. Data is cached using byte buffers stored in an * InMemoryRelation. This relation is automatically substituted query plans that return the * `sameResult` as the originally cached query. * * Internal to Spark SQL. */ class CacheManager extends Logging with AdaptiveSparkPlanHelper { /** * Maintains the list of cached plans as an immutable sequence. Any updates to the list * should be protected in a "this.synchronized" block which includes the reading of the * existing value and the update of the cachedData var. */ @transient @volatile private var cachedData = IndexedSeq[CachedData]() /** * Configurations needs to be turned off, to avoid regression for cached query, so that the * outputPartitioning of the underlying cached query plan can be leveraged later. * Configurations include: * 1. AQE * 2. Automatic bucketed table scan */ private val forceDisableConfigs: Seq[ConfigEntry[Boolean]] = Seq( SQLConf.ADAPTIVE_EXECUTION_ENABLED, SQLConf.AUTO_BUCKETED_SCAN_ENABLED) /** Clears all cached tables. */ def clearCache(): Unit = this.synchronized { cachedData.foreach(_.cachedRepresentation.cacheBuilder.clearCache()) cachedData = IndexedSeq[CachedData]() } /** Checks if the cache is empty. */ def isEmpty: Boolean = { cachedData.isEmpty } /** * Caches the data produced by the logical representation of the given [[Dataset]]. * Unlike `RDD.cache()`, the default storage level is set to be `MEMORY_AND_DISK` because * recomputing the in-memory columnar representation of the underlying table is expensive. */ def cacheQuery( query: Dataset[_], tableName: Option[String] = None, storageLevel: StorageLevel = MEMORY_AND_DISK): Unit = { cacheQuery(query.sparkSession, query.logicalPlan, tableName, storageLevel) } /** * Caches the data produced by the given [[LogicalPlan]]. * Unlike `RDD.cache()`, the default storage level is set to be `MEMORY_AND_DISK` because * recomputing the in-memory columnar representation of the underlying table is expensive. */ def cacheQuery( spark: SparkSession, planToCache: LogicalPlan, tableName: Option[String]): Unit = { cacheQuery(spark, planToCache, tableName, MEMORY_AND_DISK) } /** * Caches the data produced by the given [[LogicalPlan]]. */ def cacheQuery( spark: SparkSession, planToCache: LogicalPlan, tableName: Option[String], storageLevel: StorageLevel): Unit = { if (lookupCachedData(planToCache).nonEmpty) { logWarning("Asked to cache already cached data.") } else { val sessionWithConfigsOff = SparkSession.getOrCloneSessionWithConfigsOff( spark, forceDisableConfigs) val inMemoryRelation = sessionWithConfigsOff.withActive { val qe = sessionWithConfigsOff.sessionState.executePlan(planToCache) InMemoryRelation( storageLevel, qe, tableName) } this.synchronized { if (lookupCachedData(planToCache).nonEmpty) { logWarning("Data has already been cached.") } else { cachedData = CachedData(planToCache, inMemoryRelation) +: cachedData } } } } /** * Un-cache the given plan or all the cache entries that refer to the given plan. * @param query The [[Dataset]] to be un-cached. * @param cascade If true, un-cache all the cache entries that refer to the given * [[Dataset]]; otherwise un-cache the given [[Dataset]] only. */ def uncacheQuery( query: Dataset[_], cascade: Boolean): Unit = { uncacheQuery(query.sparkSession, query.logicalPlan, cascade) } /** * Un-cache the given plan or all the cache entries that refer to the given plan. * @param spark The Spark session. * @param plan The plan to be un-cached. * @param cascade If true, un-cache all the cache entries that refer to the given * plan; otherwise un-cache the given plan only. * @param blocking Whether to block until all blocks are deleted. */ def uncacheQuery( spark: SparkSession, plan: LogicalPlan, cascade: Boolean, blocking: Boolean = false): Unit = { val shouldRemove: LogicalPlan => Boolean = if (cascade) { _.find(_.sameResult(plan)).isDefined } else { _.sameResult(plan) } val plansToUncache = cachedData.filter(cd => shouldRemove(cd.plan)) this.synchronized { cachedData = cachedData.filterNot(cd => plansToUncache.exists(_ eq cd)) } plansToUncache.foreach { _.cachedRepresentation.cacheBuilder.clearCache(blocking) } // Re-compile dependent cached queries after removing the cached query. if (!cascade) { recacheByCondition(spark, cd => { // If the cache buffer has already been loaded, we don't need to recompile the cached plan, // as it does not rely on the plan that has been uncached anymore, it will just produce // data from the cache buffer. // Note that the `CachedRDDBuilder.isCachedColumnBuffersLoaded` call is a non-locking // status test and may not return the most accurate cache buffer state. So the worse case // scenario can be: // 1) The buffer has been loaded, but `isCachedColumnBuffersLoaded` returns false, then we // will clear the buffer and re-compiled the plan. It is inefficient but doesn't affect // correctness. // 2) The buffer has been cleared, but `isCachedColumnBuffersLoaded` returns true, then we // will keep it as it is. It means the physical plan has been re-compiled already in the // other thread. val cacheAlreadyLoaded = cd.cachedRepresentation.cacheBuilder.isCachedColumnBuffersLoaded cd.plan.find(_.sameResult(plan)).isDefined && !cacheAlreadyLoaded }) } } // Analyzes column statistics in the given cache data private[sql] def analyzeColumnCacheQuery( sparkSession: SparkSession, cachedData: CachedData, column: Seq[Attribute]): Unit = { val relation = cachedData.cachedRepresentation val (rowCount, newColStats) = CommandUtils.computeColumnStats(sparkSession, relation, column) relation.updateStats(rowCount, newColStats) } /** * Tries to re-cache all the cache entries that refer to the given plan. */ def recacheByPlan(spark: SparkSession, plan: LogicalPlan): Unit = { recacheByCondition(spark, _.plan.find(_.sameResult(plan)).isDefined) } /** * Re-caches all the cache entries that satisfies the given `condition`. */ private def recacheByCondition( spark: SparkSession, condition: CachedData => Boolean): Unit = { val needToRecache = cachedData.filter(condition) this.synchronized { // Remove the cache entry before creating a new ones. cachedData = cachedData.filterNot(cd => needToRecache.exists(_ eq cd)) } needToRecache.foreach { cd => cd.cachedRepresentation.cacheBuilder.clearCache() val sessionWithConfigsOff = SparkSession.getOrCloneSessionWithConfigsOff( spark, forceDisableConfigs) val newCache = sessionWithConfigsOff.withActive { val qe = sessionWithConfigsOff.sessionState.executePlan(cd.plan) InMemoryRelation(cd.cachedRepresentation.cacheBuilder, qe) } val recomputedPlan = cd.copy(cachedRepresentation = newCache) this.synchronized { if (lookupCachedData(recomputedPlan.plan).nonEmpty) { logWarning("While recaching, data was already added to cache.") } else { cachedData = recomputedPlan +: cachedData } } } } /** Optionally returns cached data for the given [[Dataset]] */ def lookupCachedData(query: Dataset[_]): Option[CachedData] = { lookupCachedData(query.logicalPlan) } /** Optionally returns cached data for the given [[LogicalPlan]]. */ def lookupCachedData(plan: LogicalPlan): Option[CachedData] = { cachedData.find(cd => plan.sameResult(cd.plan)) } /** Replaces segments of the given logical plan with cached versions where possible. */ def useCachedData(plan: LogicalPlan): LogicalPlan = { val newPlan = plan transformDown { case command: IgnoreCachedData => command case currentFragment => lookupCachedData(currentFragment).map { cached => // After cache lookup, we should still keep the hints from the input plan. val hints = EliminateResolvedHint.extractHintsFromPlan(currentFragment)._2 val cachedPlan = cached.cachedRepresentation.withOutput(currentFragment.output) // The returned hint list is in top-down order, we should create the hint nodes from // right to left. hints.foldRight[LogicalPlan](cachedPlan) { case (hint, p) => ResolvedHint(p, hint) } }.getOrElse(currentFragment) } newPlan transformAllExpressions { case s: SubqueryExpression => s.withNewPlan(useCachedData(s.plan)) } } /** * Tries to re-cache all the cache entries that contain `resourcePath` in one or more * `HadoopFsRelation` node(s) as part of its logical plan. */ def recacheByPath(spark: SparkSession, resourcePath: String): Unit = { val path = new Path(resourcePath) val fs = path.getFileSystem(spark.sessionState.newHadoopConf()) recacheByPath(spark, path, fs) } /** * Tries to re-cache all the cache entries that contain `resourcePath` in one or more * `HadoopFsRelation` node(s) as part of its logical plan. */ def recacheByPath(spark: SparkSession, resourcePath: Path, fs: FileSystem): Unit = { val qualifiedPath = fs.makeQualified(resourcePath) recacheByCondition(spark, _.plan.find(lookupAndRefresh(_, fs, qualifiedPath)).isDefined) } /** * Traverses a given `plan` and searches for the occurrences of `qualifiedPath` in the * [[org.apache.spark.sql.execution.datasources.FileIndex]] of any [[HadoopFsRelation]] nodes * in the plan. If found, we refresh the metadata and return true. Otherwise, this method returns * false. */ private def lookupAndRefresh(plan: LogicalPlan, fs: FileSystem, qualifiedPath: Path): Boolean = { plan match { case lr: LogicalRelation => lr.relation match { case hr: HadoopFsRelation => refreshFileIndexIfNecessary(hr.location, fs, qualifiedPath) case _ => false } case DataSourceV2Relation(fileTable: FileTable, _, _, _, _) => refreshFileIndexIfNecessary(fileTable.fileIndex, fs, qualifiedPath) case _ => false } } /** * Refresh the given [[FileIndex]] if any of its root paths starts with `qualifiedPath`. * @return whether the [[FileIndex]] is refreshed. */ private def refreshFileIndexIfNecessary( fileIndex: FileIndex, fs: FileSystem, qualifiedPath: Path): Boolean = { val prefixToInvalidate = qualifiedPath.toString val needToRefresh = fileIndex.rootPaths .map(_.makeQualified(fs.getUri, fs.getWorkingDirectory).toString) .exists(_.startsWith(prefixToInvalidate)) if (needToRefresh) fileIndex.refresh() needToRefresh } }
witgo/spark
sql/core/src/main/scala/org/apache/spark/sql/execution/CacheManager.scala
Scala
apache-2.0
13,379
object Test { def f1c(x: Int) = { class T1 { def f2 = { trait T2 { def f3: Int = { def f4 = 10 def f5 = f4 def f7 = this.f3 f5 } def f3a = f3 } class C2 extends T2 class C3 extends T1 new C2().f3a + new C3().f6 } def f6 = 10 } } }
som-snytt/dotty
tests/init/pos/inner28.scala
Scala
apache-2.0
378
package com.sksamuel.elastic4s.script import com.sksamuel.elastic4s.FieldsMapper import org.elasticsearch.script.Script import org.elasticsearch.script.ScriptService.ScriptType import scala.collection.JavaConverters._ import scala.language.implicitConversions case class ScriptDefinition(script: String, lang: Option[String] = None, scriptType: ScriptType = ScriptType.INLINE, params: Map[String, Any] = Map.empty) { def lang(lang: String): ScriptDefinition = copy(lang = Option(lang)) def param(name: String, value: Any): ScriptDefinition = copy(params = params + (name -> value)) def params(first: (String, Any), rest: (String, AnyRef)*): ScriptDefinition = params(first +: rest) def params(seq: Seq[(String, Any)]): ScriptDefinition = params(seq.toMap) def params(map: Map[String, Any]): ScriptDefinition = copy(params = params ++ map) def scriptType(scriptType: ScriptType): ScriptDefinition = copy(scriptType = scriptType) @deprecated("use build", "5.0.0") def toJavaAPI: Script = build def build: Script = { if (params.isEmpty) { new Script(script, scriptType, lang.orNull, null) } else { val mappedParams = FieldsMapper.mapper(params).asJava new Script(script, scriptType, lang.orNull, mappedParams) } } } object ScriptDefinition { implicit def string2Script(script: String): ScriptDefinition = ScriptDefinition(script) }
ulric260/elastic4s
elastic4s-core/src/main/scala/com/sksamuel/elastic4s/script/ScriptDefinition.scala
Scala
apache-2.0
1,473
package de.zalando.model import de.zalando.apifirst.Application._ import de.zalando.apifirst.Domain._ import de.zalando.apifirst.ParameterPlace import de.zalando.apifirst.naming._ import de.zalando.apifirst.Hypermedia._ import de.zalando.apifirst.Http._ import de.zalando.apifirst.Security import java.net.URL import Security._ //noinspection ScalaStyle object instagram_api_yaml extends WithModel { def types = Map[Reference, Type]( Reference("⌿definitions⌿User") β†’ TypeDef(Reference("⌿definitions⌿User"), Seq( Field(Reference("⌿definitions⌿User⌿website"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿username"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿bio"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿counts"), Opt(TypeDef(Reference("⌿definitions⌿User⌿counts"), Seq( Field(Reference("⌿definitions⌿User⌿counts⌿media"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿counts⌿follows"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿counts⌿follwed_by"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 7"), List())), Reference("⌿definitions⌿Image") β†’ TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), Reference("⌿definitions⌿Tag") β†’ TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿definitions⌿Comment") β†’ TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), Reference("⌿definitions⌿Media") β†’ TypeDef(Reference("⌿definitions⌿Media"), Seq( Field(Reference("⌿definitions⌿Media⌿location"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿created_time"), Opt(BInt(TypeMeta(Some("Epoc time (ms)"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:"), Opt(TypeDef(Reference("⌿definitions⌿Media⌿comments:"), Seq( Field(Reference("⌿definitions⌿Media⌿comments:⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:⌿data"), Opt(Arr(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()), "csv"), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿tags"), Opt(Arr(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()), "csv"), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿users_in_photo"), Opt(Arr(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()), "csv"), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿filter"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes"), Opt(TypeDef(Reference("⌿definitions⌿Media⌿likes"), Seq( Field(Reference("⌿definitions⌿Media⌿likes⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes⌿data"), Opt(Arr(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()), "csv"), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos"), Opt(TypeDef(Reference("⌿definitions⌿Media⌿videos"), Seq( Field(Reference("⌿definitions⌿Media⌿videos⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images"), Opt(TypeDef(Reference("⌿definitions⌿Media⌿images"), Seq( Field(Reference("⌿definitions⌿Media⌿images⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images⌿thumbnail"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿user"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 12"), List())), Reference("⌿definitions⌿Like") β†’ TypeDef(Reference("⌿definitions⌿Like"), Seq( Field(Reference("⌿definitions⌿Like⌿first_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Like⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Like⌿last_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Like⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Like⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 5"), List())), Reference("⌿definitions⌿Location") β†’ TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), Reference("⌿definitions⌿MiniProfile") β†’ TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), Reference("⌿parameters⌿user-id-param⌿user-id") β†’ BDcml(TypeMeta(None, List())), Reference("⌿parameters⌿tag-name⌿tag-name") β†’ Str(None, TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿count") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/locations/{location-id}⌿⌿location-id") β†’ BInt(TypeMeta(None, List())), Reference("⌿paths⌿/tags/{tag-name}/media/recent⌿⌿tag-name") β†’ Str(None, TypeMeta(None, List())), Reference("⌿paths⌿/locations/search⌿get⌿lng") β†’ Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/media/{media-id}⌿⌿media-id") β†’ BInt(TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿max_id") β†’ Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/media/recent⌿⌿user-id") β†’ BDcml(TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/relationship⌿post⌿action") β†’ Opt( EnumTrait(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), TypeMeta(Some("Enum type : 5"), List()), Set( EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "follow", TypeMeta(Some("follow"), List())), EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "unblock", TypeMeta(Some("unblock"), List())), EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "approve", TypeMeta(Some("approve"), List())), EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "unfollow", TypeMeta(Some("unfollow"), List())), EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "block", TypeMeta(Some("block"), List())) )), TypeMeta(None, List())), Reference("⌿paths⌿/media/search⌿get⌿MAX_TIMESTAMP") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/followed-by⌿⌿user-id") β†’ BDcml(TypeMeta(None, List())), Reference("⌿paths⌿/media/search⌿get⌿LAT") β†’ Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/locations/search⌿get⌿distance") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/locations/search⌿get⌿facebook_places_id") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/self/feed⌿get⌿max_id") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/media/search⌿get⌿DISTANCE") β†’ BInt(TypeMeta(None, List("""max(BigInt("5000"), false)"""))), Reference("⌿paths⌿/tags/{tag-name}⌿⌿tag-name") β†’ Str(None, TypeMeta(None, List())), Reference("⌿paths⌿/tags/search⌿get⌿q") β†’ Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿min_id") β†’ Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/locations/search⌿get⌿lat") β†’ Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿min_id") β†’ Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿count") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}⌿⌿user-id") β†’ BDcml(TypeMeta(None, List())), Reference("⌿paths⌿/users/self/feed⌿get⌿min_id") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/locations/{location-id}/media/recent⌿⌿location-id") β†’ BInt(TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿min_timestamp") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/media/search⌿get⌿MIN_TIMESTAMP") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/relationship⌿⌿user-id") β†’ BDcml(TypeMeta(None, List())), Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿TEXT") β†’ Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿max_id") β†’ Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/media/search⌿get⌿LNG") β†’ Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿min_timestamp") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/self/media/liked⌿get⌿max_like_id") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/media/{media-id}/comments⌿⌿media-id") β†’ BInt(TypeMeta(None, List())), Reference("⌿paths⌿/locations/search⌿get⌿foursquare_id") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/search⌿get⌿count") β†’ Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/self/media/liked⌿get⌿count") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/media/{media-id}/likes⌿⌿media-id") β†’ BInt(TypeMeta(None, List())), Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿min_id") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/locations/search⌿get⌿foursquare_v2_id") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/follows⌿⌿user-id") β†’ BDcml(TypeMeta(None, List())), Reference("⌿paths⌿/users/self/feed⌿get⌿count") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/media/{shortcode}⌿⌿shortcode") β†’ Str(None, TypeMeta(None, List())), Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿max_timestamp") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿max_timestamp") β†’ Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿⌿geo-id") β†’ BInt(TypeMeta(None, List())), Reference("⌿paths⌿/users/search⌿get⌿q") β†’ Str(None, TypeMeta(None, List())), Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Media"), Seq( Field(Reference("⌿definitions⌿Media⌿location"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿created_time"), Opt(BInt(TypeMeta(Some("Epoc time (ms)"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:"), Opt(TypeDef(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿comments:"), Seq( Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿comments:⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿comments:⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿tags"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿users_in_photo"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿filter"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes"), Opt(TypeDef(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿likes"), Seq( Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿likes⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿likes⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos"), Opt(TypeDef(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿videos"), Seq( Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿videos⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿videos⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images"), Opt(TypeDef(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿images"), Seq( Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿images⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿images⌿thumbnail"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200⌿data⌿images⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿user"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 12"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Media"), Seq( Field(Reference("⌿definitions⌿Media⌿location"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿created_time"), Opt(BInt(TypeMeta(Some("Epoc time (ms)"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:"), Opt(TypeDef(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿comments:"), Seq( Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿comments:⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿comments:⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿tags"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿users_in_photo"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿filter"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes"), Opt(TypeDef(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿likes"), Seq( Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿likes⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿likes⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos"), Opt(TypeDef(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿videos"), Seq( Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿videos⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿videos⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images"), Opt(TypeDef(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿images"), Seq( Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿images⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿images⌿thumbnail"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200⌿data⌿images⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿user"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 12"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/media/{media-id}/comments⌿delete⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/media/{media-id}/comments⌿delete⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/comments⌿delete⌿responses⌿200⌿meta"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}/comments⌿delete⌿responses⌿200⌿meta"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/comments⌿delete⌿responses⌿200⌿meta⌿code"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}/comments⌿delete⌿responses⌿200⌿data"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿paths⌿/users/{user-id}/follows⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/users/{user-id}/follows⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/users/{user-id}/follows⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/tags/{tag-name}/media/recent⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/tags/{tag-name}/media/recent⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/tags/{tag-name}/media/recent⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/users/self/requested-by⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/users/self/requested-by⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/users/self/requested-by⌿get⌿responses⌿200⌿meta"), Opt(TypeDef(Reference("⌿paths⌿/users/self/requested-by⌿get⌿responses⌿200⌿meta"), Seq( Field(Reference("⌿paths⌿/users/self/requested-by⌿get⌿responses⌿200⌿meta⌿code"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/requested-by⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿paths⌿/media/{media-id}/likes⌿post⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/media/{media-id}/likes⌿post⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/likes⌿post⌿responses⌿200⌿meta"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}/likes⌿post⌿responses⌿200⌿meta"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/likes⌿post⌿responses⌿200⌿meta⌿code"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}/likes⌿post⌿responses⌿200⌿data"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿paths⌿/users/{user-id}/followed-by⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/users/{user-id}/followed-by⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/users/{user-id}/followed-by⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/locations/{location-id}⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/locations/{location-id}⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/locations/{location-id}⌿get⌿responses⌿200⌿data"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Media"), Seq( Field(Reference("⌿definitions⌿Media⌿location"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿created_time"), Opt(BInt(TypeMeta(Some("Epoc time (ms)"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:"), Opt(TypeDef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿comments:"), Seq( Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿comments:⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿comments:⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿tags"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿users_in_photo"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿filter"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes"), Opt(TypeDef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿likes"), Seq( Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿likes⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿likes⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos"), Opt(TypeDef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿videos"), Seq( Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿videos⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿videos⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images"), Opt(TypeDef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿images"), Seq( Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿images⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿images⌿thumbnail"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200⌿data⌿images⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿user"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 12"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Media"), Seq( Field(Reference("⌿definitions⌿Media⌿location"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿created_time"), Opt(BInt(TypeMeta(Some("Epoc time (ms)"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:"), Opt(TypeDef(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿comments:"), Seq( Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿comments:⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿comments:⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿tags"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿users_in_photo"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿filter"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes"), Opt(TypeDef(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿likes"), Seq( Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿likes⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿likes⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos"), Opt(TypeDef(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿videos"), Seq( Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿videos⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿videos⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images"), Opt(TypeDef(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿images"), Seq( Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿images⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿images⌿thumbnail"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200⌿data⌿images⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿user"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 12"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Media"), Seq( Field(Reference("⌿definitions⌿Media⌿location"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿created_time"), Opt(BInt(TypeMeta(Some("Epoc time (ms)"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:"), Opt(TypeDef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿comments:"), Seq( Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿comments:⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿comments:⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿tags"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿users_in_photo"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿filter"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes"), Opt(TypeDef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿likes"), Seq( Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿likes⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿likes⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos"), Opt(TypeDef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿videos"), Seq( Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿videos⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿videos⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images"), Opt(TypeDef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿images"), Seq( Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿images⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿images⌿thumbnail"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200⌿data⌿images⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿user"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 12"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/tags/{tag-name}⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿paths⌿/media/{media-id}/likes⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/media/{media-id}/likes⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/likes⌿get⌿responses⌿200⌿meta"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}/likes⌿get⌿responses⌿200⌿meta"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/likes⌿get⌿responses⌿200⌿meta⌿code"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}/likes⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Like"), Seq( Field(Reference("⌿definitions⌿Like⌿first_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Like⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Like⌿last_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Like⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Like⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 5"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿paths⌿/media/search⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data"), Opt(ArrResult( AllOf(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿data"), TypeMeta(Some("Schemas: 2"), List()), Seq( TypeDef(Reference("⌿definitions⌿Media"), Seq( Field(Reference("⌿definitions⌿Media⌿location"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿created_time"), Opt(BInt(TypeMeta(Some("Epoc time (ms)"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:"), Opt(TypeDef(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿comments:"), Seq( Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿comments:⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿comments:⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿tags"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿users_in_photo"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿filter"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes"), Opt(TypeDef(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿likes"), Seq( Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿likes⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿likes⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos"), Opt(TypeDef(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿videos"), Seq( Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿videos⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿videos⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images"), Opt(TypeDef(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿images"), Seq( Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿images⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿images⌿thumbnail"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿images⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿user"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 12"), List())), TypeDef(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data"), Seq( Field(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200⌿data⌿distance"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List()))) , None), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/tags/search⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/tags/search⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/tags/search⌿get⌿responses⌿200⌿meta"), Opt(TypeDef(Reference("⌿paths⌿/tags/search⌿get⌿responses⌿200⌿meta"), Seq( Field(Reference("⌿paths⌿/tags/search⌿get⌿responses⌿200⌿meta⌿code"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/tags/search⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿definitions⌿Media"), Seq( Field(Reference("⌿definitions⌿Media⌿location"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿created_time"), Opt(BInt(TypeMeta(Some("Epoc time (ms)"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿comments:"), Seq( Field(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿comments:⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿comments:⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿tags"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿users_in_photo"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿filter"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿likes"), Seq( Field(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿likes⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿likes⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿videos"), Seq( Field(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿videos⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿videos⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿images"), Seq( Field(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿images⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿images⌿thumbnail"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200⌿images⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿user"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 12"), List())), Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿definitions⌿Media"), Seq( Field(Reference("⌿definitions⌿Media⌿location"), Opt(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿created_time"), Opt(BInt(TypeMeta(Some("Epoc time (ms)"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿comments:"), Opt(TypeDef(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿comments:"), Seq( Field(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿comments:⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿comments:⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿tags"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Tag"), Seq( Field(Reference("⌿definitions⌿Tag⌿media_count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Tag⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿users_in_photo"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿filter"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿likes"), Opt(TypeDef(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿likes"), Seq( Field(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿likes⌿count"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿likes⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿videos"), Opt(TypeDef(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿videos"), Seq( Field(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿videos⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿videos⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿type"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿images"), Opt(TypeDef(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿images"), Seq( Field(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿images⌿low_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿images⌿thumbnail"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200⌿images⌿standard_resolution"), Opt(TypeDef(Reference("⌿definitions⌿Image"), Seq( Field(Reference("⌿definitions⌿Image⌿width"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿height"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Image⌿url"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Media⌿user"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 12"), List())), Reference("⌿paths⌿/users/search⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/users/search⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/users/search⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/users/{user-id}⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/users/{user-id}⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/users/{user-id}⌿get⌿responses⌿200⌿data"), Opt(TypeDef(Reference("⌿definitions⌿User"), Seq( Field(Reference("⌿definitions⌿User⌿website"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿username"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿bio"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿User⌿counts"), Opt(TypeDef(Reference("⌿paths⌿/users/{user-id}⌿get⌿responses⌿200⌿data⌿counts"), Seq( Field(Reference("⌿paths⌿/users/{user-id}⌿get⌿responses⌿200⌿data⌿counts⌿media"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/{user-id}⌿get⌿responses⌿200⌿data⌿counts⌿follows"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/users/{user-id}⌿get⌿responses⌿200⌿data⌿counts⌿follwed_by"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 3"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 7"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/media/{media-id}/comments⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/media/{media-id}/comments⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/comments⌿get⌿responses⌿200⌿meta"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}/comments⌿get⌿responses⌿200⌿meta"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/comments⌿get⌿responses⌿200⌿meta⌿code"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}/comments⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Comment"), Seq( Field(Reference("⌿definitions⌿Comment⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿created_time"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿text"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Comment⌿from"), Opt(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿responses⌿200") β†’ Null(TypeMeta(None, List())), Reference("⌿paths⌿/media/{media-id}/likes⌿delete⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/media/{media-id}/likes⌿delete⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/likes⌿delete⌿responses⌿200⌿meta"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}/likes⌿delete⌿responses⌿200⌿meta"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/likes⌿delete⌿responses⌿200⌿meta⌿code"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}/likes⌿delete⌿responses⌿200⌿data"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿responses⌿200⌿meta"), Opt(TypeDef(Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿responses⌿200⌿meta"), Seq( Field(Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿responses⌿200⌿meta⌿code"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), TypeMeta(None, List()))), Field(Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿responses⌿200⌿data"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 2"), List())), Reference("⌿paths⌿/users/{user-id}/relationship⌿post⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/users/{user-id}/relationship⌿post⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/users/{user-id}/relationship⌿post⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿MiniProfile"), Seq( Field(Reference("⌿definitions⌿MiniProfile⌿user_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿full_name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿id"), Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿MiniProfile⌿profile_picture"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())), Reference("⌿paths⌿/locations/search⌿get⌿responses⌿200") β†’ TypeDef(Reference("⌿paths⌿/locations/search⌿get⌿responses⌿200"), Seq( Field(Reference("⌿paths⌿/locations/search⌿get⌿responses⌿200⌿data"), Opt(ArrResult(TypeDef(Reference("⌿definitions⌿Location"), Seq( Field(Reference("⌿definitions⌿Location⌿id"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿name"), Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿latitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))), Field(Reference("⌿definitions⌿Location⌿longitude"), Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 4"), List())), TypeMeta(None, List())), TypeMeta(None, List()))) ), TypeMeta(Some("Named types: 1"), List())) ) def parameters = Map[ParameterRef, Parameter]( ParameterRef( Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿min_timestamp")) β†’ Parameter("min_timestamp", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/media/{media-id}/likes⌿delete⌿media-id")) β†’ Parameter("media-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/locations/{location-id}⌿get⌿location-id")) β†’ Parameter("location-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/media/search⌿get⌿MAX_TIMESTAMP")) β†’ Parameter("MAX_TIMESTAMP", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/media/{media-id}/likes⌿post⌿media-id")) β†’ Parameter("media-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/relationship⌿post⌿action")) β†’ Parameter("action", Opt(EnumTrait(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), TypeMeta(Some("Enum type : 5"), List()), Set( EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "follow", TypeMeta(Some("follow"), List())), EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "block", TypeMeta(Some("block"), List())), EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "unblock", TypeMeta(Some("unblock"), List())), EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "unfollow", TypeMeta(Some("unfollow"), List())), EnumObject(Str(None, TypeMeta(None, List("""enum("approve,unblock,block,unfollow,follow")"""))), "approve", TypeMeta(Some("approve"), List())) )), TypeMeta(None, List())), None, None, ".+", encode = false, ParameterPlace.withName("body")), ParameterRef( Reference("⌿paths⌿/users/{user-id}⌿get⌿user-id")) β†’ Parameter("user-id", BDcml(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/followed-by⌿get⌿user-id")) β†’ Parameter("user-id", BDcml(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/users/self/feed⌿get⌿count")) β†’ Parameter("count", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/users/self/feed⌿get⌿min_id")) β†’ Parameter("min_id", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿max_timestamp")) β†’ Parameter("max_timestamp", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/locations/search⌿get⌿foursquare_v2_id")) β†’ Parameter("foursquare_v2_id", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿max_timestamp")) β†’ Parameter("max_timestamp", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿min_id")) β†’ Parameter("min_id", Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/tags/{tag-name}⌿get⌿tag-name")) β†’ Parameter("tag-name", Str(None, TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/media/search⌿get⌿DISTANCE")) β†’ Parameter("DISTANCE", BInt(TypeMeta(None, List("""max(BigInt("5000"), false)"""))), None, Some("1000"), ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/tags/{tag-name}/media/recent⌿get⌿tag-name")) β†’ Parameter("tag-name", Str(None, TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿min_timestamp")) β†’ Parameter("min_timestamp", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿TEXT")) β†’ Parameter("TEXT", Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = false, ParameterPlace.withName("body")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/follows⌿get⌿user-id")) β†’ Parameter("user-id", BDcml(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿location-id")) β†’ Parameter("location-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/users/self/feed⌿get⌿max_id")) β†’ Parameter("max_id", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/users/self/media/liked⌿get⌿count")) β†’ Parameter("count", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/media/search⌿get⌿LNG")) β†’ Parameter("LNG", Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿min_id")) β†’ Parameter("min_id", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/locations/search⌿get⌿facebook_places_id")) β†’ Parameter("facebook_places_id", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿media-id")) β†’ Parameter("media-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/media/{media-id}⌿get⌿media-id")) β†’ Parameter("media-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/users/self/media/liked⌿get⌿max_like_id")) β†’ Parameter("max_like_id", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/media/search⌿get⌿MIN_TIMESTAMP")) β†’ Parameter("MIN_TIMESTAMP", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/locations/search⌿get⌿distance")) β†’ Parameter("distance", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/users/search⌿get⌿count")) β†’ Parameter("count", Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿max_id")) β†’ Parameter("max_id", Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/media/search⌿get⌿LAT")) β†’ Parameter("LAT", Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/locations/search⌿get⌿lat")) β†’ Parameter("lat", Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/locations/search⌿get⌿foursquare_id")) β†’ Parameter("foursquare_id", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿min_id")) β†’ Parameter("min_id", Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/tags/search⌿get⌿q")) β†’ Parameter("q", Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿max_id")) β†’ Parameter("max_id", Opt(Str(None, TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/media/{media-id}/likes⌿get⌿media-id")) β†’ Parameter("media-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/relationship⌿post⌿user-id")) β†’ Parameter("user-id", BDcml(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/media/{media-id}/comments⌿delete⌿media-id")) β†’ Parameter("media-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/media/{media-id}/comments⌿get⌿media-id")) β†’ Parameter("media-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/users/search⌿get⌿q")) β†’ Parameter("q", Str(None, TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/media/{shortcode}⌿get⌿shortcode")) β†’ Parameter("shortcode", Str(None, TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿count")) β†’ Parameter("count", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿count")) β†’ Parameter("count", Opt(BInt(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/locations/search⌿get⌿lng")) β†’ Parameter("lng", Opt(BDcml(TypeMeta(None, List())), TypeMeta(None, List())), None, None, ".+", encode = true, ParameterPlace.withName("query")), ParameterRef( Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿user-id")) β†’ Parameter("user-id", BDcml(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")), ParameterRef( Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿geo-id")) β†’ Parameter("geo-id", BInt(TypeMeta(None, List())), None, None, "[^/]+", encode = true, ParameterPlace.withName("path")) ) def basePath: String = "/v1" def discriminators: DiscriminatorLookupTable = Map[Reference, Reference]( ) def securityDefinitions: SecurityDefinitionsTable = Map[String, Security.Definition]( "oauth" -> OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), "key" -> ApiKey(None, "access_token", ParameterPlace.withName("query")) ) def stateTransitions: StateTransitionsTable = Map[State, Map[State, TransitionProperties]]() def calls: Seq[ApiCall] = Seq( ApiCall(GET, Path(Reference("⌿media⌿{media-id}⌿likes")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getmediaByMedia_idLikes",parameters = Seq( ParameterRef(Reference("⌿paths⌿/media/{media-id}/likes⌿get⌿media-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/{media-id}/likes⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(POST, Path(Reference("⌿media⌿{media-id}⌿likes")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "postmediaByMedia_idLikes",parameters = Seq( ParameterRef(Reference("⌿paths⌿/media/{media-id}/likes⌿post⌿media-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/{media-id}/likes⌿post⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("comments")) )), ApiCall(DELETE, Path(Reference("⌿media⌿{media-id}⌿likes")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "deletemediaByMedia_idLikes",parameters = Seq( ParameterRef(Reference("⌿paths⌿/media/{media-id}/likes⌿delete⌿media-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/{media-id}/likes⌿delete⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿users⌿{user-id}⌿follows")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getusersByUser_idFollows",parameters = Seq( ParameterRef(Reference("⌿paths⌿/users/{user-id}/follows⌿get⌿user-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/users/{user-id}/follows⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿locations⌿{location-id}")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getlocationsByLocation_id",parameters = Seq( ParameterRef(Reference("⌿paths⌿/locations/{location-id}⌿get⌿location-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/locations/{location-id}⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿users⌿search")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getusersSearch",parameters = Seq( ParameterRef(Reference("⌿paths⌿/users/search⌿get⌿q")), ParameterRef(Reference("⌿paths⌿/users/search⌿get⌿count")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/users/search⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿users⌿self⌿media⌿liked")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getusersSelfMediaLiked",parameters = Seq( ParameterRef(Reference("⌿paths⌿/users/self/media/liked⌿get⌿count")), ParameterRef(Reference("⌿paths⌿/users/self/media/liked⌿get⌿max_like_id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/users/self/media/liked⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿tags⌿{tag-name}")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "gettagsByTag_name",parameters = Seq( ParameterRef(Reference("⌿paths⌿/tags/{tag-name}⌿get⌿tag-name")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/tags/{tag-name}⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿tags⌿search")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "gettagsSearch",parameters = Seq( ParameterRef(Reference("⌿paths⌿/tags/search⌿get⌿q")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/tags/search⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿users⌿{user-id}⌿followed-by")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getusersByUser_idFollowed_by",parameters = Seq( ParameterRef(Reference("⌿paths⌿/users/{user-id}/followed-by⌿get⌿user-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/users/{user-id}/followed-by⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿media⌿{media-id}⌿comments")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getmediaByMedia_idComments",parameters = Seq( ParameterRef(Reference("⌿paths⌿/media/{media-id}/comments⌿get⌿media-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/{media-id}/comments⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(POST, Path(Reference("⌿media⌿{media-id}⌿comments")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "postmediaByMedia_idComments",parameters = Seq( ParameterRef(Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿media-id")), ParameterRef(Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿TEXT")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/{media-id}/comments⌿post⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("comments")) )), ApiCall(DELETE, Path(Reference("⌿media⌿{media-id}⌿comments")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "deletemediaByMedia_idComments",parameters = Seq( ParameterRef(Reference("⌿paths⌿/media/{media-id}/comments⌿delete⌿media-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/{media-id}/comments⌿delete⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿tags⌿{tag-name}⌿media⌿recent")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "gettagsByTag_nameMediaRecent",parameters = Seq( ParameterRef(Reference("⌿paths⌿/tags/{tag-name}/media/recent⌿get⌿tag-name")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/tags/{tag-name}/media/recent⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(POST, Path(Reference("⌿users⌿{user-id}⌿relationship")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "postusersByUser_idRelationship",parameters = Seq( ParameterRef(Reference("⌿paths⌿/users/{user-id}/relationship⌿post⌿user-id")), ParameterRef(Reference("⌿paths⌿/users/{user-id}/relationship⌿post⌿action")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/users/{user-id}/relationship⌿post⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("relationships")) )), ApiCall(GET, Path(Reference("⌿users⌿self⌿feed")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getusersSelfFeed",parameters = Seq( ParameterRef(Reference("⌿paths⌿/users/self/feed⌿get⌿count")), ParameterRef(Reference("⌿paths⌿/users/self/feed⌿get⌿max_id")), ParameterRef(Reference("⌿paths⌿/users/self/feed⌿get⌿min_id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/users/self/feed⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿users⌿{user-id}")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getusersByUser_id",parameters = Seq( ParameterRef(Reference("⌿paths⌿/users/{user-id}⌿get⌿user-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/users/{user-id}⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))), OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic")) )), ApiCall(GET, Path(Reference("⌿media⌿search")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getmediaSearch",parameters = Seq( ParameterRef(Reference("⌿paths⌿/media/search⌿get⌿MAX_TIMESTAMP")), ParameterRef(Reference("⌿paths⌿/media/search⌿get⌿DISTANCE")), ParameterRef(Reference("⌿paths⌿/media/search⌿get⌿LNG")), ParameterRef(Reference("⌿paths⌿/media/search⌿get⌿MIN_TIMESTAMP")), ParameterRef(Reference("⌿paths⌿/media/search⌿get⌿LAT")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/search⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿geographies⌿{geo-id}⌿media⌿recent")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getgeographiesByGeo_idMediaRecent",parameters = Seq( ParameterRef(Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿geo-id")), ParameterRef(Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿count")), ParameterRef(Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿min_id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/geographies/{geo-id}/media/recent⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿media⌿{shortcode}")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getmediaByShortcode",parameters = Seq( ParameterRef(Reference("⌿paths⌿/media/{shortcode}⌿get⌿shortcode")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/{shortcode}⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿locations⌿search")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getlocationsSearch",parameters = Seq( ParameterRef(Reference("⌿paths⌿/locations/search⌿get⌿foursquare_v2_id")), ParameterRef(Reference("⌿paths⌿/locations/search⌿get⌿facebook_places_id")), ParameterRef(Reference("⌿paths⌿/locations/search⌿get⌿distance")), ParameterRef(Reference("⌿paths⌿/locations/search⌿get⌿lat")), ParameterRef(Reference("⌿paths⌿/locations/search⌿get⌿foursquare_id")), ParameterRef(Reference("⌿paths⌿/locations/search⌿get⌿lng")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/locations/search⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿users⌿self⌿requested-by")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getusersSelfRequested_by",parameters = Seq( ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/users/self/requested-by⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿media⌿{media-id}")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getmediaByMedia_id",parameters = Seq( ParameterRef(Reference("⌿paths⌿/media/{media-id}⌿get⌿media-id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/{media-id}⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿locations⌿{location-id}⌿media⌿recent")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getlocationsByLocation_idMediaRecent",parameters = Seq( ParameterRef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿location-id")), ParameterRef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿max_timestamp")), ParameterRef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿min_timestamp")), ParameterRef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿min_id")), ParameterRef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿max_id")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/locations/{location-id}/media/recent⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿users⌿{user-id}⌿media⌿recent")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getusersByUser_idMediaRecent",parameters = Seq( ParameterRef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿user-id")), ParameterRef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿max_timestamp")), ParameterRef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿min_id")), ParameterRef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿min_timestamp")), ParameterRef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿max_id")), ParameterRef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿count")) ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/users/{user-id}/media/recent⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) )), ApiCall(GET, Path(Reference("⌿media⌿popular")), HandlerCall( "instagram.api.yaml", "InstagramApiYaml", instantiate = false, "getmediaPopular",parameters = Seq( ) ), Set(MimeType("application/json")), Set(MimeType("application/json")), Map.empty[String, Seq[Class[Exception]]], TypesResponseInfo( Map[Int, ParameterRef]( 200 -> ParameterRef(Reference("⌿paths⌿/media/popular⌿get⌿responses⌿200")) ), None), StateResponseInfo( Map[Int, State]( 200 -> Self ), None), Set( OAuth2Constraint("oauth", OAuth2Definition(None, Some(new URL("https://instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=token")), Map[String, String]( "basic" -> "to read any and all data related to a user (e.g. following/followed-by lists, photos, etc.) (granted by default) " , "comments" -> "to create or delete comments on a user’s behalf" , "relationships" -> "to follow and unfollow users on a user’s behalf" , "likes" -> "to like and unlike items on a user’s behalf" )), Set("basic", "comments", "relationships", "likes")), ApiKeyConstraint("key", ApiKey(None, "access_token", ParameterPlace.withName("query"))) ))) def packageName: Option[String] = Some("instagram.api.yaml") def model = new StrictModel(calls, types, parameters, discriminators, basePath, packageName, stateTransitions, securityDefinitions) }
zalando/play-swagger
api-first-core/src/test/scala/model/resources.instagram_api_yaml.scala
Scala
mit
171,134
package org.bitcoins.db import com.typesafe.config.ConfigFactory import org.bitcoins.chain.config.ChainAppConfig import org.bitcoins.core.config.MainNet import org.bitcoins.node.config.NodeAppConfig import org.bitcoins.testkit.BitcoinSTestAppConfig import org.bitcoins.testkit.BitcoinSTestAppConfig.ProjectType import org.bitcoins.testkit.util.{BitcoinSAsyncTest, FileUtil} import org.bitcoins.wallet.config.WalletAppConfig import java.io.File import java.nio.file._ class DBConfigTest extends BitcoinSAsyncTest { it should "use sqlite as default database and set its connection pool size to 1" in { withTempDir { dataDir => val bytes = Files.readAllBytes( new File("db-commons/src/main/resources/reference.conf").toPath) Files.write(dataDir.resolve("bitcoin-s.conf"), bytes, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE) val chainConfig = ChainAppConfig(dataDir, Vector.empty) val nodeConfig = NodeAppConfig(dataDir, Vector.empty) val walletConfig = WalletAppConfig(dataDir, Vector.empty) val slickChainConfig = chainConfig.slickDbConfig assert(slickChainConfig.profileName == "slick.jdbc.SQLiteProfile") assert(slickChainConfig.config.hasPath("db.numThreads")) assert(slickChainConfig.config.getInt("db.numThreads") == 1) assert(slickChainConfig.config.getInt("db.queueSize") == 5000) val slickNodeConfig = nodeConfig.slickDbConfig assert(slickNodeConfig.profileName == "slick.jdbc.SQLiteProfile") assert(slickNodeConfig.config.hasPath("db.numThreads")) assert(slickNodeConfig.config.getInt("db.numThreads") == 1) assert(slickNodeConfig.config.getInt("db.queueSize") == 5000) val slickWalletConfig = walletConfig.slickDbConfig assert(slickWalletConfig.profileName == "slick.jdbc.SQLiteProfile") assert(slickWalletConfig.config.hasPath("db.numThreads")) assert(slickWalletConfig.config.getInt("db.numThreads") == 1) assert(slickWalletConfig.config.getInt("db.queueSize") == 5000) } } it should "use sqlite as default database and disable connection pool for tests" in { withTempDir { dataDir => val chainConfig = ChainAppConfig(dataDir, Vector.empty) val slickChainConfig = chainConfig.slickDbConfig assert(slickChainConfig.profileName == "slick.jdbc.SQLiteProfile") assert(slickChainConfig.config.hasPath("db.numThreads")) assert(slickChainConfig.config.getInt("db.numThreads") == 1) assert( slickChainConfig.config.getString("db.connectionPool") == "disabled") assert(slickChainConfig.config.getInt("db.queueSize") == 5000) val nodeConfig = NodeAppConfig(dataDir, Vector.empty) val slickNodeConfig = nodeConfig.slickDbConfig assert(slickNodeConfig.profileName == "slick.jdbc.SQLiteProfile") assert(slickNodeConfig.config.hasPath("db.numThreads")) assert(slickNodeConfig.config.getInt("db.numThreads") == 1) assert( slickNodeConfig.config.getString("db.connectionPool") == "disabled") assert(slickNodeConfig.config.getInt("db.queueSize") == 5000) val walletConfig = WalletAppConfig(dataDir, Vector.empty) val slickWalletConfig = walletConfig.slickDbConfig assert(slickWalletConfig.profileName == "slick.jdbc.SQLiteProfile") assert(slickWalletConfig.config.hasPath("db.numThreads")) assert(slickWalletConfig.config.getInt("db.numThreads") == 1) assert( slickWalletConfig.config.getString("db.connectionPool") == "disabled") assert(slickWalletConfig.config.getInt("db.queueSize") == 5000) } } it must "override a configuration with a hardcoded value" in { val memoryDb = BitcoinSTestAppConfig.configWithEmbeddedDb(Some(ProjectType.Chain), () => None) val mainnetConf = ConfigFactory.parseString("bitcoin-s.network = mainnet") val chainConfig: ChainAppConfig = { BitcoinSTestAppConfig.getSpvTestConfig(mainnetConf).chainConf } assert(chainConfig.network == MainNet) val mainNetChainAppConfig: ChainAppConfig = chainConfig.withOverrides(memoryDb) assert(mainNetChainAppConfig.network == MainNet) } def withTempDir[T](f: Path => T): T = FileUtil.withTempDir(getClass.getName)(f) }
bitcoin-s/bitcoin-s
db-commons-test/src/test/scala/org/bitcoins/db/DBConfigTest.scala
Scala
mit
4,365
package codegen.types object StructGenerator { private val tabWidth = 4 /** * Generates a string to declare a C struct * @param definition Definition of the struct to generate * @return String to declare the C struct */ def apply(definition: StructDefinition): String = { s"""typedef struct | { |${fieldDeclarations(definition.fields)} | } ${definition.name};""".stripMargin } /** * Gets a formatted string to declare a fields of a struct. The names * of all fields in the struct will be aligned to the same column for * improved readability * @param fields List of fields contained in the struct * @return Formatted string to declare fields of a struct */ private def fieldDeclarations(fields: Seq[StructField]): String = { val fieldNameColumn = fieldNameColumnNumber(fields) val fieldDeclarations = fields.map(field => { val declaration = fieldDeclaration(field, fieldNameColumn) s" $declaration;" }) fieldDeclarations.mkString("\\n") } /** * In order to format the struct field declarations so that all field names are aligned, * this function determines the column number at which to declare the name of the struct * fields. * @param fields List of fields contained in the struct * @return Column number at which to declare the struct field names */ private def fieldNameColumnNumber(fields: Seq[StructField]): Int = { // Determine the maximum width of the longest type declaration of all fields // in the struct val typeDeclarations = fields.map({ case FixedArrayStructField(_, elementTypeDeclaration, _) => elementTypeDeclaration case SimpleStructField(_, typeDeclaration) => typeDeclaration }) // Simple add an amount of spacing equal to the width of the indentation // to declare the field name val maxFieldTypeWidth = typeDeclarations.map(_.length).max maxFieldTypeWidth + tabWidth } /** * Gets the formatted string to declare the given struct field * @param field Field to declare * @param fieldNameColumn Column number at which to declare the struct field names * @return Formatted string to declare the given struct field within the struct */ private def fieldDeclaration(field: StructField, fieldNameColumn: Int): String = { field match { case array @ FixedArrayStructField(_, _, _) => fixedArrayFieldDeclaration(array, fieldNameColumn) case simpleField @ SimpleStructField(_, _) => simpleStructFieldDeclaration(simpleField, fieldNameColumn) } } /** * Gets the string to declare a field of a struct that is a fixed-length array of some * type, e.g. 'char identifier[ 33 ];' * @param field - Fixed array field to declare * @param fieldNameColumn Column number at which to declare the struct field names * @return String to declare a fixed-length array field */ private def fixedArrayFieldDeclaration(field: FixedArrayStructField, fieldNameColumn: Int): String = { val spacing = fieldTypeNameSpacing(field.elementTypeDeclaration, fieldNameColumn) s"${field.elementTypeDeclaration}$spacing${field.name}[ ${field.maxSize} ]" } /** * Gets the spacing to place between a field's type declaration and a fields name * to ensure that the names of all struct fields are aligned. * @param fieldType Type declaration of the field * @param fieldNameColumn Column number at which to declare the struct field names * @return */ private def fieldTypeNameSpacing(fieldType: String, fieldNameColumn: Int): String = { require(fieldNameColumn > fieldType.length) " " * (fieldNameColumn - fieldType.length) } /** * Gets the string to declare a simple field that is not a fixed length array, * e.g. 'char* url;' * @param field Simple struct field to declare * @param fieldNameColumn Column number at which to declare the struct field names * @return String to declare a simple struct field */ private def simpleStructFieldDeclaration(field: SimpleStructField, fieldNameColumn: Int): String = { val spacing = fieldTypeNameSpacing(field.typeDeclaration, fieldNameColumn) s"${field.typeDeclaration}$spacing${field.name}" } }
gatkin/cDTO
src/main/scala/codegen/types/StructGenerator.scala
Scala
mit
4,277
package cakesolutions.kafka import org.apache.kafka.clients.consumer.ConsumerRecords import org.apache.kafka.common.KafkaException import org.apache.kafka.common.requests.IsolationLevel import org.apache.kafka.common.serialization.{StringDeserializer, StringSerializer} import org.slf4j.LoggerFactory import scala.collection.JavaConverters._ import scala.util.Random class IdempotentProducerSpec extends KafkaIntSpec { private val log = LoggerFactory.getLogger(getClass) private def randomString: String = Random.alphanumeric.take(5).mkString("") val idempotentProducerConfig: KafkaProducer.Conf[String, String] = KafkaProducer.Conf(new StringSerializer(), new StringSerializer(), bootstrapServers = s"localhost:$kafkaPort", enableIdempotence = true) val transactionalProducerConfig: KafkaProducer.Conf[String, String] = KafkaProducer.Conf(new StringSerializer(), new StringSerializer(), bootstrapServers = s"localhost:$kafkaPort", transactionalId = Some("t1"), enableIdempotence = true) val consumerConfig: KafkaConsumer.Conf[String, String] = KafkaConsumer.Conf(new StringDeserializer(), new StringDeserializer(), bootstrapServers = s"localhost:$kafkaPort", groupId = randomString, enableAutoCommit = false) val transactionConsumerConfig: KafkaConsumer.Conf[String, String] = KafkaConsumer.Conf(new StringDeserializer(), new StringDeserializer(), bootstrapServers = s"localhost:$kafkaPort", groupId = randomString, enableAutoCommit = false, isolationLevel = IsolationLevel.READ_COMMITTED) "Producer with idempotent config" should "deliver batch" in { val topic = randomString log.info(s"Using topic [$topic] and kafka port [$kafkaPort]") val producer = KafkaProducer(idempotentProducerConfig) val consumer = KafkaConsumer(consumerConfig) consumer.subscribe(List(topic).asJava) val records1 = consumer.poll(1000) records1.count() shouldEqual 0 log.info("Kafka producer connecting on port: [{}]", kafkaPort) producer.send(KafkaProducerRecord(topic, Some("key"), "value")) producer.flush() val records2: ConsumerRecords[String, String] = consumer.poll(1000) records2.count() shouldEqual 1 producer.close() consumer.close() } "Producer with transaction" should "deliver batch" in { val topic = randomString log.info(s"Using topic [$topic] and kafka port [$kafkaPort]") val producer = KafkaProducer(transactionalProducerConfig) val consumer = KafkaConsumer(transactionConsumerConfig) consumer.subscribe(List(topic).asJava) val records1 = consumer.poll(1000) records1.count() shouldEqual 0 log.info("Kafka producer connecting on port: [{}]", kafkaPort) producer.initTransactions() try { producer.beginTransaction() producer.send(KafkaProducerRecord(topic, Some("key"), "value")) producer.commitTransaction() } catch { case ex: KafkaException => log.error(ex.getMessage, ex) producer.abortTransaction() } val records2: ConsumerRecords[String, String] = consumer.poll(1000) records2.count() shouldEqual 1 producer.close() consumer.close() } }
cakesolutions/scala-kafka-client
client/src/test/scala/cakesolutions/kafka/IdempotentProducerSpec.scala
Scala
mit
3,253
package com.chriswk.bnet.wow.model case class StatHolder(amount: Long, stat: Long)
chriswk/sbnetapi
src/main/scala/com/chriswk/bnet/wow/model/Stat.scala
Scala
mit
84
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.openwhisk.core.containerpool import akka.actor.ActorSystem import org.apache.openwhisk.common.{Logging, TransactionId} import org.apache.openwhisk.core.WhiskConfig import org.apache.openwhisk.core.entity.{ByteSize, ExecManifest, InvokerInstanceId} import org.apache.openwhisk.spi.Spi import scala.concurrent.Future case class ContainerArgsConfig(network: String, dnsServers: Seq[String] = Seq.empty, extraArgs: Map[String, Set[String]] = Map.empty) case class ContainerPoolConfig(userMemory: ByteSize, concurrentPeekFactor: Double, akkaClient: Boolean) { require( concurrentPeekFactor > 0 && concurrentPeekFactor <= 1.0, s"concurrentPeekFactor must be > 0 and <= 1.0; was $concurrentPeekFactor") /** * The shareFactor indicates the number of containers that would share a single core, on average. * cpuShare is a docker option (-c) whereby a container's CPU access is limited. * A value of 1024 is the full share so a strict resource division with a shareFactor of 2 would yield 512. * On an idle/underloaded system, a container will still get to use underutilized CPU shares. */ private val totalShare = 1024.0 // This is a pre-defined value coming from docker and not our hard-coded value. // Grant more CPU to a container if it allocates more memory. def cpuShare(reservedMemory: ByteSize) = (totalShare / (userMemory.toBytes / reservedMemory.toBytes)).toInt } /** * An abstraction for Container creation */ trait ContainerFactory { /** create a new Container */ def createContainer(tid: TransactionId, name: String, actionImage: ExecManifest.ImageName, userProvidedImage: Boolean, memory: ByteSize, cpuShares: Int)(implicit config: WhiskConfig, logging: Logging): Future[Container] /** perform any initialization */ def init(): Unit /** cleanup any remaining Containers; should block until complete; should ONLY be run at startup/shutdown */ def cleanup(): Unit } object ContainerFactory { /** based on https://github.com/moby/moby/issues/3138 and https://github.com/moby/moby/blob/master/daemon/names/names.go */ private def isAllowed(c: Char) = c.isLetterOrDigit || c == '_' || c == '.' || c == '-' /** include the instance name, if specified and strip invalid chars before attempting to use them in the container name */ def containerNamePrefix(instanceId: InvokerInstanceId): String = s"wsk${instanceId.uniqueName.getOrElse("")}${instanceId.toInt}".filter(isAllowed) } /** * An SPI for ContainerFactory creation * All impls should use the parameters specified as additional args to "docker run" commands */ trait ContainerFactoryProvider extends Spi { def instance(actorSystem: ActorSystem, logging: Logging, config: WhiskConfig, instance: InvokerInstanceId, parameters: Map[String, Set[String]]): ContainerFactory }
starpit/openwhisk
common/scala/src/main/scala/org/apache/openwhisk/core/containerpool/ContainerFactory.scala
Scala
apache-2.0
3,856
package mimir.adaptive import java.io._ import com.typesafe.scalalogging.LazyLogging import scala.collection.JavaConverters._ import scala.collection.mutable.ListBuffer import mimir.Database import mimir.parser._ import mimir.algebra._ import mimir.lenses._ import mimir.models._ import mimir.views._ import mimir.statistics.FuncDep import mimir.provenance.Provenance import mimir.exec.spark.RAToSpark object CheckHeader extends Multilens with LazyLogging { def initSchema(db: Database, config: MultilensConfig): TraversableOnce[Model] = { val viewName = config.schema val modelName = ID("MIMIR_CH_", viewName) val dhOp = Limit(0,Some(6),config.query) //TODO: This is a temporary fix for detect headers when there are multiple partitions // spark is returning the first X rows for limit queries from a nondeterministic partition //val td = db.query(dhOp)(_.toList.map(_.tuple)).toSeq val td = db.compiler.compileToSparkWithRewrites(config.query) .take(6).map(row => row.toSeq.map(spel => RAToSpark.sparkInternalRowValueToMimirPrimitive(spel)) ).toSeq val (headerDetected, initialHeaders) = DetectHeader.detect_header(config.query.columnNames, td) db.compiler.compileToSparkWithRewrites(config.query).take(6).map(_.toString()) val detectmodel = new DetectHeaderModel( modelName, config.humanReadableName, headerDetected, initialHeaders ) Seq(detectmodel) } def tableCatalogFor(db: Database, config: MultilensConfig): Operator = { HardTable( Seq( (ID("TABLE_NAME"),TString()) ), Seq( Seq( StringPrimitive("DATA") ) ) ) } def attrCatalogFor(db: Database, config: MultilensConfig): Operator = { HardTable( Seq( (ID("TABLE_NAME") -> TString()), (ID("ATTR_TYPE") -> TType()), (ID("IS_KEY") -> TBool()), (ID("COLUMN_ID") -> TInt()) ), (0 until config.query.columnNames.size).map { col => Seq( StringPrimitive("DATA"), TypePrimitive(TString()), BoolPrimitive(false), IntPrimitive(col) ) } ).addColumns( "ATTR_NAME" -> VGTerm(config.schema.withPrefix("MIMIR_CH_"), 0, Seq(Var(ID("COLUMN_ID"))), Seq()) ).removeColumns("COLUMN_ID") } def viewFor(db: Database, config: MultilensConfig, table: ID): Option[Operator] = { if(table.equals(ID("DATA"))){ val model = db.models.get(ID("MIMIR_CH_",config.schema)).asInstanceOf[DetectHeaderModel] var oper = config.query // If we have a header... if(model.headerDetected) { // Strip off row #1 val firstRowID = db.query(oper.limit(1))(res => { val resList = res.toList if(resList.isEmpty) RowIdPrimitive("0") else resList.head.provenance }) oper = oper.filter { RowIdVar().neq(firstRowID) } // And then rename columns accordingly oper = oper.renameByID( config.query.columnNames .zipWithIndex .map { case (col, idx) => // the model takes the column index and returns a string val guessedColumnName = model.bestGuess(0, Seq(IntPrimitive(idx)), Seq()) // map from the existing name to the new one col -> ID(guessedColumnName.asString) } :_* ) } return Some(oper) } else { logger.warn(s"Getting invalid table $table from Detect Headers adaptive schema") return None } } }
UBOdin/mimir
src/main/scala/mimir/adaptive/CheckHeader.scala
Scala
apache-2.0
3,691
/* * Copyright 2011 TomTom International BV * * 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 tomtom.splitter.layer7 import java.io.File import org.jboss.netty.handler.codec.http.{DefaultHttpRequest, HttpMethod, HttpVersion} import org.scalatest.{Matchers, WordSpec} /** * Verifies basic behavior of RequestMapper. * * @author Eric Bowman * @since 2011-04-12 19:15:22 */ class RequestsTest extends WordSpec with Matchers with RequestMapperModule { override val shadowHostname = Some("my.hostname") override val rewriteConfig = Some(new File("ofbiz.config")) def fromUri(method: HttpMethod)(uri: String) = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, uri) def post(uri: String) = fromUri(HttpMethod.POST)(uri) def get(uri: String) = fromUri(HttpMethod.GET)(uri) def put(uri: String) = fromUri(HttpMethod.PUT)(uri) def delete(uri: String) = fromUri(HttpMethod.DELETE)(uri) import RequestMapper._ "The RequestMapper" should { "rewrite a CreateUser user POST" in { assert(rewrite(post("/buenos-aires-ws/services/wfe/users/<q_f>")).map(_.getUri) === Some("/ttuser/atom/users/<q_f>")) } "rewrite a CreateUser user PUT" in { assert(rewrite(put("/buenos-aires-ws/services/wfe/users/<q_f>")).map(_.getUri) === Some("/ttuser/atom/users/<q_f>")) } "not rewrite a CreateUser user GET" in { assert(rewrite(get("/buenos-aires-ws/services/wfe/users/<q_f>")).map(_.getUri) === None) } "rewrite a GetUserBasicProfile GET" in { assert(rewrite(get("/buenos-aires-ws/services/wfe/users/<uid>/profiles/basic<q_f>")).map(_.getUri) === Some("/ttuser/atom/users/<uid>/profiles/basic<q_f>")) } "not rewrite a GetUserBasicProfile POST" in { assert(rewrite(post("/buenos-aires-ws/services/wfe/users/<uid>/profiles/basic<q_f>")).map(_.getUri) === None) } "rewrite any ManageUser method" in { assert(rewrite(get("/buenos-aires-ws/tomtommain/UserService.rpc")).map(_.getUri) === Some("/ttuser/gwtrpc/UserService.rpc")) assert(rewrite(post("/buenos-aires-ws/tomtommain/UserService.rpc")).map(_.getUri) === Some("/ttuser/gwtrpc/UserService.rpc")) assert(rewrite(put("/buenos-aires-ws/tomtommain/UserService.rpc")).map(_.getUri) === Some("/ttuser/gwtrpc/UserService.rpc")) } "rewrite legacy manage user POST" in { assert(rewrite(post("/proxy.php")).map(_.getUri) === Some("/ttuser/control/legacy")) } "not rewrite legacy manage user GET or PUT" in { assert(rewrite(get("/proxy.php")).map(_.getUri) === None) assert(rewrite(put("/proxy.php")).map(_.getUri) === None) } } type ? = this.type }
ebowman/splitter
src/test/scala/tomtom/splitter/layer7/RequestsTest.scala
Scala
apache-2.0
3,168
package nl.dekkr.hoppr.rest import nl.dekkr.hoppr.model.{Feed, Syndication, FetchLogger} import nl.dekkr.hoppr.rss.{FeedLogOutput, AtomOutput} import spray.http.MediaTypes._ import spray.http.StatusCodes import spray.httpx.marshalling._ import StatusCodes._ import spray.routing.HttpService case class Url(uri: String) /** * REST Service definition */ // this trait defines our service behavior independently from the service actor trait RestService extends HttpService { import nl.dekkr.hoppr.rest.MyJsonProtocol._ import spray.httpx.SprayJsonSupport._ //TODO Actor per request ? lazy val index = <html> <body> <h1>This is <i>hoppR</i> !</h1> <p>Defined resources:</p> <ul> <li> <a href="/api/log">/log</a> </li> <li>Add feed: <form action="/api/feed" method="post"> <input type="text" name="url"></input> <input type="submit" name="Add feed"/> </form> </li> </ul> </body> </html> val myRoute = { get { pathSingleSlash { complete(index) } } ~ pathPrefix("api") { get { path("log") { respondWithMediaType(`application/json`) { complete { marshal(FetchLogger.getLast100) } } } } ~ path("feed") { post { entity(as[Url]) { url => respondWithMediaType(`application/json`) { Syndication.addNewFeed(url.uri) match { case feed: Feed => respondWithStatus(Created) { complete(feed) } case _ => respondWithStatus(BadRequest) { complete("Could not add feed") } } } } } ~ delete { entity(as[Url]) { url => respondWithMediaType(`application/json`) { Syndication.removeFeed(url.uri) match { case 1 => complete(OK) case 0 => complete(NotFound) case _ => respondWithStatus(BadRequest) { complete("Could not remove feed") } } } } } ~ get { entity(as[Url]) { url => respondWithMediaType(`application/json`) { Syndication.getFeed(url.uri) match { case Some(feed) => respondWithStatus(OK) { complete(feed) } case None => complete(NotFound) } } } } } ~ path("rss" / IntNumber) { feedId => get { respondWithMediaType(`application/xml`) { if (feedId == 0) { complete(FeedLogOutput.getAtomFeed(0).get) } else { AtomOutput.getAtomFeed(feedId) match { case Some(output) => complete(output) case None => complete(NotFound) } } } } } } } }
plamola/hoppR
src/main/scala/nl/dekkr/hoppr/rest/RestService.scala
Scala
mit
3,285
package eu.timepit.refined.types import eu.timepit.refined.api.{Refined, RefinedTypeOps} import eu.timepit.refined.boolean.{And, Or} import eu.timepit.refined.numeric.Interval import eu.timepit.refined.string.{IPv4, MatchesRegex, StartsWith} /** Module for refined types that are related to the Internet protocol suite. */ object net { /** An `Int` in the range from 0 to 65535 representing a port number. */ type PortNumber = Int Refined Interval.Closed[0, 65535] object PortNumber extends RefinedTypeOps[PortNumber, Int] /** An `Int` in the range from 0 to 1023 representing a port number. */ type SystemPortNumber = Int Refined Interval.Closed[0, 1023] object SystemPortNumber extends RefinedTypeOps[SystemPortNumber, Int] /** An `Int` in the range from 1024 to 49151 representing a port number. */ type UserPortNumber = Int Refined Interval.Closed[1024, 49151] object UserPortNumber extends RefinedTypeOps[UserPortNumber, Int] /** An `Int` in the range from 49152 to 65535 representing a port number. */ type DynamicPortNumber = Int Refined Interval.Closed[49152, 65535] object DynamicPortNumber extends RefinedTypeOps[DynamicPortNumber, Int] /** An `Int` in the range from 1024 to 65535 representing a port number. */ type NonSystemPortNumber = Int Refined Interval.Closed[1024, 65535] object NonSystemPortNumber extends RefinedTypeOps[NonSystemPortNumber, Int] import PrivateNetworks._ /** A `String` representing a valid IPv4 in the private network 10.0.0.0/8 (RFC1918) */ type Rfc1918ClassAPrivate = String Refined Rfc1918ClassAPrivateSpec /** A `String` representing a valid IPv4 in the private network 172.15.0.0/12 (RFC1918) */ type Rfc1918ClassBPrivate = String Refined Rfc1918ClassBPrivateSpec /** A `String` representing a valid IPv4 in the private network 192.168.0.0/16 (RFC1918) */ type Rfc1918ClassCPrivate = String Refined Rfc1918ClassCPrivateSpec /** A `String` representing a valid IPv4 in a private network according to RFC1918 */ type Rfc1918Private = String Refined Rfc1918PrivateSpec /** A `String` representing a valid IPv4 in the private network 192.0.2.0/24 (RFC5737) */ type Rfc5737Testnet1 = String Refined Rfc5737Testnet1Spec /** A `String` representing a valid IPv4 in the private network 198.51.100.0/24 (RFC5737) */ type Rfc5737Testnet2 = String Refined Rfc5737Testnet2Spec /** A `String` representing a valid IPv4 in the private network 203.0.113.0/24 (RFC5737) */ type Rfc5737Testnet3 = String Refined Rfc5737Testnet3Spec /** A `String` representing a valid IPv4 in a private network according to RFC5737 */ type Rfc5737Testnet = String Refined Rfc5737TestnetSpec /** A `String` representing a valid IPv4 in the local link network 169.254.0.0/16 (RFC3927) */ type Rfc3927LocalLink = String Refined Rfc3927LocalLinkSpec /** A `String` representing a valid IPv4 in the benchmarking network 198.18.0.0/15 (RFC2544) */ type Rfc2544Benchmark = String Refined Rfc2544BenchmarkSpec /** A `String` representing a valid IPv4 in a private network according to RFC1918, RFC5737, RFC3927 or RFC2544 */ type PrivateNetwork = String Refined (Rfc1918PrivateSpec Or Rfc5737TestnetSpec Or Rfc3927LocalLinkSpec Or Rfc2544BenchmarkSpec) object PrivateNetworks { type Rfc1918ClassAPrivateSpec = IPv4 And StartsWith["10."] type Rfc1918ClassBPrivateSpec = IPv4 And MatchesRegex["^172\\\\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)\\\\..+"] type Rfc1918ClassCPrivateSpec = IPv4 And StartsWith["192.168."] type Rfc1918PrivateSpec = Rfc1918ClassAPrivateSpec Or Rfc1918ClassBPrivateSpec Or Rfc1918ClassCPrivateSpec type Rfc5737Testnet1Spec = IPv4 And StartsWith["192.0.2."] type Rfc5737Testnet2Spec = IPv4 And StartsWith["198.51.100."] type Rfc5737Testnet3Spec = IPv4 And StartsWith["203.0.113."] type Rfc5737TestnetSpec = Rfc5737Testnet1Spec Or Rfc5737Testnet2Spec Or Rfc5737Testnet3Spec type Rfc3927LocalLinkSpec = IPv4 And StartsWith["169.254."] type Rfc2544BenchmarkSpec = IPv4 And Or[StartsWith["198.18."], StartsWith["198.19."]] } } trait NetTypes { final type PortNumber = net.PortNumber final val PortNumber = net.PortNumber final type SystemPortNumber = net.SystemPortNumber final val SystemPortNumber = net.SystemPortNumber final type UserPortNumber = net.UserPortNumber final val UserPortNumber = net.UserPortNumber final type DynamicPortNumber = net.DynamicPortNumber final val DynamicPortNumber = net.DynamicPortNumber final type NonSystemPortNumber = net.NonSystemPortNumber final val NonSystemPortNumber = net.NonSystemPortNumber final type Rfc1918ClassAPrivate = net.Rfc1918ClassAPrivate final type Rfc1918ClassBPrivate = net.Rfc1918ClassBPrivate final type Rfc1918ClassCPrivate = net.Rfc1918ClassCPrivate final type Rfc1918Private = net.Rfc1918Private final type Rfc5737Testnet1 = net.Rfc5737Testnet1 final type Rfc5737Testnet2 = net.Rfc5737Testnet2 final type Rfc5737Testnet3 = net.Rfc5737Testnet3 final type Rfc5737Testnet = net.Rfc5737Testnet final type Rfc3927LocalLink = net.Rfc3927LocalLink final type Rfc2544Benchmark = net.Rfc2544Benchmark final type PrivateNetwork = net.PrivateNetwork }
fthomas/refined
modules/core/shared/src/main/scala-3.0+/eu/timepit/refined/types/net.scala
Scala
mit
5,304
/* * Copyright (C) 2014 - 2016 Softwaremill <http://softwaremill.com> * Copyright (C) 2016 - 2019 Lightbend Inc. <http://www.lightbend.com> */ package akka.kafka.javadsl import java.util import java.util.concurrent.{CompletionStage, Executor, Executors} import java.util.concurrent.atomic.AtomicBoolean import akka.Done import akka.kafka.internal.ConsumerControlAsJava import akka.kafka.tests.scaladsl.LogCapturing import org.apache.kafka.common.{Metric, MetricName} import org.scalatest.concurrent.ScalaFutures import org.scalatest.{Matchers, WordSpecLike} import scala.compat.java8.FutureConverters._ import scala.concurrent.Future import scala.language.reflectiveCalls object ControlSpec { def createControl(stopFuture: Future[Done] = Future.successful(Done), shutdownFuture: Future[Done] = Future.successful(Done)) = { val control = new akka.kafka.scaladsl.ControlSpec.ControlImpl(stopFuture, shutdownFuture) val wrapped = new ConsumerControlAsJava(control) new Consumer.Control { def shutdownCalled: AtomicBoolean = control.shutdownCalled override def stop(): CompletionStage[Done] = wrapped.stop() override def shutdown(): CompletionStage[Done] = wrapped.shutdown() override def drainAndShutdown[T](streamCompletion: CompletionStage[T], ec: Executor): CompletionStage[T] = wrapped.drainAndShutdown(streamCompletion, ec) override def isShutdown: CompletionStage[Done] = wrapped.isShutdown override def getMetrics: CompletionStage[util.Map[MetricName, Metric]] = wrapped.getMetrics } } } class ControlSpec extends WordSpecLike with ScalaFutures with Matchers with LogCapturing { import ControlSpec._ val ec = Executors.newCachedThreadPool() "Control" should { "drain to stream result" in { val control = createControl() val drainingControl = Consumer.createDrainingControl(akka.japi.Pair(control, Future.successful("expected").toJava)) drainingControl.drainAndShutdown(ec).toScala.futureValue should be("expected") control.shutdownCalled.get() should be(true) } "drain to stream failure" in { val control = createControl() val drainingControl = Consumer.createDrainingControl( akka.japi.Pair(control, Future.failed[String](new RuntimeException("expected")).toJava) ) val value = drainingControl.drainAndShutdown(ec).toScala.failed.futureValue value shouldBe a[RuntimeException] // endWith to accustom Scala 2.11 and 2.12 value.getMessage should endWith("expected") control.shutdownCalled.get() should be(true) } "drain to stream failure even if shutdown fails" in { val control = createControl(shutdownFuture = Future.failed(new RuntimeException("not this"))) val drainingControl = Consumer.createDrainingControl( akka.japi.Pair(control, Future.failed[String](new RuntimeException("expected")).toJava) ) val value = drainingControl.drainAndShutdown(ec).toScala.failed.futureValue value shouldBe a[RuntimeException] // endWith to accustom Scala 2.11 and 2.12 value.getMessage should endWith("expected") control.shutdownCalled.get() should be(true) } "drain to shutdown failure when stream succeeds" in { val control = createControl(shutdownFuture = Future.failed(new RuntimeException("expected"))) val drainingControl = Consumer.createDrainingControl(akka.japi.Pair(control, Future.successful(Done).toJava)) val value = drainingControl.drainAndShutdown(ec).toScala.failed.futureValue value shouldBe a[RuntimeException] // endWith to accustom Scala 2.11 and 2.12 value.getMessage should endWith("expected") control.shutdownCalled.get() should be(true) } } }
softwaremill/reactive-kafka
tests/src/test/scala/akka/kafka/javadsl/ControlSpec.scala
Scala
apache-2.0
3,788
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.examples.streaming import java.io.File import java.nio.charset.Charset import com.google.common.io.Files import org.apache.spark.SparkConf import org.apache.spark.rdd.RDD import org.apache.spark.streaming.{Time, Seconds, StreamingContext} import org.apache.spark.util.IntParam /** * Counts words in text encoded with UTF8 received from the network every second. * * Usage: RecoverableNetworkWordCount <hostname> <port> <checkpoint-directory> <output-file> * <hostname> and <port> describe the TCP server that Spark Streaming would connect to receive * data. <checkpoint-directory> directory to HDFS-compatible file system which checkpoint data * <output-file> file to which the word counts will be appended * * <checkpoint-directory> and <output-file> must be absolute paths * * To run this on your local machine, you need to first run a Netcat server * * `$ nc -lk 9999` * * and run the example as * * `$ ./bin/run-example org.apache.spark.examples.streaming.RecoverableNetworkWordCount \\ * localhost 9999 ~/checkpoint/ ~/out` * * If the directory ~/checkpoint/ does not exist (e.g. running for the first time), it will create * a new StreamingContext (will print "Creating new context" to the console). Otherwise, if * checkpoint data exists in ~/checkpoint/, then it will create StreamingContext from * the checkpoint data. * * Refer to the online documentation for more details. */ object RecoverableNetworkWordCount { def createContext(ip: String, port: Int, outputPath: String, checkpointDirectory: String) : StreamingContext = { // If you do not see this printed, that means the StreamingContext has been loaded // from the new checkpoint println("Creating new context") val outputFile = new File(outputPath) if (outputFile.exists()) outputFile.delete() val sparkConf = new SparkConf().setAppName("RecoverableNetworkWordCount") // Create the context with a 1 second batch size val ssc = new StreamingContext(sparkConf, Seconds(1)) ssc.checkpoint(checkpointDirectory) // Create a socket stream on target ip:port and count the // words in input stream of \\n delimited text (eg. generated by 'nc') val lines = ssc.socketTextStream(ip, port) val words = lines.flatMap(_.split(" ")) val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _) wordCounts.foreachRDD((rdd: RDD[(String, Int)], time: Time) => { val counts = "Counts at time " + time + " " + rdd.collect().mkString("[", ", ", "]") println(counts) println("Appending to " + outputFile.getAbsolutePath) Files.append(counts + "\\n", outputFile, Charset.defaultCharset()) }) ssc } def main(args: Array[String]) { if (args.length != 4) { System.err.println("You arguments were " + args.mkString("[", ", ", "]")) System.err.println( """ |Usage: RecoverableNetworkWordCount <hostname> <port> <checkpoint-directory> | <output-file>. <hostname> and <port> describe the TCP server that Spark | Streaming would connect to receive data. <checkpoint-directory> directory to | HDFS-compatible file system which checkpoint data <output-file> file to which the | word counts will be appended | |In local mode, <master> should be 'local[n]' with n > 1 |Both <checkpoint-directory> and <output-file> must be absolute paths """.stripMargin ) System.exit(1) } val Array(ip, IntParam(port), checkpointDirectory, outputPath) = args val ssc = StreamingContext.getOrCreate(checkpointDirectory, () => { createContext(ip, port, outputPath, checkpointDirectory) }) ssc.start() ssc.awaitTermination() } }
shenbaise/mltoy
src/main/scala/org/apache/spark/examples/streaming/RecoverableNetworkWordCount.scala
Scala
apache-2.0
4,612
package learn.danipl.model /** * Created by Daniel on 07/09/2017. */ case class SimpleRecord(id: Long, body: Array[Byte])
danipl/LearnScalaProject
src/main/scala/learn/danipl/model/SimpleRecord.scala
Scala
gpl-3.0
126
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.deploy.master.ui import java.io.DataOutputStream import java.net.{HttpURLConnection, URL} import java.nio.charset.StandardCharsets import java.util.Date import scala.collection.mutable.HashMap import org.mockito.Mockito.{mock, times, verify, when} import org.scalatest.BeforeAndAfterAll import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite} import org.apache.spark.deploy.DeployMessages.{KillDriverResponse, RequestKillDriver} import org.apache.spark.deploy.DeployTestUtils._ import org.apache.spark.deploy.master._ import org.apache.spark.rpc.{RpcEndpointRef, RpcEnv} class MasterWebUISuite extends SparkFunSuite with BeforeAndAfterAll { val conf = new SparkConf val securityMgr = new SecurityManager(conf) val rpcEnv = mock(classOf[RpcEnv]) val master = mock(classOf[Master]) val masterEndpointRef = mock(classOf[RpcEndpointRef]) when(master.securityMgr).thenReturn(securityMgr) when(master.conf).thenReturn(conf) when(master.rpcEnv).thenReturn(rpcEnv) when(master.self).thenReturn(masterEndpointRef) val masterWebUI = new MasterWebUI(master, 0) override def beforeAll() { super.beforeAll() masterWebUI.bind() } override def afterAll() { masterWebUI.stop() super.afterAll() } test("kill application") { val appDesc = createAppDesc() // use new start date so it isn't filtered by UI val activeApp = new ApplicationInfo( new Date().getTime, "app-0", appDesc, new Date(), null, Int.MaxValue) when(master.idToApp).thenReturn(HashMap[String, ApplicationInfo]((activeApp.id, activeApp))) val url = s"http://localhost:${masterWebUI.boundPort}/app/kill/" val body = convPostDataToString(Map(("id", activeApp.id), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify the master was called to remove the active app verify(master, times(1)).removeApplication(activeApp, ApplicationState.KILLED) } test("kill driver") { val activeDriverId = "driver-0" val url = s"http://localhost:${masterWebUI.boundPort}/driver/kill/" val body = convPostDataToString(Map(("id", activeDriverId), ("terminate", "true"))) val conn = sendHttpRequest(url, "POST", body) conn.getResponseCode // Verify that master was asked to kill driver with the correct id verify(masterEndpointRef, times(1)).ask[KillDriverResponse](RequestKillDriver(activeDriverId)) } private def convPostDataToString(data: Map[String, String]): String = { (for ((name, value) <- data) yield s"$name=$value").mkString("&") } /** * Send an HTTP request to the given URL using the method and the body specified. * Return the connection object. */ private def sendHttpRequest( url: String, method: String, body: String = ""): HttpURLConnection = { val conn = new URL(url).openConnection().asInstanceOf[HttpURLConnection] conn.setRequestMethod(method) if (body.nonEmpty) { conn.setDoOutput(true) conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") conn.setRequestProperty("Content-Length", Integer.toString(body.length)) val out = new DataOutputStream(conn.getOutputStream) out.write(body.getBytes(StandardCharsets.UTF_8)) out.close() } conn } }
bravo-zhang/spark
core/src/test/scala/org/apache/spark/deploy/master/ui/MasterWebUISuite.scala
Scala
apache-2.0
4,136
package com.redis import java.io._ import java.net.{Socket, InetSocketAddress} import serialization.Parse.parseStringSafe trait IO extends Log { val host: String val port: Int var socket: Socket = _ var out: OutputStream = _ var in: InputStream = _ var db: Int = _ def connected = { socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected() && !socket.isInputShutdown() && !socket.isOutputShutdown(); } def reconnect = { disconnect && connect } // Connects the socket, and sets the input and output streams. def connect: Boolean = { try { socket = new Socket(host, port) socket.setSoTimeout(0) socket.setKeepAlive(true) socket.setTcpNoDelay(true) out = socket.getOutputStream in = new BufferedInputStream(socket.getInputStream) true } catch { case x: Throwable => clearFd throw new RuntimeException(x) } } // Disconnects the socket. def disconnect: Boolean = { try { socket.close out.close in.close clearFd true } catch { case x: Throwable => false } } def clearFd = { socket = null out = null in = null } // Wrapper for the socket write operation. def write_to_socket(data: Array[Byte])(op: OutputStream => Unit) = op(out) // Writes data to a socket using the specified block. def write(data: Array[Byte]) = { ifDebug("C: " + parseStringSafe(data)) if (!connected) connect; write_to_socket(data){ os => try { os.write(data) os.flush } catch { case x: Throwable => throw new RedisConnectionException("connection is closed. write error") } } } private val crlf = List(13,10) def readLine: Array[Byte] = { if(!connected) connect var delimiter = crlf var found: List[Int] = Nil var build = new scala.collection.mutable.ArrayBuilder.ofByte while (delimiter != Nil) { val next = in.read if (next < 0) return null if (next == delimiter.head) { found ::= delimiter.head delimiter = delimiter.tail } else { if (found != Nil) { delimiter = crlf build ++= found.reverseMap(_.toByte) found = Nil } build += next.toByte } } build.result } def readCounted(count: Int): Array[Byte] = { if(!connected) connect val arr = new Array[Byte](count) var cur = 0 while (cur < count) { cur += in.read(arr, cur, count - cur) } arr } }
Tjoene/thesis
Case_Programs/scala-redis-2.9-pre-scala-2.10/src/main/scala/com/redis/IO.scala
Scala
gpl-2.0
2,572
package stefansavev.demo.hyperloglog.hashing trait Hasher { def hash(obj: Long): Long }
dvgodoy/HashingAndSketching
out/production/hyperloglog/stefansavev/demo/hyperloglog/hashing/Hasher.scala
Scala
apache-2.0
91
package dsl import ch.epfl.yinyang._ import ch.epfl.yinyang.typetransformers._ import scala.language.experimental.macros import scala.reflect.macros.blackbox.Context package object la { def la[T](block: => T): T = macro implementations.liftRep[T] def laDebug[T](block: => T): T = macro implementations.liftRepDebug[T] object implementations { def liftRep[T](c: Context)(block: c.Expr[T]): c.Expr[T] = YYTransformer[c.type, T](c)( "dsl.la.rep.VectorDSL", new GenericTypeTransformer[c.type](c) { override val IRType = "R" }, None, None, Map( "direct" -> false, "virtualizeFunctions" -> true, "virtualizeValDef" -> true, "debug" -> 0, "restrictLanguage" -> false, "ascribeTerms" -> false), None)(block) def liftRepDebug[T](c: Context)(block: c.Expr[T]): c.Expr[T] = YYTransformer[c.type, T](c)( "dsl.la.rep.VectorDSL", new GenericTypeTransformer[c.type](c) { override val IRType = "R" }, None, None, Map( "direct" -> false, "virtualizeFunctions" -> true, "virtualizeValDef" -> true, "debug" -> 3, "restrictLanguage" -> false, "ascribeTerms" -> false), None)(block) } }
scala-yinyang/scala-yinyang
components/examples/src/la/package.scala
Scala
bsd-3-clause
1,335
package demo.pages import japgolly.scalajs.react._ import japgolly.scalajs.react.vdom.prefix_<^._ import com.acework.js.components.bootstrap._ import demo.examples._ import org.scalajs.dom.raw.{HTMLDocument, HTMLElement} import scala.scalajs.js.{UndefOr, undefined} import org.scalajs.dom.{Event, document, window} import Utils._ /** * Created by weiyin on 16/03/15. */ object Components { val alerts = <.div( PageHeader(<.h1("Alert messages ", <.small("alert"))), <.h3("Example Alerts"), Alert(Alert.Alert(bsStyle = Styles.warning), <.strong("Holy guacamole!"), "Best check yo self, you're not looking too good."), <.h3("closable alert"), AlertDismissable(), <.h3("Auto hide alert"), AlertAutoDismissable(), Alert(Alert.Alert(bsStyle = Styles.success), "Well done! You successfully read this important alert message."), Alert(Alert.Alert(bsStyle = Styles.info), "Heads up! This alert needs your attention, but it's not super important."), Alert(Alert.Alert(bsStyle = Styles.warning), "Warning! Better check yourself, you're not looking too good."), Alert(Alert.Alert(bsStyle = Styles.danger), "Oh snap! Change a few things up and try submitting again.") ) case class State(activeNavItemHref: UndefOr[String], navOffsetTop: UndefOr[Int], navOffsetBottom: UndefOr[Int]) class Backend(scope: BackendScope[Unit, State]) { def handleNavItemSelect(args: Seq[UndefOr[String]]) = { if (args.length > 1) { if (args(1).isDefined) { val href = args(1).get scope.modState(_.copy(activeNavItemHref = href)) window.location.href = href } } } def onComponentDidMount() = { val elem: TopNode = sideNavRef(scope).get.getDOMNode() val sideNavOffsetTop = getOffset(elem).top val sideNavMarginTop = elem.asInstanceOf[HTMLElement].ownerDocument.asInstanceOf[HTMLDocument].defaultView.getComputedStyle(elem, "").marginTop.toInt val topNavHeight = topNavRef(scope).get.getDOMNode().asInstanceOf[HTMLElement].offsetHeight val navOffsetBottom = footerRef(scope).get.getDOMNode().asInstanceOf[HTMLElement].offsetHeight.toInt scope.modState(s => s.copy(navOffsetTop = (sideNavOffsetTop - topNavHeight - sideNavMarginTop).toInt, navOffsetBottom = navOffsetBottom)) } } val footerRef = Ref("footerNav") val sideNavRef = Ref("sideNav") val topNavRef = Ref("topNav") val content = ReactComponentB[Unit]("Components") .initialState(State(undefined, undefined, undefined)) .backend(new Backend(_)) .render((P, C, S, B) => { <.div( //NavMain.withRef(topNavRef)(NavMain.NavMain(activePage="components")), ExamplePageHeader.ExamplePageHeader(title = "Components", subTitle = "")(), <.div(^.className := "container bs-docs-container", <.div(^.className := "row", <.div(^.className := "col-md-9", ^.role := "main", <.div( Buttons.content() , ButtonGroups.content() , DropdownButtons.content() , Panels.content() , Modals.content() , Tooltips.content() , Popovers.content() , Progressbars.content() , Navs.content() , Navbars.content() , Tabs.content() , Pagers.content() , Alerts.content() , Carousels.content() , Grids.content() , ListGroups.content() , Labels.content() , Badges.content() , Jumbotrons.content() , PageHeaders.content() , Wells.content() , Glyphicons.content() , Tables.content() , Inputs.content() ) ), <.div(^.className := "col-md-3", Affix.Affix(addClasses = "bs-docs-sidebar hidden-print", role = "complementary": UndefOr[String], offset = 0.0, offsetTop = 0.0, offsetBottom = 0.0)( Nav.withRef("sideRef")(Nav.Nav(addClasses = "bs-docs-sidenav", activeHref = "", onSelect = (args: Seq[UndefOr[String]]) => B.handleNavItemSelect(args)), SubNav.withKey(1)(SubNav.SubNav(href = "#buttons", text = "Buttons"), NavItem.withKey(2)(NavItem.NavItem(href = "#btn-groups"), "Button groups") , NavItem.withKey(3)(NavItem.NavItem(href = "#btn-dropdowns"), "Button dropdowns") ) , NavItem.withKey(4)(NavItem.NavItem(href = "#panels"), "Panels") , NavItem.withKey(5)(NavItem.NavItem(href = "#modals"), "Modals") , NavItem.withKey(6)(NavItem.NavItem(href = "#tooltips"), "Tooltips") , NavItem.withKey(7)(NavItem.NavItem(href = "#popovers"), "Popovers") , NavItem.withKey(8)(NavItem.NavItem(href = "#progressbars"), "Progress bars") , NavItem.withKey(9)(NavItem.NavItem(href = "#navs"), "Navs") , NavItem.withKey(10)(NavItem.NavItem(href = "#navbars"), "Navbars") , NavItem.withKey(11)(NavItem.NavItem(href = "#tabs"), "Togglable tabs") , NavItem.withKey(12)(NavItem.NavItem(href = "#pagers"), "Pager") , NavItem.withKey(13)(NavItem.NavItem(href = "#alerts"), "Alerts") , NavItem.withKey(14)(NavItem.NavItem(href = "#carousels"), "Carousels") , NavItem.withKey(15)(NavItem.NavItem(href = "#grids"), "Grids") , NavItem.withKey(16)(NavItem.NavItem(href = "#listgroup"), "List group") , NavItem.withKey(17)(NavItem.NavItem(href = "#labels"), "Labels") , NavItem.withKey(18)(NavItem.NavItem(href = "#badges"), "Badges") , NavItem.withKey(19)(NavItem.NavItem(href = "#jumbotron"), "Jumbotron") , NavItem.withKey(20)(NavItem.NavItem(href = "#page-header"), "Page Header") , NavItem.withKey(21)(NavItem.NavItem(href = "#wells"), "Wells") , NavItem.withKey(22)(NavItem.NavItem(href = "#glyphicons"), "Glyphicons") , NavItem.withKey(23)(NavItem.NavItem(href = "#tables"), "Tables") , NavItem.withKey(24)(NavItem.NavItem(href = "#inputs"), "Input") ) ) ) ) ), ExamplePageFooter() ) }).buildU }
weiyinteo/scalajs-react-bootstrap
demo/src/main/scala/demo/pages/Components.scala
Scala
mit
6,463
package com.giyeok.jparser.visualize import org.eclipse.swt.graphics.Font import org.eclipse.jface.resource.JFaceResources import org.eclipse.swt.SWT import org.eclipse.draw2d.MarginBorder import org.eclipse.draw2d.Figure import org.eclipse.draw2d.ColorConstants import org.eclipse.draw2d.LineBorder trait VisualizeResources[Fig] { val default12Font: Font val fixedWidth12Font: Font val italic14Font: Font val bold14Font: Font val smallFont: Font val smallerFont: Font val nodeFigureGenerators: NodeFigureGenerators[Fig] } object BasicVisualizeResources extends VisualizeResources[Figure] { val defaultFontName = JFaceResources.getTextFont.getFontData.head.getName val default12Font = new Font(null, defaultFontName, 12, SWT.NONE) val fixedWidth12Font = new Font(null, defaultFontName, 12, SWT.NONE) val italic14Font = new Font(null, defaultFontName, 14, SWT.ITALIC) val bold14Font = new Font(null, defaultFontName, 14, SWT.BOLD) val smallFont = new Font(null, defaultFontName, 8, SWT.NONE) val smallerFont = new Font(null, defaultFontName, 6, SWT.NONE) val default10Font = new Font(null, defaultFontName, 10, SWT.NONE) val nonterminalFont = new Font(null, defaultFontName, 12, SWT.BOLD) val terminalFont = new Font(null, defaultFontName, 12, SWT.NONE) val nodeFigureGenerators = { val figureGenerator: FigureGenerator.Generator[Figure] = FigureGenerator.draw2d.Generator val figureAppearances = new FigureGenerator.Appearances[Figure] { val default = FigureGenerator.draw2d.FontAppearance(default10Font, ColorConstants.black) val nonterminal = FigureGenerator.draw2d.FontAppearance(nonterminalFont, ColorConstants.blue) val terminal = FigureGenerator.draw2d.FontAppearance(terminalFont, ColorConstants.red) override val small = FigureGenerator.draw2d.FontAppearance(new Font(null, defaultFontName, 8, SWT.NONE), ColorConstants.gray) override val kernelDot = FigureGenerator.draw2d.FontAppearance(new Font(null, defaultFontName, 12, SWT.NONE), ColorConstants.green) override val symbolBorder = FigureGenerator.draw2d.BorderAppearance(new LineBorder(ColorConstants.lightGray)) override val hSymbolBorder = new FigureGenerator.draw2d.ComplexAppearance( FigureGenerator.draw2d.BorderAppearance(new MarginBorder(0, 1, 1, 1)), FigureGenerator.draw2d.NewFigureAppearance(), FigureGenerator.draw2d.BorderAppearance(new FigureGenerator.draw2d.PartialLineBorder(ColorConstants.lightGray, 1, false, true, true, true))) override val vSymbolBorder = new FigureGenerator.draw2d.ComplexAppearance( FigureGenerator.draw2d.BorderAppearance(new MarginBorder(1, 0, 1, 1)), FigureGenerator.draw2d.NewFigureAppearance(), FigureGenerator.draw2d.BorderAppearance(new FigureGenerator.draw2d.PartialLineBorder(ColorConstants.lightGray, 1, true, false, true, true))) override val wsBorder = new FigureGenerator.draw2d.ComplexAppearance( FigureGenerator.draw2d.BorderAppearance(new MarginBorder(0, 1, 1, 1)), FigureGenerator.draw2d.NewFigureAppearance(), FigureGenerator.draw2d.BorderAppearance(new FigureGenerator.draw2d.PartialLineBorder(ColorConstants.lightBlue, 1, false, true, true, true)), FigureGenerator.draw2d.BackgroundAppearance(ColorConstants.lightGray)) override val joinHighlightBorder = new FigureGenerator.draw2d.ComplexAppearance( FigureGenerator.draw2d.BorderAppearance(new MarginBorder(1, 1, 1, 1)), FigureGenerator.draw2d.NewFigureAppearance(), FigureGenerator.draw2d.BorderAppearance(new LineBorder(ColorConstants.red))) } val symbolFigureGenerator = new SymbolFigureGenerator(figureGenerator, figureAppearances) new NodeFigureGenerators(figureGenerator, figureAppearances, symbolFigureGenerator) } }
Joonsoo/moon-parser
visualize/src/main/scala/com/giyeok/jparser/visualize/VisualizeResources.scala
Scala
mit
4,166
package service import model._ import scala.slick.driver.H2Driver.simple._ import Database.threadLocalSession import util.JGitUtil trait RepositoryService { self: AccountService => import RepositoryService._ /** * Creates a new repository. * * @param repositoryName the repository name * @param userName the user name of the repository owner * @param description the repository description * @param isPrivate the repository type (private is true, otherwise false) * @param originRepositoryName specify for the forked repository. (default is None) * @param originUserName specify for the forked repository. (default is None) */ def createRepository(repositoryName: String, userName: String, description: Option[String], isPrivate: Boolean, originRepositoryName: Option[String] = None, originUserName: Option[String] = None, parentRepositoryName: Option[String] = None, parentUserName: Option[String] = None): Unit = { Repositories insert Repository( userName = userName, repositoryName = repositoryName, isPrivate = isPrivate, description = description, defaultBranch = "master", registeredDate = currentDate, updatedDate = currentDate, lastActivityDate = currentDate, originUserName = originUserName, originRepositoryName = originRepositoryName, parentUserName = parentUserName, parentRepositoryName = parentRepositoryName) IssueId insert (userName, repositoryName, 0) } def renameRepository(oldUserName: String, oldRepositoryName: String, newUserName: String, newRepositoryName: String): Unit = { (Query(Repositories) filter { t => t.byRepository(oldUserName, oldRepositoryName) } firstOption).map { repository => Repositories insert repository.copy(userName = newUserName, repositoryName = newRepositoryName) val webHooks = Query(WebHooks ).filter(_.byRepository(oldUserName, oldRepositoryName)).list val milestones = Query(Milestones ).filter(_.byRepository(oldUserName, oldRepositoryName)).list val issueId = Query(IssueId ).filter(_.byRepository(oldUserName, oldRepositoryName)).list val issues = Query(Issues ).filter(_.byRepository(oldUserName, oldRepositoryName)).list val pullRequests = Query(PullRequests ).filter(_.byRepository(oldUserName, oldRepositoryName)).list val labels = Query(Labels ).filter(_.byRepository(oldUserName, oldRepositoryName)).list val issueComments = Query(IssueComments).filter(_.byRepository(oldUserName, oldRepositoryName)).list val issueLabels = Query(IssueLabels ).filter(_.byRepository(oldUserName, oldRepositoryName)).list val collaborators = Query(Collaborators).filter(_.byRepository(oldUserName, oldRepositoryName)).list val commitLog = Query(CommitLog ).filter(_.byRepository(oldUserName, oldRepositoryName)).list val activities = Query(Activities ).filter(_.byRepository(oldUserName, oldRepositoryName)).list Repositories.filter { t => (t.originUserName is oldUserName.bind) && (t.originRepositoryName is oldRepositoryName.bind) }.map { t => t.originUserName ~ t.originRepositoryName }.update(newUserName, newRepositoryName) Repositories.filter { t => (t.parentUserName is oldUserName.bind) && (t.parentRepositoryName is oldRepositoryName.bind) }.map { t => t.originUserName ~ t.originRepositoryName }.update(newUserName, newRepositoryName) PullRequests.filter { t => t.requestRepositoryName is oldRepositoryName.bind }.map { t => t.requestUserName ~ t.requestRepositoryName }.update(newUserName, newRepositoryName) deleteRepository(oldUserName, oldRepositoryName) WebHooks .insertAll(webHooks .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) Milestones .insertAll(milestones .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) IssueId .insertAll(issueId .map(_.copy(_1 = newUserName, _2 = newRepositoryName)) :_*) Issues .insertAll(issues .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) PullRequests .insertAll(pullRequests .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) IssueComments .insertAll(issueComments .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) Labels .insertAll(labels .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) IssueLabels .insertAll(issueLabels .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) Collaborators .insertAll(collaborators .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) CommitLog .insertAll(commitLog .map(_.copy(_1 = newUserName, _2 = newRepositoryName)) :_*) Activities .insertAll(activities .map(_.copy(userName = newUserName, repositoryName = newRepositoryName)) :_*) // Update activity messages val updateActivities = Activities.filter { t => (t.message like s"%:${oldUserName}/${oldRepositoryName}]%") || (t.message like s"%:${oldUserName}/${oldRepositoryName}#%") }.map { t => t.activityId ~ t.message }.list updateActivities.foreach { case (activityId, message) => Activities.filter(_.activityId is activityId.bind).map(_.message).update( message .replace(s"[repo:${oldUserName}/${oldRepositoryName}]" ,s"[repo:${newUserName}/${newRepositoryName}]") .replace(s"[branch:${oldUserName}/${oldRepositoryName}#" ,s"[branch:${newUserName}/${newRepositoryName}#") .replace(s"[tag:${oldUserName}/${oldRepositoryName}#" ,s"[tag:${newUserName}/${newRepositoryName}#") .replace(s"[pullreq:${oldUserName}/${oldRepositoryName}#",s"[pullreq:${newUserName}/${newRepositoryName}#") .replace(s"[issue:${oldUserName}/${oldRepositoryName}#" ,s"[issue:${newUserName}/${newRepositoryName}#") ) } } } def deleteRepository(userName: String, repositoryName: String): Unit = { Activities .filter(_.byRepository(userName, repositoryName)).delete CommitLog .filter(_.byRepository(userName, repositoryName)).delete Collaborators .filter(_.byRepository(userName, repositoryName)).delete IssueLabels .filter(_.byRepository(userName, repositoryName)).delete Labels .filter(_.byRepository(userName, repositoryName)).delete IssueComments .filter(_.byRepository(userName, repositoryName)).delete PullRequests .filter(_.byRepository(userName, repositoryName)).delete Issues .filter(_.byRepository(userName, repositoryName)).delete IssueId .filter(_.byRepository(userName, repositoryName)).delete Milestones .filter(_.byRepository(userName, repositoryName)).delete WebHooks .filter(_.byRepository(userName, repositoryName)).delete Repositories .filter(_.byRepository(userName, repositoryName)).delete } /** * Returns the repository names of the specified user. * * @param userName the user name of repository owner * @return the list of repository names */ def getRepositoryNamesOfUser(userName: String): List[String] = Query(Repositories) filter(_.userName is userName.bind) map (_.repositoryName) list /** * Returns the specified repository information. * * @param userName the user name of the repository owner * @param repositoryName the repository name * @param baseUrl the base url of this application * @return the repository information */ def getRepository(userName: String, repositoryName: String, baseUrl: String): Option[RepositoryInfo] = { (Query(Repositories) filter { t => t.byRepository(userName, repositoryName) } firstOption) map { repository => // for getting issue count and pull request count val issues = Query(Issues).filter { t => t.byRepository(repository.userName, repository.repositoryName) && (t.closed is false.bind) }.map(_.pullRequest).list new RepositoryInfo( JGitUtil.getRepositoryInfo(repository.userName, repository.repositoryName, baseUrl), repository, issues.size, issues.filter(_ == true).size, getForkedCount( repository.originUserName.getOrElse(repository.userName), repository.originRepositoryName.getOrElse(repository.repositoryName) ), getRepositoryManagers(repository.userName)) } } def getUserRepositories(userName: String, baseUrl: String): List[RepositoryInfo] = { Query(Repositories).filter { t1 => (t1.userName is userName.bind) || (Query(Collaborators).filter { t2 => t2.byRepository(t1.userName, t1.repositoryName) && (t2.collaboratorName is userName.bind)} exists) }.sortBy(_.lastActivityDate desc).list.map{ repository => new RepositoryInfo( JGitUtil.getRepositoryInfo(repository.userName, repository.repositoryName, baseUrl), repository, getForkedCount( repository.originUserName.getOrElse(repository.userName), repository.originRepositoryName.getOrElse(repository.repositoryName) ), getRepositoryManagers(repository.userName)) } } /** * Returns the list of visible repositories for the specified user. * If repositoryUserName is given then filters results by repository owner. * * @param loginAccount the logged in account * @param baseUrl the base url of this application * @param repositoryUserName the repository owner (if None then returns all repositories which are visible for logged in user) * @return the repository information which is sorted in descending order of lastActivityDate. */ def getVisibleRepositories(loginAccount: Option[Account], baseUrl: String, repositoryUserName: Option[String] = None): List[RepositoryInfo] = { (loginAccount match { // for Administrators case Some(x) if(x.isAdmin) => Query(Repositories) // for Normal Users case Some(x) if(!x.isAdmin) => Query(Repositories) filter { t => (t.isPrivate is false.bind) || (t.userName is x.userName) || (Query(Collaborators).filter { t2 => t2.byRepository(t.userName, t.repositoryName) && (t2.collaboratorName is x.userName.bind)} exists) } // for Guests case None => Query(Repositories) filter(_.isPrivate is false.bind) }).filter { t => repositoryUserName.map { userName => t.userName is userName.bind } getOrElse ConstColumn.TRUE }.sortBy(_.lastActivityDate desc).list.map{ repository => new RepositoryInfo( JGitUtil.getRepositoryInfo(repository.userName, repository.repositoryName, baseUrl), repository, getForkedCount( repository.originUserName.getOrElse(repository.userName), repository.originRepositoryName.getOrElse(repository.repositoryName) ), getRepositoryManagers(repository.userName)) } } private def getRepositoryManagers(userName: String): Seq[String] = if(getAccountByUserName(userName).exists(_.isGroupAccount)){ getGroupMembers(userName).collect { case x if(x.isManager) => x.userName } } else { Seq(userName) } /** * Updates the last activity date of the repository. */ def updateLastActivityDate(userName: String, repositoryName: String): Unit = Repositories.filter(_.byRepository(userName, repositoryName)).map(_.lastActivityDate).update(currentDate) /** * Save repository options. */ def saveRepositoryOptions(userName: String, repositoryName: String, description: Option[String], defaultBranch: String, isPrivate: Boolean): Unit = Repositories.filter(_.byRepository(userName, repositoryName)) .map { r => r.description.? ~ r.defaultBranch ~ r.isPrivate ~ r.updatedDate } .update (description, defaultBranch, isPrivate, currentDate) /** * Add collaborator to the repository. * * @param userName the user name of the repository owner * @param repositoryName the repository name * @param collaboratorName the collaborator name */ def addCollaborator(userName: String, repositoryName: String, collaboratorName: String): Unit = Collaborators insert(Collaborator(userName, repositoryName, collaboratorName)) /** * Remove collaborator from the repository. * * @param userName the user name of the repository owner * @param repositoryName the repository name * @param collaboratorName the collaborator name */ def removeCollaborator(userName: String, repositoryName: String, collaboratorName: String): Unit = Collaborators.filter(_.byPrimaryKey(userName, repositoryName, collaboratorName)).delete /** * Remove all collaborators from the repository. * * @param userName the user name of the repository owner * @param repositoryName the repository name */ def removeCollaborators(userName: String, repositoryName: String): Unit = Collaborators.filter(_.byRepository(userName, repositoryName)).delete /** * Returns the list of collaborators name which is sorted with ascending order. * * @param userName the user name of the repository owner * @param repositoryName the repository name * @return the list of collaborators name */ def getCollaborators(userName: String, repositoryName: String): List[String] = Query(Collaborators).filter(_.byRepository(userName, repositoryName)).sortBy(_.collaboratorName).map(_.collaboratorName).list def hasWritePermission(owner: String, repository: String, loginAccount: Option[Account]): Boolean = { loginAccount match { case Some(a) if(a.isAdmin) => true case Some(a) if(a.userName == owner) => true case Some(a) if(getCollaborators(owner, repository).contains(a.userName)) => true case _ => false } } private def getForkedCount(userName: String, repositoryName: String): Int = Query(Repositories.filter { t => (t.originUserName is userName.bind) && (t.originRepositoryName is repositoryName.bind) }.length).first def getForkedRepositories(userName: String, repositoryName: String): List[(String, String)] = Query(Repositories).filter { t => (t.originUserName is userName.bind) && (t.originRepositoryName is repositoryName.bind) } .sortBy(_.userName asc).map(t => t.userName ~ t.repositoryName).list } object RepositoryService { case class RepositoryInfo(owner: String, name: String, httpUrl: String, repository: Repository, issueCount: Int, pullCount: Int, commitCount: Int, forkedCount: Int, branchList: Seq[String], tags: Seq[util.JGitUtil.TagInfo], managers: Seq[String]){ lazy val host = """^https?://(.+?)(:\d+)?/""".r.findFirstMatchIn(httpUrl).get.group(1) def sshUrl(port: Int, userName: String) = s"ssh://${userName}@${host}:${port}/${owner}/${name}.git" /** * Creates instance with issue count and pull request count. */ def this(repo: JGitUtil.RepositoryInfo, model: Repository, issueCount: Int, pullCount: Int, forkedCount: Int, managers: Seq[String]) = this(repo.owner, repo.name, repo.url, model, issueCount, pullCount, repo.commitCount, forkedCount, repo.branchList, repo.tags, managers) /** * Creates instance without issue count and pull request count. */ def this(repo: JGitUtil.RepositoryInfo, model: Repository, forkedCount: Int, managers: Seq[String]) = this(repo.owner, repo.name, repo.url, model, 0, 0, repo.commitCount, forkedCount, repo.branchList, repo.tags, managers) } case class RepositoryTreeNode(owner: String, name: String, children: List[RepositoryTreeNode]) }
emag/gitbucket
src/main/scala/service/RepositoryService.scala
Scala
apache-2.0
15,954
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2021 Andre White. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.truthencode.ddo.model.feats import io.truthencode.ddo.model.classes.HeroicCharacterClass import io.truthencode.ddo.model.classes.HeroicCharacterClass.Monk import io.truthencode.ddo.support.requisite.{FeatRequisiteImpl, FreeFeat, GrantsToClass} /** * You can avoid even magical and unusual attacks with great agility. When you attempt a Reflex save * against an effect that normally does half damage when saved against, you suffer no damage if you * successfully save and half damage even if you fail. Improved Evasion can be used only if the * character is wearing light armor or no armor, is not wielding a heavy shield or tower shield, and * is not heavily encumbered. A helpless character does not gain the benefit of improved evasion. */ trait ImprovedEvasion extends FeatRequisiteImpl with Passive with GrantsToClass with RogueOptionalAbility with FreeFeat { override def grantToClass: Seq[(HeroicCharacterClass, Int)] = rogueOptionMatrix :+ (Monk, 9) }
adarro/ddo-calc
subprojects/common/ddo-core/src/main/scala/io/truthencode/ddo/model/feats/ImprovedEvasion.scala
Scala
apache-2.0
1,665
package battle import battle.GameBoard.Coordinate class GameBoard(val width: Int, val height: Int) { private val grid = Array.ofDim[AnyRef](width, height) def put(obj: AnyRef, coordinate: Coordinate): Unit = { grid(coordinate.x)(coordinate.y) = obj } def get(coordinate: Coordinate): Option[AnyRef] = { if (grid(coordinate.x)(coordinate.y) == null) None else Some(grid(coordinate.x)(coordinate.y)) } def move(obj: AnyRef, newCoordinate: Coordinate): Unit = { val coordinate = find(obj) grid(coordinate.x)(coordinate.y) = null grid(newCoordinate.x)(newCoordinate.y) = obj } def find(obj: AnyRef) : Coordinate = { val col = for { xCoord <- 0 until width yCoord <- 0 until height if grid(xCoord)(yCoord) == obj } yield Coordinate(xCoord, yCoord) col(0) } } object GameBoard { def apply(width: Int, height: Int) = new GameBoard(width, height) case class Coordinate(x: Int, y: Int) }
bbalser/gladiator-actors
src/main/scala/battle/GameBoard.scala
Scala
cc0-1.0
966
import scala.quoted.* trait IsExpr { type Underlying } val foo: IsExpr = ??? def g()(using Quotes): Unit = { val a = Type.of[foo.Underlying] () }
dotty-staging/dotty
tests/pos-macros/i7048b.scala
Scala
apache-2.0
155
package java.net import java.io.UnsupportedEncodingException import java.nio.{CharBuffer, ByteBuffer} import java.nio.charset.{Charset, MalformedInputException} object URLDecoder { @Deprecated def decode(s: String): String = decodeImpl(s, Charset.defaultCharset) def decode(s: String, enc: String): String = { /* An exception is thrown only if the * character encoding needs to be consulted */ lazy val charset = { if (!Charset.isSupported(enc)) throw new UnsupportedEncodingException(enc) else Charset.forName(enc) } decodeImpl(s, charset) } private def decodeImpl(s: String, charset: => Charset): String = { val len = s.length lazy val charsetDecoder = charset.newDecoder() lazy val byteBuffer = ByteBuffer.allocate(len / 3) val charBuffer = CharBuffer.allocate(len) def throwIllegalHex() = { throw new IllegalArgumentException( "URLDecoder: Illegal hex characters in escape (%) pattern") } var i = 0 while (i < len) { s.charAt(i) match { case '+' => charBuffer.append(' ') i += 1 case '%' if i + 3 > len => throwIllegalHex() case '%' => val decoder = charsetDecoder val buffer = byteBuffer buffer.clear() decoder.reset() while (i + 3 <= len && s.charAt(i) == '%') { val c1 = Character.digit(s.charAt(i + 1), 16) val c2 = Character.digit(s.charAt(i + 2), 16) if (c1 < 0 || c2 < 0) throwIllegalHex() buffer.put(((c1 << 4) + c2).toByte) i += 3 } buffer.flip() val decodeResult = decoder.decode(buffer, charBuffer, true) val flushResult = decoder.flush(charBuffer) if (decodeResult.isError || flushResult.isError) throwIllegalHex() case c => charBuffer.append(c) i += 1 } } charBuffer.flip() charBuffer.toString } }
mdedetrich/scala-js
javalib/src/main/scala/java/net/URLDecoder.scala
Scala
bsd-3-clause
2,033
// Compiles with no options // Compiles with -Ydebug -Ydisable-unreachable-prevention // Crashes with -Ydebug trait Bippy { 3 match { case 3 => } }
yusuke2255/dotty
tests/untried/pos/t7427.scala
Scala
bsd-3-clause
148
/** * Copyright (C) 2014 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 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 Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.xml import org.junit.Test import org.orbeon.oxf.fr.persistence.relational.rest.RequestReader import org.orbeon.oxf.test.ResourceManagerTestBase import org.orbeon.oxf.xml.JXQName._ import org.orbeon.oxf.xml.XMLParsing.ParserConfiguration._ import org.orbeon.scaxon.DocumentAndElementsCollector import org.orbeon.scaxon.SAXEvents._ import org.scalatest.junit.AssertionsForJUnit class FormRunnerFilterReceiverTest extends ResourceManagerTestBase with AssertionsForJUnit { @Test def resultingEvents(): Unit = { val collector = new DocumentAndElementsCollector // Test extraction of the Form Runner <metadata> element val metadataFilter = new FilterReceiver( collector, RequestReader.isMetadataElement ) XMLParsing.urlToSAX("oxf:/org/orbeon/oxf/fr/form-with-metadata.xhtml", metadataFilter, XINCLUDE_ONLY, false) val XMLLang = JXQName("http://www.w3.org/XML/1998/namespace" β†’ "lang") val Operations = JXQName("operations") val expected = List( StartDocument, StartPrefixMapping("sql", "http://orbeon.org/oxf/xml/sql"), StartPrefixMapping("fr", "http://orbeon.org/oxf/xml/form-runner"), StartPrefixMapping("ev", "http://www.w3.org/2001/xml-events"), StartPrefixMapping("xxf", "http://orbeon.org/oxf/xml/xforms"), StartPrefixMapping("xs", "http://www.w3.org/2001/XMLSchema"), StartPrefixMapping("xh", "http://www.w3.org/1999/xhtml"), StartPrefixMapping("exf", "http://www.exforms.org/exf/1-0"), StartPrefixMapping("xml", "http://www.w3.org/XML/1998/namespace"), StartPrefixMapping("saxon", "http://saxon.sf.net/"), StartPrefixMapping("soap", "http://schemas.xmlsoap.org/soap/envelope/"), StartPrefixMapping("fb", "http://orbeon.org/oxf/xml/form-builder"), StartPrefixMapping("xxi", "http://orbeon.org/oxf/xml/xinclude"), StartPrefixMapping("xi", "http://www.w3.org/2001/XInclude"), StartPrefixMapping("xsi", "http://www.w3.org/2001/XMLSchema-instance"), StartPrefixMapping("xf", "http://www.w3.org/2002/xforms"), StartElement("metadata", Atts(Nil)), StartElement("application-name", Atts(Nil)), EndElement("application-name"), StartElement("form-name", Atts(Nil)), EndElement("form-name"), StartElement("title", Atts(List(XMLLang β†’ "en"))), EndElement("title"), StartElement("description", Atts(List(XMLLang β†’ "en"))), EndElement("description"), StartElement("title", Atts(List(XMLLang β†’ "fr"))), EndElement("title"), StartElement("description", Atts(List(XMLLang β†’ "fr"))), EndElement("description"), StartElement("permissions", Atts(Nil)), StartElement("permission", Atts(List(Operations β†’ "read update delete"))), StartElement("group-member", Atts(Nil)), EndElement("group-member"), EndElement("permission"), StartElement("permission", Atts(List(Operations β†’ "read update delete"))), StartElement("owner", Atts(Nil)), EndElement("owner"), EndElement("permission"), StartElement("permission", Atts(List(Operations β†’ "create"))), EndElement("permission"), EndElement("permissions"), StartElement("available", Atts(Nil)), EndElement("available"), EndElement("metadata"), EndPrefixMapping("sql"), EndPrefixMapping("fr"), EndPrefixMapping("ev"), EndPrefixMapping("xxf"), EndPrefixMapping("xs"), EndPrefixMapping("xh"), EndPrefixMapping("exf"), EndPrefixMapping("xml"), EndPrefixMapping("saxon"), EndPrefixMapping("soap"), EndPrefixMapping("fb"), EndPrefixMapping("xxi"), EndPrefixMapping("xi"), EndPrefixMapping("xsi"), EndPrefixMapping("xf"), EndDocument ) assert(expected === collector.events) } }
brunobuzzi/orbeon-forms
form-runner/jvm/src/test/scala/org/orbeon/oxf/xml/FormRunnerFilterReceiverTest.scala
Scala
lgpl-2.1
4,709
package csvdb import org.scalatest.{Matchers, FlatSpec} import scala.io.Source class DBSpec extends FlatSpec with Matchers { "DB" should "sanitize file names" in { DB.tableNameFor("../../../exported-data.csv") should be ("exported_data_csv") DB.tableNameFor("exported-data.csv") should be ("exported_data_csv") DB.tableNameFor("my file.tsv") should be ("my_file_tsv") } it should "count columns based on the first line of input" in { val csv = """foo,bar,baz,this is a thing,quux\\t |monkey,monkey,monkey """.stripMargin DB.countColumns(Source.fromString(csv), ",") should be (5) // this test fails if I don't use a string context; there's something funky going on here w.r.t. // the interpretation of tabs val tsv = s"""foo\\tbar\\tbaz\\tthis is a thing\\tquux, |monkey, monkey """.stripMargin DB.countColumns(Source.fromString(tsv), "\\t") should be (5) } }
mtomko/csvdb
src/test/scala/csvdb/DBSpec.scala
Scala
epl-1.0
947
package scala.meta.internal.io import java.io.File import java.net.URI import java.nio.file.Path // Rough implementation of java.nio.Path, should work similarly for the happy // path but has undefined behavior for error handling. case class NodeNIOPath(filename: String) extends Path { private[this] val escapedSeparator = java.util.regex.Pattern.quote(File.separator) private def adjustIndex(idx: Int): Int = if (isAbsolute) idx + 1 else idx override def subpath(beginIndex: Int, endIndex: Int): Path = NodeNIOPath( filename .split(escapedSeparator) .slice(adjustIndex(beginIndex), adjustIndex(endIndex)) .mkString) override def toFile: File = new File(filename) override def isAbsolute: Boolean = if (JSIO.isNode) JSIO.path.isAbsolute(filename) else filename.startsWith(File.separator) override def getName(index: Int): Path = NodeNIOPath( filename .split(escapedSeparator) .lift(adjustIndex(index)) .getOrElse(throw new IllegalArgumentException)) override def getParent: Path = NodeNIOPath(JSIO.path.dirname(filename)) override def toAbsolutePath: Path = if (isAbsolute) this else NodeNIOPath.workingDirectory.resolve(this) override def relativize(other: Path): Path = NodeNIOPath(JSIO.path.relative(filename, other.toString)) override def getNameCount: Int = { val strippeddrive = if ((filename.length > 1) && (filename(1) == ':')) filename.substring(2) else filename val (first, remaining) = strippeddrive.split(escapedSeparator + "+").span(_.isEmpty) if (remaining.isEmpty) first.length else remaining.length } override def toUri: URI = toFile.toURI override def getFileName: Path = NodeNIOPath(JSIO.path.basename(filename)) override def getRoot: Path = if (!isAbsolute) null else NodeNIOPath(File.separator) override def normalize(): Path = if (JSIO.isNode) NodeNIOPath(JSIO.path.normalize(filename)) else this override def endsWith(other: Path): Boolean = endsWith(other.toString) override def endsWith(other: String): Boolean = paths(filename).endsWith(paths(other)) // JSIO.path.resolve(relpath, relpath) produces an absolute path from cwd. // This method turns the generated absolute path back into a relative path. private def adjustResolvedPath(resolved: Path): Path = if (isAbsolute) resolved else NodeNIOPath.workingDirectory.relativize(resolved) override def resolveSibling(other: Path): Path = resolveSibling(other.toString) override def resolveSibling(other: String): Path = adjustResolvedPath(NodeNIOPath(JSIO.path.resolve(JSIO.path.dirname(filename), other))) override def resolve(other: Path): Path = resolve(other.toString) override def resolve(other: String): Path = adjustResolvedPath(NodeNIOPath(JSIO.path.resolve(filename, other))) override def startsWith(other: Path): Boolean = startsWith(other.toString) override def startsWith(other: String): Boolean = paths(filename).startsWith(paths(other)) private def paths(name: String) = name.split(escapedSeparator) override def toString: String = filename } object NodeNIOPath { def workingDirectory = NodeNIOPath(PlatformPathIO.workingDirectoryString) }
MasseGuillaume/scalameta
scalameta/io/js/src/main/scala/scala/meta/internal/io/NodeNIOPath.scala
Scala
bsd-3-clause
3,273
package docs object next_steps { val _ = { //#logdata val logData = """|2013-06-29 11:16:23 124.67.34.60 keyboard |2013-06-29 11:32:12 212.141.23.67 mouse |2013-06-29 11:33:08 212.141.23.67 monitor |2013-06-29 12:12:34 125.80.32.31 speakers |2013-06-29 12:51:50 101.40.50.62 keyboard |2013-06-29 13:10:45 103.29.60.13 mouse |""".stripMargin //#logdata //#imports import atto._, Atto._ import cats.implicits._ //#imports //#ubyte case class UByte(toByte: Byte) { override def toString: String = (toByte.toInt & 0xFF).toString } val ubyte: Parser[UByte] = { int.filter(n => n >= 0 && n < 256) // ensure value is in [0 .. 256) .map(n => UByte(n.toByte)) // construct our UByte .namedOpaque("UByte") // give our parser a name } //#ubyte //#ubyte-parse ubyte.parseOnly("foo") // res0: ParseResult[UByte] = Fail(foo,List(),Failure reading:UByte) ubyte.parseOnly("-42") // res1: ParseResult[UByte] = Fail(,List(),Failure reading:UByte) ubyte.parseOnly("255") // ok! // res2: ParseResult[UByte] = Done(,255) //#ubyte-parse //#ip case class IP(a: UByte, b: UByte, c: UByte, d: UByte) val ip: Parser[IP] = for { a <- ubyte _ <- char('.') b <- ubyte _ <- char('.') c <- ubyte _ <- char('.') d <- ubyte } yield IP(a, b, c, d) //#ip //#ip-parse ip parseOnly "foo.bar" // res3: ParseResult[IP] = Fail(foo.bar,List(),Failure reading:UByte) ip parseOnly "128.42.42.1" // res4: ParseResult[IP] = Done(,IP(128,42,42,1)) ip.parseOnly("128.42.42.1").option // res5: Option[IP] = Some(IP(128,42,42,1)) //#ip-parse val _ = { //#ip-2 val dot: Parser[Char] = char('.') val ip: Parser[IP] = for { a <- ubyte <~ dot b <- ubyte <~ dot c <- ubyte <~ dot d <- ubyte } yield IP(a, b, c, d) //#ip-2 //#ip-parse-2 ip.parseOnly("128.42.42.1").option // res6: Option[IP] = Some(IP(128,42,42,1)) //#ip-parse-2 //#ip-named val ip2 = ip named "ip-address" val ip3 = ip namedOpaque "ip-address" // difference is illustrated below //#ip-named //#ip-named-parse ip2 parseOnly "foo.bar" // res7: ParseResult[IP] = Fail(foo.bar,List(ip-address),Failure reading:UByte) ip3 parseOnly "foo.bar" // res8: ParseResult[IP] = Fail(foo.bar,List(),Failure reading:ip-address) //#ip-named-parse //#ip-4 val ubyteDot = ubyte <~ dot // why not? val ip4 = (ubyteDot, ubyteDot, ubyteDot, ubyte).mapN(IP.apply) named "ip-address" //#ip-4 //#ip-4-parse ip4.parseOnly("128.42.42.1").option // res9: Option[IP] = Some(IP(128,42,42,1)) //#ip-4-parse //#ip-4-parse-either ip4.parseOnly("abc.42.42.1").either // res10: Either[String,IP] = Left(Failure reading:UByte) ip4.parseOnly("128.42.42.1").either // res11: Either[String,IP] = Right(IP(128,42,42,1)) //#ip-4-parse-either //#data-types case class Date(year: Int, month: Int, day: Int) case class Time(hour: Int, minutes: Int, seconds: Int) case class DateTime(date: Date, time: Time) sealed trait Product // Products are an enumerated type case object Mouse extends Product case object Keyboard extends Product case object Monitor extends Product case object Speakers extends Product case class LogEntry(entryTime: DateTime, entryIP: IP, entryProduct: Product) type Log = List[LogEntry] //#data-types //#fixed def fixed(n:Int): Parser[Int] = count(n, digit).map(_.mkString).flatMap { s => try ok(s.toInt) catch { case e: NumberFormatException => err(e.toString) } } //#fixed //#log val date: Parser[Date] = (fixed(4) <~ char('-'), fixed(2) <~ char('-'), fixed(2)).mapN(Date.apply) val time: Parser[Time] = (fixed(2) <~ char(':'), fixed(2) <~ char(':'), fixed(2)).mapN(Time.apply) val dateTime: Parser[DateTime] = (date <~ char(' '), time).mapN(DateTime.apply) val product: Parser[Product] = { string("keyboard").map(_ => Keyboard : Product) | string("mouse") .map(_ => Mouse : Product) | string("monitor") .map(_ => Monitor : Product) | string("speakers").map(_ => Speakers : Product) } val logEntry: Parser[LogEntry] = (dateTime <~ char(' '), ip <~ char(' '), product).mapN(LogEntry.apply) val log: Parser[Log] = sepBy(logEntry, char('\\n')) //#log //#log-parse (log parseOnly logData).option.foldMap(_.mkString("\\n")) // res12: String = // LogEntry(DateTime(Date(2013,6,29),Time(11,16,23)),IP(124,67,34,60),Keyboard) // LogEntry(DateTime(Date(2013,6,29),Time(11,32,12)),IP(212,141,23,67),Mouse) // LogEntry(DateTime(Date(2013,6,29),Time(11,33,8)),IP(212,141,23,67),Monitor) // LogEntry(DateTime(Date(2013,6,29),Time(12,12,34)),IP(125,80,32,31),Speakers) // LogEntry(DateTime(Date(2013,6,29),Time(12,51,50)),IP(101,40,50,62),Keyboard) // LogEntry(DateTime(Date(2013,6,29),Time(13,10,45)),IP(103,29,60,13),Mouse) //#log-parse } () } }
tpolecat/atto
modules/docs/src/main/scala/next-steps.scala
Scala
mit
5,157
/* Copyright (C) 2012-2013 Treode, 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.treode.cps.stub.io import java.nio.file.{OpenOption, Path} import org.scalatest.FlatSpec import org.scalatest.junit.JUnitRunner import com.treode.cps.scalatest.CpsFlatSpec import com.treode.cps.io.{File, FileBehaviors} import com.treode.cps.stub.scheduler.TestScheduler class FileStubSpec extends CpsFlatSpec with FileBehaviors { class StubSpecKit extends FileSpecKit { val scheduler = TestScheduler.multithreaded() val files = FileSystemStub() def openFile (path: Path, opts: OpenOption*): File = files.open (path, opts: _*) } "A file stub" should behave like aFile (() => new StubSpecKit) }
Treode/cps
src/test/scala/com/treode/cps/stub/io/FileStubSpec.scala
Scala
apache-2.0
1,239
package service import dao.{ PasswordDao, UserDao } import model.{ User, UserPassword } import router.dto.UserDto import utils.DatabaseConfig._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future import scalaz.OptionT import scalaz.OptionT._ import scalaz.std.scalaFuture._ trait UserService { def userDao: UserDao def passwordDao: PasswordDao def add(user: UserDto): Future[Option[User]] def getAll(): Future[Seq[User]] def get(id: Int): Future[Option[User]] def get(email: String): Future[Option[(User, UserPassword)]] def delete(id: Int):Future[Int] def update(id: Int, userDto: UserDto): Future[Option[User]] def populateUser: UserDto => User = (userDto: UserDto) => User( 0, userDto.email, userDto.firstName, userDto.lastName, userDto.twitterId, userDto.linkedinId, userDto.bio, userDto.permission ) } object UserService extends UserService { override val userDao = UserDao override val passwordDao = PasswordDao override def add(user: UserDto): Future[Option[User]] = db.run { for { passwordId <- passwordDao.add(UserPassword newWithPassword user.password) userId <- userDao.add(populateUser(user).copy(passwordId = Some(passwordId))) // "This DBMS allows only a single AutoInc" // H2 doesn't allow return the whole user once created so we have to do this instead of returning the object from // the dao on inserting user <- UserDao.get(userId.getOrElse(-1)) } yield user } override def getAll(): Future[Seq[User]] = db.run { userDao.getAll } override def get(id: Int): Future[Option[User]] = db.run { userDao.get(id) } override def get(email: String): Future[Option[(User, UserPassword)]] = db.run { userDao.get(email) } override def delete(id: Int):Future[Int] = db.run { userDao.delete(id) } override def update(id: Int, userDto: UserDto): Future[Option[User]] = { val toUpdate = populateUser(userDto).copy(id = id) val result = for { p <- optionT(db.run(userDao.get(id))) newPasswordId <- optionT(db.run(passwordDao.add(UserPassword newWithPassword userDto.password)).map(Option.apply)) resultUpdate <- optionT(db.run(userDao.add(toUpdate.copy(passwordId = Option(newPasswordId)))).map(Option.apply)) updated <- optionT(db.run(userDao.get(id))) } yield updated result.run } }
Gneotux/pfc
src/main/scala/service/UserService.scala
Scala
apache-2.0
2,450
package scryetek.vecmath @inline final class Vec4(var x: Float, var y: Float, var z: Float, var w: Float) { def this() = this(0, 0, 0, 0) @inline def set(x: Float = this.x, y: Float = this.y, z: Float = this.z, w: Float = this.w) = { this.x = x this.y = y this.z = z this.w = w this } @inline def set(v: Vec4): Vec4 = set(v.x, v.y, v.z, v.w) /** Adds two vectors. */ @inline def +(v: Vec4): Vec4 = Vec4(x + v.x, y + v.y, z + v.z, w + v.w) @inline def add(v: Vec4, out: Vec4 = this): Vec4 = out.set(x + v.x, y + v.y, z + v.z, w + v.w) @inline def add(x: Float, y: Float, z: Float, w: Float): Vec4 = add(x, y, z, w, this) @inline def add(x: Float, y: Float, z: Float, w: Float, out: Vec4): Vec4 = out.set(this.x + x, this.y + y, this.z + z, this.w + w) /** Subtracts two vectors. */ @inline def -(v: Vec4): Vec4 = Vec4(x - v.x, y - v.y, z - v.z, w - v.w) @inline def sub(v: Vec4, out: Vec4 = this): Vec4 = out.set(x - v.x, y - v.y, z - v.z, w - v.w) @inline def sub(x: Float, y: Float, z: Float, w: Float, out: Vec4): Vec4 = out.set(this.x - x, this.y - y, this.z - z, this.w - w) @inline def sub(x: Float, y: Float, z: Float, w: Float): Vec4 = sub(x, y, z, w, this) /** The dot product of two vectors. */ @inline def *(v: Vec4): Float = x*v.x + y*v.y + z*v.z + z*v.z /** Returns the vector scaled by the given scalar. */ @inline def *(s: Float): Vec4 = Vec4(x*s, y*s, z*s, w*s) @inline def scale(s: Float, out: Vec4 = this): Vec4 = out.set(x*s, y*s, z*s, w*s) /** Returns the vector dividied by the given scalar. */ @inline def /(s: Float): Vec4 = { val f = 1/s Vec4(x*f, y*f, z*f, w*f) } @inline def div(s: Float, out: Vec4 = this): Vec4 = scale(1/s, out) @inline def unary_- = Vec4(-x, -y, -z, -w) @inline def negate(out: Vec4 = this) = out.set(-x, -y, -z, -w) /** Returns the squared magnitude (length<sup>2</sup>) of this vector. */ @inline def magSqr = x*x + y*y + z*z + w*w @inline /** Returns the magnitude (length) of this vector. */ def magnitude = math.sqrt(magSqr).toFloat /** Returns the normalized vector. */ @inline def normalized = this / magnitude @inline def normalize(out: Vec4 = this) = out.set(this).div(magnitude) @inline def max(v: Vec4): Vec4 = Vec4(v.x max x, v.y max y, v.z max z, v.w max w) @inline def min(v: Vec4): Vec4 = Vec4(v.x min x, v.y min y, v.z min z, v.w max w) @inline def copy(x: Float = x, y: Float = y, z: Float = z, w: Float = w) = new Vec4(x,y,z,w) /** * Returns the linear interpolation of this vector with another, with t ranging from 0..1 */ @inline def lerp(q: Vec4, t: Float): Vec4 = Vec4(x + t*(q.x-x), y + t*(q.y-y), z + t*(q.z-z), w + t*(q.w-w)) /** * Destructively places the linear interpolation of this vector with another into out, with t ranging from 0..1 */ def lerp(q: Vec4, t: Float, out: Vec4): Vec4 = out.set(x + t*(q.x-x), y + t*(q.y-y), z + t*(q.z-z), w + t*(q.w-w)) override def toString = s"Vec4(${x}f,${y}f,${z}f,${w}f})" override def equals(o: Any): Boolean = o match { case v: Vec4 => x == v.x && y == v.y && z == v.z && w == v.w case _ => false } override def hashCode: Int = x.hashCode()*19 + y.hashCode()*23 + z.hashCode()*29 + w.hashCode()*31 } object Vec4 { def apply(x: Float, y: Float, z: Float, w: Float) = new Vec4(x,y,z,w) def apply() = new Vec4() }
mseddon/vecmath
shared/src/main/scala/scryetek/vecmath/Vec4.scala
Scala
bsd-3-clause
3,603
/* * Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com> */ package play.sbt import sbt.Keys._ import sbt.{ Def, Level, Scope, Settings, State } import sbt.internal.LogManager import sbt.internal.util.ManagedLogger /** * Fix compatibility issues for PlayImport. This is the version compatible with sbt 1.0. */ private[sbt] trait PlayImportCompat { // has nothing }
Shenker93/playframework
framework/src/sbt-plugin/src/main/scala-sbt-1.0/play/sbt/PlayImportCompat.scala
Scala
apache-2.0
389
package org.dele.misc.bookFastDS import org.apache.spark.sql.types._ import org.apache.spark.sql.{DataFrame, Dataset, SparkSession} /** * Created by dele on 2017-02-27. */ object GeoCityDataTest extends App { case class GeoLocEntry( locId:Int, country:String, region:String, city:String, postalCode:String, latitude:Double, longitude:Double, metroCode:String, areaCode:String ) val spark = SparkSession.builder() .appName("GeoCity") .master("local[*]") .getOrCreate() //val inFile = spark.sparkContext.textFile( import spark.implicits._ /* val customSchema = StructType(Array( StructField("locId", IntegerType), StructField("country", StringType), StructField("region", StringType), StructField("city", StringType), StructField("postalCode", StringType), StructField("latitude", DoubleType), StructField("longitude", DoubleType), StructField("metroCode", StringType), StructField("areaCode", StringType) )) */ import org.apache.spark.sql.catalyst.ScalaReflection val customSchema = ScalaReflection.schemaFor[GeoLocEntry].dataType.asInstanceOf[StructType] val df:DataFrame = spark.read .option("header", "true") .schema(customSchema) .csv("/home/dele/tmp/GeoLiteCity_20170207/GeoLiteCity-Location.csv") //.csv("res/data/g1.csv") val ds = df.as[GeoLocEntry] println(ds.count()) val countries = ds.map(_.country).distinct().collect() val countryMap = countries.indices.map(idx => countries(idx) -> idx).toMap spark.sparkContext.broadcast(countryMap) val mapped = ds.map{ geo => val idx = countryMap(geo.country) idx -> geo }.collect() println(mapped) spark.close() }
new2scala/text-util
misc/src/test/scala/org/dele/misc/bookFastDS/GeoCityDataTest.scala
Scala
apache-2.0
1,895
// Synchronous Shopping // https://www.hackerrank.com/challenges/synchronous-shopping package search.syncshopping import scala.collection._ /** * */ object Solution { val Debug = false val PrintPath = Debug && true val PrintAdding = Debug && PrintPath && false val PrintLast = Debug && PrintPath && true val Pause = Debug && false val PrintPathFrequency = 1000000 case class CatPath(time: Int, lastNode: Int = 0) { def movingTo(node: Int, edgeTime: Int) = CatPath(time + edgeTime, node) } /* case class CatPath(val time: Int = 0, nodes: IndexedSeq[Int] = IndexedSeq(0)) { def this(time: Int, node: Int) = this(time, IndexedSeq(node)) lazy val lastNode = nodes(nodes.size - 1) def movingTo(node: Int, edgeTime: Int) = new CatPath(time + edgeTime, nodes :+ node) } */ object FishSet { def apply(fish: Iterable[Int]): FishSet = { fish.foldLeft(FishSet(0, 0))((f, a) => f + a) } } case class FishSet(mask: Int, override val size: Int) extends Iterable[Int] { def fullyContains(other: FishSet) = mask == (mask | other.mask) def +(fish: Int) = { val bit = 1 << (fish - 1) if ((mask & bit) == 0) FishSet(mask | bit, size + 1) else this } def ++(other: FishSet) = { if (size == 0) { other } else if (other.size == 0) { this } else { val newMask = mask | other.mask var count = 1 var x = newMask & (newMask - 1) while (x != 0) { x = x & (x - 1) count += 1 } FishSet(newMask, count) } } override def iterator: Iterator[Int] = { new Iterator[Int] { var currentMask = mask var index = 0 override def hasNext: Boolean = currentMask != 0 override def next(): Int = { if (!hasNext) { throw new NoSuchElementException() } while ((currentMask & 1) == 0) { currentMask >>= 1 index += 1 } currentMask >>= 1 index += 1 index } } } } case class FishScore(fish: FishSet, score: Int) { def covers(other: FishScore) = fish.fullyContains(other.fish) && score <= other.score } case class Path(bigCat: CatPath, littleCat: CatPath, bigFish: FishSet, littleFish: FishSet, level: Int) extends Ordered[Path] { var bigCatEstimate = 0 var littleCatEstimate = 0 lazy val fishScore = FishScore(bigFish ++ littleFish, Math.max(bigCat.time + bigCatEstimate, littleCat.time + littleCatEstimate)) def posPair = (bigCat.lastNode, littleCat.lastNode) def maxTime = Math.max(bigCat.time, littleCat.time) def fish = fishScore.fish def score = fishScore.score def hasAllFish(count: Int) = fish.size == count def updateEstimates(forwardDistances: Map[Int, Int], backwardDistances: Map[Int, Int]) { bigCatEstimate = forwardDistances(bigCat.lastNode) littleCatEstimate = backwardDistances(littleCat.lastNode) } override def compare(that: Path): Int = { val r = Integer.compare(this.fish.size, that.fish.size) if (r == 0) Integer.compare(that.score, this.score) else r } } type Grid = mutable.HashMap[Int, mutable.Map[Int, Int]] // Node => { Node => Time } case class Task(grid: Grid, shoppingCenters: Array[FishSet], K: Int, N: Int) class ScoreTable(n: Int) { val table: Array[Array[Option[Array[FishScore]]]] = (1 to n).toArray.map(_ => Array.fill[Option[Array[FishScore]]](n)(None)) def update(pos: (Int, Int), arr: Array[FishScore]): Unit = { table(pos._1)(pos._2) = Some(arr) } def get(pos: (Int, Int)): Option[Array[FishScore]] = { table(pos._1)(pos._2) } } def printPath(path: Path, prefix: String) { println(s"$prefix$path; Score = ${path.score}; Distance = ${path.maxTime}") } def buildDistanceMatrix(n: Int, grid: Grid, startNode: Int): Array[Int] = { val matrix = Array.fill(n)(Integer.MAX_VALUE) matrix(startNode) = 0 var frontier = Set(startNode) while (frontier.nonEmpty) { val newFrontier = for { node <- frontier distance = matrix(node) (neighbour, edge) <- grid(node) newDistance = distance + edge if newDistance < matrix(neighbour) } yield { matrix(neighbour) = newDistance neighbour } frontier = newFrontier.toSet } matrix } def buildFishMap(task: Task): Map[Int, IndexedSeq[Int]] = { var result = Map.empty[Int, IndexedSeq[Int]] for { i <- 0 until task.N fish = task.shoppingCenters(i) fishNumber <- fish } { result.get(fishNumber) match { case Some(nodes) => result += ((fishNumber, nodes :+ i)) case None => result += ((fishNumber, IndexedSeq(i))) } } result } def solve(task: Task, distanceMatrix: Array[Array[Int]], fishMap: Map[Int, IndexedSeq[Int]]): Path = { def isFinalCondition(path: Path): Boolean = { path.hasAllFish(task.K) && path.bigCat.lastNode == task.N - 1 && path.littleCat.lastNode == task.N - 1 } val queue = mutable.PriorityQueue.empty[Path] var finalResult = Path(CatPath(Integer.MAX_VALUE), CatPath(0), FishSet(0, 0), FishSet(0, 0), 0) def queuePath(path: Path): Unit = { path.bigCatEstimate = distanceMatrix(path.bigCat.lastNode)(task.N - 1) path.littleCatEstimate = distanceMatrix(path.littleCat.lastNode)(task.N - 1) if (path.score < finalResult.maxTime) { if (isFinalCondition(path)) { if (PrintLast) { println(s"Finish: $path; Distance = ${path.maxTime}") } finalResult = path } else { queue += path } } } queuePath(Path(CatPath(0, 0), CatPath(0, 0), task.shoppingCenters(0), task.shoppingCenters(0), 0)) var count = 0 while (queue.nonEmpty) { val path = queue.dequeue() if (path.score < finalResult.maxTime) { if (isFinalCondition(path)) { if (PrintPath) { println(s"Finish: $path; Distance = ${path.maxTime}") } finalResult = path } else { if (PrintPath && (count % PrintPathFrequency) == 0) { printPath(path, "") } count += 1 val missingFish = (1 to task.K).toSet -- path.fish if (missingFish.isEmpty) { queuePath(Path( path.bigCat.movingTo(task.N - 1, distanceMatrix(path.bigCat.lastNode)(task.N - 1)), path.littleCat.movingTo(task.N - 1, distanceMatrix(path.littleCat.lastNode)(task.N - 1)), path.bigFish, path.littleFish, 1 )) } else { val targetNodes = (for { fishNumber <- missingFish fishNode <- fishMap(fishNumber) } yield fishNode).toSet if (path.level == 0) { for (node <- targetNodes) { queuePath(Path( path.bigCat.movingTo(node, distanceMatrix(path.bigCat.lastNode)(node)), path.littleCat, path.bigFish ++ task.shoppingCenters(node), path.littleFish, 1)) } } else { for (node <- targetNodes) { queuePath(Path( path.bigCat, path.littleCat.movingTo(node, distanceMatrix(path.littleCat.lastNode)(node)), path.bigFish, path.littleFish ++ task.shoppingCenters(node), 0)) } } } } } } finalResult } def main(args: Array[String]): Unit = { val task = readTask() val startTime = System.currentTimeMillis() val forwardDistances = buildDistanceMatrix(task.N, task.grid, task.N - 1) val backwardDistances = buildDistanceMatrix(task.N, task.grid, 0) val distanceMatrix = (0 until task.N).toArray.map(i => buildDistanceMatrix(task.N, task.grid, i)) val fishMap = buildFishMap(task) if (Debug) { println(s"Fish map: $fishMap") } val result = solve(task, distanceMatrix, fishMap) if (PrintLast) { println("Solution: " + result) val time = System.currentTimeMillis() - startTime println(s"Time: ${time / 1000.0} seconds") } println(result.maxTime) } def readTask() = { def readInts(): Array[Int] = readLine().split("\\\\s+").map(_.toInt) val line = readInts() val (n, m, k) = (line(0), line(1), line(2)) val shoppingCenters = (1 to n).map(_ => { val sc = readInts() assert(sc(0) == sc.size - 1) sc.slice(1, sc.size).foldLeft(FishSet(0, 0)) { (fishSet, fish) => fishSet + fish } }) val grid = new Grid() for (_ <- 1 to m) { val edge = readInts() val (from, to, time) = (edge(0) - 1, edge(1) - 1, edge(2)) val map = grid.getOrElseUpdate(from, mutable.Map.empty) map.put(to, time) val map2 = grid.getOrElseUpdate(to, mutable.Map.empty) map2.put(from, time) } Task(grid, shoppingCenters.toArray, k, n) } }
uliashkevich/hackerrank
src/search/syncshopping/Solution.scala
Scala
artistic-2.0
9,195
package io.getquill.context.sql.norm import io.getquill.Spec import io.getquill.context.sql.testContext.qr1 import io.getquill.context.sql.testContext.qr2 import io.getquill.context.sql.testContext.qr3 import io.getquill.context.sql.testContext.quote import io.getquill.context.sql.testContext.unquote class ExpandJoinSpec extends Spec { "expands the outer join by mapping the result" - { "simple" in { val q = quote { qr1.leftJoin(qr2).on((a, b) => a.s == b.s) } ExpandJoin(q.ast).toString mustEqual """querySchema("TestEntity").leftJoin(querySchema("TestEntity2")).on((a, b) => a.s == b.s).map(ab => (a, b))""" } "nested" - { "inner" in { val q = quote { qr1.join(qr2).on((a, b) => a.s == b.s).join(qr3).on((c, d) => c._1.s == d.s) } ExpandJoin(q.ast).toString mustEqual """querySchema("TestEntity").join(querySchema("TestEntity2")).on((a, b) => a.s == b.s).join(querySchema("TestEntity3")).on((c, d) => a.s == d.s).map(cd => ((a, b), d))""" } "left" in { val q = quote { qr1.leftJoin(qr2).on((a, b) => a.s == b.s).leftJoin(qr3).on((c, d) => c._1.s == d.s) } ExpandJoin(q.ast).toString mustEqual """querySchema("TestEntity").leftJoin(querySchema("TestEntity2")).on((a, b) => a.s == b.s).leftJoin(querySchema("TestEntity3")).on((c, d) => a.s == d.s).map(cd => ((a, b), d))""" } "right" in { val q = quote { qr1.leftJoin(qr2.leftJoin(qr3).on((a, b) => a.s == b.s)).on((c, d) => c.s == d._1.s) } ExpandJoin(q.ast).toString mustEqual """querySchema("TestEntity").leftJoin(querySchema("TestEntity2").leftJoin(querySchema("TestEntity3")).on((a, b) => a.s == b.s)).on((c, d) => c.s == a.s).map(cd => (c, (a, b)))""" } "both" in { val q = quote { qr1.leftJoin(qr2).on((a, b) => a.s == b.s).leftJoin(qr3.leftJoin(qr2).on((c, d) => c.s == d.s)).on((e, f) => e._1.s == f._1.s) } ExpandJoin(q.ast).toString mustEqual """querySchema("TestEntity").leftJoin(querySchema("TestEntity2")).on((a, b) => a.s == b.s).leftJoin(querySchema("TestEntity3").leftJoin(querySchema("TestEntity2")).on((c, d) => c.s == d.s)).on((e, f) => a.s == c.s).map(ef => ((a, b), (c, d)))""" } } } }
getquill/quill
quill-sql/src/test/scala/io/getquill/context/sql/norm/ExpandJoinSpec.scala
Scala
apache-2.0
2,342
package dsl.reactive.examples import dsl.reactive._ import dsl.reactive.auxiliary._ import dsl.reactive.optimizations._ import virtualization.lms.common._ import scala.collection.mutable.ListBuffer trait SignalCodeGeneration extends ReactiveDSL { def exec(x: Rep[Unit]) = { val v = ReactiveVar(5) val s = ISignal { v.get + 1 } s } } object GenerateSignalCode extends App { val program = new SignalCodeGeneration with ReactiveDSLExpOpt with CompileScala { self => override val codegen = new ReactiveDSLGenOpt { val IR: self.type = self } } program.codegen.emitSource(program.exec, "SignalCode", new java.io.PrintWriter(System.out)) }
markus1189/OptiReactive
src/main/scala/dsl/reactive/examples/SignalCodeGeneration.scala
Scala
gpl-3.0
696
// Generated by the Scala Plugin for the Protocol Buffer Compiler. // Do not edit! // // Protofile syntax: PROTO3 package com.komanov.serialization.domain.protos.site @SerialVersionUID(0L) final case class PagePb( name: String = "", path: String = "", metaTags: Seq[com.komanov.serialization.domain.protos.site.MetaTagPb] = Nil, components: Seq[com.komanov.serialization.domain.protos.site.PageComponentPb] = Nil ) extends com.trueaccord.scalapb.GeneratedMessage with com.trueaccord.scalapb.Message[PagePb] with com.trueaccord.lenses.Updatable[PagePb] { @transient private[this] var __serializedSizeCachedValue: Int = 0 private[this] def __computeSerializedValue(): Int = { var __size = 0 if (name != "") { __size += com.google.protobuf.CodedOutputStream.computeStringSize(1, name) } if (path != "") { __size += com.google.protobuf.CodedOutputStream.computeStringSize(2, path) } metaTags.foreach(metaTags => __size += 1 + com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(metaTags.serializedSize) + metaTags.serializedSize) components.foreach(components => __size += 1 + com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(components.serializedSize) + components.serializedSize) __size } final override def serializedSize: Int = { var read = __serializedSizeCachedValue if (read == 0) { read = __computeSerializedValue() __serializedSizeCachedValue = read } read } def writeTo(output: com.google.protobuf.CodedOutputStream): Unit = { { val __v = name if (__v != "") { output.writeString(1, __v) } }; { val __v = path if (__v != "") { output.writeString(2, __v) } }; metaTags.foreach { __v => output.writeTag(3, 2) output.writeUInt32NoTag(__v.serializedSize) __v.writeTo(output) }; components.foreach { __v => output.writeTag(4, 2) output.writeUInt32NoTag(__v.serializedSize) __v.writeTo(output) }; } def mergeFrom(__input: com.google.protobuf.CodedInputStream): com.komanov.serialization.domain.protos.site.PagePb = { var __name = this.name var __path = this.path val __metaTags = (scala.collection.immutable.Vector.newBuilder[com.komanov.serialization.domain.protos.site.MetaTagPb] ++= this.metaTags) val __components = (scala.collection.immutable.Vector.newBuilder[com.komanov.serialization.domain.protos.site.PageComponentPb] ++= this.components) var _done__ = false while (!_done__) { val _tag__ = __input.readTag() _tag__ match { case 0 => _done__ = true case 10 => __name = __input.readString() case 18 => __path = __input.readString() case 26 => __metaTags += com.trueaccord.scalapb.LiteParser.readMessage(__input, com.komanov.serialization.domain.protos.site.MetaTagPb.defaultInstance) case 34 => __components += com.trueaccord.scalapb.LiteParser.readMessage(__input, com.komanov.serialization.domain.protos.site.PageComponentPb.defaultInstance) case tag => __input.skipField(tag) } } com.komanov.serialization.domain.protos.site.PagePb( name = __name, path = __path, metaTags = __metaTags.result(), components = __components.result() ) } def withName(__v: String): PagePb = copy(name = __v) def withPath(__v: String): PagePb = copy(path = __v) def clearMetaTags = copy(metaTags = Seq.empty) def addMetaTags(__vs: com.komanov.serialization.domain.protos.site.MetaTagPb*): PagePb = addAllMetaTags(__vs) def addAllMetaTags(__vs: TraversableOnce[com.komanov.serialization.domain.protos.site.MetaTagPb]): PagePb = copy(metaTags = metaTags ++ __vs) def withMetaTags(__v: Seq[com.komanov.serialization.domain.protos.site.MetaTagPb]): PagePb = copy(metaTags = __v) def clearComponents = copy(components = Seq.empty) def addComponents(__vs: com.komanov.serialization.domain.protos.site.PageComponentPb*): PagePb = addAllComponents(__vs) def addAllComponents(__vs: TraversableOnce[com.komanov.serialization.domain.protos.site.PageComponentPb]): PagePb = copy(components = components ++ __vs) def withComponents(__v: Seq[com.komanov.serialization.domain.protos.site.PageComponentPb]): PagePb = copy(components = __v) def getField(__field: com.google.protobuf.Descriptors.FieldDescriptor): scala.Any = { __field.getNumber match { case 1 => { val __t = name if (__t != "") __t else null } case 2 => { val __t = path if (__t != "") __t else null } case 3 => metaTags case 4 => components } } override def toString: String = com.trueaccord.scalapb.TextFormat.printToUnicodeString(this) def companion = com.komanov.serialization.domain.protos.site.PagePb } object PagePb extends com.trueaccord.scalapb.GeneratedMessageCompanion[PagePb] { implicit def messageCompanion: com.trueaccord.scalapb.GeneratedMessageCompanion[PagePb] = this def fromFieldsMap(__fieldsMap: Map[com.google.protobuf.Descriptors.FieldDescriptor, scala.Any]): com.komanov.serialization.domain.protos.site.PagePb = { require(__fieldsMap.keys.forall(_.getContainingType() == descriptor), "FieldDescriptor does not match message type.") val __fields = descriptor.getFields com.komanov.serialization.domain.protos.site.PagePb( __fieldsMap.getOrElse(__fields.get(0), "").asInstanceOf[String], __fieldsMap.getOrElse(__fields.get(1), "").asInstanceOf[String], __fieldsMap.getOrElse(__fields.get(2), Nil).asInstanceOf[Seq[com.komanov.serialization.domain.protos.site.MetaTagPb]], __fieldsMap.getOrElse(__fields.get(3), Nil).asInstanceOf[Seq[com.komanov.serialization.domain.protos.site.PageComponentPb]] ) } def descriptor: com.google.protobuf.Descriptors.Descriptor = SiteProto.descriptor.getMessageTypes.get(6) def messageCompanionForField(__field: com.google.protobuf.Descriptors.FieldDescriptor): com.trueaccord.scalapb.GeneratedMessageCompanion[_] = { require(__field.getContainingType() == descriptor, "FieldDescriptor does not match message type.") var __out: com.trueaccord.scalapb.GeneratedMessageCompanion[_] = null __field.getNumber match { case 3 => __out = com.komanov.serialization.domain.protos.site.MetaTagPb case 4 => __out = com.komanov.serialization.domain.protos.site.PageComponentPb } __out } def enumCompanionForField(__field: com.google.protobuf.Descriptors.FieldDescriptor): com.trueaccord.scalapb.GeneratedEnumCompanion[_] = throw new MatchError(__field) lazy val defaultInstance = com.komanov.serialization.domain.protos.site.PagePb( ) implicit class PagePbLens[UpperPB](_l: com.trueaccord.lenses.Lens[UpperPB, PagePb]) extends com.trueaccord.lenses.ObjectLens[UpperPB, PagePb](_l) { def name: com.trueaccord.lenses.Lens[UpperPB, String] = field(_.name)((c_, f_) => c_.copy(name = f_)) def path: com.trueaccord.lenses.Lens[UpperPB, String] = field(_.path)((c_, f_) => c_.copy(path = f_)) def metaTags: com.trueaccord.lenses.Lens[UpperPB, Seq[com.komanov.serialization.domain.protos.site.MetaTagPb]] = field(_.metaTags)((c_, f_) => c_.copy(metaTags = f_)) def components: com.trueaccord.lenses.Lens[UpperPB, Seq[com.komanov.serialization.domain.protos.site.PageComponentPb]] = field(_.components)((c_, f_) => c_.copy(components = f_)) } final val NAME_FIELD_NUMBER = 1 final val PATH_FIELD_NUMBER = 2 final val METATAGS_FIELD_NUMBER = 3 final val COMPONENTS_FIELD_NUMBER = 4 }
dkomanov/scala-serialization
scala-serialization/src/main/scala/com/komanov/serialization/domain/protos/site/PagePb.scala
Scala
mit
7,782
/*********************************************************************** * Copyright (c) 2013-2018 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.utils.stats import org.geotools.feature.simple.SimpleFeatureBuilder import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes trait StatTestHelper { val sftSpec = "strAttr:String,intAttr:Integer,longAttr:Long,doubleAttr:Double,floatAttr:Float,cat1:Integer,cat2:String,geom:Geometry:srid=4326,dtg:Date" val sft = SimpleFeatureTypes.createType("test", sftSpec) val stringIndex = sft.indexOf("strAttr") val intIndex = sft.indexOf("intAttr") val longIndex = sft.indexOf("longAttr") val doubleIndex = sft.indexOf("doubleAttr") val floatIndex = sft.indexOf("floatAttr") val category1Index = sft.indexOf("cat1") val category2Index = sft.indexOf("cat2") val geomIndex = sft.indexOf("geom") val dateIndex = sft.indexOf("dtg") val features = (0 until 100).toArray.map { i => val a = Array(f"abc$i%03d", i, i, i, i, i%10, String.valueOf((math.abs(i%26) + 'A').toChar), s"POINT(-$i ${i / 2})", f"2012-01-01T${i%24}%02d:00:00.000Z") SimpleFeatureBuilder.build(sft, a.asInstanceOf[Array[AnyRef]], i.toString) } val features2 = (100 until 200).toArray.map { i => val a = Array(f"abc$i%03d", i, i, i, i, i%10, String.valueOf((math.abs(i%26) + 'A').toChar),s"POINT(${i -20} ${i / 2 - 20})", f"2012-01-02T${i%24}%02d:00:00.000Z") SimpleFeatureBuilder.build(sft, a.asInstanceOf[Array[AnyRef]], i.toString) } val features3 = (-100 until 0).toArray.map { i => val a = Array(f"abc$i%+03d", i, i, i, i, i%10, String.valueOf((math.abs(i%26) + 'A').toChar),s"POINT($i $i)", f"2012-01-02T${Math.abs(i)%24}%02d:00:00.000Z") SimpleFeatureBuilder.build(sft, a.asInstanceOf[Array[AnyRef]], i.toString) } implicit class WhiteSpace(s: String) { def ignoreSpace: String = s.replaceAll("\\\\s+","\\\\\\\\s*") } }
jahhulbert-ccri/geomesa
geomesa-utils/src/test/scala/org/locationtech/geomesa/utils/stats/StatTestHelper.scala
Scala
apache-2.0
2,251
package org.http4s package client package jetty import cats.effect._ import cats.implicits._ import fs2._ import org.eclipse.jetty.client.HttpClient import org.eclipse.jetty.client.api.{Request => JettyRequest} import org.eclipse.jetty.http.{HttpVersion => JHttpVersion} import org.log4s.{Logger, getLogger} object JettyClient { private val logger: Logger = getLogger def allocate[F[_]](client: HttpClient = defaultHttpClient())( implicit F: ConcurrentEffect[F]): F[(Client[F], F[Unit])] = { val acquire = F .pure(client) .flatTap(client => F.delay { client.start() }) .map(client => Client[F] { req => Resource.suspend(F.asyncF[Resource[F, Response[F]]] { cb => F.bracket(StreamRequestContentProvider()) { dcp => val jReq = toJettyRequest(client, req, dcp) for { rl <- ResponseListener(cb) _ <- F.delay(jReq.send(rl)) _ <- dcp.write(req) } yield () } { dcp => F.delay(dcp.close()) } }) }) val dispose = F .delay(client.stop()) .handleErrorWith(t => F.delay(logger.error(t)("Unable to shut down Jetty client"))) acquire.map((_, dispose)) } def resource[F[_]](client: HttpClient = new HttpClient())( implicit F: ConcurrentEffect[F]): Resource[F, Client[F]] = Resource(allocate[F](client)) def stream[F[_]](client: HttpClient = new HttpClient())( implicit F: ConcurrentEffect[F]): Stream[F, Client[F]] = Stream.resource(resource(client)) def defaultHttpClient(): HttpClient = { val c = new HttpClient() c.setFollowRedirects(false) c.setDefaultRequestContentType(null) c } private def toJettyRequest[F[_]]( client: HttpClient, request: Request[F], dcp: StreamRequestContentProvider[F]): JettyRequest = { val jReq = client .newRequest(request.uri.toString) .method(request.method.name) .version( request.httpVersion match { case HttpVersion.`HTTP/1.1` => JHttpVersion.HTTP_1_1 case HttpVersion.`HTTP/2.0` => JHttpVersion.HTTP_2 case HttpVersion.`HTTP/1.0` => JHttpVersion.HTTP_1_0 case _ => JHttpVersion.HTTP_1_1 } ) for (h <- request.headers.toList) jReq.header(h.name.toString, h.value) jReq.content(dcp) } }
ChristopherDavenport/http4s
jetty-client/src/main/scala/org/http4s/client/jetty/JettyClient.scala
Scala
apache-2.0
2,405
package lila.mod import lila.user.{ User, UserRepo } final class UserSearch( securityApi: lila.security.Api, emailAddress: lila.security.EmailAddress) { // http://stackoverflow.com/questions/106179/regular-expression-to-match-hostname-or-ip-address private val ipv4Pattern = """^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$""".r.pattern // ipv6 in standard form private val ipv6Pattern = """^((0|[1-9a-f][0-9a-f]{0,3}):){7}(0|[1-9a-f][0-9a-f]{0,3})""".r.pattern // from playframework private val emailPattern = """^[a-zA-Z0-9\\.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$""".r.pattern def apply(query: String): Fu[List[User]] = if (query.isEmpty) fuccess(Nil) else if (emailPattern.matcher(query).matches) searchEmail(query) else if (ipv4Pattern.matcher(query).matches) searchIp(query) else if (ipv6Pattern.matcher(query).matches) searchIp(query) else searchUsername(query) private def searchIp(ip: String) = securityApi recentUserIdsByIp ip map (_.reverse) flatMap UserRepo.byOrderedIds private def searchUsername(username: String) = UserRepo named username map (_.toList) private def searchEmail(email: String) = emailAddress.validate(email) ?? { fixed => UserRepo byEmail fixed map (_.toList) } }
clarkerubber/lila
modules/mod/src/main/UserSearch.scala
Scala
agpl-3.0
1,401
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.streaming.dstream import org.apache.spark.rdd.RDD import org.apache.spark.rdd.UnionRDD import scala.collection.mutable.Queue import scala.collection.mutable.ArrayBuffer import org.apache.spark.streaming.{Time, StreamingContext} import scala.reflect.ClassTag private[streaming] class QueueInputDStream[T: ClassTag]( @transient ssc: StreamingContext, val queue: Queue[RDD[T]], oneAtATime: Boolean, defaultRDD: RDD[T] ) extends InputDStream[T](ssc) { override def start() { } override def stop() { } override def compute(validTime: Time): Option[RDD[T]] = { val buffer = new ArrayBuffer[RDD[T]]() if (oneAtATime && queue.size > 0) { buffer += queue.dequeue() } else { buffer ++= queue.dequeueAll(_ => true) } if (buffer.size > 0) { if (oneAtATime) { Some(buffer.head) } else { Some(new UnionRDD(ssc.sc, buffer.toSeq)) } } else if (defaultRDD != null) { Some(defaultRDD) } else { None } } }
trueyao/spark-lever
streaming/src/main/scala/org/apache/spark/streaming/dstream/QueueInputDStream.scala
Scala
apache-2.0
1,836
package org.jetbrains.plugins.scala package lang package surroundWith package surrounders package expression import com.intellij.lang.ASTNode import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import psi.api.expr.{ScParenthesisedExpr, ScIfStmt, ScExpression} import psi.types.result.TypingContext import org.jetbrains.plugins.scala.lang.psi.types.Any /** * User: Alexander Podkhalyuzin * Date: 29.09.2008 */ class ScalaWithIfConditionSurrounder extends ScalaExpressionSurrounder { override def getTemplateAsString(elements: Array[PsiElement]): String = "if (" + super.getTemplateAsString(elements) + ") {}" override def getTemplateDescription: String = "if (expr) {...}" override def isApplicable(elements: Array[PsiElement]): Boolean = { if (elements.length != 1) return false elements(0) match { case x: ScExpression if x.getType(TypingContext.empty).getOrAny == psi.types.Boolean => return true case _ => return false } } override def getSurroundSelectionRange(withIfNode: ASTNode): TextRange = { val element: PsiElement = withIfNode.getPsi match { case x: ScParenthesisedExpr => x.expr match { case Some(y) => y case _ => return x.getTextRange } case x => x } val ifStmt: ScIfStmt = element.asInstanceOf[ScIfStmt] val body = (ifStmt.thenBranch: @unchecked) match { case Some(x) => x } val offset = body.getTextRange.getStartOffset + 1 new TextRange(offset,offset) } }
consulo/consulo-scala
src/org/jetbrains/plugins/scala/lang/surroundWith/surrounders/expression/ScalaWithIfConditionSurrounder.scala
Scala
apache-2.0
1,513
package com.seanshubin.scala.training.sample.data trait RandomChooser { def fromSeq[T](seq: Seq[T]): T }
SeanShubin/scala-training
sample-data/src/main/scala/com/seanshubin/scala/training/sample/data/RandomChooser.scala
Scala
unlicense
108
package com.github.gdefacci.di.macrodef import scala.reflect.macros.blackbox.Context private[di] trait DagNodeOrRefFactory[C <: Context] { self:DagNodes[C] => import context.universe._ def alias(exprNm:TermName, valueExpr: Tree, tpe:Type, scope:DagScope, parent:Option[Dag[DagNodeOrRef]]):Dag[DagNodeOrRef] = { val vexpr = q""" val $exprNm = $valueExpr """ parent.map { par => Dag(DagNode.value(scope, q"$exprNm", tpe, valueExpr.pos, DagToExpression(exprNm, valueExpr)), par :: Nil) }.getOrElse { Dag(DagNode.value(scope, q"$exprNm", tpe, valueExpr.pos, DagToExpression(exprNm, valueExpr))) } } def outboundParameterDag(scope:DagScope, par:Symbol):Ref = { val parTyp = par.info match { case TypeRef(pre, k, args) if k == definitions.ByNameParamClass => assert(args.length==1) args.head case _ => par.info } Ref(scope, parTyp, par.pos) } private def paramListsRefs(paramLists:List[List[Symbol]]):List[Ref] = paramLists.flatMap(pars => pars.map { par => val scope = scopeProvider(par) if (scope != DefaultScope) { context.abort(par.pos, "parameters can have scope annotation") } outboundParameterDag(scope, par) }) def paramListsDags(paramLists:List[List[Symbol]]) = paramListsRefs(paramLists).map( par => Dag(par)) def methodDag(container: Dag[DagNodeOrRef], containerTermName: TermName, method: Symbol): Dag[DagNodeOrRef] = { val paramLists = method.asMethod.paramLists val parametersDags: Seq[Dag[DagNodeOrRef]] = paramListsDags(paramLists) assert(paramLists.map(_.length).sum == parametersDags.length) val scope = scopeProvider(method) Dag(DagNode.methodCall(scope, Some(containerTermName), method), parametersDags.toSeq :+ container) } def constructorDag(scope:DagScope, exprType:Type, constructorMethod:MethodSymbol, members:Seq[Tree]): Dag[DagNodeOrRef] = { val typ = constructorMethod.owner if (!typ.isClass) { context.abort(context.enclosingPosition, typ.toString()) } val parametersDags: Seq[Dag[DagNodeOrRef]] = paramListsDags(constructorMethod.paramLists) assert(parametersDags.length == constructorMethod.paramLists.map(_.length).sum) Dag(DagNode.constructorCall(scope, exprType, constructorMethod, members), parametersDags) } }
gdefacci/di
macros/src/main/scala/com/github/gdefacci/di/macrodef/DagNodeOrRefFactory.scala
Scala
mit
2,454
/*********************************************************************** * Copyright (c) 2013-2018 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.kudu.data import java.util.Date import org.locationtech.geomesa.curve.BinnedTime.TimeToBinnedTime import org.locationtech.geomesa.index.api.WrappedFeature import org.opengis.feature.simple.SimpleFeature class KuduFeature(val feature: SimpleFeature, dtgIndex: Option[Int], toBin: TimeToBinnedTime) extends WrappedFeature { val bin: Short = toBin(dtgIndex.flatMap(i => Option(feature.getAttribute(i).asInstanceOf[Date]).map(_.getTime)).getOrElse(0L)).bin override def idBytes: Array[Byte] = throw new NotImplementedError() }
ddseapy/geomesa
geomesa-kudu/geomesa-kudu-datastore/src/main/scala/org/locationtech/geomesa/kudu/data/KuduFeature.scala
Scala
apache-2.0
1,034
package jp.pigumer.sbt.cloud.aws.s3 import jp.pigumer.sbt.cloud.aws.cloudformation.AwscfSettings import com.amazonaws.services.s3.AmazonS3 import com.amazonaws.services.s3.model.PutObjectRequest import sbt.Keys._ import sbt._ import sbt.complete.DefaultParsers._ import scala.annotation.tailrec import scala.util.{Failure, Success, Try} trait UploadTemplates { import jp.pigumer.sbt.cloud.aws.cloudformation.CloudformationPlugin.autoImport._ protected def key(dir: String, fileName: String): String protected def url(bucketName: String, key: String): String protected def url(bucketName: String, dir: String, fileName: String): String private def put(dir: String, file: File, uploads: Seq[String])(implicit settings: AwscfSettings, client: AmazonS3, log: Logger): Seq[String] = { val bucketName = settings.bucketName.get val k = key(dir, file.getName) if (file.isFile) { val u = url(bucketName, dir, file.getName) log.info(s"putObject $u") val request = new PutObjectRequest(bucketName, k, file) client.putObject(request) uploads :+ u } else { putFiles(k, file.listFiles, uploads) } } @tailrec private def putFiles(dir: String, files: Seq[File], uploads: Seq[String])(implicit settings: AwscfSettings, client: AmazonS3, log: Logger): Seq[String] = { files match { case head +: tails β‡’ { val res = put(dir, head, uploads) putFiles(dir, tails, res) } case Nil β‡’ uploads } } private def uploads(client: AmazonS3, settings: AwscfSettings, log: Logger) = Try { implicit val s = settings implicit val l = log implicit val s3 = client put(settings.projectName, settings.templates.get, Seq.empty) } def uploadTemplatesTask = Def.task { val log = streams.value.log val settings = awscfSettings.value val client = awss3.value uploads(client, settings, log) match { case Success(r) β‡’ r case Failure(t) β‡’ { log.trace(t) sys.error(t.toString) } } } def putObjectsTask = Def.task { val log = streams.value.log val client = awss3.value val requests = (awss3PutObjectRequests in awss3).value val responses = requests.values.map { request β‡’ Try { client.putObject(request) val u = url(request.getBucketName, request.getKey) log.info(s"putObject $u") u } }.foldLeft(Try(Seq.empty[String])) { (r, url) β‡’ for { x ← r u ← url } yield x :+ u } responses match { case Success(r) β‡’ r case Failure(t) β‡’ log.trace(t) sys.error("putObject failed") } } private def upload(client: AmazonS3, settings: AwscfSettings, bucketName: String, dist: String, key: String, log: Logger) = Try { val request = new PutObjectRequest(bucketName, key, new File(dist)) client.putObject(request) val u = url(bucketName, key) log.info(s"putObject $u") u } def uploadTask = Def.inputTask { val log = streams.value.log val settings = awscfSettings.value val client = awss3.value spaceDelimited("<dist> <bucket> <key>").parsed match { case Seq(dist, bucket, key) β‡’ upload(client, settings, bucket, dist, key, log) match { case Success(url) β‡’ url case Failure(t) β‡’ { log.trace(t) sys.error(t.toString) } } case _ β‡’ sys.error("Usage: upload <dist> <bucket> <key>") } } }
PigumerGroup/sbt-aws-cloudformation
src/main/scala/jp/pigumer/sbt/cloud/aws/s3/UploadTemplates.scala
Scala
mit
3,872
package com.automatatutor.model import net.liftweb.mapper._ import net.liftweb.common.{Full,Box} import net.liftweb.http.SessionVar import net.liftweb.util.StringHelpers import net.liftweb.util.Mailer import net.liftweb.common.Empty import net.liftweb.util.FieldError import scala.xml.Text import net.liftweb.util.Mailer import javax.mail.{Authenticator,PasswordAuthentication} import bootstrap.liftweb.StartupHook import com.automatatutor.lib.Config class User extends MegaProtoUser[User] { override def getSingleton = User def hasStudentRole = Role.findAll(By(Role.userId, this)).exists(role => role.isStudentRole) def hasInstructorRole = Role.findAll(By(Role.userId, this)).exists(role => role.isInstructorRole) def hasAdminRole = Role.findAll(By(Role.userId, this)).exists(role => role.isAdminRole) def addStudentRole = Role.createStudentRoleFor(this) def addInstructorRole = Role.createInstructorRoleFor(this) def addAdminRole = Role.createAdminRoleFor(this) def removeStudentRole = Role.findAll(By(Role.userId, this)).filter(_.isStudentRole).map(_.delete_!) def removeInstructorRole = Role.findAll(By(Role.userId, this)).filter(_.isInstructorRole).map(_.delete_!) def removeAdminRole = Role.findAll(By(Role.userId, this)).filter(_.isAdminRole).map(_.delete_!) def supervisesCourses : Boolean = !Supervision.findByInstructor(this).isEmpty def getSupervisedCourses : Seq[Course] = Supervision.findByInstructor(this).map(_.getCourse) def attendsCourses : Boolean = !Attendance.findAllByUser(this).isEmpty def getAttendedCourses : List[Course] = Attendance.findAllByUser(this).map(_.getCourse.openOrThrowException("User should not attend inexistent courses")) def canBeDeleted : Boolean = !(attendsCourses || supervisesCourses || hasAdminRole) def getDeletePreventers : Seq[String] = { val attendancePreventers : Seq[String] = if (this.attendsCourses) List("User still attends courses") else List() val supervisionPreventers : Seq[String] = if (this.supervisesCourses) List("User still supervises courses") else List() val adminPreventers : Seq[String] = if (this.hasAdminRole) List("User is Admin") else List() val preventers = attendancePreventers ++ supervisionPreventers ++ adminPreventers return preventers } override def delete_! : Boolean = { if (!canBeDeleted) { return false; } else { return super.delete_! } } override def validate = (this.validateFirstName) ++ (this.validateLastName) ++ (super.validate) private def validateFirstName : List[FieldError] = { if (this.firstName == null || this.firstName.is.isEmpty()) { return List[FieldError](new FieldError(this.firstName, Text("First name must be set"))) } else { return List[FieldError]() } } private def validateLastName : List[FieldError] = { if (this.lastName == null || this.lastName.is.isEmpty()) { return List[FieldError](new FieldError(this.lastName, Text("Last name must be set"))) } else { return List[FieldError]() } } } object User extends User with MetaMegaProtoUser[User] with StartupHook { // Don't send out emails to users after registration. Remember to set this to false before we go into production override def skipEmailValidation = false // this overridse the noreply@... address that is set by default right now // for this to work the correct properties must //Mailer.authenticator.map(_.user) openOr override def emailFrom = Config.mail.from.get // Display the standard template around the User-defined pages override def screenWrap = Full(<lift:surround with="default" at="content"><lift:bind /></lift:surround>) // Only query given name, family name, email address and password on signup override def signupFields = List(firstName, lastName, email, password) // Only display given name, family name and email address for editing override def editFields = List(firstName, lastName) override def afterCreate = List( (user : User) => { user.addStudentRole }, (user : User) => { Attendance.finalizePreliminaryEnrollments(user) } ) def onStartup = { val adminEmail = Config.admin.email.get val adminPassword = Config.admin.password.get val adminFirstName = Config.admin.firstname.get val adminLastName = Config.admin.lastname.get /* Delete all existing admin accounts, in case there are any leftover from * previous runs */ val adminAccounts = User.findAll(By(User.email, adminEmail)) //User.bulkDelete_!!(By(User.email, adminEmail)) // Create new admin only if the user in the config does not exists if (adminAccounts.isEmpty){ val adminUser = User.create adminUser.firstName(adminFirstName).lastName(adminLastName).email(adminEmail).password(adminPassword).validated(true).save adminUser.addAdminRole adminUser.addInstructorRole } else { // otherwise just change the password for his account to the one in the config var user = adminAccounts.head var passwordList = List(adminPassword,adminPassword) passwordList user.setPasswordFromListString(passwordList) user.save } } def findByEmail(email : String) : Box[User] = { val users = User.findAll(By(User.email, email)) if(users.size == 1) { return Full(users.head) } else { return Empty } } def currentUser_! : User = { this.currentUser openOrThrowException "This method may only be called if we are certain that a user is logged in" } def currentUserIdInt : Int = { this.currentUserId match { case Full(myId) => myId.toInt; case _ => 0 } } }
AutomataTutor/automatatutor-frontend
src/main/scala/com/automatatutor/model/User.scala
Scala
mit
5,575
import org.scalatest._ // abstract general testing class abstract class UnitTestSpec extends FlatSpec with Matchers with OptionValues with Inside with Inspectors case class ConditionResolver(val check:Boolean) { def skip(ignore: () => Unit) = Executor(check, ignore) } case class Executor(val flag:Boolean, val ignore: () => Unit) { def makeItHappen(action: => Unit) { if (flag) action else ignore.apply } def otherwise(action: => Unit) { makeItHappen (action) } } trait ConditionSpec { private def resolve(negate:Boolean, expression: => Boolean): ConditionResolver = { ConditionResolver(negate ^ expression) } def unless(expression: => Boolean): ConditionResolver = resolve(false, expression) def `if`(expression: => Boolean): ConditionResolver = resolve(true, expression) }
sadikovi/sbt-multi-project-example
bar/src/test/scala/UnitTestSpec.scala
Scala
mit
819
package threesbrain.game.consoleplay import threesbrain.game.core.Play object ConsolePlay extends App { val end = Play.play(ConsolePlayer) println(end) println("Score: " + end.score) }
zommerfelds/threes-brain
src/main/scala/threesbrain/game/consoleplay/ConsolePlay.scala
Scala
mit
198
package org.jetbrains.plugins.scala.lang.typeInference package generated import org.jetbrains.plugins.scala.lang.typeInference.testInjectors.{SCL9532Injector, SCL9445Injector, SCL9533Injector, SCL9865Injector} class TypeInferenceBugs5Test extends TypeInferenceTestBase { //This class was generated by build script, please don't change this override def folderPath: String = super.folderPath + "bugs5/" def testAnyPatternMatching(): Unit = doTest() def testAssignmentNotImported(): Unit = doTest() def testCloseable(): Unit = doTest() def testCompoundTypeConformance(): Unit = doTest() def testCompoundTypeUnapply(): Unit = doTest() def testCyclicGetClass(): Unit = doTest() def testDeeperLub(): Unit = doTest() def testDefaultParamInference(): Unit = doTest() def testEA52539(): Unit = doTest() def testExistentialConformance(): Unit = doTest() def testExistentialConformance2(): Unit = doTest() def testExpectedOption(): Unit = doTest() def testFakePrimitiveConversion(): Unit = doTest() def testForStmtBug(): Unit = doTest() def testFromTwitter(): Unit = doTest() def testImplicitClause(): Unit = doTest() def testImplicitlyAddedExtractor(): Unit = doTest() def testImplicitTest(): Unit = doTest() def testImplicitVsNone(): Unit = { doTest() } def testInfixApply(): Unit = doTest() def testJavaArrayType(): Unit = doTest() def testParametersLub(): Unit = doTest() def testParenthesisedUnderscore(): Unit = doTest() def testParenthesisedUnderscore2(): Unit = doTest() def testPatternInterpolation(): Unit = doTest() def testRecursiveFunction(): Unit = doTest() def testRepeatedParams(): Unit = doTest() def testRepeatedParamsResolve(): Unit = doTest() def testSCL1971(): Unit = doTest() def testSCL2055(): Unit = doTest() def testSCL2292(): Unit = doTest() def testSCL2929(): Unit = doTest() def testSCL2936(): Unit = doTest() def testSCL3052(): Unit = doTest() def testSCL3074(): Unit = doTest() def testSCL3288(): Unit = doTest() def testSCL2381A(): Unit = doTest() def testSCL2381B(): Unit = doTest() def testSCL2381C(): Unit = doTest() def testSCL2381D(): Unit = doTest() def testSCL2426(): Unit = doTest() def testSCL2480(): Unit = doTest() def testSCL2487(): Unit = doTest() def testSCL2493(): Unit = doTest() def testSCL2618(): Unit = doTest() def testSCL2656(): Unit = doTest() def testSCL2777A(): Unit = doTest() def testSCL2777B(): Unit = doTest() def testSCL3063(): Unit = doTest() def testSCL2806(): Unit = doTest() def testSCL2806B(): Unit = doTest() def testSCL2817(): Unit = doTest() def testSCL2820(): Unit = doTest() def testSCL2889(): Unit = doTest() def testSCL2893(): Unit = doTest() def testSCL3076(): Unit = doTest() def testSCL3123(): Unit = doTest() def testSCL3213(): Unit = doTest() def testSCL3216(): Unit = doTest() def testSCL3275(): Unit = doTest() def testSCL3277(): Unit = doTest() def testSCL3278A(): Unit = doTest() def testSCL3328(): Unit = doTest() def testSCL3329(): Unit = doTest() def testSCL3330(): Unit = doTest() def testSCL3338(): Unit = doTest() def testSCL3343(): Unit = doTest() def testSCL3347(): Unit = doTest() def testSCL3351(): Unit = doTest() def testSCL3354(): Unit = doTest() def testSCL3367(): Unit = doTest() def testSCL3590(): Unit = doTest() def testSCL3372(): Unit = doTest() def testSCL3385(): Unit = doTest() def testSCL3394(): Unit = doTest() def testSCL3412(): Unit = doTest() def testSCL3414A(): Unit = doTest() def testSCL3414B(): Unit = doTest() def testSCL3414C(): Unit = doTest() def testSCL3414D(): Unit = doTest() def testSCL3414E(): Unit = doTest() def testSCL3414F(): Unit = doTest() def testSCL3414G(): Unit = doTest() def testSCL3426(): Unit = doTest() def testSCL3427(): Unit = doTest() def testSCL3429(): Unit = doTest() def testSCL3455(): Unit = doTest() def testSCL3460(): Unit = doTest() def testSCL3468(): Unit = doTest() def testSCL3470(): Unit = doTest() def testSCL3482(): Unit = doTest() def testSCL3487(): Unit = doTest() def testSCL3496(): Unit = doTest() def testSCL3512(): Unit = doTest() def testSCL3517A(): Unit = doTest() def testSCL3517B(): Unit = doTest() def testSCL3517C(): Unit = doTest() def testSCL3537(): Unit = doTest() def testSCL3540(): Unit = doTest() def testSCL3542(): Unit = doTest() def testSCL3544(): Unit = doTest() def testSCL3549A(): Unit = doTest() def testSCL3549B(): Unit = doTest() def testSCL3552(): Unit = doTest() def testSCL3555(): Unit = doTest() def testSCL3565(): Unit = doTest() def testSCL3567(): Unit = doTest() def testSCL3603A(): Unit = doTest() def testSCL3603B(): Unit = doTest() def testSCL3654(): Unit = doTest() def testSCL3654B(): Unit = doTest() def testSCL3730(): Unit = doTest() def testSCL3735(): Unit = doTest() def testSCL3738(): Unit = doTest() def testSCL3766(): Unit = doTest() def testSCL3796(): Unit = doTest() def testSCL3801A(): Unit = doTest() def testSCL3801B(): Unit = doTest() def testSCL3817(): Unit = doTest() def testSCL3833(): Unit = doTest() def testSCL3834(): Unit = doTest() def testSCL3845(): Unit = doTest() def testSCL3854(): Unit = doTest() def testSCL3865(): Unit = doTest() def testSCL3877(): Unit = doTest() def testSCL3893(): Unit = doTest() def testSCL3908A(): Unit = doTest() def testSCL3908B(): Unit = doTest() def testSCL3912(): Unit = doTest() def testSCL3975(): Unit = doTest() def testSCL4031(): Unit = doTest() def testSCL4040(): Unit = doTest() def testSCL4052(): Unit = doTest() def testSCL4065(): Unit = doTest() def testSCL4077(): Unit = doTest() def testSCL4092(): Unit = doTest() def testSCL4093(): Unit = doTest() def testSCL4095A(): Unit = doTest() def testSCL4095B(): Unit = doTest() def testSCL4095C(): Unit = doTest() def testSCL4095D(): Unit = doTest() def testSCL4095E(): Unit = doTest() def testSCL4139(): Unit = doTest() def testSCL4150A(): Unit = doTest() def testSCL4150B(): Unit = doTest() def testSCL4150C(): Unit = doTest() def testSCL4150D(): Unit = doTest() def testSCL4158(): Unit = doTest() def testSCL4163A(): Unit = doTest() def testSCL4163B(): Unit = doTest() def testSCL4163C(): Unit = doTest() def testSCL4163D(): Unit = doTest() def testSCL4163E(): Unit = doTest() def testSCL4163F(): Unit = doTest() def testSCL4163G(): Unit = doTest() def testSCL4169(): Unit = doTest() def testSCL4186(): Unit = doTest() def testSCL4200(): Unit = doTest() def testSCL4276(): Unit = doTest() def testSCL4282(): Unit = doTest() def testSCL4293(): Unit = doTest() def testSCL4312(): Unit = doTest() def testSCL4321(): Unit = doTest() def testSCL4324(): Unit = doTest() def testSCL4353A(): Unit = doTest() def testSCL4353B(): Unit = doTest() def testSCL4353C(): Unit = doTest() def testSCL4354(): Unit = doTest() def testSCL4357(): Unit = doTest() def testSCL4357B(): Unit = doTest() def testSCL4363A(): Unit = doTest() def testSCL4363B(): Unit = doTest() def testSCL4375(): Unit = doTest() def testSCL4380(): Unit = doTest() def testSCL4389(): Unit = doTest() def testSCL4416(): Unit = doTest() def testSCL4432(): Unit = doTest() def testSCL4451(): Unit = doTest() def testSCL4478(): Unit = doTest() def testSCL4482(): Unit = doTest() def testSCL4493(): Unit = doTest() def testSCL4500(): Unit = doTest() def testSCL4513(): Unit = doTest() def testSCL4545(): Unit = doTest() def testSCL4558(): Unit = doTest() def testSCL4559A(): Unit = doTest() def testSCL4559B(): Unit = doTest() def testSCL4589(): Unit = doTest() def testSCL4617(): Unit = doTest() def testSCL4650(): Unit = doTest() def testSCL4651(): Unit = doTest() def testSCL4656(): Unit = doTest() def testSCL4685(): Unit = doTest() def testSCL4695(): Unit = doTest() def testSCL4718(): Unit = doTest() def testSCL4740(): Unit = doTest() def testSCL4749(): Unit = doTest() def testSCL4801(): Unit = doTest() def testSCL4807(): Unit = doTest() def testSCL4809(): Unit = doTest() def testSCL4823(): Unit = doTest() def testSCL4891A(): Unit = doTest() def testSCL4897(): Unit = doTest() def testSCL4904(): Unit = doTest() def testSCL4938(): Unit = doTest() def testSCL4981(): Unit = doTest() def testSCL5023(): Unit = doTest() def testSCL5029(): Unit = doTest() def testSCL5030(): Unit = doTest() def testSCL5033(): Unit = doTest() def testSCL5048(): Unit = doTest() def testSCL5048B(): Unit = doTest() def testSCL5055(): Unit = doTest() def testSCL5060(): Unit = doTest() def testSCL5081(): Unit = doTest() def testSCL5104(): Unit = doTest() def testSCL5144(): Unit = doTest() def testSCL5159(): Unit = doTest() def testSCL5180(): Unit = doTest() def testSCL5183(): Unit = { doTest( s""" |class D |def foo[Q >: List[T], T >: D](): Q = List(new D) | |val x = foo() | |${START}x$END |//List[D] """.stripMargin) } def testSCL5185(): Unit = doTest() def testSCL5192(): Unit = doTest() def testSCL5193(): Unit = doTest() def testSCL5197(): Unit = doTest() def testSCL5222(): Unit = doTest() def testSCL5247(): Unit = doTest() def testSCL5250(): Unit = doTest() def testSCL5269(): Unit = doTest() def testSCL5303(): Unit = doTest() def testSCL5356(): Unit = doTest() def testSCL5337(): Unit = doTest() def testSCL5361(): Unit = doTest() def testSCL5393(): Unit = doTest() def testSCL5429(): Unit = doTest() def testSCL5454(): Unit = doTest() def testSCL5472(): Unit = doTest() def testSCL5472A(): Unit = doTest() def testSCL5472B(): Unit = doTest() def testSCL5472C(): Unit = doTest() def testSCL5475(): Unit = doTest() def testSCL5489(): Unit = doTest() def testSCL5538(): Unit = doTest() def testSCL5594(): Unit = doTest() def testSCL5650A(): Unit = doTest() def testSCL5650B(): Unit = doTest() def testSCL5650C(): Unit = doTest() def testSCL5661(): Unit = doTest() def testSCL5669(): Unit = doTest() def testSCL5669A(): Unit = doTest() def testSCL5669B(): Unit = doTest() def testSCL5681(): Unit = doTest() def testSCL5729(): Unit = doTest() def testSCL5733(): Unit = doTest() def testSCL5736(): Unit = doTest() def testSCL5737(): Unit = doTest() def testSCL5738(): Unit = doTest() def testSCL5744(): Unit = doTest() def testSCL5834(): Unit = doTest() def testSCL5840(): Unit = doTest() def testSCL5854(): Unit = doTest( """ |object SCL5854 { | | case class MayErr[+E, +A](e: Either[E, A]) | | object MayErr { | import scala.language.implicitConversions | implicit def eitherToError[E, EE >: E, A, AA >: A](e: Either[E, A]): MayErr[EE, AA] = MayErr[E, A](e) | } | | abstract class SQLError | | import scala.collection.JavaConverters._ | def convert = { | val m = new java.util.HashMap[String, String] | m.asScala.toMap | } | | /*start*/MayErr.eitherToError(Right(convert))/*end*/: MayErr[SQLError, Map[String, String]] |} | |//SCL5854.MayErr[SCL5854.SQLError, Map[String, String]] """.stripMargin ) def testSCL5856(): Unit = doTest() def testSCL5982(): Unit = doTest() def testSCL6022(): Unit = doTest() def testSCL6025(): Unit = doTest() def testSCL6079(): Unit = doTest() def testSCL6089(): Unit = doTest() def testSCL6091(): Unit = doTest() def testSCL6116(): Unit = doTest() def testSCL6118(): Unit = doTest() def testSCL6118B(): Unit = doTest() def testSCL6123(): Unit = doTest() def testSCL6157(): Unit = doTest() def testSCL6158(): Unit = doTest() def testSCL6169(): Unit = doTest() def testSCL6177(): Unit = doTest() def testSCL6195(): Unit = doTest() def testSCL6198(): Unit = doTest() def testSCL6235(): Unit = doTest() def testSCL6259(): Unit = doTest() def testSCL6270(): Unit = doTest() def testSCL6304(): Unit = doTest() def testSCL6309(): Unit = doTest() def testSCL6350(): Unit = doTest() def testSCL6386(): Unit = doTest() def testSCL6507(): Unit = doTest() def testSCL6511(): Unit = doTest() def testSCL6514(): Unit = doTest() def testSCL6541(): Unit = doTest() def testSCL6549(): Unit = doTest() def testSCL6601(): Unit = doTest() def testSCL6601B(): Unit = doTest() def testSCL6605A(): Unit = doTest() def testSCL6605B(): Unit = doTest() def testSCL6605C(): Unit = doTest() def testSCL6608(): Unit = doTest() def testSCL6608B(): Unit = doTest() def testSCL6658(): Unit = doTest() def testSCL6660(): Unit = doTest() def testSCL6667(): Unit = doTest() def testSCL6730(): Unit = doTest() def testSCL6730B(): Unit = doTest() def testSCL6736(): Unit = { doTest( s"""val concatenate = "%s%s" format (_: String, _: String ) |${START}concatenate$END |//(String, String) => String""".stripMargin) } def testSCL6745(): Unit = doTest() def testSCL6786(): Unit = doTest() def testSCL6787(): Unit = doTest() def testSCL6807(): Unit = doTest() def testSCL6854(): Unit = doTest() def testSCL6885(): Unit = doTest() def testSCL6978(): Unit = doTest() def testSCL7008(): Unit = doTest() def testSCL7031(): Unit = doTest() def testSCL7036(): Unit = doTest() def testSCL7043(): Unit = doTest() def testSCL7100(): Unit = doTest() def testSCL7174(): Unit = doTest() def testSCL7192(): Unit = doTest() def testSCL7268(): Unit = doTest() def testSCL7278(): Unit = doTest() def testSCL7321(): Unit = doTest() def testSCL7322(): Unit = doTest() def testSCL7388(): Unit = doTest() def testSCL7388B(): Unit = doTest() def testSCL7388C(): Unit = doTest() def testSCL7404(): Unit = doTest() def testSCL7413(): Unit = doTest() def testSCL7502A(): Unit = doTest() def testSCL7518(): Unit = doTest() def testSCL7502B(): Unit = doTest() def testSCL7521(): Unit = doTest() def testSCL7521B(): Unit = doTest() def testSCL7544A(): Unit = doTest() def testSCL7544B(): Unit = doTest() def testSCL7604(): Unit = doTest() def testSCL7618(): Unit = doTest() def testSCL7805(): Unit = doTest() def testSCL7901(): Unit = doTest() def testSCL7927(): Unit = doTest() def testSCL8005(): Unit = doTest() def testSCL8005A(): Unit = doTest() def testSCL8036(): Unit = doTest() def testSCL8157A(): Unit = doTest() def testSCL8157B(): Unit = doTest() def testSCL8079(): Unit = doTest() def testSCL8119A(): Unit = doTest() def testSCL8119B(): Unit = doTest() def testSCL8178(): Unit = doTest() def testSCL8191(): Unit = doTest() def testSCL8232(): Unit = { doTest() } def testSCL8240(): Unit = doTest() def testSCL8241(): Unit = doTest() def testSCL8246(): Unit = doTest() def testSCL8261(): Unit = doTest() def testSCL8280(): Unit = doTest() def testSCL8282(): Unit = doTest() def testSCL8288(): Unit = doTest() def testSCL8317(): Unit = doTest() def testSCL8359(): Unit = doTest() def testSCL8398(): Unit = doTest() def testSCL5728(): Unit = doTest() def testSCL8705(): Unit = doTest( """ |trait Ura[M[_]] { self => | type S | | def start : M[S] | | def foo = new Ura[M] { | type S = (Ura.this.S, Int) | | def start = /*start*/self.start/*end*/ | } | |} |//M[Ura.this.S] """.stripMargin ) def testSCL8800(): Unit = doTest() def testSCL8933(): Unit = doTest() def testSCL8989(): Unit = doTest() def testSCL8995(): Unit = doTest() def testSCL9000(): Unit = doTest() def testSCL9052(): Unit = { doTest( s""" |case class Foo[T](a: T) | |class Bar[T] { | def fix(in: List[Foo[T]]): List[Foo[T]] = { | def it(i: List[Foo[T]], o: List[Foo[T]]): List[Foo[T]] = { | in match { | case c :: rest => | val x = c.copy() | it(i.tail, $START(x :: o)$END) | }} | it(in, Nil) |}} |//List[Foo[T]] """.stripMargin) } def testSCL9181(): Unit = doTest() def testSCL9306A(): Unit = doTest() def testSCL9306B(): Unit = doTest() def testSCL9426(): Unit = doTest() def testSCL9445(): Unit = doInjectorTest(new SCL9445Injector) def testSCL9473(): Unit = doTest() def testSCL9532(): Unit = doInjectorTest(new SCL9532Injector) def testSCL9533(): Unit = doInjectorTest(new SCL9533Injector) def testSCL9865(): Unit = doInjectorTest(new SCL9865Injector) def testSCL9877(): Unit = doTest() def testSCL10037() = doTest { """ |import scala.language.existentials |class SCL10037 { | | trait A | | trait B[a <: A]{ | def c:CWithA[a] | } | | trait C[a <: A, _ <: B[a]] | | type BAny = B[_ <: A] | type CWithA[a <: A] = C[a, _ <: B[a]] | type CAny = C[a, _ <: B[a]] forSome {type a <: A} | | def f(c:CAny): Int = 1 | def f(s: String): String = s | val b:BAny= null | /*start*/f(b.c)/*end*/ |} |//Int """.stripMargin.trim } def testSCL9877_1(): Unit = doTest() def testSCL9925(): Unit = { doTest( """ |object SCL9925 { | | abstract class Parser[+T] { | def |[U >: T](x: => Parser[U]): Parser[U] = ??? | } | | abstract class PerfectParser[+T] extends Parser[T] | | implicit def parser2packrat[T](p: => Parser[T]): PerfectParser[T] = ??? | | def foo: PerfectParser[String] = ??? | | def foo1: PerfectParser[Nothing] = ??? | | def fooo4: PerfectParser[String] = /*start*/foo | foo1 | foo1/*end*/ |} | |//SCL9925.PerfectParser[String] """.stripMargin) } def testSCL9929() = doTest() def testSOE(): Unit = doTest() def testSOE2(): Unit = doTest() def testSOEFix(): Unit = doTest() def testUnaryMethods(): Unit = doTest() def testTupleAnonymous(): Unit = doTest() def testTupleExpectedType(): Unit = doTest() def testTupleExpectedType2(): Unit = doTest() def test10471A(): Unit = { val code = """ |package outer { | package a { | class Foo | } | package object a { | class B | implicit def string2Foo(s: String): Foo = new Foo | } |} | |package b { | import outer.a.Foo | | object Moo { | def baz(m: Foo): Foo = { | /*start*/""/*end*/ | } | } |} |//Foo """.stripMargin doTest(code) } def test10471B(): Unit = { val code = """ |package outer { | | import outer.a.c.Foo | package a { | package c { | class Foo | | } | } | package object a { | implicit def string2Foo(s: String): Foo = new Foo | } |} | |package b { | import outer.a.c.Foo | | object Moo { | def baz(m: Foo): Foo = { | /*start*/""/*end*/ | } | } |} |//Foo """.stripMargin doTest(code) } def testEmptyImplicits(): Unit = { val code = """ |trait A { | def foo: Int = 1 |} | |implicit class AExt(a: A) { | def foo(x : Int = 1): Boolean = false |} | |val l : List[A] = List(new A {}) | |/*start*/l.map(_.foo())/*end*/ |//List[Boolean] """.stripMargin doTest(code) } def testEarlyDefRecursion(): Unit = doTest() def testSCL7474(): Unit = doTest( """ | object Repro { | | import scala.collection.generic.IsTraversableLike | | def head[A](a: A)(implicit itl: IsTraversableLike[A]): itl.A = itl.conversion(a).head | | val one: Int = /*start*/head(Vector(1, 2, 3))/*end*/ | } | | //Int""".stripMargin ) // wrong highlighting in scala lang 2.10. // 2.11, 2.12 - ok def testSCL9677(): Unit = doTest( s""" |import scala.concurrent.Future | | |val s = for (i <- 1 to 100) yield Future.successful(0) // infers IndexedSeq[Future[Int]] correctly | |//Future.sequence(s) //correct |Future.sequence{${START}s$END} | |//IndexedSeq[Future[Int]] """.stripMargin) def testSCL11142(): Unit = { addFileToProject("Tier1.java", """public final class Tier1 { | public static final class Tier2 { | public static final class Tier3 | } |}""".stripMargin) doTest( """object SCL11142 { | /*start*/new Tier1.Tier2.Tier3/*end*/ |} |//Tier2.Tier3 """.stripMargin) } def testSCL9432(): Unit = doTest { """ |object SCL9432 { | def f(int: Int): Option[Int] = if (int % 2 == 0) Some(int) else None | def g(as: List[Int])(b: Int): Option[Int] = if (as contains b) None else f(b) | /*start*/List(1) flatMap g(List(2, 4))/*end*/ |} |//List[Int] """.stripMargin.trim } def testSCL7010(): Unit = doTest { """ |object O { | case class Z() | def Z(i: Int) = 123 | val x: Int => Int = /*start*/Z/*end*/ | } |//Int => Int """.stripMargin.trim } def testSCL8267(): Unit = doTest() def testSCL9119(): Unit = doTest { """ |object ApplyBug { | class Foo { | def apply(t: Int): Int = 2 | } | | def foo = new Foo | def a(i: Int): Int = /*start*/new Foo()(i)/*end*/ |} |//Int """.stripMargin.trim } def testSCL9858(): Unit = doTest { """ |trait TX { | type T |} | |def recursiveFn(a: TX)(b: a.T): a.T = { | val res: a.T = /*start*/recursiveFn(a)(b)/*end*/ | res |} |//a.T """.stripMargin.trim } }
triplequote/intellij-scala
scala/scala-impl/test/org/jetbrains/plugins/scala/lang/typeInference/generated/TypeInferenceBugs5Test.scala
Scala
apache-2.0
22,606
/** * Copyright (C) 2016 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 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 Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.fr.persistence.relational import java.sql.{Connection, PreparedStatement, ResultSet} import org.orbeon.io.IOUtils._ object Statement { type Setter = (PreparedStatement, Int) => Unit case class StatementPart( sql : String, setters: List[Setter] ) val NilPart = StatementPart("", Nil) def buildQuery(parts: List[StatementPart]): String = parts .map { case StatementPart(partSQL, _) => partSQL } .mkString("\\n") def executeQuery[T]( connection : Connection, sql : String, parts : List[StatementPart])( block : ResultSet => T ): T = { useAndClose(connection.prepareStatement(sql)) { ps => val index = Iterator.from(1) parts .map(_.setters) .foreach(setters => setters.foreach(setter => setter(ps, index.next()))) useAndClose(ps.executeQuery())(block) } } }
orbeon/orbeon-forms
form-runner/jvm/src/main/scala/org/orbeon/oxf/fr/persistence/relational/Statement.scala
Scala
lgpl-2.1
1,571
/* * Copyright (c) 2017 Magomed Abdurakhmanov, Hypertino * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * */ package com.hypertino.hyperbus.util import com.hypertino.hyperbus.model.{ErrorBody, HyperbusError, InternalServerError, MessagingContext} import monix.eval.Task import scala.util.{Failure, Success, Try} object ErrorUtils { def unexpected[T](r: Any)(implicit mcx: MessagingContext): T = throw toHyperbusError(r) def unexpectedTask[T](r: Any)(implicit mcx: MessagingContext): Task[T] = Task.raiseError(toHyperbusError(r)) def unexpected[T](implicit mcx: MessagingContext): PartialFunction[Try[_], T] = { case x β‡’ unexpected(x)(mcx) } def unexpectedTask[T](implicit mcx: MessagingContext): PartialFunction[Try[_], Task[T]] = { case x β‡’ unexpectedTask(x)(mcx) } def toHyperbusError(r: Any)(implicit mcx: MessagingContext): HyperbusError[_] = { r match { case e: HyperbusError[_] β‡’ e case Failure(e: HyperbusError[_]) β‡’ e case Success(s: Any) β‡’ InternalServerError (ErrorBody ("unexpected", Some (s"Unexpected result: $r") ) ) case Failure(e: Throwable) β‡’ InternalServerError (ErrorBody ("unexpected_error", Some (e.toString) ) ) case _ β‡’ InternalServerError (ErrorBody ("unexpected", Some (s"Unexpected result: $r") ) ) } } }
hypertino/hyperbus
hyperbus/src/main/scala/com/hypertino/hyperbus/util/ErrorUtils.scala
Scala
mpl-2.0
1,479
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.sql.catalyst.expressions import org.apache.spark.SparkException import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow} import org.apache.spark.sql.catalyst.expressions.codegen._ import org.apache.spark.sql.types.DataType /** * User-defined function. * @param function The user defined scala function to run. * Note that if you use primitive parameters, you are not able to check if it is * null or not, and the UDF will return null for you if the primitive input is * null. Use boxed type or [[Option]] if you wanna do the null-handling yourself. * @param dataType Return type of function. * @param children The input expressions of this UDF. * @param inputTypes The expected input types of this UDF, used to perform type coercion. If we do * not want to perform coercion, simply use "Nil". Note that it would've been * better to use Option of Seq[DataType] so we can use "None" as the case for no * type coercion. However, that would require more refactoring of the codebase. * @param udfName The user-specified name of this UDF. * @param nullable True if the UDF can return null value. * @param udfDeterministic True if the UDF is deterministic. Deterministic UDF returns same result * each time it is invoked with a particular input. */ case class ScalaUDF( function: AnyRef, dataType: DataType, children: Seq[Expression], inputTypes: Seq[DataType] = Nil, udfName: Option[String] = None, nullable: Boolean = true, udfDeterministic: Boolean = true) extends Expression with ImplicitCastInputTypes with NonSQLExpression with UserDefinedExpression { // The constructor for SPARK 2.1 and 2.2 def this( function: AnyRef, dataType: DataType, children: Seq[Expression], inputTypes: Seq[DataType], udfName: Option[String]) = { this( function, dataType, children, inputTypes, udfName, nullable = true, udfDeterministic = true) } override lazy val deterministic: Boolean = udfDeterministic && children.forall(_.deterministic) override def toString: String = s"${udfName.map(name => s"UDF:$name").getOrElse("UDF")}(${children.mkString(", ")})" // scalastyle:off line.size.limit /** This method has been generated by this script (1 to 22).map { x => val anys = (1 to x).map(x => "Any").reduce(_ + ", " + _) val childs = (0 to x - 1).map(x => s"val child$x = children($x)").reduce(_ + "\\n " + _) val converters = (0 to x - 1).map(x => s"lazy val converter$x = CatalystTypeConverters.createToScalaConverter(child$x.dataType)").reduce(_ + "\\n " + _) val evals = (0 to x - 1).map(x => s"converter$x(child$x.eval(input))").reduce(_ + ",\\n " + _) s"""case $x => val func = function.asInstanceOf[($anys) => Any] $childs $converters (input: InternalRow) => { func( $evals) } """ }.foreach(println) */ private[this] val f = children.size match { case 0 => val func = function.asInstanceOf[() => Any] (input: InternalRow) => { func() } case 1 => val func = function.asInstanceOf[(Any) => Any] val child0 = children(0) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) (input: InternalRow) => { func( converter0(child0.eval(input))) } case 2 => val func = function.asInstanceOf[(Any, Any) => Any] val child0 = children(0) val child1 = children(1) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input))) } case 3 => val func = function.asInstanceOf[(Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input))) } case 4 => val func = function.asInstanceOf[(Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input))) } case 5 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input))) } case 6 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input))) } case 7 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input))) } case 8 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input))) } case 9 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input))) } case 10 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input))) } case 11 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input))) } case 12 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input))) } case 13 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input))) } case 14 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) val child13 = children(13) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) lazy val converter13 = CatalystTypeConverters.createToScalaConverter(child13.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input)), converter13(child13.eval(input))) } case 15 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) val child13 = children(13) val child14 = children(14) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) lazy val converter13 = CatalystTypeConverters.createToScalaConverter(child13.dataType) lazy val converter14 = CatalystTypeConverters.createToScalaConverter(child14.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input)), converter13(child13.eval(input)), converter14(child14.eval(input))) } case 16 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) val child13 = children(13) val child14 = children(14) val child15 = children(15) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) lazy val converter13 = CatalystTypeConverters.createToScalaConverter(child13.dataType) lazy val converter14 = CatalystTypeConverters.createToScalaConverter(child14.dataType) lazy val converter15 = CatalystTypeConverters.createToScalaConverter(child15.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input)), converter13(child13.eval(input)), converter14(child14.eval(input)), converter15(child15.eval(input))) } case 17 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) val child13 = children(13) val child14 = children(14) val child15 = children(15) val child16 = children(16) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) lazy val converter13 = CatalystTypeConverters.createToScalaConverter(child13.dataType) lazy val converter14 = CatalystTypeConverters.createToScalaConverter(child14.dataType) lazy val converter15 = CatalystTypeConverters.createToScalaConverter(child15.dataType) lazy val converter16 = CatalystTypeConverters.createToScalaConverter(child16.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input)), converter13(child13.eval(input)), converter14(child14.eval(input)), converter15(child15.eval(input)), converter16(child16.eval(input))) } case 18 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) val child13 = children(13) val child14 = children(14) val child15 = children(15) val child16 = children(16) val child17 = children(17) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) lazy val converter13 = CatalystTypeConverters.createToScalaConverter(child13.dataType) lazy val converter14 = CatalystTypeConverters.createToScalaConverter(child14.dataType) lazy val converter15 = CatalystTypeConverters.createToScalaConverter(child15.dataType) lazy val converter16 = CatalystTypeConverters.createToScalaConverter(child16.dataType) lazy val converter17 = CatalystTypeConverters.createToScalaConverter(child17.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input)), converter13(child13.eval(input)), converter14(child14.eval(input)), converter15(child15.eval(input)), converter16(child16.eval(input)), converter17(child17.eval(input))) } case 19 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) val child13 = children(13) val child14 = children(14) val child15 = children(15) val child16 = children(16) val child17 = children(17) val child18 = children(18) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) lazy val converter13 = CatalystTypeConverters.createToScalaConverter(child13.dataType) lazy val converter14 = CatalystTypeConverters.createToScalaConverter(child14.dataType) lazy val converter15 = CatalystTypeConverters.createToScalaConverter(child15.dataType) lazy val converter16 = CatalystTypeConverters.createToScalaConverter(child16.dataType) lazy val converter17 = CatalystTypeConverters.createToScalaConverter(child17.dataType) lazy val converter18 = CatalystTypeConverters.createToScalaConverter(child18.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input)), converter13(child13.eval(input)), converter14(child14.eval(input)), converter15(child15.eval(input)), converter16(child16.eval(input)), converter17(child17.eval(input)), converter18(child18.eval(input))) } case 20 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) val child13 = children(13) val child14 = children(14) val child15 = children(15) val child16 = children(16) val child17 = children(17) val child18 = children(18) val child19 = children(19) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) lazy val converter13 = CatalystTypeConverters.createToScalaConverter(child13.dataType) lazy val converter14 = CatalystTypeConverters.createToScalaConverter(child14.dataType) lazy val converter15 = CatalystTypeConverters.createToScalaConverter(child15.dataType) lazy val converter16 = CatalystTypeConverters.createToScalaConverter(child16.dataType) lazy val converter17 = CatalystTypeConverters.createToScalaConverter(child17.dataType) lazy val converter18 = CatalystTypeConverters.createToScalaConverter(child18.dataType) lazy val converter19 = CatalystTypeConverters.createToScalaConverter(child19.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input)), converter13(child13.eval(input)), converter14(child14.eval(input)), converter15(child15.eval(input)), converter16(child16.eval(input)), converter17(child17.eval(input)), converter18(child18.eval(input)), converter19(child19.eval(input))) } case 21 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) val child13 = children(13) val child14 = children(14) val child15 = children(15) val child16 = children(16) val child17 = children(17) val child18 = children(18) val child19 = children(19) val child20 = children(20) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) lazy val converter13 = CatalystTypeConverters.createToScalaConverter(child13.dataType) lazy val converter14 = CatalystTypeConverters.createToScalaConverter(child14.dataType) lazy val converter15 = CatalystTypeConverters.createToScalaConverter(child15.dataType) lazy val converter16 = CatalystTypeConverters.createToScalaConverter(child16.dataType) lazy val converter17 = CatalystTypeConverters.createToScalaConverter(child17.dataType) lazy val converter18 = CatalystTypeConverters.createToScalaConverter(child18.dataType) lazy val converter19 = CatalystTypeConverters.createToScalaConverter(child19.dataType) lazy val converter20 = CatalystTypeConverters.createToScalaConverter(child20.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input)), converter13(child13.eval(input)), converter14(child14.eval(input)), converter15(child15.eval(input)), converter16(child16.eval(input)), converter17(child17.eval(input)), converter18(child18.eval(input)), converter19(child19.eval(input)), converter20(child20.eval(input))) } case 22 => val func = function.asInstanceOf[(Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any, Any) => Any] val child0 = children(0) val child1 = children(1) val child2 = children(2) val child3 = children(3) val child4 = children(4) val child5 = children(5) val child6 = children(6) val child7 = children(7) val child8 = children(8) val child9 = children(9) val child10 = children(10) val child11 = children(11) val child12 = children(12) val child13 = children(13) val child14 = children(14) val child15 = children(15) val child16 = children(16) val child17 = children(17) val child18 = children(18) val child19 = children(19) val child20 = children(20) val child21 = children(21) lazy val converter0 = CatalystTypeConverters.createToScalaConverter(child0.dataType) lazy val converter1 = CatalystTypeConverters.createToScalaConverter(child1.dataType) lazy val converter2 = CatalystTypeConverters.createToScalaConverter(child2.dataType) lazy val converter3 = CatalystTypeConverters.createToScalaConverter(child3.dataType) lazy val converter4 = CatalystTypeConverters.createToScalaConverter(child4.dataType) lazy val converter5 = CatalystTypeConverters.createToScalaConverter(child5.dataType) lazy val converter6 = CatalystTypeConverters.createToScalaConverter(child6.dataType) lazy val converter7 = CatalystTypeConverters.createToScalaConverter(child7.dataType) lazy val converter8 = CatalystTypeConverters.createToScalaConverter(child8.dataType) lazy val converter9 = CatalystTypeConverters.createToScalaConverter(child9.dataType) lazy val converter10 = CatalystTypeConverters.createToScalaConverter(child10.dataType) lazy val converter11 = CatalystTypeConverters.createToScalaConverter(child11.dataType) lazy val converter12 = CatalystTypeConverters.createToScalaConverter(child12.dataType) lazy val converter13 = CatalystTypeConverters.createToScalaConverter(child13.dataType) lazy val converter14 = CatalystTypeConverters.createToScalaConverter(child14.dataType) lazy val converter15 = CatalystTypeConverters.createToScalaConverter(child15.dataType) lazy val converter16 = CatalystTypeConverters.createToScalaConverter(child16.dataType) lazy val converter17 = CatalystTypeConverters.createToScalaConverter(child17.dataType) lazy val converter18 = CatalystTypeConverters.createToScalaConverter(child18.dataType) lazy val converter19 = CatalystTypeConverters.createToScalaConverter(child19.dataType) lazy val converter20 = CatalystTypeConverters.createToScalaConverter(child20.dataType) lazy val converter21 = CatalystTypeConverters.createToScalaConverter(child21.dataType) (input: InternalRow) => { func( converter0(child0.eval(input)), converter1(child1.eval(input)), converter2(child2.eval(input)), converter3(child3.eval(input)), converter4(child4.eval(input)), converter5(child5.eval(input)), converter6(child6.eval(input)), converter7(child7.eval(input)), converter8(child8.eval(input)), converter9(child9.eval(input)), converter10(child10.eval(input)), converter11(child11.eval(input)), converter12(child12.eval(input)), converter13(child13.eval(input)), converter14(child14.eval(input)), converter15(child15.eval(input)), converter16(child16.eval(input)), converter17(child17.eval(input)), converter18(child18.eval(input)), converter19(child19.eval(input)), converter20(child20.eval(input)), converter21(child21.eval(input))) } } // scalastyle:on line.size.limit override def doGenCode( ctx: CodegenContext, ev: ExprCode): ExprCode = { val converterClassName = classOf[Any => Any].getName // The type converters for inputs and the result. val converters: Array[Any => Any] = children.map { c => CatalystTypeConverters.createToScalaConverter(c.dataType) }.toArray :+ CatalystTypeConverters.createToCatalystConverter(dataType) val convertersTerm = ctx.addReferenceObj("converters", converters, s"$converterClassName[]") val errorMsgTerm = ctx.addReferenceObj("errMsg", udfErrorMessage) val resultTerm = ctx.freshName("result") // codegen for children expressions val evals = children.map(_.genCode(ctx)) // Generate the codes for expressions and calling user-defined function // We need to get the boxedType of dataType's javaType here. Because for the dataType // such as IntegerType, its javaType is `int` and the returned type of user-defined // function is Object. Trying to convert an Object to `int` will cause casting exception. val evalCode = evals.map(_.code).mkString("\\n") val (funcArgs, initArgs) = evals.zipWithIndex.map { case (eval, i) => val argTerm = ctx.freshName("arg") val convert = s"$convertersTerm[$i].apply(${eval.value})" val initArg = s"Object $argTerm = ${eval.isNull} ? null : $convert;" (argTerm, initArg) }.unzip val udf = ctx.addReferenceObj("udf", function, s"scala.Function${children.length}") val getFuncResult = s"$udf.apply(${funcArgs.mkString(", ")})" val resultConverter = s"$convertersTerm[${children.length}]" val boxedType = CodeGenerator.boxedType(dataType) val callFunc = s""" |$boxedType $resultTerm = null; |try { | $resultTerm = ($boxedType)$resultConverter.apply($getFuncResult); |} catch (Exception e) { | throw new org.apache.spark.SparkException($errorMsgTerm, e); |} """.stripMargin ev.copy(code = s""" |$evalCode |${initArgs.mkString("\\n")} |$callFunc | |boolean ${ev.isNull} = $resultTerm == null; |${CodeGenerator.javaType(dataType)} ${ev.value} = ${CodeGenerator.defaultValue(dataType)}; |if (!${ev.isNull}) { | ${ev.value} = $resultTerm; |} """.stripMargin) } private[this] val resultConverter = CatalystTypeConverters.createToCatalystConverter(dataType) lazy val udfErrorMessage = { val funcCls = function.getClass.getSimpleName val inputTypes = children.map(_.dataType.simpleString).mkString(", ") s"Failed to execute user defined function($funcCls: ($inputTypes) => ${dataType.simpleString})" } override def eval(input: InternalRow): Any = { val result = try { f(input) } catch { case e: Exception => throw new SparkException(udfErrorMessage, e) } resultConverter(result) } }
ddna1021/spark
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/ScalaUDF.scala
Scala
apache-2.0
52,837
package io.buoyant.namerd.iface import com.fasterxml.jackson.annotation.JsonIgnore import com.twitter.conversions.time._ import com.twitter.finagle._ import com.twitter.finagle.buoyant.TlsClientConfig import com.twitter.finagle.naming.NameInterpreter import com.twitter.finagle.param.{HighResTimer, Label} import com.twitter.finagle.service._ import com.twitter.logging.Logger import com.twitter.util.{NonFatal => _, _} import io.buoyant.admin.Admin import io.buoyant.admin.Admin.{Handler, NavItem} import io.buoyant.namer.{InterpreterInitializer, NamespacedInterpreterConfig} import io.buoyant.namerd.iface.{thriftscala => thrift} import scala.util.control.NonFatal /** * The namerd interpreter offloads the responsibilities of name resolution to * the namerd service via the namerd thrift API. Any namers configured in this * linkerd are not used. */ class NamerdInterpreterInitializer extends InterpreterInitializer { val configClass = classOf[NamerdInterpreterConfig] override def configId: String = "io.l5d.namerd" } object NamerdInterpreterInitializer extends NamerdInterpreterInitializer case class Retry( baseSeconds: Int, maxSeconds: Int ) { if (baseSeconds <= 0 || maxSeconds <= 0 || baseSeconds > maxSeconds) { val msg = s"illegal retry values: baseSeconds=$baseSeconds maxSeconds=$maxSeconds" throw new IllegalArgumentException(msg) } } case class ClientTlsConfig(commonName: String, caCert: Option[String]) { def params: Stack.Params = { TlsClientConfig( disableValidation = Some(false), commonName = Some(commonName), trustCerts = caCert.map(Seq(_)), clientAuth = None ).params } } case class NamerdInterpreterConfig( dst: Option[Path], namespace: Option[String], retry: Option[Retry], tls: Option[ClientTlsConfig] ) extends NamespacedInterpreterConfig { config => @JsonIgnore private[this] val log = Logger.get() @JsonIgnore val defaultRetry = Retry(5, 10.minutes.inSeconds) /** * Construct a namer. */ @JsonIgnore def newInterpreter(params: Stack.Params): NameInterpreter = { val name = dst match { case None => throw new IllegalArgumentException("`dst` is a required field") case Some(dst) => Name.Path(dst) } val label = s"interpreter/${NamerdInterpreterConfig.kind}" val Retry(baseRetry, maxRetry) = retry.getOrElse(defaultRetry) val backoffs = Backoff.exponentialJittered(baseRetry.seconds, maxRetry.seconds) // replaces the client's retry filter with one that retries unconditionally val retryTransformer = new Stack.Transformer { def apply[Req, Rsp](stk: Stack[ServiceFactory[Req, Rsp]]) = stk.replace(Retries.Role, module[Req, Rsp]) def module[Req, Rsp]: Stackable[ServiceFactory[Req, Rsp]] = new Stack.Module1[param.Stats, ServiceFactory[Req, Rsp]] { val role = Retries.Role val description = "Retries on any non-fatal error" def make(_stats: param.Stats, next: ServiceFactory[Req, Rsp]) = { val param.Stats(stats) = _stats val retry = new RetryFilter[Req, Rsp]( RetryPolicy.backoff(backoffs) { case (_, Throw(NonFatal(ex))) => log.error(ex, "namerd request failed") true }, HighResTimer.Default, stats, RetryBudget.Infinite ) retry.andThen(next) } } } val param.Stats(stats0) = params[param.Stats] val stats = stats0.scope(label) val tlsParams = tls.map(_.params).getOrElse(Stack.Params.empty) val client = ThriftMux.client .withParams(ThriftMux.client.params ++ tlsParams ++ params + Thrift.ThriftImpl.Netty4) .transformed(retryTransformer) .withSessionQualifier.noFailFast .withSessionQualifier.noFailureAccrual val iface = client.newIface[thrift.Namer.FutureIface](name, label) val ns = namespace.getOrElse("default") val Label(routerLabel) = params[Label] new ThriftNamerClient(iface, ns, stats) with Admin.WithHandlers with Admin.WithNavItems { val handler = new NamerdHandler(Seq(routerLabel -> config), Map(routerLabel -> this)) override def adminHandlers: Seq[Handler] = Seq(Handler("/namerd", handler, css = Seq("delegator.css"))) override def navItems: Seq[NavItem] = Seq(NavItem("namerd", "namerd")) } } } object NamerdInterpreterConfig { def kind = classOf[NamerdInterpreterConfig].getCanonicalName }
denverwilliams/linkerd
interpreter/namerd/src/main/scala/io/buoyant/namerd/iface/NamerdInterpreterInitializer.scala
Scala
apache-2.0
4,528
final class Natural extends scala.math.ScalaNumber with scala.math.ScalaNumericConversions { def intValue: Int = 0 def longValue: Long = 0L def floatValue: Float = 0.0F def doubleValue: Double = 0.0D def isWhole: Boolean = false def underlying = this }
lrytz/scala
test/files/pos/t6600.scala
Scala
apache-2.0
265
// goseumdochi: experiments with incarnation // Copyright 2016 John V. Sichi // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.goseumdochi.android.lib import android.app._ import android.content._ import android.content.pm._ import android.os._ import android.widget._ import android.support.v7.app._ import com.typesafe.config._ trait ContextBase { def getApplicationContext() : Context protected def toastLong(resId : Int) { toastLong(getApplicationContext.getString(resId)) } protected def toastLong(msg : String) { Toast.makeText(getApplicationContext, msg, Toast.LENGTH_LONG).show } } trait ActivityBaseNoCompat extends Activity with ContextBase { protected final val PERMISSION_REQUEST = 42 protected lazy val config = ConfigFactory.load( getApplication.asInstanceOf[MultidexApplication].getResourceClassLoader, "android.conf") protected def hasPermission(permission : String) = { (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) || (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) } } trait ActivityBase extends AppCompatActivity with ActivityBaseNoCompat { }
lingeringsocket/goseumdochi
android/src/main/scala/org/goseumdochi/android/lib/ActivityBase.scala
Scala
apache-2.0
1,669
package org.workcraft.services abstract class Format(val description: String, val extension: String) object Format { case object DotG extends Format("Signal Transition Graph", ".g") case object LolaPetriNet extends Format("Petri Net in LoLA format", ".lola") case object WorkcraftPetriNet extends Format("Petri Net in Workcraft format", ".pn") case object Dot extends Format("GraphViz dot", ".dot") case object Llnet extends Format("Petri Net in PEP tool format", ".ll_net") }
tuura/workcraft-2.2
Core/src/main/scala/org/workcraft/services/Format.scala
Scala
gpl-3.0
489
package com.aimplicits.gallery import org.scalatest.{MustMatchers, WordSpec} /** * Created by Paul Lysak on 14/08/17. */ class SampleSpec extends WordSpec with MustMatchers { "something" must { "work" in { //TODO } } }
paul-lysak/gallery-proto
gallery_cookies_lambda/src/test/scala/com/aimplicits/gallery/SampleSpec.scala
Scala
apache-2.0
244
package uk.gov.dvla.vehicles.presentation.common.helpers import uk.gov.dvla.vehicles.presentation.common.composition.TestComposition import uk.gov.dvla.vehicles.presentation.common.testhelpers.UnitTestHelper abstract class UnitSpec extends UnitTestHelper with TestComposition
dvla/vehicles-presentation-common
common-test/test/uk/gov/dvla/vehicles/presentation/common/helpers/UnitSpec.scala
Scala
mit
278
// Copyright: 2010 - 2016 https://github.com/ensime/ensime-server/graphs // License: http://www.gnu.org/licenses/gpl-3.0.en.html package org.ensime.indexer import akka.event.slf4j.SLF4JLogging import java.io.File import org.apache.commons.vfs2._ import org.ensime.api._ import org.ensime.vfs._ import org.ensime.util.file._ import org.ensime.util.list._ import org.ensime.util.map._ // mutable: lookup of user's source files are atomically updated class SourceResolver( config: EnsimeConfig )( implicit vfs: EnsimeVFS ) extends FileChangeListener with SLF4JLogging { def fileAdded(f: FileObject) = if (relevant(f)) update() def fileRemoved(f: FileObject) = if (relevant(f)) update() def fileChanged(f: FileObject) = {} def relevant(f: FileObject): Boolean = f.getName.isFile && { val file = new File(f.getName.getURI) (file.isScala || file.isJava) && !file.getPath.contains(".ensime_cache") } // we only support the case where RawSource has a Some(filename) def resolve(clazz: PackageName, source: RawSource): Option[FileObject] = source.filename match { case None => None case Some(filename) => all.get(clazz) flatMap { _.find(_.getName.getBaseName == filename) } match { case s @ Some(_) => s case None if clazz.path == Nil => None case _ => resolve(clazz.parent, source) } } def update(): Unit = { log.debug("updating sources") all = recalculate } private def scan(f: FileObject) = f.findFiles(SourceSelector) match { case null => Nil case res => res.toList } private val depSources = { val srcJars = config.referenceSourceJars.toSet ++ { for { (_, module) <- config.modules srcArchive <- module.referenceSourceJars } yield srcArchive } for { srcJarFile <- srcJars.toList // interestingly, this is able to handle zip files srcJar = vfs.vjar(srcJarFile) srcEntry <- scan(srcJar) inferred = infer(srcJar, srcEntry) // continue to hold a reference to source jars // so that we can access their contents elsewhere. // this does mean we have a file handler, sorry. //_ = vfs.nuke(srcJar) } yield (inferred, srcEntry) }.toMultiMapSet private def userSources = { for { (_, module) <- config.modules.toList root <- module.sourceRoots dir = vfs.vfile(root) file <- scan(dir) } yield (infer(dir, file), file) }.toMultiMapSet private def recalculate = depSources merge userSources private var all = recalculate private def infer(base: FileObject, file: FileObject): PackageName = { // getRelativeName feels the wrong way round, but this is correct val relative = base.getName.getRelativeName(file.getName) // vfs separator char is always / PackageName((relative split "/").toList.init) } }
sugakandrey/ensime-server
core/src/main/scala/org/ensime/indexer/SourceResolver.scala
Scala
gpl-3.0
2,881
/*********************************************************************** * Copyright (c) 2013-2017 Commonwealth Computer Research, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License, Version 2.0 * which accompanies this distribution and is available at * http://www.opensource.org/licenses/apache2.0.php. ***********************************************************************/ package org.locationtech.geomesa.features.avro.serde import java.util.{Date, UUID} import com.vividsolutions.jts.geom.Geometry import org.apache.avro.io.Decoder import org.locationtech.geomesa.features.avro.{AvroSimpleFeatureUtils, AvroSimpleFeature} /** * Trait that encapsulates the methods needed to deserialize * an AvroSimpleFeature */ trait ASFDeserializer { def setString(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = sf.setAttributeNoConvert(field, in.readString()) def setInt(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = sf.setAttributeNoConvert(field, in.readInt().asInstanceOf[Object]) def setDouble(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = sf.setAttributeNoConvert(field, in.readDouble().asInstanceOf[Object]) def setLong(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = sf.setAttributeNoConvert(field, in.readLong().asInstanceOf[Object]) def setFloat(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = sf.setAttributeNoConvert(field, in.readFloat().asInstanceOf[Object]) def setBool(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = sf.setAttributeNoConvert(field, in.readBoolean().asInstanceOf[Object]) def setUUID(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = { val bb = in.readBytes(null) sf.setAttributeNoConvert(field, AvroSimpleFeatureUtils.decodeUUID(bb)) } def setDate(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = sf.setAttributeNoConvert(field, new Date(in.readLong())) def setList(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = { val bb = in.readBytes(null) sf.setAttributeNoConvert(field, AvroSimpleFeatureUtils.decodeList(bb)) } def setMap(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = { val bb = in.readBytes(null) sf.setAttributeNoConvert(field, AvroSimpleFeatureUtils.decodeMap(bb)) } def setBytes(sf: AvroSimpleFeature, field: String, in:Decoder): Unit = { val bb = in.readBytes(null) val bytes = new Array[Byte](bb.remaining) bb.get(bytes) sf.setAttributeNoConvert(field, bytes) } def setGeometry(sf: AvroSimpleFeature, field: String, in:Decoder): Unit def consumeGeometry(in: Decoder): Unit def buildConsumeFunction(cls: Class[_]) = cls match { case c if classOf[java.lang.String].isAssignableFrom(cls) => (in: Decoder) => in.skipString() case c if classOf[java.lang.Integer].isAssignableFrom(cls) => (in: Decoder) => in.readInt() case c if classOf[java.lang.Long].isAssignableFrom(cls) => (in: Decoder) => in.readLong() case c if classOf[java.lang.Double].isAssignableFrom(cls) => (in: Decoder) => in.readDouble() case c if classOf[java.lang.Float].isAssignableFrom(cls) => (in: Decoder) => in.readFloat() case c if classOf[java.lang.Boolean].isAssignableFrom(cls) => (in: Decoder) => in.readBoolean() case c if classOf[UUID].isAssignableFrom(cls) => (in: Decoder) => in.skipBytes() case c if classOf[Date].isAssignableFrom(cls) => (in: Decoder) => in.readLong() case c if classOf[Geometry].isAssignableFrom(cls) => (in: Decoder) => consumeGeometry(in) case c if classOf[java.util.List[_]].isAssignableFrom(cls) => (in: Decoder) => in.skipBytes() case c if classOf[java.util.Map[_, _]].isAssignableFrom(cls) => (in: Decoder) => in.skipBytes() case c if classOf[Array[Byte]].isAssignableFrom(cls) => (in: Decoder) => in.skipBytes() } }
ronq/geomesa
geomesa-features/geomesa-feature-avro/src/main/scala/org/locationtech/geomesa/features/avro/serde/ASFDeserializer.scala
Scala
apache-2.0
3,991
package core class DispatchContext(val game: Game, channel: Channel) extends Receiver { private[this] val mailbox = collection.mutable.Queue.empty[(Receiver, Message)] private[this] var inputRequirer: Option[(Receiver, String)] = None private[this] val logBuffer = new StringBuilder() channel.subscribeInput(handleInput) def send(receiver: Receiver, message: Message) { mailbox.enqueue((receiver, message)) } def receive(message: Message, context: DispatchContext) { message match { case InputRequired(dialogMessage, sender) => inputRequirer = Some(sender, dialogMessage) }} def log(content: String) { logBuffer.append(content) logBuffer.append(Utils.newline) } private[this] def handleInput(input: String): (String, Boolean) = { inputRequirer match { case Some((receiver, _)) => send(receiver, InputArrived(input)) case None => } inputRequirer = None processMailbox() val bufferOutput = logBuffer.toString() logBuffer.clear() inputRequirer match { case Some((_, dialogMessage)) => (bufferOutput + dialogMessage, true) case None => (bufferOutput, false) } } @annotation.tailrec private[this] final def processMailbox() { if (!inputRequirer.isDefined && !mailbox.isEmpty) { val (receiver, message) = mailbox.dequeue() receiver.receive(message, this) processMailbox() } } } trait Receiver { def receive(message: Message, context: DispatchContext) } trait Channel { def subscribeInput(handler: String => (String, Boolean)) }
whence/powerlife
scala/powercards_actor/core/Dispatch.scala
Scala
mit
1,594
package rea.examples import rea._ import P._ object Drawing { val winSize = Vec(640, 360) val win = Win(size = winSize, clear = false, bkg = Color(102)) object ContinuousLines { def draw(p: Boolean, a: Vec, b: Vec) { if (p) { line(a, b) } } def main = win.setup(stroke(255)).run { Get.lift(draw, mousePressed.map(x => true).getOrElse(false), mouse, pmouse) } } object Patterns { def variableEllipse(a: Vec, b: Vec) { val speed = a.l1(b) stroke(speed) circle(a, speed) } def main = win.run { Get.lift(variableEllipse, mouse, pmouse) } } }
anton-k/reactive-processing
src/main/scala/examples/Drawing.scala
Scala
bsd-3-clause
596
package simple import org.scalatest._ class SimpleSpec extends FlatSpec { "Calling native methods in tests" should "work" in { assert(Library.say("hello") == 42) } }
jodersky/sbt-jni
plugin/src/sbt-test/sbt-jni/simple/core/src/test/scala/simple/Test.scala
Scala
bsd-3-clause
178
import annotation.* import elidable.* trait T { @elidable(FINEST) def f1(): Unit @elidable(SEVERE) def f2(): Unit @elidable(FINEST) def f3() = assert(false, "Should have been elided.") def f4(): Unit } class C extends T { def f1() = println("Good for me, I was not elided. C.f1") def f2() = println("Good for me, I was not elided. C.f2") @elidable(FINEST) def f4() = assert(false, "Should have been elided.") } object O { @elidable(FINEST) def f1() = assert(false, "Should have been elided.") @elidable(INFO) def f2() = assert(false, "Should have been elided.") @elidable(SEVERE) def f3() = println("Good for me, I was not elided. O.f3") @elidable(INFO) def f4 = assert(false, "Should have been elided (no parens).") } object Test { @elidable(FINEST) def f1() = assert(false, "Should have been elided.") @elidable(INFO) def f2() = assert(false, "Should have been elided.") @elidable(SEVERE) def f3() = println("Good for me, I was not elided. Test.f3") @elidable(INFO) def f4 = assert(false, "Should have been elided (no parens).") @elidable(FINEST) def f5() = {} @elidable(FINEST) def f6() = true @elidable(FINEST) def f7() = 1:Byte @elidable(FINEST) def f8() = 1:Short @elidable(FINEST) def f9() = 1:Char @elidable(FINEST) def fa() = 1 @elidable(FINEST) def fb() = 1l @elidable(FINEST) def fc() = 1.0f @elidable(FINEST) def fd() = 1.0 @elidable(FINEST) def fe() = "s" def main(args: Array[String]): Unit = { f1() f2() f3() f4 O.f1() O.f2() O.f3() O.f4 val c = new C c.f1() c.f2() c.f3() c.f4() // make sure a return value is still available when eliding a call println(f5()) println(f6()) println(f7()) println(f8()) println(f9().toInt) println(fa()) println(fb()) println(fc()) println(fd()) println(fe()) // this one won't show up in the output because a call to f1 is elidable when accessed through T (c:T).f1() // Test whether the method definitions are still available. List("Test", "Test$", "O", "O$", "C", "T") foreach { className => List("f1", "f2", "f3", "f4") foreach { methodName => Class.forName(className).getMethod(methodName) } } List("Test", "Test$") foreach { className => List("f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe") foreach { methodName => Class.forName(className).getMethod(methodName) } } Class.forName("T$class").getMethod("f3", classOf[T]) } }
dotty-staging/dotty
tests/pending/run/elidable.scala
Scala
apache-2.0
2,520
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.plan.rules.logical import java.util import org.apache.calcite.plan.RelOptRule.{none, operand} import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall} import org.apache.calcite.rex.RexProgram import org.apache.flink.table.expressions.Expression import org.apache.flink.table.plan.schema.TableSourceTable import org.apache.flink.table.plan.util.RexProgramExtractor import org.apache.flink.table.plan.nodes.logical.{FlinkLogicalCalc, FlinkLogicalTableSourceScan} import org.apache.flink.table.sources.FilterableTableSource import org.apache.flink.table.validate.FunctionCatalog import org.apache.flink.util.Preconditions import scala.collection.JavaConverters._ class PushFilterIntoTableSourceScanRule extends RelOptRule( operand(classOf[FlinkLogicalCalc], operand(classOf[FlinkLogicalTableSourceScan], none)), "PushFilterIntoTableSourceScanRule") { override def matches(call: RelOptRuleCall): Boolean = { val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] val scan: FlinkLogicalTableSourceScan = call.rel(1).asInstanceOf[FlinkLogicalTableSourceScan] scan.tableSource match { case source: FilterableTableSource[_] => calc.getProgram.getCondition != null && !source.isFilterPushedDown case _ => false } } override def onMatch(call: RelOptRuleCall): Unit = { val calc: FlinkLogicalCalc = call.rel(0).asInstanceOf[FlinkLogicalCalc] val scan: FlinkLogicalTableSourceScan = call.rel(1).asInstanceOf[FlinkLogicalTableSourceScan] val tableSourceTable = scan.getTable.unwrap(classOf[TableSourceTable[_]]) val filterableSource = scan.tableSource.asInstanceOf[FilterableTableSource[_]] pushFilterIntoScan(call, calc, scan, tableSourceTable, filterableSource, description) } private def pushFilterIntoScan( call: RelOptRuleCall, calc: FlinkLogicalCalc, scan: FlinkLogicalTableSourceScan, tableSourceTable: TableSourceTable[_], filterableSource: FilterableTableSource[_], description: String): Unit = { Preconditions.checkArgument(!filterableSource.isFilterPushedDown) val program = calc.getProgram val functionCatalog = FunctionCatalog.withBuiltIns val (predicates, unconvertedRexNodes) = RexProgramExtractor.extractConjunctiveConditions( program, call.builder().getRexBuilder, functionCatalog) if (predicates.isEmpty) { // no condition can be translated to expression return } val remainingPredicates = new util.LinkedList[Expression]() predicates.foreach(e => remainingPredicates.add(e)) val newTableSource = filterableSource.applyPredicate(remainingPredicates) // check whether framework still need to do a filter val relBuilder = call.builder() val remainingCondition = { if (!remainingPredicates.isEmpty || unconvertedRexNodes.nonEmpty) { relBuilder.push(scan) val remainingConditions = (remainingPredicates.asScala.map(expr => expr.toRexNode(relBuilder)) ++ unconvertedRexNodes) remainingConditions.reduce((l, r) => relBuilder.and(l, r)) } else { null } } // check whether we still need a RexProgram. An RexProgram is needed when either // projection or filter exists. val newScan = scan.copy(scan.getTraitSet, newTableSource) val newRexProgram = { if (remainingCondition != null || !program.projectsOnlyIdentity) { val expandedProjectList = program.getProjectList.asScala .map(ref => program.expandLocalRef(ref)).asJava RexProgram.create( program.getInputRowType, expandedProjectList, remainingCondition, program.getOutputRowType, relBuilder.getRexBuilder) } else { null } } if (newRexProgram != null) { val newCalc = calc.copy(calc.getTraitSet, newScan, newRexProgram) call.transformTo(newCalc) } else { call.transformTo(newScan) } } } object PushFilterIntoTableSourceScanRule { val INSTANCE: RelOptRule = new PushFilterIntoTableSourceScanRule }
hongyuhong/flink
flink-libraries/flink-table/src/main/scala/org/apache/flink/table/plan/rules/logical/PushFilterIntoTableSourceScanRule.scala
Scala
apache-2.0
4,954
/* * Copyright 2014 Lars Edenbrandt * * 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 se.nimsa.sbx.app.routing import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import se.nimsa.sbx.app.SliceboxBase trait UiRoutes { this: SliceboxBase => def staticResourcesRoute = get { path(Remaining) { remaining => getFromResource("public/" + remaining) } } def angularRoute = get { getFromResource("public/index.html") } def faviconRoutes: Route = path("apple-touch-icon-57x57.png") { getFromResource("public/images/favicons/apple-touch-icon-57x57.png") } ~ path("apple-touch-icon-60x60.png") { getFromResource("public/images/favicons/apple-touch-icon-60x60.png") } ~ path("apple-touch-icon-72x72.png") { getFromResource("public/images/favicons/apple-touch-icon-72x72.png") } ~ path("apple-touch-icon-76x76.png") { getFromResource("public/images/favicons/apple-touch-icon-76x76.png") } ~ path("apple-touch-icon-114x114.png") { getFromResource("public/images/favicons/apple-touch-icon-114x114.png") } ~ path("apple-touch-icon-120x120.png") { getFromResource("public/images/favicons/apple-touch-icon-120x120.png") } ~ path("apple-touch-icon-144x144.png") { getFromResource("public/images/favicons/apple-touch-icon-144x144.png") } ~ path("apple-touch-icon-152x152.png") { getFromResource("public/images/favicons/apple-touch-icon-152x152.png") } ~ path("apple-touch-icon-180x180.png") { getFromResource("public/images/favicons/apple-touch-icon-180x180.png") } ~ path("favicon.ico") { getFromResource("public/images/favicons/favicon.ico") } ~ path("favicon-16x16.png") { getFromResource("public/images/favicons/favicon-16x16.png") } ~ path("favicon-32x32.png") { getFromResource("public/images/favicons/favicon-32x32.png") } ~ path("favicon-96x96.png") { getFromResource("public/images/favicons/favicon-96x96.png") } ~ path("favicon-194x194.png") { getFromResource("public/images/favicons/favicon-194x194.png") } ~ path("android-chrome-36x36.png") { getFromResource("public/images/favicons/android-chrome-36x36.png") } ~ path("android-chrome-48x48.png") { getFromResource("public/images/favicons/android-chrome-48x48.png") } ~ path("android-chrome-72x72.png") { getFromResource("public/images/favicons/android-chrome-72x72.png") } ~ path("android-chrome-96x96.png") { getFromResource("public/images/favicons/android-chrome-96x96.png") } ~ path("android-chrome-144x144.png") { getFromResource("public/images/favicons/android-chrome-144x144.png") } ~ path("android-chrome-192x192.png") { getFromResource("public/images/favicons/android-chrome-192x192.png") } ~ path("mstile-70x70.png") { getFromResource("public/images/favicons/mstile-70x70.png") } ~ path("mstile-144x144.png") { getFromResource("public/images/favicons/mstile-144x144.png") } ~ path("mstile-150x150.png") { getFromResource("public/images/favicons/mstile-150x150.png") } ~ path("mstile-310x150.png") { getFromResource("public/images/favicons/mstile-310x150.png") } ~ path("mstile-310x310.png") { getFromResource("public/images/favicons/mstile-310x310.png") } ~ path("manifest.json") { getFromResource("public/images/favicons/manifest.json") } ~ path("browserconfig.xml") { getFromResource("public/images/favicons/browserconfig.xml") } }
slicebox/slicebox
src/main/scala/se/nimsa/sbx/app/routing/UiRoutes.scala
Scala
apache-2.0
4,068
/* * Copyright 2001-2008 Artima, 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 org.scalatest.fixture import org.scalatest._ import collection.immutable.TreeSet // import Suite._ import java.lang.reflect.{InvocationTargetException, Method, Modifier} import org.scalatest.events._ import org.scalatest.Suite._ import exceptions.{TestCanceledException, TestPendingException} import OutcomeOf.outcomeOf /** * Base trait for a family of style traits that can pass a fixture object into tests. * * <p> * <strong>Prior to ScalaTest 2.0.M4, trait <code>fixture.Suite</code> served two purposes: 1) It served as the base * class of ScalaTest's family of "fixture" style traits, and 2) It was itself a style trait in which tests are methods * that take a fixture parameter. Although it will continue to serve its first purpose, <code>fixture.Suite</code> has * been deprecated as a style trait. Pre-existing code that used <code>fixture.Suite</code> as a style trait to define * tests as methods will continue to work during the deprecation period, but will generate a deprecation warning. Please * change all such uses of <code>fixture.Suite</code> to use trait <a href="Spec.html"><code>fixture.Spec</code></a> instead.</strong> * </p> * * @author Bill Venners */ @Finders(Array("org.scalatest.finders.MethodFinder")) trait Suite extends org.scalatest.Suite { thisSuite => /** * The type of the fixture parameter that can be passed into tests in this suite. */ protected type FixtureParam /** * Trait whose instances encapsulate a test function that takes a fixture and config map. * * <p> * The <code>fixture.Suite</code> trait's implementation of <code>runTest</code> passes instances of this trait * to <code>fixture.Suite</code>'s <code>withFixture</code> method, such as: * </p> * * <pre class="stHighlight"> * def testSomething(fixture: Fixture) { * // ... * } * def testSomethingElse(fixture: Fixture, info: Informer) { * // ... * } * </pre> * * <p> * For more detail and examples, see the * <a href="Suite.html">documentation for trait <code>fixture.Suite</code></a>. * </p> */ protected trait OneArgTest extends (FixtureParam => Outcome) with TestData { thisOneArgTest => /** * Run the test, using the passed <code>FixtureParam</code>. */ def apply(fixture: FixtureParam): Outcome /** * Convert this <code>OneArgTest</code> to a <code>NoArgTest</code> whose * <code>name</code> and <code>configMap</code> methods return the same values * as this <code>OneArgTest</code>, and whose <code>apply</code> method invokes * this <code>OneArgTest</code>'s apply method, * passing in the given <code>fixture</code>. * * <p> * This method makes it easier to invoke the <code>withFixture</code> method * that takes a <code>NoArgTest</code>. For example, if a <code>fixture.Suite</code> * mixes in <code>SeveredStackTraces</code>, it will inherit an implementation * of <code>withFixture(NoArgTest)</code> provided by * <code>SeveredStackTraces</code> that implements the stack trace severing * behavior. If the <code>fixture.Suite</code> does not delegate to that * <code>withFixture(NoArgTest)</code> method, the stack trace severing behavior * will not happen. Here's how that might look in a <code>fixture.Suite</code> * whose <code>FixtureParam</code> is <code>StringBuilder</code>: * </p> * * <pre class="stHighlight"> * def withFixture(test: OneArgTest) = { * withFixture(test.toNoArgTest(new StringBuilder)) * } * </pre> */ def toNoArgTest(fixture: FixtureParam) = new NoArgTest { val name = thisOneArgTest.name val configMap = thisOneArgTest.configMap def apply(): Outcome = { thisOneArgTest(fixture) } val scopes = thisOneArgTest.scopes val text = thisOneArgTest.text val tags = thisOneArgTest.tags } } /** * Run the passed test function with a fixture created by this method. * * <p> * This method should create the fixture object needed by the tests of the * current suite, invoke the test function (passing in the fixture object), * and if needed, perform any clean up needed after the test completes. * For more detail and examples, see the <a href="Suite.html">main documentation for this trait</a>. * </p> * * @param fun the <code>OneArgTest</code> to invoke, passing in a fixture */ protected def withFixture(test: OneArgTest): Outcome private[fixture] class TestFunAndConfigMap(val name: String, test: FixtureParam => Any, val configMap: ConfigMap) extends OneArgTest { def apply(fixture: FixtureParam): Outcome = { outcomeOf { test(fixture) } } private val testData = testDataFor(name, configMap) val scopes = testData.scopes val text = testData.text val tags = testData.tags } private[fixture] class FixturelessTestFunAndConfigMap(override val name: String, test: () => Any, override val configMap: ConfigMap) extends NoArgTest { def apply(): Outcome = { outcomeOf { test() } } private val testData = testDataFor(name, configMap) val scopes = testData.scopes val text = testData.text val tags = testData.tags } // TODO: add documentation here, so people know they can pass an Informer as the second arg. override def testNames: Set[String] = { def takesTwoParamsOfTypesAnyAndInformer(m: Method) = { val paramTypes = m.getParameterTypes val hasTwoParams = paramTypes.length == 2 hasTwoParams && classOf[Informer].isAssignableFrom(paramTypes(1)) } def takesOneParamOfAnyType(m: Method) = m.getParameterTypes.length == 1 def isTestMethod(m: Method) = { // Factored out to share code with Suite.testNames val (isInstanceMethod, simpleName, firstFour, paramTypes, hasNoParams, isTestNames, isTestTags, isTestDataFor) = isTestMethodGoodies(m) // Also, will discover both // testNames(Object) and testNames(Object, Informer). Reason is if I didn't discover these // it would likely just be silently ignored, and that might waste users' time isInstanceMethod && (firstFour == "test") && !isTestDataFor && ((hasNoParams && !isTestNames && !isTestTags) || takesInformer(m) || takesOneParamOfAnyType(m) || takesTwoParamsOfTypesAnyAndInformer(m)) } val testNameArray = for (m <- getClass.getMethods; if isTestMethod(m)) yield if (takesInformer(m)) m.getName + InformerInParens else if (takesOneParamOfAnyType(m)) m.getName + FixtureInParens else if (takesTwoParamsOfTypesAnyAndInformer(m)) m.getName + FixtureAndInformerInParens else m.getName TreeSet[String]() ++ testNameArray } protected override def runTest(testName: String, args: Args): Status = { if (testName == null) throw new NullPointerException("testName was null") if (args == null) throw new NullPointerException("args was null") import args._ val (stopRequested, report, method, testStartTime) = getSuiteRunTestGoodies(thisSuite, stopper, reporter, testName) reportTestStarting(thisSuite, report, tracker, testName, testName, thisSuite.rerunner, Some(getTopOfMethod(thisSuite, testName))) val formatter = getEscapedIndentedTextForTest(testName, 1, true) val messageRecorderForThisTest = new MessageRecorder(report) val informerForThisTest = MessageRecordingInformer( messageRecorderForThisTest, (message, payload, isConstructingThread, testWasPending, testWasCanceled, location) => createInfoProvided(thisSuite, report, tracker, Some(testName), message, payload, 2, location, isConstructingThread, true) ) val documenterForThisTest = MessageRecordingDocumenter( messageRecorderForThisTest, (message, _, isConstructingThread, testWasPending, testWasCanceled, location) => createInfoProvided(thisSuite, report, tracker, Some(testName), message, None, 2, location, isConstructingThread, true) // TODO: Need a test that fails because testWasCanceleed isn't being passed ) // TODO: Use a message recorder in FixtureSuite. Maybe just allow the state and // use Engine in Suite, though then I'd have two Engines in everything. Or even three down here. // Nah, go ahead and use message recording informer here, and maybe find some other way to // reduce the duplication between Suite, FixtureSuite, and Engine. try { if (testMethodTakesAFixtureAndInformer(testName) || testMethodTakesAFixture(testName)) { val testFun: FixtureParam => Unit = { (fixture: FixtureParam) => { val anyRefFixture: AnyRef = fixture.asInstanceOf[AnyRef] // TODO zap this cast val args: Array[Object] = if (testMethodTakesAFixtureAndInformer(testName)) { Array(anyRefFixture, informerForThisTest) } else Array(anyRefFixture) method.invoke(thisSuite, args: _*) } } withFixture(new TestFunAndConfigMap(testName, testFun, configMap)).toUnit } else { // Test method does not take a fixture val testFun: () => Unit = { () => { val args: Array[Object] = if (testMethodTakesAnInformer(testName)) Array(informerForThisTest) else Array() method.invoke(this, args: _*) } } withFixture(new FixturelessTestFunAndConfigMap(testName, testFun, configMap)).toUnit } val duration = System.currentTimeMillis - testStartTime reportTestSucceeded(thisSuite, report, tracker, testName, testName, messageRecorderForThisTest.recordedEvents(false, false), duration, formatter, thisSuite.rerunner, Some(getTopOfMethod(thisSuite, method))) SucceededStatus } catch { case ite: InvocationTargetException => val t = ite.getTargetException t match { case _: TestPendingException => val duration = System.currentTimeMillis - testStartTime // testWasPending = true so info's printed out in the finally clause show up yellow reportTestPending(thisSuite, report, tracker, testName, testName, messageRecorderForThisTest.recordedEvents(true, false), duration, formatter, Some(getTopOfMethod(thisSuite, method))) SucceededStatus case e: TestCanceledException => val duration = System.currentTimeMillis - testStartTime val message = getMessageForException(e) val formatter = getEscapedIndentedTextForTest(testName, 1, true) // testWasCanceled = true so info's printed out in the finally clause show up yellow report(TestCanceled(tracker.nextOrdinal(), message, thisSuite.suiteName, thisSuite.suiteId, Some(thisSuite.getClass.getName), testName, testName, messageRecorderForThisTest.recordedEvents(false, true), Some(e), Some(duration), Some(formatter), Some(getTopOfMethod(thisSuite, method)), thisSuite.rerunner)) SucceededStatus case e if !anExceptionThatShouldCauseAnAbort(e) => val duration = System.currentTimeMillis - testStartTime handleFailedTest(thisSuite, t, testName, messageRecorderForThisTest.recordedEvents(false, false), report, tracker, getEscapedIndentedTextForTest(testName, 1, true), duration) FailedStatus case e => throw e } case e if !anExceptionThatShouldCauseAnAbort(e) => val duration = System.currentTimeMillis - testStartTime handleFailedTest(thisSuite, e, testName, messageRecorderForThisTest.recordedEvents(false, false), report, tracker, getEscapedIndentedTextForTest(testName, 1, true), duration) FailedStatus case e: Throwable => throw e } } /* // Overriding this in fixture.Suite to reduce duplication of tags method private[scalatest] override def getMethodForTestName(theSuite: org.scalatest.Suite, testName: String): Method = { val candidateMethods = theSuite.getClass.getMethods.filter(_.getName == Suite.simpleNameForTest(testName)) val found = if (testMethodTakesAFixtureAndInformer(testName)) candidateMethods.find( candidateMethod => { val paramTypes = candidateMethod.getParameterTypes paramTypes.length == 2 && paramTypes(1) == classOf[Informer] } ) else if (testMethodTakesAnInformer(testName)) candidateMethods.find( candidateMethod => { val paramTypes = candidateMethod.getParameterTypes paramTypes.length == 1 && paramTypes(0) == classOf[Informer] } ) else if (testMethodTakesAFixture(testName)) candidateMethods.find( candidateMethod => { val paramTypes = candidateMethod.getParameterTypes paramTypes.length == 1 } ) else candidateMethods.find(_.getParameterTypes.length == 0) found match { case Some(method) => method case None => throw new IllegalArgumentException(Resources("testNotFound", testName)) } } */ /** * Suite style name. */ override val styleName: String = "org.scalatest.fixture.Suite" } /* private[scalatest] object Suite { val FixtureAndInformerInParens = "(FixtureParam, Informer)" val FixtureInParens = "(FixtureParam)" private def testMethodTakesAFixtureAndInformer(testName: String) = testName.endsWith(FixtureAndInformerInParens) private[scalatest] def testMethodTakesAFixture(testName: String) = testName.endsWith(FixtureInParens) private[scalatest] def simpleNameForTest(testName: String) = if (testName.endsWith(FixtureAndInformerInParens)) testName.substring(0, testName.length - FixtureAndInformerInParens.length) else if (testName.endsWith(FixtureInParens)) testName.substring(0, testName.length - FixtureInParens.length) else if (testName.endsWith(InformerInParens)) testName.substring(0, testName.length - InformerInParens.length) else testName private def argsArrayForTestName(testName: String): Array[Class[_]] = if (testMethodTakesAFixtureAndInformer(testName)) Array(classOf[Object], classOf[Informer]) else Array(classOf[Informer]) } */
svn2github/scalatest
src/main/scala/org/scalatest/fixture/Suite.scala
Scala
apache-2.0
15,032
package config import java.io.File import com.typesafe.config.ConfigFactory import com.typesafe.scalalogging.LazyLogging object Config extends LazyLogging { implicit class RichConfig(val underlying: com.typesafe.config.Config) extends AnyVal { def getOptional[T](path: String, f: (String β‡’ T)) = if(underlying.hasPath(path)) { Some(f(path)) } else { None } } def readApiConfig(location: String) : Option[(Int, String)]= { val config = ConfigFactory.parseFile(new File("api.conf")) val keyOption = config.getOptional("api.keyId", config.getInt) keyOption match { case None β‡’ logger.error("You did not provide a keyId in the api.conf") case _ β‡’ } val verifCodeOption = config.getOptional("api.verificationCode", config.getString) verifCodeOption match { case None β‡’ logger.error("You did not provide a valid verificationCode in the api.conf") case _ β‡’ } for(key ← keyOption; verif ← verifCodeOption) yield { (key, verif) } } }
Calavoow/eve-corp-contracts
src/main/scala/config/Config.scala
Scala
gpl-2.0
995
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.table.plan.stream.sql.join import java.sql.Timestamp import org.apache.flink.api.scala._ import org.apache.flink.table.api.TableException import org.apache.flink.table.util.{StreamTableTestUtil, TableTestBase} import org.hamcrest.Matchers.containsString import org.junit.Test class TemporalJoinTest extends TableTestBase { val util: StreamTableTestUtil = streamTestUtil() val orders = util.addDataStream[(Long, String, Timestamp)]( "Orders", 'o_amount, 'o_currency, 'o_rowtime) val ratesHistory = util.addDataStream[(String, Int, Timestamp)]( "RatesHistory", 'currency, 'rate, 'rowtime) val rates = util.addFunction( "Rates", ratesHistory.createTemporalTableFunction("rowtime", "currency")) val proctimeOrders = util.addDataStream[(Long, String)]( "ProctimeOrders", 'o_amount, 'o_currency, 'o_proctime) val proctimeRatesHistory = util.addDataStream[(String, Int)]( "ProctimeRatesHistory", 'currency, 'rate, 'proctime) val proctimeRates = util.addFunction( "ProctimeRates", proctimeRatesHistory.createTemporalTableFunction("proctime", "currency")) @Test def testSimpleJoin(): Unit = { val sqlQuery = "SELECT " + "o_amount * rate as rate " + "FROM Orders AS o, " + "LATERAL TABLE (Rates(o.o_rowtime)) AS r " + "WHERE currency = o_currency" util.verifyPlan(sqlQuery) } @Test def testSimpleProctimeJoin(): Unit = { val sqlQuery = "SELECT " + "o_amount * rate as rate " + "FROM ProctimeOrders AS o, " + "LATERAL TABLE (ProctimeRates(o.o_proctime)) AS r " + "WHERE currency = o_currency" util.verifyPlan(sqlQuery) } /** * Test versioned joins with more complicated query. * Important thing here is that we have complex OR join condition * and there are some columns that are not being used (are being pruned). */ @Test def testComplexJoin(): Unit = { val util = streamTestUtil() util.addDataStream[(String, Int)]("Table3", 't3_comment, 't3_secondary_key) util.addDataStream[(Timestamp, String, Long, String, Int)]( "Orders", 'o_rowtime, 'o_comment, 'o_amount, 'o_currency, 'o_secondary_key) val ratesHistory = util.addDataStream[(Timestamp, String, String, Int, Int)]( "RatesHistory", 'rowtime, 'comment, 'currency, 'rate, 'secondary_key) val rates = util.tableEnv .sqlQuery("SELECT * FROM RatesHistory WHERE rate > 110") .createTemporalTableFunction("rowtime", "currency") util.addFunction("Rates", rates) val sqlQuery = "SELECT * FROM " + "(SELECT " + "o_amount * rate as rate, " + "secondary_key as secondary_key " + "FROM Orders AS o, " + "LATERAL TABLE (Rates(o_rowtime)) AS r " + "WHERE currency = o_currency OR secondary_key = o_secondary_key), " + "Table3 " + "WHERE t3_secondary_key = secondary_key" util.verifyPlan(sqlQuery) } @Test def testUncorrelatedJoin(): Unit = { expectedException.expect(classOf[TableException]) expectedException.expectMessage(containsString("Cannot generate a valid execution plan")) val sqlQuery = "SELECT " + "o_amount * rate as rate " + "FROM Orders AS o, " + "LATERAL TABLE (Rates(TIMESTAMP '2016-06-27 10:10:42.123')) AS r " + "WHERE currency = o_currency" util.verifyExplain(sqlQuery) } @Test def testTemporalTableFunctionScan(): Unit = { expectedException.expect(classOf[TableException]) expectedException.expectMessage(containsString("Cannot generate a valid execution plan")) val sqlQuery = "SELECT * FROM LATERAL TABLE (Rates(TIMESTAMP '2016-06-27 10:10:42.123'))" util.verifyExplain(sqlQuery) } }
shaoxuan-wang/flink
flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/plan/stream/sql/join/TemporalJoinTest.scala
Scala
apache-2.0
4,533
package org.scalajs.core.compiler.test import org.scalajs.core.compiler.test.util._ import org.junit.Test // scalastyle:off line.size.limit /** This tests the UndefinedParam tracker in the compiler backend. * * In order to properly implement removal of trailing default parameters, the * compiler backend may generate a UndefinedParam tree and catch it later. * However, some macros and compiler plugins may generate trees the backend * doesn't expect. As a result the backend used to generate invalid IR. * Instead, we now track these helper trees and emit a more helpful error * message if one of them sticks around. * * This test contains a macro that generates a tree we cannot handle and * verifies that the compiler bails out. */ class JSUndefinedParamTest extends DirectTest with TestHelpers { /* We need a macro in the test. Therefore, we add scala-reflect and the * compiler's output path itself to the classpath. */ override def classpath: List[String] = super.classpath ++ List(scalaReflectPath, testOutputPath) @Test def noDanglingUndefinedParam: Unit = { // Define macro that extracts method parameter. """ import language.experimental.macros /** Dummy object to get the right shadowing for cross compilation */ private object Compat210 { object blackbox { // scalastyle:ignore type Context = scala.reflect.macros.Context } } import Compat210._ object JSUndefinedParamTest { import scala.reflect.macros._ // shadows blackbox from above import blackbox.Context def extractArg(call: Any): Any = macro extractArg_impl def extractArg_impl(c: Context)(call: c.Expr[Any]): c.Expr[Any] = { import c.universe._ call.tree match { case Apply(fun, List(arg)) => c.Expr[Any](arg) case tree => c.abort(tree.pos, "Bad tree. Need function call with single argument.") } } } """.succeeds() // Use the macro to trigger UndefinedParam catcher. """ import scala.scalajs.js import scala.scalajs.js.annotation._ @js.native trait MyTrait extends js.Any { def foo(x: Int = js.native): Int = js.native } object A { val myTrait: MyTrait = ??? /* We assign the default parameter value for foo to b. * This should fail. */ val b = JSUndefinedParamTest.extractArg(myTrait.foo()) } """ hasErrors """ |newSource1.scala:10: error: Found a dangling UndefinedParam at Position(virtualfile:newSource1.scala,15,54). This is likely due to a bad interaction between a macro or a compiler plugin and the Scala.js compiler plugin. If you hit this, please let us know. | object A { | ^ """ } }
xuwei-k/scala-js
compiler/src/test/scala/org/scalajs/core/compiler/test/JSUndefinedParamTest.scala
Scala
bsd-3-clause
2,786
package controllers.auth import java.util.UUID import javax.inject.Inject import com.mohiva.play.silhouette.api._ import com.mohiva.play.silhouette.api.repositories.AuthInfoRepository import com.mohiva.play.silhouette.api.services.AvatarService import com.mohiva.play.silhouette.api.util.PasswordHasherRegistry import com.mohiva.play.silhouette.impl.providers._ import controllers.{ WebJarAssets, auth } import forms.auth.SignUpForm import models.User import models.services.{ AuthTokenService, UserService } import play.api.i18n.{ I18nSupport, Messages, MessagesApi } import play.api.libs.concurrent.Execution.Implicits._ import play.api.libs.mailer.{ Email, MailerClient } import play.api.mvc.{ Action, AnyContent, Controller } import utils.auth.DefaultEnv import scala.concurrent.Future /** * The `Sign Up` controller. * * @param messagesApi The Play messages API. * @param silhouette The Silhouette stack. * @param userService The user service implementation. * @param authInfoRepository The auth info repository implementation. * @param authTokenService The auth token service implementation. * @param avatarService The avatar service implementation. * @param passwordHasherRegistry The password hasher registry. * @param mailerClient The mailer client. * @param webJarAssets The webjar assets implementation. */ class SignUpController @Inject() ( val messagesApi: MessagesApi, silhouette: Silhouette[DefaultEnv], userService: UserService, authInfoRepository: AuthInfoRepository, authTokenService: AuthTokenService, avatarService: AvatarService, passwordHasherRegistry: PasswordHasherRegistry, mailerClient: MailerClient, implicit val webJarAssets: WebJarAssets ) extends Controller with I18nSupport { /** * Views the `Sign Up` page. * * @return The result to display. */ def view: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request => Future.successful(Ok(views.html.auth.signUp(SignUpForm.form))) } /** * Handles the submitted form. * * @return The result to display. */ def submit: Action[AnyContent] = silhouette.UnsecuredAction.async { implicit request => SignUpForm.form.bindFromRequest.fold( form => Future.successful(BadRequest(views.html.auth.signUp(form))), data => { val result = Redirect(auth.routes.SignUpController.view()).flashing("info" -> Messages("sign.up.email.sent", data.email)) val loginInfo = LoginInfo(CredentialsProvider.ID, data.email) userService.retrieve(loginInfo).flatMap { case Some(user) => val url = auth.routes.SignInController.view().absoluteURL() mailerClient.send(Email( subject = Messages("email.already.signed.up.subject"), from = Messages("email.from"), to = Seq(data.email), bodyText = Some(views.txt.emails.alreadySignedUp(user, url).body), bodyHtml = Some(views.html.emails.alreadySignedUp(user, url).body) )) Future.successful(result) case None => val authInfo = passwordHasherRegistry.current.hash(data.password) val user = User( userID = UUID.randomUUID(), loginInfo = loginInfo, firstName = Some(data.firstName), lastName = Some(data.lastName), fullName = Some(data.firstName + " " + data.lastName), email = Some(data.email), avatarURL = None, activated = false, // activated = true, role = None ) for { avatar <- avatarService.retrieveURL(data.email) user <- userService.save(user.copy(avatarURL = avatar)) authInfo <- authInfoRepository.add(loginInfo, authInfo) authToken <- authTokenService.create(user.userID) } yield { val url = auth.routes.ActivateAccountController.activate(authToken.id).absoluteURL() mailerClient.send(Email( subject = Messages("email.sign.up.subject"), from = Messages("email.from"), to = Seq(data.email), bodyText = Some(views.txt.emails.signUp(user, url).body), bodyHtml = Some(views.html.emails.signUp(user, url).body) )) silhouette.env.eventBus.publish(SignUpEvent(user, request)) result } } } ) } }
stanikol/walnuts
server/app/controllers/auth/SignUpController.scala
Scala
apache-2.0
4,586
package katas.scala.newton import org.junit.Test import org.scalatest.Matchers class Newton9 extends Matchers { @Test def `find square root of number`() { sqrt(1) should beTolerantEqualTo(1) sqrt(2) should beTolerantEqualTo(1.414) sqrt(3) should beTolerantEqualTo(1.732) sqrt(4) should beTolerantEqualTo(2) } private def sqrt(n: Double, r: Double = 1, tolerance: Double = 0.001): Double = { if ((r * r - n).abs < tolerance) r else { val improvedResult = r - ((r * r - n) / (2 * r)) sqrt(n, improvedResult, tolerance) } } }
dkandalov/katas
scala/src/katas/scala/newton/Newton9.scala
Scala
unlicense
550
/* * Copyright (c) 2011-2015 EPFL DATA Laboratory * Copyright (c) 2014-2015 The Squall Collaboration (see NOTICE) * * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 ch.epfl.data.squall.api.scala import ch.epfl.data.squall.api.scala.SquallType._ import ch.epfl.data.squall.api.scala.TPCHSchema._ import ch.epfl.data.squall.api.scala.operators.{ScalaAggregateOperator, ScalaFlatMapOperator, ScalaMapOperator} import ch.epfl.data.squall.api.scala.operators.predicates.ScalaPredicate import ch.epfl.data.squall.components.{Component, DataSourceComponent, EquiJoinComponent} import ch.epfl.data.squall.expressions.ColumnReference import ch.epfl.data.squall.operators.{Operator, SelectOperator} import ch.epfl.data.squall.predicates.{AndPredicate, ComparisonPredicate, Predicate, booleanPrimitive} import ch.epfl.data.squall.query_plans.QueryBuilder import ch.epfl.data.squall.types.IntegerType import ch.epfl.data.squall.utilities.SquallContext import org.apache.log4j.Logger import scala.collection.JavaConverters._ import scala.reflect.runtime.universe._ /** * @author mohamed */ object Stream { val LOG: Logger= Logger.getLogger(Stream.getClass()); case class Source[T: SquallType](name: String) extends Stream[T] case class FilteredStream[T: SquallType](Str: Stream[T], fn: T => Boolean) extends Stream[T] case class MappedStream[T: SquallType, U: SquallType](Str: Stream[T], fn: T => U) extends Stream[U] case class FlatMappedStream[T: SquallType, U: SquallType](Str: Stream[T], fn: T => Seq[U]) extends Stream[U] case class JoinedStream[T: SquallType, U: SquallType, V: SquallType, L: SquallType](Str1: Stream[T], Str2: Stream[U], ind1: T => L, ind2: U => L) extends JoinStream[V] { val tpT = implicitly[SquallType[T]] val tpU = implicitly[SquallType[U]] val tpL = implicitly[SquallType[L]] val tpV = implicitly[SquallType[V]] } case class SlideWindowJoinStream[T: SquallType](Str: JoinStream[T], rangeSize: Int) extends Stream[T] case class GroupedStream[T: SquallType, U: SquallType, N: Numeric](Str: Stream[T], agg: T => N, ind: T => U) extends TailStream[T, U, N] case class WindowStream[T: SquallType, U: SquallType, N: Numeric](Str: TailStream[T, U, N], rangeSize: Int, slideSize: Int) extends TailStream[T, U, N] //TODO change types to be generic class Stream[T: SquallType] extends Serializable { val squalType: SquallType[T] = implicitly[SquallType[T]] def filter(fn: T => Boolean): Stream[T] = FilteredStream(this, fn) def map[U: SquallType](fn: T => U): Stream[U] = MappedStream[T, U](this, fn) def flatMap[U: SquallType](fn: T => Seq[U]): Stream[U] = FlatMappedStream[T, U](this, fn) def join[U: SquallType, L: SquallType](other: Stream[U])(joinIndices1: T => L)(joinIndices2: U => L): JoinStream[Tuple2[T, U]] = JoinedStream[T, U, Tuple2[T, U], L](this, other, joinIndices1, joinIndices2) def groupByKey[N: Numeric, U: SquallType](agg: T => N, keyIndices: T => U): TailStream[T, U, N] = GroupedStream[T, U, N](this, agg, keyIndices) } class JoinStream[T: SquallType] extends Stream[T] { def onSlidingWindow(rangeSize: Int) = SlideWindowJoinStream[T](this, rangeSize) } class TailStream[T: SquallType, U: SquallType, N: Numeric] { //def slidingWindow(rangeSize:Int) = SlideWindowStream[T](rangeSize) def onWindow(rangeSize: Int, slideSize: Int) = WindowStream[T, U, N](this, rangeSize, slideSize) def onTumblingWindow(rangeSize: Int) = WindowStream[T, U, N](this, rangeSize, -1) def execute(context: SquallContext): QueryBuilder = { var metaData = List[Int](-1, -1) mainInterprete[T, U, N](this, metaData, context) } } // MetaData // 1: List of operators, // 2: Hash Indexes of R1 // 3: Hash Indexes of R2 // 4: Sliding Window value // TODO: why is metadata a tuple? private def interprete[T: SquallType](str: Stream[T], qb: QueryBuilder, metaData: Tuple4[List[Operator], List[Int], List[Int], Int], context: SquallContext): Component = str match { case Source(name) => { LOG.debug("Reached Source") var dataSourceComponent = context.createDataSource(name) qb.add(dataSourceComponent) val operatorList = metaData._1 if (operatorList != null) { operatorList.foreach { operator => LOG.debug(" adding operator: " + operator); dataSourceComponent = dataSourceComponent.add(operator) } } if (metaData._2 != null) dataSourceComponent = dataSourceComponent.setOutputPartKey(metaData._2: _*) else if (metaData._3 != null) dataSourceComponent = dataSourceComponent.setOutputPartKey(metaData._3: _*) dataSourceComponent } case FilteredStream(parent, fn) => { LOG.debug("Reached Filtered Stream") val filterPredicate = new ScalaPredicate(fn) val filterOperator = new SelectOperator(filterPredicate) interprete(parent, qb, Tuple4(filterOperator :: metaData._1, metaData._2, metaData._3, -1), context) } case MappedStream(parent, fn) => { LOG.debug("Reached Mapped Stream") val mapOp = new ScalaMapOperator(fn)(parent.squalType, str.squalType) interprete(parent, qb, Tuple4(mapOp :: metaData._1, metaData._2, metaData._3, -1), context)(parent.squalType) } case FlatMappedStream(parent, fn) => { LOG.debug("Reached FlatMapped Stream") val mapOp = new ScalaFlatMapOperator(fn)(parent.squalType, str.squalType) interprete(parent, qb, Tuple4(mapOp :: metaData._1, metaData._2, metaData._3, -1), context)(parent.squalType) } case j @ JoinedStream(parent1, parent2, ind1, ind2) => { LOG.debug("Reached Joined Stream") val typeT = j.tpT val typeU = j.tpU val typeL = j.tpL val typeV = j.tpV interpJoin(j, qb, metaData, context)(typeT, typeU, typeV, typeL) } case SlideWindowJoinStream(parent, rangeSize) => { interprete(parent, qb, Tuple4(metaData._1, metaData._2, metaData._3, rangeSize), context) } } def createPredicate(first: List[Int], second: List[Int]): Predicate = { //NumericConversion val keyType = new IntegerType(); val inter = first.zip(second).map(keyPairs => new ComparisonPredicate(ComparisonPredicate.EQUAL_OP, new ColumnReference(keyType, keyPairs._1), new ColumnReference(keyType, keyPairs._2))) val start: Predicate = new booleanPrimitive(true) inter.foldLeft(start)((pred1, pred2) => new AndPredicate(pred1, pred2)) } def interpJoin[T: SquallType, U: SquallType, V: SquallType, L: SquallType](j: JoinedStream[T, U, V, L], qb: QueryBuilder, metaData: Tuple4[List[Operator], List[Int], List[Int], Int], context: SquallContext): Component = { val typeT = j.tpT val typeU = j.tpU val typeL = j.tpL val typeV = j.tpV val lengthT = typeT.getLength() val lengthU = typeU.getLength() val lengthL = typeL.getLength() val indexArrayT = List.range(0, lengthT) val indexArrayU = List.range(0, lengthU) val indexArrayL = List.range(0, lengthL) val imageT = typeT.convertToIndexesOfTypeT(indexArrayT) val imageU = typeU.convertToIndexesOfTypeT(indexArrayU) val imageL = typeL.convertToIndexesOfTypeT(indexArrayL) val resT = j.ind1(imageT) val resU = j.ind2(imageU) val indicesL1 = typeL.convertIndexesOfTypeToListOfInt(resT) val indicesL2 = typeL.convertIndexesOfTypeToListOfInt(resU) val firstComponent = interprete(j.Str1, qb, Tuple4(List(), indicesL1, null, -1), context)(j.Str1.squalType) val secondComponent = interprete(j.Str2, qb, Tuple4(List(), null, indicesL2, -1), context)(j.Str2.squalType) var equijoinComponent = qb.createEquiJoin(firstComponent, secondComponent, false) equijoinComponent.setJoinPredicate(createPredicate(indicesL1, indicesL2)) val operatorList = metaData._1 if (operatorList != null) { operatorList.foreach { operator => equijoinComponent = equijoinComponent.add(operator) } } if (metaData._2 != null) equijoinComponent = equijoinComponent.setOutputPartKey(metaData._2: _*) else if (metaData._3 != null) equijoinComponent = equijoinComponent.setOutputPartKey(metaData._3: _*) equijoinComponent } private implicit def toIntegerList(lst: List[Int]) = seqAsJavaListConverter(lst.map(i => i: java.lang.Integer)).asJava private def mainInterprete[T: SquallType, U: SquallType, A: Numeric](str: TailStream[T, U, A], windowMetaData: List[Int], context: SquallContext): QueryBuilder = str match { case GroupedStream(parent, agg, ind) => { val st1 = implicitly[SquallType[T]] val st2 = implicitly[SquallType[U]] val length = st1.getLength() val indexArray = List.range(0, length) val image = st1.convertToIndexesOfTypeT(indexArray) val res = ind(image) val indices = st2.convertIndexesOfTypeToListOfInt(res) var aggOp = new ScalaAggregateOperator(agg, context.getConfiguration()).setGroupByColumns(toIntegerList(indices)) //.SetWindowSemantics(10) if (windowMetaData.get(0) > 0 && windowMetaData.get(1) <= 0) aggOp.SetWindowSemantics(windowMetaData.get(0)) else if (windowMetaData.get(1) > 0 && windowMetaData.get(0) > windowMetaData.get(1)) aggOp.SetWindowSemantics(windowMetaData.get(0), windowMetaData.get(1)) val _queryBuilder = new QueryBuilder(); interprete(parent, _queryBuilder, Tuple4(List(aggOp), null, null, -1), context) _queryBuilder } case WindowStream(parent, rangeSize, slideSize) => { //only the last one is effective if ((windowMetaData.get(0) < 0 && windowMetaData.get(1) < 0)) { mainInterprete(parent, List(rangeSize, slideSize), context) } else mainInterprete(parent, windowMetaData, context) } } def main(args: Array[String]) { /* val x=Source[Int]("hello").filter{ x:Int => true }.map[(Int,Int)]{ y:Int => Tuple2(2*y,3*y) }; val y = Source[Int]("hello").filter{ x:Int => true }.map[Int]{ y:Int => 2*y }; val z = x.join[Int,(Int,Int)](y, List(2),List(2)).reduceByKey(x => 3*x._2, List(1,2)) val conf= new java.util.HashMap[String,String]() interp(z,conf) */ } }
epfldata/squall
squall-functional/src/main/scala/ch/epfl/data/squall/api/scala/Stream.scala
Scala
apache-2.0
10,678
/******************************************************************************* Copyright (c) 2013-2014, S-Core, KAIST. All rights reserved. Use is subject to license terms. This distribution may include materials developed by third parties. ******************************************************************************/ package kr.ac.kaist.jsaf.analysis.typing.models.Tizen import kr.ac.kaist.jsaf.analysis.typing.AddressManager._ import kr.ac.kaist.jsaf.analysis.cfg.{CFG, CFGExpr, InternalError} import kr.ac.kaist.jsaf.analysis.typing.domain.{BoolFalse => F, BoolTrue => T, _} import kr.ac.kaist.jsaf.analysis.typing.models._ import kr.ac.kaist.jsaf.analysis.typing._ import kr.ac.kaist.jsaf.analysis.typing.domain.Heap import kr.ac.kaist.jsaf.analysis.typing.domain.Context object TIZENnetworkbearerselection extends Tizen { private val name = "networkbearerselection" /* predefined locations */ val loc_obj = TIZENtizen.loc_networkbearerselection val loc_proto = newSystemRecentLoc(name + "Proto") override def getInitList(): List[(Loc, List[(String, AbsProperty)])] = List( (loc_obj, prop_obj), (loc_proto, prop_proto) ) /* constructor or object*/ private val prop_obj: List[(String, AbsProperty)] = List( ("@class", AbsConstValue(PropValue(AbsString.alpha("Object")))), ("@proto", AbsConstValue(PropValue(ObjectValue(Value(loc_proto), F, F, F)))), ("@extensible", AbsConstValue(PropValue(T))) ) /* prototype */ private val prop_proto: List[(String, AbsProperty)] = List( ("@class", AbsConstValue(PropValue(AbsString.alpha("CallbackObject")))), ("@proto", AbsConstValue(PropValue(ObjectValue(Value(ObjProtoLoc), F, F, F)))), ("@extensible", AbsConstValue(PropValue(T))), ("requestRouteToHost", AbsBuiltinFunc("tizen.networkbearerselection.requestRouteToHost", 4)), ("releaseRouteToHost", AbsBuiltinFunc("tizen.networkbearerselection.releaseRouteToHost", 4)) ) override def getSemanticMap(): Map[String, SemanticFun] = { Map( ("tizen.networkbearerselection.requestRouteToHost" -> ( (sem: Semantics, h: Heap, ctx: Context, he: Heap, ctxe: Context, cp: ControlPoint, cfg: CFG, fun: String, args: CFGExpr) => { val lset_env = h(SinglePureLocalLoc)("@env")._2._2 val set_addr = lset_env.foldLeft[Set[Address]](Set())((a, l) => a + locToAddr(l)) if (set_addr.size > 1) throw new InternalError("API heap allocation: Size of env address is " + set_addr.size) val addr_env = (cp._1._1, set_addr.head) val addr1 = cfg.getAPIAddress(addr_env, 0) val l_r1 = addrToLoc(addr1, Recent) val (h_1, ctx_1) = Helper.Oldify(h, ctx, addr1) val v_1 = getArgValue(h_1, ctx_1, args, "0") val v_2 = getArgValue(h_1, ctx_1, args, "1") val v_3 = getArgValue(h_1, ctx_1, args, "2") val n_arglen = Operator.ToUInt32(getArgValue(h_1, ctx_1, args, "length")) val es_1 = if (v_1._1._5 </ StrTop) Set[WebAPIException](TypeMismatchError) else TizenHelper.TizenExceptionBot val es_2 = if (v_2._1._5 </ StrTop) Set[WebAPIException](TypeMismatchError) else TizenHelper.TizenExceptionBot val (h_2, es_3) = v_3._2.foldLeft((h_1, TizenHelper.TizenExceptionBot))((_he, l) => { val v1 = Helper.Proto(_he._1, l, AbsString.alpha("onsuccess")) val v2 = Helper.Proto(_he._1, l, AbsString.alpha("ondisconnected")) val es1 = if (v1._2.exists((l) => Helper.IsCallable(_he._1, l) <= F)) Set[WebAPIException](TypeMismatchError) else TizenHelper.TizenExceptionBot val es2 = if (v2._2.exists((l) => Helper.IsCallable(_he._1, l) <= F)) Set[WebAPIException](TypeMismatchError) else TizenHelper.TizenExceptionBot val h_2 = TizenHelper.addCallbackHandler(h_1, AbsString.alpha("NetworkSuccessCB.onsuccess"), Value(v1._2), Value(UndefTop)) val h_3 = TizenHelper.addCallbackHandler(h_2, AbsString.alpha("NetworkSuccessCB.ondisconnected"), Value(v2._2), Value(UndefTop)) (h_3, _he._2 ++ es1 ++ es2) }) val (h_3, es_4) = AbsNumber.getUIntSingle(n_arglen) match { case Some(n) if n == 3 => (h_2, TizenHelper.TizenExceptionBot) case Some(n) if n>= 4 => val v_4 = getArgValue(h_2, ctx_1, args, "3") val es_4 = if (v_4._2.exists((l) => Helper.IsCallable(h_2, l) <= F)) Set[WebAPIException](TypeMismatchError) else TizenHelper.TizenExceptionBot val o_arr1 = Helper.NewArrayObject(AbsNumber.alpha(1)). update("0", PropValue(ObjectValue(Value(LocSet(TIZENtizen.loc_unknownerr)), T, T, T))) val h_3 = h_2.update(l_r1, o_arr1) val h_4 = TizenHelper.addCallbackHandler(h_3, AbsString.alpha("errorCB"), Value(v_4._2), Value(l_r1)) (h_4, es_4) case _ => (HeapBot, TizenHelper.TizenExceptionBot) } val est = Set[WebAPIException](NotSupportedError, SecurityError, UnknownError) val (h_e, ctx_e) = TizenHelper.TizenRaiseException(h, ctx, es_1 ++ es_2 ++ es_3 ++ es_4 ++ est) ((h_3, ctx_1), (he + h_e, ctxe + ctx_e)) } )), ("tizen.networkbearerselection.releaseRouteToHost" -> ( (sem: Semantics, h: Heap, ctx: Context, he: Heap, ctxe: Context, cp: ControlPoint, cfg: CFG, fun: String, args: CFGExpr) => { val lset_env = h(SinglePureLocalLoc)("@env")._2._2 val set_addr = lset_env.foldLeft[Set[Address]](Set())((a, l) => a + locToAddr(l)) if (set_addr.size > 1) throw new InternalError("API heap allocation: Size of env address is " + set_addr.size) val addr_env = (cp._1._1, set_addr.head) val addr1 = cfg.getAPIAddress(addr_env, 0) val l_r1 = addrToLoc(addr1, Recent) val (h_1, ctx_1) = Helper.Oldify(h, ctx, addr1) val v_1 = getArgValue(h_1, ctx_1, args, "0") val v_2 = getArgValue(h_1, ctx_1, args, "1") val v_3 = getArgValue(h_1, ctx_1, args, "2") val n_arglen = Operator.ToUInt32(getArgValue(h_1, ctx_1, args, "length")) val es_1 = if (v_1._1._5 </ StrTop) Set[WebAPIException](TypeMismatchError) else TizenHelper.TizenExceptionBot val es_2 = if (v_2._1._5 </ StrTop) Set[WebAPIException](TypeMismatchError) else TizenHelper.TizenExceptionBot val es_3 = if (v_3._2.exists((l) => Helper.IsCallable(h_1, l) <= F)) Set[WebAPIException](TypeMismatchError) else TizenHelper.TizenExceptionBot val h_2 = TizenHelper.addCallbackHandler(h_1, AbsString.alpha("successCB"), Value(v_3._2), Value(UndefTop)) val (h_3, es_4) = AbsNumber.getUIntSingle(n_arglen) match { case Some(n) if n == 3 => (h_2, TizenHelper.TizenExceptionBot) case Some(n) if n>= 4 => val v_4 = getArgValue(h_2, ctx_1, args, "3") val es_4 = if (v_4._2.exists((l) => Helper.IsCallable(h_2, l) <= F)) Set[WebAPIException](TypeMismatchError) else TizenHelper.TizenExceptionBot val o_arr1 = Helper.NewArrayObject(AbsNumber.alpha(1)). update("0", PropValue(ObjectValue(Value(LocSet(TIZENtizen.loc_unknownerr)), T, T, T))) val h_3 = h_2.update(l_r1, o_arr1) val h_4 = TizenHelper.addCallbackHandler(h_3, AbsString.alpha("errorCB"), Value(v_4._2), Value(l_r1)) (h_4, es_4) case _ => (HeapBot, TizenHelper.TizenExceptionBot) } val est = Set[WebAPIException](NotSupportedError, SecurityError, UnknownError) val (h_e, ctx_e) = TizenHelper.TizenRaiseException(h, ctx, es_1 ++ es_2 ++ es_3 ++ es_4 ++ est) ((h_3, ctx_1), (he + h_e, ctxe + ctx_e)) } )) ) } override def getPreSemanticMap(): Map[String, SemanticFun] = {Map()} override def getDefMap(): Map[String, AccessFun] = {Map()} override def getUseMap(): Map[String, AccessFun] = {Map()} }
darkrsw/safe
src/main/scala/kr/ac/kaist/jsaf/analysis/typing/models/Tizen/TIZENnetworkbearerselection.scala
Scala
bsd-3-clause
8,404
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sparklinedata.druid.client import org.json4s.CustomSerializer import org.json4s.JsonAST._ case class ColumnDetails(typ : String, size : Long, cardinality : Option[Long], errorMessage : Option[String]) case class MetadataResponse(id : String, intervals : List[String], columns : Map[String, ColumnDetails], size : Long) case class QueryResultRow(version : Option[String], timestamp : String, event : Map[String, Any]) class QueryResultRowSerializer extends CustomSerializer[QueryResultRow](format => ( { case JObject( JField("version", JString(v)) :: JField("timestamp", JString(t)) :: JField("event", JObject(obj)) :: Nil ) => val m : Map[String, Any] = obj.map(t => (t._1, t._2.values)).toMap QueryResultRow(Some(v), t, m) case JObject( JField("timestamp", JString(t)) :: JField("result", JObject(obj)) :: Nil ) => val m : Map[String, Any] = obj.map(t => (t._1, t._2.values)).toMap QueryResultRow(None, t, m) }, { case x: QueryResultRow => throw new RuntimeException("QueryRow serialization not supported.") } ) )
benschaff/spark-druid-olap
src/main/scala/org/sparklinedata/druid/client/DruidMessages.scala
Scala
apache-2.0
2,085
package Scalisp import org.scalatest.FlatSpec import org.scalatest.matchers.ShouldMatchers class LambdaSpec extends FlatSpec with ShouldMatchers { val repl = new REPL() "Lambdas" should "be allowed" in { repl.executeLine("(define test (lambda (r) (* 3.141592653 (* r r))))") } it should "execute correctly" in { repl.executeLine("(define square (lambda (x) (* x x)))") repl.executeLine("(square 4)") should equal (16) } }
quantintel/Scalisp
src/test/scala/Lambda.scala
Scala
mit
439
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.mapred import java.io.IOException import org.apache.hadoop.mapreduce.{TaskAttemptContext => MapReduceTaskAttemptContext} import org.apache.hadoop.mapreduce.{OutputCommitter => MapReduceOutputCommitter} import org.apache.spark.{SparkEnv, TaskContext} import org.apache.spark.executor.CommitDeniedException import org.apache.spark.internal.Logging import org.apache.spark.util.Utils object SparkHadoopMapRedUtil extends Logging { /** * Commits a task output. Before committing the task output, we need to know whether some other * task attempt might be racing to commit the same output partition. Therefore, coordinate with * the driver in order to determine whether this attempt can commit (please see SPARK-4879 for * details). * * Output commit coordinator is only used when `spark.hadoop.outputCommitCoordination.enabled` * is set to true (which is the default). */ def commitTask( committer: MapReduceOutputCommitter, mrTaskContext: MapReduceTaskAttemptContext, jobId: Int, splitId: Int): Unit = { val mrTaskAttemptID = mrTaskContext.getTaskAttemptID // Called after we have decided to commit def performCommit(): Unit = { try { val (_, timeCost) = Utils.timeTakenMs(committer.commitTask(mrTaskContext)) logInfo(s"$mrTaskAttemptID: Committed. Elapsed time: $timeCost ms.") } catch { case cause: IOException => logError(s"Error committing the output of task: $mrTaskAttemptID", cause) committer.abortTask(mrTaskContext) throw cause } } // First, check whether the task's output has already been committed by some other attempt if (committer.needsTaskCommit(mrTaskContext)) { val shouldCoordinateWithDriver: Boolean = { val sparkConf = SparkEnv.get.conf // We only need to coordinate with the driver if there are concurrent task attempts. // Note that this could happen even when speculation is not enabled (e.g. see SPARK-8029). // This (undocumented) setting is an escape-hatch in case the commit code introduces bugs. sparkConf.getBoolean("spark.hadoop.outputCommitCoordination.enabled", defaultValue = true) } if (shouldCoordinateWithDriver) { val outputCommitCoordinator = SparkEnv.get.outputCommitCoordinator val ctx = TaskContext.get() val canCommit = outputCommitCoordinator.canCommit(ctx.stageId(), ctx.stageAttemptNumber(), splitId, ctx.attemptNumber()) if (canCommit) { performCommit() } else { val message = s"$mrTaskAttemptID: Not committed because the driver did not authorize commit" logInfo(message) // We need to abort the task so that the driver can reschedule new attempts, if necessary committer.abortTask(mrTaskContext) throw new CommitDeniedException(message, ctx.stageId(), splitId, ctx.attemptNumber()) } } else { // Speculation is disabled or a user has chosen to manually bypass the commit coordination performCommit() } } else { // Some other attempt committed the output, so we do nothing and signal success logInfo(s"No need to commit output of task because needsTaskCommit=false: $mrTaskAttemptID") } } }
ueshin/apache-spark
core/src/main/scala/org/apache/spark/mapred/SparkHadoopMapRedUtil.scala
Scala
apache-2.0
4,159
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.spark.executor import java.io.{BufferedInputStream, FileInputStream} import java.net.URL import java.nio.ByteBuffer import java.util.Locale import java.util.concurrent.atomic.AtomicBoolean import scala.collection.mutable import scala.util.{Failure, Success} import scala.util.control.NonFatal import com.fasterxml.jackson.databind.exc.MismatchedInputException import org.json4s.DefaultFormats import org.json4s.JsonAST.JArray import org.json4s.MappingException import org.json4s.jackson.JsonMethods._ import org.apache.spark._ import org.apache.spark.TaskState.TaskState import org.apache.spark.deploy.SparkHadoopUtil import org.apache.spark.deploy.worker.WorkerWatcher import org.apache.spark.internal.Logging import org.apache.spark.internal.config._ import org.apache.spark.rpc._ import org.apache.spark.scheduler.{ExecutorLossReason, TaskDescription} import org.apache.spark.scheduler.cluster.CoarseGrainedClusterMessages._ import org.apache.spark.serializer.SerializerInstance import org.apache.spark.util.{ThreadUtils, Utils} private[spark] class CoarseGrainedExecutorBackend( override val rpcEnv: RpcEnv, driverUrl: String, executorId: String, hostname: String, cores: Int, userClassPath: Seq[URL], env: SparkEnv, resourcesFile: Option[String]) extends ThreadSafeRpcEndpoint with ExecutorBackend with Logging { private implicit val formats = DefaultFormats private[this] val stopping = new AtomicBoolean(false) var executor: Executor = null @volatile var driver: Option[RpcEndpointRef] = None // If this CoarseGrainedExecutorBackend is changed to support multiple threads, then this may need // to be changed so that we don't share the serializer instance across threads private[this] val ser: SerializerInstance = env.closureSerializer.newInstance() /** * Map each taskId to the information about the resource allocated to it, Please refer to * [[ResourceInformation]] for specifics. * Exposed for testing only. */ private[executor] val taskResources = new mutable.HashMap[Long, Map[String, ResourceInformation]] override def onStart() { logInfo("Connecting to driver: " + driverUrl) val resources = parseOrFindResources(resourcesFile) rpcEnv.asyncSetupEndpointRefByURI(driverUrl).flatMap { ref => // This is a very fast action so we can use "ThreadUtils.sameThread" driver = Some(ref) ref.ask[Boolean](RegisterExecutor(executorId, self, hostname, cores, extractLogUrls, extractAttributes, resources)) }(ThreadUtils.sameThread).onComplete { // This is a very fast action so we can use "ThreadUtils.sameThread" case Success(msg) => // Always receive `true`. Just ignore it case Failure(e) => exitExecutor(1, s"Cannot register with driver: $driverUrl", e, notifyDriver = false) }(ThreadUtils.sameThread) } // visible for testing def parseOrFindResources(resourcesFile: Option[String]): Map[String, ResourceInformation] = { // only parse the resources if a task requires them val resourceInfo = if (env.conf.getAllWithPrefix(SPARK_TASK_RESOURCE_PREFIX).nonEmpty) { val actualExecResources = resourcesFile.map { rFile => { ResourceDiscoverer.parseAllocatedFromJsonFile(rFile) }}.getOrElse { ResourceDiscoverer.discoverResourcesInformation(env.conf, SPARK_EXECUTOR_RESOURCE_PREFIX) } if (actualExecResources.isEmpty) { throw new SparkException("User specified resources per task via: " + s"$SPARK_TASK_RESOURCE_PREFIX, but can't find any resources available on the executor.") } val execReqResourcesAndCounts = env.conf.getAllWithPrefixAndSuffix(SPARK_EXECUTOR_RESOURCE_PREFIX, SPARK_RESOURCE_AMOUNT_SUFFIX).toMap ResourceDiscoverer.checkActualResourcesMeetRequirements(execReqResourcesAndCounts, actualExecResources) logInfo("===============================================================================") logInfo(s"Executor $executorId Resources:") actualExecResources.foreach { case (k, v) => logInfo(s"$k -> $v") } logInfo("===============================================================================") actualExecResources } else { if (resourcesFile.nonEmpty) { logWarning(s"A resources file was specified but the application is not configured " + s"to use any resources, see the configs with prefix: ${SPARK_TASK_RESOURCE_PREFIX}") } Map.empty[String, ResourceInformation] } resourceInfo } def extractLogUrls: Map[String, String] = { val prefix = "SPARK_LOG_URL_" sys.env.filterKeys(_.startsWith(prefix)) .map(e => (e._1.substring(prefix.length).toLowerCase(Locale.ROOT), e._2)) } def extractAttributes: Map[String, String] = { val prefix = "SPARK_EXECUTOR_ATTRIBUTE_" sys.env.filterKeys(_.startsWith(prefix)) .map(e => (e._1.substring(prefix.length).toUpperCase(Locale.ROOT), e._2)) } override def receive: PartialFunction[Any, Unit] = { case RegisteredExecutor => logInfo("Successfully registered with driver") try { executor = new Executor(executorId, hostname, env, userClassPath, isLocal = false) } catch { case NonFatal(e) => exitExecutor(1, "Unable to create executor due to " + e.getMessage, e) } case RegisterExecutorFailed(message) => exitExecutor(1, "Slave registration failed: " + message) case LaunchTask(data) => if (executor == null) { exitExecutor(1, "Received LaunchTask command but executor was null") } else { val taskDesc = TaskDescription.decode(data.value) logInfo("Got assigned task " + taskDesc.taskId) taskResources(taskDesc.taskId) = taskDesc.resources executor.launchTask(this, taskDesc) } case KillTask(taskId, _, interruptThread, reason) => if (executor == null) { exitExecutor(1, "Received KillTask command but executor was null") } else { executor.killTask(taskId, interruptThread, reason) } case StopExecutor => stopping.set(true) logInfo("Driver commanded a shutdown") // Cannot shutdown here because an ack may need to be sent back to the caller. So send // a message to self to actually do the shutdown. self.send(Shutdown) case Shutdown => stopping.set(true) new Thread("CoarseGrainedExecutorBackend-stop-executor") { override def run(): Unit = { // executor.stop() will call `SparkEnv.stop()` which waits until RpcEnv stops totally. // However, if `executor.stop()` runs in some thread of RpcEnv, RpcEnv won't be able to // stop until `executor.stop()` returns, which becomes a dead-lock (See SPARK-14180). // Therefore, we put this line in a new thread. executor.stop() } }.start() case UpdateDelegationTokens(tokenBytes) => logInfo(s"Received tokens of ${tokenBytes.length} bytes") SparkHadoopUtil.get.addDelegationTokens(tokenBytes, env.conf) } override def onDisconnected(remoteAddress: RpcAddress): Unit = { if (stopping.get()) { logInfo(s"Driver from $remoteAddress disconnected during shutdown") } else if (driver.exists(_.address == remoteAddress)) { exitExecutor(1, s"Driver $remoteAddress disassociated! Shutting down.", null, notifyDriver = false) } else { logWarning(s"An unknown ($remoteAddress) driver disconnected.") } } override def statusUpdate(taskId: Long, state: TaskState, data: ByteBuffer) { val resources = taskResources.getOrElse(taskId, Map.empty[String, ResourceInformation]) val msg = StatusUpdate(executorId, taskId, state, data, resources) if (TaskState.isFinished(state)) { taskResources.remove(taskId) } driver match { case Some(driverRef) => driverRef.send(msg) case None => logWarning(s"Drop $msg because has not yet connected to driver") } } /** * This function can be overloaded by other child classes to handle * executor exits differently. For e.g. when an executor goes down, * back-end may not want to take the parent process down. */ protected def exitExecutor(code: Int, reason: String, throwable: Throwable = null, notifyDriver: Boolean = true) = { val message = "Executor self-exiting due to : " + reason if (throwable != null) { logError(message, throwable) } else { logError(message) } if (notifyDriver && driver.nonEmpty) { driver.get.send(RemoveExecutor(executorId, new ExecutorLossReason(reason))) } System.exit(code) } } private[spark] object CoarseGrainedExecutorBackend extends Logging { case class Arguments( driverUrl: String, executorId: String, hostname: String, cores: Int, appId: String, workerUrl: Option[String], userClassPath: mutable.ListBuffer[URL], resourcesFile: Option[String]) def main(args: Array[String]): Unit = { val createFn: (RpcEnv, Arguments, SparkEnv) => CoarseGrainedExecutorBackend = { case (rpcEnv, arguments, env) => new CoarseGrainedExecutorBackend(rpcEnv, arguments.driverUrl, arguments.executorId, arguments.hostname, arguments.cores, arguments.userClassPath, env, arguments.resourcesFile) } run(parseArguments(args, this.getClass.getCanonicalName.stripSuffix("$")), createFn) System.exit(0) } def run( arguments: Arguments, backendCreateFn: (RpcEnv, Arguments, SparkEnv) => CoarseGrainedExecutorBackend): Unit = { Utils.initDaemon(log) SparkHadoopUtil.get.runAsSparkUser { () => // Debug code Utils.checkHost(arguments.hostname) // Bootstrap to fetch the driver's Spark properties. val executorConf = new SparkConf val fetcher = RpcEnv.create( "driverPropsFetcher", arguments.hostname, -1, executorConf, new SecurityManager(executorConf), clientMode = true) val driver = fetcher.setupEndpointRefByURI(arguments.driverUrl) val cfg = driver.askSync[SparkAppConfig](RetrieveSparkAppConfig) val props = cfg.sparkProperties ++ Seq[(String, String)](("spark.app.id", arguments.appId)) fetcher.shutdown() // Create SparkEnv using properties we fetched from the driver. val driverConf = new SparkConf() for ((key, value) <- props) { // this is required for SSL in standalone mode if (SparkConf.isExecutorStartupConf(key)) { driverConf.setIfMissing(key, value) } else { driverConf.set(key, value) } } cfg.hadoopDelegationCreds.foreach { tokens => SparkHadoopUtil.get.addDelegationTokens(tokens, driverConf) } driverConf.set(EXECUTOR_ID, arguments.executorId) val env = SparkEnv.createExecutorEnv(driverConf, arguments.executorId, arguments.hostname, arguments.cores, cfg.ioEncryptionKey, isLocal = false) env.rpcEnv.setupEndpoint("Executor", backendCreateFn(env.rpcEnv, arguments, env)) arguments.workerUrl.foreach { url => env.rpcEnv.setupEndpoint("WorkerWatcher", new WorkerWatcher(env.rpcEnv, url)) } env.rpcEnv.awaitTermination() } } def parseArguments(args: Array[String], classNameForEntry: String): Arguments = { var driverUrl: String = null var executorId: String = null var hostname: String = null var cores: Int = 0 var resourcesFile: Option[String] = None var appId: String = null var workerUrl: Option[String] = None val userClassPath = new mutable.ListBuffer[URL]() var argv = args.toList while (!argv.isEmpty) { argv match { case ("--driver-url") :: value :: tail => driverUrl = value argv = tail case ("--executor-id") :: value :: tail => executorId = value argv = tail case ("--hostname") :: value :: tail => hostname = value argv = tail case ("--cores") :: value :: tail => cores = value.toInt argv = tail case ("--resourcesFile") :: value :: tail => resourcesFile = Some(value) argv = tail case ("--app-id") :: value :: tail => appId = value argv = tail case ("--worker-url") :: value :: tail => // Worker url is used in spark standalone mode to enforce fate-sharing with worker workerUrl = Some(value) argv = tail case ("--user-class-path") :: value :: tail => userClassPath += new URL(value) argv = tail case Nil => case tail => // scalastyle:off println System.err.println(s"Unrecognized options: ${tail.mkString(" ")}") // scalastyle:on println printUsageAndExit(classNameForEntry) } } if (driverUrl == null || executorId == null || hostname == null || cores <= 0 || appId == null) { printUsageAndExit(classNameForEntry) } Arguments(driverUrl, executorId, hostname, cores, appId, workerUrl, userClassPath, resourcesFile) } private def printUsageAndExit(classNameForEntry: String): Unit = { // scalastyle:off println System.err.println( s""" |Usage: $classNameForEntry [options] | | Options are: | --driver-url <driverUrl> | --executor-id <executorId> | --hostname <hostname> | --cores <cores> | --resourcesFile <fileWithJSONResourceInformation> | --app-id <appid> | --worker-url <workerUrl> | --user-class-path <url> |""".stripMargin) // scalastyle:on println System.exit(1) } }
icexelloss/spark
core/src/main/scala/org/apache/spark/executor/CoarseGrainedExecutorBackend.scala
Scala
apache-2.0
14,680
package edu.gemini.spModel.inst import edu.gemini.pot.ModelConverters._ import edu.gemini.spModel.core._ import edu.gemini.spModel.gemini.gmos._ import edu.gemini.spModel.guide.VignettingCalculator import edu.gemini.spModel.inst.FeatureGeometry._ import edu.gemini.spModel.obs.context.ObsContext import org.scalacheck._ import org.scalacheck.Arbitrary._ import org.scalacheck.Prop.forAll import org.specs2.ScalaCheck import org.specs2.mutable.Specification import scala.collection.JavaConverters._ import scalaz._ import Scalaz._ import edu.gemini.shared.util.immutable.ScalaConverters._ object VignettingCalcSpec extends Specification with ScalaCheck with VignettingArbitraries with Helpers { case class TestEnv(ctx: ObsContext, candidates: List[Coordinates]) { val vc = VignettingCalculator(ctx, GmosOiwfsProbeArm, GmosScienceAreaGeometry) override def toString: String = { val gmosN = ctx.getInstrument.asInstanceOf[InstGmosNorth] s"""---- Test Env ---- | Base = ${ctx.getBaseCoordinates.asScalaOpt.map(_.toNewModel.shows)} | Instrument: | Pos Angle = ${ctx.getPositionAngle} | ISS Port = ${ctx.getIssPort} | Mode = ${gmosN.getFPUnitMode} | IFU = ${gmosN.getFPUnit} | Offsets = ${ctx.getSciencePositions.asScala.map(_.toNewModel.shows).mkString(",")} | Candidates: | ${candidates.map(_.shows).mkString("\\n ")} """.stripMargin } } implicit val arbTest: Arbitrary[TestEnv] = Arbitrary { for { ctx <- arbitrary[ObsContext] can <- genCandidates(ctx) } yield TestEnv(ctx, can) } "VignettingCalculator" should { "generate vignetting ratios" ! forAll { (env: TestEnv) => // maximum vignetting is 1.0 but since the GMOS probe arm is much // smaller than the gmos science area for imaging, we can reduce it // even further sometimes. For spectroscopy, the slit is small // so we stick with 1.0 in those cases val gmosArea = GmosScienceAreaGeometry.unadjustedGeometry(env.ctx).map(approximateArea) val maxProbeArea = GmosOiwfsProbeArm.unadjustedGeometry(env.ctx).map(approximateArea) val maxVig = 1.0 min (maxProbeArea.get / gmosArea.get) env.candidates.forall { gs => val vig = env.vc.calc(gs) (0 <= vig) && (vig <= maxVig) } } "only generate 0 vignetting if the guide star does not fall on the science area at any offset" ! forAll { (env: TestEnv) => // Figure out the offset from the base of each candidate that does not // vignette the science area. val zeroVigCandidates = env.candidates.filter(env.vc.calc(_) == 0) val base = env.ctx.getBaseCoordinates.getValue.toNewModel val candidateOffsets = zeroVigCandidates.map(Coordinates.difference(base, _).offset) // Check that at each offset, the candidate isn't on the science area. env.ctx.getSciencePositions.asScala.map(_.toNewModel).forall { off => val geo = GmosScienceAreaGeometry.geometry(env.ctx, off).get candidateOffsets.forall { candidate => !geo.contains(candidate.toPoint) } } // Note it can be the case that the guide star causes vignetting w/o // falling on the science area, particularly for spectroscopy or when // using the IFU. } /* Struggling to figure out a property that applies in all cases. "(for GMOS) calculate higher vignetting for candidates that fall in the half of the usable area closest to the base position + offset" ! forAll { (env: TestEnv) => val base = env.ctx.getBaseCoordinates.toNewModel val pf = GmosOiwfsGuideProbe.instance.getPatrolField val usable = pf.usableArea(env.ctx) val unRot = AffineTransform.getRotateInstance(env.ctx.getPositionAngle.toRadians.getMagnitude) val usable0 = unRot.createTransformedShape(usable) val bounds = usable0 .getBounds2D val close0 = new Rectangle2D.Double(bounds.getX, bounds.getY, bounds.getWidth/2, bounds.getHeight) val far0 = new Area(usable0 ) <| (_.subtract(new Area(close0))) val rot = AffineTransform.getRotateInstance(-env.ctx.getPositionAngle.toRadians.getMagnitude) val close = rot.createTransformedShape(close0) val far = rot.createTransformedShape(far0) env.ctx.getSciencePositions.asScala.map(_.toNewModel).forall { off => // Separate the candidates into those that fall in the closest // quadrant vs. the rest. val points = env.candidates.map { coords => val candidateOffset = Coordinates.difference(base, coords).offset val candidatePoint = candidateOffset.toPoint (coords, candidatePoint) } val containedPoints = points.filter { case (_,p) => usable.contains(p) } val (closePoints, farPoints) = containedPoints.partition { case (_,p) => close.contains(p) } val cTups = closePoints.map { case (c,_) => (c, env.vc.calc(c)) } val fTups = farPoints.map { case (f,_) => (f, env.vc.calc(f)) } cTups.forall { case (cCoords, cVig) => fTups.forall { case (fCoords, fVig) => val res = cVig >= fVig if (!res) { Console.err.println("FAILS: " + formatCoordinates(cCoords) + " \\t" + formatCoordinates(fCoords) + " \\t" + cVig + " < " + fVig) } res } } } } */ } }
arturog8m/ocs
bundle/edu.gemini.pot/src/test/scala/edu/gemini/spModel/inst/VignettingCalcSpec.scala
Scala
bsd-3-clause
5,684
/** * Copyright (C) 2013 Orbeon, Inc. * * This program is free software; you can redistribute it and/or modify it under the terms of the * GNU Lesser General Public License as published by the Free Software Foundation; either version * 2.1 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 Lesser General Public License for more details. * * The full text of the license is available at http://www.gnu.org/copyleft/lesser.html */ package org.orbeon.oxf.resources.handler import org.apache.commons.codec.binary.Base64 import org.apache.commons.codec.net.URLCodec import org.orbeon.oxf.util.NetUtils // Decode as per https://tools.ietf.org/html/rfc2397 object DataURLDecoder { private val DefaultMediatype = "text/plain" private val DefaultCharset = "US-ASCII" def decode(url: String) = { require(url.startsWith("data")) val comma = url.indexOf(',') val beforeData = url.substring("data:".length, comma) val data = url.substring(comma + 1).getBytes(DefaultCharset) val mediatype = Option(NetUtils.getContentTypeMediaType(beforeData)) getOrElse DefaultMediatype val params = parseContentTypeParameters(beforeData) val isBase64 = params.contains("base64") val charset = if (mediatype.startsWith("text/")) params.get("charset").flatten.orElse(Some(DefaultCharset)) else None // See: https://github.com/orbeon/orbeon-forms/issues/1065 val decodedData = if (isBase64) Base64.decodeBase64(data) else URLCodec.decodeUrl(data) new DecodedDataURL(decodedData, mediatype, charset) } // Support missing attribute values so we can collect ";base64" as well private def parseContentTypeParameters(s: String) = { def parseParameter(p: String) = { val parts = p.split('=') (parts(0), parts.lift(1)) } s.split(';') drop 1 map parseParameter toMap } } class DecodedDataURL(val bytes: Array[Byte], val mediatype: String, val charset: Option[String]) { def contentType = mediatype + (charset map (";" + _) getOrElse "") def asString = charset map (new String(bytes, _)) }
martinluther/orbeon-forms
src/main/scala/org/orbeon/oxf/resources/handler/DataURLDecoder.scala
Scala
lgpl-2.1
2,483
/** * (c) Copyright 2013 WibiData, Inc. * * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kiji.schema.shell.ddl import scala.collection.JavaConversions._ import org.kiji.annotations.ApiAudience import org.kiji.schema.avro.TableLayoutDesc import org.kiji.schema.layout.KijiTableLayout import org.kiji.schema.shell.AddToAllSchemaUsageFlags import org.kiji.schema.shell.DDLException import org.kiji.schema.shell.Environment @ApiAudience.Private final class AlterTableSetFamilySchemaCommand( val env: Environment, val tableName: String, val familyName: String, val schema: SchemaSpec) extends TableDDLCommand { override def validateArguments(): Unit = { val layout = getInitialLayout() checkColFamilyIsMapType(layout, familyName) } override def updateLayout(layout: TableLayoutDesc.Builder): Unit = { val cellSchemaContext: CellSchemaContext = CellSchemaContext.create(env, layout, AddToAllSchemaUsageFlags) if (cellSchemaContext.supportsLayoutValidation) { echo("Deprecation warning: ALTER TABLE.. SET SCHEMA.. FOR FAMILY is deprecated.") echo("New syntax: ALTER TABLE.. ADD SCHEMA.. FOR FAMILY") // This class is deprecated in layout-1.3; run the AddSchema command's logic. new AlterTableAddFamilySchemaCommand(env, tableName, AddToAllSchemaUsageFlags, familyName, schema).updateLayout(layout) } else { // layout-1.2 or below: replace the CellSchema for the column. getFamily(layout, familyName) .getOrElse(throw new DDLException("Missing family: " + familyName)) .setMapSchema(schema.toNewCellSchema(cellSchemaContext)) } } }
kijiproject/kiji-schema-shell
src/main/scala/org/kiji/schema/shell/ddl/AlterTableSetFamilySchemaCommand.scala
Scala
apache-2.0
2,295
package org.jetbrains.plugins.scala.annotator import com.intellij.psi.PsiElement class ScalaLibVarianceTest extends VarianceTestBase { override def annotateFun(element: PsiElement, annotator: ScalaAnnotator, mock: AnnotatorHolderMock): Unit = annotator.annotate(element, mock) protected def code(insertLine: String): String = s""" |object O { | trait C[-T] | trait Tr[+T] { | $insertLine | } |} """.stripMargin def testSCL13235(): Unit = assertNothing(messages(code("val foo: C[_ <: T]"))) def testSCL13235_1(): Unit = assertNothing(messages(code("def foo: C[_ <: T]"))) def testSCL13235_2(): Unit = assertMatches(messages(code("object Inner extends C[T]"))) { case Error("C[T]", ContravariantPosition()) :: Nil => } def testSCL13235_3(): Unit = assertMatches(messages(code("trait Inner extends C[T]"))) { case Error("C[T]", ContravariantPosition()) :: Nil => } def testSCL13235_4(): Unit = assertMatches(messages(code("class Inner extends C[T]"))) { case Error("C[T]", ContravariantPosition()) :: Nil => } def testSCL13235_5(): Unit = assertMatches(messages(code("val foo: C[T]"))) { case Error("foo", ContravariantPosition()) :: Nil => } def testSCL13235_6(): Unit = assertNothing(messages( """ |object O { |trait T1 |trait T2 extends T1 | |class T[C] { | def bar1[B >: T1 <: T2] = {} | def bar2[B >: T2 <: T1] = {} |} |} """.stripMargin)) def testSCL13236(): Unit = assertNothing(messages( """ |object O { | class B[T] | class A[+T] { | private val foo: Any = new B[T] | } |} """.stripMargin)) def testSCL13235_7(): Unit = assertNothing(messages( """ |object O { | trait V[T] | trait V1[-T] | trait V2[+T] | trait MyTrait[+T, -T2] { | val foo: V[_ <: T] | val bar: V[_ >: T2] | val foo1: V1[_ <: T] | val bar1: V1[_ >: T2] | val foo2: V2[_ <: T] | val bar2: V2[_ >: T2] | } |} """.stripMargin)) def testSCL4391(): Unit = assertMatches(messages("class Thing[+A](var thing: A)")) { case Error("thing", ContravariantPosition()) :: Nil => } def testSCL4391_1(): Unit = assertNothing(messages("class Thing[-A](val thing: A)")) }
jastice/intellij-scala
scala/scala-impl/test/org/jetbrains/plugins/scala/annotator/ScalaLibVarianceTest.scala
Scala
apache-2.0
2,395
/* * Copyright (C) 2009-2018 Lightbend Inc. <https://www.lightbend.com> */ object Transitive
Shenker93/playframework
framework/src/sbt-plugin/src/sbt-test/play-sbt-plugin/multiproject/transitive/app/Transitive.scala
Scala
apache-2.0
95
package de.frosner.broccoli.models import de.frosner.broccoli.models.JobStatus.JobStatus import play.api.libs.json._ object JobStatus extends Enumeration { type JobStatus = Value val Running = Value("running") val Pending = Value("pending") val Stopped = Value("stopped") val Dead = Value("dead") val Unknown = Value("unknown") } object JobStatusJson { implicit val jobStatusWrites: Writes[JobStatus] = Writes(value => JsString(value.toString)) implicit val jobStatusReads: Reads[JobStatus] = Reads(_.validate[String].map(JobStatus.withName)) }
FRosner/cluster-broccoli
server/src/main/scala/de/frosner/broccoli/models/JobStatus.scala
Scala
apache-2.0
570
/* * Copyright (c) 2016. <[email protected]> * * TagTest.scala is part of marc4scala. * * marc4scala is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * marc4scala 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with marc4scala; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.marc4scala import org.scalatest.FlatSpec /** * Created by jason on 3/1/16. */ class TagTest extends FlatSpec { }
jasonzou/marc4scala
src/test/scala/org/marc4scala/TagTest.scala
Scala
gpl-3.0
958
package com.scalaAsm.x86 package Instructions package General // Description: Jump short if not overflow (OF=0) // Category: general/branch/cond trait JNO extends InstructionDefinition { val mnemonic = "JNO" } object JNO extends OneOperand[JNO] with JNOImpl trait JNOImpl extends JNO { implicit object _0 extends OneOp[rel8] { val opcode: OneOpcode = 0x71 val format = ImmFormat } implicit object _1 extends OneOp[rel16] { val opcode: TwoOpcodes = (0x0F, 0x81) val format = ImmFormat } implicit object _2 extends OneOp[rel32] { val opcode: TwoOpcodes = (0x0F, 0x81) val format = ImmFormat } }
bdwashbu/scala-x86-inst
src/main/scala/com/scalaAsm/x86/Instructions/General/JNO.scala
Scala
apache-2.0
637
import com.nn.math.activations.StepFunction import com.nn.{PerceptronLearningTrait, NNetwork} import org.scalatest._ import org.scalatest.junit.AssertionsForJUnit import org.junit.Assert._ import org.junit.Test import org.junit.Before import scala.collection.mutable.ArrayBuffer import scala.util.Random /** * Created by george on 10/11/14. */ class TestPerceptron extends AssertionsForJUnit { var neural_net: NNetwork with PerceptronLearningTrait = _ /** * Intialize the neural network for the tests */ @Before def initialize(): Unit ={ neural_net = new NNetwork with PerceptronLearningTrait } @Test def testInvalidOutputLayer(): Unit ={ try { neural_net.createOutputLayer(10,null) // fail if we succeed in creating the output layer fail() } catch { case e: IllegalStateException => // expected error } } @Test def testLayerCreation(): Unit ={ neural_net.createInputLayer(12,new StepFunction(0.0)) neural_net.createOutputLayer(1,new StepFunction(0.0)) neural_net.init() val neuralMap = neural_net.neurons // assertTrue(neuralMap(0).size > 0 && neuralMap(0).size == 11) // assertTrue(neuralMap(1).size > 0 && neuralMap(1).size == 1) } /** * Make sure the framework is correctly loading and storing the input data for the network */ @Test def testNNInputData(): Unit ={ val testInput = Array.fill[Double](10)(Random.nextInt()); neural_net.loadTrainingExample(testInput) neural_net.createInputLayer(10,new StepFunction(0.0)) neural_net.createOutputLayer(1,new StepFunction(0.0)) assertTrue(neural_net.inputTraining.size == 1 && neural_net.inputTraining(0) == testInput) } @Test def testFeedingTrainingData(): Unit ={ neural_net = new NNetwork with PerceptronLearningTrait val testInput = Array.fill[Double](12)(Random.nextInt()); neural_net.loadTrainingExample(testInput) neural_net.createInputLayer(10,new StepFunction(0.0)) neural_net.createOutputLayer(1,new StepFunction(0.0)) // Initialize the network with random weights between -1 and 1 neural_net.init() neural_net.learn(1,1) val neurons = neural_net.neurons // check that our output nodes have input data assertTrue(neurons(0).neuralLayer.forall(x => x.inputs.size > 0)) } }
GeorgeDittmar/Scala-NeuralNet
src/test/scala/TestPerceptron.scala
Scala
apache-2.0
2,326
trait Exec[T <: Exec[T]] object Tree { sealed trait Next[+T, +PL, +P, +H, +A] sealed trait Child[+T, +PL, +P, +H, +A] sealed trait Branch[T <: Exec[T], PL, P, H, A] extends Child[T, PL, P, H, A] with NonEmpty[T, PL, P, H] sealed trait NonEmpty[T <: Exec[T], PL, P, H] case object Empty extends Next[Nothing, Nothing, Nothing, Nothing, Nothing] sealed trait RightBranch[T <: Exec[T], PL, P, H, A] extends Next[T, PL, P, H, A] with Branch[T, PL, P, H, A] trait BranchImpl[T <: Exec[T], PL, P, H, A] { def next: Next[T, PL, P, H, A] def nextOption: Option[Branch[T, PL, P, H, A]] = next match { // crashes case b: RightBranch[T, PL, P, H, A] => Some(b) case Empty => None } } }
dotty-staging/dotty
tests/pos/i9841b.scala
Scala
apache-2.0
760
/* * Copyright 2014 Joshua R. Rodgers * * 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.theenginerd.core.client.model.builder.shapes import com.theenginerd.core.client.model.builder._ import com.theenginerd.core.client.model.builder.FaceGroup case class Box(width: Int, height: Int, depth: Int, x: Int = 0, y: Int = 0, z: Int = 0) extends Shape with QuadBuilder { private val vertices = Vector( //Bottom ((-width + x) / 32D, y / 32D, (-depth + z) / 32D), ((-width + x) / 32D, y / 32D, (depth + z) / 32D), ((width + x) / 32D, y / 32D, (depth + z) / 32D), ((width + x) / 32D, y / 32D, (-depth + z) / 32D), //Top ((-width + x) / 32D, (2 * height + y) / 32D, (-depth + z) / 32D), ((-width + x) / 32D, (2 * height + y) / 32D, (depth + z) / 32D), ((width + x) / 32D, (2 * height + y) / 32D, (depth + z) / 32D), ((width + x) / 32D, (2 * height + y) / 32D, (-depth + z) / 32D) ) private def defaultTextureCoordinates(side: BoxSide): (Int, Int, Int, Int) = side match { case BoxFront | BoxBack => (x + 8 - width / 2, y, width, height) case BoxLeft | BoxRight => (z + 8 - depth / 2, y, depth, height) case BoxTop | BoxBottom => (x + 8 - width / 2, z + 8 - depth / 2, width, depth) case _ => (0, 0, 16, 16) } private var sides: Map[BoxSide, SideInfo] = Map(BoxTop -> SideInfo(TextureDefault, None), BoxBottom -> SideInfo(TextureDefault, None), BoxLeft -> SideInfo(TextureDefault, None), BoxRight -> SideInfo(TextureDefault, None), BoxFront -> SideInfo(TextureDefault, None), BoxBack -> SideInfo(TextureDefault, None)) def setSideInfo(boxSides: BoxSide*)(textureCoordinates: TextureCoordinates = TextureDefault, groupName: Option[String] = None): Box = { sides ++= boxSides.map(_ -> SideInfo(textureCoordinates, groupName)) this } def toFaceGroups: Seq[FaceGroup] = { var faceGroups: Map[Option[String], Seq[Face]] = Map() for ((side, sideInfo) <- sides) { val faceGroupName = sideInfo.faceGroupName val faces = getFacesForSide(side, sideInfo) faceGroups += faceGroupName -> faceGroups.get(faceGroupName).map(_ ++ faces).getOrElse(faces) } (for ((group, faces) <- faceGroups) yield FaceGroup(group, faces)).toSeq } private def getFacesForSide(side: BoxSide, sideInfo: SideInfo): Seq[Face] = { val textureCoordinates = sideInfo.textureCoordinates.getOrElse(defaultTextureCoordinates(side)) side match { case BoxBottom => buildQuad(vertices, TopLeft(0), TopRight(3), BottomRight(2), BottomLeft(1), textureCoordinates) case BoxTop => buildQuad(vertices, TopLeft(4), BottomLeft(5), BottomRight(6), TopRight(7), textureCoordinates) case BoxLeft => buildQuad(vertices, BottomLeft(0), BottomRight(1), TopRight(5), TopLeft(4), textureCoordinates) case BoxRight => buildQuad(vertices, BottomRight(2), BottomLeft(3), TopLeft(7), TopRight(6), textureCoordinates) case BoxBack => buildQuad(vertices, BottomLeft(0), TopLeft(4), TopRight(7), BottomRight(3), textureCoordinates) case BoxFront => buildQuad(vertices, BottomLeft(1), BottomRight(2), TopRight(6), TopLeft(5), textureCoordinates) } } }
Mr-Byte/Random-Redstone
core/src/main/scala/com/theenginerd/core/client/model/builder/shapes/Box.scala
Scala
apache-2.0
4,318
package ulang.prove import ulang.expr.Expr import ulang.expr.Var import ulang.expr.App import ulang.expr.Apps class congruence { val emptyUse: Set[Expr] = Set() var rep = Map[Expr, Expr]() var use = Map[Expr, Set[Expr]]() withDefaultValue emptyUse var sig = Map[Expr, Expr]() def find(a: Expr): Expr = { val b = rep.getOrElse(a, a) if (a == b) { a } else { val c = find(b) // path compression rep += (a -> c) c } } def union(e1: Expr, e2: Expr) { rep += (find(e1) -> find(e2)) } def canon(e: Expr): Expr = e match { case App(fun, args) => canonsig(App(canon(fun), canon(args))) case _ => canonsig(e) } def ++=(es: List[(Expr, Expr)]) = { for ((e1, e2) <- es) this += (e1, e2) } def +=(e1: Expr, e2: Expr) = { merge(canon(e1), canon(e2)) } def canon(es: List[Expr]): List[Expr] = { es map canon } def replace(e: Expr, e1: Expr, e2: Expr): Expr = e match { case `e1` => e2 case App(fun, arg) => App(replace(fun, e1, e2), replace(arg, e1, e2)) case _ => e } def merge(e1: Expr, e2: Expr) { if (e1 != e2) { union(e1, e2) for (u <- use(e1)) { sig += u -> replace(sig(u), e1, e2) for (v <- use(e2) if sig(v) == sig(u)) { merge(find(u), find(v)) } use += e2 -> (use(e2) + u) } } } def canonsig(e: Expr): Expr = e match { case Apps(fun, args) => args flatMap use find (sig(_) == e) match { case Some(u) => find(u) case None => for (arg <- args) use += arg -> (use(arg) + e) sig += e -> e use -= e e } case _ => find(e) } }
gernst/ulang-proto
src/main/scala/ulang/prove/congruence.scala
Scala
mit
1,742
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 kafka.coordinator import kafka.common.TopicAndPartition import kafka.utils.nonthreadsafe /** * Consumer metadata contains the following metadata: * * Heartbeat metadata: * 1. negotiated heartbeat session timeout * 2. timestamp of the latest heartbeat * * Subscription metadata: * 1. subscribed topics * 2. assigned partitions for the subscribed topics * * In addition, it also contains the following state information: * * 1. Awaiting rebalance callback: when the consumer group is in the prepare-rebalance state, * its rebalance callback will be kept in the metadata if the * consumer has sent the join group request */ @nonthreadsafe private[coordinator] class ConsumerMetadata(val consumerId: String, val groupId: String, var topics: Set[String], val sessionTimeoutMs: Int) { var awaitingRebalanceCallback: (Set[TopicAndPartition], String, Int, Short) => Unit = null var assignedTopicPartitions = Set.empty[TopicAndPartition] var latestHeartbeat: Long = -1 var isLeaving: Boolean = false }
vkroz/kafka
core/src/main/scala/kafka/coordinator/ConsumerMetadata.scala
Scala
apache-2.0
2,027
package im.actor.server.api.rpc.service import java.net.URLEncoder import java.time.{ LocalDateTime, ZoneOffset } import scala.concurrent.{ ExecutionContext, Future } import scala.util.Random import scalaz.\\/ import akka.contrib.pattern.DistributedPubSubExtension import com.google.protobuf.{ ByteString, CodedInputStream } import org.scalatest.Inside._ import im.actor.api.rpc._ import im.actor.api.rpc.auth._ import im.actor.api.rpc.contacts.UpdateContactRegistered import im.actor.api.rpc.misc.ResponseVoid import im.actor.api.rpc.users.{ ContactRecord, ContactType, Sex } import im.actor.server.activation.internal.{ ActivationConfig, InternalCodeActivation } import im.actor.server.api.rpc.RpcApiService import im.actor.server.api.rpc.service.auth.AuthErrors import im.actor.server.api.rpc.service.sequence.{ SequenceServiceConfig, SequenceServiceImpl } import im.actor.server.models.contact.UserContact import im.actor.server.mtproto.codecs.protocol.MessageBoxCodec import im.actor.server.mtproto.protocol.{ MessageBox, SessionHello } import im.actor.server.oauth.{ GoogleProvider, OAuth2GoogleConfig } import im.actor.server.persist.auth.AuthTransaction import im.actor.server.presences.{ GroupPresenceManager, PresenceManager } import im.actor.server.push.{ SeqUpdatesManager, WeakUpdatesManager } import im.actor.server.session.{ HandleMessageBox, Session, SessionConfig, SessionEnvelope } import im.actor.server.sms.AuthSmsEngine import im.actor.server._ final class AuthServiceSpec extends BaseAppSuite with ImplicitUserRegions with ImplicitSequenceService with ImplicitSessionRegionProxy with SequenceMatchers { behavior of "AuthService" //phone part "StartPhoneAuth handler" should "respond with ok to correct phone number" in s.e1 it should "respond with ok to phone number of registered user" in s.e2 it should "respond with error to invalid phone number" in s.e3 it should "respond with same transactionHash when called multiple times" in s.e33 "ValidateCode handler" should "respond with error to invalid transactionHash" in s.e4 it should "respond with error to wrong sms auth code" in s.e5 it should "respond with error to expired sms auth code" in s.e50 it should "respond with PhoneNumberUnoccupied error when new user code validation succeed" in s.e6 it should "complete sign in process for registered user" in s.e7 it should "invalidate auth code after number attempts given in config" in s.e70 "SignUp handler" should "respond with error if it was called before validateCode" in s.e8 it should "complete sign up process for unregistered user" in s.e9 it should "register unregistered contacts and send updates" in s.e90 "AuthTransaction and AuthSmsCode" should "be invalidated after sign in process successfully completed" in s.e10 it should "be invalidated after sign up process successfully completed" in s.e11 //email part "StartEmailAuth handler" should "respond with ok to correct email address" in s.e12 // it should "respond with ok to email of registered user" in s.e13 it should "respond with error to malformed email address" in s.e14 it should "respond with same transactionHash when called multiple times" in s.e15 "GetOAuth2Params handler" should "respond with error when malformed url is passed" in s.e16 it should "respond with error when wrong transactionHash is passed" in s.e17 it should "respond with correct authUrl on correct request" in s.e18 "CompleteOAuth2 handler" should "respond with error when wrong transactionHash is passed" in s.e19 it should "respond with EmailUnoccupied error when new user oauth token retreived" in s.e20 it should "respond with error when unable to get oauth2 token" in s.e200 // it should "complete sign in process for registered user" in s.e21 "SignUp handler" should "respond with error if it was called before completeOAuth2" in s.e22 it should "complete sign up process for unregistered user via email oauth" in s.e23 it should "register unregistered contacts and send updates for email auth" in s.e24 "Logout" should "remove authId and vendor credentials" in s.e25 object s { implicit val ec = system.dispatcher implicit val weakUpdManagerRegion = WeakUpdatesManager.startRegion() implicit val presenceManagerRegion = PresenceManager.startRegion() implicit val groupPresenceManagerRegion = GroupPresenceManager.startRegion() val mediator = DistributedPubSubExtension(system).mediator implicit val sessionConfig = SessionConfig.load(system.settings.config.getConfig("session")) Session.startRegion(Some(Session.props(mediator))) implicit val sessionRegion = Session.startRegionProxy() val oauthGoogleConfig = DummyOAuth2Server.config implicit val oauth2Service = new GoogleProvider(oauthGoogleConfig) val activationConfig = ActivationConfig.load.get val activationContext = InternalCodeActivation.newContext(activationConfig, new DummySmsEngine, null) implicit val service = new auth.AuthServiceImpl(activationContext, mediator) implicit val rpcApiService = system.actorOf(RpcApiService.props(Seq(service))) val correctUri = "https://actor.im/registration" val correctAuthCode = "0000" val gmail = "gmail.com" DummyOAuth2Server.start() def e1() = { val phoneNumber = buildPhone() implicit val clientData = ClientData(createAuthId(), createSessionId(), None) whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ inside(resp) { case Ok(ResponseStartPhoneAuth(hash, false)) β‡’ hash should not be empty } } } def e2() = { val (user, authId, phoneNumber) = createUser() implicit val clientData = ClientData(authId, createSessionId(), Some(user.id)) whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ inside(resp) { case Ok(ResponseStartPhoneAuth(hash, true)) β‡’ hash should not be empty } } } def e3() = { implicit val clientData = ClientData(createAuthId(), createSessionId(), None) whenReady(startPhoneAuth(2)) { resp β‡’ inside(resp) { case Error(AuthErrors.PhoneNumberInvalid) β‡’ } } } def e33() = { val phoneNumber = buildPhone() implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } resp.toOption.get.transactionHash } val seq = Future.sequence(List( startPhoneAuth(phoneNumber), startPhoneAuth(phoneNumber), startPhoneAuth(phoneNumber), startPhoneAuth(phoneNumber) )) whenReady(seq) { resps β‡’ resps foreach { inside(_) { case Ok(ResponseStartPhoneAuth(hash, false)) β‡’ hash shouldEqual transactionHash } } } } def e4() = { val phoneNumber = buildPhone() implicit val clientData = ClientData(createAuthId(), createSessionId(), None) whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } } whenReady(service.handleValidateCode("wrongHash123123", correctAuthCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.InvalidAuthTransaction) β‡’ } } } def e5() = { val phoneNumber = buildPhone() implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val wrongCode = "12321" val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleValidateCode(transactionHash, wrongCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.PhoneCodeInvalid) β‡’ } } } def e50() = { import im.actor.server.db.ActorPostgresDriver.api._ val phoneNumber = buildPhone() implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } resp.toOption.get.transactionHash } val dateUpdate = persist.AuthCode.codes .filter(_.transactionHash === transactionHash) .map(_.createdAt) .update(LocalDateTime.now(ZoneOffset.UTC).minusHours(25)) whenReady(db.run(dateUpdate))(_ β‡’ ()) whenReady(service.handleValidateCode(transactionHash, correctAuthCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.PhoneCodeExpired) β‡’ } } whenReady(db.run(AuthTransaction.find(transactionHash))) { _ shouldBe empty } whenReady(db.run(persist.AuthCode.findByTransactionHash(transactionHash))) { _ shouldBe empty } } def e6() = { val phoneNumber = buildPhone() implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleValidateCode(transactionHash, correctAuthCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.PhoneNumberUnoccupied) β‡’ } } whenReady(db.run(persist.auth.AuthTransaction.find(transactionHash))) { optCache β‡’ optCache should not be empty optCache.get.isChecked shouldEqual true } } def e7() = { val (user, authId, phoneNumber) = createUser() val sessionId = createSessionId() implicit val clientData = ClientData(authId, sessionId, Some(user.id)) sendSessionHello(authId, sessionId) val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, true)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleValidateCode(transactionHash, correctAuthCode)) { resp β‡’ inside(resp) { case Ok(ResponseAuth(respUser, _)) β‡’ respUser.name shouldEqual user.name respUser.sex shouldEqual user.sex } } } def e70() = { val phoneNumber = buildPhone() implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val wrongCode = "12321" val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleValidateCode(transactionHash, wrongCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.PhoneCodeInvalid) β‡’ } } whenReady(service.handleValidateCode(transactionHash, wrongCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.PhoneCodeInvalid) β‡’ } } whenReady(service.handleValidateCode(transactionHash, wrongCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.PhoneCodeExpired) β‡’ } } //after code invalidation we remove authCode and AuthTransaction, thus we got InvalidAuthTransaction error whenReady(service.handleValidateCode(transactionHash, correctAuthCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.InvalidAuthTransaction) β‡’ } } whenReady(db.run(persist.AuthCode.findByTransactionHash(transactionHash))) { code β‡’ code shouldBe empty } whenReady(db.run(persist.auth.AuthTransaction.find(transactionHash))) { transaction β‡’ transaction shouldBe empty } } def e8() = { val phoneNumber = buildPhone() val userName = "Rock Jam" val userSex = Some(Sex.Male) val authId = createAuthId() val sessionId = createSessionId() implicit val clientData = ClientData(authId, sessionId, None) val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleSignUp(transactionHash, userName, userSex)) { resp β‡’ inside(resp) { case Error(AuthErrors.NotValidated) β‡’ } } whenReady(db.run(persist.auth.AuthTransaction.find(transactionHash))) { optCache β‡’ optCache should not be empty optCache.get.isChecked shouldEqual false } } def e9() = { val phoneNumber = buildPhone() val userName = "Rock Jam" val userSex = Some(Sex.Male) val authId = createAuthId() val sessionId = createSessionId() implicit val clientData = ClientData(authId, sessionId, None) sendSessionHello(authId, sessionId) val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleValidateCode(transactionHash, correctAuthCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.PhoneNumberUnoccupied) β‡’ } } whenReady(service.handleSignUp(transactionHash, userName, userSex)) { resp β‡’ inside(resp) { case Ok(ResponseAuth(user, _)) β‡’ user.name shouldEqual userName user.sex shouldEqual userSex user.phone shouldEqual Some(phoneNumber) user.contactInfo should have length 1 user.contactInfo.head should matchPattern { case ContactRecord(ContactType.Phone, None, Some(phone), Some(_), None) β‡’ } } } } def e90() = { val phoneNumber = buildPhone() val userName = "Rock Jam" val userSex = Some(Sex.Male) val authId = createAuthId() val sessionId = createSessionId() val unregClientData = ClientData(authId, sessionId, None) //make unregistered contact val (regUser, regAuthId, _) = createUser() whenReady(db.run(persist.contact.UnregisteredPhoneContact.createIfNotExists(phoneNumber, regUser.id, Some("Local name"))))(_ β‡’ ()) val regClientData = ClientData(regAuthId, sessionId, Some(regUser.id)) sendSessionHello(authId, sessionId) val user = { implicit val clientData = unregClientData val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleValidateCode(transactionHash, correctAuthCode))(_ β‡’ ()) whenReady(service.handleSignUp(transactionHash, userName, userSex))(_.toOption.get.user) } { implicit val clientData = regClientData expectUpdate[UpdateContactRegistered](0, Array.empty, UpdateContactRegistered.header)(identity) } whenReady(db.run(persist.contact.UnregisteredPhoneContact.find(phoneNumber))) { _ shouldBe empty } whenReady(db.run(persist.contact.UserContact.find(regUser.id, user.id))) { optContact β‡’ optContact should not be empty optContact.get should matchPattern { case UserContact(_, _, Some(_), _, false) β‡’ } } } def e10() = { val (user, authId, phoneNumber) = createUser() val sessionId = createSessionId() implicit val clientData = ClientData(authId, sessionId, Some(user.id)) sendSessionHello(authId, sessionId) val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, true)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleValidateCode(transactionHash, correctAuthCode)) { resp β‡’ inside(resp) { case Ok(ResponseAuth(respUser, _)) β‡’ } } whenReady(db.run(persist.auth.AuthTransaction.find(transactionHash))) { _ shouldBe empty } whenReady(db.run(persist.AuthCode.findByTransactionHash(transactionHash))) { _ shouldBe empty } } def e11() = { val phoneNumber = buildPhone() val userName = "Rock Jam" val userSex = Some(Sex.Male) val authId = createAuthId() val sessionId = createSessionId() implicit val clientData = ClientData(authId, sessionId, None) sendSessionHello(authId, sessionId) val transactionHash = whenReady(startPhoneAuth(phoneNumber)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartPhoneAuth(_, false)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleValidateCode(transactionHash, correctAuthCode)) { resp β‡’ inside(resp) { case Error(AuthErrors.PhoneNumberUnoccupied) β‡’ } } whenReady(service.handleSignUp(transactionHash, userName, userSex)) { resp β‡’ inside(resp) { case Ok(ResponseAuth(user, _)) β‡’ } } whenReady(db.run(persist.auth.AuthTransaction.find(transactionHash))) { _ shouldBe empty } whenReady(db.run(persist.AuthCode.findByTransactionHash(transactionHash))) { _ shouldBe empty } } def e12() = { val email = buildEmail(gmail) implicit val clientData = ClientData(createAuthId(), createSessionId(), None) whenReady(startEmailAuth(email)) { resp β‡’ inside(resp) { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ hash should not be empty } } } def e13() = {} def e14() = { val malformedEmail = "foo@bar" implicit val clientData = ClientData(createAuthId(), createSessionId(), None) whenReady(startEmailAuth(malformedEmail)) { resp β‡’ inside(resp) { case Error(err) β‡’ err.tag shouldEqual "EMAIL_INVALID" } } } def e15() = { val email = buildEmail(gmail) implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val transactionHash = whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } resp.toOption.get.transactionHash } val seq = Future.sequence(List( startEmailAuth(email), startEmailAuth(email), startEmailAuth(email), startEmailAuth(email), startEmailAuth(email), startEmailAuth(email) )) whenReady(seq) { resps β‡’ resps foreach { inside(_) { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ hash shouldEqual transactionHash } } } } def e16() = { val email = buildEmail(gmail) implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val malformedUri = "ht :/asda.rr/123" val transactionHash = whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleGetOAuth2Params(transactionHash, malformedUri)) { resp β‡’ inside(resp) { case Error(AuthErrors.RedirectUrlInvalid) β‡’ } } } def e17() = { val email = buildEmail(gmail) implicit val clientData = ClientData(createAuthId(), createSessionId(), None) whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } } whenReady(service.handleGetOAuth2Params("wrongHash22aksdl320d3", correctUri)) { resp β‡’ inside(resp) { case Error(AuthErrors.InvalidAuthTransaction) β‡’ } } } def e18() = { val email = buildEmail(gmail) implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val transactionHash = whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleGetOAuth2Params(transactionHash, correctUri)) { resp β‡’ inside(resp) { case Ok(ResponseGetOAuth2Params(url)) β‡’ url should not be empty url should include(oauthGoogleConfig.authUri) url should include(URLEncoder.encode(correctUri, "utf-8")) } } whenReady(db.run(persist.auth.AuthEmailTransaction.find(transactionHash))) { optCache β‡’ optCache should not be empty val cache = optCache.get cache.redirectUri shouldEqual Some(correctUri) } } def e19() = { val email = buildEmail(gmail) implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val transactionHash = whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleGetOAuth2Params(transactionHash, correctUri)) { resp β‡’ inside(resp) { case Ok(ResponseGetOAuth2Params(url)) β‡’ } } whenReady(service.handleCompleteOAuth2("wrongTransactionHash29191djlksa", "4/YUlNIa55xSZRA4JcQkLzAh749bHAcv96aA-oVMHTQRU")) { resp β‡’ inside(resp) { case Error(AuthErrors.InvalidAuthTransaction) β‡’ } } } def e20() = { val email = buildEmail(gmail) DummyOAuth2Server.email = email implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val transactionHash = whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleGetOAuth2Params(transactionHash, correctUri)) { resp β‡’ inside(resp) { case Ok(ResponseGetOAuth2Params(url)) β‡’ } } whenReady(service.handleCompleteOAuth2(transactionHash, "code")) { resp β‡’ inside(resp) { case Error(AuthErrors.EmailUnoccupied) β‡’ } } whenReady(db.run(persist.auth.AuthTransaction.find(transactionHash))) { optCache β‡’ optCache should not be empty optCache.get.isChecked shouldEqual true } whenReady(db.run(persist.OAuth2Token.findByUserId(email))) { optToken β‡’ optToken should not be empty val token = optToken.get token.accessToken should not be empty token.refreshToken should not be empty } } def e200() = { val email = buildEmail(gmail) implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val transactionHash = whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleGetOAuth2Params(transactionHash, correctUri)) { resp β‡’ inside(resp) { case Ok(ResponseGetOAuth2Params(url)) β‡’ } } whenReady(service.handleCompleteOAuth2(transactionHash, "wrongCode")) { resp β‡’ inside(resp) { case Error(AuthErrors.FailedToGetOAuth2Token) β‡’ } } whenReady(db.run(persist.auth.AuthTransaction.find(transactionHash))) { optCache β‡’ optCache should not be empty optCache.get.isChecked shouldEqual false } } def e21() = {} def e22() = { val email = buildEmail(gmail) val userName = "Rock Jam" val userSex = Some(Sex.Male) implicit val clientData = ClientData(createAuthId(), createSessionId(), None) val transactionHash = whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleSignUp(transactionHash, userName, userSex)) { resp β‡’ inside(resp) { case Error(AuthErrors.NotValidated) β‡’ } } whenReady(db.run(persist.auth.AuthTransaction.find(transactionHash))) { optCache β‡’ optCache should not be empty optCache.get.isChecked shouldEqual false } } def e23() = { val email = buildEmail(gmail) DummyOAuth2Server.email = email val userName = "Rock Jam" val userSex = Some(Sex.Male) val authId = createAuthId() val sessionId = createSessionId() implicit val clientData = ClientData(authId, sessionId, None) sendSessionHello(authId, sessionId) val transactionHash = whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleGetOAuth2Params(transactionHash, correctUri)) { resp β‡’ inside(resp) { case Ok(ResponseGetOAuth2Params(url)) β‡’ } } whenReady(service.handleCompleteOAuth2(transactionHash, "code")) { resp β‡’ inside(resp) { case Error(AuthErrors.EmailUnoccupied) β‡’ } } val user = whenReady(service.handleSignUp(transactionHash, userName, userSex)) { resp β‡’ inside(resp) { case Ok(ResponseAuth(u, _)) β‡’ u.name shouldEqual userName u.sex shouldEqual userSex u.contactInfo should have length 1 u.contactInfo.head should matchPattern { case ContactRecord(ContactType.Email, Some(`email`), None, Some(_), None) β‡’ } } resp.toOption.get.user } whenReady(db.run(persist.UserEmail.find(email))) { optEmail β‡’ optEmail should not be empty optEmail.get.userId shouldEqual user.id } whenReady(db.run(persist.OAuth2Token.findByUserId(email))) { optToken β‡’ optToken should not be empty val token = optToken.get token.accessToken should not be empty token.refreshToken should not be empty } } def e24() = { val email = buildEmail(gmail) DummyOAuth2Server.email = email val userName = "Rock Jam" val userSex = Some(Sex.Male) val authId = createAuthId() val sessionId = createSessionId() val unregClientData = ClientData(authId, sessionId, None) //make unregistered contact val (regUser, regAuthId, _) = createUser() whenReady(db.run(persist.contact.UnregisteredEmailContact.createIfNotExists(email, regUser.id, Some("Local name"))))(_ β‡’ ()) val regClientData = ClientData(regAuthId, sessionId, Some(regUser.id)) sendSessionHello(authId, sessionId) val user = { implicit val clientData = unregClientData val transactionHash = whenReady(startEmailAuth(email)) { resp β‡’ resp should matchPattern { case Ok(ResponseStartEmailAuth(hash, false, EmailActivationType.OAUTH2)) β‡’ } resp.toOption.get.transactionHash } whenReady(service.handleGetOAuth2Params(transactionHash, correctUri))(_ β‡’ ()) whenReady(service.handleCompleteOAuth2(transactionHash, "code"))(_ β‡’ ()) whenReady(service.handleSignUp(transactionHash, userName, userSex))(_.toOption.get.user) } { implicit val clientData = regClientData expectUpdate[UpdateContactRegistered](0, Array.empty, UpdateContactRegistered.header)(identity) } whenReady(db.run(persist.contact.UnregisteredEmailContact.find(email))) { _ shouldBe empty } whenReady(db.run(persist.contact.UserContact.find(regUser.id, user.id))) { optContact β‡’ optContact should not be empty optContact.get should matchPattern { case UserContact(_, _, _, _, false) β‡’ } } } def e25() = { val (user, authId, _) = createUser() val sessionId = createSessionId() implicit val clientData = ClientData(authId, sessionId, Some(user.id)) SeqUpdatesManager.setPushCredentials(authId, models.push.GooglePushCredentials(authId, 22L, "hello")) SeqUpdatesManager.setPushCredentials(authId, models.push.ApplePushCredentials(authId, 22, "hello".getBytes())) //let seqUpdateManager register credentials Thread.sleep(1000L) whenReady(db.run(persist.AuthId.find(authId))) { optAuthId β‡’ optAuthId shouldBe defined } whenReady(db.run(persist.push.GooglePushCredentials.find(authId))) { optGoogleCreds β‡’ optGoogleCreds shouldBe defined } whenReady(db.run(persist.push.ApplePushCredentials.find(authId))) { appleCreds β‡’ appleCreds shouldBe defined } whenReady(service.handleSignOut()) { resp β‡’ resp should matchPattern { case Ok(ResponseVoid) β‡’ } } //let seqUpdateManager register credentials Thread.sleep(1000L) whenReady(db.run(persist.AuthId.find(authId))) { optAuthId β‡’ optAuthId should not be defined } whenReady(db.run(persist.push.GooglePushCredentials.find(authId))) { optGoogleCreds β‡’ optGoogleCreds should not be defined } whenReady(db.run(persist.push.ApplePushCredentials.find(authId))) { appleCreds β‡’ appleCreds should not be defined } } private def startPhoneAuth(phoneNumber: Long)(implicit clientData: ClientData): Future[\\/[RpcError, ResponseStartPhoneAuth]] = { service.handleStartPhoneAuth( phoneNumber = phoneNumber, appId = 42, apiKey = "apiKey", deviceHash = Random.nextLong().toBinaryString.getBytes, deviceTitle = "Specs virtual device" ) } private def startEmailAuth(email: String)(implicit clientData: ClientData): Future[\\/[RpcError, ResponseStartEmailAuth]] = { service.handleStartEmailAuth( email = email, appId = 42, apiKey = "apiKey", deviceHash = Random.nextLong().toBinaryString.getBytes, deviceTitle = "Specs virtual device" ) } private def sendSessionHello(authId: Long, sessionId: Long): Unit = { val message = HandleMessageBox(ByteString.copyFrom(MessageBoxCodec.encode(MessageBox(Random.nextLong(), SessionHello)).require.toByteBuffer)) sessionRegion.ref ! SessionEnvelope(authId, sessionId).withHandleMessageBox(message) } } } object DummyOAuth2Server { import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model.FormData import akka.http.scaladsl.server.Directives._ import akka.http.scaladsl.server.Route import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers._ import akka.stream.Materializer import org.apache.commons.codec.digest.DigestUtils val config = OAuth2GoogleConfig( "http://localhost:3000/o/oauth2/auth", "http://localhost:3000", "http://localhost:3000", "actor", "AA1865139A1CACEABFA45E6635AA7761", "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile" ) var email: String = "" private def response() = { val bytes = Random.nextLong().toBinaryString.getBytes val refreshToken = DigestUtils.md5Hex(bytes) val accessToken = DigestUtils.sha256Hex(bytes) s"""{"access_token": "$accessToken", | "token_type": "Bearer", | "expires_in": 3600, | "refresh_token": "$refreshToken"}""".stripMargin } def start()( implicit system: ActorSystem, materializer: Materializer ): Unit = { implicit val ec: ExecutionContext = system.dispatcher def profile = s"""{"family_name": "Jam", | "name": "Rock Jam", | "picture": "https://lh3.googleusercontent.com/-LL4HijQ2VDo/AAAAAAAAAAI/AAAAAAAAAAc/Lo5E9bw1Loc/s170-c-k-no/photo.jpg", | "locale": "ru", | "gender": "male", | "email": "$email", | "link": "https://plus.google.com/108764816638640823343", | "given_name": "Rock", | "id": "108764816638640823343", | "verified_email": true}""".stripMargin def routes: Route = post { entity(as[FormData]) { data β‡’ data.fields.get("code") match { case Some("wrongCode") β‡’ complete("{}") case Some(_) β‡’ complete(response()) case None β‡’ throw new Exception("invalid request!") } } } ~ get { complete(profile) } Http().bind("0.0.0.0", 3000).runForeach { connection β‡’ connection handleWith Route.handlerFlow(routes) } } } class DummySmsEngine extends AuthSmsEngine { override def sendCode(phoneNumber: Long, code: String): Future[Unit] = Future.successful(()) }
x303597316/actor-platform
actor-server/actor-tests/src/test/scala/im/actor/server/api/rpc/service/AuthServiceSpec.scala
Scala
mit
33,929