text:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
module Effect (
    module U,
    Data(..),
    Effect,
    runUserUpdate,
    getLogins,
    getUsers,
    getUserByEmail,
    runServantEffect
) where

import Caltrops.Client
import Web.User as U
import Data.Text (Text)
import Data.Acid
import Data.Acid.Core (MethodState, MethodResult)
import Servant
import Control.Monad.Reader
import Control.Monad.Trans.Either

data Data = Data { userData :: AcidState UserData }

type Effect = (EitherT ServantErr (ReaderT Data IO))

runUserUpdate :: (UpdateEvent event, MethodState event ~ UserData)
              => event -> Effect (MethodResult event)
runUserUpdate f = do
    acid <- asks userData
    liftIO $ update acid f

getUserByEmail :: Text -> Effect (Maybe User)
getUserByEmail e = do
    users <- getUsers
    return $ foldl look4Email Nothing users
        where look4Email (Just u) _ = Just u
              look4Email Nothing u  = if userEmail u == e
                                      then Just u
                                      else Nothing

getLogins :: Effect Logins
getLogins = getsUserData udataLogins

getUsers :: Effect Users
getUsers = getsUserData udataUsers

getsUserData :: (UserData -> a) -> Effect a
getsUserData f = do
    acid <- asks userData
    f <$> (liftIO $ query acid GetUserData)

runServantEffect :: Data -> Effect :~> EitherT ServantErr IO
runServantEffect dat = Nat $ effectToServant dat

effectToServant :: forall a. Data -> Effect a -> EitherT ServantErr IO a
effectToServant dat s = do
    result <- liftIO $ runReaderT (runEitherT s) dat
    case result of
        Left err -> left err
        Right a  -> right a


text:
<?php

class MessagesModel extends Eloquent
{
	protected $table	=	'private_messages';
}

redpajama_set_name: RedPajamaGithub


text:
<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Was willst du Morsen?"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="32dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text"
        android:layout_below="@+id/textView"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:hint="Dein supergeiler Text"
        android:singleLine="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="tu es!"
        android:id="@+id/button"
        android:layout_below="@+id/name"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="25dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Verrate deinen Namen!"
        android:id="@+id/textView2"
        android:layout_below="@+id/text"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="28dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:layout_below="@+id/textView2"
        android:layout_alignRight="@+id/text"
        android:layout_alignEnd="@+id/text"
        android:layout_alignLeft="@+id/text"
        android:layout_alignStart="@+id/text"
        android:singleLine="true"
        android:hint="Der ist optional" />
</RelativeLayout>


text:
from datetime import datetime

TIME_FORMAT = "%H:%M"

def parseTime(time_str):
    return datetime.strptime(time_str, TIME_FORMAT)

def formatTime(time):
    return datetime.strftime(time, TIME_FORMAT)


text: Either your email or your password was wrong...


text:
layout: page
title: "THTR 4049: PROBLM:CONCEPTUALIZATION Statistics"
comments: true
description: "blanks"
keywords: "THTR,4049,CU,Boulder"
---

#### GRADE AND WORKLOAD STATISTICS

**Percent withdrawn**: 10.94%

**Percent incomplete**: 0.0%

**Average grade** (4.0 scale): 3.67

**Standard deviation in grades** (4.0 scale): 0.0

**Average workload** (raw): 2.17

**Standard deviation in workload** (raw): 0.0

#### COURSE AND INSTRUCTOR RATINGS/INFORMATION

**Average course rating** (6 point scale): 3.58

**Standard deviation in course rating** (6 point scale): 0.0

**Average instructor rating** (6 point scale): 3.67

**Standard deviation in instructor rating** (6 point scale): 0.0

**Instructors**: Bruce Alan Bergner

#### GENERAL CLASS INFORMATION

**Years provided**: Spring 2010

**Credits**: 3

**RAP/Honors class?** Neither

**Number of Sections**: 1

**Department**: THDN

**College**: College of Arts and Sciences

**A&S Division**: Arts and Humanities

**Level**: Upper

**Activity**: SEM - Seminar


text:
import os,tarfile,subprocess
import pandas as pd
from igf_data.utils.fileutils import check_file_path,get_temp_dir,remove_dir,copy_local_file
from igf_data.utils.analysis_fastq_fetch_utils import get_fastq_input_list

def run_cellranger_multi(
      cellranger_exe, library_csv, sample_id, output_dir, use_ephemeral_space=False,
      job_timeout=43200, cellranger_options=('--localcores 1','--localmem 8')):
  """
  A function for running Cellranger multi tool

  :param cellranger_exe: Path to Cellranger exe
  :param library_csv: Path to library.csv file
  :param sample_id: Sample id
  :param output_dir: Output path
  :param use_ephemeral_space: A toggle for using EPHEMERAL temp space, default False
  :param job_timeout: Job timeout, default 43200
  :param cellranger_options: Cellranger multi options, default: ('--localcores 1','--localmem 8')
  :returns: two strings, cmd and output_dir
  """
  try:
    tmp_dir = \
      get_temp_dir(
        use_ephemeral_space=use_ephemeral_space)
    os.chdir(tmp_dir)
    check_file_path(library_csv)
    check_file_path(cellranger_exe)
    check_file_path(output_dir)
    cmd = [
      cellranger_exe,
      'multi',
      '--id', sample_id,
      '--csv', library_csv,
      '--disable-ui']
    if isinstance(cellranger_options, tuple):
      cellranger_options = list(cellranger_options)
    if isinstance(cellranger_options, list) and \
       len(cellranger_options) > 0:
      cmd.extend(cellranger_options)
    cmd = \
      ' '.join(cmd)
    try:
      subprocess.\
        check_call(
          cmd,
          shell=True,
          timeout=job_timeout)
    except Exception as e:
      raise ValueError(
              'Failed to run cellranger multi, error: {0}'.\
                format(e))
    cellranger_output = \
      os.path.join(
        tmp_dir,
        sample_id,
        'outs')
    _check_cellranger_multi_output(
      cellranger_output=cellranger_output,
      library_csv=library_csv,
      sample_id=sample_id)
    output_dir = \
      os.path.join(
        output_dir,
        sample_id)
    copy_local_file(
      cellranger_output,
      output_dir)
    output_dir = \
      os.path.join(
        output_dir,
        'per_sample_outs',
        sample_id)
    return cmd, output_dir
  except Exception as e:
    raise ValueError(
            'Failed cellranger run: error: {0}'.format(e))

def _check_cellranger_multi_output(cellranger_output, library_csv, sample_id):
  """
  Internal function for checking cellranger v6 multi output

  :param cellranger_output: Cellranger output path
  :param library_csv: path to cellranger multi csv
  :param sample_id: Sample id, for non cell-multiplexing samples
  :returns: None
  """
  try:
    #file_check_dict = {
    #  'gene_expression':[
    #    'web_summary.html',
    #    'count/filtered_feature_bc_matrix.h5',
    #    'count/possorted_genome_bam.bam',
    #    'count/cloupe.cloupe'],
    #  'vdj':[
    #    'web_summary.html',
    #    'vdj/filtered_contig_annotations.csv',
    #    'vdj/vloupe.vloupe'],
    #  'vdj-b':[
    #    'web_summary.html',
    #    'vdj_b/filtered_contig_annotations.csv',
    #    'vdj_b/vloupe.vloupe'],
    #  'vdj-t':[
    #    'web_summary.html',
    #    'vdj_t/filtered_contig_annotations.csv',
    #    'vdj_t/vloupe.vloupe'],
    #  'antibody_capture':['web_summary.html'],
    #  'antigen_capture':['web_summary.html'],
    #  'crisper_guide_capture':['web_summary.html']}
    file_check_dict = {
      'gene_expression': [
        'per_sample_outs/{0}/web_summary.html'.format(sample_id),
        'per_sample_outs/{0}/metrics_summary.csv'.format(sample_id),
        'per_sample_outs/{0}/count/sample_feature_bc_matrix.h5'.format(sample_id),
        'per_sample_outs/{0}/count/sample_alignments.bam'.format(sample_id),
        'per_sample_outs/{0}/count/cloupe.cloupe'.format(sample_id)],
      'vdj': [
        'per_sample_outs/{0}/web_summary.html'.format(sample_id),
        'per_sample_outs/{0}/vdj/filtered_contig_annotations.csv'.format(sample_id),
        'per_sample_outs/{0}/vdj/vloupe.vloupe'.format(sample_id)],
      'vdj-b': [
        'per_sample_outs/{0}/web_summary.html'.format(sample_id),
        'per_sample_outs/{0}/vdj_b/filtered_contig_annotations.csv'.format(sample_id),
        'per_sample_outs/{0}/vdj_b/vloupe.vloupe'.format(sample_id)],
      'vdj-t': [
        'per_sample_outs/{0}/web_summary.html'.format(sample_id),
        'per_sample_outs/{0}/vdj_t/filtered_contig_annotations.csv'.format(sample_id),
        'per_sample_outs/{0}/vdj_t/vloupe.vloupe'.format(sample_id)],
      'antibody_capture': ['per_sample_outs/{0}/web_summary.html'.format(sample_id)],
      'antigen_capture': ['per_sample_outs/{0}/web_summary.html'.format(sample_id)],
      'crisper_guide_capture': ['per_sample_outs/{0}/web_summary.html'.format(sample_id)]}
    check_file_path(library_csv)
    data = list()
    columns = list()
    with open(library_csv,'r') as fp:
      lib_data = 0
      for line in fp:
        line = line.strip()
        if lib_data == 1:
          if line.startswith('fastq_id'):
            columns = line.split(',')
          else:
            data.extend([line.split(',')])
        if line.startswith('[libraries]'):
          lib_data = 1
    df = pd.DataFrame(data,columns=columns)
    feature_list = \
      list(df['feature_types'].\
           map(lambda x: x.lower().replace(' ','_')).\
           drop_duplicates().values)
    for f in feature_list:
      if f not in file_check_dict:
        raise KeyError('Missing feature {0}'.format(f))
      file_list = file_check_dict.get(f)
      if file_list is None:
        raise ValueError(
                'No file entry found for feature {0}'.\
                  format(f))
      for file_path in file_list:
        check_file_path(
          os.path.join(cellranger_output,file_path))
  except Exception as e:
    raise ValueError(
            'Failed cellranger output checking, error: {0}'.\
              format(e))

def get_cellranger_count_input_list(
      db_session_class, experiment_igf_id, fastq_collection_type='demultiplexed_fastq',
      active_status='ACTIVE'):
  '''
  A function for fetching input list for cellranger count run for a specific experiment

  :param db_session_class: A database session class
  :param experiment_igf_id: An experiment igf id
  :param fastq_collection_type: Fastq collection type name, default demultiplexed_fastq
  :param active_status: text label for active runs, default ACTIVE
  :returns: A list of fastq dir path for the cellranger count run
  :raises ValueError: It raises ValueError if no fastq directory found
  '''
  try:
    fastq_dir_list=get_fastq_input_list(
      db_session_class=db_session_class,
      experiment_igf_id=experiment_igf_id,
      combine_fastq_dir=True,
      fastq_collection_type='demultiplexed_fastq',
      active_status='ACTIVE')                                                   # get fastq dir list
    return fastq_dir_list                                                       # return list of fastq dirs
  except Exception as e:
    raise ValueError(
            'Failed to get cellranger count output list, error: {0}'.format(e))

def check_cellranger_count_output(
      output_path,
      file_list=(
        'web_summary.html',
        'metrics_summary.csv',
        'possorted_genome_bam.bam',
        'possorted_genome_bam.bam.bai',
        'filtered_feature_bc_matrix.h5',
        'raw_feature_bc_matrix.h5',
        'molecule_info.h5',
        'cloupe.cloupe',
        'analysis/tsne/2_components/projection.csv',
        'analysis/clustering/graphclust/clusters.csv',
        'analysis/diffexp/kmeans_3_clusters/differential_expression.csv',
        'analysis/pca/10_components/variance.csv')):
  '''
  A function for checking cellranger count output

  :param output_path: A filepath for cellranger count output directory
  :param file_list: List of files to check in the output directory

    default file list to check
      * web_summary.html
      * metrics_summary.csv
      * possorted_genome_bam.bam
      * possorted_genome_bam.bam.bai
      * filtered_feature_bc_matrix.h5
      * raw_feature_bc_matrix.h5
      * molecule_info.h5
      * cloupe.cloupe
      * analysis/tsne/2_components/projection.csv
      * analysis/clustering/graphclust/clusters.csv
      * analysis/diffexp/kmeans_3_clusters/differential_expression.csv
      * analysis/pca/10_components/variance.csv
  :returns: None
  :raises IOError: when any file is missing from the output path
  '''
  try:
    file_list = list(file_list)
    file_dict_value = [
      i for i in range(len(file_list))]                                         # get file index values
    file_dict = dict(zip(file_list, file_dict_value))                           # convert file list to a dictionary
    for file_name in file_list:
      file_path = \
        os.path.join(
          output_path,
          file_name)
      if os.path.exists(file_path) and \
         os.path.getsize(file_path) > 0:
        del file_dict[file_name]                                                # remove file from dictionary if its present
    if len(list(file_dict.keys())) > 0:
      raise IOError(
              'Partial Cellranger count output found, missing following files: {0}'.\
                format(list(file_dict.keys())))
  except Exception as e:
    raise ValueError('Failed to check cellranger output, error: {0}'.format(e))

def extract_cellranger_count_metrics_summary(
      cellranger_tar, collection_name=None, collection_type=None,
      attribute_name='attribute_name', attribute_value='attribute_value',
      attribute_prefix='None', target_filename='metrics_summary.csv'):
  '''
  A function for extracting metrics summary file for cellranger ourput tar and parse the file.
  Optionally it can add the collection name and type info to the output dictionary.

  :param cellranger_tar: A cellranger output tar file
  :param target_filename: A filename for metrics summary file lookup, default metrics_summary.csv
  :param collection_name: Optional collection name, default None
  :param collection_type: Optional collection type, default None
  :param attribute_tag: An optional string to add as prefix of the attribute names, default None
  :returns: A dictionary containing the metrics values
  '''
  try:
    check_file_path(cellranger_tar)
    temp_work_dir = \
      get_temp_dir(use_ephemeral_space=False)
    metrics_file = None
    with tarfile.open(cellranger_tar, mode='r') as tar:
      for file_name in tar.getnames():
        if os.path.basename(file_name) == target_filename:
            tar.extract(file_name, path=temp_work_dir)
            metrics_file = \
              os.path.join(
                temp_work_dir,
                file_name)
    if metrics_file is None:
      raise IOError(
              'Required file {0} not found in tar {1}'.\
                format(target_filename,cellranger_tar))
    attribute_data = \
      pd.read_csv(metrics_file).\
        T.reset_index()
    attribute_data.columns = [
      attribute_name, attribute_value]
    if attribute_prefix is None:
      attribute_data[attribute_name] = \
        attribute_data[attribute_name].\
          map(lambda x: x.replace(' ', '_'))
    else:
      attribute_data[attribute_name] = \
        attribute_data[attribute_name].\
          map(lambda x: \
              '{0}_{1}'.format(\
                attribute_prefix,
                x.replace(' ', '_')))
    if collection_name is not None:
      attribute_data['name'] = collection_name
    if collection_type is not None:
      attribute_data['type'] = collection_type
    attribute_data = \
      attribute_data.\
        to_dict(orient='records')
    remove_dir(temp_work_dir)
    return attribute_data
  except Exception as e:
    raise ValueError(
            'Failed to extract cellranger tar, error: {0}'.format(e))


text:
import React, { Component } from 'react';
import radium from 'radium';

class AnimationSummaryComponent extends Component {
  constructor(props) {
    super(props);

    this.componentStyle = {};
    this.state = {
      cssRules: [],
    };
  }

  componentWillMount() {
    this.setState({
      cssRules: document.head.querySelector('style').sheet.cssRules,
    });
  }

  render() {
    return (

        {Object.keys(this.state.cssRules).map(key => (

{this.state.cssRules[key].cssText}

        ))}

    );
  }
}

AnimationSummaryComponent.propTypes = {};

export default radium(AnimationSummaryComponent);


text:
var express = require('express'),
    app     = express();

app
   .use(express.static('./public'))
   .get('*', function (req, res) {
      res.sendfile('public/main.html');
}).listen(3000);


text:
/*
* Template function less-than object
*
* The operator() can be used to compare if the pass in object is less than the
* initialized object.
*
* Functors like this one carry the value that is to be compared against with
* them.
*/
template<typename T>
class Less_than{
  const T val;
public:
  Less_than(const T& v) :val(v) {}
  bool operator()(const T& x) const { return x<val; }
};


text:
package channel

import (
	"ipe/connection"
	"ipe/mocks"
	"ipe/subscription"
	"testing"
)

func TestIsOccupied(t *testing.T) {
	c := New("ID")

	if c.IsOccupied() {
		t.Errorf("c.IsOccupied() == %t, wants %t", c.IsOccupied(), false)
	}

	c.subscriptions["ID"] = subscription.New(connection.New("ID", mocks.MockSocket{}), "")

	if !c.IsOccupied() {
		t.Errorf("c.IsOccupied() == %t, wants %t", c.IsOccupied(), true)
	}
}

func TestIsPrivate(t *testing.T) {
	c := New("private-Channel")

	if !c.IsPrivate() {
		t.Errorf("c.IsPrivate() == %t, wants %t", c.IsPrivate(), true)
	}
}

func TestIsPresence(t *testing.T) {
	c := New("presence-Channel")

	if !c.IsPresence() {
		t.Errorf("c.IsPresence() == %t, wants %t", c.IsPresence(), true)
	}
}

func TestIsPublic(t *testing.T) {
	c := New("Channel")

	if !c.IsPublic() {
		t.Errorf("c.IsPublic() == %t, wants %t", c.IsPublic(), true)
	}
}

func TestIsPrivateOrPresence(t *testing.T) {
	c := New("private-Channel")

	if !c.IsPresenceOrPrivate() {
		t.Errorf("c.IsPresenceOrPrivate() == %t, wants %t", c.IsPresenceOrPrivate(), true)
	}

	c = New("presence-Channel")

	if !c.IsPresenceOrPrivate() {
		t.Errorf("c.IsPresenceOrPrivate() == %t, wants %t", c.IsPresenceOrPrivate(), true)
	}
}

func TestTotalSubscriptions(t *testing.T) {
	c := New("ID")

	if c.TotalSubscriptions() != len(c.subscriptions) {
		t.Errorf("c.TotalSubscriptions() == %d, wants %d", c.TotalSubscriptions(), len(c.subscriptions))
	}
}

func TestTotalUsers(t *testing.T) {
	c := New("ID")

	c.subscriptions["1"] = subscription.New(connection.New("ID", mocks.MockSocket{}), "")
	c.subscriptions["2"] = subscription.New(connection.New("ID", mocks.MockSocket{}), "")

	if c.TotalSubscriptions() != len(c.subscriptions) {
		t.Errorf("c.TotalSubscriptions() == %d, wants %d", c.TotalSubscriptions(), len(c.subscriptions))
	}

	if c.TotalUsers() != 1 {
		t.Errorf("c.TotalUsers() == %d, wants %d", c.TotalUsers(), 1)
	}

}

func TestIsSubscribed(t *testing.T) {
	c := New("ID")
	conn := connection.New("ID", mocks.MockSocket{})

	if c.IsSubscribed(conn) {
		t.Errorf("c.IsSubscribed(%q) == %t, wants %t", conn, c.IsSubscribed(conn), false)
	}

	c.subscriptions["ID"] = subscription.New(conn, "")

	if !c.IsSubscribed(conn) {
		t.Errorf("c.IsSubscribed(%q) == %t, wants %t", conn, c.IsSubscribed(conn), true)
	}
}


text:
from mitmproxy.test import tflow
from mitmproxy.test import tutils
from mitmproxy.test import taddons

from mitmproxy.addons import stickycookie
from mitmproxy.test import tutils as ntutils

def test_domain_match():
    assert stickycookie.domain_match("www.google.com", ".google.com")
    assert stickycookie.domain_match("google.com", ".google.com")

class TestStickyCookie:
    def test_config(self):
        sc = stickycookie.StickyCookie()
        with taddons.context() as tctx:
            tutils.raises(
                "invalid filter", tctx.configure, sc, stickycookie="~b"
            )

            tctx.configure(sc, stickycookie="foo")
            assert sc.flt
            tctx.configure(sc, stickycookie=None)
            assert not sc.flt

    def test_simple(self):
        sc = stickycookie.StickyCookie()
        with taddons.context() as tctx:
            tctx.configure(sc, stickycookie=".*")
            f = tflow.tflow(resp=True)
            f.response.headers["set-cookie"] = "foo=bar"
            sc.request(f)

            f.reply.acked = False
            sc.response(f)

            assert sc.jar
            assert "cookie" not in f.request.headers

            f = f.copy()
            f.reply.acked = False
            sc.request(f)
            assert f.request.headers["cookie"] == "foo=bar"

    def _response(self, sc, cookie, host):
        f = tflow.tflow(req=ntutils.treq(host=host, port=80), resp=True)
        f.response.headers["Set-Cookie"] = cookie
        sc.response(f)
        return f

    def test_response(self):
        sc = stickycookie.StickyCookie()
        with taddons.context() as tctx:
            tctx.configure(sc, stickycookie=".*")

            c = "SSID=mooo; domain=.google.com, FOO=bar; Domain=.google.com; Path=/; " \
                "Expires=Wed, 13-Jan-2021 22:23:01 GMT; Secure; "

            self._response(sc, c, "host")
            assert not sc.jar.keys()

            self._response(sc, c, "www.google.com")
            assert sc.jar.keys()

            sc.jar.clear()
            self._response(sc, "SSID=mooo", "www.google.com")
            assert list(sc.jar.keys())[0] == ('www.google.com', 80, '/')

    def test_response_multiple(self):
        sc = stickycookie.StickyCookie()
        with taddons.context() as tctx:
            tctx.configure(sc, stickycookie=".*")

            # Test setting of multiple cookies
            c1 = "somecookie=test; Path=/"
            c2 = "othercookie=helloworld; Path=/"
            f = self._response(sc, c1, "www.google.com")
            f.response.headers["Set-Cookie"] = c2
            sc.response(f)
            googlekey = list(sc.jar.keys())[0]
            assert len(sc.jar[googlekey].keys()) == 2

    def test_response_weird(self):
        sc = stickycookie.StickyCookie()
        with taddons.context() as tctx:
            tctx.configure(sc, stickycookie=".*")

            # Test setting of weird cookie keys
            f = tflow.tflow(req=ntutils.treq(host="www.google.com", port=80), resp=True)
            cs = [
                "foo/bar=hello",
                "foo:bar=world",
                "foo@bar=fizz",
            ]
            for c in cs:
                f.response.headers["Set-Cookie"] = c
                sc.response(f)
            googlekey = list(sc.jar.keys())[0]
            assert len(sc.jar[googlekey].keys()) == len(cs)

    def test_response_overwrite(self):
        sc = stickycookie.StickyCookie()
        with taddons.context() as tctx:
            tctx.configure(sc, stickycookie=".*")

            # Test overwriting of a cookie value
            c1 = "somecookie=helloworld; Path=/"
            c2 = "somecookie=newvalue; Path=/"
            f = self._response(sc, c1, "www.google.com")
            f.response.headers["Set-Cookie"] = c2
            sc.response(f)
            googlekey = list(sc.jar.keys())[0]
            assert len(sc.jar[googlekey].keys()) == 1
            assert list(sc.jar[googlekey]["somecookie"].items())[0][1] == "newvalue"

    def test_response_delete(self):
        sc = stickycookie.StickyCookie()
        with taddons.context() as tctx:
            tctx.configure(sc, stickycookie=".*")

            # Test that a cookie is be deleted
            # by setting the expire time in the past
            f = self._response(sc, "duffer=zafar; Path=/", "www.google.com")
            f.response.headers["Set-Cookie"] = "duffer=; Expires=Thu, 01-Jan-1970 00:00:00 GMT"
            sc.response(f)
            assert not sc.jar.keys()

    def test_request(self):
        sc = stickycookie.StickyCookie()
        with taddons.context() as tctx:
            tctx.configure(sc, stickycookie=".*")

            f = self._response(sc, "SSID=mooo", "www.google.com")
            assert "cookie" not in f.request.headers
            sc.request(f)
            assert "cookie" in f.request.headers


text:
<?php
/**
 * WPSEO plugin file.
 *
 * @package WPSEO\Frontend\Schema
 */

/**
 * Returns schema Organization data.
 *
 * @since 10.2
 */
class WPSEO_Schema_Organization implements WPSEO_Graph_Piece {
	/**
	 * A value object with context variables.
	 *
	 * @var WPSEO_Schema_Context
	 */
	private $context;

	/**
	 * WPSEO_Schema_Breadcrumb constructor.
	 *
	 * @param WPSEO_Schema_Context $context A value object with context variables.
	 */
	public function __construct( WPSEO_Schema_Context $context ) {
		$this->context = $context;
	}

	/**
	 * Determines whether an Organization graph piece should be added.
	 *
	 * @return bool
	 */
	public function is_needed() {
		return ( $this->context->site_represents === 'company' );
	}

	/**
	 * Returns the Organization Schema data.
	 *
	 * @return array $data The Organization schema.
	 */
	public function generate() {
		$data = array(
			'@type'  => 'Organization',
			'@id'    => $this->context->site_url . WPSEO_Schema_IDs::ORGANIZATION_HASH,
			'name'   => $this->context->company_name,
			'url'    => $this->context->site_url,
			'sameAs' => $this->fetch_social_profiles(),
		);
		$data = $this->add_logo( $data );

		return $data;
	}

	/**
	 * Adds a site's logo.
	 *
	 * @param array $data The Organization schema.
	 *
	 * @return array $data The Organization schema.
	 */
	private function add_logo( $data ) {
		$logo = WPSEO_Options::get( 'company_logo', '' );
		if ( empty( $logo ) ) {
			return $data;
		}
		$id            = $this->context->site_url . WPSEO_Schema_IDs::ORGANIZATION_LOGO_HASH;
		$schema_image  = new WPSEO_Schema_Image( $id );
		$data['logo']  = $schema_image->generate_from_url( $logo, $this->context->company_name );
		$data['image'] = array( '@id' => $id );

		return $data;
	}

	/**
	 * Retrieve the social profiles to display in the organization schema.
	 *
	 * @since 1.8
	 *
	 * @link  https://developers.google.com/webmasters/structured-data/customize/social-profiles
	 *
	 * @return array $profiles An array of social profiles.
	 */
	private function fetch_social_profiles() {
		$profiles        = array();
		$social_profiles = array(
			'facebook_site',
			'instagram_url',
			'linkedin_url',
			'myspace_url',
			'youtube_url',
			'pinterest_url',
			'wikipedia_url',
		);
		foreach ( $social_profiles as $profile ) {
			if ( WPSEO_Options::get( $profile, '' ) !== '' ) {
				$profiles[] = WPSEO_Options::get( $profile );
			}
		}

		if ( WPSEO_Options::get( 'twitter_site', '' ) !== '' ) {
			$profiles[] = 'https://twitter.com/' . WPSEO_Options::get( 'twitter_site' );
		}

		return $profiles;
	}
}


text:
use common::{ConsoleLogger, FeatureFlag, FeatureFlags, NamedItem, SourceLocationKey};
use fixture_tests::Fixture;
use graphql_ir::{
    build_ir_with_extra_features, BuilderOptions, FragmentDefinition, FragmentVariablesSemantic,
    OperationDefinition, Program, RelayMode,
};
use graphql_syntax::parse_executable;
use graphql_test_helpers::diagnostics_to_sorted_string;
use graphql_text_printer::print_full_operation;

use intern::string_key::Intern;
use relay_codegen::{
    build_request_params, print_fragment, print_operation, print_request, JsModuleFormat,
};
use relay_compiler::{validate, ProjectConfig};
use relay_config::SchemaConfig;
use relay_test_schema::{
    get_test_schema_with_custom_id, get_test_schema_with_custom_id_with_extensions,
};
use relay_transforms::{apply_transforms, DIRECTIVE_SPLIT_OPERATION};
use std::sync::Arc;

pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> {
    let source_location = SourceLocationKey::standalone(fixture.file_name);

    if fixture.content.contains("%TODO%") {
        if fixture.content.contains("expected-to-throw") {
            return Err("TODO".to_string());
        }
        return Ok("TODO".to_string());
    }

    let parts: Vec<_> = fixture.content.split("%extensions%").collect();
    let (base, schema) = match parts.as_slice() {
        [base, extensions] => (
            base,
            get_test_schema_with_custom_id_with_extensions(extensions),
        ),
        [base] => (base, get_test_schema_with_custom_id()),
        _ => panic!("Invalid fixture input {}", fixture.content),
    };

    let ast = parse_executable(base, source_location)
        .map_err(|diagnostics| diagnostics_to_sorted_string(fixture.content, &diagnostics))?;
    let ir_result = build_ir_with_extra_features(
        &schema,
        &ast.definitions,
        &BuilderOptions {
            allow_undefined_fragment_spreads: false,
            fragment_variables_semantic: FragmentVariablesSemantic::PassedValue,
            relay_mode: Some(RelayMode {
                enable_provided_variables: &FeatureFlag::Enabled,
            }),
            default_anonymous_operation_name: None,
        },
    );
    let ir = ir_result
        .map_err(|diagnostics| diagnostics_to_sorted_string(fixture.content, &diagnostics))?;
    let program = Program::from_definitions(Arc::clone(&schema), ir);

    let feature_flags = FeatureFlags {
        enable_flight_transform: true,
        hash_supported_argument: FeatureFlag::Disabled,
        no_inline: FeatureFlag::Enabled,
        enable_relay_resolver_transform: true,
        enable_3d_branch_arg_generation: true,
        actor_change_support: FeatureFlag::Enabled,
        text_artifacts: FeatureFlag::Disabled,
        enable_client_edges: FeatureFlag::Enabled,
        enable_provided_variables: FeatureFlag::Enabled,
        skip_printing_nulls: FeatureFlag::Disabled,
    };

    let project_config = ProjectConfig {
        name: "test".intern(),
        feature_flags: Arc::new(feature_flags),
        schema_config: SchemaConfig {
            node_interface_id_field: "global_id".intern(),
            ..Default::default()
        },
        js_module_format: JsModuleFormat::Haste,
        ..Default::default()
    };

    validate(&program, &project_config, &None)
        .map_err(|diagnostics| diagnostics_to_sorted_string(fixture.content, &diagnostics))?;

    // TODO pass base fragment names
    let programs = apply_transforms(
        &project_config,
        Arc::new(program),
        Default::default(),
        Arc::new(ConsoleLogger),
        None,
        None,
    )
    .map_err(|diagnostics| diagnostics_to_sorted_string(fixture.content, &diagnostics))?;

    let mut operations: Vec<&std::sync::Arc<OperationDefinition>> =
        programs.normalization.operations().collect();
    operations.sort_by_key(|operation| operation.name.item);
    let result = operations
        .into_iter()
        .map(|operation| {
            if operation
                .directives
                .named(*DIRECTIVE_SPLIT_OPERATION)
                .is_some()
            {
                let mut import_statements = Default::default();
                let operation =
                    print_operation(&schema, operation, &project_config, &mut import_statements);
                format!("{}{}", import_statements, operation)
            } else {
                let name = operation.name.item;
                let print_operation_node = programs
                    .operation_text
                    .operation(name)
                    .expect("a query text operation should be generated for this operation");
                let text = print_full_operation(&programs.operation_text, print_operation_node);

                let reader_operation = programs
                    .reader
                    .operation(name)
                    .expect("a reader fragment should be generated for this operation");
                let operation_fragment = FragmentDefinition {
                    name: reader_operation.name,
                    variable_definitions: reader_operation.variable_definitions.clone(),
                    selections: reader_operation.selections.clone(),
                    used_global_variables: Default::default(),
                    directives: reader_operation.directives.clone(),
                    type_condition: reader_operation.type_,
                };
                let request_parameters = build_request_params(operation);
                let mut import_statements = Default::default();
                let request = print_request(
                    &schema,
                    operation,
                    &operation_fragment,
                    request_parameters,
                    &project_config,
                    &mut import_statements,
                );
                format!("{}{}\n\nQUERY:\n\n{}", import_statements, request, text)
            }
        })
        .chain({
            let mut fragments: Vec<&std::sync::Arc<FragmentDefinition>> =
                programs.reader.fragments().collect();
            fragments.sort_by_key(|fragment| fragment.name.item);
            fragments.into_iter().map(|fragment| {
                let mut import_statements = Default::default();
                let fragment =
                    print_fragment(&schema, fragment, &project_config, &mut import_statements);
                format!("{}{}", import_statements, fragment)
            })
        })
        .collect::<Vec<_>>();
    Ok(result.join("\n\n"))
}


text:
.container {
    width: 100%;
}

html {
  background-color: white;
}

body {
    color: #000080;
}

a {
    color: purple;
}

a:active {
    color: red;
}

.left-coloumn {
    float: left;
    display: inline-block;
    width: 50%;
}

.right-coloumn {
    float: right;
    display: inline-block;
    width: 50%;
}

.top {
    float: top;
    font-weight: bold;
    text-align: center;
    border-bottom: 1px solid black;
}

header>h1 {
        font-size: 212.5%;
}

header>h3 {
        font-size: 120%;
}

.small {
        font-size: 140%;
}

.geico {
    float: bottom;
    clear: both;
    text-align: center;
    font-size: 80%;
    border-top: 1px solid black
}

.comments {
    border-top: 1px solid black;
    border-bottom: 1px solid black;
}

.bottom {
    float: bottom;
    clear: both;
    font-size: 80%;
}

.block {
    display: block;
}

li>p {
    font-size: 50%;
}

.mini {
       font-size: 50%;

}
/*
When linking an external file such as a stylesheet into an HTML file, you should include three attributes. First, define the relationship between the working file and the external file. For linking CSS into HTML, it would be done with a link tag and a rel attribute: <link rel="stylesheet">. Second, declare the type of file being linked with the type attribute: <link rel="stylesheet" type="text/css">. The last attribute to include is the path to the file itself using href: <link rel="stylsheet" type="text/css" href="stylesheets/index.css">.

We tried a few different things to work on positioning the elements. First, we tried breaking up the site into four divs; a top, bottom, left, and right. We floated them to where we thought they should go. We also displayed our left and right divs in inline-block to get them to sit next to each other. That only worked after we set the width of the right and left divs to 50% and the width of the container div to 100%. To keep the bottom from drifting up and next to our left and right divs, we set clear to both. Once we had this basic format, we went through much of the same process to position elements within the header, the footer, and the gieco ad.

Since there is a distinct lack of flair within this website, most of our trickier styling was to do with font sizes. We used font-size for that. I am considering font-color and font-family to dress it up a bit, or maybe even throw in that image they suggested. We'll see.

We decided to use classes within our html to target specific points on the page that we wanted to style. We chose classes instead of ids so that we could apply the same styling to multiple elements. Since we didn't know ahead of time what styling we'd want to put onto all the elements, choosing classes gave us the flexibility to apply css that we had already written on to elements that we had not yet considered. Now that we have all the styling laid out, we could use ids for the elements that don't share any styling with any other elements, but the classes are already there and they work just as well for these purposes. If we were to get into more a more complicated hierarchy of stylings, we might switch some of our classes to ids since id styling overrules class stylings.

When we looked at the site's source code, we were very surprised to see all the inline styling they had done! We were also surprised that they had used a table to display their links. They had each table cell formatted with inline css, which would be a nightmare to go through and change if they ever decided they wanted something different. They also had empty div tags and p tags lying around, which seemed sloppy and untidy. Our code was much more organized, easier to read and easier to change. Our code totally won.
*/


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module App where

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

import Control.Monad.State (StateT, runStateT, modify)
import Control.Monad.Trans (MonadIO)
import Data.Lens.Common (getL, modL)
import Data.Lens.Template (makeLenses)
import Data.Map (Map)
import Data.Monoid (Monoid(..), Sum(..))
import Data.Set (Set)

import qualified Data.Map as Map

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

import Data.Git.Types
import Data.Git.Enumeratee.LinesPerDay

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

type DateMap = Map CommitDate (Sum Integer)
type CommitMap = Map CommitAuthor DateMap

data AppState
  = AppState {
    _commitMap  :: CommitMap
  }
  deriving (Show)

newtype AppMonad m b
  = AppMonad {
    _fromAppMonad :: StateT AppState m b
  }
  deriving (Monad, MonadIO)

makeLenses [''AppState, ''AppMonad]

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

instance Monad m => HasLinesPerDay (AppMonad m) where
  registerLPD author date n = AppMonad $
      modify (modL commitMap appendAuthor)
    where
      appendAuthor = Map.alter appendDate author
      appendDate Nothing = Just $ Map.fromList [(date, Sum n)]
      appendDate (Just datem) = Just $ Map.alter appendSum date datem
      appendSum Nothing = Just $ Sum n
      appendSum (Just n') = Just $ Sum n `mappend` n'

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

emptyAppState :: AppState
emptyAppState = AppState Map.empty

runAppMonad :: Monad m => AppMonad m a -> m (a, AppState)
runAppMonad (AppMonad app) = runStateT app emptyAppState

avgLinesPerDay :: CommitAuthor -> AppState -> Maybe Double
avgLinesPerDay author state =
    processSumDivByDay `fmap` Map.lookup author (getL commitMap state)
  where
    processSumDivByDay :: DateMap -> Double
    processSumDivByDay days =
      let nom = getSum (Map.fold mappend mempty days)
          denom = Map.size days
      in (fromIntegral nom) / (fromIntegral denom)

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


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**_class** | **character** |  | [optional]
**number** | **integer** |  | [optional]
**url** | **character** |  | [optional]
**actions** | [**array[CauseAction]**](CauseAction.md) |  | [optional]
**building** | **character** |  | [optional]
**description** | **character** |  | [optional]
**displayName** | **character** |  | [optional]
**duration** | **integer** |  | [optional]
**estimatedDuration** | **integer** |  | [optional]
**executor** | **character** |  | [optional]
**fullDisplayName** | **character** |  | [optional]
**id** | **character** |  | [optional]
**keepLog** | **character** |  | [optional]
**queueId** | **integer** |  | [optional]
**result** | **character** |  | [optional]
**timestamp** | **integer** |  | [optional]
**builtOn** | **character** |  | [optional]
**changeSet** | [**EmptyChangeLogSet**](EmptyChangeLogSet.md) |  | [optional]


text:
#include "modules/perception/inference/inference_factory.h"

#include "modules/perception/inference/caffe/caffe_net.h"
#include "modules/perception/inference/paddlepaddle/paddle_net.h"
#include "modules/perception/inference/tensorrt/rt_net.h"

namespace apollo {
namespace perception {
namespace inference {

Inference *CreateInferenceByName(const std::string &name,
                                 const std::string &proto_file,
                                 const std::string &weight_file,
                                 const std::vector<std::string> &outputs,
                                 const std::vector<std::string> &inputs,
                                 const std::string &model_root) {
  if (name == "CaffeNet") {
    return new CaffeNet(proto_file, weight_file, outputs, inputs);
  } else if (name == "RTNet") {
    return new RTNet(proto_file, weight_file, outputs, inputs);
  } else if (name == "RTNetInt8") {
    return new RTNet(proto_file, weight_file, outputs, inputs, model_root);
  } else if (name == "PaddleNet") {
    return new PaddleNet(proto_file, weight_file, outputs, inputs);
  }
  return nullptr;
}

}  // namespace inference
}  // namespace perception
}  // namespace apollo


text:
import { ArgType } from "cwise-compiler";
import * as ndarray from "ndarray";

declare function cwise(a: string | cwise.UserArgs): cwise.Return;

declare namespace cwise {
	type Arg = ndarray | ((row: number, col: number) => number) | number[] | any;
	type Return = (a: ndarray, ...b: Arg[]) => void;
	interface UserArgs {
		args: ArgType[];
		pre?(a: number, ...args: any[]): void;
		body(a: number, ...args: any[]): void;
		post?(a: number, ...args: any[]): void;
		funcName?: string;
		blockSize?: number;
		printCode?: boolean;
	}
}
export = cwise;


text:
package permissions.dispatcher.sample.camera;

import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

/**
 * Camera preview that displays a {@link Camera}.
 *
 * Handles basic lifecycle methods to display and stop the preview.
 * <p>
 * Implementation is based directly on the documentation at
 * http://developer.android.com/guide/topics/media/camera.html
 */
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {

    private static final String TAG = "CameraPreview";
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private Camera.CameraInfo mCameraInfo;
    private int mDisplayOrientation;

    public CameraPreview(Context context, Camera camera, Camera.CameraInfo cameraInfo,
            int displayOrientation) {
        super(context);

        // Do not initialise if no camera has been set
        if (camera == null || cameraInfo == null) {
            return;
        }
        mCamera = camera;
        mCameraInfo = cameraInfo;
        mDisplayOrientation = displayOrientation;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
            Log.d(TAG, "Camera preview started.");
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null) {
            // preview surface does not exist
            Log.d(TAG, "Preview surface does not exist");
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
            Log.d(TAG, "Preview stopped.");
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }

        int orientation = calculatePreviewOrientation(mCameraInfo, mDisplayOrientation);
        mCamera.setDisplayOrientation(orientation);

        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();
            Log.d(TAG, "Camera preview started.");
        } catch (Exception e) {
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    /**
     * Calculate the correct orientation for a {@link Camera} preview that is displayed on screen.
     *
     * Implementation is based on the sample code provided in
     * {@link Camera#setDisplayOrientation(int)}.
     */
    public static int calculatePreviewOrientation(Camera.CameraInfo info, int rotation) {
        int degrees = 0;

        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }

        return result;
    }
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Enterphace</title>
	<meta name="description" content="">
	<meta name="author" content="">

	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

	<link rel="stylesheet" href="stylesheets/base.css">
	<link rel="stylesheet" href="stylesheets/skeleton.css">
	<link rel="stylesheet" href="stylesheets/landings.css">
    <link rel="stylesheet" href="stylesheets/landings_layouts.css">

	<link rel="shortcut icon" href="images/favicon.ico">
	<link rel="apple-touch-icon" href="images/apple-touch-icon.png">
	<link rel="apple-touch-icon" sizes="72x72" href="images/apple-touch-icon-72x72.png">
	<link rel="apple-touch-icon" sizes="114x114" href="images/apple-touch-icon-114x114.png">

Featured Homes

                        Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore.

Welcome to Hotel

Lorem ipsum dolor sit amet consectetur adipiscing elite.

                             $45 per day

Best Services

Lorem ipsum dolor sit amet consectetur adipiscing elite.

                             $30 per day

Daily Trips

Lorem ipsum dolor sit amet consectetur adipiscing elite.

                              $75 per day

Great Support

Lorem ipsum dolor sit amet consectetur adipiscing elite.

                              $125 per day


text:
Baccalaureat
============

Projet ecommerce pour le baccalaureat terminale STMG SIG


text:
<?php

namespace EksamiKeskkond\Service;

use Zend\Mail\Message;

class EmailService {

	static function sendEmail($emailTo, $emailFrom, $subject, $body, $transport) {
		$message = new Message();

		$message->setEncoding('UTF-8')
			->addTo($emailTo)
			->addFrom($emailFrom)
			->setSubject($subject)
			->setBody($body);

		$transport->send($message);

		return;
	}
}


text:
/******************************************************************************
  This source file is part of the Avogadro project.
  This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/

#ifndef AVOGADRO_QTPLUGINS_MANIPULATOR_H
#define AVOGADRO_QTPLUGINS_MANIPULATOR_H

#include <avogadro/qtgui/toolplugin.h>

#include <avogadro/qtgui/molecule.h>
#include <avogadro/rendering/primitive.h>

#include <QtCore/QPoint>
#include <QtCore/Qt> // for Qt:: namespace

namespace Avogadro {
namespace QtPlugins {

/**
 * @class Manipulator manipulator.h
 * <avogadro/qtplugins/manipulator/manipulator.h>
 * @brief The Manipulator class manipulates a molecule's geometry.
 * @author Allison Vacanti
 */
class Manipulator : public QtGui::ToolPlugin
{
  Q_OBJECT
public:
  explicit Manipulator(QObject* parent_ = nullptr);
  ~Manipulator() override;

  QString name() const override { return tr("Manipulate tool"); }
  QString description() const override { return tr("Manipulate tool"); }
  unsigned char priority() const override { return 30; }
  QAction* activateAction() const override { return m_activateAction; }
  QWidget* toolWidget() const override;

  void setMolecule(QtGui::Molecule* mol) override
  {
    if (mol)
      m_molecule = mol->undoMolecule();
  }

  void setEditMolecule(QtGui::RWMolecule* mol) override { m_molecule = mol; }

  void setGLRenderer(Rendering::GLRenderer* renderer) override
  {
    m_renderer = renderer;
  }

  QUndoCommand* mousePressEvent(QMouseEvent* e) override;
  QUndoCommand* mouseReleaseEvent(QMouseEvent* e) override;
  QUndoCommand* mouseMoveEvent(QMouseEvent* e) override;

private:
  /**
   * Update the currently pressed buttons, accounting for modifier keys.
   * \todo Account for modifier keys.
   */
  void updatePressedButtons(QMouseEvent*, bool release);

  void resetObject() { m_object = Rendering::Identifier(); }
  void translate(Vector3 delta);
  void rotate(Vector3 delta, Vector3 centroid);
  void tilt(Vector3 delta, Vector3 centroid);

  QAction* m_activateAction;
  QtGui::RWMolecule* m_molecule;
  Rendering::GLRenderer* m_renderer;
  Rendering::Identifier m_object;
  QPoint m_lastMousePosition;
  Vector3f m_lastMouse3D;
  Qt::MouseButtons m_pressedButtons;

  enum ToolAction
  {
    Nothing = 0,
    Rotation,
    Translation,
    ZoomTilt,
    Zoom
  };
  ToolAction m_currentAction;
};

} // namespace QtOpenGL
} // namespace Avogadro

#endif // AVOGADRO_QTOPENGL_MANIPULATOR_H


text:
using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.IO;
using System.Linq;
using NUnit.Framework;
using ProtoBuf;
using ProtoBuf.Meta;

namespace Examples.Issues
{
    [TestFixture]
    public class Issue297
    {
    // also asked: http://stackoverflow.com/q/11134370
        [Test]
        public void TestInt32()
        {
            Node<int> tree = new Node<int>.RootNode("abc",1), clone;
            var children = tree.getChildren();
            children.Add(new Node<int>("abc/def", 2));
            children.Add(new Node<int>("abc/ghi", 3));
            Assert.AreEqual(2, tree.getChildren().Count);

            using(var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, tree);
                Assert.Greater(1, 0); // I always get these args the wrong way around, so always check!
                Assert.Greater(ms.Length, 0);
                ms.Position = 0;
                clone = Serializer.Deserialize<Node<int>>(ms);
            }
            Assert.IsInstanceOfType(typeof(Node<int>.RootNode), clone);
            Assert.AreEqual("abc", clone.Key);
            Assert.AreEqual(1, clone.Value);
            children = clone.getChildren();
            Assert.AreEqual(2, children.Count);

            Assert.IsFalse(children[0].HasChildren);
            Assert.AreEqual("abc/def", children[0].Key);
            Assert.AreEqual(2, children[0].Value);

            Assert.IsFalse(children[1].HasChildren);
            Assert.AreEqual("abc/ghi", children[1].Key);
            Assert.AreEqual(3, children[1].Value);
        }

        [TestFixtureSetUp]
        public void Init()
        {
            RuntimeTypeModel.Default.Add(typeof(Node<int>), true).AddSubType(4, typeof(Node<int>.RootNode));
            RuntimeTypeModel.Default.Add(typeof(Node<MyDto>), true).AddSubType(4, typeof(Node<MyDto>.RootNode));
            RuntimeTypeModel.Default.Add(typeof(Node<SomeNewType>), true).AddSubType(4, typeof(Node<SomeNewType>.RootNode));
        }

        [Test]
        public void TestMyDTO()
        {
            Node<MyDto> tree = new Node<MyDto>.RootNode("abc", new MyDto { Value =  1}), clone;
            var children = tree.getChildren();
            children.Add(new Node<MyDto>("abc/def", new MyDto { Value =  2}));
            children.Add(new Node<MyDto>("abc/ghi", new MyDto { Value =  3}));
            Assert.AreEqual(2, tree.getChildren().Count);

            using (var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, tree);
                Assert.Greater(1, 0); // I always get these args the wrong way around, so always check!
                Assert.Greater(ms.Length, 0);
                ms.Position = 0;
                clone = Serializer.Deserialize<Node<MyDto>>(ms);
            }
            Assert.IsInstanceOfType(typeof(Node<MyDto>.RootNode), clone);
            Assert.AreEqual("abc", clone.Key);
            Assert.AreEqual(1, clone.Value.Value);
            children = clone.getChildren();
            Assert.AreEqual(2, children.Count);

            Assert.IsFalse(children[0].HasChildren);
            Assert.AreEqual("abc/def", children[0].Key);
            Assert.AreEqual(2, children[0].Value.Value);

            Assert.IsFalse(children[1].HasChildren);
            Assert.AreEqual("abc/ghi", children[1].Key);
            Assert.AreEqual(3, children[1].Value.Value);
        }

        [Test, ExpectedException(typeof(NotSupportedException), ExpectedMessage = "Nested or jagged lists and arrays are not supported"), Ignore("Needs attention")]
        public void TestListMyDTO()
        {
            Node<List<MyDto>> tree = new Node<List<MyDto>>.RootNode("abc", new List<MyDto> { new MyDto { Value = 1 }}), clone;
            var children = tree.getChildren();
            children.Add(new Node<List<MyDto>>("abc/def", new List<MyDto> { new MyDto { Value = 2 } }));
            children.Add(new Node<List<MyDto>>("abc/ghi", new List<MyDto> { new MyDto { Value = 3 } }));
            Assert.AreEqual(2, tree.getChildren().Count);

            using (var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, tree);
                Assert.Greater(1, 0); // I always get these args the wrong way around, so always check!
                Assert.Greater(ms.Length, 0, "stream length");
                ms.Position = 0;
                clone = Serializer.Deserialize<Node<List<MyDto>>>(ms);
            }

            Assert.AreEqual("abc", clone.Key);
            Assert.AreEqual(1, clone.Value.Single().Value);
            children = clone.getChildren();
            Assert.AreEqual(2, children.Count);

            Assert.IsFalse(children[0].HasChildren);
            Assert.AreEqual("abc/def", children[0].Key);
            Assert.AreEqual(2, children[0].Value.Single().Value);

            Assert.IsFalse(children[1].HasChildren);
            Assert.AreEqual("abc/ghi", children[1].Key);
            Assert.AreEqual(3, children[1].Value.Single().Value);
        }

        [Test]
        public void TestSomeNewType()
        {
            Node<SomeNewType> tree = new Node<SomeNewType>.RootNode("abc", new SomeNewType { Items = { new MyDto { Value = 1 } }}), clone;
            var children = tree.getChildren();
            children.Add(new Node<SomeNewType>("abc/def", new SomeNewType { Items = { new MyDto { Value = 2 } } }));
            children.Add(new Node<SomeNewType>("abc/ghi", new SomeNewType { Items = { new MyDto { Value = 3 } } }));
            Assert.AreEqual(2, tree.getChildren().Count);

            using (var ms = new MemoryStream())
            {
                Serializer.Serialize(ms, tree);
                Assert.Greater(1, 0); // I always get these args the wrong way around, so always check!
                Assert.Greater(ms.Length, 0);
                ms.Position = 0;
                clone = Serializer.Deserialize<Node<SomeNewType>>(ms);
            }

            Assert.AreEqual("abc", clone.Key);
            Assert.AreEqual(1, clone.Value.Items.Single().Value);
            children = clone.getChildren();
            Assert.AreEqual(2, children.Count);

            Assert.IsFalse(children[0].HasChildren);
            Assert.AreEqual("abc/def", children[0].Key);
            Assert.AreEqual(2, children[0].Value.Items.Single().Value);

            Assert.IsFalse(children[1].HasChildren);
            Assert.AreEqual("abc/ghi", children[1].Key);
            Assert.AreEqual(3, children[1].Value.Items.Single().Value);
        }

        [ProtoContract]
        class SomeNewType
        {
            [ProtoMember(1)]
            public List<MyDto> Items { get { return items; } }
            private readonly List<MyDto> items = new List<MyDto>();
        }

        [Serializable, ProtoContract]
        public class Node<T>
        {
            [ProtoMember(3)]
            private readonly List<Node<T>> children = new List<Node<T>>();
            [ProtoMember(1)]
            private readonly string key;
            [ProtoMember(2)]
            private T value;

            public string Key { get { return key; } }
            public T Value { get { return value; } }

            public Node(string key, T value)
            {
                this.key = key;
                this.value = value;
            }

            private Node()
            {
            }

            public bool HasChildren
            {
                get { return children.Count > 0; }
            }

            public void Insert(string key, T value)
            {
                var potentialChild = new Node<T>(key, value);
                Add(potentialChild);
            }

            private bool Add(Node<T> theNewChild)
            {
                if (Contains(theNewChild))
                    throw new DuplicateKeyException(string.Format("Duplicate key: '{0}'", theNewChild.key));

                if (!IsParentOf(theNewChild))
                    return false;

                bool childrenObligedRequest = RequestChildrenToOwn(theNewChild);
                if (childrenObligedRequest) return true;

                AcceptAsOwnChild(theNewChild);
                return true;
            }

            private bool RequestChildrenToOwn(Node<T> newChild)
            {
                return
                    children.Exists(
                        existingChild =>
                        existingChild.MergeIfSameAs(newChild) || existingChild.Add(newChild) ||
                        ForkANewChildAndAddChildren(existingChild, newChild));
            }

            private bool MergeIfSameAs(Node<T> potentialChild)
            {
                if (!IsTheSameAs(potentialChild) || IsNotUnrealNode())
                    return false;

                value = potentialChild.value;
                return true;
            }

            private bool IsNotUnrealNode()
            {
                return !IsUnrealNode();
            }

            private void Disown(Node<T> existingChild)
            {
                children.Remove(existingChild);
            }

            private Node<T> AcceptAsOwnChild(Node<T> child)
            {
                if (NotItself(child)) children.Add(child);
                return this;
            }

            private bool NotItself(Node<T> child)
            {
                return !Equals(child);
            }

            private bool ForkANewChildAndAddChildren(Node<T> existingChild, Node<T> newChild)
            {
                if (existingChild.IsNotMySibling(newChild))
                    return false;

                var surrogateParent = MakeASurrogateParent(existingChild, newChild);
                if (surrogateParent.IsTheSameAs(this))
                    return false;

                SwapChildren(existingChild, newChild, surrogateParent);
                return true;
            }

            private bool IsNotMySibling(Node<T> newChild)
            {
                return !IsMySibling(newChild);
            }

            private void SwapChildren(Node<T> existingChild, Node<T> newChild, Node<T> surrogateParent)
            {
                surrogateParent.AcceptAsOwnChild(existingChild)
                    .AcceptAsOwnChild(newChild);

                AcceptAsOwnChild(surrogateParent);
                Disown(existingChild);
            }

            private Node<T> MakeASurrogateParent(Node<T> existingChild, Node<T> newChild)
            {
                string keyForNewParent = existingChild.CommonBeginningInKeys(newChild);
                keyForNewParent = keyForNewParent.Trim();
                var surrogateParent = new Node<T>(keyForNewParent, default(T));

                return surrogateParent.IsTheSameAs(newChild) ? newChild : surrogateParent;
            }

            private bool IsTheSameAs(Node<T> parent)
            {
                return Equals(parent);
            }

            private bool IsMySibling(Node<T> potentialSibling)
            {
                return CommonBeginningInKeys(potentialSibling).Length > 0;
            }

            private string CommonBeginningInKeys(Node<T> potentialSibling)
            {
                return "foo"; // return key.CommonBeginningWith(potentialSibling.key);
            }

            internal virtual bool IsParentOf(Node<T> potentialChild)
            {
                return potentialChild.key.StartsWith(key);
            }

            public bool Delete(string key)
            {
                Node<T> nodeToBeDeleted = children.Find(child => child.Find(key) != null);
                if (nodeToBeDeleted == null) return false;

                if (nodeToBeDeleted.HasChildren)
                {
                    nodeToBeDeleted.MarkAsUnreal();
                    return true;
                }

                children.Remove(nodeToBeDeleted);
                return true;
            }

            private void MarkAsUnreal()
            {
                value = default(T);
            }

            public T Find(string key)
            {
                var childBeingSearchedFor = new Node<T>(key, default(T));
                return Find(childBeingSearchedFor);
            }

            private T Find(Node<T> childBeingSearchedFor)
            {
                if (Equals(childBeingSearchedFor)) return value;
                T node = default(T);
                children.Find(child =>
                                  {
                                      node = child.Find(childBeingSearchedFor);
                                      return node != null;
                                  });
                if (node == null) return default(T);
                return node;
            }

            public bool Contains(string key)
            {
                return Contains(new Node<T>(key, default(T)));
            }

            private bool Contains(Node<T> child)
            {
                if (Equals(child) && IsUnrealNode()) return false;

                if (Equals(child)) return true;

                return children.Exists(node => node.Contains(child));
            }

            private bool IsUnrealNode()
            {
                return value == null;
            }

            public List<T> Search(string keyPrefix)
            {
                var nodeBeingSearchedFor = new Node<T>(keyPrefix, default(T));
                return Search(nodeBeingSearchedFor);
            }

            private List<T> Search(Node<T> nodeBeingSearchedFor)
            {
                if (IsTheSameAs(nodeBeingSearchedFor))
                    return MeAndMyDescendants();

                return SearchInMyChildren(nodeBeingSearchedFor);
            }

            private List<T> SearchInMyChildren(Node<T> nodeBeingSearchedFor)
            {
                List<T> searchResults = null;

                children.Exists(
                    existingChild => (searchResults = existingChild.SearchUpAndDown(nodeBeingSearchedFor)).Count > 0);

                return searchResults;
            }

            private List<T> SearchUpAndDown(Node<T> node)
            {
                if (node.IsParentOf(this))
                    return MeAndMyDescendants();

                return IsParentOf(node) ? Search(node) : new List<T>();

            }

            private List<T> MeAndMyDescendants()
            {
                var meAndMyDescendants = new List<T>();
                if (!IsUnrealNode())
                    meAndMyDescendants.Add(value);

                children.ForEach(child => meAndMyDescendants.AddRange(child.MeAndMyDescendants()));
                return meAndMyDescendants;
            }

            public long Size()
            {
                const long size = 0;
                return Size(size);
            }

            private long Size(long size)
            {
                if (!IsUnrealNode())
                    size++;

                children.ForEach(node => size += node.Size());
                return size;
            }

            public override string ToString()
            {
                return key;
            }

            public bool Equals(Node<T> other)
            {
                if (ReferenceEquals(null, other)) return false;
                if (ReferenceEquals(this, other)) return true;
                return Equals(other.key, key);
            }

            public override bool Equals(object obj)
            {
                if (ReferenceEquals(null, obj)) return false;
                if (ReferenceEquals(this, obj)) return true;
                if (obj.GetType() != typeof (Node<T>)) return false;
                return Equals((Node<T>) obj);
            }

            public override int GetHashCode()
            {
                return (key != null ? key.GetHashCode() : 0);
            }

            public static Node<T> Root()
            {
                return new RootNode();
            }

            public List<Node<T>> getChildren()
            {
                return children;
            }

            [Serializable, ProtoContract]
            public class RootNode : Node<T>
            {
                public RootNode() { }
                public RootNode(string key, T value) : base(key, value) {}
                internal override bool IsParentOf(Node<T> potentialChild)
                {
                    return true;
                }
            }

        }
        [ProtoContract]
        public class MyDto
        {
            [ProtoMember(1)]
            public int Value { get; set; }
        }
    }
}


text:
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/random.h>
#include "cifs_unicode.h"
#include "cifspdu.h"
#include "md5.h"
#include "cifs_debug.h"
#include "cifsencrypt.h"

#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif

/* following came from the other byteorder.h to avoid include conflicts */
#define CVAL(buf,pos) (((unsigned char *)(buf))[pos])
#define SSVALX(buf,pos,val) (CVAL(buf,pos)=(val)&0xFF,CVAL(buf,pos+1)=(val)>>8)
#define SSVAL(buf,pos,val) SSVALX((buf),(pos),((__u16)(val)))

/*The following definitions come from  libsmb/smbencrypt.c  */

void SMBencrypt(unsigned char *passwd, unsigned char *c8, unsigned char *p24);
void E_md4hash(const unsigned char *passwd, unsigned char *p16);
void nt_lm_owf_gen(char *pwd, unsigned char nt_p16[16], unsigned char p16[16]);
static void SMBOWFencrypt(unsigned char passwd[16], unsigned char *c8,
		   unsigned char p24[24]);
void NTLMSSPOWFencrypt(unsigned char passwd[8],
		       unsigned char *ntlmchalresp, unsigned char p24[24]);
void SMBNTencrypt(unsigned char *passwd, unsigned char *c8, unsigned char *p24);

/*
   This implements the X/Open SMB password encryption
   It takes a password, a 8 byte "crypt key" and puts 24 bytes of
   encrypted password into p24 */
/* Note that password must be uppercased and null terminated */
void
SMBencrypt(unsigned char *passwd, unsigned char *c8, unsigned char *p24)
{
	unsigned char p14[15], p21[21];

	memset(p21, '\0', 21);
	memset(p14, '\0', 14);
	strncpy((char *) p14, (char *) passwd, 14);

/*	strupper((char *)p14); *//* BB at least uppercase the easy range */
	E_P16(p14, p21);

	SMBOWFencrypt(p21, c8, p24);

	memset(p14,0,15);
	memset(p21,0,21);
}

/* Routines for Windows NT MD4 Hash functions. */
static int
_my_wcslen(__u16 * str)
{
	int len = 0;
	while (*str++ != 0)
		len++;
	return len;
}

/*
 * Convert a string into an NT UNICODE string.
 * Note that regardless of processor type
 * this must be in intel (little-endian)
 * format.
 */

static int
_my_mbstowcs(__u16 * dst, const unsigned char *src, int len)
{				/* not a very good conversion routine - change/fix */
	int i;
	__u16 val;

	for (i = 0; i < len; i++) {
		val = *src;
		SSVAL(dst, 0, val);
		dst++;
		src++;
		if (val == 0)
			break;
	}
	return i;
}

/*
 * Creates the MD4 Hash of the users password in NT UNICODE.
 */

void
E_md4hash(const unsigned char *passwd, unsigned char *p16)
{
	int len;
	__u16 wpwd[129];

	/* Password cannot be longer than 128 characters */
	if(passwd) {
		len = strlen((char *) passwd);
		if (len > 128) {
			len = 128;
		}
		/* Password must be converted to NT unicode */
		_my_mbstowcs(wpwd, passwd, len);
	} else
		len = 0;

	wpwd[len] = 0;	/* Ensure string is null terminated */
	/* Calculate length in bytes */
	len = _my_wcslen(wpwd) * sizeof (__u16);

	mdfour(p16, (unsigned char *) wpwd, len);
	memset(wpwd,0,129 * 2);
}

/* Does both the NT and LM owfs of a user's password */
void
nt_lm_owf_gen(char *pwd, unsigned char nt_p16[16], unsigned char p16[16])
{
	char passwd[514];

	memset(passwd, '\0', 514);
	if (strlen(pwd) < 513)
		strcpy(passwd, pwd);
	else
		memcpy(passwd, pwd, 512);
	/* Calculate the MD4 hash (NT compatible) of the password */
	memset(nt_p16, '\0', 16);
	E_md4hash(passwd, nt_p16);

	/* Mangle the passwords into Lanman format */
	passwd[14] = '\0';
/*	strupper(passwd); */

	/* Calculate the SMB (lanman) hash functions of the password */

	memset(p16, '\0', 16);
	E_P16((unsigned char *) passwd, (unsigned char *) p16);

	/* clear out local copy of user's password (just being paranoid). */
	memset(passwd, '\0', sizeof (passwd));
}

/* Does the NTLMv2 owfs of a user's password */
#if 0  /* function not needed yet - but will be soon */
static void
ntv2_owf_gen(const unsigned char owf[16], const char *user_n,
		const char *domain_n, unsigned char kr_buf[16],
		const struct nls_table *nls_codepage)
{
	wchar_t * user_u;
	wchar_t * dom_u;
	int user_l, domain_l;
	struct HMACMD5Context ctx;

	/* might as well do one alloc to hold both (user_u and dom_u) */
	user_u = kmalloc(2048 * sizeof(wchar_t),GFP_KERNEL);
	if(user_u == NULL)
		return;
	dom_u = user_u + 1024;

	/* push_ucs2(NULL, user_u, user_n, (user_l+1)*2, STR_UNICODE|STR_NOALIGN|STR_TERMINATE|STR_UPPER);
	   push_ucs2(NULL, dom_u, domain_n, (domain_l+1)*2, STR_UNICODE|STR_NOALIGN|STR_TERMINATE|STR_UPPER); */

	/* BB user and domain may need to be uppercased */
	user_l = cifs_strtoUCS(user_u, user_n, 511, nls_codepage);
	domain_l = cifs_strtoUCS(dom_u, domain_n, 511, nls_codepage);

	user_l++;		/* trailing null */
	domain_l++;

	hmac_md5_init_limK_to_64(owf, 16, &ctx);
	hmac_md5_update((const unsigned char *) user_u, user_l * 2, &ctx);
	hmac_md5_update((const unsigned char *) dom_u, domain_l * 2, &ctx);
	hmac_md5_final(kr_buf, &ctx);

	kfree(user_u);
}
#endif

/* Does the des encryption from the NT or LM MD4 hash. */
static void
SMBOWFencrypt(unsigned char passwd[16], unsigned char *c8,
	      unsigned char p24[24])
{
	unsigned char p21[21];

	memset(p21, '\0', 21);

	memcpy(p21, passwd, 16);
	E_P24(p21, c8, p24);
}

/* Does the des encryption from the FIRST 8 BYTES of the NT or LM MD4 hash. */
void
NTLMSSPOWFencrypt(unsigned char passwd[8],
		  unsigned char *ntlmchalresp, unsigned char p24[24])
{
	unsigned char p21[21];

	memset(p21, '\0', 21);
	memcpy(p21, passwd, 8);
	memset(p21 + 8, 0xbd, 8);

	E_P24(p21, ntlmchalresp, p24);
}

/* Does the NT MD4 hash then des encryption. */

void
SMBNTencrypt(unsigned char *passwd, unsigned char *c8, unsigned char *p24)
{
	unsigned char p21[21];

	memset(p21, '\0', 21);

	E_md4hash(passwd, p21);
	SMBOWFencrypt(p21, c8, p24);
}

/* Does the md5 encryption from the NT hash for NTLMv2. */
/* These routines will be needed later */
#if 0
static void
SMBOWFencrypt_ntv2(const unsigned char kr[16],
                   const struct data_blob * srv_chal,
                   const struct data_blob * cli_chal, unsigned char resp_buf[16])
{
        struct HMACMD5Context ctx;

        hmac_md5_init_limK_to_64(kr, 16, &ctx);
        hmac_md5_update(srv_chal->data, srv_chal->length, &ctx);
        hmac_md5_update(cli_chal->data, cli_chal->length, &ctx);
        hmac_md5_final(resp_buf, &ctx);
}

static void
SMBsesskeygen_ntv2(const unsigned char kr[16],
		   const unsigned char *nt_resp, __u8 sess_key[16])
{
	struct HMACMD5Context ctx;

	hmac_md5_init_limK_to_64(kr, 16, &ctx);
	hmac_md5_update(nt_resp, 16, &ctx);
	hmac_md5_final((unsigned char *) sess_key, &ctx);
}

static void
SMBsesskeygen_ntv1(const unsigned char kr[16],
		   const unsigned char *nt_resp, __u8 sess_key[16])
{
	mdfour((unsigned char *) sess_key, (unsigned char *) kr, 16);
}
#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<holidays xmlns="https://kayaposoft.com/enrico/xsd/1.0" country="ukr">
	<metadata>
		<reference>https://en.wikipedia.org/wiki/Public_holidays_in_Ukraine</reference>
	</metadata>

	<holiday validFrom="2021-01-01" validTo="2021-12-31" holidayType="extra_working_day">
		<date>
			<fixedDate day="16" month="1" />
		</date>
		<name lang="uk">Робочий день</name>
		<name lang="en">Extra Working Day</name>
	</holiday>

	<holiday validFrom="2021-01-01" validTo="2021-12-31" holidayType="extra_working_day">
		<date>
			<fixedDate day="28" month="8" />
		</date>
		<name lang="uk">Робочий день</name>
		<name lang="en">Extra Working Day</name>
	</holiday>

	<holiday validFrom="2021-01-01" validTo="2021-12-31" holidayType="extra_working_day">
		<date>
			<fixedDate day="23" month="10" />
		</date>
		<name lang="uk">Робочий день</name>
		<name lang="en">Extra Working Day</name>
	</holiday>

</holidays>


text:
import {Component, Input} from '@angular/core';

@Component({
    selector: 'employment-card',
    template: `
<div [style.display]='active? "block" : "none"'>
    <h1>{{title}}</h1>
    <ng-content></ng-content>
</div>
    `
})
export class EmploymentCard
{
    @Input() title: string;
    @Input() active: boolean = false;
}


text:
require 'rails_helper'
require 'description_formatter'

describe DescriptionFormatter do
  describe '.format' do
    it 'replaces & with ampersands' do
      description = 'bread & butter'

      expect(
        DescriptionFormatter.format(description: description)
      ).to eq 'bread & butter'
    end

    it 'does not replace & followed with # (html entity)' do
      description = ''A' with an 'X''

      expect(
        DescriptionFormatter.format(description: description)
      ).to eq description
    end

    it 'does not replace & followed by nbsp (non breaking space entity)' do
      description = 'a paragraph'

      expect(
        DescriptionFormatter.format(description: description)
      ).to eq description
    end

    it 'replaces | with non breaking space html entity' do
      expect(
        DescriptionFormatter.format(description: ' | ')
      ).to eq '   '
    end

    it 'replaces !1! with breaking space tags' do
      expect(
        DescriptionFormatter.format(description: ' !1! ')
      ).to eq '
 '
    end

    it 'replaces !X! with times html entity' do
      expect(
        DescriptionFormatter.format(description: ' !X! ')
      ).to eq ' × '
    end

    it 'replaces !x! with times html entity' do
      expect(
        DescriptionFormatter.format(description: ' !x! ')
      ).to eq ' × '
    end

    it 'replaces !o! with deg html entity' do
      expect(
        DescriptionFormatter.format(description: ' !o! ')
      ).to eq ' ° '
    end

    it 'replaces !O! with deg html entity' do
      expect(
        DescriptionFormatter.format(description: ' !O! ')
      ).to eq ' ° '
    end

    it 'replaces !>=! with greater or equals html entity' do
      expect(
        DescriptionFormatter.format(description: ' !>=! ')
      ).to eq ' ≥ '
    end

    it 'replaces !<=! with less or equal html entity' do
      expect(
        DescriptionFormatter.format(description: ' !<=! ')
      ).to eq ' ≤ '
    end

    it 'replaces and wraps @<anycharacter> with html sub tag' do
      expect(
        DescriptionFormatter.format(description: ' @1 ')
      ).to eq ' 1 '
    end

    it 'replaces and wraps $<anycharacter> with html sup tag' do
      expect(
        DescriptionFormatter.format(description: ' $1 ')
      ).to eq ' 1 '
    end
  end
end


text:
package com.citelic.game.entity.npc.combat;

import java.util.HashMap;

import com.citelic.game.entity.Entity;
import com.citelic.game.entity.npc.NPC;
import com.citelic.utility.Logger;
import com.citelic.utility.Utilities;

public class CombatScriptsHandler {

	private static final HashMap<Object, CombatScript> cachedCombatScripts = new HashMap<Object, CombatScript>();
	private static final CombatScript DEFAULT_SCRIPT = new Default();

	@SuppressWarnings("rawtypes")
	public static final void init() {
		try {
			Class[] classes = Utilities
					.getClasses("com.citelic.game.entity.npc.combat.impl");
			for (Class c : classes) {
				if (c.isAnonymousClass()) // next
					continue;
				Object o = c.newInstance();
				if (!(o instanceof CombatScript))
					continue;
				CombatScript script = (CombatScript) o;
				for (Object key : script.getKeys())
					cachedCombatScripts.put(key, script);
			}
		} catch (Throwable e) {
			Logger.handle(e);
		}
	}

	public static int specialAttack(final NPC npc, final Entity target) {
		CombatScript script = cachedCombatScripts.get(npc.getId());
		if (script == null) {
			script = cachedCombatScripts.get(npc.getDefinitions().name);
			if (script == null)
				script = DEFAULT_SCRIPT;
		}
		return script.attack(npc, target);
	}
}


text:
This website was created based on a theme developed by Camille Diez (http://diezcami.github.io/). Theme details and license are below. Thanks for the theme, Camille!

# Arctic Fox
An open source minimal theme for Jekyll, ideal for blogging.

View the demo at http://diezcami.github.io/arctic-fox-theme

## License
The MIT License (MIT)

Copyright (c) 2015 Camille Diez

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.


text:
import { Action } from "action/Action";
import { ActionArgument } from "action/IAction";
declare const _default: Action<[[ActionArgument.ItemNearby, ActionArgument.Undefined], [ActionArgument.Doodad, ActionArgument.Undefined], [ActionArgument.RestType, ActionArgument.Undefined], [ActionArgument.Boolean, ActionArgument.Undefined]], import("../../player/IPlayer").IPlayer, void>;
export default _default;


text:
driver-go-webhook
=================


text:
/*
Package magic implements simple interface to libmagic for Go Programming Language.
*/
package magic


text:
package mutate

import (
	"github.com/google/go-containerregistry/pkg/v1/types"
	"github.com/sigstore/cosign/pkg/cosign/bundle"
	"github.com/sigstore/cosign/pkg/oci"
)

// DupeDetector scans a list of signatures looking for a duplicate.
type DupeDetector interface {
	Find(oci.Signatures, oci.Signature) (oci.Signature, error)
}

type ReplaceOp interface {
	Replace(oci.Signatures, oci.Signature) (oci.Signatures, error)
}

type SignOption func(*signOpts)

type signOpts struct {
	dd DupeDetector
	ro ReplaceOp
}

func makeSignOpts(opts ...SignOption) *signOpts {
	so := &signOpts{}
	for _, opt := range opts {
		opt(so)
	}
	return so
}

// WithDupeDetector configures Sign* to use the following DupeDetector
// to avoid attaching duplicate signatures.
func WithDupeDetector(dd DupeDetector) SignOption {
	return func(so *signOpts) {
		so.dd = dd
	}
}

func WithReplaceOp(ro ReplaceOp) SignOption {
	return func(so *signOpts) {
		so.ro = ro
	}
}

type signatureOpts struct {
	annotations map[string]string
	bundle      *bundle.RekorBundle
	cert        []byte
	chain       []byte
	mediaType   types.MediaType
}

type SignatureOption func(*signatureOpts)

// WithAnnotations specifies the annotations the Signature should have.
func WithAnnotations(annotations map[string]string) SignatureOption {
	return func(so *signatureOpts) {
		so.annotations = annotations
	}
}

// WithBundle specifies the new Bundle the Signature should have.
func WithBundle(b *bundle.RekorBundle) SignatureOption {
	return func(so *signatureOpts) {
		so.bundle = b
	}
}

// WithCertChain specifies the new cert and chain the Signature should have.
func WithCertChain(cert, chain []byte) SignatureOption {
	return func(so *signatureOpts) {
		so.cert = cert
		so.chain = chain
	}
}

// WithMediaType specifies the new MediaType the Signature should have.
func WithMediaType(mediaType types.MediaType) SignatureOption {
	return func(so *signatureOpts) {
		so.mediaType = mediaType
	}
}

func makeSignatureOption(opts ...SignatureOption) *signatureOpts {
	so := &signatureOpts{}
	for _, opt := range opts {
		opt(so)
	}
	return so
}


text:
@interface PodsDummy_Pods_Gradebook : NSObject
@end
@implementation PodsDummy_Pods_Gradebook
@end


text:
CDAP for Linux/MacOSX provides a complete environment for installing and running CDAP on your Linux or MacOSX desktop or laptop.

#### What's New:

* View [release notes](https://cdap.atlassian.net/wiki/spaces/DOCS/pages/1661108225/CDAP+Release+6.5.0)

#### System Requirements

* Supported OS: MacOS, RedHat Linux, Ubuntu, CentOs
* Supported browsers: Chrome, Safari, Firefox
* Other requirements: JDK 8, Node.js versions 10.16.2+, Apache Maven 3.0+


text:
package com.dassmeta.passport.dal.redis.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import com.dassmeta.passport.dal.dataobject.AuOrgInfo;
import com.dassmeta.passport.dal.ibatis.AuOrgInfoDao;
import com.dassmeta.passport.util.IbatisMapperNameSpaceUtil;
import com.dassmeta.passport.util.PageList;
import com.dassmeta.passport.util.PageQueryUtils;

public class AuOrgInfoDaoImpl extends SqlSessionDaoSupport implements AuOrgInfoDao {

	private JdbcTemplate jdbcTemplate;

	public AuOrgInfo findByPrimaryKey(Serializable id) throws DataAccessException {
		return getSqlSession().selectOne("selectByPrimaryKey", id);
	}

	public long create(AuOrgInfo t) throws DataAccessException {
		return getSqlSession().insert("insert", t);
	}

	public int update(AuOrgInfo t) throws DataAccessException {
		return getSqlSession().update("update", t);
	}

	public int remove(AuOrgInfo t) throws DataAccessException {
		return getSqlSession().delete("remove", t);
	}

	public int remove(Serializable id) throws DataAccessException {
		return getSqlSession().delete("deleteByPrimaryKey", id);
	}

	public int saveOrUpdate(AuOrgInfo t) throws DataAccessException {
		return getSqlSession().update("saveOrUpdate", t);
	}

	public int batchSave(List<AuOrgInfo> paramList) throws DataAccessException {
		return getSqlSession().insert("batchSave", paramList);
	}

	public List<AuOrgInfo> batchSaveReturnIds(List<AuOrgInfo> paramList) throws DataAccessException {
		return null;
	}

	public int batchUpdate(List<AuOrgInfo> paramList) throws DataAccessException {
		return getSqlSession().update("batchUpdate", paramList);
	}

	public PageList<AuOrgInfo> findPageList(AuOrgInfo t, int pageSize, int pageNo) {
		IbatisMapperNameSpaceUtil.getMethodPath(this.getClass(), "pageList");
		return PageQueryUtils.pageQuery(getSqlSession(), "pageList", t, pageNo, pageSize);
	}

	public PageList<AuOrgInfo> findPageList(Map<String, Object> params, int pageSize, int pageNo) {
		return PageQueryUtils.pageQuery(getSqlSession(), "pageList", params, pageNo, pageSize);
	}

	public JdbcTemplate getJdbcTemplate() {
		return this.jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate paramJdbcTemplate) {
		this.jdbcTemplate = paramJdbcTemplate;
	}

}


text:
package net.liftweb
package json
package ext

import java.io._
import java.lang.reflect.ParameterizedType
import scala.reflect.Manifest
import common._
import Extraction.{decompose, extract}
import org.apache.commons.codec.binary.Base64

class JsonBoxSerializer extends Serializer[Box[_]] {
  private val BoxClass = classOf[Box[_]]

  def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), Box[_]] = {
    case (TypeInfo(BoxClass, ptype), json) => json match {
      case JNull | JNothing => Empty
      case JObject(JField("box_failure", JString("Failure")) ::
                   JField("msg", JString(msg)) ::
                   JField("exception", exception) ::
                   JField("chain", chain) :: Nil) =>
                     Failure(msg, deserializeException(exception),
                             extract(chain, TypeInfo(BoxClass, Some(typeHoldingFailure))).asInstanceOf[Box[Failure]])
      case JObject(JField("box_failure", JString("ParamFailure")) ::
                   JField("msg", JString(msg)) ::
                   JField("exception", exception) ::
                   JField("chain", chain) ::
                   JField("paramType", JString(paramType)) ::
                   JField("param", param) :: Nil) =>
                     val clazz = Thread.currentThread.getContextClassLoader.loadClass(paramType)
                     ParamFailure(msg, deserializeException(exception),
                                  extract(chain, TypeInfo(BoxClass, Some(typeHoldingFailure))).asInstanceOf[Box[Failure]],
                                  extract(param, TypeInfo(clazz, None)))
      case x =>
        val t = ptype.getOrElse(throw new MappingException("parameterized type not known for Box"))
        Full(extract(x, TypeInfo(t.getActualTypeArguments()(0).asInstanceOf[Class[_]], None)))
    }
  }

  def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
    case Full(x) => decompose(x)
    case Empty => JNull
    case ParamFailure(msg, exception, chain, param) =>
      JObject(JField("box_failure", JString("ParamFailure")) ::
              JField("msg", JString(msg)) ::
              JField("exception", serializeException(exception)) ::
              JField("chain", decompose(chain)) ::
              JField("paramType", JString(param.asInstanceOf[AnyRef].getClass.getName)) ::
              JField("param", decompose(param)) :: Nil)
    case Failure(msg, exception, chain) =>
      JObject(JField("box_failure", JString("Failure")) ::
              JField("msg", JString(msg)) ::
              JField("exception", serializeException(exception)) ::
              JField("chain", decompose(chain)) :: Nil)
  }

  private val typeHoldingFailure = new ParameterizedType {
    def getActualTypeArguments = Array(classOf[Failure])
    def getOwnerType = classOf[Box[Failure]]
    def getRawType = classOf[Box[Failure]]
  }

  private def serializeException(exception: Box[Throwable]) = exception match {
    case Full(x) => JString(javaSerialize(x))
    case _ => JNull
  }

  private def deserializeException(json: JValue) = json match {
    case JString(s) => Full(javaDeserialize(s).asInstanceOf[Throwable])
    case _ => Empty
  }

  private def javaSerialize(obj: AnyRef): String = {
    val bytes = new ByteArrayOutputStream
    val out = new ObjectOutputStream(bytes)
    out.writeObject(obj)
    new String((new Base64).encode(bytes.toByteArray))
  }

  private def javaDeserialize(s: String): Any = {
    val bytes = new ByteArrayInputStream((new Base64).decode(s.getBytes("UTF-8")))
    val in = new ObjectInputStream(bytes)
    in.readObject
  }
}


text:
rvm get stable --auto-dotfiles
rvm reload
rvm --version | awk '{print $2}' | grep [0-9] > RVM_VERSION

# ruby
LATEST_REMOTE_RUBY_VERSION=$(rvm list known strings | grep "1.9.3" | sed "s/\[//g" | sed "s/\]//g" | grep -v "head" | grep -v "rc" | grep -v "preview" | sort -r | head -n 1)

if [[ $(rvm list strings | grep $LATEST_REMOTE_RUBY_VERSION) == '' ]]
then
  rvm install $LATEST_REMOTE_RUBY_VERSION --disable-binary && source $HOME/.rvm/scripts/rvm && rvm use $LATEST_REMOTE_RUBY_VERSION && gem install bundler
fi

source $HOME/.rvm/scripts/rvm
rvm use $LATEST_REMOTE_RUBY_VERSION --default
echo $LATEST_REMOTE_RUBY_VERSION > RUBY_VERSION

# rubygems
gem update --system
gem --version > GEM_VERSION

# bundler
gem update bundler
bundle --version | awk '{print $3}' > BUNDLER_VERSION

# bundle
bundle update

## javascript: jquery
#URL="http://code.jquery.com"
#wget $URL/jquery.min.js -O public/javascripts/jquery/jquery.min.js
#CURRENT_UI_PATH=$(wget $URL -O - | egrep '\/ui\/[0-9\.]+\/jquery-ui.min.js' | awk -F \" '{print $2}' | sort -Vr | head -n 1)
#wget $URL/$CURRENT_UI_PATH -O public/javascripts/jquery/jquery-ui.custom.min.js
#
## javascript: jeditable
#wget https://raw.github.com/tuupola/jquery_jeditable/master/jquery.jeditable.js -O public/javascripts/jquery/jquery.jeditable.js
#
## javascript: jquery form
#wget http://malsup.github.com/jquery.form.js -O public/javascripts/jquery/jquery.form.js
#
## javascript: jquery timepicker
#TIME_PICKER_URL="https://raw.github.com/trentrichardson/jQuery-Timepicker-Addon/master"
#wget $TIME_PICKER_URL/jquery-ui-timepicker-addon.js -O public/javascripts/jquery/jquery-ui-timepicker-addon.js
#wget $TIME_PICKER_URL/localization/jquery-ui-timepicker-de.js -O public/javascripts/jquery/jquery-ui-timepicker-de.js
#wget $TIME_PICKER_URL/jquery-ui-timepicker-addon.css -O public/stylesheets/jquery/timepicker-addon.css
#
#wget https://raw.github.com/jquery/jquery-ui/master/ui/i18n/jquery.ui.datepicker-de.js -O public/javascripts/jquery/jquery.ui.datepicker-de.js
#wget https://raw.github.com/jquery/jquery-ui/master/ui/i18n/jquery.ui.datepicker-en-GB.js -O public/javascripts/jquery/jquery.ui.datepicker-en-GB.js
#
## javascript: jquery livequery
#wget https://raw.github.com/brandonaaron/livequery/master/jquery.livequery.js -O public/javascripts/jquery/jquery.livequery.js

# javascript: ckeditor
# aktuelle Download-Url
#CKEDITOR_DOWNLOAD=$(wget http://ckeditor.com/download -O - | egrep -o "href=(\"|\')[^\"\']+download[^\"\']+(\"|\')" | grep tar | grep ckeditor | sort -r | head -n 1 | awk -F "(\"|\')" '{print $2}')
#
#if [[ $CKEDITOR_DOWNLOAD != '' && $(cat CKEDITOR_VERSION) != $CKEDITOR_DOWNLOAD ]]
#then
#  CKEDITOR_PATH="public/javascripts/ckeditor/"
#  CKEDITOR_TMP_PATH="/tmp/ckeditor_backup/"
#  # eigene Dateien sichern
#  mkdir -p $CKEDITOR_TMP_PATH
#  cp ${CKEDITOR_PATH}config.js ${CKEDITOR_TMP_PATH}
#  cp ${CKEDITOR_PATH}contents.css ${CKEDITOR_TMP_PATH}
#
#  # alten CKeditor entfernen
#  svn delete $CKEDITOR_PATH
#  svn commit $CKEDITOR_PATH -m "CKEditor für das Update entfernt"
#  # neue Version einfügen
#  wget $CKEDITOR_DOWNLOAD -O - | tar -xz -C public/javascripts/
#  rm $(find public -type f -name '\.htacc*' | grep -v svn)
#  svn add $CKEDITOR_PATH
#  svn commit $CKEDITOR_PATH -m "CKEditor aktualisiert"
#  # eigene Config wieder einspielen
#  cp ${CKEDITOR_TMP_PATH}config.js ${CKEDITOR_PATH}
#  cp ${CKEDITOR_TMP_PATH}contents.css ${CKEDITOR_PATH}
#  svn commit $CKEDITOR_PATH -m "CKEditor aktualisiert"
#
#  echo $CKEDITOR_DOWNLOAD > CKEDITOR_VERSION
#  NEW_CKEDITOR=1
#fi
#
# Firefox
#firefox -v > FIREFOX_BROWSER_VERSION