text:
package org.jetbrains.plugins.scala
package lang
package psi
package impl
package base

import com.intellij.lang.ASTNode
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi._
import com.intellij.psi.impl.source.JavaDummyHolder
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.IncorrectOperationException
import org.jetbrains.plugins.scala.annotator.intention.ScalaImportTypeFix
import org.jetbrains.plugins.scala.annotator.intention.ScalaImportTypeFix.{ClassTypeToImport, TypeAliasToImport, TypeToImport}
import org.jetbrains.plugins.scala.extensions.{PsiClassExt, PsiElementExt, PsiNamedElementExt, PsiTypeExt, ifReadAllowed}
import org.jetbrains.plugins.scala.lang.completion.lookups.LookupElementManager
import org.jetbrains.plugins.scala.lang.formatting.settings.ScalaCodeStyleSettings
import org.jetbrains.plugins.scala.lang.lexer.ScalaTokenTypes
import org.jetbrains.plugins.scala.lang.psi.api.base._
import org.jetbrains.plugins.scala.lang.psi.api.base.patterns.{ScBindingPattern, ScConstructorPattern, ScInfixPattern, ScInterpolationPattern}
import org.jetbrains.plugins.scala.lang.psi.api.base.types.{ScInfixTypeElement, ScParameterizedTypeElement, ScSimpleTypeElement, ScTypeElement}
import org.jetbrains.plugins.scala.lang.psi.api.expr.{ScReferenceExpression, ScSuperReference, ScThisReference}
import org.jetbrains.plugins.scala.lang.psi.api.statements.{ScAnnotationsHolder, ScFunction, ScMacroDefinition, ScTypeAlias}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.imports._
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.templates.{ScExtendsBlock, ScTemplateBody}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef._
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.{ScPackaging, ScTypedDefinition}
import org.jetbrains.plugins.scala.lang.psi.api.{ScPackage, ScalaElementVisitor, ScalaFile}
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory.createReferenceFromText
import org.jetbrains.plugins.scala.lang.psi.impl.expr.ScReferenceElementImpl
import org.jetbrains.plugins.scala.lang.psi.types.ScSubstitutor
import org.jetbrains.plugins.scala.lang.psi.types.api.Nothing
import org.jetbrains.plugins.scala.lang.psi.types.api.designator.{ScDesignatorType, ScProjectionType}
import org.jetbrains.plugins.scala.lang.resolve.processor.{BaseProcessor, CompletionProcessor, ExtractorResolveProcessor}
import org.jetbrains.plugins.scala.lang.resolve.{StableCodeReferenceElementResolver, _}
import org.jetbrains.plugins.scala.lang.scaladoc.psi.api.ScDocResolvableCodeReference
import org.jetbrains.plugins.scala.macroAnnotations.{CachedWithRecursionGuard, ModCount}
import org.jetbrains.plugins.scala.worksheet.ammonite.AmmoniteUtil

/**
 * @author AlexanderPodkhalyuzin
 *         Date: 22.02.2008
 */

class ScStableCodeReferenceElementImpl(node: ASTNode) extends ScReferenceElementImpl(node) with ScStableCodeReferenceElement {
  override def accept(visitor: PsiElementVisitor) {
    visitor match {
      case visitor: ScalaElementVisitor => super.accept(visitor)
      case _ => super.accept(visitor)
    }
  }

  def getVariants: Array[Object] = {
    val isInImport: Boolean = this.parentOfType(classOf[ScImportStmt], strict = false).isDefined
    doResolve(new CompletionProcessor(getKinds(incomplete = true), this)).flatMap {
      case res: ScalaResolveResult =>
        val qualifier = res.fromType.getOrElse(Nothing)
        LookupElementManager.getLookupElement(res, isInImport = isInImport, qualifierType = qualifier, isInStableCodeReference = true)
      case r => Seq(r.getElement)
    }
  }

  def getResolveResultVariants: Array[ScalaResolveResult] = {
    doResolve(new CompletionProcessor(getKinds(incomplete = true), this)).flatMap {
      case res: ScalaResolveResult => Seq(res)
      case _ => Seq.empty
    }
  }

  def getConstructor: Option[ScConstructor] = {
    getContext match {
      case s: ScSimpleTypeElement =>
        s.getContext match {
          case p: ScParameterizedTypeElement =>
            p.getContext match {
              case constr: ScConstructor => Some(constr)
              case _ => None
            }
          case constr: ScConstructor => Some(constr)
          case _ => None
        }
      case _ => None
    }
  }

  def isConstructorReference: Boolean = getConstructor.nonEmpty

  override def toString: String = "CodeReferenceElement: " + ifReadAllowed(getText)("")

  def getKinds(incomplete: Boolean, completion: Boolean): Set[ResolveTargets.Value] = {
    import org.jetbrains.plugins.scala.lang.resolve.StdKinds._

    // The qualified identifier immediately following the `macro` keyword
    // may only refer to a method.
    def isInMacroDef = getContext match {
      case _: ScMacroDefinition =>
        this.prevSiblings.exists {
          case l: LeafPsiElement if l.getNode.getElementType == ScalaTokenTypes.kMACRO => true
          case _ => false
        }
      case _ => false
    }

    val result = getContext match {
      case _: ScStableCodeReferenceElement => stableQualRef
      case e: ScImportExpr => if (e.selectorSet.isDefined
              //import Class._ is not allowed
        || qualifier.isEmpty || e.isSingleWildcard) stableQualRef
      else stableImportSelector
      case ste: ScSimpleTypeElement =>
        if (incomplete) noPackagesClassCompletion // todo use the settings to include packages
        else if (ste.getLastChild.isInstanceOf[PsiErrorElement]) stableQualRef

        else if (ste.singleton) stableQualRef
        else if (ste.annotation) annotCtor
        else stableClass
      case _: ScTypeAlias => stableClass
      case _: ScInterpolationPattern => stableImportSelector
      case _: ScConstructorPattern => objectOrValue
      case _: ScInfixPattern => objectOrValue
      case _: ScThisReference | _: ScSuperReference => stableClassOrObject
      case _: ScImportSelector => stableImportSelector
      case _: ScInfixTypeElement => stableClass
      case _ if isInMacroDef => methodsOnly
      case _ => stableQualRef
    }
    if (completion) result + ResolveTargets.PACKAGE + ResolveTargets.OBJECT + ResolveTargets.VAL else result
  }

  def nameId: PsiElement = findChildByType[PsiElement](ScalaTokenTypes.tIDENTIFIER)

  //  @throws(IncorrectOperationException)
  def bindToElement(element: PsiElement): PsiElement = {
    object CheckedAndReplaced {
      def unapply(text: String): Option[PsiElement] = {
        val ref = createReferenceFromText(text, getContext, ScStableCodeReferenceElementImpl.this)
        if (ref.isReferenceTo(element)) {
          val ref = createReferenceFromText(text)
          Some(ScStableCodeReferenceElementImpl.this.replace(ref))
        }
        else None
      }
    }

    if (isReferenceTo(element)) this
    else {
      val aliasedRef: Option[ScReferenceElement] = ScalaPsiUtil.importAliasFor(element, this)
      if (aliasedRef.isDefined) {
        this.replace(aliasedRef.get)
      }
      else {
        def bindToType(c: ScalaImportTypeFix.TypeToImport): PsiElement = {
          val suitableKinds = getKinds(incomplete = false)
          if (!ResolveUtils.kindMatches(element, suitableKinds)) {
            reportWrongKind(c, suitableKinds)
          }
          if (nameId.getText != c.name) {
            val ref = createReferenceFromText(c.name)
            return this.replace(ref).asInstanceOf[ScStableCodeReferenceElement].bindToElement(element)
          }
          val qname = c.qualifiedName
          val isPredefined = ScalaCodeStyleSettings.getInstance(getProject).hasImportWithPrefix(qname)
          if (qualifier.isDefined && !isPredefined) {
            c.name match {
              case CheckedAndReplaced(newRef) => return newRef
              case _ =>
            }
          }
          if (qname != null) {
            val selector: ScImportSelector = PsiTreeUtil.getParentOfType(this, classOf[ScImportSelector])
            val importExpr = PsiTreeUtil.getParentOfType(this, classOf[ScImportExpr])
            if (selector != null) {
              selector.deleteSelector() //we can't do anything here, so just simply delete it
              return importExpr.reference.get //todo: what we should return exactly?
              //              }
            } else if (importExpr != null) {
              if (importExpr == getParent && !importExpr.isSingleWildcard && importExpr.selectorSet.isEmpty) {
                val holder = PsiTreeUtil.getParentOfType(this, classOf[ScImportsHolder])
                importExpr.deleteExpr()
                c match {
                  case ClassTypeToImport(clazz) => holder.addImportForClass(clazz)
                  case ta => holder.addImportForPath(ta.qualifiedName)
                }
                //todo: so what to return? probable PIEAE after such code invocation
              } else {
                //qualifier reference in import expression
                qname match {
                  case CheckedAndReplaced(newRef) => return newRef
                  case _ =>
                }
              }
            }
            else {
              return safeBindToElement(qname, {
                case (qual, true) => createReferenceFromText(qual, getContext, this)
                case (qual, false) => createReferenceFromText(qual)
              }) {
                c match {
                  case ClassTypeToImport(clazz) =>
                    ScalaImportTypeFix.getImportHolder(ref = this, project = getProject).
                      addImportForClass(clazz, ref = this)
                  case ta =>
                    ScalaImportTypeFix.getImportHolder(ref = this, project = getProject).
                      addImportForPath(ta.qualifiedName, ref = this)
                }
                if (qualifier.isDefined) {
                  //let's make our reference unqualified
                  val ref: ScStableCodeReferenceElement = createReferenceFromText(c.name)
                  this.replace(ref).asInstanceOf[ScReferenceElement]
                }
                this
              }
            }
          }
          this
        }
        element match {
          case c: PsiClass =>
            val suitableKinds = getKinds(incomplete = false)
            if (!ResolveUtils.kindMatches(element, suitableKinds)) {
              ScalaPsiUtil.getCompanionModule(c) match {
                case Some(companion) => bindToType(ClassTypeToImport(companion))
                case None => bindToType(ClassTypeToImport(c))
              }
            }
            else bindToType(ClassTypeToImport(c))
          case ta: ScTypeAlias =>
            if (ta.containingClass != null && ScalaPsiUtil.hasStablePath(ta)) {
              bindToType(TypeAliasToImport(ta))
            } else {
              //todo: nothing to do yet, probably in future it would be great to implement something context-specific
              this
            }
          case binding: ScBindingPattern =>
            binding.nameContext match {
              case member: ScMember =>
                val containingClass = member.containingClass
                val refToClass = bindToElement(containingClass)
                val refToMember = createReferenceFromText(refToClass.getText + "." + binding.name)
                this.replace(refToMember).asInstanceOf[ScReferenceElement]
            }
          case fun: ScFunction if Seq("unapply", "unapplySeq").contains(fun.name) && ScalaPsiUtil.hasStablePath(fun) =>
            bindToElement(fun.containingClass)
          case fun: ScFunction if fun.isConstructor =>
            bindToElement(fun.containingClass)
          case m: PsiMethod if m.isConstructor =>
            bindToElement(m.getContainingClass)
          case pckg: PsiPackage => bindToPackage(pckg)
          case _ => throw new IncorrectOperationException(s"Cannot bind to $element")
        }
      }
    }
  }

  private def reportWrongKind(c: TypeToImport, suitableKinds: Set[ResolveTargets.Value]): Nothing = {
    val contextText = if (getContext != null)
      if (getContext.getContext != null)
        if (getContext.getContext.getContext != null)
          getContext.getContext.getContext.getText
        else getContext.getContext.getText
      else getContext.getText
    else getText
    throw new IncorrectOperationException(
      s"""${c.element} does not match expected kind,
         |kinds: ${suitableKinds.mkString(", ")}
         |problem place: $refName in
         |$contextText""".stripMargin)
  }

  def getSameNameVariants: Array[ResolveResult] = doResolve(new CompletionProcessor(getKinds(incomplete = true), this) {

    override protected val forName = Some(refName)
  })

  override def delete() {
    getContext match {
      case sel: ScImportSelector => sel.deleteSelector()
      case expr: ScImportExpr => expr.deleteExpr()
      case _ => super.delete()
    }
  }

  @CachedWithRecursionGuard(this, Array.empty, ModCount.getBlockModificationCount)
  override def multiResolve(incomplete: Boolean): Array[ResolveResult] = {
    val resolver = new StableCodeReferenceElementResolver(ScStableCodeReferenceElementImpl.this, false, false, false)
    resolver.resolve(ScStableCodeReferenceElementImpl.this, incomplete)
  }

  protected def processQualifier(processor: BaseProcessor): Unit = {
    _qualifier() match {
      case None =>
        @scala.annotation.tailrec
        def treeWalkUp(place: PsiElement, lastParent: PsiElement) {
          ProgressManager.checkCanceled()
          place match {
            case null =>
            case p: ScTypeElement if p.analog.isDefined =>
              // this allows the type elements in a context or view bound to be path-dependent types, based on parameters.
              // See ScalaPsiUtil.syntheticParamClause and StableCodeReferenceElementResolver#computeEffectiveParameterClauses
              treeWalkUp(p.analog.get, lastParent)
                // annotation should not walk through it's own annotee while resolving
            case p: ScAnnotationsHolder
              if processor.kinds.contains(ResolveTargets.ANNOTATION) && PsiTreeUtil.isContextAncestor(p, this, true) =>
                treeWalkUp(place.getContext, place)
            case p =>
              if (!p.processDeclarations(processor, ResolveState.initial, lastParent, this)) return
              place match {
                case (_: ScTemplateBody | _: ScExtendsBlock) => // template body and inherited members are at the same level.
                case _ => if (!processor.changedLevel) return
              }
              treeWalkUp(place.getContext, place)
          }
        }

        treeWalkUp(this, null)
      case Some(p: ScInterpolationPattern) =>
        val expr =
          ScalaPsiElementFactory.createExpressionWithContextFromText(s"""_root_.scala.StringContext("").$refName""", p, this)
        expr match {
          case ref: ScReferenceExpression =>
            ref.doResolve(processor)
          case _ =>
        }
      case Some(q: ScDocResolvableCodeReference) =>
        q.multiResolve(/*incomplete = */ true).foreach((res: ResolveResult) => processQualifierResolveResult(res, processor))
      case Some(q: ScStableCodeReferenceElement) =>
        q.bind() match {
          case Some(res) => processQualifierResolveResult(res, processor)
          case _ =>
        }
      case Some(thisQ: ScThisReference) => for (ttype <- thisQ.`type`()) processor.processType(ttype, this)
      case Some(superQ: ScSuperReference) => ResolveUtils.processSuperReference(superQ, processor, this)
      case Some(qual) => assert(assertion = false, s"Weird qualifier: ${qual.getClass}")
    }
  }

  protected def processQualifierResolveResult(res: ResolveResult, processor: BaseProcessor): Unit = {
    res match {
      case r@ScalaResolveResult(td: ScTypeDefinition, substitutor) =>
        td match {
          case obj: ScObject =>
            val fromType = r.fromType match {
              case Some(fType) => Right(ScProjectionType(fType, obj, superReference = false))
              case _ => td.`type`().map(substitutor.subst)
            }
            val state = ResolveState.initial.put(ScSubstitutor.key, substitutor)

            fromType match {
              case Right(value) =>
                processor.processType(value, this, state.put(BaseProcessor.FROM_TYPE_KEY, value))
              case _ =>
                td.processDeclarations(processor, state, null, this)
            }
          case _: ScClass | _: ScTrait =>
            td.processDeclarations(processor, ResolveState.initial.put(ScSubstitutor.key, substitutor), null, this)
        }
      case ScalaResolveResult(typed: ScTypedDefinition, s) =>
        val fromType = s.subst(typed.`type`().getOrElse(return))
        processor.processType(fromType, this, ResolveState.initial().put(BaseProcessor.FROM_TYPE_KEY, fromType))
        processor match {
          case _: ExtractorResolveProcessor =>
            if (processor.candidatesS.isEmpty) {
              //check implicit conversions
              val expr =
                ScalaPsiElementFactory.createExpressionWithContextFromText(getText, getContext, this)
              //todo: this is really hacky solution... Probably can be joint somehow with interpolated pattern.
              expr match {
                case ref: ScReferenceExpression =>
                  ref.doResolve(processor)
                case _ =>
              }
            }
          case _ => //do nothing
        }
      case ScalaResolveResult(field: PsiField, s) =>
        processor.processType(s.subst(field.getType.toScType()), this)
      case ScalaResolveResult(clazz: PsiClass, _) =>
        processor.processType(new ScDesignatorType(clazz, true), this) //static Java import
      case ScalaResolveResult(pack: ScPackage, s) =>
        pack.processDeclarations(processor, ResolveState.initial.put(ScSubstitutor.key, s),
          null, this)
      case other: ScalaResolveResult =>
        other.element.processDeclarations(processor, ResolveState.initial.put(ScSubstitutor.key, other.substitutor),
          null, this)
      case _ =>
    }
  }

  private def _qualifier() = {
    getContext match {
      case p: ScInterpolationPattern => Some(p)
      case sel: ScImportSelector =>
        sel.getContext /*ScImportSelectors*/ .getContext.asInstanceOf[ScImportExpr].reference
      case _ => pathQualifier
    }
  }

  def doResolve(processor: BaseProcessor, accessibilityCheck: Boolean = true): Array[ResolveResult] = {
    def candidatesFilter(result: ScalaResolveResult) = {
      result.element match {
        case c: PsiClass if c.name == c.qualifiedName => c.getContainingFile match {
          case _: ScalaFile => true // scala classes are available from default package
          /** in completion in [[ScalaFile]] [[JavaDummyHolder]] usually used as file */
          case dummyHolder: JavaDummyHolder
            if Option(dummyHolder.getContext).map(_.getContainingFile).exists(_.isInstanceOf[ScalaFile]) =>
            true
          // Other classes from default package are available only for top-level Scala statements
          case _ => PsiTreeUtil.getContextOfType(this, true, classOf[ScPackaging]) == null
        }
        case _ => true
      }
    }

    getContainingFile match {
      case ammoniteScript: ScalaFile if AmmoniteUtil.isAmmoniteFile(ammoniteScript) =>
        def psi2result(psiElement: PsiNamedElement): Array[ResolveResult] = Array(new ScalaResolveResult(psiElement))

        val fsi = AmmoniteUtil.scriptResolveQualifier(this)

        (fsi, fsi.flatMap(AmmoniteUtil.file2Object)) match {
          case (_, Some(obj)) =>
            return psi2result(obj)
          case (Some(dir), _) =>
            return psi2result(dir)
          case _ =>
            AmmoniteUtil.scriptResolveSbtDependency(this) match {
              case Some(dir) => return psi2result(dir)
              case _ =>
            }
        }
      case _ =>
    }

    val importStmt = PsiTreeUtil.getContextOfType(this, true, classOf[ScImportStmt])

    if (importStmt != null) {
      val importHolder = PsiTreeUtil.getContextOfType(importStmt, true, classOf[ScImportsHolder])
      if (importHolder != null) {
        val importExprs = importHolder.getImportStatements
          .takeWhile(_ != importStmt)
          .flatMap(_.importExprs)
          .filter(_.isSingleWildcard)
          .iterator

        while (importExprs.hasNext) {
          val expr = importExprs.next()
          expr.reference match {
            case Some(reference) => reference.resolve()
            case None => expr.qualifier.resolve()
          }
        }
      }
    }
    if (!accessibilityCheck) processor.doNotCheckAccessibility()
    var x = false
    //performance improvement
    ScalaPsiUtil.fileContext(this) match {
      case s: ScalaFile if s.isCompiled =>
        x = true
        //todo: improve checking for this and super
        val refText: String = getText
        if (!refText.contains("this") && !refText.contains("super") && (
          refText.contains(".") || getContext.isInstanceOf[ScStableCodeReferenceElement]
          )) {
          //so this is full qualified reference => findClass, or findPackage
          val facade = JavaPsiFacade.getInstance(getProject)
          val manager = ScalaPsiManager.instance(getProject)
          val classes = manager.getCachedClasses(getResolveScope, refText)
          val pack = facade.findPackage(refText)
          if (pack != null) processor.execute(pack, ResolveState.initial)
          for (clazz <- classes) processor.execute(clazz, ResolveState.initial)
          val candidates = processor.candidatesS
          val filtered = candidates.filter(candidatesFilter)

          if (filtered.nonEmpty) return filtered.toArray
        }

      case _ =>
    }

    processQualifier(processor)

    val candidates = processor.candidatesS
    val filtered = candidates.filter(candidatesFilter)
    if (accessibilityCheck && filtered.isEmpty) return doResolve(processor, accessibilityCheck = false)
    filtered.toArray
  }

}


text:
How to configure login banners in Linux (RedHat, Ubuntu, CentOS, Fedora)
======
Learn how to create login banners in Linux to display different warning or information messages to user who is about to log in or after he logs in.

![Login banners in Linux][1]

Whenever you login to some production systems of firm, you get to see some login messages, warnings or info about server you are about to login or already logged in like below. Those are the login banners.

![Login welcome messages in Linux][2]

In this article we will walk you through how to configure them.

There are two types of banners you can configure.

  1. Banner message to display before user log in (configure in file of your choice eg. `/etc/login.warn`)
  2. Banner message to display after user successfully logged in (configure in `/etc/motd`)

### How to display message when user connects to system before login

This message will be displayed to user when he connects to server and before he logged in. Means when he enter the username, this message will be displayed before password prompt.

You can use any filename and enter your message within. Here we used `/etc/login.warn` file and put our messages inside.

```
# cat /etc/login.warn
        !!!! Welcome to KernelTalks test server !!!!
This server is meant for testing Linux commands and tools. If you are
not associated with kerneltalks.com and not authorized please dis-connect
immediately.
```

Now, you need to supply this file and path to `sshd` daemon so that it can fetch this banner for each user login request. For that open `/etc/sshd/sshd_config` file and search for line `#Banner none`

Here you have to edit file and write your filename and remove hash mark. It should look like : `Banner /etc/login.warn`

Save file and restart `sshd` daemon. To avoid disconnecting existing connected users, use HUP signal to restart sshd.

```
oot@kerneltalks # ps -ef |grep -i sshd
root     14255     1  0 18:42 ?        00:00:00 /usr/sbin/sshd -D
root     19074 14255  0 18:46 ?        00:00:00 sshd: ec2-user [priv]
root     19177 19127  0 18:54 pts/0    00:00:00 grep -i sshd

root@kerneltalks # kill -HUP 14255
```

Thats it! Open new session and try login. You will be greeted with the message you configured in above steps .

![Login banner in Linux][3]

You can see message is displayed before user enter his password and log in to system.

### How to display message after user logs in

Message user sees after he logs into system successfully is **M** essage **O** f **T** he **D** ay & is controlled by `/etc/motd` file. Edit this file and enter message you want to greet user with once he successfully logged in.

```
root@kerneltalks # cat /etc/motd
           W E L C O M E
Welcome to the testing environment of kerneltalks.
Feel free to use this system for testing your Linux
skills. In case of any issues reach out to admin at
info@kerneltalks.com. Thank you.

```

You dont need to restart `sshd` daemon to take this change effect. As soon as you save the file, its content will be read and displayed by sshd daemon from very next login request it serves.

![motd in linux][4]

You can see in above screenshot : Yellow box is MOTD controlled by `/etc/motd` and green box is what we saw earlier login banner.

You can use tools like [cowsay][5], [banner][6], [figlet][7], [lolcat ][8]to create fancy, eye-catching messages to display at login. This method works on almost all Linux distros like RedHat, CentOs, Ubuntu, Fedora etc.

--------------------------------------------------------------------------------

via: https://kerneltalks.com/tips-tricks/how-to-configure-login-banners-in-linux/

作者:[kerneltalks][a]
译者:[译者ID](https://github.com/译者ID)
校对:[校对者ID](https://github.com/校对者ID)

本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出

[a]:https://kerneltalks.com
[1]:https://c3.kerneltalks.com/wp-content/uploads/2017/11/login-banner-message-in-linux.png
[2]:https://c3.kerneltalks.com/wp-content/uploads/2017/11/Login-message-in-linux.png
[3]:https://c1.kerneltalks.com/wp-content/uploads/2017/11/login-banner.png
[4]:https://c3.kerneltalks.com/wp-content/uploads/2017/11/motd-message-in-linux.png
[5]:https://kerneltalks.com/tips-tricks/cowsay-fun-in-linux-terminal/
[6]:https://kerneltalks.com/howto/create-nice-text-banner-hpux/
[7]:https://kerneltalks.com/tips-tricks/create-beautiful-ascii-text-banners-linux/
[8]:https://kerneltalks.com/linux/lolcat-tool-to-rainbow-color-linux-terminal/

redpajama_set_name: RedPajamaGithub


text:
package IFTest::TestModule;

use strict;
use base qw(
    Test::Class
);

use Test::More;
use IFTest::Application;
use IF::Log;
use IF::Application::Module;
use IF::Web::ActionLocator;

use Data::Dumper;

sub setUp : Test(startup => 2) {
    my ($self) = @_;
    my $app = IFTest::Application->application();
    ok($app, "Application instantiated correctly");
    $self->{app} = $app;

    # check modules
    my $modules = $app->modules();
    ok(scalar @$modules == 2, "Has two modules");
}

sub test_locating_modules : Test(3) {
    my ($self) = @_;

    my $twang = $self->{app}->moduleWithName("IFTest::Module::Twang");
    ok($twang, "Found twang");
    my $bong = $self->{app}->moduleWithName("IFTest::Module::Bong");
    ok($bong, "Found bong");
    my $foo = $self->{app}->moduleWithName("IFTest::Module::Foo");
    ok(!$foo, "No foo found");
}

sub test_basic_url_generation : Test(13) {
    my ($self) = @_;

    my $URL1 = "/IFTest/root/en/Home/default";
    my $URL1r = "/ift/h";

    my $al = IF::Web::ActionLocator->newFromString($URL1);
    ok($al, "Constructed a web action locator");

    ok($al->urlRoot() eq "IFTest", "URL Root parsed correctly");
    ok($al->siteClassifierName() eq "root", "Site classifier name parsed correctly");
    ok($al->language() eq "en", "Language parsed correctly");
    ok($al->targetComponentName() eq "Home", "component parsed correctly");
    ok($al->directAction() eq "default", "Action parsed correctly");

    my $twang = $self->{app}->moduleWithName("IFTest::Module::Twang");
    my $ru = $twang->urlFromActionLocatorAndQueryDictionary($al, {});
    ok($ru eq $URL1r, "Rewrote url as $URL1r");

    # now try more complex one

    my $URL2 = "/IFTest/banana/ni/Zibzab/view";
    my $URL2r = "/ift/ni/banana/he-man";

    my $al = IF::Web::ActionLocator->newFromString($URL2);

    ok($al->urlRoot() eq "IFTest", "URL Root parsed correctly");
    ok($al->siteClassifierName() eq "banana", "Site classifier name parsed correctly");
    ok($al->language() eq "ni", "Language parsed correctly");
    ok($al->targetComponentName() eq "Zibzab", "component parsed correctly");
    ok($al->directAction() eq "view", "Action parsed correctly");

    my $bong = $self->{app}->moduleWithName("IFTest::Module::Bong");
    my $ru = $bong->urlFromActionLocatorAndQueryDictionary($al, { "questor" => "he-man" });
    ok($ru = $URL2r, "Rewrote url as $ru");
}

sub test_basic_url_parsing : Test(5) {
    my ($self) = @_;
    my $twang = $self->{app}->moduleWithName("IFTest::Module::Twang");
    my $bong  = $self->{app}->moduleWithName("IFTest::Module::Bong");

    my $URL1 = "/ift/h";
    my $URL2 = "/ift/ni/banana/he-man";

    my ($url, $qs) = $twang->urlFromIncomingUrl($URL1);
    ok($url eq "/IFTest/root/en/Home/default", "Parsed incoming $URL1");
    diag $url;
    ok(!$qs, "No qd found");

    my ($url, $qs) = $twang->urlFromIncomingUrl($URL2);
    ok($url eq $URL2, "Couldn't parse");
    my ($url, $qs) = $bong->urlFromIncomingUrl($URL2);
    ok($url eq "/IFTest/banana/ni/Zibzab/view", "Parsed $URL2");
    diag($url);
    ok($qs eq "questor=he-man", "Generated qs correctly");
}

1;


text:
var SwaggerClient = require("swagger-client");
var _ = require('lodash');
var BitMEXAPIKeyAuthorization = require('./lib/BitMEXAPIKeyAuthorization');
var config = require('./config.js');

function getBalance(cb){
  new SwaggerClient({
    url: 'https://www.bitmex.com/api/explorer/swagger.json',
    usePromise: true
  })
  .then(function(client) {
    client.clientAuthorizations.add(
      "apiKey",
      new BitMEXAPIKeyAuthorization(
        config.bitmexApiKey,
        config.bitmexApiSecret
      )
    );

    client.User.User_getMargin()
    .then(function(response){
      var margin = JSON.parse(response.data.toString());
      cb(margin);
    })
    .catch(function(e) {
      console.log('Error:', e);
      cb(0);
    });
  })
  .catch(function(e) {
    console.error("Unable to connect:", e);
    cb(0);
  })
}

exports.GetBalance = getBalance;


text:
module Furnace::AVM2::ABC
  class FunctionReturnOpcode < Opcode
  end
 end


text:
- [ ] Matriz de Controle de Acesso

- [ ] Integridade
  - [ ] A prova de falsidade

- [ ] Confidencialidade
  - [ ] Segredo / Sigilo / AES

- [ ] Autenticação
  - [ ] Hash + Salt


text:
<!DOCTYPE html>

  <title>Register</title>

Register

<form>

    First Name:
    <input type="text" id="firstName" name="firstName" required placeholder="John">
    Last Name:
    <input type="text" id="lastName" name="lastName" required placeholder="Doe">

    Male
    <input type="radio" name="gender" id="male" value="Male">
    Female
    <input type="radio" name="gender" id="female" value="Female">
    Other
    <input type="radio" name="gender" id="other" value="Other">

    Email:
    <input type="email" name="email" id="email" required placeholder="your email">
    Password:
    <input type="password" name="password" id="password" pattern=".{5,10}" title="Password requres between 5 and 10 characters" required placeholder="your password">

    Birthday:
      <select name="birthMonth">
        <option value="">Month</option>
        <option value="1">Jan</option>
        <option value="2">Feb</option>
        <option value="3">Mar</option>
        <option value="4">Apr</option>
      </select>
        <select name="birthDay">
        <option value="">Day</option>
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
      </select>
        <select name="birthYear">
        <option value="">Year</option>
        <option value="1968">1968</option>
        <option value="1969">1969</option>
        <option value="1970">1970</option>
        <option value="1971">1971</option>
      </select>

    I agree to the terms and conditions
    <input type="checkbox" name="agree" id="agree">

  <input type="submit">
</form>


text:
#include "startsettingdialog.h"
#include <QFileDialog>
#include "ui_startsettingdialog.h"

StartSettingDialog::StartSettingDialog(QWidget *parent) :
  QDialog(parent),
  ui(new Ui::StartSettingDialog)
{
  ui->setupUi(this);
}

StartSettingDialog::~StartSettingDialog()
{
  delete ui;
}

QString StartSettingDialog::getWorkDir()
{
  return ui->workDirLineEdit->text();
}

void StartSettingDialog::setWorkDir(const QString &dir)
{
  ui->workDirLineEdit->setText(dir);
}

void StartSettingDialog::on_pushButton_clicked()
{
  QString fileName = QFileDialog::getExistingDirectory(this, tr("Autosave"),
        ".", QFileDialog::ShowDirsOnly/* | QFileDialog::DontUseNativeDialog*/);
  if (!fileName.isEmpty()) {
    setWorkDir(fileName);
  }
}


text:
package com.smooth.typt.org.entity;

import com.smooth.typt.common.entity.BaseEntity;

import javax.persistence.*;

/**
 * 项目名称:typt
 * 模块名称:com.smooth.typt.org.entity
 * 功能描述:
 * 创建人:倪少君
 * 创建时间:2017/4/6
 * 修改人:
 * 修改时间:
 *
 * @版本:V
 */
@Entity
@Table(name = "org_org")
public class Org extends BaseEntity {
    private static final long serialVersionUID = 1355436566033216395L;
    private Integer orgId;
    private String orgName;
    private String orgType;
    private String orgCode;
    private Integer orgPid;
    private String city;
    private String province;
    private Integer state;

    @Id
    @Column(name = "org_id", nullable = false, insertable = true, updatable = true)
    public Integer getOrgId() {
        return orgId;
    }

    public void setOrgId(Integer orgId) {
        this.orgId = orgId;
    }

    @Basic
    @Column(name = "org_name", nullable = true, insertable = true, updatable = true, length = 100)
    public String getOrgName() {
        return orgName;
    }

    public void setOrgName(String orgName) {
        this.orgName = orgName;
    }

    @Basic
    @Column(name = "org_type", nullable = true, insertable = true, updatable = true)
    public String getOrgType() {
        return orgType;
    }

    public void setOrgType(String orgType) {
        this.orgType = orgType;
    }

    @Basic
    @Column(name = "org_code", nullable = true, insertable = true, updatable = true)
    public String getOrgCode() {
        return orgCode;
    }

    public void setOrgCode(String orgCode) {
        this.orgCode = orgCode;
    }

    @Basic
    @Column(name = "org_pid", nullable = true, insertable = true, updatable = true)
    public Integer getOrgPid() {
        return orgPid;
    }

    public void setOrgPid(Integer orgPid) {
        this.orgPid = orgPid;
    }

    @Basic
    @Column(name = "city", nullable = true, insertable = true, updatable = true, length = 11)
    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Basic
    @Column(name = "province", nullable = true, insertable = true, updatable = true, length = 11)
    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    @Basic
    @Column(name = "state", nullable = true, insertable = true, updatable = true)
    public Integer getState() {
        return state;
    }

    public void setState(Integer state) {
        this.state = state;
    }

}


text:
ActiveRecord::Schema.define(version: 20150710061947) do

  create_table "uploads", force: :cascade do |t|
    t.integer  "uploadable_id"
    t.string   "uploadable_type"
    t.string   "type"
    t.integer  "position"
    t.string   "data_file_name"
    t.string   "data_content_type"
    t.integer  "data_file_size"
    t.datetime "created_at",        null: false
    t.datetime "updated_at",        null: false
  end

  add_index "uploads", ["position"], name: "index_uploads_on_position"
  add_index "uploads", ["type"], name: "index_uploads_on_type"
  add_index "uploads", ["uploadable_id", "uploadable_type"], name: "index_uploads_on_uploadable_id_and_uploadable_type"

end


text:
package org.cactoos.bytes;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicBoolean;
import org.cactoos.Text;
import org.cactoos.io.InputOf;
import org.cactoos.io.Sticky;
import org.cactoos.iterable.Endless;
import org.cactoos.iterable.HeadOf;
import org.cactoos.iterable.IterableOfBytes;
import org.cactoos.iterator.IteratorOfBytes;
import org.cactoos.text.Concatenated;
import org.cactoos.text.Joined;
import org.cactoos.text.TextOf;
import org.hamcrest.core.AllOf;
import org.hamcrest.core.IsEqual;
import org.junit.jupiter.api.Test;
import org.llorllale.cactoos.matchers.Assertion;
import org.llorllale.cactoos.matchers.EndsWith;
import org.llorllale.cactoos.matchers.HasString;
import org.llorllale.cactoos.matchers.IsText;
import org.llorllale.cactoos.matchers.IsTrue;
import org.llorllale.cactoos.matchers.StartsWith;

/**
 * Test case for {@link BytesOf}.
 *
 * @since 0.12
 * @checkstyle JavadocMethodCheck (500 lines)
 */
final class BytesOfTest {

    @Test
    void readsLargeInMemoryContent() throws Exception {
        final int multiplier = 5_000;
        final String body = "1234567890";
        new Assertion<>(
            "must read large content from in-memory Input",
            new BytesOf(
                new InputOf(
                    new Concatenated(
                        new HeadOf<>(
                            multiplier, new Endless<>(new TextOf(body))
                        )
                    )
                )
            ).asBytes().length,
            new IsEqual<>(body.length() * multiplier)
        ).affirm();
    }

    @Test
    @SuppressWarnings("unchecked")
    void readsInputIntoBytes() throws Exception {
        new Assertion<>(
            "must read bytes from Input",
            new TextOf(
                new BytesOf(
                    new InputOf("Hello, друг!")
                )
            ),
            new AllOf<>(
                new StartsWith("Hello, "),
                new EndsWith("друг!")
            )
        ).affirm();
    }

    @Test
    void readsFromReader() throws Exception {
        final String source = "hello, друг!";
        new Assertion<>(
            "must read string through a reader",
            new TextOf(
                new Sticky(
                    new InputOf(
                        new BytesOf(
                            new StringReader(source),
                            StandardCharsets.UTF_8,
                            16 << 10
                        )
                    )
                )
            ),
            new IsText(source)
        ).affirm();
    }

    @Test
    @SuppressWarnings("unchecked")
    void readsInputIntoBytesWithSmallBuffer() throws Exception {
        new Assertion<>(
            "must read bytes from Input with a small reading buffer",
            new TextOf(
                new BytesOf(
                    new InputOf("Hello, товарищ!"),
                    2
                )
            ),
            new AllOf<>(
                new StartsWith("Hello,"),
                new EndsWith("товарищ!")
            )
        ).affirm();
    }

    @Test
    void closesInputStream() throws Exception {
        final AtomicBoolean closed = new AtomicBoolean();
        final InputStream input = new ByteArrayInputStream(
            "how are you?".getBytes()
        );
        new TextOf(
            new InputOf(
                new InputStream() {
                    @Override
                    public int read() throws IOException {
                        return input.read();
                    }

                    @Override
                    public void close() throws IOException {
                        input.close();
                        closed.set(true);
                    }
                }
            ),
            StandardCharsets.UTF_8
        ).asString();
        new Assertion<>(
            "must close InputStream correctly",
            closed.get(),
            new IsTrue()
        ).affirm();
    }

    @Test
    void asBytes() throws Exception {
        final Text text = new TextOf("Hello!");
        new Assertion<>(
            "Can't convert text into bytes",
            new BytesOf(
                new InputOf(text)
            ).asBytes(),
            new IsEqual<>(
                new BytesOf(text.asString()).asBytes()
            )
        ).affirm();
    }

    @Test
    void asBytesFromIterator() throws Exception {
        final Text text = new TextOf("Good bye!");
        new Assertion<>(
            "Can't convert iterator into bytes",
            new BytesOf(
                new IteratorOfBytes(text)
            ).asBytes(),
            new IsEqual<>(
                new BytesOf(text).asBytes()
            )
        ).affirm();
    }

    @Test
    void asBytesFromIterable() throws Exception {
        final Text text = new TextOf("Good bye");
        new Assertion<>(
            "Must convert iterable into bytes",
            new BytesOf(
                new IterableOfBytes(text)
            ).asBytes(),
            new IsEqual<>(new BytesOf(text).asBytes())
        ).affirm();
    }

    @Test
    void printsStackTrace() {
        new Assertion<>(
            "Can't print exception stacktrace",
            new TextOf(
                new BytesOf(
                    new IOException(
                        "It doesn't work at all"
                    )
                )
            ),
            new HasString(
                new Joined(
                    System.lineSeparator(),
                    "java.io.IOException: It doesn't work at all",
                    "\tat org.cactoos.bytes.BytesOfTest"
                )
            )
        ).affirm();
    }

    @Test
    void printsStackTraceFromArray() {
        new Assertion<>(
            "Can't print exception stacktrace from array",
            new TextOf(
                new BytesOf(
                    new IOException("").getStackTrace()
                )
            ),
            new HasString("org.cactoos.bytes.BytesOfTest")
        ).affirm();
    }

}


text:
@interface DBBViewController ()

@end

@implementation DBBViewController
@synthesize clearDocsBtn, navBar, imgView;

//------------------------------------------------------------------------------------------------------------//
//Region: View Lifecycle -------------------------------------------------------------------------------------//
//------------------------------------------------------------------------------------------------------------//
#pragma mark - View Lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.

    //Setup Background Color
    self.view.backgroundColor = [UIColor underPageBackgroundColor];

    //Setup Navigation Bar Image
    [navBar setBackgroundImage:[UIImage imageNamed:@"navBar"] forBarMetrics:UIBarMetricsDefault];

    //Setup Background Image
    if ([[UIScreen mainScreen] bounds].size.height == 568) {
        [imgView setImage:[UIImage imageNamed:@"Background-568h"]];
    } else {
        [imgView setImage:[UIImage imageNamed:@"Background"]];
    }

    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
    clearDocsBtn.hidden = NO;
    [super viewWillAppear:YES];
}

- (void)viewDidUnload {
    [self setClearDocsBtn:nil];
    [self setNavBar:nil];
    [self setImgView:nil];
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)done {
    [self dismissViewControllerAnimated:YES completion:nil];
}

//------------------------------------------------------------------------------------------------------------//
//Region: Dropbox --------------------------------------------------------------------------------------------//
//------------------------------------------------------------------------------------------------------------//
#pragma mark - Dropbox

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"showDropboxBrowser"])
    {
        // Get reference to the destination view controller
        UINavigationController *navigationController = [segue destinationViewController];

        // Pass any objects to the view controller here, like...

        DropboxBrowserViewController *dropboxBrowser = (DropboxBrowserViewController *) navigationController.topViewController;

        #warning create an array of allowed types. (N.B. to allow all file types simply don't set the property)
        dropboxBrowser.allowedFileTypes = @[@"docx", @"pdf"];
        dropboxBrowser.rootViewDelegate = self;

    }}

- (IBAction)browseDropbox:(id)sender {
    [self performSegueWithIdentifier:@"showDropboxBrowser" sender:self];
}

- (void)dropboxBrowser:(DropboxBrowserViewController *)browser downloadedFile:(NSString *)fileName isLocalFileOverwritten:(BOOL)isLocalFileOverwritten{
    NSLog(@"Downloaded %@ overwritten = %d", fileName, isLocalFileOverwritten);
}

- (void)dropboxBrowser:(DropboxBrowserViewController *)browser failedToDownloadFile:(NSString *)fileName {
    NSLog(@"Failed to download %@", fileName);
}

- (void)dropboxBrowser:(DropboxBrowserViewController *)browser fileConflictError:(NSDictionary *)conflict {
    DBMetadata *file = [conflict objectForKey:@"file"];
    NSString *errorMessage = [conflict objectForKey:@"message"];
    NSLog(@"Conflict error with %@\n%@ last modified on %@\nError: %@", file.filename, file.filename, file.lastModifiedDate, errorMessage);
}

- (void)dropboxBrowserDismissed:(DropboxBrowserViewController *)browser {
    //This method is called after Dropbox Browser is dismissed. Do NOT dismiss DropboxBrowser from this method
    //Perform any UI updates here to display any new data from Dropbox Browser
    // ex. Update a UITableView that shows downloaded files or get the name of the most recently selected file:
    //     NSString *fileName = [DropboxBrowserViewController fileName];
}

//------------------------------------------------------------------------------------------------------------//
//Region: Documents ------------------------------------------------------------------------------------------//
//------------------------------------------------------------------------------------------------------------//
#pragma mark - Documents

- (IBAction)clearDocs:(id)sender {
    //Clear all files from the local documents folder. This is helpful for testing purposes
    dispatch_queue_t delete = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(delete, ^{
        //Background Process;
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        NSArray *fileArray = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];

        for (NSString *filename in fileArray)  {
            [fileMgr removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            //Main UI Process
            clearDocsBtn.titleLabel.text = @"Cleared Docs";
            clearDocsBtn.hidden = YES;
        });
    });
}

@end


text:
<?php

namespace Ehann\Tests;

use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\Test;
use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestSuite;
use PHPUnit\Framework\Warning;

class TestTimeListener implements TestListener
{
    public function endTest(Test $test, float $time): void
    {
        $formattedNumber = round($time, 4);
        print "{$test->getName()} took $formattedNumber seconds." . PHP_EOL;
    }

    public function addError(Test $test, \Throwable $t, float $time): void
    {
        // TODO: Implement addError() method.
    }

    public function addWarning(Test $test, Warning $e, float $time): void
    {
        // TODO: Implement addWarning() method.
    }

    public function addFailure(Test $test, AssertionFailedError $e, float $time): void
    {
        // TODO: Implement addFailure() method.
    }

    public function addIncompleteTest(Test $test, \Throwable $t, float $time): void
    {
        // TODO: Implement addIncompleteTest() method.
    }

    public function addRiskyTest(Test $test, \Throwable $t, float $time): void
    {
        // TODO: Implement addRiskyTest() method.
    }

    public function addSkippedTest(Test $test, \Throwable $t, float $time): void
    {
        // TODO: Implement addSkippedTest() method.
    }

    public function startTestSuite(TestSuite $suite): void
    {
        // TODO: Implement startTestSuite() method.
    }

    public function endTestSuite(TestSuite $suite): void
    {
        // TODO: Implement endTestSuite() method.
    }

    public function startTest(Test $test): void
    {
        // TODO: Implement startTest() method.
    }
}


text:
#ifndef _MAGICKCORE_CIPHER_H
#define _MAGICKCORE_CIPHER_H

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

extern MagickExport MagickBooleanType
  DecipherImage(Image *,const char *,ExceptionInfo *),
  EncipherImage(Image *,const char *,ExceptionInfo *),
  PasskeyDecipherImage(Image *,const StringInfo *,ExceptionInfo *),
  PasskeyEncipherImage(Image *,const StringInfo *,ExceptionInfo *);

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif

#endif


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width initial-scale=1" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <title>Zoe Genevieve LeBlanc | Citizen Journalism and Infographics</title>
  <meta name="description" content="Zoe LeBlanc, Digital Historian.">

  <link rel="shortcut icon" href="/assets/img/favicon.ico">

  <link rel="stylesheet" href="/assets/css/main.css">
  <link rel="canonical" href="/blog/citizen-journalism-and-infographics/">

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css">

<link rel="stylesheet" href="/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="/assets/css/academicons.min.css">

        Zoe LeBlanc

      <input type="checkbox" id="nav-trigger" class="nav-trigger" />

            <svg viewBox="0 0 18 15" width="18px" height="15px">
              <path fill="#424242"
                d="M18,1.484c0,0.82-0.665,1.484-1.484,1.484H1.484C0.665,2.969,0,2.304,0,1.484l0,0C0,0.665,0.665,0,1.484,0 h15.031C17.335,0,18,0.665,18,1.484L18,1.484z" />
              <path fill="#424242"
                d="M18,7.516C18,8.335,17.335,9,16.516,9H1.484C0.665,9,0,8.335,0,7.516l0,0c0-0.82,0.665-1.484,1.484-1.484 h15.031C17.335,6.031,18,6.696,18,7.516L18,7.516z" />
              <path fill="#424242"
                d="M18,13.516C18,14.335,17.335,15,16.516,15H1.484C0.665,15,0,14.335,0,13.516l0,0 c0-0.82,0.665-1.484,1.484-1.484h15.031C17.335,12.031,18,12.696,18,13.516L18,13.516z" />
            </svg>

        about

        blog

        projects

        teaching

Citizen Journalism and Infographics

March 18, 2015

This post was one I produced for my VIDL Series "In Pursuit of Digital Pedagogy", which you can read here.

In Pursuit of Digital Pedagogy: A Series on Digital Tools in the Classroom

For this post, I decided to investigate a digitally based methodology that I have often stumbled upon but yet to try - Citizen Journalism. If you are unfamiliar with the term, I would suggest that you do a quick web search just to see the wealth of examples and debates about Citizen Journalism.

What attracted me to this method was the ethos of Citizen Journalism, which emphasizes the use of digital and open source tools to collaborate and be engaged as citizens. To explore this method, I decided to adopt a meta-approach of trying out a potential digital tool that I wanted to use in my classroom as a medium for my post. I explain the methodology of Citizen Journalism in my first infographic so click here to see how this method could work for you.

So what is an infographic?

Don't worry if you've never heard of an infographic, the concept is pretty straight forward. To quote Wikipedia, "Information graphics or infographics are graphic visual representations of information, data or knowledge intended to present complex information quickly and clearly". In my opinion, infographics or infograms are a great method for creating an eye catching visualization of an argument that forces both the 'producer' and 'consumer' to actively consider how information is presented and organized. This method is particularly suited to visualizing data or analyzing visual media.

So why infographics? And how can infographics work in the classroom?

Have you ever had a student challenge your revisions or comments on a paper, calling the changes simply stylistic ones?

Then an infographic is for you!

In all seriousness though, this method is great for challenging students conceptions about the importance of style when presenting an argument both in the written and visual form. Often academics scoff at concerns of aesthetics or design, and students tend to treat these issues as somehow less serious ones. Yet, how we present our information is directly tied to our ability to communicate effectively. Furthermore, infographics seem deceptively easy at first glance, but require a whole set of digital and critical skills, which really embodies the goals of digital learning.

Using Infographics in the Classroom

Instead of assigning a writing assignment, why not try an infographic?

Most humanities classes usually assign a smaller, low stakes writing assignment in the first few weeks of a course to get students thinking about larger paper topics and exposed to academic writing conventions. While, I'm still a proponent of writing assignments, I believe using an infographic can further the overall goal of these assignments.

So instead of a first writing assignment have your students build an infographic about whatever issue or problem relates to your course. Be sure to walk through with students on how to use an infographic and the principles of good design. If you google for design tips for infographics you'll find lots of hits, and I personally found the subreddit Infographics helpful.

Next step, have your students post their infographic to the course website or virtual collaborative space, and either in class or digitally have your students comment and offer suggestions on the infographics. Revising an infographic seems more low-stakes than revising an entire essay, but the results can be just as worthwhile.

With the revised infographics, now have the students translate the infographic to a written version in either a blog post or an essay.

Seems easy? Let me assure you, after creating my own infographics this assignment will be both a challenge and eye-opening for your students. In limiting the amount of text, students will be forced to distill their arguments and make sure that their evidence actually furthers their thesis. Furthermore, deciding what to visualize and how is an additional challenge and really forces the creator to think about the shape of an argument.

So what tools should you use and how difficult are infographics to learn?

Before starting this project, I had always wanted to try out making my own infographic but had zero previous experience. [Full disclosure, I wish I had spent more time on thinking and reading about design prior to making my infographics.] If like me you're a neophyte when it comes to design, this assignment may be a great opportunity to either bring in an outside expert from campus or the public to talk about design prior to staring the assignment.

In terms of tools, I tried out two free tools: Infogr.am and Piktochart. Both tools are user friendly and allow for a diverse range of multimedia in the infographic. For this project, I decided to use Piktochart because of the wider ability to embed media. However, if I wanted to visualize any graphs I probably would have chosen Infogram.

Piktochart was really easy to use and allowed me to move around images, pictures, and embed videos from Youtube and Vimeo. I particularly enjoyed the easy of uploading images and the fairly wide range of graphics already available on the site. I started my infographics from scratch but there are numerous templates to choose from for free. Finally, Piktochart allows continuous web publishing, has a slideshow capability, and looks really clean and powerful when finished. One difficulty was embedding piktochart onto my Wordpress blog, which initially didn't work great. Luckily, there is a free github Wordpress shortcode for Piktochart that you can easily upload into your plugins and works seemlessly with Piktochart.

Overall Assessment of Piktochart

Allows for Creative Content Creation: A
Ease of Use: A
Open Source: A+
Ease to Publish or Share: B (because of issues in embedding Piktochart on wordpress, though its not impossible)
Ease of Assessing Learning: A
Ability to Integrate into Curriculum: A

Recommendation: Great tool with a low barrier to use and high potential for innovative learning.

Final Thoughts

In the end, what I actually created was not really what I set out to originally, and I'm not sure the final product is really in line with a traditional infographic. Instead, I feel like I unintentionally built more of a multi-media essay about Citizen Journalism. This unintentional final product really embodies for me both the concerns and benefits of digital tools - the possibility of creating unexpected results. I'll go into more about multi-media or transmedia essays in my next post, but take a look at how I organized and presented information. You can judge whether the end result was a success, but overall the experience was certainly informative on a number of levels.

Want more information?

Check out The Vanderbilt CFT's great guide on Visualization and Teaching, which has a section on infographics that you can look at here. On HASTAC, Lorna Gonzalez has a post about using infographics in the High School classroom, and provides a lot of detailed analysis on initial setup, working through the assignment, and assessment.

Have you tried using infographics in your classroom? If you haven't what are the concerns that keep you from trying? If you have, any tips or suggestions? I would love to hear about your experiences so please comment or tweet me

Now to visualize ALL the things.

Zoe

    © Copyright 2021 Zoe Genevieve LeBlanc 😄 🍁 ☕.
    Powered by Jekyll with al-folio theme. Hosted by GitHub Pages.

        Last updated:


text:
package org.thymeleaf.templatemode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.TemplateEngine;

/**
 *
 * @author Daniel Fernández
 *
 * @since 3.0.0
 *
 */
public enum TemplateMode {

    HTML(true, false, false), XML(false, true, false),
    TEXT(false, false, true), JAVASCRIPT(false, false, true), CSS(false, false, true),
    RAW(false, false, false);

    private static Logger logger = LoggerFactory.getLogger(TemplateMode.class);

    private final boolean html;
    private final boolean xml;
    private final boolean text;
    private final boolean caseSensitive;

    TemplateMode(final boolean html, final boolean xml, final boolean text) {
        this.html = html;
        this.xml = xml;
        this.text = text;
        this.caseSensitive = !this.html;
    }

    public boolean isMarkup() {
        return this.html || this.xml;
    }

    public boolean isText() {
        return this.text;
    }

    public boolean isCaseSensitive() {
        return this.caseSensitive;
    }

    public static TemplateMode parse(final String mode) {
        if (mode == null || mode.trim().length() == 0) {
            throw new IllegalArgumentException("Template mode cannot be null or empty");
        }
        if ("HTML".equalsIgnoreCase(mode)) {
            return HTML;
        }
        if ("XML".equalsIgnoreCase(mode)) {
            return XML;
        }
        if ("TEXT".equalsIgnoreCase(mode)) {
            return TEXT;
        }
        if ("JAVASCRIPT".equalsIgnoreCase(mode)) {
            return JAVASCRIPT;
        }
        if ("CSS".equalsIgnoreCase(mode)) {
            return CSS;
        }
        if ("RAW".equalsIgnoreCase(mode)) {
            return RAW;
        }
        logger.warn(
                "[THYMELEAF][{}] Unknown Template Mode '{}'. Must be one of: 'HTML', 'XML', 'TEXT', 'JAVASCRIPT', 'CSS', 'RAW'. " +
                "Using default Template Mode '{}'.",
                new Object[]{TemplateEngine.threadIndex(), mode, HTML});
        return HTML;
    }

}


text:
(function (t) {
// it
t.add("An authentication exception occurred.", "Si \u00e8 verificato un errore di autenticazione.", "security", "it");
t.add("Authentication credentials could not be found.", "Impossibile trovare le credenziali di autenticazione.", "security", "it");
t.add("Authentication request could not be processed due to a system problem.", "La richiesta di autenticazione non pu\u00f2 essere processata a causa di un errore di sistema.", "security", "it");
t.add("Invalid credentials.", "Credenziali non valide.", "security", "it");
t.add("Cookie has already been used by someone else.", "Il cookie \u00e8 gi\u00e0 stato usato da qualcun altro.", "security", "it");
t.add("Not privileged to request the resource.", "Non hai i privilegi per richiedere questa risorsa.", "security", "it");
t.add("Invalid CSRF token.", "CSRF token non valido.", "security", "it");
t.add("Digest nonce has expired.", "Il numero di autenticazione \u00e8 scaduto.", "security", "it");
t.add("No authentication provider found to support the authentication token.", "Non \u00e8 stato trovato un valido fornitore di autenticazione per supportare il token.", "security", "it");
t.add("No session available, it either timed out or cookies are not enabled.", "Nessuna sessione disponibile, pu\u00f2 essere scaduta o i cookie non sono abilitati.", "security", "it");
t.add("No token could be found.", "Nessun token trovato.", "security", "it");
t.add("Username could not be found.", "Username non trovato.", "security", "it");
t.add("Account has expired.", "Account scaduto.", "security", "it");
t.add("Credentials have expired.", "Credenziali scadute.", "security", "it");
t.add("Account is disabled.", "L'account \u00e8 disabilitato.", "security", "it");
t.add("Account is locked.", "L'account \u00e8 bloccato.", "security", "it");
})(Translator);


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Welcome and thank you! on Useless Machines! (VMMF-2017)</title>
    <link>https://vanhugo.github.io/useless/welcome/</link>
    <description>Recent content in Welcome and thank you! on Useless Machines! (VMMF-2017)</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <lastBuildDate>Mon, 05 Jun 2017 15:21:23 -0700</lastBuildDate>

	<atom:link href="https://vanhugo.github.io/useless/welcome/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>Kit Contents</title>
      <link>https://vanhugo.github.io/useless/welcome/kit-contents/</link>
      <pubDate>Mon, 05 Jun 2017 15:24:36 -0700</pubDate>

      <guid>https://vanhugo.github.io/useless/welcome/kit-contents/</guid>
      <description>The first thing you should do is unpack and organize the bag of wooden parts.    Notice that there is a burned side and a clean side to each part. You can choose what side you want to be the outside of the box.    Now separate your parts into groups:    Box    Lid    Motor mount    Battery holder holder    Hinges     Now it is time to assemble these parts.</description>
    </item>

  </channel>
</rss>


text:
namespace user_education {

ScopedNewBadgeTrackerBase::ScopedNewBadgeTrackerBase(
    feature_engagement::Tracker* tracker)
    : tracker_(tracker) {}

// TODO(crbug.com/1258216): When we have the ability to do concurrent FE promos,
// dismiss all of the badge promos here instead of in TryShowNewBadge().
ScopedNewBadgeTrackerBase::~ScopedNewBadgeTrackerBase() = default;

bool ScopedNewBadgeTrackerBase::TryShowNewBadge(
    const base::Feature& badge_feature,
    const base::Feature* promoted_feature) {
  // In the event of a submenu that the user could open multiple times while
  // navigating the same top-level menu, and we don't want to count those as
  // separate times the user sees the New Badge:
  if (base::Contains(active_badge_features_, &badge_feature))
    return true;

  // If there is no tracker available or the feature being promoted is disabled,
  // do not show the New Badge.
  if (!tracker_)
    return false;
  if (promoted_feature && !base::FeatureList::IsEnabled(*promoted_feature))
    return false;

  const bool result = tracker_->ShouldTriggerHelpUI(badge_feature);
  if (result) {
    active_badge_features_.insert(&badge_feature);
    // TODO(crbug.com/1258216): Immediately dismiss to work around an issue
    // where the FE backend disallows concurrent promos; move the call to
    // Dismiss() to the destructor when concurrency is added.
    //
    // Note that "Dismiss" in this case does not dismiss the UI. It's telling
    // the FE backend that the promo is done so that other promos can run. A
    // badge showing in a menu should not block e.g. other badges from
    // displaying (never mind help bubbles).
    tracker_->Dismissed(badge_feature);
  }
  return result;
}

void ScopedNewBadgeTrackerBase::ActionPerformed(const char* event_name) {
  if (tracker_)
    tracker_->NotifyEvent(event_name);
}

}  // namespace user_education


text:
/*
*/

final int DEF_USER_TURN_SPEED = 1.0;
final int DEF_USER_MOVE_SPEED = 30.0;

class User{
  PVector position;
  PVector direction;

  private float moveSpeed;
  private float turnSpeed;
  private float rot;

  public User(){
    position = new PVector(0, 3, 35);
    direction = new PVector(0, 0, 1);

    turnSpeed = DEF_USER_TURN_SPEED;
    moveSpeed = DEF_USER_MOVE_SPEED;

    rot = 0.0f;
  }

  public void setPosition(PVector pos){
    position = pos;
  }

  public float getFacing(){
    return rot;
  }

  public PVector getPosition(){
    return position;
  }

  public void setDirection(PVector dir){
    direction = direction;
  }

  public PVector getDirection(){
    return direction;
  }

  public void turnLeft(float deltaTime){
    rot += turnSpeed * deltaTime;
	  direction.x = sin(rot);
	  direction.z = cos(rot);
  }

  public void turnRight(float deltaTime){
    rot -= turnSpeed * deltaTime;
	  direction.x = sin(rot);
	  direction.z = cos(rot);
  }

  public void goForward(deltaTime){
    position.x -= direction.x * deltaTime * moveSpeed;
    position.y -= direction.y * deltaTime;
    position.z -= direction.z * deltaTime * moveSpeed;
  }

  public void goBackward(deltaTime){
	  position.x += direction.x * deltaTime * moveSpeed;
	  position.y += direction.y * deltaTime;
	  position.z += direction.z * deltaTime * moveSpeed;
  }

  public void update(float deltaTime){
  }
}


text:
namespace net {

class SendAlgorithmInterface;

namespace test {

class QuicSentPacketManagerPeer {
 public:
  static void SetSendAlgorithm(QuicSentPacketManager* sent_packet_manager,
                               SendAlgorithmInterface* send_algorithm);

  static size_t GetNackCount(
      const QuicSentPacketManager* sent_packet_manager,
      QuicPacketSequenceNumber sequence_number);

  static QuicTime GetSentTime(const QuicSentPacketManager* sent_packet_manager,
                              QuicPacketSequenceNumber sequence_number);

  static QuicTime::Delta rtt(QuicSentPacketManager* sent_packet_manager);

  // Returns true if |sequence_number| is a retransmission of a packet.
  static bool IsRetransmission(QuicSentPacketManager* sent_packet_manager,
                               QuicPacketSequenceNumber sequence_number);

  static void MarkForRetransmission(QuicSentPacketManager* sent_packet_manager,
                                    QuicPacketSequenceNumber sequence_number,
                                    TransmissionType transmission_type);

 private:
  DISALLOW_COPY_AND_ASSIGN(QuicSentPacketManagerPeer);
};

}  // namespace test

}  // namespace net

#endif  // NET_QUIC_TEST_TOOLS_QUIC_SENT_PACKET_MANAGER_PEER_H_


text:
package org.springframework.beans.propertyeditors;

import java.beans.PropertyEditorSupport;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

/**
 * Property editor for Collections, converting any source Collection
 * to a given target Collection type.
 *
 *
By default registered for Set, SortedSet and List,
 * to automatically convert any given Collection to one of those
 * target types if the type does not match the target property.
 *
 * @author Juergen Hoeller
 * @since 1.1.3
 * @see java.util.Collection
 * @see java.util.Set
 * @see java.util.SortedSet
 * @see java.util.List
 */
public class CustomCollectionEditor extends PropertyEditorSupport {

	private final Class collectionType;

	private final boolean nullAsEmptyCollection;

	/**
	 * Create a new CustomCollectionEditor for the given target type,
	 * keeping an incoming null as-is.
	 * @param collectionType the target type, which needs to be a
	 * sub-interface of Collection or a concrete Collection class
	 * @see java.util.Collection
	 * @see java.util.ArrayList
	 * @see java.util.TreeSet
	 * @see java.util.LinkedHashSet
	 */
	public CustomCollectionEditor(Class collectionType) {
		this(collectionType, false);
	}

	/**
	 * Create a new CustomCollectionEditor for the given target type.
	 *
If the incoming value is of the given type, it will be used as-is.
	 * If it is a different Collection type or an array, it will be converted
	 * to a default implementation of the given Collection type.
	 * If the value is anything else, a target Collection with that single
	 * value will be created.
	 *
The default Collection implementations are: ArrayList for List,
	 * TreeSet for SortedSet, and LinkedHashSet for Set.
	 * @param collectionType the target type, which needs to be a
	 * sub-interface of Collection or a concrete Collection class
	 * @param nullAsEmptyCollection whether to convert an incoming null
	 * value to an empty Collection (of the appropriate type)
	 * @see java.util.Collection
	 * @see java.util.ArrayList
	 * @see java.util.TreeSet
	 * @see java.util.LinkedHashSet
	 */
	public CustomCollectionEditor(Class collectionType, boolean nullAsEmptyCollection) {
		if (collectionType == null) {
			throw new IllegalArgumentException("Collection type is required");
		}
		if (!Collection.class.isAssignableFrom(collectionType)) {
			throw new IllegalArgumentException(
					"Collection type [" + collectionType.getName() + "] does not implement [java.util.Collection]");
		}
		this.collectionType = collectionType;
		this.nullAsEmptyCollection = nullAsEmptyCollection;
	}

	/**
	 * Convert the given text value to a Collection with a single element.
	 */
	public void setAsText(String text) throws IllegalArgumentException {
		setValue(text);
	}

	/**
	 * Convert the given value to a Collection of the target type.
	 */
	public void setValue(Object value) {
		if (value == null && this.nullAsEmptyCollection) {
			super.setValue(createCollection(this.collectionType, 0));
		}
		else if (value == null || (this.collectionType.isInstance(value) && !alwaysCreateNewCollection())) {
			// Use the source value as-is, as it matches the target type.
			super.setValue(value);
		}
		else if (value instanceof Collection) {
			// Convert Collection elements.
			Collection source = (Collection) value;
			Collection target = createCollection(this.collectionType, source.size());
			for (Iterator it = source.iterator(); it.hasNext();) {
				target.add(convertElement(it.next()));
			}
			super.setValue(target);
		}
		else if (value.getClass().isArray()) {
			// Convert array elements to Collection elements.
			int length = Array.getLength(value);
			Collection target = createCollection(this.collectionType, length);
			for (int i = 0; i < length; i++) {
				target.add(convertElement(Array.get(value, i)));
			}
			super.setValue(target);
		}
		else {
			// A plain value: convert it to a Collection with a single element.
			Collection target = createCollection(this.collectionType, 1);
			target.add(convertElement(value));
			super.setValue(target);
		}
	}

	/**
	 * Create a Collection of the given type, with the given
	 * initial capacity (if supported by the Collection type).
	 * @param collectionType a sub-interface of Collection
	 * @param initialCapacity the initial capacity
	 * @return the new Collection instance
	 */
	protected Collection createCollection(Class collectionType, int initialCapacity) {
		if (!collectionType.isInterface()) {
			try {
				return (Collection) collectionType.newInstance();
			}
			catch (Exception ex) {
				throw new IllegalArgumentException(
						"Could not instantiate collection class [" + collectionType.getName() + "]: " + ex.getMessage());
			}
		}
		else if (List.class.equals(collectionType)) {
			return new ArrayList(initialCapacity);
		}
		else if (SortedSet.class.equals(collectionType)) {
			return new TreeSet();
		}
		else {
			return new LinkedHashSet(initialCapacity);
		}
	}

	/**
	 * Return whether to always create a new Collection,
	 * even if the type of the passed-in Collection already matches.
	 *
Default is "false"; can be overridden to enforce creation of a
	 * new Collection, for example to convert elements in any case.
	 * @see #convertElement
	 */
	protected boolean alwaysCreateNewCollection() {
		return false;
	}

	/**
	 * Hook to convert each encountered Collection/array element.
	 * The default implementation simply returns the passed-in element as-is.
	 *
Can be overridden to perform conversion of certain elements,
	 * for example String to Integer if a String array comes in and
	 * should be converted to a Set of Integer objects.
	 *
Only called if actually creating a new Collection!
	 * This is by default not the case if the type of the passed-in Collection
	 * already matches. Override {@link #alwaysCreateNewCollection()} to
	 * enforce creating a new Collection in every case.
	 * @param element the source element
	 * @return the element to be used in the target Collection
	 * @see #alwaysCreateNewCollection()
	 */
	protected Object convertElement(Object element) {
		return element;
	}

	/**
	 * This implementation returns null to indicate that
	 * there is no appropriate text representation.
	 */
	public String getAsText() {
		return null;
	}

}


text:
package org.lightcouch;

import java.io.Closeable;
import java.io.IOException;
import java.net.URLDecoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import org.apache.http.Consts;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.RequestLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

/**
 * Presents a client to CouchDB database server.
 *
This class is the main object to use to gain access to the APIs.
 *
Usage Example:

 *
Create a new client instance:
 *

 * CouchDbClient dbClient = new CouchDbClient();
 *

 *
 *
Start using the API by the client:
 *
 *
Documents CRUD APIs is accessed by the client directly, eg.: {@link CouchDbClientBase#find(Class, String) dbClient.find(Foo.class, "doc-id")}
 *
View APIs {@link View dbClient.view()}
 *
Change Notifications {@link Changes dbClient.changes()}
 *
Replication {@link Replication dbClient.replication()} and {@link Replicator dbClient.replicator()}
 *
DB server {@link CouchDbContext dbClient.context()}
 *
Design documents {@link CouchDbDesign dbClient.design()}
 *
 *
At the end of a client usage; it's useful to call: {@link #shutdown()} to ensure proper release of resources.
 *
 * @see CouchDbClientAndroid
 * @since 0.0.2
 * @author Ahmed Yehia
 *
 */
public class CouchDbClient extends CouchDbClientBase implements Closeable {

	/**
	 * Constructs a new instance of this class, expects a configuration file named
	 * couchdb.properties to be available in your application default classpath.
	 */
	public CouchDbClient() {
		super();
	}

	/**
	 * Constructs a new instance of this class.
	 * @param configFileName The configuration file name.
	 */
	public CouchDbClient(String configFileName) {
		super(new CouchDbConfig(configFileName));
	}

	/**
	 * Constructs a new instance of this class.
	 * @param dbName The database name.
	 * @param createDbIfNotExist To create a new database if it does not already exist.
	 * @param protocol The protocol to use (i.e http or https)
	 * @param host The database host address
	 * @param port The database listening port
	 * @param username The Username credential
	 * @param password The Password credential
	 */
	public CouchDbClient(String dbName, boolean createDbIfNotExist,
			String protocol, String host, int port, String username, String password) {
		super(new CouchDbConfig(new CouchDbProperties(dbName, createDbIfNotExist, protocol, host, port, username, password)));
	}

	/**
	 * Constructs a new instance of this class.
	 * @param properties An object containing configuration properties.
	 * @see CouchDbProperties
	 */
	public CouchDbClient(CouchDbProperties properties) {
		super(new CouchDbConfig(properties));
	}

	/**
	 * @return {@link CloseableHttpClient} instance.
	 */
	@Override
	HttpClient createHttpClient(CouchDbProperties props) {
		try {
			Registry<ConnectionSocketFactory> registry = createRegistry(props);
			PoolingHttpClientConnectionManager ccm = createConnectionManager(props, registry);
			HttpClientBuilder clientBuilder = HttpClients.custom()
					.setConnectionManager(ccm)
					.setDefaultConnectionConfig(ConnectionConfig.custom()
							.setCharset(Consts.UTF_8).build())
					.setDefaultRequestConfig(RequestConfig.custom()
							.setSocketTimeout(props.getSocketTimeout())
							.setConnectTimeout(props.getConnectionTimeout()).build());
			if (props.getProxyHost() != null)
				clientBuilder.setProxy(new HttpHost(props.getProxyHost(), props.getProxyPort()));
			if (props.getUsername() != null) {
				CredentialsProvider credsProvider = new BasicCredentialsProvider();
				credsProvider.setCredentials(new AuthScope(props.getHost(),
						props.getPort()),
						new UsernamePasswordCredentials(props.getUsername(),
								props.getPassword()));
				clientBuilder.setDefaultCredentialsProvider(credsProvider);
				props.clearPassword();
			}
			registerInterceptors(clientBuilder);
			return clientBuilder.build();
		} catch (Exception e) {
			throw new IllegalStateException("Error Creating HTTPClient: ", e);
		}
	}

	@Override
	HttpContext createContext() {
		AuthCache authCache = new BasicAuthCache();
		authCache.put(host, new BasicScheme());
		HttpContext context = new BasicHttpContext();
	    context.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
		return context;
	}

	private PoolingHttpClientConnectionManager createConnectionManager(
			CouchDbProperties props, Registry<ConnectionSocketFactory> registry) {
		PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(registry);
		if (props.getMaxConnections() != 0) {
			ccm.setMaxTotal(props.getMaxConnections());
			ccm.setDefaultMaxPerRoute(props.getMaxConnections());
		}
		return ccm;
	}

	private Registry<ConnectionSocketFactory> createRegistry(CouchDbProperties props) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
		RegistryBuilder<ConnectionSocketFactory> registry = RegistryBuilder
				.<ConnectionSocketFactory> create();

		if("https".equals(props.getProtocol())) {
			SSLContext sslcontext = SSLContexts.custom()
					.loadTrustMaterial(null, new TrustStrategy(){
						public boolean isTrusted(X509Certificate[] chain, String authType)
								throws CertificateException {
							return true;
						}
					}).build();

			return registry.register("https", new SSLConnectionSocketFactory(sslcontext,
					new NoopHostnameVerifier())).build();
		} else {
			return registry.register("http", PlainConnectionSocketFactory.INSTANCE).build();
		}
	}

	/**
	 * Adds request/response interceptors for logging and validation.
	 * @param clientBuilder
	 */
	private void registerInterceptors(HttpClientBuilder clientBuilder) {
		clientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {
			public void process(final HttpRequest request,
					final HttpContext context) throws IOException {
				if (log.isInfoEnabled()) {
					RequestLine req = request.getRequestLine();
					log.info("> " + req.getMethod() + " " + URLDecoder.decode(req.getUri(), "UTF-8"));
				}
			}
		});
		clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
			public void process(final HttpResponse response,
					final HttpContext context) throws IOException {
				if (log.isInfoEnabled()) {
					log.info("< Status: " + response.getStatusLine().getStatusCode());
				}
				validate(response);
			}
		});
	}

	public void shutdown() {
		HttpClientUtils.closeQuietly(this.httpClient);
	}

	@Override
	public void close() throws IOException {
		shutdown();
	}
}


text:
package org.openengsb.core.api.security.model;

/**
 * Baseclass for Permissions used for Access control in OpenEngSB.
 *
 * Permissions can be stored and managed using a {@link org.openengsb.core.api.security.service.UserDataManager}
 * service. In order to save and read permissions again, a permission must be designed as a plain Java Object. All
 * property types must fulfill certain requirements:
 *

 *
a constructor with exactly one argument of type {@link String}

 *
the {@link Object#toString()} must create a string-representation that can be used with that constructor the
 * recreate the object

 *

 *
 * Collections of values are also allowed. However the types of the values underly the same constraints as single
 * values.
 */
public interface Permission {

    /**
     * return a description of what this permission object permits a user to do (filling in what the values of the
     * argument mean).
     *
     * Example: Allows the user to perform the operation "doSomething" on all services of type "example".
     */
    String describe();

}


text:
from __future__ import print_function
import argparse
import os
import shutil
import subprocess
import sys

from lib.util import get_electron_branding, rm_rf

PROJECT_NAME = get_electron_branding()['project_name']
PRODUCT_NAME = get_electron_branding()['product_name']
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

def main():
  args = parse_args()

  source_root = os.path.abspath(args.source_root)
  initial_app_path = os.path.join(source_root, args.build_dir)
  app_path = create_app_copy(initial_app_path)

  if sys.platform == 'darwin':
    electron = os.path.join(app_path, 'Contents', 'MacOS', PRODUCT_NAME)
    ffmpeg_name = 'libffmpeg.dylib'
    ffmpeg_app_path = os.path.join(app_path, 'Contents', 'Frameworks',
                    '{0} Framework.framework'.format(PRODUCT_NAME),
                    'Libraries')
  elif sys.platform == 'win32':
    electron = os.path.join(app_path, '{0}.exe'.format(PROJECT_NAME))
    ffmpeg_app_path = app_path
    ffmpeg_name = 'ffmpeg.dll'
  else:
    electron = os.path.join(app_path, PROJECT_NAME)
    ffmpeg_app_path = app_path
    ffmpeg_name = 'libffmpeg.so'

  # Copy ffmpeg without proprietary codecs into app.
  ffmpeg_lib_path = os.path.join(source_root, args.ffmpeg_path, ffmpeg_name)
  shutil.copy(ffmpeg_lib_path, ffmpeg_app_path)

  returncode = 0
  try:
    test_path = os.path.join(SOURCE_ROOT, 'spec', 'fixtures',
        'no-proprietary-codecs.js')
    env = dict(os.environ)
    env['ELECTRON_ENABLE_STACK_DUMPING'] = 'true'
    # FIXME: Enable after ELECTRON_ENABLE_LOGGING works again
    # env['ELECTRON_ENABLE_LOGGING'] = 'true'
    subprocess.check_call([electron, test_path] + sys.argv[1:], env=env)
  except subprocess.CalledProcessError as e:
    returncode = e.returncode
  except KeyboardInterrupt:
    returncode = 0

  if returncode == 0:
    print('ok Non proprietary ffmpeg does not contain proprietary codes.')
  return returncode

# Create copy of app to install ffmpeg library without proprietary codecs into
def create_app_copy(initial_app_path):
  app_path = os.path.join(os.path.dirname(initial_app_path),
                          os.path.basename(initial_app_path)
                          + '-no-proprietary-codecs')

  if sys.platform == 'darwin':
    app_name = '{0}.app'.format(PRODUCT_NAME)
    initial_app_path = os.path.join(initial_app_path, app_name)
    app_path = os.path.join(app_path, app_name)

  rm_rf(app_path)
  shutil.copytree(initial_app_path, app_path, symlinks=True)
  return app_path

def parse_args():
  parser = argparse.ArgumentParser(description='Test non-proprietary ffmpeg')
  parser.add_argument('-b', '--build-dir',
                      help='Path to an Electron build folder. \
                          Relative to the --source-root.',
                      default=None,
                      required=True)
  parser.add_argument('--source-root',
                      default=SOURCE_ROOT,
                      required=False)
  parser.add_argument('--ffmpeg-path',
                      help='Path to a folder with a ffmpeg lib. \
                          Relative to the --source-root.',
                      default=None,
                      required=True)
  return parser.parse_args()

if __name__ == '__main__':
  sys.exit(main())


text:
class CreateAdminProjects < ActiveRecord::Migration[5.1]
  def self.up
    create_table :admin_projects do |t|
      t.integer :user_id
      t.string :name
      t.string :url
      t.text :description
      t.text :states_and_provinces
      t.integer :maven_jnlp_server_id
      t.integer :maven_jnlp_family_id
      t.string :jnlp_version_str
      t.boolean :snapshot_enabled
      t.boolean :enable_default_users

      t.string :uuid, :limit => 36

      t.timestamps
    end
  end

  def self.down
    drop_table :admin_projects
  end
end


text:
use Getopt::Std;
use JSON;
use LWP::UserAgent;
use Data::Dumper;
use File::Basename;
use strict;
use warnings;

# arguments
# s : samplesheet
# u : url of VariantDB
# a : apikey
# p : project name
# c : custom field string.
# l : lockdown mode: VariantDB is brought down to speed up import.
our %opts = ();
getopts("s:u:a:p:c:hl", \%opts);
print "\nStarting...\n\n";
if (defined($opts{'h'})) {
	&PrintHelp;
}
if (!-f $opts{'s'}) {
	print "ERROR: No Samplesheet provided\n";
	&PrintHelp;
}
if (!defined($opts{'u'}) || $opts{'u'} !~ m/^http/) {
	print "WARNING: No/invalid URL provided for VariantDB. The main server will be used (http://143.169.238.105/variantdb/)\n";
	$opts{'u'} = 'http://143.169.238.105/variantdb/';
}
my $vdb_url = $opts{'u'}."/api";

if (!defined($opts{'a'}) || $opts{'a'} eq '') {
	print "ERROR: No apiKey provided for VariantDB. To get one, register on the website and activate api-access under user details (menu located under the username in the top right corner)\n";
	&PrintHelp;
}
my $apikey = $opts{'a'};

# get basename of samplesheet
my $datadir = dirname($opts{'s'});

# check if connection & api key are ok.
my $ua = LWP::UserAgent->new;
my $url = $vdb_url."/CheckApiKey?apiKey=$apikey";
my $content = $ua->get($url);
my $return = $content->decoded_content;
$return =~ s/"//g;
if ($return ne '1') {
	print "ERROR: Connection failed or apikey is not valid.\n";
	&PrintHelp;
}
print "Connection established!\n";

# construct the api call to create the import folder on the server.
my $call = $vdb_url."/PrepareImportData";#?apiKey=$apikey";
open IN, $opts{'s'} or die("Could not open samplesheet for reading\n");
my $i = 0;
my %form = ("apiKey" => "$apikey");
while (<IN>) {
	chomp;
	my ($n,$g,$v,$b,$s,$f) = split(/\t/,$_);
	$i++;
	$form{"n$i"} = $n;
	$form{"g$i"} = $g;
	$form{"v$i"} = $v;
	$form{"b$i"} = $b;
	$form{"s$i"} = $s;
	$form{"f$i"} = $f;
	#$call .= "&n$i=$n&g$i=$g&v$i=$v&b$i=$b&s$i=$s&f$i=$f";
}
close IN;
# project defined?
if (defined($opts{'p'}) && $opts{'p'} ne '') {
	# add project name if provided.
	#$call .= "&p=".$opts{'p'};
	$form{"p"} = $opts{'p'};
}
# custom fields?
if (defined($opts{'c'})) {
	my %accepted = ('varchar' => 1,'integer'=> 1,'decimal' => 1, 'float' => 1, 'list' => '1');
	my $idx = 0;
	my @items = split(/,/,$opts{'c'});
	foreach my $item (@items) {
		$idx++;
		my ($k,$t) = split(/=/,$item);
		$t = lc($t);
		if (!defined($accepted{$t})) {
			print "WARNING: field type '$t' is not accepted. Setting to generic 'varchar' type\n";
		}
		if ($t eq 'float') {
			print "NOTE : floating point will be considered as a decimal.\n";
			$t = 'decimal';
		}
		#$call .= "&cf_name$idx=$k&cf_type$idx=$t";
		$form{"cf_name$idx"} = $k;
		$form{"cf_type$idx"} = $t;
	}
}
# just add the lockdown, it's ignored for non admin users.
if (defined($opts{'l'})) {
	$form{'l'} = 1;
}

my $nr_samples = $i;
$content = $ua->post($call,\%form);
my $stat = -1;
while ($stat == -1) {
	($stat,$return) = j_decode($content);
	if ($stat == -1) {
		print "no json obtained.\n";
		sleep 5;
		$content = $ua->post($call,\%form);
		next;
	}
}
if (!defined($return->{'status'}) || $return->{'status'} ne 'ok') {
	print "ERROR: Preparation of the import job failed.";
	if (defined($return->{'ERROR'})) {
		print $return->{'ERROR'};
	}
	exit;
}
my $path = $return->{'path'};
# submit the actual import.
$call =  $vdb_url."/ImportData/$path/$nr_samples?apiKey=$apikey";
$stat = -1;
$content = $ua->get($call);
while ($stat == -1) {
	($stat,$return) = j_decode($content);
	if ($stat == -1) {
		print "no json obtained.\n";
		sleep 5;
		$content = $ua->get($call);
		next;
	}
}
if (!defined($return->{'result'}) || $return->{'result'} ne 'Started') {
	print "ERROR: Unable to start the import Job.\n";
	if (defined($return->{'error'})) {
		print $return->{'error'}."\n";
	}
	exit;
}
my $importKey = $return->{'job_key'};
print " => Import started with job key : $importKey\n";
# now wait for the import to finish.
my $finished = '';
while ($finished ne 'Finished') {
	# poll every 30s
	sleep 15;
	my $status_call = $vdb_url."/GetStatus/Import/$importKey?apiKey=$apikey";
	my $stat = -1;
	$content = $ua->get($status_call);
	($stat,$return) = j_decode($content);
	if ($stat == -1) {
		print "no json obtained.\n";
		sleep 5;
		$content = $ua->get($status_call);
		next;
	}
	if (defined($return->{'ERROR'}) ) {
		print $return->{'ERROR'}."\n";
		exit;
	}
	$finished = $return->{'status'};
}

## import finished, store some details.
open OUT, ">$datadir/import.log";
print OUT $return->{'runtime_output'};
close OUT;
open OUT, ">$datadir/ProjectID.txt";
print OUT $return->{'ProjectID'};
close OUT;
my %id_map = ();
open OUT, ">$datadir/ID_MAP.txt";
foreach my $sname (keys(%{$return->{'id_map'}})) {
	$id_map{$sname} = $return->{'id_map'}->{$sname};
	print OUT "$sname=".$id_map{$sname}."\n";
}
close OUT;

sub j_decode {
	my ($c) = @_;
	my $d = $c->decoded_content;
	my $r;
	eval  {
		$r = decode_json($d);
		1;
	}
	or do {
		# temporary failure?
		print "Could not valid catch response from server. response was: ";
		print Dumper($d);
		my @result = (-1,'');
		return @result;
	};
	my @result = (1,$r);
	return @result;

}

sub PrintHelp {
	print "\nHow to use: \n";
	print "perl Import.URL.Data.pl -s samplesheet.txt -u 'http://143.169.238.105/variantdb' -a 'my_api_key' -p project_name -c 'Dels=decimal,MQ0=integer'\n";
	print "\n";
	print "Samplesheet is structured with the following columns, without headers: \n";
	print " - sample_name : an arbitrary name\n";
	print " - gender : undef, male, female\n";
	print " - URL or path on VariantDB server of the VCF file\n";
	print " - URL or path on VariantDB server of the BAM file\n";
	print " - Store the VCF/BAM after import? 0 or 1\n";
	print " - VCF Format : \n";
	print "     - UG : Unified Genotyper\n";
	print "     - HC : HaplotypeCaller\n";
	print "     - MT : MuTect\n";
	print "     - VSC : VarScan Cohort\n";
	print "     - VS : Varscan paired samples\n";
	print "     - 23 : 23andMe array data, converted to genotypes\n";
	print "     - IT : ion-torrent (experimental)\n";
	print "\n";
	print "For UG/HC, cohort VCF files can be loaded using by specifying '%cohort%' as samplename\n";
	print "\n";
	print "The -c argument takes a list of custom info/format fields that must be stored, apart from the default set of annotations. Format is a comma-seperated list of field_name=field_type tuples, where field_type is one of (integer,decimal,varchar,list). Varchar is a variable string up to 255 characters. List is a more performant option to store strings, when the number of different values is limited.\n";
	print "\n";
	print exit;
}


text:
module Evopop
  # Represents the population that is being trained. Has various methods
  # relevant to training.
  #
  #
  # Examples
  #   population = Evopop::Population.new
  #   ... initialize population with parameters ...
  #   population.train
  #   population.crossover
  #   population.mutate
  class Population
    attr_accessor :candidates, :population_size, :max_generations,
                  :crossover_function, :crossover_params, :initial_range_min,
                  :initial_range_max, :mutation_range_min, :mutation_range_max,
                  :mutation_num, :fitness_function, :dna_len, :average_fitness,
                  :fitness_preference

    # Initializes the attributes with default values. This is not guaranteed
    # to reach maxima.
    def initialize
      Evopop.config.instance_variables.each do |iv|
        instance_variable_set(
          iv,
          Evopop.config.instance_variable_get(iv)
        )
      end
      create
      self
    end

    # Creates a new set of population. Should be called after all the
    # parameters have been set to the attributes.
    def create
      @candidates = Array.new(@population_size) do
        dna = Evopop::Dna.new(
          @initial_range_min,
          @initial_range_max,
          @mutation_range_min,
          @mutation_range_max,
          @dna_len
        )
        candidate = Evopop::Candidate.new(dna)
        candidate
      end
    end

    # Determines the fitness of the population and thereafter sorts it
    # based on fitness descdending (high fitness first, low fitness last).
    def train
      average_fitness = 0
      @candidates.each do |c|
        c.fitness = fitness_function.call(c.dna)
        average_fitness += + c.fitness
      end

      average_fitness /= @population_size

      @average_fitness << average_fitness

      @candidates = @candidates.sort_by(&:fitness)
      @candidates = @candidates.reverse if fitness_preference != :minimum
    end

    # Performs simple mechanism of crossover - in this case picks two
    # random candidates in from a top percentile of the population and
    # performs one point crossover, producing new offspring equal to the
    # population size attribute.
    def crossover
      new_generation = []

      # For all the top candidates, take the top 2 and crossover
      (0...@population_size).each do
        children = @crossover_function.call(top_candidates.sample(2), @crossover_params)
        new_generation += children

        if new_generation.length >= population_size
          new_generation = new_generation.take(population_size)
          break
        end
      end

      @candidates = new_generation
    end

    # Performs simple mutation over the next generation. In this case,
    # it either adds or substracts an amount to each dimension given the
    # mutation range attributes.
    def mutate
      mutated_candidates.each do |c|
        c.dna.dna_len_range.each do |i|
          c.dna.mutate(i)
        end
      end
    end

    private

    def top_candidates
      @candidates.take((@population_size * 0.80).to_i)
    end

    def mutated_candidates
      @candidates.sample(@mutation_num)
    end
  end
end


text:
import constants
from resource import ResourceExt
from girder import events
from girder.models.model_base import ValidationException

def validateSettings(event):
    key, val = event.info['key'], event.info['value']

    if key == constants.PluginSettings.PROVENANCE_RESOURCES:
        if val:
            if not isinstance(val, basestring):
                raise ValidationException(
                    'Provenance Resources must be a string.', 'value')
            # accept comma or space separated lists
            resources = val.replace(",", " ").strip().split()
            # reformat to a comma-separated list
            event.info["value"] = ",".join(resources)
        event.preventDefault().stopPropagation()

def load(info):
    events.bind('model.setting.validate', 'provenanceMain', validateSettings)
    ext = ResourceExt(info)
    events.bind('model.setting.save.after', 'provenanceMain', ext.bindModels)
    events.bind('provenance.initialize', 'provenanceMain', ext.bindModels)
    events.trigger('provenance.initialize', info={})
    events.bind('model.file.save', 'provenanceMain', ext.fileSaveHandler)
    events.bind('model.file.save.created', 'provenanceMain',
                ext.fileSaveCreatedHandler)
    events.bind('model.file.remove', 'provenance', ext.fileRemoveHandler)