text:
#include <QStringList>

#include "menuitem.h"
#include "menumodel.h"

MenuItem::MenuItem(Desktop *data, MenuItem *parent)
{
    parentItem = parent;
    itemData = data;
}

MenuItem::~MenuItem()
{
    qDeleteAll(childItems);
}

void MenuItem::setCategoryName(QString name)
{
    if(!itemData)
        categoryName = name;
}

QString MenuItem::getCategoryName()
{
    return categoryName;
}

void MenuItem::setCategoryIcon(QString icon)
{
    if(!itemData)
        categoryIcon = icon;
}

QString MenuItem::getCategoryIcon()
{
    return categoryIcon;
}

void MenuItem::setCategoryGroups(QList<QString> groups)
{
    if(!itemData)
    {
        while(!categoryGroups.isEmpty())
            categoryGroups.removeFirst();
        foreach (QString item, groups)
            categoryGroups << item;
    }
}

QList<QString> MenuItem::getCategoryGroups()
{
    return categoryGroups;
}

bool MenuItem::containsGroup(QString group)
{
    return categoryGroups.contains(group);
}

void MenuItem::appendChild(MenuItem *item)
{
    childItems.append(item);
}

MenuItem *MenuItem::child(int row)
{
    return childItems.value(row);
}

int MenuItem::childCount() const
{
    return childItems.count();
}

int MenuItem::columnCount() const
{
    return 1;
}

QVariant MenuItem::data(int column, int role) const
{
    Q_UNUSED(column);
    if(role == MenuModel::name)
    {
        if(itemData)
            return itemData->title();
        else
            return categoryName;
    }
    else if(role == MenuModel::exec)
    {
        if(itemData)
            return itemData->exec();
        else
            return "";
    }
    else if(role == MenuModel::comment)
    {
        if(itemData)
            return itemData->comment();
        else
            return "";
    }
    else if(role == MenuModel::icon)
    {
        if(itemData)
            return itemData->icon();
        else
            return categoryIcon;
    }
    else if(role == MenuModel::filename)
    {
        if(itemData)
            return itemData->filename();
        else
            return "";
    }
    else if(role == MenuModel::custom)
    {
/*
        if(!itemData->contains(m_customValue))
        {
            qDebug()<<"couldn't find custom field: "<< m_customValue;
        }
        return itemData->value(m_customValue);
 */
    }

    return QVariant();
}

MenuItem *MenuItem::parent()
{
    return parentItem;
}

int MenuItem::row() const
{
    if (parentItem)
        return parentItem->childItems.indexOf(const_cast<MenuItem*>(this));

    return 0;
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('race', '0004_remove_map_map_type'),
    ]

    operations = [
        migrations.AddField(
            model_name='map',
            name='video',
            field=models.URLField(blank=True, default=b''),
        ),
        migrations.AlterField(
            model_name='server',
            name='last_connection_at',
            field=models.DateTimeField(editable=False),
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
personalblog
============

Live Version: www.ericshi.ca

This is my personal djangoblog. I am still learning and will be constantly updating this blog. Please feel free to branch and contribute.

For anyone who would like to set up a local version.

I'm using

Python 2.7

Installation instructions
sudo apt-get install build-essential
sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
cd ~/<folder to tar>/
wget http://python.org/ftp/python/2.7.5/Python-2.7.5.tgz
tar -xvf Python-2.7.5.tgz
cd Python-2.7.5
./configure
make
sudo make install

Install pip
sudo apt-get install python-pip

Install virtualenv
sudo pip install virtualenv

Go to the project root folder and run
sudo pip install virtualenv
To install dependencies.

Please note pg_config for postGRE will fail, I'm using SQLite locally and I have postGRE on my hosting server.

Work in progress.


text:
package net.lightbody.bmp.mitm.trustmanager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.Socket;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import me.moxun.dreamcatcher.misc.X509ExtendedTrustManager;
import io.netty.util.internal.EmptyArrays;

/**
 * An {@link X509ExtendedTrustManager} and {@link javax.net.ssl.X509TrustManager} that will accept all server and client
 * certificates. Before accepting a certificate, the InsecureExtendedTrustManager uses the default X509ExtendedTrustManager
 * to determine if the certificate would otherwise be trusted, and logs a debug-level message if it is not trusted.
 */
public class InsecureExtendedTrustManager extends X509ExtendedTrustManager {
    private static final Logger log = LoggerFactory.getLogger(InsecureExtendedTrustManager.class);

    /**
     * The default extended trust manager, which will be used to determine if certificates would otherwise be trusted.
     */
    protected static final X509ExtendedTrustManager DEFAULT_EXTENDED_TRUST_MANAGER = getDefaultExtendedTrustManager();

    /**
     * An {@link X509ExtendedTrustManager} that does no certificate validation whatsoever.
     */
    private static final X509ExtendedTrustManager NOOP_EXTENDED_TRUST_MANAGER = new X509ExtendedTrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return EmptyArrays.EMPTY_X509_CERTIFICATES;
        }
    };

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
        try {
            DEFAULT_EXTENDED_TRUST_MANAGER.checkClientTrusted(x509Certificates, s, socket);
        } catch (Exception e) {
            log.debug("Accepting an untrusted client certificate: {}", x509Certificates[0].getSubjectDN(), e);
        }
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
        try {
            DEFAULT_EXTENDED_TRUST_MANAGER.checkServerTrusted(x509Certificates, s, socket);
        } catch (Exception e) {
            log.debug("Accepting an untrusted server certificate: {}", x509Certificates[0].getSubjectDN(), e);
        }
    }

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {
        try {
            DEFAULT_EXTENDED_TRUST_MANAGER.checkClientTrusted(x509Certificates, s, sslEngine);
        } catch (Exception e) {
            log.debug("Accepting an untrusted client certificate: {}", x509Certificates[0].getSubjectDN(), e);
        }
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {
        try {
            DEFAULT_EXTENDED_TRUST_MANAGER.checkServerTrusted(x509Certificates, s, sslEngine);
        } catch (Exception e) {
            log.debug("Accepting an untrusted server certificate: {}", x509Certificates[0].getSubjectDN(), e);
        }
    }

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        try {
            DEFAULT_EXTENDED_TRUST_MANAGER.checkClientTrusted(x509Certificates, s);
        } catch (Exception e) {
            log.debug("Accepting an untrusted client certificate: {}", x509Certificates[0].getSubjectDN(), e);
        }
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        try {
            DEFAULT_EXTENDED_TRUST_MANAGER.checkServerTrusted(x509Certificates, s);
        } catch (Exception e) {
            log.debug("Accepting an untrusted server certificate: {}", x509Certificates[0].getSubjectDN(), e);
        }
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return EmptyArrays.EMPTY_X509_CERTIFICATES;
    }

    /**
     * Returns the JDK's default X509ExtendedTrustManager, or a no-op trust manager if the default cannot be found.
     */
    private static X509ExtendedTrustManager getDefaultExtendedTrustManager() {
        TrustManagerFactory trustManagerFactory;
        try {
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            // initialize the TrustManagerFactory with the default KeyStore
            trustManagerFactory.init((KeyStore) null);
        } catch (NoSuchAlgorithmException | KeyStoreException e) {
            log.debug("Unable to initialize default TrustManagerFactory. Using no-op X509ExtendedTrustManager.", e);
            return NOOP_EXTENDED_TRUST_MANAGER;
        }

        // find the X509ExtendedTrustManager in the list of registered trust managers
        for (TrustManager tm : trustManagerFactory.getTrustManagers()) {
            if (tm instanceof X509ExtendedTrustManager) {
                return (X509ExtendedTrustManager) tm;
            }
        }

        // no default X509ExtendedTrustManager found, so return a no-op
        log.debug("No default X509ExtendedTrustManager found. Using no-op.");
        return NOOP_EXTENDED_TRUST_MANAGER;
    }
}


text:
namespace EntityFramework.Northwind.Entities
{
    using System;
    using System.Collections.Generic;

    public partial class Customers
    {
        public Customers()
        {
            this.Orders = new HashSet<Orders>();
            this.CustomerDemographics = new HashSet<CustomerDemographics>();
        }

        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }

        public virtual ICollection<Orders> Orders { get; set; }
        public virtual ICollection<CustomerDemographics> CustomerDemographics { get; set; }
    }
}


text:
package org.squbs.unicomplex

import java.lang.management.ManagementFactory
import javax.management.ObjectName
import javax.management.openmbean.CompositeData
import akka.actor.ActorSystem
import akka.http.scaladsl.model.HttpEntity.Chunked
import akka.http.scaladsl.model.{ContentTypes, HttpEntity, StatusCodes}
import akka.pattern.ask
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Keep, Sink, Source}
import akka.testkit.{ImplicitSender, TestKit}
import com.typesafe.config.ConfigFactory
import org.scalatest.{BeforeAndAfterAll, Inspectors}
import org.scalatest.concurrent.{Eventually, Waiters}
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike
import org.squbs.lifecycle.GracefulStop
import org.squbs.unicomplex.Timeouts._
import org.squbs.unicomplex.UnicomplexBoot.StartupType
import org.squbs.unicomplex.dummyextensions.DummyExtension
import org.squbs.unicomplex.dummysvcactor.GetWebContext

import scala.concurrent.Await
import scala.language.postfixOps

object UnicomplexSpec {

  val dummyJarsDir = getClass.getClassLoader.getResource("classpaths").getPath

  val classPaths = Array(
    "DummyCube",
    "DummyCubeSvc",
    "DummySvc",
    "DummySvcActor",
    "DummyFlowSvc",
    "StashCube",
    "DummyExtensions"
  ) map (dummyJarsDir + "/" + _)

  val config = ConfigFactory.parseString(
    s"""
       |squbs {
       |  actorsystem-name = UnicomplexSpec
       |  ${JMX.prefixConfig} = true
       |}
       |default-listener.bind-port = 0
       |akka.http.server.remote-address-header = on
    """.stripMargin
  )

  val boot = UnicomplexBoot(config)
    .createUsing {(name, config) => ActorSystem(name, config)}
    .scanComponents(classPaths)
    .initExtensions.start()

}

class UnicomplexSpec extends TestKit(UnicomplexSpec.boot.actorSystem) with ImplicitSender
                             with AnyWordSpecLike with Matchers with Inspectors with BeforeAndAfterAll
                             with Waiters with Eventually {

  import UnicomplexSpec._
  import system.dispatcher

  val portBindings = Await.result((Unicomplex(system).uniActor ? PortBindings).mapTo[Map[String, Int]], awaitMax)
  val port = portBindings("default-listener")

  override def afterAll(): Unit = {
    Unicomplex(system).uniActor ! GracefulStop
  }

  "UnicomplexBoot" must {

    "start all cube actors" in {
      val w = new Waiter

      system.actorSelection("/user/DummyCube").resolveOne().onComplete { result =>
        w {assert(result.isSuccess)}
        w.dismiss()
      }
      w.await()

      system.actorSelection("/user/DummyCubeSvc").resolveOne().onComplete { result =>
        w {assert(result.isSuccess)}
        w.dismiss()
      }
      w.await()

      system.actorSelection("/user/DummyCube/Appender").resolveOne().onComplete { result =>
        w {assert(result.isSuccess)}
        w.dismiss()
      }
      w.await()

      system.actorSelection("/user/DummyCube/Prepender").resolveOne().onComplete { result =>
        w {assert(result.isSuccess)}
        w.dismiss()
      }
      w.await()

      system.actorSelection("/user/DummyCubeSvc/PingPongPlayer").resolveOne().onComplete { result =>
        w {assert(result.isSuccess)}
        w.dismiss()
      }
      w.await()

      system.actorSelection("/user/StashCube").resolveOne().onComplete { result =>
        w {assert(result.isSuccess)}
        w.dismiss()
      }
      w.await()
    }

    "start all services" in {
      val services = boot.cubes flatMap { cube => cube.components.getOrElse(StartupType.SERVICES, Seq.empty) }
      assert(services.size == 7)

      Await.result(entityAsString(s"http://127.0.0.1:$port/dummysvc/msg/hello"), awaitMax) should be ("^hello$")

      Await.result(entityAsString(s"http://127.0.0.1:$port/dummysvc/who"), awaitMax) should fullyMatch regex """\d+(\.\d+){3}:\d+"""

      Await.result(entityAsString(s"http://127.0.0.1:$port/dummy2svc/v1/msg/hello"), awaitMax) should be ("^hello$")
      // This implementation reverses the message
      Await.result(entityAsString(s"http://127.0.0.1:$port/dummy2svc/msg/hello"), awaitMax) should be ("^olleh$")

      Await.result(entityAsString(s"http://127.0.0.1:$port/pingpongsvc/ping"), awaitMax) should be ("Pong")

      Await.result(entityAsString(s"http://127.0.0.1:$port/pingpongsvc/pong"), awaitMax) should be ("Ping")

      Await.result(entityAsString(s"http://127.0.0.1:$port/dummysvcactor/ping"), awaitMax) should be ("pong")

      Await.result(entityAsString(s"http://127.0.0.1:$port/dummyflowsvc/ping"), awaitMax) should be ("pong")

      val requestChunks = Source.single("Hi this is a test")
        .mapConcat { s => s.split(' ').toList }
        .map (HttpEntity.ChunkStreamPart(_))

      val errResp = Await.result(get(s"http://127.0.0.1:$port/dummyflowsvc/throwit"), awaitMax)
      errResp.status shouldBe StatusCodes.InternalServerError
      val respEntity = Await.result(errResp.entity.toStrict(awaitMax), awaitMax)
      respEntity.data.utf8String shouldBe empty

      val response = Await.result(
          post(s"http://127.0.0.1:$port/dummyflowsvc/chunks", Chunked(ContentTypes.`text/plain(UTF-8)`, requestChunks)),
          awaitMax)

      response.entity shouldBe 'chunked
      val responseStringF = response.entity.dataBytes.map(_.utf8String).toMat(Sink.fold("") { _ + _ })(Keep.right).run()
      val responseString = Await.result(responseStringF, awaitMax)
      responseString should be ("Received 5 chunks and 13 bytes.\r\nThis is the last chunk!")

      Await.result(post(s"http://127.0.0.1:$port/withstash/", HttpEntity("request message")),
        awaitMax).status should be (StatusCodes.Accepted)

      Await.result(entityAsString(s"http://127.0.0.1:$port/withstash/"), awaitMax) should be (Seq.empty[String].toString)

      Await.result(put(s"http://127.0.0.1:$port/withstash/"), awaitMax).status should be (StatusCodes.Created)

      // Whether messages from unstashall or the message from this request will be the first message to StashCubeSvc
      // is not deterministic.  So, running it in eventually.
      eventually {
        Await.result(entityAsString(s"http://127.0.0.1:$port/withstash/"), awaitMax) should be (Seq("request message").toString)
      }
    }

    "service actor with WebContext must have a WebContext" in {
      val w = new Waiter
      for {
        svcActor <- system.actorSelection("/user/DummySvcActor/dummysvcactor-DummySvcActor-handler").resolveOne()
        result   <- (svcActor ? GetWebContext).mapTo[String]
      } {
        w { result should be ("dummysvcactor") }
        w.dismiss()
      }
      w.await()
    }

    "check cube MXbean" in {
      import org.squbs.unicomplex.JMX._
      val mBeanServer = ManagementFactory.getPlatformMBeanServer
      val cubesObjName = new ObjectName(prefix(system) + cubesName)
      val attr = mBeanServer.getAttribute(cubesObjName, "Cubes")
      attr shouldBe a [Array[_]]
      val attrs = attr.asInstanceOf[Array[_]]

      // 6 cubes registered above.
      attrs should have size 7
      all (attrs) shouldBe a [javax.management.openmbean.CompositeData]
    }

    "check cube state MXbean" in {
      import org.squbs.unicomplex.JMX._
      val cubeName = "DummyCube"
      val mBeanServer = ManagementFactory.getPlatformMBeanServer
      val cubesObjName = new ObjectName(prefix(system) + cubeStateName + cubeName)
      val name = mBeanServer.getAttribute(cubesObjName, "Name")
      name should be (cubeName)

      val cubeState = mBeanServer.getAttribute(cubesObjName, "CubeState")
      cubeState should be ("Active")

      val WellKnownActors = mBeanServer.getAttribute(cubesObjName, "WellKnownActors").asInstanceOf[String]
      WellKnownActors should include ("Actor[akka://UnicomplexSpec/user/DummyCube/Prepender#")
      WellKnownActors should include ("Actor[akka://UnicomplexSpec/user/DummyCube/Appender#")
    }

    "check listener MXbean" in {
      import org.squbs.unicomplex.JMX._
      val mBeanServer = ManagementFactory.getPlatformMBeanServer
      val listenersObjName = new ObjectName(prefix(system) + listenersName)
      val ls = mBeanServer.getAttribute(listenersObjName, "Listeners")
      ls shouldBe a [Array[_]]
      val listeners = ls.asInstanceOf[Array[_]]
      all (listeners) shouldBe a [javax.management.openmbean.CompositeData]

      // 6 services registered on one listener
      listeners should have size 7

    }

    "check extension MBean" in {
      import org.squbs.unicomplex.JMX._
      val mBeanServer = ManagementFactory.getPlatformMBeanServer
      val extensionObjName = new ObjectName(prefix(system) + extensionsName)
      val xs = mBeanServer.getAttribute(extensionObjName, "Extensions")
      xs shouldBe a [Array[_]]
      val extensions = xs.asInstanceOf[Array[_]]
      all (extensions) shouldBe a [javax.management.openmbean.CompositeData]
      extensions should have size 2
      val dummyExtensionA = extensions(0).asInstanceOf[CompositeData]
      val dummyExtensionB = extensions(1).asInstanceOf[CompositeData]
      dummyExtensionA.get("cube") should be ("DummyExtensions")
      dummyExtensionA.get("sequence") should be (30)
      dummyExtensionA.get("error") should be ("")
      dummyExtensionA.get("phase") should be ("")
      dummyExtensionB.get("cube") should be ("DummyExtensions")
      dummyExtensionB.get("sequence") should be (40)
      dummyExtensionB.get("error") should be ("")
      dummyExtensionB.get("phase") should be ("")
    }

    "preInit, init, preCubesInit   and postInit all extensions" in {
      boot.extensions.size should be (2)
      forAll (boot.extensions) { _.extLifecycle.get shouldBe a [DummyExtension]}
      boot.extensions(0).extLifecycle.get.asInstanceOf[DummyExtension].state should be ("AstartpreInitinitpreCubesInitpostInit")
      boot.extensions(1).extLifecycle.get.asInstanceOf[DummyExtension].state should be ("BstartpreInitinitpreCubesInitpostInit")
    }

    "ReportStatus" in {
      Unicomplex(system).uniActor ! ReportStatus
      expectMsgPF(){
        case StatusReport(state, _, _) =>
          state should be(Active)
      }
    }
  }
}


text:
namespace content {

OfflinePolicy::OfflinePolicy()
    : enabled_(CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kEnableOfflineCacheAccess)),
      state_(INIT),
      resource_loads_initiated_(0),
      resource_loads_successfully_started_(0) {}

OfflinePolicy::~OfflinePolicy() {
  RecordAndResetStats();
}

void OfflinePolicy::RecordAndResetStats() {
  if (enabled_ && OFFLINE == state_ && 0 != resource_loads_initiated_) {
    UMA_HISTOGRAM_PERCENTAGE(
        "OfflinePolicy.SuccessfulResourceLoadPercentage",
        (resource_loads_successfully_started_ * 100 /
         resource_loads_initiated_));
  }
  resource_loads_initiated_ = 0;
  resource_loads_successfully_started_ = 0;
}

int OfflinePolicy::GetAdditionalLoadFlags(int current_flags,
                                          bool reset_state) {
  // Don't do anything if offline mode is disabled.
  if (!enabled_)
    return 0;

  if (reset_state) {
    RecordAndResetStats();
    state_ = INIT;
  }

  ++resource_loads_initiated_;

  // If a consumer has requested something contradictory, it wins; we
  // don't modify the load flags.
  if (current_flags &
      (net::LOAD_BYPASS_CACHE | net::LOAD_PREFERRING_CACHE |
       net::LOAD_ONLY_FROM_CACHE | net::LOAD_FROM_CACHE_IF_OFFLINE |
       net::LOAD_DISABLE_CACHE)) {
    return 0;
  }

  switch(state_) {
    case INIT:
      return net::LOAD_FROM_CACHE_IF_OFFLINE;
    case ONLINE:
      return 0;
    case OFFLINE:
      return net::LOAD_ONLY_FROM_CACHE;
  }
  NOTREACHED();
  return 0;
}

void OfflinePolicy::UpdateStateForSuccessfullyStartedRequest(
    const net::HttpResponseInfo& response_info) {
  // Don't do anything if offline mode is disabled.
  if (!enabled_)
    return;

  // If we get here, we're going to be providing some amount of information
  // to the renderer.
  ++resource_loads_successfully_started_;

  if (state_ != INIT)
    // We've already made the decision for the rest of this set
    // of navigations.
    return;

  if (response_info.server_data_unavailable) {
    state_ = OFFLINE;
  } else if (response_info.network_accessed) {
    // If we got the response from the network or validated it as part
    // of this request, that means our connection to the host is working.
    state_ = ONLINE;
  }
}

}  // namespace content


text:
class CreateChouetteGroupOfLine < ActiveRecord::Migration
  def up
    create_table :group_of_lines, :force => true do |t|
      t.string   "objectid", :null => false
      t.integer  "object_version"
      t.datetime "creation_time"
      t.string   "creator_id"

      t.string   "name"
      t.string   "comment"
    end
   add_index "group_of_lines", ["objectid"], :name => "group_of_lines_objectid_key", :unique => true
  end

  def down
    drop_table :group_of_lines
  end
end


text:
/*
Problem 18. Extract e-mails
Write a program for extracting all email addresses from given text.
All sub-strings that match the format  <identifier>@<host>…<domain>  should be recognized as emails.
*/

using System;
using System.Collections.Generic;
class ExtractЕМails
{
    static void Main()
    {
        Console.Write("Ënter text: ");
        string text = Console.ReadLine();

        string[] splittedText = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        List<string> result = new List<string>();

        foreach (var substring in splittedText)
        {
            if (substring.Contains("@") && substring.Contains("."))
            {
                result.Add(substring);
            }
        }
        for (int i = 0; i < result.Count; i++)
        {
            Console.WriteLine(result[i]);
        }
    }
}


text:
package com.iboxapp.ibox.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.iboxapp.ibox.IshowFragment;
import com.iboxapp.ibox.R;
import com.iboxapp.ibox.adapter.FindRecyclerViewAdapter;
import com.iboxapp.ibox.widget.GridSpacingItemDecoration;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class FindActivity extends AppCompatActivity {

    private Button mButton;
    private Toolbar mToolbar;
    private RecyclerView mRecyclerView;
    private GridLayoutManager mGridLayoutManager;
    private FindRecyclerViewAdapter mAdapter;

    private static final String ACTIVITY_TAG="LogDemo";
    private String[] mDatasText={"女装","女鞋","美妆","男装","男鞋","箱包","饰品","户外/运动","数码","美食","日常百货","家具装饰"};
    private ArrayList<Integer> mDatasImg = new ArrayList<Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find);

        mToolbar = (Toolbar) findViewById(R.id.simple_toolbar);
        mToolbar.setTitle(getResources().getString(R.string.show_find));
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mRecyclerView = (RecyclerView) findViewById(R.id.activity_find_recycler_view);
        // 网格布局管理器
        mGridLayoutManager = new GridLayoutManager(this, 3);
        mGridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        //如果可以确定每个item的高度是固定的,设置这个选项可以提高性能
        mRecyclerView.setHasFixedSize(true);
        //创建并设置Adapter
        mAdapter = new FindRecyclerViewAdapter(this,mDatasText,mDatasImg);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new FindRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(getApplicationContext(), "Click", Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(FindActivity.this, MultiCategoryActivity.class);
                intent.putExtra("mButton", position);
                startActivity(intent);
            }
        });
        // 设置item动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        int spanCount = 3;
        int spacing = 30;
        boolean includeEdge = true;
        mRecyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
        initDatasImg();
        /*initButton();

        Log.i(FindActivity.ACTIVITY_TAG, "This is Information2");
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(FindActivity.ACTIVITY_TAG, "This is Information3");
                Intent intent = new Intent(FindActivity.this, MultiCategoryActivity.class);
                startActivity(intent);
            }
        });*/
    }

    public void initDatasImg() {
        for (int position = 1; position <= 12; position++)
            mDatasImg.add(getResId("ic_button_" + position, R.drawable.class));
    }

    /**
     * 通过文件名获取资源id 例子:getResId("icon", R.drawable.class);
     *
     * @param variableName
     * @param c
     * @return
     */
    public static int getResId(String variableName, Class<?> c) {
        try {
            Field idField = c.getDeclaredField(variableName);
            return idField.getInt(idField);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // TODO Auto-generated method stub
        if(item.getItemId() == android.R.id.home)
        {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}


text:
package org.apache.druid.data.input.kafkainput;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.apache.kafka.common.header.Headers;

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes(value = {
        @JsonSubTypes.Type(name = "string", value = KafkaStringHeaderFormat.class)
})

public interface KafkaHeaderFormat
{
  KafkaHeaderReader createReader(
            Headers headers,
            String headerLabelPrefix
    );
}


text:
package dht

import (
	"net"

	"github.com/anacrolix/missinggo"
)

// Used internally to refer to node network addresses.
type dHTAddr interface {
	net.Addr
	UDPAddr() *net.UDPAddr
	IP() net.IP
}

// Speeds up some of the commonly called Addr methods.
type cachedAddr struct {
	a  net.Addr
	s  string
	ip net.IP
}

func (ca cachedAddr) Network() string {
	return ca.a.Network()
}

func (ca cachedAddr) String() string {
	return ca.s
}

func (ca cachedAddr) UDPAddr() *net.UDPAddr {
	return ca.a.(*net.UDPAddr)
}

func (ca cachedAddr) IP() net.IP {
	return ca.ip
}

func newDHTAddr(addr net.Addr) dHTAddr {
	return cachedAddr{addr, addr.String(), missinggo.AddrIP(addr)}
}


text:
class CreateNewsItems < ActiveRecord::Migration[5.2]
  def change
    create_table :news_items do |t|
      t.string :title
      t.string :description
      t.string :url
      t.timestamps
    end
  end
end


text:
#ifndef VMATH_H_
#define VMATH_H_

#if defined(WIN32)
#define INLINE
#else
#define INLINE  inline
#endif

typedef struct { float x, y, z; } vec3_t;
typedef struct { float x, y, z, w; } vec4_t;

typedef vec4_t quat_t;

typedef float mat4_t[4][4];

/* vector functions */
static INLINE vec3_t v3_cons(float x, float y, float z);
static INLINE float v3_dot(vec3_t v1, vec3_t v2);

/* quaternion functions */
static INLINE quat_t quat_cons(float s, float x, float y, float z);
static INLINE vec3_t quat_vec(quat_t q);
static INLINE quat_t quat_mul(quat_t q1, quat_t q2);
static INLINE void quat_to_mat(mat4_t res, quat_t q);
quat_t quat_rotate(quat_t q, float angle, float x, float y, float z);

/* matrix functions */
static INLINE void m4_cons(mat4_t m,
    float m11, float m12, float m13, float m14,
    float m21, float m22, float m23, float m24,
    float m31, float m32, float m33, float m34,
    float m41, float m42, float m43, float m44);

#include "vmath.inl"

#endif  /* VMATH_H_ */


text:
// Copyright 2014-2016 Aaron Viviano
// MIT License (MIT).
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Torino.Language;
using Torino.SyntacticalAnalyzer;
using Torino.SyntacticalAnalyzer.Results;

namespace TorinoTest
{
    [TestClass]
    public class SelectTests : TestSQLBase
    {
        #region Select Columns
        [TestMethod]
        public void SelectAllFromTable()
        {
            Check("SELECT * FROM Products;");
        }

        [TestMethod]
        public void SelectColumnFromTable()
        {
            Check("SELECT ProductName FROM Products;");
        }

        [TestMethod]
        public void SelectMultipleColumnsFromTable()
        {
            Check("SELECT ProductName, SupplierID FROM Products;");
        }
        #endregion Select Columns

        #region Joins
        [TestMethod]
        public void SelectColumnsFromMultipleTables()
        {
            Check("SELECT Employees.FirstName, Employees.LastName, OrderID FROM Employees INNER JOIN Orders ON Orders.EmployeeID = Employees.EmployeeID;");
        }

        [TestMethod]
        public void SelectLeftJoin()
        {
            Check("SELECT Employees.FirstName, Employees.LastName, OrderID FROM Employees LEFT JOIN Orders ON Orders.EmployeeID = Employees.EmployeeID;");
        }

        [TestMethod]
        public void SelectRightJoin()
        {
            Check("SELECT Employees.FirstName, Employees.LastName, OrderID FROM Employees RIGHT JOIN Orders ON Orders.EmployeeID = Employees.EmployeeID;");
        }

        [TestMethod]
        public void SelectFullOuterJoin()
        {
            Check("SELECT Employees.FirstName, Employees.LastName, OrderID FROM Employees FULL OUTER JOIN Orders ON Orders.EmployeeID = Employees.EmployeeID;");
        }
        #endregion Joins

        #region Character Casing
        [TestMethod]
        public void LowerCaseSelect()
        {
            Check("select Employees.FirstName, Employees.LastName, OrderID from Employees full outer join Orders on Orders.EmployeeID = Employees.EmployeeID;");
        }

        [TestMethod]
        public void MixedCaseSelect()
        {
            Check("Select Employees.FirstName, Employees.LastName, OrderID From Employees Full Outer Join Orders On Orders.EmployeeID = Employees.EmployeeID;");
        }
        #endregion Character Casing

    }
}


text:
package org.inaturalist.android;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import org.tinylog.Logger;

import java.util.HashMap;
import java.util.Map;

public class ObservationEditorSlider extends AppCompatActivity {
    private static final String TAG = "ObservationEditorSlider";
    private ViewPager mPager;
    private PagerAdapter mPagerAdapter;

    Map<Integer, Fragment> mFragmentsByPositions = new HashMap<>();
    int mLastPosition = 0;
    private INaturalistApp mApp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.obs_editor_slider);

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
        mPager.setCurrentItem(mLastPosition);

        mApp = (INaturalistApp) getApplicationContext();

        mPager.clearOnPageChangeListeners();
        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                ObservationEditor fragment = (ObservationEditor) mFragmentsByPositions.get(mLastPosition);

                if (fragment != null) {
                    // Tell the fragment it needs to save current observation
                    fragment.saveObservation();
                }

                mLastPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    @Override
    public void onBackPressed() {
        int position = mPager.getCurrentItem();
        Fragment fragment = mFragmentsByPositions.get(position);
        if (fragment != null) {
            ((ObservationEditor)fragment).onBack();
        }
    }

    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        private Cursor mCursor = null;

        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);

            if ((getIntent().getAction() == Intent.ACTION_INSERT) ||
                    (getIntent().getAction() == Intent.ACTION_SEND) ||
                    (getIntent().getAction() == Intent.ACTION_SEND_MULTIPLE)) {
                // New observation / share image to iNat
                return;
            }

            SharedPreferences prefs = getSharedPreferences("iNaturalistPreferences", Activity.MODE_PRIVATE);
            String login = prefs.getString("username", null);
            String conditions = "(_synced_at IS NULL";
            if (login != null) {
                conditions += " OR user_login = '" + login + "'";
            }
            conditions += ") AND (is_deleted = 0 OR is_deleted is NULL)"; // Don't show deleted observations

            mCursor = getContentResolver().query(Observation.CONTENT_URI, Observation.PROJECTION,
                    conditions, null, Observation.DEFAULT_SORT_ORDER);

            // Find initial position according to the URI the activity was launched with
            Long initialObsId = Long.valueOf(getIntent().getData().getLastPathSegment());
            mCursor.moveToFirst();
            do {
                Long obsId = mCursor.getLong(mCursor.getColumnIndexOrThrow(Observation._ID));
                if (obsId.equals(initialObsId)) {
                    break;
                }
            } while (mCursor.moveToNext());
            mLastPosition = mCursor.getPosition();
        }

        @Override
        public Fragment getItem(int position) {
            Fragment fragment = new ObservationEditor();

            Bundle args = new Bundle();
            if (mCursor != null) {
                mCursor.moveToPosition(position);
                Observation obs = new Observation(mCursor);
                args.putString(ObservationEditor.OBS_URI, obs.getUri().toString());
            } else if ((getIntent().getAction() != Intent.ACTION_SEND) &&
                    (getIntent().getAction() != Intent.ACTION_SEND_MULTIPLE)) {
                args.putString(ObservationEditor.OBS_URI, getIntent().getData().toString());
            }

            Logger.tag(TAG).error("getItem: " + position + ": " + args.getString(ObservationEditor.OBS_URI));
            fragment.setArguments(args);

            mFragmentsByPositions.put(position, fragment);
            return fragment;
        }

        @Override
        public int getCount() {
            return mCursor != null ? mCursor.getCount() : 1;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        mApp.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}


text:
package org.elasticsearch.client.security;

import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.util.Objects;

import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg;

/**
 * Response when adding a user to the native realm. Returns a
 * single boolean field for whether the user was created or updated.
 */
public final class PutUserResponse {

    private final boolean created;

    public PutUserResponse(boolean created) {
        this.created = created;
    }

    public boolean isCreated() {
        return created;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        PutUserResponse that = (PutUserResponse) o;
        return created == that.created;
    }

    @Override
    public int hashCode() {
        return Objects.hash(created);
    }

    private static final ConstructingObjectParser<PutUserResponse, Void> PARSER = new ConstructingObjectParser<>("put_user_response",
        true, args -> new PutUserResponse((boolean) args[0]));

    static {
        ConstructingObjectParser<Boolean, Void> roleMappingParser = new ConstructingObjectParser<>(
                "put_user_response.user", true, args -> (Boolean) args[0]);
        roleMappingParser.declareBoolean(constructorArg(), new ParseField("created"));
        PARSER.declareObject(constructorArg(), roleMappingParser::parse, new ParseField("user"));
    }

    public static PutUserResponse fromXContent(XContentParser parser) throws IOException {
        return PARSER.parse(parser, null);
    }
}


text:
using Cudafy;
using Cudafy.Host;
using Cudafy.Translator;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Athena
{
    internal class Word2Vec
    {
        // Start hyperparameters.
        private const bool USE_CBOW = true;
        private const float BaseLearningRate = 0.05f;
        private const double SubSample = 1e-8;
        private const int Iterations = 5;
        private const int NegativeSamples = 5;
        private const int SentenceBatches = 10;
        private const int SentencePositions = 64;
        private const int Window = 5;
        // End hyperparameters.

        private readonly Model _model;
        private readonly Random _rnd = new Random();
        private int[,] _tokens = new int[SentenceBatches, 1 + SentencePositions];
        private float _learningRate = BaseLearningRate;
        private float[,] _gpuContext;
        private float[,] _gpuLocation;
        private int[] _gpuRoulette;
        private int _rouletteLength;
        private int _sentence;
        private GPGPU _gpu;

        public Word2Vec(bool learnVocab)
        {
            _model = new Model(learnVocab);
            _gpu = CudafyHost.GetDevice(CudafyModes.Target, Program.DeviceID);
            _gpu.LoadModule(CudafyTranslator.Cudafy(_gpu.GetArchitecture()));
            _gpu.FreeAll();
            CopyToGPU();

            for (var iteration = 0; iteration < Iterations; iteration++)
            {
                Train(iteration);
                CopyFromGPU();
                _model.Save();
            }

            _gpu.FreeAll();
        }

        private void CopyToGPU()
        {
            var arrayContext = new float[_model.Count, Model.Dims];
            var arrayLocation = new float[_model.Count, Model.Dims];

            int id = 0;
            foreach (var item in _model)
            {
                item.Value.ID = id;
                for (var i = 0; i < Model.Dims; i++)
                {
                    arrayContext[id, i] = (float)(0.5 - _rnd.NextDouble());
                    arrayLocation[id, i] = (float)(0.5 - _rnd.NextDouble());
                }
                id++;
            }

            var tmp = new List<int>();
            var div = Math.Pow(Model.TrainMin, 0.6);
            foreach (var word in _model)
            {
                var count = (int)(Math.Pow(word.Value.Count, 0.6) / div);
                for (var i = 0; i < count; i++) tmp.Add(word.Value.ID);
            }
            var arrayRoulette = tmp.ToArray();
            _rouletteLength = arrayRoulette.Length;

            _gpuContext = _gpu.Allocate<float>(arrayContext);
            _gpuLocation = _gpu.Allocate<float>(arrayLocation);
            _gpuRoulette = _gpu.Allocate<int>(arrayRoulette);

            _gpu.CopyToDevice(arrayContext, _gpuContext);
            _gpu.CopyToDevice(arrayLocation, _gpuLocation);
            _gpu.CopyToDevice(arrayRoulette, _gpuRoulette);
        }

        private void CopyFromGPU()
        {
            var arrayContext = new float[_model.Count, Model.Dims];
            var arrayLocation = new float[_model.Count, Model.Dims];

            _gpu.CopyFromDevice(_gpuContext, arrayContext);
            _gpu.CopyFromDevice(_gpuLocation, arrayLocation);

            foreach (var item in _model)
            {
                var id = item.Value.ID;
                var location = item.Value.Vector;
                for (var i = 0; i < Model.Dims; i++)
                    location[i] = arrayLocation[id, i];
            }
        }

        private void Train(int iteration)
        {
            Console.WriteLine("Training model [{0:H:mm:ss}]", DateTime.Now);
            Console.WriteLine();
            var start = DateTime.Now;
            var checkpoint = DateTime.Now;
            var wordCount = 0;
            double length = new FileInfo(Program.Path_Corpus_1).Length;
            using (var sr = new StreamReader(Program.Path_Corpus_1))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    var sentence = new List<string>();
                    foreach (
                        var word in
                        line.Split(null as string[], StringSplitOptions.RemoveEmptyEntries)
                            .Where(word => _model.ContainsKey(word)))
                    {
                        wordCount++;
                        sentence.Add(word);
                    }

                    if (sentence.Count > 1) ProcessSentence(sentence, _learningRate);

                    if (checkpoint < DateTime.Now)
                    {
                        var progress = (float)(sr.BaseStream.Position / length);
                        var seconds = (DateTime.Now - start).TotalSeconds + 1;
                        var rate = wordCount / seconds / 1000.0;
                        _learningRate = BaseLearningRate - (iteration * BaseLearningRate / Iterations) - (progress * BaseLearningRate / Iterations);
                        Console.Write("Iteration {0}  Progress: {1:0.000%}  words/sec: {2:0.000}k  learning rate: {3:0.000}  \r", iteration, progress, rate, _learningRate);
                        checkpoint = DateTime.Now.AddSeconds(1);
                    }
                }
            }
            Console.WriteLine("\r\n");
        }

        private void ProcessSentence(IReadOnlyList<string> sentence, float learningRate)
        {
            var position = 1;
            foreach (var word in sentence)
            {
                var tmp = _model[word];
                if (_rnd.NextDouble() > 1 - Math.Sqrt(SubSample * tmp.Count)) continue;
                _tokens[_sentence, position] = tmp.ID;
                position++;
                if (position == SentencePositions) break;
            }
            _tokens[_sentence, 0] = position - 1;

            _sentence++;
            if (_sentence == SentenceBatches)
            {
                _sentence = 0;
                _gpu.CopyToConstantMemory(_tokens, Tokens);
                if (USE_CBOW)
                    _gpu.Launch(SentenceBatches * SentencePositions, Model.Dims).CBOW(_gpuContext, _gpuLocation, _gpuRoulette, _rouletteLength, _rnd.Next(99999), learningRate);
                else
                    _gpu.Launch(SentenceBatches * SentencePositions, Model.Dims).SGNS(_gpuContext, _gpuLocation, _gpuRoulette, _rouletteLength, _rnd.Next(99999), learningRate);
                _tokens = new int[SentenceBatches, 1 + SentencePositions];
            }
        }

        [Cudafy]
        public static int[,] Tokens = new int[SentenceBatches, 1 + SentencePositions];

        [Cudafy]
        // Predict a word given its context.
        public static void CBOW(GThread thread, float[,] context, float[,] location, int[] roulette, int rouletteLength, int seed, float learningRate)
        {
            float[] activation = thread.AllocateShared<float>("activation", Model.Dims);
            float[] error = thread.AllocateShared<float>("error", Model.Dims);
            float[] hidden = thread.AllocateShared<float>("hidden", Model.Dims);
            float[] g = thread.AllocateShared<float>("g", 1);
            int[] crop = thread.AllocateShared<int>("crop", 1);
            int[] negID = thread.AllocateShared<int>("negID", 1);

            int sentence = thread.blockIdx.x / SentencePositions;
            int position = thread.blockIdx.x - sentence * SentencePositions;
            int dim = thread.threadIdx.x;

            int len = Tokens[sentence, 0];
            if (position <= len)
            {
                uint random = (uint)(seed + position);
                if (dim == 0)
                {
                    random = random * 1664525u + 1013904223u;
                    crop[0] = (int)(random % Window);
                }
                thread.SyncThreads();

                int c = 0;
                hidden[dim] = 0;
                for (var w = crop[0]; w < Window * 2 + 1 - crop[0]; w++)
                {
                    var p = position - Window + w;
                    if ((p < 0) || (p >= len)) continue;

                    if (w == Window) continue;

                    hidden[dim] += location[Tokens[sentence, p + 1], dim];
                    c++;
                }
                hidden[dim] /= c;

                error[dim] = 0;

                for (int n = 0; n <= NegativeSamples; n++)
                {
                    if (dim == 0)
                    {
                        random = random * 1664525u + 1013904223u;
                        negID[0] = roulette[random % rouletteLength];
                    }
                    thread.SyncThreads();

                    int targetID = negID[0];
                    if (n == 0) targetID = Tokens[sentence, position + 1];

                    activation[dim] = hidden[dim] * context[targetID, dim];
                    thread.SyncThreads();

                    int j = Model.Dims / 2;
                    while (j != 0)
                    {
                        if (dim < j) activation[dim] += activation[dim + j];
                        thread.SyncThreads();
                        j /= 2;
                    }

                    if ((n != 0 || activation[0] <= 5f) && (n == 0 || activation[0] >= -5f))
                    {
                        if (dim == 0)
                        {
                            int label = 0;
                            if (n == 0) label = 1;
                            g[0] = (label - 1 / (1 + GMath.Exp(-activation[0]))) * learningRate;
                        }
                        thread.SyncThreads();

                        error[dim] += g[0] * context[targetID, dim];
                        context[targetID, dim] += g[0] * hidden[dim];
                    }
                    thread.SyncThreads();
                }

                for (var w = crop[0]; w < Window * 2 + 1 - crop[0]; w++)
                {
                    var p = position - Window + w;
                    if ((p < 0) || (p >= len)) continue;

                    if (w == Window) continue;

                    location[Tokens[sentence, p + 1], dim] += error[dim];
                }
            }
        }

        [Cudafy]
        // Predict the context given a word.
        public static void SGNS(GThread thread, float[,] context, float[,] location, int[] roulette, int rouletteLength, int seed, float learningRate)
        {
            float[] activation = thread.AllocateShared<float>("activation", Model.Dims);
            float[] error = thread.AllocateShared<float>("error", Model.Dims);
            float[] g = thread.AllocateShared<float>("g", 1);
            int[] crop = thread.AllocateShared<int>("crop", 1);
            int[] negID = thread.AllocateShared<int>("negID", 1);

            int sentence = thread.blockIdx.x / SentencePositions;
            int position = thread.blockIdx.x - sentence * SentencePositions;
            int dim = thread.threadIdx.x;

            int len = Tokens[sentence, 0];
            if (position <= len)
            {
                uint random = (uint)(seed + position);
                if (dim == 0)
                {
                    random = random * 1664525u + 1013904223u;
                    crop[0] = (int)(random % Window);
                }
                thread.SyncThreads();

                for (var w = crop[0]; w < Window * 2 + 1 - crop[0]; w++)
                {
                    if (w != Window)
                    {
                        var p = position - Window + w;
                        if ((p < 0) || (p >= len)) continue;

                        error[dim] = 0;
                        for (int n = 0; n < NegativeSamples + 1; n++)
                        {
                            if (dim == 0)
                            {
                                random = random * 1664525u + 1013904223u;
                                negID[0] = roulette[random % rouletteLength];
                            }
                            thread.SyncThreads();

                            int targetID = negID[0];
                            if (n == 0) targetID = Tokens[sentence, p + 1];

                            activation[dim] = location[Tokens[sentence, position + 1], dim] * context[targetID, dim];
                            thread.SyncThreads();

                            int j = Model.Dims / 2;
                            while (j != 0)
                            {
                                if (dim < j) activation[dim] += activation[dim + j];
                                thread.SyncThreads();
                                j /= 2;
                            }

                            if ((n != 0 || activation[0] <= 5f) && (n == 0 || activation[0] >= -5f))
                            {
                                if (dim == 0)
                                {
                                    int label = 0;
                                    if (n == 0) label = 1;
                                    g[0] = (label - 1 / (1 + GMath.Exp(-activation[0]))) * learningRate;
                                }
                                thread.SyncThreads();

                                error[dim] += g[0] * context[targetID, dim];
                                context[targetID, dim] += g[0] * location[Tokens[sentence, position + 1], dim];
                            }
                            thread.SyncThreads();
                        }
                        location[Tokens[sentence, position + 1], dim] += error[dim];
                    }
                }
            }
        }
    }
}


text:
package errs

import (
	"fmt"
	"github.com/gostart/debug"
)

// FormatSkipStackFrames formats an error with call stack information if FormatWithCallStack is true.
// It skips skip stack frames.
func FormatSkipStackFrames(skip int, format string, args ...interface{}) error {
	if Config.FormatWithCallStack {
		format += "\n" + debug.CallStackInfo(skip+1)
	}
	return fmt.Errorf(format, args...)
}

// Format formats an error with call stack information if FormatWithCallStack is true
func Format(format string, args ...interface{}) error {
	return FormatSkipStackFrames(2, format, args...)
}

func Assert(condition bool, description string, args ...interface{}) {
	if !condition {
		panic(FormatSkipStackFrames(2, "Failed assertion: "+description, args...))
	}
}

// todo test
//func Catch(err *error) {
//	if err == nil {
//		panic(FormatSkipStackFrames(2, "errs.Catch expects non nil error pointer"))
//	}
//	CatchCall(func(e error) {
//		*err = e
//	})
//}
//
//func CatchCall(callback func(error)) {
//	if r := recover(); r != nil {
//		var err error
//		if e, ok := r.(runtime.Error); ok {
//			panic(e)
//			//*err = e
//		} else if e, ok := r.(error); ok {
//			err = e
//		} else if s, ok := r.(fmt.Stringer); ok {
//			err = os.NewError(s.String())
//		} else if s, ok := r.(string); ok {
//			err = os.NewError(s)
//		} else {
//			panic(r)
//		}
//		callback(err)
//	}
//}

// Panic if any of the args is a non nil error
func PanicOnError(args ...interface{}) {
	for _, arg := range args {
		if arg != nil {
			if err, ok := arg.(error); ok {
				panic(err)
			}
		}
	}
}

// Panic if the last element of args is a non nil error
func LastPanicOnError(args ...interface{}) {
	arg := args[len(args)-1]
	if arg != nil {
		if err, ok := arg.(error); ok {
			panic(err)
		}
	}
}

// Returns the first error in args
func First(args ...interface{}) error {
	for _, arg := range args {
		if arg != nil {
			if err, ok := arg.(error); ok {
				return err
			}
		}
	}
	return nil
}


text:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web;

namespace ElmahDashboardHostingApp.Areas.MvcElmahDashboard.Code
{
    public class ExternalServiceConfig : DynamicObject
    {
        private Dictionary<string, string> config = new Dictionary<string, string>();

        public ExternalServiceConfig(string configuration)
        {
            if (configuration != null)
            {
                foreach(var pair in configuration.Split(';').Select(p => p.Split(new char[] {'='}, 2)))
                {
                    config[pair[0]] = pair[1];
                }
            }
        }

        public string this[string property]
        {
            get
            {
                string value;
                if (config.TryGetValue(property, out value))
                {
                    return value;
                }
                else
                {
                    return null;
                }
            }
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = this[binder.Name];
            return true;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>HTML5 Polyfill (Firefox 8) Demo - jQuery contextMenu Plugin</title>
    <meta name="description" content="simple contextMenu generator for interactive web applications based on jQuery" />

    <link href="../src/jquery.contextMenu.css" rel="stylesheet" type="text/css" />
    <link href="../screen.css" rel="stylesheet" type="text/css" />
    <link href="../prettify/prettify.sunburst.css" rel="stylesheet" type="text/css" />

jQuery contextMenu

About

Demo

Documentation

Author

Demo: HTML5 Polyfill (Firefox 8)

    right click me

Example Code: HTML5 Polyfill (Firefox 8)

Example HTML: HTML5 Polyfill (Firefox 8)

<menu id="html5firefox8" type="context" class="showcase">
  <menuitem label="rotate" onclick="alert('rotate')" hint="I'm a hint"></menuitem>
  <menuitem label="resize" onclick="alert('resize')"></menuitem>
  <menuitem label="disabled" onclick="alert('disabled')" disabled></menuitem>
  <menu label="share">
    <menuitem label="twitter" onclick="alert('twitter')"></menuitem>
    <menuitem label="facebook" onclick="alert('facebook')"></menuitem>

    <menuitem type="checkbox" label="(checkbox) yes or no?"
        onclick="alert('checkbox: ' + (this.checked ? 'yep!' : 'nope'))"></menuitem>

    <menuitem type="radio" label="(radio) yes" radiogroup="alpha" checked
        onclick="alert('radio: yes')"></menuitem>
    <menuitem type="radio" label="(radio) no" radiogroup="alpha"
        onclick="alert('radio: no')"></menuitem>
  </menu>
</menu>

jQuery Context Menu Demo Gallery

Simple Context Menu

Context Menu on DOM Element

Adding new Context Menu Triggers

Create Context Menu on demand

Create Context Menu (asynchronous)

Keeping the context menu open

Command's action (callbacks)

Left-Click Trigger

Swipe Trigger

Hover Activated Context Menu

Hover Activated Context Menu With Autohide

Custom Activated Context Menu

Disabled Menu

Disabled Command

Disabled Callback Command

Changing Command's disabled status

Accesskeys

Submenus

Input Commands

Custom Command Types

Menus with titles

Importing HTML5 <menu type="context">

HTML5 Polyfill

HTML5 Polyfill (Firefox 8)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace ServiceStack.Common.Extensions
{
	public static class EnumExtensions
	{
		/// <summary>
		/// Gets the textual description of the enum if it has one. e.g.
		///
		/// <code>
		/// enum UserColors
		/// {
		///     [Description("Bright Red")]
		///     BrightRed
		/// }
		/// UserColors.BrightRed.ToDescription();
		/// </code>
		/// </summary>
		/// <param name="enum"></param>
		/// <returns></returns>
		public static string ToDescription(this Enum @enum)
		{
			var type = @enum.GetType();
			var memInfo = type.GetMember(@enum.ToString());
			if (memInfo != null && memInfo.Length > 0)
			{
				var attrs = memInfo[0].GetCustomAttributes(
					typeof(DescriptionAttribute),
					false);

				if (attrs != null && attrs.Length > 0)
					return ((DescriptionAttribute)attrs[0]).Description;
			}

			return @enum.ToString();
		}

		public static List<string> ToList(this Enum @enum)
		{
			return new List<string>(Enum.GetNames(@enum.GetType()));
		}

	}
}


text:
#include "include/core/SkTypes.h" // IWYU pragma: keep

#if !defined(SK_BUILD_FOR_GOOGLE3)  // Google3 doesn't have etc1.h

#include "gm/gm.h"
#include "include/core/SkBitmap.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkColor.h"
#include "include/core/SkData.h"
#include "include/core/SkImage.h"
#include "include/core/SkImageInfo.h"
#include "include/core/SkPath.h"
#include "include/core/SkRect.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkSize.h"
#include "include/core/SkString.h"
#include "src/core/SkCompressedDataUtils.h"
#include "src/core/SkMipMap.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrDataUtils.h"
#include "src/image/SkImage_Base.h"
#include "third_party/etc1/etc1.h"

class GrContext;
class GrRenderTargetContext;

static SkPoint gen_pt(float angle, const SkVector& scale) {
    SkScalar s = SkScalarSin(angle);
    SkScalar c = SkScalarCos(angle);

    return { scale.fX * c, scale.fY * s };
}

// The resulting path will be centered at (0,0) and its size will match 'dimensions'
static SkPath make_gear(SkISize dimensions, int numTeeth) {
    SkVector outerRad{ dimensions.fWidth / 2.0f, dimensions.fHeight / 2.0f };
    SkVector innerRad{ dimensions.fWidth / 2.5f, dimensions.fHeight / 2.5f };
    const float kAnglePerTooth = 2.0f * SK_ScalarPI / (3 * numTeeth);

    float angle = 0.0f;

    SkPath tmp;
    tmp.setFillType(SkPathFillType::kWinding);

    tmp.moveTo(gen_pt(angle, outerRad));

    for (int i = 0; i < numTeeth; ++i, angle += 3*kAnglePerTooth) {
        tmp.lineTo(gen_pt(angle+kAnglePerTooth, outerRad));
        tmp.lineTo(gen_pt(angle+(1.5f*kAnglePerTooth), innerRad));
        tmp.lineTo(gen_pt(angle+(2.5f*kAnglePerTooth), innerRad));
        tmp.lineTo(gen_pt(angle+(3.0f*kAnglePerTooth), outerRad));
    }

    tmp.close();

    float fInnerRad = 0.1f * std::min(dimensions.fWidth, dimensions.fHeight);
    if (fInnerRad > 0.5f) {
        tmp.addCircle(0.0f, 0.0f, fInnerRad, SkPathDirection::kCCW);
    }

    return tmp;
}

// Render one level of a mipmap
SkBitmap render_level(SkISize dimensions, SkColor color, SkColorType colorType, bool opaque) {
    SkPath path = make_gear(dimensions, 9);

    SkImageInfo ii = SkImageInfo::Make(dimensions.width(), dimensions.height(),
                                       colorType, opaque ? kOpaque_SkAlphaType
                                                         : kPremul_SkAlphaType);
    SkBitmap bm;
    bm.allocPixels(ii);

    bm.eraseColor(opaque ? SK_ColorBLACK : SK_ColorTRANSPARENT);

    SkCanvas c(bm);

    SkPaint paint;
    paint.setColor(color | 0xFF000000);
    paint.setAntiAlias(false);

    c.translate(dimensions.width() / 2.0f, dimensions.height() / 2.0f);
    c.drawPath(path, paint);

    return bm;
}

// Create the compressed data blob needed to represent a mipmapped 2-color texture of the specified
// compression format. In this case 2-color means either opaque black or transparent black plus
// one other color.
// Note that ETC1/ETC2_RGB8_UNORM only supports 565 opaque textures.
static sk_sp<SkData> make_compressed_data(SkISize dimensions,
                                          SkColorType colorType,
                                          bool opaque,
                                          SkImage::CompressionType compression) {
    size_t totalSize = SkCompressedDataSize(compression, dimensions, nullptr, true);

    sk_sp<SkData> tmp = SkData::MakeUninitialized(totalSize);
    char* pixels = (char*) tmp->writable_data();

    int numMipLevels = SkMipMap::ComputeLevelCount(dimensions.width(), dimensions.height()) + 1;

    size_t offset = 0;

    // Use a different color for each mipmap level so we can visually evaluate the draws
    static const SkColor kColors[] = {
        SK_ColorRED,
        SK_ColorGREEN,
        SK_ColorBLUE,
        SK_ColorCYAN,
        SK_ColorMAGENTA,
        SK_ColorYELLOW,
        SK_ColorWHITE,
    };

    for (int i = 0; i < numMipLevels; ++i) {
        size_t levelSize = SkCompressedDataSize(compression, dimensions, nullptr, false);

        SkBitmap bm = render_level(dimensions, kColors[i%7], colorType, opaque);
        if (compression == SkImage::CompressionType::kETC2_RGB8_UNORM) {
            SkASSERT(bm.colorType() == kRGB_565_SkColorType);
            SkASSERT(opaque);

            if (etc1_encode_image((unsigned char*)bm.getAddr16(0, 0),
                                  bm.width(), bm.height(), 2, bm.rowBytes(),
                                  (unsigned char*) &pixels[offset])) {
                return nullptr;
            }
        } else {
            GrTwoColorBC1Compress(bm.pixmap(), kColors[i%7], &pixels[offset]);
        }

        offset += levelSize;
        dimensions = {std::max(1, dimensions.width()/2), std::max(1, dimensions.height()/2)};
    }

    return tmp;
}

// Basic test of Ganesh's ETC1 and BC1 support
// The layout is:
//               ETC2                BC1
//         --------------------------------------
//  RGB8  | kETC2_RGB8_UNORM  | kBC1_RGB8_UNORM  |
//        |--------------------------------------|
//  RGBA8 |                   | kBC1_RGBA8_UNORM |
//         --------------------------------------
//
// The nonPowerOfTwo and nonMultipleOfFour cases exercise some compression edge cases.
class CompressedTexturesGM : public skiagm::GM {
public:
    enum class Type {
        kNormal,
        kNonPowerOfTwo,
        kNonMultipleOfFour
    };

    CompressedTexturesGM(Type type) : fType(type) {
        this->setBGColor(0xFFCCCCCC);

        switch (fType) {
            case Type::kNonPowerOfTwo:
                // These dimensions force the top two mip levels to be 1x3 and 1x1
                fImgDimensions.set(20, 60);
                break;
            case Type::kNonMultipleOfFour:
                // These dimensions force the top three mip levels to be 1x7, 1x3 and 1x1
                fImgDimensions.set(13, 61); // prime numbers - just bc
                break;
            default:
                fImgDimensions.set(kBaseTexWidth, kBaseTexHeight);
                break;
        }

    }

protected:
    SkString onShortName() override {
        SkString name("compressed_textures");

        if (fType == Type::kNonPowerOfTwo) {
            name.append("_npot");
        } else if (fType == Type::kNonMultipleOfFour) {
            name.append("_nmof");
        }

        return name;
    }

    SkISize onISize() override {
        return SkISize::Make(2*kCellWidth + 3*kPad, 2*kBaseTexHeight + 3*kPad);
    }

    void onOnceBeforeDraw() override {
        fOpaqueETC2Data = make_compressed_data(fImgDimensions, kRGB_565_SkColorType, true,
                                               SkImage::CompressionType::kETC2_RGB8_UNORM);

        fOpaqueBC1Data = make_compressed_data(fImgDimensions, kRGBA_8888_SkColorType, true,
                                              SkImage::CompressionType::kBC1_RGB8_UNORM);

        fTransparentBC1Data = make_compressed_data(fImgDimensions, kRGBA_8888_SkColorType, false,
                                                   SkImage::CompressionType::kBC1_RGBA8_UNORM);
    }

    void onDraw(SkCanvas* canvas) override {
        GrContext* context = canvas->getGrContext();

        this->drawCell(context, canvas, fOpaqueETC2Data,
                       SkImage::CompressionType::kETC2_RGB8_UNORM, { kPad, kPad });

        this->drawCell(context, canvas, fOpaqueBC1Data,
                       SkImage::CompressionType::kBC1_RGB8_UNORM, { 2*kPad + kCellWidth, kPad });

        this->drawCell(context, canvas, fTransparentBC1Data,
                       SkImage::CompressionType::kBC1_RGBA8_UNORM,
                       { 2*kPad + kCellWidth, 2*kPad + kBaseTexHeight });
    }

private:
    void drawCell(GrContext* context, SkCanvas* canvas, sk_sp<SkData> data,
                  SkImage::CompressionType compression, SkIVector offset) {

        sk_sp<SkImage> image;
        if (context) {
            image = SkImage::MakeTextureFromCompressed(context, std::move(data),
                                                       fImgDimensions.width(),
                                                       fImgDimensions.height(),
                                                       compression, GrMipMapped::kYes);
        } else {
            image = SkImage::MakeRasterFromCompressed(std::move(data),
                                                      fImgDimensions.width(),
                                                      fImgDimensions.height(),
                                                      compression);
        }
        if (!image) {
            return;
        }

        SkISize levelDimensions = fImgDimensions;
        int numMipLevels = SkMipMap::ComputeLevelCount(levelDimensions.width(),
                                                       levelDimensions.height()) + 1;

        SkPaint imagePaint;
        imagePaint.setFilterQuality(kHigh_SkFilterQuality); // to force mipmapping

        bool isCompressed = false;
        if (image->isTextureBacked()) {
            const GrCaps* caps = context->priv().caps();

            GrTextureProxy* proxy = as_IB(image)->peekProxy();
            isCompressed = caps->isFormatCompressed(proxy->backendFormat());
        }

        SkPaint redStrokePaint;
        redStrokePaint.setColor(SK_ColorRED);
        redStrokePaint.setStyle(SkPaint::kStroke_Style);

        for (int i = 0; i < numMipLevels; ++i) {
            SkRect r = SkRect::MakeXYWH(offset.fX, offset.fY,
                                        levelDimensions.width(), levelDimensions.height());

            canvas->drawImageRect(image, r, &imagePaint);
            if (!isCompressed) {
                // Make it obvious which drawImages used decompressed images
                canvas->drawRect(r, redStrokePaint);
            }

            if (i == 0) {
                offset.fX += levelDimensions.width()+1;
            } else {
                offset.fY += levelDimensions.height()+1;
            }

            levelDimensions = {std::max(1, levelDimensions.width()/2),
                               std::max(1, levelDimensions.height()/2)};
        }
    }

    static const int kPad = 8;
    static const int kBaseTexWidth = 64;
    static const int kCellWidth = 1.5f * kBaseTexWidth;
    static const int kBaseTexHeight = 64;

    Type          fType;
    SkISize       fImgDimensions;
    sk_sp<SkData> fOpaqueETC2Data;
    sk_sp<SkData> fOpaqueBC1Data;
    sk_sp<SkData> fTransparentBC1Data;

    typedef GM INHERITED;
};

//////////////////////////////////////////////////////////////////////////////

DEF_GM(return new CompressedTexturesGM(CompressedTexturesGM::Type::kNormal);)
DEF_GM(return new CompressedTexturesGM(CompressedTexturesGM::Type::kNonPowerOfTwo);)
DEF_GM(return new CompressedTexturesGM(CompressedTexturesGM::Type::kNonMultipleOfFour);)

#endif


text:
package org.rapidoid.u;

import org.rapidoid.RapidoidThing;

import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.CancellationException;

/**
 * @author Nikolche Mihajlovski
 * @since 2.0.0
 */
public class U extends RapidoidThing {

    private static final int PRINTABLE_ARR_MAX_SIZE = 30;

    @SuppressWarnings("ImplicitArrayToString")
    public static String str(Object obj) {

        if (obj instanceof String) {
            return (String) obj;

        } else if (obj == null) {
            return null;

        } else if (obj instanceof byte[]) {
            byte[] arr = (byte[]) obj;
            return arr.length < PRINTABLE_ARR_MAX_SIZE ? Arrays.toString(arr) : arr.toString();

        } else if (obj instanceof short[]) {
            short[] arr = (short[]) obj;
            return arr.length < PRINTABLE_ARR_MAX_SIZE ? Arrays.toString(arr) : arr.toString();

        } else if (obj instanceof int[]) {
            int[] arr = (int[]) obj;
            return arr.length < PRINTABLE_ARR_MAX_SIZE ? Arrays.toString(arr) : arr.toString();

        } else if (obj instanceof long[]) {
            long[] arr = (long[]) obj;
            return arr.length < PRINTABLE_ARR_MAX_SIZE ? Arrays.toString(arr) : arr.toString();

        } else if (obj instanceof float[]) {
            float[] arr = (float[]) obj;
            return arr.length < PRINTABLE_ARR_MAX_SIZE ? Arrays.toString(arr) : arr.toString();

        } else if (obj instanceof double[]) {
            double[] arr = (double[]) obj;
            return arr.length < PRINTABLE_ARR_MAX_SIZE ? Arrays.toString(arr) : arr.toString();

        } else if (obj instanceof boolean[]) {
            boolean[] arr = (boolean[]) obj;
            return arr.length < PRINTABLE_ARR_MAX_SIZE ? Arrays.toString(arr) : arr.toString();

        } else if (obj instanceof char[]) {
            char[] arr = (char[]) obj;
            return arr.length < PRINTABLE_ARR_MAX_SIZE ? Arrays.toString(arr) : arr.toString();

        } else if (obj instanceof Object[]) {
            Object[] arr = (Object[]) obj;
            return arr.length < PRINTABLE_ARR_MAX_SIZE ? str(arr) : arr.toString();

        } else {
            return String.valueOf(obj);
        }
    }

    public static String str(Object[] objs) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");

        for (int i = 0; i < objs.length; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append(str(objs[i]));
        }

        sb.append("]");

        return sb.toString();
    }

    public static String str(Iterable<Object> coll) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");

        boolean first = true;

        for (Object obj : coll) {
            if (!first) {
                sb.append(", ");
            }

            sb.append(str(obj));
            first = false;
        }

        sb.append("]");
        return sb.toString();
    }

    public static String str(Iterator<?> it) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");

        boolean first = true;

        while (it.hasNext()) {
            if (first) {
                sb.append(", ");
                first = false;
            }

            sb.append(str(it.next()));
        }

        sb.append("]");

        return sb.toString();
    }

    public static String frmt(String format, Object... args) {
        for (int i = 0; i < args.length; i++) {
            if (!(args[i] instanceof Number)) {
                args[i] = str(args[i]);
            }
        }

        return String.format(format, args);
    }

    public static void print(Object... values) {
        String text;

        if (values != null) {
            text = values.length == 1 ? str(values[0]) : str(values);
        } else {
            text = "null";
        }

        System.out.println(text);
    }

    @SuppressWarnings({"varargs"})
    public static <T> String join(String sep, T... items) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < items.length; i++) {
            if (i > 0) {
                sb.append(sep);
            }
            sb.append(items[i]);
        }

        return sb.toString();
    }

    public static String join(String sep, Iterable<?> items) {
        StringBuilder sb = new StringBuilder();

        int i = 0;
        Iterator<?> it = items.iterator();
        while (it.hasNext()) {
            Object item = it.next();
            if (i > 0) {
                sb.append(sep);
            }

            sb.append(item);
            i++;
        }

        return sb.toString();
    }

    public static String join(String sep, char[][] items) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < items.length; i++) {
            if (i > 0) {
                sb.append(sep);
            }
            sb.append(items[i]);
        }

        return sb.toString();
    }

    public static <T> Iterator<T> iterator(T[] arr) {
        return Arrays.asList(arr).iterator();
    }

    @SuppressWarnings({"varargs"})
    public static <T> T[] array(T... items) {
        return items;
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] arrayOf(Class<T> type, T... elements) {
        T[] array = (T[]) Array.newInstance(type, elements.length);
        System.arraycopy(elements, 0, array, 0, elements.length);
        return array;
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] arrayOf(Class<T> type, Iterable<? extends T> items) {
        Collection<T> coll = (items instanceof Collection) ? (Collection<T>) items : list(items);

        T[] array = (T[]) Array.newInstance(type, coll.size());

        coll.toArray(array);
        return array;
    }

    @SuppressWarnings("unchecked")
    public static <T> T[] arrayOf(Iterable<? extends T> items) {
        Iterator<? extends T> it = items.iterator();

        must(it.hasNext(), "Cannot infer the array type from empty collection!");
        Class<T> type = (Class<T>) it.next().getClass();

        return arrayOf(type, items);
    }

    public static Object[] array(Iterable<?> items) {
        return (items instanceof Collection) ? ((Collection<?>) items).toArray() : list(items).toArray();
    }

    public static <T> Set<T> set() {
        return new LinkedHashSet<>();
    }

    public static <T> Set<T> set(Iterable<? extends T> values) {
        Set<T> set = set();

        for (T val : values) {
            set.add(val);
        }

        return set;
    }

    @SuppressWarnings({"varargs"})
    public static <T> Set<T> set(T... values) {
        Set<T> set = set();

        Collections.addAll(set, values);

        return set;
    }

    public static <T> List<T> list() {
        return new ArrayList<>();
    }

    public static <T> List<T> list(Iterable<? extends T> values) {
        List<T> list = list();

        for (T item : values) {
            list.add(item);
        }

        return list;
    }

    @SuppressWarnings({"varargs"})
    public static <T> List<T> list(T... values) {
        List<T> list = list();

        Collections.addAll(list, values);

        return list;
    }

    public static <K, V> Map<K, V> map() {
        return new LinkedHashMap<>();
    }

    public static <K, V> Map<K, V> map(Map<? extends K, ? extends V> src) {
        Map<K, V> map = map();
        map.putAll(src);
        return map;
    }

    public static <K, V> Map<K, V> map(K key, V value) {
        Map<K, V> map = map();
        map.put(key, value);
        return map;
    }

    public static <K, V> Map<K, V> map(K key1, V value1, K key2, V value2) {
        Map<K, V> map = map(key1, value1);
        map.put(key2, value2);
        return map;
    }

    public static <K, V> Map<K, V> map(K key1, V value1, K key2, V value2, K key3, V value3) {
        Map<K, V> map = map(key1, value1, key2, value2);
        map.put(key3, value3);
        return map;
    }

    public static <K, V> Map<K, V> map(K key1, V value1, K key2, V value2, K key3, V value3, K key4, V value4) {
        Map<K, V> map = map(key1, value1, key2, value2, key3, value3);
        map.put(key4, value4);
        return map;
    }

    public static <K, V> Map<K, V> map(K key1, V value1, K key2, V value2, K key3, V value3, K key4, V value4, K key5,
                                       V value5) {
        Map<K, V> map = map(key1, value1, key2, value2, key3, value3, key4, value4);
        map.put(key5, value5);
        return map;
    }

    @SuppressWarnings("unchecked")
    public static <K, V> Map<K, V> map(Object... keysAndValues) {
        must(keysAndValues.length % 2 == 0, "Incorrect number of arguments (expected key-value pairs)!");

        Map<K, V> map = map();

        for (int i = 0; i < keysAndValues.length / 2; i++) {
            map.put((K) keysAndValues[i * 2], (V) keysAndValues[i * 2 + 1]);
        }

        return map;
    }

    public static <T> T or(T value, T fallback) {
        return value != null ? value : fallback;
    }

    public static <T> T or(T value, T fallback1, T fallback2) {
        return value != null ? value : fallback1 != null ? fallback1 : fallback2;
    }

    public static <T> T or(T value, T fallback1, T fallback2, T fallback3) {
        return value != null ? value : fallback1 != null ? fallback1 : fallback2 != null ? fallback2 : fallback3;
    }

    public static String safe(String s) {
        return or(s, "");
    }

    public static boolean safe(Boolean b) {
        return or(b, false);
    }

    public static int safe(Integer num) {
        return or(num, 0);
    }

    public static long safe(Long num) {
        return or(num, 0L);
    }

    public static byte safe(Byte num) {
        return or(num, (byte) 0);
    }

    public static float safe(Float num) {
        return or(num, 0.0f);
    }

    public static double safe(Double num) {
        return or(num, 0.0);
    }

    public static Object[] safe(Object[] arr) {
        return arr != null ? arr : new Object[0];
    }

    public static <T> List<T> safe(List<T> list) {
        return list != null ? list : U.list();
    }

    public static <T> Set<T> safe(Set<T> set) {
        return set != null ? set : U.set();
    }

    public static <T> Collection<T> safe(Collection<T> coll) {
        return coll != null ? coll : U.list();
    }

    public static <K, V> Map<K, V> safe(Map<K, V> map) {
        return map != null ? map : U.map();
    }

    public static long time() {
        return System.currentTimeMillis();
    }

    public static boolean timedOut(long since, long timeout) {
        return U.time() - since > timeout;
    }

    public static boolean eq(Object a, Object b) {
        return a == null ? b == null : a.equals(b);
    }

    public static boolean neq(Object a, Object b) {
        return !eq(a, b);
    }

    public static RuntimeException rte(String message) {
        return new RuntimeException(message);
    }

    public static RuntimeException rte(String message, Throwable cause) {
        return new RuntimeException(message, cause);
    }

    public static RuntimeException rte(Throwable cause) {
        return rte("", cause);
    }

    public static RuntimeException rte(String message, Object... args) {
        return rte(frmt(message, args));
    }

    public static RuntimeException rte(String message, Throwable cause, Object... args) {
        return rte(frmt(message, args), cause);
    }

    public static IllegalArgumentException illegal(String message, Object... args) {
        return new IllegalArgumentException(frmt(message, args));
    }

    public static boolean must(boolean expectedCondition, String message) {
        if (!expectedCondition) {
            throw illegal(message);
        }
        return true;
    }

    public static boolean must(boolean expectedCondition) {
        if (!expectedCondition) {
            throw illegal("Expectation failed!");
        }
        return true;
    }

    public static boolean must(boolean expectedCondition, String message, long arg) {
        if (!expectedCondition) {
            throw illegal(message, arg);
        }
        return true;
    }

    public static boolean must(boolean expectedCondition, String message, Object arg) {
        if (!expectedCondition) {
            throw illegal(message, str(arg));
        }
        return true;
    }

    public static boolean must(boolean expectedCondition, String message, Object arg1, Object arg2) {
        if (!expectedCondition) {
            throw illegal(message, str(arg1), str(arg2));
        }
        return true;
    }

    public static boolean must(boolean expectedCondition, String message, Object arg1, Object arg2, Object arg3) {
        if (!expectedCondition) {
            throw illegal(message, str(arg1), str(arg2), str(arg3));
        }
        return true;
    }

    public static <T> T notNull(T value, String msgOrDesc, Object... descArgs) {
        if (value == null) {
            throw illegal("%s must NOT be null!", frmt(msgOrDesc, descArgs));
        }

        return value;
    }

    public static boolean isEmpty(String value) {
        return value == null || value.isEmpty();
    }

    public static boolean isEmpty(Object[] arr) {
        return arr == null || arr.length == 0;
    }

    public static boolean isEmpty(Collection<?> coll) {
        return coll == null || coll.isEmpty();
    }

    public static boolean isEmpty(Iterable<?> iter) {
        return iter.iterator().hasNext();
    }

    public static boolean isEmpty(Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

    public static boolean isEmpty(Object value) {
        if (value == null) {
            return true;
        } else if (value instanceof String) {
            return isEmpty((String) value);
        } else if (value instanceof byte[]) {
            return ((byte[]) value).length == 0;
        } else if (value instanceof short[]) {
            return ((short[]) value).length == 0;
        } else if (value instanceof int[]) {
            return ((int[]) value).length == 0;
        } else if (value instanceof long[]) {
            return ((long[]) value).length == 0;
        } else if (value instanceof float[]) {
            return ((float[]) value).length == 0;
        } else if (value instanceof double[]) {
            return ((double[]) value).length == 0;
        } else if (value instanceof boolean[]) {
            return ((boolean[]) value).length == 0;
        } else if (value instanceof char[]) {
            return ((char[]) value).length == 0;
        } else if (value instanceof Object[]) {
            return ((Object[]) value).length == 0;
        } else if (value instanceof Collection<?>) {
            return isEmpty((Collection<?>) value);
        } else if (value instanceof Map<?, ?>) {
            return isEmpty((Map<?, ?>) value);
        } else if (value instanceof Iterable<?>) {
            return isEmpty((Iterable<?>) value);
        }
        return false;
    }

    public static boolean notEmpty(String value) {
        return !isEmpty(value);
    }

    public static boolean notEmpty(Object[] arr) {
        return !isEmpty(arr);
    }

    public static boolean notEmpty(Collection<?> coll) {
        return !isEmpty(coll);
    }

    public static boolean notEmpty(Iterable<?> iter) {
        return !isEmpty(iter);
    }

    public static boolean notEmpty(Map<?, ?> map) {
        return !isEmpty(map);
    }

    public static boolean notEmpty(Object value) {
        return !isEmpty(value);
    }

    public static int num(String s) {
        return Integer.parseInt(s);
    }

    public static boolean bool(Object o) {
        return Boolean.TRUE.equals(o);
    }

    public static int limit(int min, int value, int max) {
        return Math.min(Math.max(min, value), max);
    }

    public static long limit(long min, long value, long max) {
        return Math.min(Math.max(min, value), max);
    }

    public static <T> T single(Iterable<T> coll) {
        Iterator<T> it = coll.iterator();
        must(it.hasNext(), "Expected exactly 1 item, but didn't find any!");
        T item = it.next();
        must(!it.hasNext(), "Expected exactly 1 item, but found more than 1!");
        return item;
    }

    public static <T> T singleOrNone(Iterable<T> coll) {
        Iterator<T> it = coll.iterator();
        T item = it.hasNext() ? it.next() : null;
        must(!it.hasNext(), "Expected 0 or 1 items, but found more than 1!");
        return item;
    }

    public static <T> T first(T[] values) {
        return values != null && values.length > 0 ? values[0] : null;
    }

    public static <T> T first(List<T> values) {
        return values != null && values.size() > 0 ? values.get(0) : null;
    }

    public static <T> T last(T[] values) {
        return values != null && values.length > 0 ? values[values.length - 1] : null;
    }

    public static <T> T last(List<T> values) {
        return values != null && values.size() > 0 ? values.get(values.size() - 1) : null;
    }

    @SuppressWarnings("unchecked")
    public static <T> int compare(T val1, T val2) {
        if (val1 == null && val2 == null) {
            return 0;
        } else if (val1 == null) {
            return -1;
        } else if (val2 == null) {
            return 1;
        } else {
            return ((Comparable<T>) val1).compareTo(val2);
        }
    }

    /**
     * Sleeps (calling Thread.sleep) for the specified period.
     * <p>
     * If the thread is interrupted while sleeping, throws {@link CancellationException} to propagate the interruption.
     *
     * @param millis the length of time to sleep in milliseconds.
     */
    public static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new CancellationException();
        }
    }

    /**
     * Simpler casts, less warnings.
     */
    @SuppressWarnings("unchecked")
    public static <T> T cast(Object value) {
        return (T) value;
    }

    public static <T> List<List<T>> groupsOf(int groupSize, Iterable<T> items) {
        List<List<T>> segments = list();
        Iterator<T> it = items.iterator();

        while (it.hasNext()) {
            List<T> segment = list();

            for (int i = 0; i < groupSize; i++) {
                if (it.hasNext()) {
                    segment.add(it.next());
                }
            }

            segments.add(segment);
        }

        return segments;
    }

    public static <T> List<List<T>> groupsOf(int groupSize, T... items) {
        return groupsOf(groupSize, list(items));
    }

}


text:
var JSON2 = require('./json2');
var cycle = require('./cycle');

JSON2.decycle = cycle.decycle;
JSON2.retrocycle = cycle.retrocycle;

module.exports = JSON2;


text:
[![Cookbook Version](https://img.shields.io/cookbook/v/golang.svg?style=flat)](https://supermarket.chef.io/cookbooks/golang)
[![CI State](https://github.com/sous-chefs/golang/workflows/ci/badge.svg)](https://github.com/sous-chefs/golang/actions?query=workflow%3Aci)
[![OpenCollective](https://opencollective.com/sous-chefs/backers/badge.svg)](#backers)
[![OpenCollective](https://opencollective.com/sous-chefs/sponsors/badge.svg)](#sponsors)
[![License](https://img.shields.io/badge/License-Apache%202.0-green.svg)](https://opensource.org/licenses/Apache-2.0)

## Description

Chef cookbook for the [Go programming language](http://golang.org/).

## Requirements

### Platform

* Ubuntu >= 18.04
* Debian >= 8
* CentOS >= 7

## Usage

### golang::default

Include `golang` in your node's `run_list`:

```json
{
  "name":"my_node",
  "run_list": [
    "recipe[golang]"
  ]
}
```

### golang::packages

To install Go packages using node attributes add the packages to the `['golang']['packages']` attribute:

```json
{
  "name":"my_node",
  "golang": {
    "packages": [
      "github.com/go-check/check"
    ]
  },
  "run_list": [
    "recipe[golang]"
  ]
}
```

## Contributors

This project exists thanks to all the people who [contribute.](https://opencollective.com/sous-chefs/contributors.svg?width=890&button=false)

### Backers

Thank you to all our backers!

![https://opencollective.com/sous-chefs#backers](https://opencollective.com/sous-chefs/backers.svg?width=600&avatarHeight=40)

### Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website.

![https://opencollective.com/sous-chefs/sponsor/0/website](https://opencollective.com/sous-chefs/sponsor/0/avatar.svg?avatarHeight=100)
![https://opencollective.com/sous-chefs/sponsor/1/website](https://opencollective.com/sous-chefs/sponsor/1/avatar.svg?avatarHeight=100)
![https://opencollective.com/sous-chefs/sponsor/2/website](https://opencollective.com/sous-chefs/sponsor/2/avatar.svg?avatarHeight=100)
![https://opencollective.com/sous-chefs/sponsor/3/website](https://opencollective.com/sous-chefs/sponsor/3/avatar.svg?avatarHeight=100)
![https://opencollective.com/sous-chefs/sponsor/4/website](https://opencollective.com/sous-chefs/sponsor/4/avatar.svg?avatarHeight=100)
![https://opencollective.com/sous-chefs/sponsor/5/website](https://opencollective.com/sous-chefs/sponsor/5/avatar.svg?avatarHeight=100)
![https://opencollective.com/sous-chefs/sponsor/6/website](https://opencollective.com/sous-chefs/sponsor/6/avatar.svg?avatarHeight=100)
![https://opencollective.com/sous-chefs/sponsor/7/website](https://opencollective.com/sous-chefs/sponsor/7/avatar.svg?avatarHeight=100)
![https://opencollective.com/sous-chefs/sponsor/8/website](https://opencollective.com/sous-chefs/sponsor/8/avatar.svg?avatarHeight=100)
![https://opencollective.com/sous-chefs/sponsor/9/website](https://opencollective.com/sous-chefs/sponsor/9/avatar.svg?avatarHeight=100)


text:
import * as internal from "./internal.js";

declare const SelectionInViewMixin: Mixin<
  {},
  {
    scrollItemIntoView(item: Element): void;
    [internal.scrollTarget]: Element;
  }
>;

export default SelectionInViewMixin;


text:
/* DOES THIS HELP AUTOSIZING? */
.admin .users {
	height: auto !important;
}

.admin .users .tabTitle {
	background-color: #264eea;
	text-align: center !important;
	vertical-align: middle;
	font-size: 20px;
	font-stretch: expanded;
	font-weight: bold;
	color: #FFF;
}

.admin .users .label {
	text-align:	center !important;
	font-weight: bolder;
	font-size: 18px;
	font-family: Verdana;
	font-size: 14px;
	font-style: oblique;
	height: 20px;
	vertical-align: bottom !important;
	background: #EEE;
}

.admin .users .refresh {
	width: 20px !important;
	background-image: url(../../../plugins/cloud/images/app-18.png);
	text-indent: 22px;
	background-repeat: no-repeat;
	height: 18px;
	background: #EEE;
}

.admin .users .addUserButton {
	font-size: 14px;
	color: #224;
}

.admin .users .username,
.admin .users .firstname,
.admin .users .lastname,
.admin .users .email,
.admin .users .password
{
	font-size: 14px;
	color: #444;
	text-align: left !important;
	vertical-align: middle !important;
	font-style: oblique;
	font-weight: bolder !important;
	padding-top: 4px;
}

.admin .users .invalid ,
.admin .users .firstname .dijitTextArea .invalid,
.admin .users .lastname .dijitTextArea .invalid,
.admin .users .email .dijitTextArea .invalid
{
	border: 2px solid #F00 !important;
}

.admin .users .editUserRow {
	width: 100%;
	height: 20px !important;
}

.admin .users .dragSource .username {
	font-size: 14px;
	color: darkred;
	font-weight: bolder;
	text-align: left !important;

	background-image: url(../../../plugins/cloud/images/user-18.png);
	text-indent: 22px;
	background-repeat: no-repeat;
	height: 18px;
}

.admin .users .dragSource {
	-moz-background-clip:			border;
	-moz-background-inline-policy:	continuous;
	-moz-background-origin:			padding;
	border-radius:	8pt;
	border-radius-bottomright:	8pt;
	border-radius:		8pt;
	border-radius-topright:	8pt;

	background:#FFFFFF none repeat scroll 0 0;
	border:3px solid #CCCCCC;
	cursor:default;
	padding:1em 0.5em;

	/*margin-top: 5px;*/
	width: 120px;
	height: 260px;
	min-height: 100px;

	text-align: left !important;
	font-family: Verdana;
	font-size: 12px;
	border-color: #333;

	/* NEEDED SO THAT SCROLLBAR WILL SHOW */
	display: block !important;
	overflow:auto !important;
}

.admin .users .dragSource .firstname,
.admin .users .dragSource .lastname {
	font-size: 14px;
	font-weight: bold;
	text-align: left !important;
}

.admin .users .dragSource .email {
	font-weight: normal;
	font-size: 12px;
	text-align: left !important;
}

.admin .users .dragSource .password {
	color: #000;
	font-weight: normal;
	font-size: 12px;
	font-style: italic;
	text-align: left !important;
}

.admin .users .trash {
	-moz-background-clip:border;
	-moz-background-inline-policy:continuous;
	-moz-background-origin:padding;
	border-radius:8pt;
	background:#FFFFFF none repeat scroll 0 0;
	border:3px solid #CCCCCC;
	cursor:default;
	padding:1em 0.5em;

	margin-top: 5px;
	width: 150px;
	height: 60px;
	text-align: center;
	vertical-align: middle;
}

.admin .users .trashIcon {
	height: 100%;
	width: 100px;
	margin-left: auto;
	margin-right: auto;

	background-image: url(../../../plugins/cloud/images/trash-60.png);
	background-repeat: no-repeat;

}


text:
import re

class synonyms:

    def __init__(self):

        list_from   = "ŞüÉéçčňİışíáñóåäöÅÄÖłŁęøéú"
        list_to     = "SuEeccnIisianoaaoAAOlLeoeu"

        self.trans_list = str.maketrans(list_from, list_to)

        self.characters_to_remove = ["'", ".", "*"]

        self.characters_to_replace = [
                ("æ", "ae"),
                ("-", " ")]

    def sanitize_characters(self, string):

        for char in self.characters_to_remove:
            string = string.replace(char, "")

        for (old, new) in self.characters_to_replace:
            string = string.replace(old, new)

        return string.translate(self.trans_list)

    def sanitize_ixes(self, string):

        for (old, new) in self.prefixes:
            string = re.sub("^" + old, new, string, flags=re.IGNORECASE)

        for (old, new) in self.suffixes:
            string = re.sub(old + "$", new, string, flags=re.IGNORECASE)

        year_regex = '\s[0-9]{2,}$|^[0-9]{2,}\s'

        return re.sub(year_regex, "", string)

    def get_synonym(self, string):

        before = string

        string = self.sanitize_characters(string)

        if string in self.synonym_list:
            string = self.synonym_list[string]

        after = self.sanitize_ixes(string)

        if before != after:
            self.log.write("%s -> %s\n" % (before, after))

        return after