text: var disqus_developer = 0;

redpajama_set_name: RedPajamaGithub


text:
<ParaViewFilters>
 <Category name="Objectivity">
  <Filter name="Fracture Trace"/>
  <Filter name="DUMMY_FILTER"/>
 </Category>
</ParaViewFilters>


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="
  http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:property-placeholder location="classpath:serviceconfig/olat.properties, classpath:olat.local.properties" />

<bean id="collaborationToolsFactory" class="org.olat.collaboration.CollaborationToolsFactory"
depends-on="instantMessagingModule" >
	<constructor-arg ref="coordinatorManager" />
</bean>

<!-- TODO: add im property enabled here -->

</beans>


text:
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Exception_1 = require("./Exception");
/**
 * Represents an error that occurs when a service operation fails locally (e.g. validation error).
 */
var ServiceLocalException = (function (_super) {
    __extends(ServiceLocalException, _super);
    function ServiceLocalException(message, innerException) {
        if (message === void 0) { message = null; }
        if (innerException === void 0) { innerException = null; }
        _super.call(this, message, innerException);
    }
    return ServiceLocalException;
}(Exception_1.Exception));
exports.ServiceLocalException = ServiceLocalException;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>fonten</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="have your own realtime font subsetter">
    <meta name="author" content="Shih-Wen Su">

    <link href="/css/bootstrap.min.css" rel="stylesheet">

    <link href="/css/bootstrap-responsive.min.css" rel="stylesheet">

中文

Demo

Github

fonten

fonten

 - have your own realtime font subsetter -

Why fonten?

            The online and real time fonten builds a much smaller size font file that contains only specified characters. One runs a fonten server that hosts all his or her favorite fonts and builds subset font file on the fly. For Chinese fonts, the subset font file built by fonten is only a few KB, which is less than 1/1000 of the original size (10~20MB). What makes it even better? It's open source!

How to use?

            To be specific, fonten contains a server side runtime provides dynamic font files and a set of APIs for the client. You need to host your own fonten server and upload authorized fonts to the server to make it work. We don't have a centralized server and we don't provide orginal fonts. Your fonten server can be hosted on Google App Engine/Java for free, and don't worry, you don't need to know how to write Java.

            about GAE's free quota

Example Usage

  @font-face{
    font-family: myfont;
    src: url('/font?id=opensans&text=SomeCharaters&format=eot');
  }

Install fonten server

 Start a Google App Engine (GAE) project, say my_gae_project.

 Download and install GAE for Java

 Download fonten git clone git://github.com/flyakite/fonten.git

 Change application name in appengine-web.xml to my_gae_project and import the project to GAE.

 Deploy it to GAE server. Your server is now at http://my_gae_project.appspot.com/

 Go to http://my_gae_project.appspot.com/fontlist and upload your font file.

Simple API (GET API)

            Use Simple API if you only need not so many characters ( ~<2000 for Ascii and ~<200 for encoded Chinese characters to comply with IE's URL limit)

            Request to your server's /font with following parameters to get the font:

id

Font id, this is the same as you specified when you upload your font

text

Input character set. The subset font file can be cached and reused better if the input characters are unique and sorted.

format

Font format. "eot" or "woff". If not specified, the oringal font format is served. (optional)

strip

Strip hinting. Usually available in truetype font(.ttf). Default is true, set to "0" to stop stripping.(optional)

            Example css:

  @font-face{
    font-family: myfont;
    src: url('/font?id=opensans&text=ABC&format=eot');
    src: local('☺');
    src: url('/font?id=opensans&text=ABC&format=woff'') format('woff');
    src: url('/font?id=opensans&text=ABC') format('truetype');
  }

Advanced API (POST API)

            Use Advanced API if you want to get subset font file with more characters. You need to post the input character set to the fonten server first, exchange a reserved token and use the token to get the font file.

            POST request to your server's/reserve to reserve a token with parameters:

text

Charaters you want with the font.

            Example javascript:

  $.ajax({
    type: 'POST',
    url: options.server + '/reserve',
    crossDomain: true,
    data: {text: text},
    dataType: 'json',
  });

              and assign the  to /font with parameters like in Simple API and the following:

token

Reserved token returned from server.

  var fontURL = "http://fonten-demo.appspot.com/font?id=opensans&token=" + reservedToken

jQuery Plugin

            Use fonten jQuery plugin to change font and interact with fonten server can should be easier. (source)

            Example 1:

  $('#selector').fonten({
    id: 'opensans'
  });

            fonten jQuery plugin options:

id

                Font ID, specified on fonten server.

                Font ID can also be specified in the html tag data-attribute.

  <div class="fonten" data-font-id="opensans">OpenSans</div>
  <div class="fonten" data-font-id="droidsans">DroidSans</div>

server

fonten server URI, default points to current server. e.g: "http://myfonten.appspot.com"

fontPath

Font path on fonten server, default is "/font"

reservePath

Font reservation path on fonten server, default is "/reserve"

strip

Whether to strip font hinting, default is true, can be set to 0 or false

success

callback function when the font is successfully loaded

error

callback function when an error occured

            Example 2:

  $.fonten({
    fontTextDict: {
      'opensans': 'ABCD'
    },
    success: function(fontID, fontFamily){
      console.log('success! start to paint my canvas');
    }
  });

fontTextDict

Sometimes, there is no element in the dom tree we want to manipulate. We just need the font to be loaded. In this situation, can specify fontTextDict as a font ID - text dictionary mapping and give it to $.fonten to load the font of the specified text.

Powered by

This project is developed based on sfntly and Google App Engine/Java.

Author

            Shih-Wen Su

            sushi@summeridea.com

             github

License

Apache 2.0


text:
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace DDS.OpenSplice.OS
{
    // from os_report.h
    [StructLayout(LayoutKind.Sequential)]
    public struct ReportInfo
    {
        // char *reportContext;
        public IntPtr reportContext;
        // char *sourceLine;
        public IntPtr sourceLine;
        // char *callStack;
        public IntPtr callStack;
        // os_int32 reportCode;
        public int reportCode;
        // char *description;
        public IntPtr description;
    }

    static internal class Report
    {
        /*
         *     os_reportInfo *
         *     os_reportGetApiInfo(void);
         */
        [DllImport("ddskernel", EntryPoint = "os_reportGetApiInfo", CallingConvention = CallingConvention.Cdecl)]
        internal static extern IntPtr GetApiInfo();
    }
}


text:
<?php

/**
 * Store grid column filter
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author     Magento Core Team <core@magentocommerce.com>
 */
class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Store
    extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    protected $_skipAllStoresLabel = false;
    protected $_skipEmptyStoresLabel = false;

    /**
     * Retrieve System Store model
     *
     * @return Mage_Adminhtml_Model_System_Store
     */
    protected function _getStoreModel()
    {
        return Mage::getSingleton('adminhtml/system_store');
    }

    /**
     * Retrieve 'show all stores label' flag
     *
     * @return bool
     */
    protected function _getShowAllStoresLabelFlag()
    {
        return $this->getColumn()->getData('skipAllStoresLabel')
            ? $this->getColumn()->getData('skipAllStoresLabel')
            : $this->_skipAllStoresLabel;
    }

    /**
     * Retrieve 'show empty stores label' flag
     *
     * @return bool
     */
    protected function _getShowEmptyStoresLabelFlag()
    {
        return $this->getColumn()->getData('skipEmptyStoresLabel')
            ? $this->getColumn()->getData('skipEmptyStoresLabel')
            : $this->_skipEmptyStoresLabel;
    }

    /**
     * Render row store views
     *
     * @param Varien_Object $row
     * @return string
     */
    public function render(Varien_Object $row)
    {
        $out = '';
        $skipAllStoresLabel = $this->_getShowAllStoresLabelFlag();
        $skipEmptyStoresLabel = $this->_getShowEmptyStoresLabelFlag();
        $origStores = $row->getData($this->getColumn()->getIndex());

        if (is_null($origStores) && $row->getStoreName()) {
            $scopes = array();
            foreach (explode("\n", $row->getStoreName()) as $k => $label) {
                $scopes[] = str_repeat(' ', $k * 3) . $label;
            }
            $out .= implode('
', $scopes) . $this->__(' [deleted]');
            return $out;
        }

        if (empty($origStores) && !$skipEmptyStoresLabel) {
            return '';
        }
        if (!is_array($origStores)) {
            $origStores = array($origStores);
        }

        if (empty($origStores)) {
            return '';
        }
        elseif (in_array(0, $origStores) && count($origStores) == 1 && !$skipAllStoresLabel) {
            return Mage::helper('adminhtml')->__('All Store Views');
        }

        $data = $this->_getStoreModel()->getStoresStructure(false, $origStores);

        foreach ($data as $website) {
            $out .= $website['label'] . '
';
            foreach ($website['children'] as $group) {
                $out .= str_repeat(' ', 3) . $group['label'] . '
';
                foreach ($group['children'] as $store) {
                    $out .= str_repeat(' ', 6) . $store['label'] . '
';
                }
            }
        }

        return $out;
    }

    /**
     * Render row store views for export
     *
     * @param Varien_Object $row
     * @return string
     */
    public function renderExport(Varien_Object $row)
    {
        $out = '';
        $skipAllStoresLabel = $this->_getShowAllStoresLabelFlag();
        $origStores = $row->getData($this->getColumn()->getIndex());

        if (is_null($origStores) && $row->getStoreName()) {
            $scopes = array();
            foreach (explode("\n", $row->getStoreName()) as $k => $label) {
                $scopes[] = str_repeat(' ', $k * 3) . $label;
            }
            $out .= implode("\r\n", $scopes) . $this->__(' [deleted]');
            return $out;
        }

        if (!is_array($origStores)) {
            $origStores = array($origStores);
        }

        if (in_array(0, $origStores) && !$skipAllStoresLabel) {
            return Mage::helper('adminhtml')->__('All Store Views');
        }

        $data = $this->_getStoreModel()->getStoresStructure(false, $origStores);

        foreach ($data as $website) {
            $out .= $website['label'] . "\r\n";
            foreach ($website['children'] as $group) {
                $out .= str_repeat(' ', 3) . $group['label'] . "\r\n";
                foreach ($group['children'] as $store) {
                    $out .= str_repeat(' ', 6) . $store['label'] . "\r\n";
                }
            }
        }

        return $out;
    }
}


text:
namespace Selenium.WebDriver.Extensions.Parsers
{
    using System.Diagnostics.CodeAnalysis;
    using static Softlr.Suppress;

    internal class NullValueParser : ParserBase
    {
        public NullValueParser()
            : base(new WebElementCollectionParser())
        {
        }

        [SuppressMessage(SONARQUBE, S4018)]
        public override TResult Parse<TResult>(object rawResult) =>
            rawResult == null ? default : Successor.Parse<TResult>(rawResult);
    }
}


text:
package scodec
package codecs

import scodec.bits.{ BitVector, ByteVector }

class StringCodecTest extends CodecSuite {

  "ascii codec" should {
    "roundtrip" in {
      roundtripAll(ascii, Seq("test", "", "with\ttabs"))
    }
  }

  "ascii32 codec" should {
    "roundtrip" in {
      roundtripAll(ascii32, Seq("test", "", "with\ttabs"))
    }
  }

  "ascii32L codec" should {
    "roundtrip" in {
      roundtripAll(ascii32L, Seq("test", "", "with\ttabs"))
    }
  }

  "cstring codec" should {

    "roundtrip" in {
      roundtripAll(cstring, Seq("test", ""))
    }

    "decode up to the first null-character" in {
      cstring.decode(ascii.encode("hello\u0000").require ++ BitVector.bit(true)) should be (Attempt.successful(DecodeResult("hello", BitVector.bit(true))))
    }

    "fail decoding with an error when buffer contains bytes unsupported by charset" in {
      cstring.decode(ascii.encode("0123456789ABCDEF").require) shouldBe Attempt.failure(Err("Does not contain a 'NUL' termination byte."))
    }

  }

  "utf8 codec" should {
    "roundtrip" in {
      roundtripAll(utf8, Seq("test", "", "with\ttabs", "withλ"))
    }
  }

  "utf8_32 codec" should {
    "roundtrip" in {
      roundtripAll(utf8_32, Seq("test", "", "with\ttabs", "withλ"))
    }
  }

  "utf8_32L codec" should {
    "roundtrip" in {
      roundtripAll(utf8_32L, Seq("test", "", "with\ttabs", "withλ"))
    }
  }

  "string codecs" should {
    "fail encoding with an error when string to encode contains chars unsupported by charset" in {
      ascii.encode("λ") shouldBe Attempt.failure(Err("US-ASCII cannot encode character 'λ'"))
      ascii.encode("Includes a λ") shouldBe Attempt.failure(Err("US-ASCII cannot encode character 'λ'"))
    }

    "fail decoding with an error when buffer contains bytes unsupported by charset" in {
      utf8.decode(BitVector(ByteVector.fromValidHex("0xf4ffffff"))) shouldBe Attempt.failure(Err("UTF-8 cannot decode string from '0xf4ffffff'"))
    }
  }
}


text:
package org.javad.pdf;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.PdfContentByte;
import java.awt.Color;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.javad.pdf.fonts.FontRegistry;
import org.javad.pdf.fonts.PdfFontDefinition;
import org.javad.pdf.model.PageConfiguration;
import org.javad.pdf.util.PdfUtil;
import org.javad.stamp.xml.XMLDefinitions;
import org.javad.xml.XMLSerializable;

/**
 *
 */
public class TitlePageContent extends PositionalContent implements XMLSerializable, IContentGenerator {

    private String title;
    private String subTitle;
    private Image image;
    private String description;
    private List<String> items = new ArrayList<>();
    private static final Logger logger = Logger.getLogger(TitlePageContent.class.getName());

    public TitlePageContent(PageConfiguration configuration) {
        super(configuration);
    }

    @Override
    public void writeToXml(XMLStreamWriter writer) throws XMLStreamException {
        if( getTitle() != null ) {
            writer.writeAttribute("title", getTitle());
        }
        if (getSubTitle() != null) {
            writer.writeAttribute("subtitle", getSubTitle());
        }
        if( getDescription() != null ) {
            writer.writeAttribute(XMLDefinitions.DESCRIPTION, getDescription());
        }
        if( !getItems().isEmpty()) {
            writer.writeStartElement(XMLDefinitions.CONTENT_ITEMS);
            for(String s: getItems()) {
                writer.writeStartElement(XMLDefinitions.ITEM);
                writer.writeCharacters(s);
                writer.writeEndElement();
            }
            writer.writeEndElement();
        }
    }

    protected com.itextpdf.text.Image determineScaledImage(Image image) throws Exception {
        com.itextpdf.text.Image img = com.itextpdf.text.Image.getInstance(image, Color.WHITE);
        if(image instanceof BufferedImage ) {
            BufferedImage bImg = (BufferedImage)image;
            int[] transparencyMask;
            if( bImg.getColorModel().getTransparency() == Transparency.TRANSLUCENT) {
                int components = bImg.getColorModel().getColorSpace().getNumComponents();
                transparencyMask = new int[components*2];
                for( int i = 0; i < transparencyMask.length; i = i + 2) {
                    transparencyMask[i] = 0;
                    transparencyMask[i+1] = 1;
                }
                img.setTransparency(transparencyMask);
            }
        }

        float vRatio = img.getHeight() / PdfUtil.convertFromMillimeters(configuration.getHeight() - configuration.getMarginTop() - configuration.getMarginBottom());
        float hRatio = img.getWidth() / PdfUtil.convertFromMillimeters(configuration.getWidth() - configuration.getMarginLeft() - configuration.getMarginRight());
        float ratio = Math.max(1.0f, Math.max(vRatio / 0.5f, hRatio / 0.5f));
        logger.log(Level.FINE, "Ratio is: {0}", ratio);
        img.scaleAbsolute(img.getWidth() / ratio, img.getHeight() / ratio);
        float x = PdfUtil.convertFromMillimeters(configuration.getMarginLeft() + ( configuration.getWidth() - configuration.getMarginLeft() - configuration.getMarginRight()) / 2) - img.getWidth() / (2 * ratio);
        float y = PdfUtil.convertFromMillimeters(configuration.getMarginBottom() + (configuration.getHeight() - configuration.getMarginTop() - configuration.getMarginBottom())/ 1.5f) - img.getHeight() / (2 * ratio);
        img.setAbsolutePosition(x, y);
        return img;
    }

    private float getWorkablePageHeight() {
    	return configuration.getHeight() - configuration.getMarginBottom() - configuration.getMarginTop();
    }

    @Override
    public OutputBounds generate(PdfContentByte content) {
        if (isSkipped()) {
            return new OutputBounds(getX(), getY(), 0, 0);
        }
        int maxWidth = 0;
        float top = getY();
        if (getImage() != null) {
            try {
                com.itextpdf.text.Image img = determineScaledImage(getImage());
                if (img != null) {
                    content.addImage(img);
                    top -= PdfUtil.convertFromMillimeters(getWorkablePageHeight() / 2 - configuration.getMarginBottom());
                    top = img.getAbsoluteY() - PdfUtil.convertFromMillimeters(25.0f);
                }
            } catch (Exception e) {
                logger.log(Level.FINER, "An error occured scaling the image. ", e);
            }
        } else {
        	top -=  PdfUtil.convertFromMillimeters(getWorkablePageHeight() / 3 - configuration.getMarginBottom());
        }
        content.setColorStroke(BaseColor.BLACK);

        Font f = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumTitle);
        content.setFontAndSize(f.getBaseFont(), f.getSize());

        content.setHorizontalScaling(110.0f);

        if(getTitle() != null && !getTitle().isEmpty()) {
            String theTitle = PdfUtil.toUpperCase(getTitle());
            maxWidth = (int) f.getBaseFont().getWidthPoint(theTitle, f.getSize());
            top += PdfUtil.renderConstrainedText(content, theTitle, f, getX(), top, maxWidth);
        }
        if (getSubTitle() != null && !getSubTitle().isEmpty()) {
            String sTitle = PdfUtil.toUpperCase(getSubTitle());
            Font subFont = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumSubtitle);
            top -= subFont.getCalculatedSize() + PdfUtil.convertFromMillimeters(3.0f);
            content.setFontAndSize(subFont.getBaseFont(), subFont.getSize());
            maxWidth = Math.max(maxWidth, (int)content.getEffectiveStringWidth(sTitle, false));
            top += PdfUtil.renderConstrainedText(content, sTitle, subFont, getX(), top, maxWidth);
        }
        if( getDescription() != null && !getDescription().isEmpty()) {
            Font subFont = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumDescription);
            top -= PdfUtil.convertFromMillimeters(15.0f);
            float width = PdfUtil.convertFromMillimeters((configuration.getWidth() - configuration.getMarginLeft() - configuration.getMarginRight()) /2 );
            content.setFontAndSize(subFont.getBaseFont(), subFont.getSize());
            top += PdfUtil.renderConstrainedText(content, getDescription(), subFont, width + PdfUtil.convertFromMillimeters(configuration.getMarginLeft()), top, (int)(width * 0.7f));
        }
        if( !getItems().isEmpty()) {
            Font subFont = FontRegistry.getInstance().getFont(PdfFontDefinition.AlbumContents);
            top -= subFont.getCalculatedSize() + PdfUtil.convertFromMillimeters(6.0f);
            content.setFontAndSize(subFont.getBaseFont(), subFont.getSize());
            for(String s: getItems() ) {
                maxWidth = Math.max(maxWidth, (int) subFont.getBaseFont().getWidthPoint(s, subFont.getSize()));
                PdfUtil.renderConstrainedText(content, s, subFont, getX(), top, maxWidth);
                top -= PdfUtil.convertFromMillimeters(3.0f);
            }
        }
        content.setHorizontalScaling(100.0f);

        OutputBounds rect = new OutputBounds(getX() - maxWidth / 2, getY(), maxWidth, getY() - top);
        return rect;
    }

    public String getTitle() {
        return title;
    }

    public Image getImage() {
        return image;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public String getDescription() {
        return description;
    }

    public List<String> getItems() {
        return items;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setImage(Image image) {
        this.image = image;
    }

    public void setItems(List<String> items) {
        this.items = items;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}


text:
layout: default
title: File Structure
prev: index
next:
---


text:
use criterion::black_box;
use criterion::Criterion;
use criterion::{criterion_group, criterion_main};

use zxcvbn::zxcvbn;

pub fn bench_zxcvbn(c: &mut Criterion) {
    c.bench_function("zxcvbn", |b| {
        b.iter(|| zxcvbn(black_box("r0sebudmaelstrom11/20/91aaaa"), &[]))
    });
}

criterion_group!(benches, bench_zxcvbn);
criterion_main!(benches);


text:
'use strict'

const app = require('.')
const cheerio = require('cheerio')
const request = require('supertest')(app)
const superTestSession = require('supertest-session')

function loadPage (URL, callback) {
  // request.get(URL).expect(200).end(function (error, res) {
  request.get(URL).end(function (error, res) {
    if (error) {
      callback(error, res)
      return
    }
    var $ = cheerio.load(res.text)
    callback(null, $)
  })
}

['get', 'post', 'put'].forEach(function (method) {
  exports[method] = function methodWrapper (url) {
    return request[method](url)
  }
})

function session () {
  return superTestSession(app)
}

exports.loadPage = loadPage
exports.session = session


text:
from google.cloud import firestore
from google.cloud import secretmanager
from google.api_core.exceptions import NotFound
from base64 import b64decode
from base64 import b64encode
import re
import os
import sys
import hmac
import argparse
import secrets

class Hasher():
  def __init__(self, argv=None):
    parser = argparse.ArgumentParser(description='Hash and upload SSNs to Firestore')
    parser.add_argument('command',
      help="Command to execute",
      type=str.lower,
      choices=["upload", "verify", "create_key"])
    parser.add_argument('-p', '--project',
      help="Project ID where the Firestore DB should be initialized")
    parser.add_argument('-S', '--secret',
      help="Fully qualified secret name where the base64 encoded hash key lives")
    parser.add_argument('-s', '--salt',
      help="Salt for use with the HMAC hash.")
    parser.add_argument('-i', '--infile',
      help="Newline-separated list of SSNs to be stored in Firestore. They will be normalized by removing the dash character")
    parser.add_argument('--region',
      help="The region for Firestore. Use `gcloud app regions list` to list available regions",
      default='us-west2')
    parser.add_argument('--collection',
      help="The collection name within the Firestore DB where the Hashed SSNs should be stored",
      default='hashed_socials')
    self.opts = parser.parse_args(argv)
    self.sm = secretmanager.SecretManagerServiceClient()
    self.secret_path = f'{self.opts.secret}/versions/latest'

  def get_hash_key(self):
    try:
      version = self.sm.access_secret_version(self.secret_path)
      return b64decode(version.payload.data)
    except NotFound:
      return None

  def set_hash_key(self):
    if self.get_hash_key():
      return False
    key = secrets.token_bytes(64)
    b64 = b64encode(key)
    self.sm.add_secret_version(self.opts.secret, {'data': b64 })
    return True

  def hash_ssn(self, ssn, key):
    norm_ssn = ssn.strip().replace('-', '')
    if not re.match(r'[0-9]{9}', norm_ssn):
      raise ValueError(f"Normalized SSN from {norm_ssn} is not a 9 digit number")
    salt = self.opts.salt.encode('utf-8')
    mac = hmac.new(key, msg=salt, digestmod='sha256')
    mac.update(norm_ssn.encode('utf-8'))
    return mac.hexdigest()

  def run(self):
    if self.opts.command == "create_key":
      if self.set_hash_key():
        print(f"Saved secret at {self.secret_path}")
      else:
        print (f"Hash key already exists at {self.secret_path}")
      exit(0)

    os.environ["GCLOUD_PROJECT"] = self.opts.project
    os.system(f"gcloud alpha firestore databases create --project {self.opts.project} --region {self.opts.region}")
    db = firestore.Client()
    col = db.collection(self.opts.collection)
    key = self.get_hash_key()
    if key == None:
      raise NotFound("Hash key does not exist yet. Please run `hasher.py create_key --secret $SECRET` first")
    if self.opts.command == "upload":
      print("Hashing and uploading SSNs...")
      for ssn in open(self.opts.infile):
        digest = self.hash_ssn(ssn, key)
        col.document(digest).set({u'exists': True})
      print("Done!")
    elif self.opts.command == 'verify':
      print("Verifying and counting SSNs...")
      count = 0
      for ssn in open(self.opts.infile):
        digest = self.hash_ssn(ssn, key)
        doc = col.document(digest).get()
        if doc.exists:
          count += 1
      print(f"Found {count} valid SSNs")

if __name__ == '__main__':
  Hasher(sys.argv[1:]).run()


text:
<?php

namespace Sunspikes\Tests\Ratelimit\Cache\Adapter;

use Sunspikes\Ratelimit\Cache\Adapter\DesarrollaCacheAdapter;
use Sunspikes\Ratelimit\Cache\Exception\ItemNotFoundException;
use Desarrolla2\Cache\CacheInterface;
use Mockery as M;

class DesarrollaCacheAdapterTest extends \PHPUnit_Framework_TestCase
{
    private $adapterMock;

    public function setUp()
    {
        $cache = M::mock(CacheInterface::class);

        $cache->shouldReceive('set')
            ->with('key', 'value', 30)
            ->andReturnNull();

        $cache->shouldReceive('get')
            ->with('key')
            ->andReturn('value');

        $cache->shouldReceive('get')
            ->with('non-existing-key')
            ->andThrow(new ItemNotFoundException());

        $cache->shouldReceive('has')
            ->with('non-existing-key')
            ->andReturn(false);

        $cache->shouldReceive('has')
            ->with('key')
            ->andReturn(true);

        $cache->shouldReceive('has')
            ->with('has-existing-key')
            ->andReturn(true);

        $cache->shouldReceive('has')
            ->with('has-nonexisting-key')
            ->andReturn(false);

        $cache->shouldReceive('delete')
            ->with('delete-key')
            ->andReturnNull();

        $cache->shouldReceive('clearCache')
            ->withNoArgs()
            ->andReturnNull();

        $this->adapterMock = new DesarrollaCacheAdapter($cache);
    }

    public function testSet()
    {
        $this->assertNull($this->adapterMock->set('key', 'value', 30));
    }

    public function testGet()
    {
        $this->assertEquals('value', $this->adapterMock->get('key'));
    }

    /**
     * @expectedException \Sunspikes\Ratelimit\Cache\Exception\ItemNotFoundException
     */
    public function testGetNonExisting()
    {
        $this->adapterMock->get('non-existing-key');
    }

    public function testHasExisting()
    {
        $this->assertTrue($this->adapterMock->has('has-existing-key'));
    }

    public function testHasNonExisting()
    {
        $this->assertFalse($this->adapterMock->has('has-nonexisting-key'));
    }

    public function testDelete()
    {
        $this->assertNull($this->adapterMock->delete('delete-key'));
    }

    public function testClear()
    {
        $this->assertNull($this->adapterMock->clear());
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
        <XML>
            <Content>UPDATE</Content>
            <Clip>
                <ClipName>INPRDOE0691</ClipName>
                <TipoContenido>INFORMATIVOS PROGRAMAS</TipoContenido>
                <Contenido><![CDATA[ 04SEP14]]></Contenido>
                <OriginalTitle></OriginalTitle>
                <Description> </Description>
                <Notes>a</Notes>
                <DurPrev></DurPrev>
                <Chapter></Chapter>
                <EndDate></EndDate>
                <EPG></EPG>
                <EPG_Content> </EPG_Content>
                <Segments>

                <Segment>
                    <SegTitle>1-2 DOSSIER ESTELAR - 04SEP14</SegTitle>
                    <MediaID>INPRDOE069101</MediaID>
                    <Duration>00:26:00.00</Duration>
                    <SegNumber>1</SegNumber>
                    <ClipGroup>PROGRAMA</ClipGroup>
                    <Description> </Description>
                </Segment>

                <Segment>
                    <SegTitle>2-2 DOSSIER ESTELAR - 04SEP14</SegTitle>
                    <MediaID>INPRDOE069102</MediaID>
                    <Duration>00:26:00.00</Duration>
                    <SegNumber>2</SegNumber>
                    <ClipGroup>PROGRAMA</ClipGroup>
                    <Description> </Description>
                </Segment>
            </Segments></Clip></XML>


text:
//
//  longest-valid-parentheses.h
//
//  Created by jeswang 27/06/2014.
//

/*
Description:
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
*/

class Solution {
public:
    int longestValidParentheses(string s) {

    }
};


text:
<?php
// ##########  Do not delete these lines
if (isset($_SERVER['SCRIPT_FILENAME']) && 'comments.php' == basename($_SERVER['SCRIPT_FILENAME'])){
    die ('Please do not load this page directly. Thanks!'); }
if ( post_password_required() ) { ?>

<?php _e('This post is password protected. Enter the password to view comments.', 'kubrick'); ?>

<?php
    return; }
// ##########  End do not delete section

// Display Comments Section
if ( have_comments() ) : ?>

<?php comments_number('No Responses', 'One Response', '% Responses');?>

<?php previous_comments_link() ?>

<?php next_comments_link() ?>

     <?php
     wp_list_comments(array(
      // see http://codex.wordpress.org/Function_Reference/wp_list_comments
      // 'login_text'        => 'Login to reply',
      // 'callback'          => null,
      // 'end-callback'      => null,
      // 'type'              => 'all',
       'avatar_size'       => 64,
      // 'reverse_top_level' => null,
      // 'reverse_children'  =>
      ));
      ?>

<?php previous_comments_link() ?>

<?php next_comments_link() ?>

    <?php
    if ( ! comments_open() ) : // There are comments but comments are now closed
        echo"
Comments are closed.
";
    endif;

else : // I.E. There are no Comments
    if ( comments_open() ) : // Comments are open, but there are none yet
        // echo"
Be the first to write a comment.
";
    else : // comments are closed
        echo"
Comments are closed.
";
    endif;
endif;

// Display Form/Login info Section
// the comment_form() function handles this and can be used without any paramaters simply as "comment_form()"
comment_form(array(
  // see codex http://codex.wordpress.org/Function_Reference/comment_form for default values
  // tutorial here http://blogaliving.com/wordpress-adding-comment_form-theme/
  'comment_field' => '
<textarea name="comment" id="comment" cols="58" rows="10" tabindex="4" aria-required="true"></textarea>
',
  'label_submit' => 'Submit Comment',
  'comment_notes_after' => ''
  ));

// RSS comments link
echo '
';
post_comments_feed_link('Comments RSS Feed');
echo '
';

?>


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18444
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Ookii.Dialogs.Wpf.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    internal class Resources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal Resources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Ookii.Dialogs.Wpf.Properties.Resources", typeof(Resources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        internal static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unable to load the progress dialog animation: {0}.
        /// </summary>
        internal static string AnimationLoadErrorFormat {
            get {
                return ResourceManager.GetString("AnimationLoadErrorFormat", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The credential target may not be an empty string..
        /// </summary>
        internal static string CredentialEmptyTargetError {
            get {
                return ResourceManager.GetString("CredentialEmptyTargetError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to An error occurred acquiring credentials..
        /// </summary>
        internal static string CredentialError {
            get {
                return ResourceManager.GetString("CredentialError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to PromptForCredentialsWithSave has not been called or the credentials were modified after the call..
        /// </summary>
        internal static string CredentialPromptNotCalled {
            get {
                return ResourceManager.GetString("CredentialPromptNotCalled", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The task dialog already has a non-custom button with the same type..
        /// </summary>
        internal static string DuplicateButtonTypeError {
            get {
                return ResourceManager.GetString("DuplicateButtonTypeError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The task dialog already has an item with the same id..
        /// </summary>
        internal static string DuplicateItemIdError {
            get {
                return ResourceManager.GetString("DuplicateItemIdError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The file "{0}" could not be found..
        /// </summary>
        internal static string FileNotFoundFormat {
            get {
                return ResourceManager.GetString("FileNotFoundFormat", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Unable to retrieve the root folder..
        /// </summary>
        internal static string FolderBrowserDialogNoRootFolder {
            get {
                return ResourceManager.GetString("FolderBrowserDialogNoRootFolder", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The current operating system does not support glass, or the Desktop Window Manager is not enabled..
        /// </summary>
        internal static string GlassNotSupportedError {
            get {
                return ResourceManager.GetString("GlassNotSupportedError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Invalid filter string,.
        /// </summary>
        internal static string InvalidFilterString {
            get {
                return ResourceManager.GetString("InvalidFilterString", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The id of a task dialog item must be higher than 0..
        /// </summary>
        internal static string InvalidTaskDialogItemIdError {
            get {
                return ResourceManager.GetString("InvalidTaskDialogItemIdError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The item is not associated with a task dialog..
        /// </summary>
        internal static string NoAssociatedTaskDialogError {
            get {
                return ResourceManager.GetString("NoAssociatedTaskDialogError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Cannot change the id for a standard button..
        /// </summary>
        internal static string NonCustomTaskDialogButtonIdError {
            get {
                return ResourceManager.GetString("NonCustomTaskDialogButtonIdError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Preview.
        /// </summary>
        internal static string Preview {
            get {
                return ResourceManager.GetString("Preview", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The progress dialog is not shown..
        /// </summary>
        internal static string ProgressDialogNotRunningError {
            get {
                return ResourceManager.GetString("ProgressDialogNotRunningError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The progress dialog is already running..
        /// </summary>
        internal static string ProgressDialogRunning {
            get {
                return ResourceManager.GetString("ProgressDialogRunning", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to A custom button or radio button cannot have an empty label..
        /// </summary>
        internal static string TaskDialogEmptyButtonLabelError {
            get {
                return ResourceManager.GetString("TaskDialogEmptyButtonLabelError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Cross-thread operation not valid: Task dialog accessed from a thread other than the thread it was created on while it is visible..
        /// </summary>
        internal static string TaskDialogIllegalCrossThreadCallError {
            get {
                return ResourceManager.GetString("TaskDialogIllegalCrossThreadCallError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The task dialog item already belongs to another task dialog..
        /// </summary>
        internal static string TaskDialogItemHasOwnerError {
            get {
                return ResourceManager.GetString("TaskDialogItemHasOwnerError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The task dialog must have buttons..
        /// </summary>
        internal static string TaskDialogNoButtonsError {
            get {
                return ResourceManager.GetString("TaskDialogNoButtonsError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The task dialog is not current displayed..
        /// </summary>
        internal static string TaskDialogNotRunningError {
            get {
                return ResourceManager.GetString("TaskDialogNotRunningError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The task dialog is already being displayed..
        /// </summary>
        internal static string TaskDialogRunningError {
            get {
                return ResourceManager.GetString("TaskDialogRunningError", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to The operating system does not support task dialogs..
        /// </summary>
        internal static string TaskDialogsNotSupportedError {
            get {
                return ResourceManager.GetString("TaskDialogsNotSupportedError", resourceCulture);
            }
        }
    }
}


text:
zrequire('message_util');

const noop = () => {};
set_global('$', global.make_zjquery({
    silent: true,
}));
set_global('hashchange', {
    exit_overlay: noop,
});
set_global('stream_data', {
    get_sub_by_id: () => {
        return {
            color: "",
            invite_only: false,
            is_web_public: true,
        };
    },
    is_muted: () => {
        // We only test via muted topics for now.
        // TODO: Make muted streams and test them.
        return false;
    },
});
set_global('overlays', {
    open_overlay: (opts) => {
        overlays.close_callback = opts.on_close;
    },
    recent_topics_open: () => {
        return true;
    },
});
set_global('people', {
    is_my_user_id: function (id) {
        return id === 1;
    },
    sender_info_with_small_avatar_urls_for_sender_ids: (ids) => {
        return ids;
    },
});
set_global('XDate', zrequire('XDate', 'xdate'));
set_global('timerender', {
    last_seen_status_from_date: () => {
        return "Just now";
    },
});
set_global('unread', {
    unread_topic_counter: {
        get: (stream_id, topic) => {
            if (stream_id === 1 && topic === "topic-1") {
                // Only stream1, topic-1 is read.
                return 0;
            }
            return 1;
        },
    },
});
set_global('hash_util', {
    by_stream_uri: () => {
        return "https://www.example.com";
    },
    by_stream_topic_uri: () => {
        return "https://www.example.com";
    },
});
set_global('recent_senders', {
    get_topic_recent_senders: () => { return [1, 2]; },
});
set_global('list_render', {
    modifier: noop,
    create: (container, mapped_topic_values, opts) => {
        const formatted_topics = [];
        list_render.modifier = opts.modifier;
        for (const item of mapped_topic_values) {
            formatted_topics.push(opts.modifier(item));
            opts.filter.predicate(item);
        }
        // Just for coverage, the mechanisms
        // are tested in list_render
        if (mapped_topic_values.length >= 2) {
            opts.sort_fields.stream_sort(mapped_topic_values[0], mapped_topic_values[1]);
            opts.sort_fields.stream_sort(mapped_topic_values[1], mapped_topic_values[0]);
            opts.sort_fields.stream_sort(mapped_topic_values[0], mapped_topic_values[0]);
            opts.sort_fields.topic_sort(mapped_topic_values[0], mapped_topic_values[1]);
            opts.sort_fields.topic_sort(mapped_topic_values[1], mapped_topic_values[0]);
            opts.sort_fields.topic_sort(mapped_topic_values[0], mapped_topic_values[0]);
        }
        return list_render;
    },
    hard_redraw: noop,
    render_item: (item) => {
        return list_render.modifier(item);
    },
});

// Custom Data

// New stream
const stream1 = 1;
const stream2 = 2;
const stream3 = 3;
const stream4 = 4;

// Topics in the stream, all unread except topic1 & stream1.
const topic1 = "topic-1";  // No Other sender & read.
const topic2 = "topic-2";  // Other sender
const topic3 = "topic-3";  // User not present
const topic4 = "topic-4";  // User not present
const topic5 = "topic-5";  // other sender
const topic6 = "topic-6";  // other sender
const topic7 = "topic-7";  // muted topic
const topic8 = "topic-8";
const topic9 = "topic-9";
const topic10 = "topic-10";

set_global('muting', {
    is_topic_muted: (stream_id, topic) => {
        if (stream_id === stream1 && topic === topic7) {
            return true;
        }
        return false;
    },
});

// sender1 == current user
// sender2 == any other user
const sender1 = 1;
const sender2 = 2;

const messages = [];

set_global('message_list', {
    all: {
        all_messages: function () {
            return messages;
        },
    },
});
set_global('message_store', {
    get: (msg_id) => {
        return messages[msg_id - 1];
    },
});

let id = 0;

messages[0] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic1,
    sender_id: sender1,
    type: 'stream',
};

messages[1] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic2,
    sender_id: sender1,
    type: 'stream',
};

messages[2] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic2,
    sender_id: sender2,
    type: 'stream',
};

messages[3] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic3,
    sender_id: sender2,
    type: 'stream',
};

messages[4] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic4,
    sender_id: sender2,
    type: 'stream',
};

messages[5] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic5,
    sender_id: sender1,
    type: 'stream',
};

messages[6] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic5,
    sender_id: sender2,
    type: 'stream',
};

messages[7] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic6,
    sender_id: sender1,
    type: 'stream',
};

messages[8] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic6,
    sender_id: sender2,
    type: 'stream',
};

messages[9] = {
    stream_id: stream1,
    stream: 'stream1',
    id: id += 1,
    topic: topic7,
    sender_id: sender1,
    type: 'stream',
};

// a message of stream4
messages[10] = {
    stream_id: stream4,
    stream: 'stream4',
    id: id += 1,
    topic: topic10,
    sender_id: sender1,
    type: 'stream',
};

function get_topic_key(stream_id, topic) {
    return stream_id + ":" + topic.toLowerCase();
}

function generate_topic_data(topic_info_array) {
    // Since most of the fields are common, this function helps generate fixtures
    // with non common fields.
    $.clear_all_elements();
    const data = [];
    const selectors = [];

    for (const [stream_id, topic, unread_count, muted, participated] of topic_info_array) {
        const topic_selector = $.create('#recent_topic:' + get_topic_key(stream_id, topic));
        topic_selector.data = function () {
            return {
                participated: participated,
                muted: muted,
                unreadCount: unread_count,
            };
        };

        selectors.push(topic_selector);
        data.push({
            other_senders_count: 0,
            invite_only: false,
            is_web_public: true,
            last_msg_time: 'Just now',
            senders: [
                1,
                2,
            ],
            stream: 'stream' + stream_id,
            stream_color: '',
            stream_id: stream_id,
            stream_url: 'https://www.example.com',
            topic: topic,
            topic_key: get_topic_key(stream_id, topic),
            topic_url: 'https://www.example.com',
            unread_count: unread_count,
            muted: muted,
            topic_muted: muted,
            participated: participated,
        });
    }
    return data;
}

function verify_topic_data(all_topics, stream, topic, last_msg_id,
                           participated) {
    const topic_data = all_topics.get(stream + ':' + topic);
    assert.equal(topic_data.last_msg_id, last_msg_id);
    assert.equal(topic_data.participated, participated);
}

run_test("test_recent_topics_launch", () => {
    // Note: unread count and urls are fake,
    // since they are generated in external libraries
    // and are not to be tested here.
    const expected = {
        filter_participated: false,
        filter_unread: false,
        filter_muted: false,
        search_val: '',
    };

    global.stub_templates(function (template_name, data) {
        if (template_name === 'recent_topics_table') {
            assert.deepEqual(data, expected);
        } else if (template_name === 'recent_topics_filters') {
            assert.equal(data.filter_unread, expected.filter_unread);
            assert.equal(data.filter_participated, expected.filter_participated);
        }
        return '<recent_topics table stub>';
    });

    const rt = zrequire('recent_topics');
    rt.process_messages(messages);

    rt.launch();

    // Test if search text is selected
    overlays.close_callback();

    // incorrect topic_key
    assert.equal(rt.inplace_rerender('stream_unknown:topic_unknown'), false);
});

run_test('test_filter_all', () => {
    // Just tests inplace rerender of a message
    // in All topics filter.
    const expected = {
        filter_participated: false,
        filter_unread: false,
        filter_muted: false,
        search_val: "",
    };
    let row_data;
    let i;
    global.stub_templates(function (template_name, data) {
        if (template_name === 'recent_topic_row') {
            // All the row will be processed.
            i -= 1;
            assert.deepEqual(data, row_data[i]);
        } else if (template_name === 'recent_topics_table') {
            assert.deepEqual(data, expected);
        }
        return '<recent_topics row stub>';
    });

    // topic is not muted
    row_data = generate_topic_data([[1, 'topic-1', 0, false, true]]);
    i = row_data.length;
    const rt = zrequire('recent_topics');
    rt.set_filter('all');
    rt.process_messages([messages[0]]);

    row_data = row_data.concat(generate_topic_data([[1, 'topic-7', 1, true, true]]));
    i = row_data.length;
    // topic is muted (=== hidden)
    rt.process_messages([messages[9]]);

    // Test search
    expected.search_val = "topic-1";
    row_data = generate_topic_data([[1, 'topic-1', 0, false, true]]);
    const search_element = $.create("#recent_topics_search");
    search_element.val('topic-3');
    i = row_data.length;
    assert.equal(rt.inplace_rerender('1:topic-1'), true);
});

run_test('test_filter_unread', () => {
    // Tests rerender of all topics when filter changes to "unread".
    const expected = {
        filter_participated: false,
        filter_unread: true,
        filter_muted: false,
        search_val: '',
    };

    const row_data = generate_topic_data([
        // stream_id, topic, unread_count,  muted, participated
        [4, 'topic-10', 1, false, true],
        [1, 'topic-7', 1, true, true],
        [1, 'topic-6', 1, false, true],
        [1, 'topic-5', 1, false, true],
        [1, 'topic-4', 1, false, false],
        [1, 'topic-3', 1, false, false],
        [1, 'topic-2', 1, false, true],
        [1, 'topic-1', 0, false, true],
    ]);
    let i = 0;

    const rt = zrequire('recent_topics');

    global.stub_templates(function () {
        return '<recent_topics table stub>';
    });
    rt.process_messages(messages);
    assert.equal(rt.inplace_rerender('1:topic-1'), true);

    $('#recent_topics_filter_buttons').removeClass('btn-recent-selected');
    global.stub_templates(function (template_name, data) {
        assert.equal(template_name, 'recent_topics_filters');
        assert.equal(data.filter_unread, expected.filter_unread);
        assert.equal(data.filter_participated, expected.filter_participated);
        return '<recent_topics table stub>';
    });

    rt.set_filter('unread');
    rt.update_filters_view();

    global.stub_templates(function (template_name, data) {
        if (template_name === 'recent_topic_row') {
            // All the row will be processed.
            assert.deepEqual(data, row_data[i]);
            i += 1;
        } else if (template_name === 'recent_topics_table') {
            assert.deepEqual(data, expected);
        }
        return '<recent_topics row stub>';
    });
    rt.process_messages([messages[0]]);

    // Unselect "unread" filter by clicking twice.
    expected.filter_unread = false;
    $('#recent_topics_filter_buttons').addClass('btn-recent-selected');
    rt.set_filter('unread');

    $('#recent_topics_filter_buttons').removeClass('btn-recent-selected');
    // reselect "unread" filter
    rt.set_filter('unread');

    // Now clicking "all" filter should have no change to expected data.
    rt.set_filter('all');
});

run_test('test_filter_participated', () => {
    // Tests rerender of all topics when filter changes to "unread".
    const expected = {
        filter_participated: true,
        filter_unread: false,
        filter_muted: false,
        search_val: '',
    };

    const row_data = generate_topic_data([
        // stream_id, topic, unread_count,  muted, participated
        [4, 'topic-10', 1, false, true],
        [1, 'topic-7', 1, true, true],
        [1, 'topic-6', 1, false, true],
        [1, 'topic-5', 1, false, true],
        [1, 'topic-4', 1, false, false],
        [1, 'topic-3', 1, false, false],
        [1, 'topic-2', 1, false, true],
        [1, 'topic-1', 0, false, true],
    ]);
    let i = 0;

    const rt = zrequire('recent_topics');

    global.stub_templates(function () {
        return '<recent_topics table stub>';
    });
    rt.process_messages(messages);
    assert.equal(rt.inplace_rerender('1:topic-4'), true);

    // Set muted filter
    rt.set_filter('muted');
    assert.equal(rt.inplace_rerender('1:topic-7'), true);

    // remove muted filter
    rt.set_filter('muted');

    $('#recent_topics_filter_buttons').removeClass('btn-recent-selected');
    global.stub_templates(function (template_name, data) {
        assert.equal(template_name, 'recent_topics_filters');
        assert.equal(data.filter_unread, expected.filter_unread);
        assert.equal(data.filter_participated, expected.filter_participated);
        return '<recent_topics table stub>';
    });
    rt.set_filter('participated');
    rt.update_filters_view();

    global.stub_templates(function (template_name, data) {
        if (template_name === 'recent_topic_row') {
            // All the row will be processed.
            assert.deepEqual(data, row_data[i]);
            i += 1;
        } else if (template_name === 'recent_topics_table') {
            assert.deepEqual(data, expected);
        }
        return '<recent_topics row stub>';
    });
    rt.process_messages([messages[4]]);

    expected.filter_participated = false;
    rt.set_filter('all');
});

run_test('test_update_unread_count', () => {
    const rt = zrequire('recent_topics');
    rt.set_filter('all');
    global.stub_templates(function () {
        return '<recent_topics table stub>';
    });
    rt.process_messages(messages);

    // update a message
    generate_topic_data([[1, 'topic-7', 1, false, true]]);
    rt.update_topic_unread_count(messages[9]);
});

// template rendering is tested in test_recent_topics_launch.
global.stub_templates(function () {
    return '<recent_topics table stub>';
});

run_test('basic assertions', () => {
    const rt = zrequire('recent_topics');
    rt.set_filter('all');
    rt.process_messages(messages);
    let all_topics = rt.get();

    // update a message
    generate_topic_data([[1, 'topic-7', 1, false, true]]);
    rt.process_messages([messages[9]]);
    // Check for expected lengths.
    // total 8 topics, 1 muted
    assert.equal(all_topics.size, 8);
    assert.equal(Array.from(all_topics.keys()).toString(),
                 '4:topic-10,1:topic-7,1:topic-6,1:topic-5,1:topic-4,1:topic-3,1:topic-2,1:topic-1');

    rt.process_message({
        type: 'private',
    });

    // Private msgs are not processed.
    assert.equal(all_topics.size, 8);
    assert.equal(Array.from(all_topics.keys()).toString(),
                 '4:topic-10,1:topic-7,1:topic-6,1:topic-5,1:topic-4,1:topic-3,1:topic-2,1:topic-1');

    // participated
    verify_topic_data(all_topics, stream1, topic1, messages[0].id, true);

    // No message was sent by us.
    verify_topic_data(all_topics, stream1, topic3, messages[3].id, false);

    // Not participated
    verify_topic_data(all_topics, stream1, topic4, messages[4].id, false);

    // topic3 now participated
    rt.process_message({
        stream_id: stream1,
        id: id += 1,
        topic: topic3,
        sender_id: sender1,
        type: 'stream',
    });

    all_topics = rt.get();
    assert.equal(Array.from(all_topics.keys()).toString(),
                 '1:topic-3,4:topic-10,1:topic-7,1:topic-6,1:topic-5,1:topic-4,1:topic-2,1:topic-1');
    verify_topic_data(all_topics, stream1, topic3, id, true);

    // Send new message to topic7 (muted)
    // The topic will be hidden when displayed
    rt.process_message({
        stream_id: stream1,
        id: id += 1,
        topic: topic7,
        sender_id: sender1,
        type: 'stream',
    });

    all_topics = rt.get();
    assert.equal(Array.from(all_topics.keys()).toString(),
                 '1:topic-7,1:topic-3,4:topic-10,1:topic-6,1:topic-5,1:topic-4,1:topic-2,1:topic-1');

    // update_topic_is_muted now relies on external libraries completely
    // so we don't need to check anythere here.
    generate_topic_data([[1, topic1, 0, false, true]]);
    assert.equal(rt.update_topic_is_muted(stream1, topic1), true);
    // a topic gets muted which we are not tracking
    assert.equal(rt.update_topic_is_muted(stream1, "topic-10"), false);
});

run_test('test_reify_local_echo_message', () => {
    const rt = zrequire('recent_topics');
    rt.set_filter('all');
    rt.process_messages(messages);

    rt.process_message({
        stream_id: stream1,
        id: 1000.01,
        topic: topic7,
        sender_id: sender1,
        type: 'stream',
    });

    assert.equal(rt.reify_message_id_if_available({
        old_id: 1000.01,
        new_id: 1001,
    }), true);

    rt.process_message({
        stream_id: stream1,
        id: 1001.01,
        topic: topic7,
        sender_id: sender1,
        type: 'stream',
    });

    // A new message arrived in the same topic before we could reify the message_id
    rt.process_message({
        stream_id: stream1,
        id: 1003,
        topic: topic7,
        sender_id: sender1,
        type: 'stream',
    });

    assert.equal(rt.reify_message_id_if_available({
        old_id: 1000.01,
        new_id: 1001,
    }), false);
});

run_test('test_topic_edit', () => {
    // NOTE: This test should always run in the end as it modified the messages data.
    const rt = zrequire('recent_topics');
    rt.set_filter('all');
    rt.process_messages(messages);

    let all_topics = rt.get();
    assert.equal(Array.from(all_topics.keys()).toString(),
                 '4:topic-10,1:topic-7,1:topic-6,1:topic-5,1:topic-4,1:topic-3,1:topic-2,1:topic-1');

    ////////////////// test change topic //////////////////
    verify_topic_data(all_topics, stream1, topic6, messages[8].id, true);
    assert.equal(all_topics.get(get_topic_key(stream1, topic8)), undefined);

    let topic_selector = $.create('#recent_topic:' + get_topic_key(stream1, topic8));
    topic_selector.data = function () {
        return {
            participated: true,
            muted: false,
            unreadCount: 1,
        };
    };
    // change topic of topic6 to topic8
    messages[7].topic = topic8;
    messages[8].topic = topic8;
    rt.process_topic_edit(stream1, topic6, topic8);
    all_topics = rt.get();

    verify_topic_data(all_topics, stream1, topic8, messages[8].id, true);
    assert.equal(all_topics.get(get_topic_key(stream1, topic6)), undefined);

    ////////////////// test stream change //////////////////
    verify_topic_data(all_topics, stream1, topic1, messages[0].id, true);
    assert.equal(all_topics.get(get_topic_key(stream2, topic1)), undefined);

    topic_selector = $.create('#recent_topic:' + get_topic_key(stream2, topic1));
    topic_selector.data = function () {
        return {
            participated: true,
            muted: false,
            unreadCount: 0,
        };
    };
    messages[0].stream_id = stream2;
    rt.process_topic_edit(stream1, topic1, topic1, stream2);
    all_topics = rt.get();

    assert.equal(all_topics.get(get_topic_key(stream1, topic1)), undefined);
    verify_topic_data(all_topics, stream2, topic1, messages[0].id, true);

    ////////////////// test stream & topic change //////////////////
    verify_topic_data(all_topics, stream2, topic1, messages[0].id, true);
    assert.equal(all_topics.get(get_topic_key(stream3, topic9)), undefined);

    topic_selector = $.create('#recent_topic:' + get_topic_key(stream3, topic9));
    topic_selector.data = function () {
        return {
            participated: false,
            muted: false,
            unreadCount: 1,
        };
    };
    messages[0].stream_id = stream3;
    messages[0].topic = topic9;
    rt.process_topic_edit(stream2, topic1, topic9, stream3);
    all_topics = rt.get();

    assert.equal(all_topics.get(get_topic_key(stream2, topic1)), undefined);
    verify_topic_data(all_topics, stream3, topic9, messages[0].id, true);
});


text:
class TagsCache {
    constructor(key = null) {
        this._index = {};
        this._key = key;
    }

    addItem(item) {
        const tags = item.tags._list;

        for (const tag of tags)
            this.add(tag, item);
    }

    removeItem(item) {
        const tags = item.tags._list;

        for (const tag of tags)
            this.remove(tag, item);
    }

    add(tag, item) {
        // already in cache
        if (this._index[tag] && this._index[tag].list.indexOf(item) !== -1)
            return;

        // create index for tag
        if (!this._index[tag]) {
            this._index[tag] = {
                list: []
            };
            // key indexing is available
            if (this._key)
                this._index[tag].keys = { };
        }

        // add to index list
        this._index[tag].list.push(item);

        // add to index keys
        if (this._key)
            this._index[tag].keys[item[this._key]] = item;
    }

    remove(tag, item) {
        // no index created for that tag
        if (!this._index[tag])
            return;

        // check if item not in cache
        if (this._key) {
            // by key
            if (!this._index[tag].keys[item[this._key]])
                return;
        }

        // by position in list
        const ind = this._index[tag].list.indexOf(item);
        if (ind === -1)
            return;

        // remove item from index list
        this._index[tag].list.splice(ind, 1);

        // remove item from index keys
        if (this._key)
            delete this._index[tag].keys[item[this._key]];

        // if index empty, remove it
        if (this._index[tag].list.length === 0)
            delete this._index[tag];
    }

    find(args) {
        const index = { };
        const items = [];
        let item, tag, tags, tagsRest, missingIndex;

        const sort = (a, b) => {
            return this._index[a].list.length - this._index[b].list.length;
        };

        for (let i = 0; i < args.length; i++) {
            tag = args[i];

            if (tag instanceof Array) {
                if (tag.length === 0)
                    continue;

                if (tag.length === 1) {
                    tag = tag[0];
                } else {
                    // check if all indexes are in present
                    missingIndex = false;
                    for (let t = 0; t < tag.length; t++) {
                        if (!this._index[tag[t]]) {
                            missingIndex = true;
                            break;
                        }
                    }
                    if (missingIndex)
                        continue;

                    // sort tags by least number of matches first
                    tags = tag.slice(0).sort(sort);

                    // remainder of tags for `has` checks
                    tagsRest = tags.slice(1);
                    if (tagsRest.length === 1)
                        tagsRest = tagsRest[0];

                    for (let n = 0; n < this._index[tags[0]].list.length; n++) {
                        item = this._index[tags[0]].list[n];
                        if ((this._key ? !index[item[this._key]] : (items.indexOf(item) === -1)) && item.tags.has(tagsRest)) {
                            if (this._key)
                                index[item[this._key]] = true;
                            items.push(item);
                        }
                    }

                    continue;
                }
            }

            if (tag && typeof tag === 'string' && this._index[tag]) {
                for (let n = 0; n < this._index[tag].list.length; n++) {
                    item = this._index[tag].list[n];

                    if (this._key) {
                        if (!index[item[this._key]]) {
                            index[item[this._key]] = true;
                            items.push(item);
                        }
                    } else if (items.indexOf(item) === -1) {
                        items.push(item);
                    }
                }
            }
        }

        return items;
    }
}

export { TagsCache };


text:
package org.motechproject.sms.configs;

/**
 * Provider-specific properties. ie: Clickatell api_key, most will have at least username & password
 */
public class ConfigProp {
    private String name;
    private String value;

    public ConfigProp() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}


text:
#include "simplecrypt.h"
#include <QByteArray>
#include <QtDebug>
#include <QtGlobal>
#include <QDateTime>
#include <QCryptographicHash>
#include <QDataStream>
#include <QRandomGenerator>

SimpleCrypt::SimpleCrypt():
    m_key(0),
    m_compressionMode(CompressionAuto),
    m_protectionMode(ProtectionChecksum),
    m_lastError(ErrorNoError)
{
}

SimpleCrypt::SimpleCrypt(quint64 key):
    m_key(key),
    m_compressionMode(CompressionAuto),
    m_protectionMode(ProtectionChecksum),
    m_lastError(ErrorNoError)
{
    splitKey();
}

void SimpleCrypt::setKey(quint64 key)
{
    m_key = key;
    splitKey();
}

void SimpleCrypt::splitKey()
{
    m_keyParts.clear();
    m_keyParts.resize(8);
    for (int i=0;i<8;i++) {
        quint64 part = m_key;
        for (int j=i; j>0; j--)
            part = part >> 8;
        part = part & 0xff;
        m_keyParts[i] = static_cast<char>(part);
    }
}

QByteArray SimpleCrypt::encryptToByteArray(const QString& plaintext)
{
    QByteArray plaintextArray = plaintext.toUtf8();
    return encryptToByteArray(plaintextArray);
}

QByteArray SimpleCrypt::encryptToByteArray(const QByteArray &plaintext)
{
    if (m_keyParts.isEmpty()) {
        qWarning() << "No key set.";
        m_lastError = ErrorNoKeySet;
        return QByteArray();
    }

    QByteArray ba = plaintext;

    CryptoFlags flags = CryptoFlagNone;
    if (m_compressionMode == CompressionAlways) {
        ba = qCompress(ba, 9); //maximum compression
        flags |= CryptoFlagCompression;
    } else if (m_compressionMode == CompressionAuto) {
        QByteArray compressed = qCompress(ba, 9);
        if (compressed.count() < ba.count()) {
            ba = compressed;
            flags |= CryptoFlagCompression;
        }
    }

    QByteArray integrityProtection;
    if (m_protectionMode == ProtectionChecksum) {
        flags |= CryptoFlagChecksum;
        QDataStream s(&integrityProtection, QIODevice::WriteOnly);
        s << qChecksum(ba.constData(), ba.length());
    } else if (m_protectionMode == ProtectionHash) {
        flags |= CryptoFlagHash;
        QCryptographicHash hash(QCryptographicHash::Sha1);
        hash.addData(ba);

        integrityProtection += hash.result();
    }

    //prepend a random char to the string
    char randomChar = char(QRandomGenerator::global()->generate() & 0xFF);
    ba = randomChar + integrityProtection + ba;

    int pos(0);
    char lastChar(0);

    int cnt = ba.count();

    while (pos < cnt) {
        ba[pos] = ba.at(pos) ^ m_keyParts.at(pos % 8) ^ lastChar;
        lastChar = ba.at(pos);
        ++pos;
    }

    QByteArray resultArray;
    resultArray.append(char(0x03));  //version for future updates to algorithm
    resultArray.append(char(flags)); //encryption flags
    resultArray.append(ba);

    m_lastError = ErrorNoError;
    return resultArray;
}

QString SimpleCrypt::encryptToString(const QString& plaintext)
{
    QByteArray plaintextArray = plaintext.toUtf8();
    QByteArray cypher = encryptToByteArray(plaintextArray);
    QString cypherString = QString::fromLatin1(cypher.toBase64());
    return cypherString;
}

QString SimpleCrypt::encryptToString(const QByteArray &plaintext)
{
    QByteArray cypher = encryptToByteArray(plaintext);
    QString cypherString = QString::fromLatin1(cypher.toBase64());
    return cypherString;
}

QString SimpleCrypt::decryptToString(const QString &cyphertext)
{
    QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
    QByteArray plaintextArray = decryptToByteArray(cyphertextArray);
    QString plaintext = QString::fromUtf8(plaintextArray, plaintextArray.size());

    return plaintext;
}

QString SimpleCrypt::decryptToString(const QByteArray &cypher)
{
    QByteArray ba = decryptToByteArray(cypher);
    QString plaintext = QString::fromUtf8(ba, ba.size());

    return plaintext;
}

QByteArray SimpleCrypt::decryptToByteArray(const QString& cyphertext)
{
    QByteArray cyphertextArray = QByteArray::fromBase64(cyphertext.toLatin1());
    QByteArray ba = decryptToByteArray(cyphertextArray);

    return ba;
}

QByteArray SimpleCrypt::decryptToByteArray(const QByteArray &cypher)
{
    if (m_keyParts.isEmpty()) {
        qWarning() << "No key set.";
        m_lastError = ErrorNoKeySet;
        return QByteArray();
    }

    QByteArray ba = cypher;

    if( cypher.count() < 3 )
        return QByteArray();

    char version = ba.at(0);

    if (version !=3) {  //we only work with version 3
        m_lastError = ErrorUnknownVersion;
        qWarning() << "Invalid version or not a cyphertext.";
        return QByteArray();
    }

    CryptoFlags flags = CryptoFlags(ba.at(1));

    ba = ba.mid(2);
    int pos(0);
    int cnt(ba.count());
    char lastChar = 0;

    while (pos < cnt) {
        char currentChar = ba[pos];
        ba[pos] = ba.at(pos) ^ lastChar ^ m_keyParts.at(pos % 8);
        lastChar = currentChar;
        ++pos;
    }

    ba = ba.mid(1); //chop off the random number at the start

    bool integrityOk(true);
    if (flags.testFlag(CryptoFlagChecksum)) {
        if (ba.length() < 2) {
            m_lastError = ErrorIntegrityFailed;
            return QByteArray();
        }
        quint16 storedChecksum;
        {
            QDataStream s(&ba, QIODevice::ReadOnly);
            s >> storedChecksum;
        }
        ba = ba.mid(2);
        quint16 checksum = qChecksum(ba.constData(), ba.length());
        integrityOk = (checksum == storedChecksum);
    } else if (flags.testFlag(CryptoFlagHash)) {
        if (ba.length() < 20) {
            m_lastError = ErrorIntegrityFailed;
            return QByteArray();
        }
        QByteArray storedHash = ba.left(20);
        ba = ba.mid(20);
        QCryptographicHash hash(QCryptographicHash::Sha1);
        hash.addData(ba);
        integrityOk = (hash.result() == storedHash);
    }

    if (!integrityOk) {
        m_lastError = ErrorIntegrityFailed;
        return QByteArray();
    }

    if (flags.testFlag(CryptoFlagCompression))
        ba = qUncompress(ba);

    m_lastError = ErrorNoError;
    return ba;
}


text:
import numpy as np

def _ensure_unicode(value):

    if not isinstance(value, basestring):
        if isinstance(value, int) or isinstance(value, float):
            if np.isnan(value):
                return ""
        return value

    try:
        return value.encode('utf-8')
    except ValueError:
        try:
            return value.decode('utf-8')
        except:
            return u''

def column_population(dataframe):
    """make column headers from the keys in dataframe
    :param dataframe:
    :return: a list of dictionaries
    """
    fields = dataframe.keys()

    columns = []
    for field in fields:
        uni = _ensure_unicode(field)
        columns.append({
            'id': uni,
            'name': uni,
            'field': uni,
        })
    return columns

def row_population(dataframe):
    """Convert the dictionary of lists Pandas has generated from the CSV into
    a list of dicts.
    :param dataframe:
    :return: JSON representation of rows
    """
    #todo this needs to be reformatted NOT to use the row names as a variable
    # to iterate over, this will break spss files that need rownames
    #todo right now it is renaming the rows in [r] when it reads it in
    fields = dataframe.keys()
    rows = []
    for n in range(len(dataframe[fields[0]])):
        rows.append({})
        for col_field in fields:
            rows[n][_ensure_unicode(col_field)] = str(_ensure_unicode(dataframe[col_field][n]))
    return rows

MAX_COLS = 400
MAX_ROWS = 1000

def check_shape(dataframe):
    """ Takes a data_frame and checks if the number of rows or columns is too
    big to quickly reformat into slickgrid's json data
    """
    return dataframe.shape[0] > MAX_ROWS or dataframe.shape[1] > MAX_COLS


text:
import {customElement, inject} from 'aurelia-framework';
import {handle} from 'aurelia-flux';

@customElement('notify')
export class Notify
{
  show = false;
  type = '';
  message = '';

  close() {
    this.show = false;
  }

  @handle('*.create.done')
  @handle('*.update.done')
  @handle('*.destroy.done')
  showSuccess() {
    this.show = true;
    this.type = 'success';
    this.message = 'Operação realizada com sucesso';

    console.log('ta vindo pra ca')

    setTimeout(() => {this.close()}, 3500);
  }
}


text:
//     The MIT License (MIT)
//
//     Copyright (c) 2015 Liquimind Inc
//
//     Permission is hereby granted, free of charge, to any person obtaining a copy
//     of this software and associated documentation files (the "Software"), to deal
//     in the Software without restriction, including without limitation the rights
//     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//     copies of the Software, and to permit persons to whom the Software is
//     furnished to do so, subject to the following conditions:
//
//     The above copyright notice and this permission notice shall be included in all
//     copies or substantial portions of the Software.
//
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//     SOFTWARE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BluetoothBear
{
    /// <summary>
    /// Bluetooth LE connection states.
    /// </summary>
    public enum BleConnectionState
    {

        /// <summary>
        /// The device is not currently connected.
        /// </summary>
        Disconnected,
        /// <summary>
        /// The device is not currently connected.
        /// </summary>
        Disconnecting,
        /// <summary>
        /// The device is connected but no services have been discovered so it cannot be used.
        /// </summary>
        Connected,
        /// <summary>
        /// The device is in the process of creating a connection
        /// </summary>
        Connecting,
        /// <summary>
        /// The device has been connected and all the services have been enumerated.
        /// </summary>
        ConnectedWithServices
    };

    /// <summary>
    /// Interface that defines the basic operations of Bluetooth LE Device
    /// </summary>
    public interface IBleDevice
    {
        /// <summary>
        /// Occurs when connection state changed.
        /// </summary>
        event BleDeviceConnectionStateChangedEventHandler ConnectionStateChanged;
        /// <summary>
        /// Occurs when characteristic changed.
        /// </summary>
        event BleDeviceCharacteristicChangedEventHandler CharacteristicChanged;
        /// <summary>
        /// Occurs when characteristic read.
        /// </summary>
        event BleDeviceCharacteristicReadEventHandler CharacteristicRead;
        /// <summary>
        /// Occurs when characteristic write.
        /// </summary>
        event BleDeviceCharacteristicWriteEventHandler CharacteristicWrite;
        /// <summary>
        /// Occurs when descriptor read.
        /// </summary>
        event BleDeviceDescriptorReadEventHandler DescriptorRead;
        /// <summary>
        /// Occurs when descriptor write.
        /// </summary>
        event BleDeviceDescriptorWriteEventHandler DescriptorWrite;

        /// <summary>
        /// Occurs when read remote rssi.
        /// </summary>
        event BleDeviceReadRemoteRssiEventHandler ReadRemoteRssi;

        /// <summary>
        /// Occurs when reliable write completed.
        /// </summary>
        event BleDeviceReliableWriteCompletedEventHandler ReliableWriteCompleted;

        /// <summary>
        /// Occurs when services discovered.
        /// </summary>
        event BleDeviceServicesDiscoveredEventHandler ServicesDiscovered;

        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>The name.</value>
        string Name { get; }

        /// <summary>
        /// Gets the ID. In Android and Windows this is a Mac Address on IOS this is a UUID
        /// </summary>
        /// <value>The UUI.</value>
        string ID { get; }

        /// <summary>
        /// Gets the state of the connection.
        /// </summary>
        /// <value>The state of the connection.</value>
        BleConnectionState ConnectionState { get; }

        /// <summary>
        /// Gets a value indicating whether this instance has performed service discovered.
        /// </summary>
        /// <value><c>true</c> if this instance is service discovered; otherwise, <c>false</c>.</value>
        bool IsServiceDiscovered { get; }

        /// <summary>
        /// Connect to this device.
        /// </summary>
        void Connect();

        /// <summary>
        /// Disconnect this device.
        /// </summary>
        void Disconnect();

        /// <summary>
        /// Gets the characteristic.
        /// </summary>
        /// <returns>The characteristic.</returns>
        /// <param name="id">Identifier.</param>
        object GetCharacteristic(Guid id);

        /// <summary>
        /// Gets the characteristic.
        /// </summary>
        /// <returns>The characteristic.</returns>
        /// <param name="id">Identifier.</param>
        object GetCharacteristic(UInt16 id);

        /// <summary>
        /// Enables the notifications on a characteristic.
        /// </summary>
        /// <returns><c>true</c>, if notifications was enabled, <c>false</c> otherwise.</returns>
        /// <param name="characteristic">Characteristic.</param>
        /// <param name="enabled">If set to <c>true</c> enabled.</param>
        bool EnableNotifications(object characteristic, bool enabled);

        /// <summary>
        /// Reads the characteristic.
        /// </summary>
        /// <param name="characteristic">Characteristic.</param>
        void ReadCharacteristic(object characteristic);

        /// <summary>
        /// Writes the characteristic.
        /// </summary>
        /// <param name="characteristic">Characteristic.</param>
        /// <param name="value">Value.</param>
        /// <param name="isReliable">If set to <c>true</c> is reliable.</param>
        void WriteCharacteristic(object characteristic, byte[] value, bool isReliable);

        void DiscoverServices();

        /// <summary>
        /// Raises the connection state changed event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnConnectionStateChanged(IBleDevice sender, BleConnectionStateChangedEventArgs e);

        /// <summary>
        /// Raises the characteristic read event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnCharacteristicRead(IBleDevice sender, BleCharacteristicReadEventArgs e);

        /// <summary>
        /// Raises the characteristic write event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnCharacteristicWrite(IBleDevice sender, BleCharacteristicWriteEventArgs e);

        /// <summary>
        /// Raises the characteristic changed event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnCharacteristicChanged(IBleDevice sender, BleCharacteristicChangedEventArgs e);

        /// <summary>
        /// Raises the descriptor read event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnDescriptorRead(IBleDevice sender, BleDescriptorReadEventArgs e);

        /// <summary>
        /// Raises the descriptor write event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnDescriptorWrite(IBleDevice sender, BleDescriptorWriteEventArgs e);

        /// <summary>
        /// Raises the read remote rssi event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnReadRemoteRssi(IBleDevice sender, BleReadRemoteRssiEventArgs e);

        /// <summary>
        /// Raises the reliable write completed event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnReliableWriteCompleted(IBleDevice sender, BleReliableWriteCompletedEventArgs e);

        /// <summary>
        /// Raises the services discovered event.
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnServicesDiscovered(IBleDevice sender, BleServicesDiscoveredEventArgs e);

    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.hibernate.persister.collection (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.hibernate.persister.collection

See: Description

Interface Summary

Interface
Description

CollectionPersister

QueryableCollection

SQLLoadableCollection

Class Summary

Class
Description

AbstractCollectionPersister

BasicCollectionPersister

CollectionPropertyMapping

CollectionPropertyNames

CompositeElementPropertyMapping

ElementPropertyMapping

NamedQueryCollectionInitializer

OneToManyPersister

Package org.hibernate.persister.collection Description

<p>
        This package abstracts the persistence mechanism for collections.
</p>
<p>
        Concrete implementations of <tt>CollectionPersister</tt>
        define strategies for persistence of particular collection
        roles. Collection persisters may optionally implement
        <tt>QueryableCollection</tt> if they should be queryable
        using HQL or loaded using <tt>OuterJoinLoader</tt>.
</p>

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
package com.darkrockstudios.apps.tminus.database.tables;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

/**
 * Created by Adam on 2/15/14.
 */
@DatabaseTable(tableName = AgencyType.TABLE_NAME)
public class AgencyType
{
	public static final String TABLE_NAME = "AgencyType";

	@DatabaseField(id = true)
	public int id;

	@DatabaseField
	public String name;
}


text:
package com.impetus.kundera.service.policy;

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

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * To test round robin algo.
 *
 * @author Kuldeep.Mishra
 *
 */
public class RoundRobinBalancingPolicyTest
{

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception
    {
    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception
    {
    }

    /**
     * Test method for
     * {@link com.impetus.kundera.service.policy.RoundRobinBalancingPolicy#getPool(java.util.Collection)}
     * .
     */
    @Test
    public void testGetPool()
    {
        Map<String, Object> map = new HashMap<String, Object>();
        Object o1 = new Object();
        Object o2 = new Object();
        Object o3 = new Object();
        map.put("first", o1);
        map.put("second", o2);
        map.put("third", o3);

        RoundRobinBalancingPolicy balancingPolicy = new RoundRobinBalancingPolicy();

        for (int i = 0; i < 1300; i++)
        {
            Object o = balancingPolicy.getPool(map.values());
            Assert.assertNotNull(o);
            if (i % 3 == 0)
            {
                Assert.assertEquals(o2, o);
            }
            else if (i % 3 == 1)
            {
                Assert.assertEquals(o3, o);
            }
            else if (i % 3 == 2)
            {
                Assert.assertEquals(o1, o);
            }
        }
    }
}


text:
package io.vertx.ext.web.handler;

import io.vertx.codegen.annotations.Fluent;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.Handler;
import io.vertx.ext.auth.webauthn.WebAuthn;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.impl.WebAuthnHandlerImpl;

/**
 * An auth handler that provides FIDO2 WebAuthN Relay Party support.
 *
 * @author Paulo Lopes
 */
@VertxGen
public interface WebAuthnHandler extends Handler<RoutingContext> {

  /**
   * Create a WebAuthN auth handler. This handler expects at least the response callback to be installed.
   *
   * @return the auth handler
   */
  static WebAuthnHandler create(WebAuthn webAuthn) {
    return new WebAuthnHandlerImpl(webAuthn);
  }

  /**
   * The callback route to create registration attestations. Usually this route is
/webauthn/register

   *
   * @param route the route where credential get options are generated.
   * @return fluent self.
   */
  @Fluent
  WebAuthnHandler setupCredentialsCreateCallback(Route route);

  /**
   * The callback route to create login attestations. Usually this route is
/webauthn/login

   *
   * @param route the route where credential get options are generated.
   * @return fluent self.
   */
  @Fluent
  WebAuthnHandler setupCredentialsGetCallback(Route route);

  /**
   * The callback route to verify attestations and assertions. Usually this route is
/webauthn/response

   *
   * @param route the route where assertions and attestations are verified.
   * @return fluent self.
   */
  @Fluent
  WebAuthnHandler setupCallback(Route route);
}


text:
class User < ActiveRecord::Base
  enum role: %i(admin org_admin super_admin)

  validates :role, presence: true
  validates :email, presence: true, length: { minimum: 4, maximum: 60 }
  validates :country, presence: true

  devise :database_authenticatable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable

  validates_presence_of :password, if: :password_required?

  belongs_to :organisation
  has_many :drawings, dependent: :destroy

  scope :active, -> { where(deleted_at: nil) }
  scope :desc, -> { order("users.created_at DESC") }

  def soft_delete
    update_attribute(:deleted_at, Time.current)
  end

  def reactivate
    update_attribute(:deleted_at, nil)
  end

  def active_for_authentication?
    super && !deleted_at
  end

  def inactive_message
    !deleted_at ? super : :deleted_account
  end

  def password_required?
    # Password is required if it is being set, but not for new records
    if persisted?
      !confirmed? || password.present? || password_confirmation.present?
    else
      false
    end
  end

  # new function to set the password without knowing the current
  # password used in our confirmation controller.
  def attempt_set_password(params)
    p = {}
    p[:password] = params[:password]
    p[:password_confirmation] = params[:password_confirmation]
    update_attributes(p)
  end

  # new function to return whether a password has been set
  def no_password?
    encrypted_password.blank?
  end

  # Devise::Models:unless_confirmed` method doesn't exist in Devise 2.0.0 anymore.
  # Instead you should use `pending_any_confirmation`.
  def only_if_unconfirmed
    pending_any_confirmation { yield }
  end
end


text:
import NativeObject from './NativeObject';

export default class Printer extends NativeObject {

  /** @override */
  _nativeCreate(param) {
    if (param !== true) {
      throw new Error('Printer can not be created');
    }
    super._nativeCreate();
  }

  get _nativeType() {
    return 'tabris.Printer';
  }

  print(data, options) {
    return new Promise((resolve, reject) => {
      if (arguments.length < 1) {
        throw new Error('Not enough arguments to print');
      }
      if (!isDataValid(data)) {
        throw new Error('data is not an ArrayBuffer or typed array');
      }
      this._nativeCall('print', {
        data: data instanceof ArrayBuffer ? data : data.buffer,
        options,
        onResult: (result) => resolve({result}),
        onError: (error) => reject(new Error(error))
      });
    });
  }

  dispose() {
    throw new Error('Cannot dispose printer object');
  }

}

function isDataValid(value) {
  return (value instanceof ArrayBuffer) ||
    (value instanceof Int8Array) ||
    (value instanceof Uint8Array) ||
    (value instanceof Uint8ClampedArray) ||
    (value instanceof Int16Array) ||
    (value instanceof Uint16Array) ||
    (value instanceof Int32Array) ||
    (value instanceof Uint32Array) ||
    (value instanceof Float32Array) ||
    (value instanceof Float64Array);
}

export function create() {
  return new Printer(true);
}


text:
/*****************************************************************************
 *
 * \file
 *
 * \brief Unit test configuration
 *
 ******************************************************************************/

/**
 * Copyright (c) 2014 Atmel Corporation. All rights reserved.
 *
 * \asf_license_start
 *
 * \page License
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. The name of Atmel may not be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * 4. This software may only be redistributed and used in connection with an
 *    Atmel microcontroller product.
 *
 * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * \asf_license_stop
 *
 */
 /**
 * Support and FAQ: visit Atmel Support
 */
#ifndef CONF_TEST_H
#define CONF_TEST_H

#include "board.h"
#include "sd_mmc_spi.h"
#include "conf_sd_mmc_spi.h"

//! \note Using USART
#define CONF_TEST_USART      USART
//! \note 57600 baud
#define CONF_TEST_BAUDRATE   57600
//! \note 8-bit character length
#define CONF_TEST_CHARLENGTH 8
//! \note No parity check
#define CONF_TEST_PARITY     USART_NO_PARITY
//! \note No extra stopbit, i.e., use 1
#define CONF_TEST_STOPBITS   USART_1_STOPBIT
//! Number of sectors to be read during the multiple sectors access test
#define CONF_TEST_NB_SECTORS 10

/*! \brief Initializes SD/MMC resources: SPI and SD/MMC.
 */
static void sd_mmc_spi_board_init(void)
{
	// SPI options.
	spi_options_t spi_options = {
		.reg         = SD_MMC_SPI_NPCS,
		.baudrate    = SD_MMC_SPI_MASTER_SPEED,
		.bits        = SD_MMC_SPI_BITS,
		.spck_delay  = 0,
		.trans_delay = 0,
		.stay_act    = 1,
		.spi_mode    = 0,
		.modfdis     = 1
	};

	// Initialize as master.
	spi_initMaster(SD_MMC_SPI, &spi_options);

	// Set SPI selection mode: variable_ps, pcs_decode, delay.
	spi_selectionMode(SD_MMC_SPI, 0, 0, 0);

	// Enable SPI module.
	spi_enable(SD_MMC_SPI);

	// Initialize SD/MMC driver with SPI clock (PBA).
	sd_mmc_spi_init(spi_options, sysclk_get_pba_hz());
}

#endif