text:
import { sinon, makeDOM, expect } from '../helpers'

import initializeApi from '../../lib/initialize'
import { Channel } from '../../lib/channel'

describe('initializeApi(currentWindow, apiCreator)', function () {
  beforeEach(function () {
    this.dom = makeDOM()
    this.apiCreator = sinon.stub().returns({})
    const init = initializeApi(this.dom.window, (...args) => this.apiCreator(...args))
    this.initialize = function () {
      return new Promise((resolve) => init(resolve))
    }
  })

  describe('callback', function () {
    beforeEach(function () {
      this.api = {}
      this.apiCreator = sinon.stub().returns(this.api)
      this.init = initializeApi(this.dom.window, this.apiCreator)
    })

    it('is not invoked before connecting', function () {
      const cb = sinon.spy()
      this.init(cb)
      expect(cb).to.not.be.called // eslint-disable-line no-unused-expressions
    })

    it('is invoked after connecting', function (done) {
      this.init(() => done())
      sendConnect(this.dom)
    })

    it('is invoked when registering it after connecting', async function () {
      const cb = sinon.spy()
      sendConnect(this.dom)
      await wait()
      await this.init(cb)
      expect(cb).to.be.called // eslint-disable-line no-unused-expressions
    })

    it('receives the result of the apiCreator', function (done) {
      this.init((arg: any) => {
        expect(arg).to.equal(this.api)
        done()
      })
      sendConnect(this.dom)
    })

    it('receives the result of the custom API creator', function (done) {
      const customApi = {}
      const makeCustomApi = sinon.stub().returns(customApi)

      this.init(
        (_: any, arg: any) => {
          expect(arg).to.equal(customApi)
          const [channel, params] = this.apiCreator.args[0]
          expect(makeCustomApi).to.be.calledWithExactly(channel, params)
          done()
        },
        { makeCustomApi }
      )

      sendConnect(this.dom)
    })
  })

  it('calls apiCreator with channel and params', function () {
    const params = { id: 'foo', val: 'x' }
    sendConnect(this.dom, params)
    return this.initialize().then(() => {
      const [channel, params] = this.apiCreator.args[0]
      expect(channel.call).to.be.a('function')
      expect(channel.send).to.be.a('function')
      expect(channel.addHandler).to.be.a('function')
      expect(params).to.deep.equal(params)
    })
  })

  it('calls handlers for queued messages', function () {
    sendConnect(this.dom, null as any, [{ method: 'M', params: ['X', 'Y'] }])
    const handler = sinon.stub()
    this.apiCreator = function (channel: Channel) {
      channel.addHandler('M', handler)
    }
    return this.initialize().then(() => {
      expect(handler).to.have.been.calledOnce // eslint-disable-line no-unused-expressions
      expect(handler).to.have.been.calledWithExactly('X', 'Y')
    })
  })

  it('adds focus handlers', function () {
    const { Event } = this.dom.window
    const send = sinon.spy()
    this.apiCreator = function (channel: Channel) {
      channel.send = send
    }
    sendConnect(this.dom)
    return this.initialize().then(() => {
      this.dom.window.document.dispatchEvent(new Event('focus'))
      expect(send).to.be.calledOnce // eslint-disable-line no-unused-expressions
      expect(send).to.be.calledWithExactly('setActive', true)

      send.resetHistory()
      this.dom.window.document.dispatchEvent(new Event('blur'))
      expect(send).to.be.calledOnce // eslint-disable-line no-unused-expressions
      expect(send).to.be.calledWithExactly('setActive', false)
    })
  })

  function sendConnect(dom: { window: Window }, params?: any, messageQueue?: any[]) {
    dom.window.postMessage(
      {
        method: 'connect',
        params: [params || { id: 'foo' }, messageQueue || []],
      },
      '*'
    )
  }

  function wait() {
    return new Promise((resolve) => setTimeout(resolve))
  }
})


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0099cc"
    tools:context=".SocialActivity" >

    <!--
         The primary full-screen view. This can be replaced with whatever view
         is needed to present your content, e.g. VideoView, SurfaceView,
         TextureView, etc.
    -->

    <!--
         This FrameLayout insets its children based on system windows using
         android:fitsSystemWindows.
    -->

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true" >

        <RelativeLayout
                android:background="@drawable/main_background_selector"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="24dp"
                android:layout_marginTop="60dp"
                android:text="Search:"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/black_overlay"
                android:textSize="10pt"
                android:textStyle="bold" />

            <EditText
                android:id="@+id/editText1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/textView1"
                android:layout_marginLeft="42dp"
                android:layout_toRightOf="@+id/textView1"
                android:ems="10"
                android:text="John Stuart"
                android:textColor="@color/black_overlay"
                android:textColorHint="@color/black_overlay"
                android:textStyle="bold" >

                <requestFocus />
            </EditText>

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textView1"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="200dp"
                android:text="Share Latest Performance"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@color/black_overlay"
                android:textStyle="bold" />

            <ImageView
                android:id="@+id/imageView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignBottom="@+id/textView2"
                android:layout_alignTop="@+id/editText1"
                android:layout_marginBottom="80dp"
                android:layout_toRightOf="@+id/imageButton1"
                android:src="@drawable/user" />

            <ImageButton
                android:id="@+id/imageButton2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/imageButton1"
                android:layout_alignParentBottom="true"
                android:layout_marginBottom="120dp"
                android:src="@drawable/signintwitter" />

            <ImageButton
                android:id="@+id/imageButton1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textView2"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="20dp"
                android:src="@drawable/signinfacebook" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignLeft="@+id/textView1"
                android:layout_below="@+id/textView1"
                android:layout_marginTop="54dp"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/textView3"
                    android:layout_width="244dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Arctic Monkeys - Mardy Bum: 95%"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="@color/black_overlay"
                    android:textColorHint="@color/black_overlay"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/textView4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Radiohead - Karma Police: 68%"
                    android:textAppearance="?android:attr/textAppearanceSmall"
                    android:textColor="@color/black_overlay"
                    android:textColorHint="@color/black_overlay"
                    android:textStyle="bold" />

            </LinearLayout>

        </RelativeLayout>

        <LinearLayout
            android:id="@+id/fullscreen_content_controls"
            style="?buttonBarStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|center_horizontal"
            android:background="@color/black_overlay"
            android:orientation="horizontal"
            tools:ignore="UselessParent" >

            <Button
                android:id="@+id/dummy_button"
                style="?buttonBarButtonStyle"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Refresh" />

        </LinearLayout>

    </FrameLayout>

</FrameLayout>

redpajama_set_name: RedPajamaGithub


text:
CLASS({
  package: 'foam.documentation',
  name: 'InterfaceFullPageDocView',
  extends: 'foam.documentation.FullPageDocView',

  requires: ['foam.ui.DAOListView',
             'foam.documentation.SimpleRowDocView'],

  documentation: "A full-page documentation view for $$DOC{ref:'Interface'} instances.",

  templates: [

    function toInnerHTML()    {/*
<%    this.destroy(); %>
<%    if (this.data) {  %>
        $$data{ model_: 'foam.documentation.SummaryDocView', model: this.data.model_ }

Methods:

$$methods{ model_: 'foam.ui.DAOListView', rowView: 'foam.documentation.SimpleRowDocView', mode: 'read-only' }

<%    } %>
    */}
  ]

});


text:
package org.yaml.snakeyaml.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CodingErrorAction;

import org.yaml.snakeyaml.error.YAMLException;
import org.yaml.snakeyaml.external.com.google.gdata.util.common.base.Escaper;
import org.yaml.snakeyaml.external.com.google.gdata.util.common.base.PercentEscaper;

public abstract class UriEncoder {
    private static final CharsetDecoder UTF8Decoder = Charset.forName("UTF-8").newDecoder()
            .onMalformedInput(CodingErrorAction.REPORT);
    // Include the [] chars to the SAFEPATHCHARS_URLENCODER to avoid
    // its escape as required by spec. See
    // http://yaml.org/spec/1.1/#escaping%20in%20URI/
    private static final String SAFE_CHARS = PercentEscaper.SAFEPATHCHARS_URLENCODER + "[]/";
    private static final Escaper escaper = new PercentEscaper(SAFE_CHARS, false);

    /**
     * Escape special characters with '%'
     */
    public static String encode(String uri) {
        return escaper.escape(uri);
    }

    /**
     * Decode '%'-escaped characters. Decoding fails in case of invalid UTF-8
     */
    public static String decode(ByteBuffer buff) throws CharacterCodingException {
        CharBuffer chars = UTF8Decoder.decode(buff);
        return chars.toString();
    }

    public static String decode(String buff) {
        try {
            return URLDecoder.decode(buff, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new YAMLException(e);
        }
    }
}


text:
django-newsfeed
===============

TODO:
--------
A small django app for news feed inspired by django-activity-stream. It uses fan-out-on-load to build the user news feed on demand. There is a cache layer (Choose Backend) that stores the most recent activities of a user (the number of the recent items to store is configurable in the settings) for faster news feed loading.


text:
<?php
namespace Kir\Logging\Essentials\Loggers;

use Kir\Logging\Essentials\Common\AbstractLogger;

class ArrayLogger extends AbstractLogger {
	/**
	 * @var array[]
	 */
	private $messages = array();

	/**
	 * @var callable[]
	 */
	private $processors = array();

	/**
	 * @return array[]
	 */
	public function getMessages() {
		return $this->messages;
	}

	/**
	 * @param callable $fn
	 * @return $this
	 */
	public function addProcessor($fn) {
		$this->processors = $fn;
		return $this;
	}

	/**
	 * Logs with an arbitrary level.
	 *
	 * @param mixed $level
	 * @param string $message
	 * @param array $context
	 * @return $this
	 */
	public function log($level, $message, array $context = array()) {
		$message = array('level' => $level, 'message' => $message, 'context' => $context);
		foreach($this->processors as $processor) {
			$message = call_user_func($processor, $message);
		}
		$this->messages[] = $message;
		return $this;
	}
}


text:
using namespace Upp;

static String sNumberAsText(int number)
{
	static const char * const digits[20] = {
		"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
		"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen",
		"seventeen", "eighteen", "nineteen"
	};
	static const char * const tens[10] = {
		"", "ten", "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety"
	};

	if(number < 20)
		return digits[number];
	if(number < 100)
		return tens[number / 10] + String(" ") + sNumberAsText(number % 10);
	if(number < 1000)
		return digits[number / 100] + String(" hundred ") + sNumberAsText(number % 100);
	if(number < 1000000)
		return sNumberAsText(number / 1000) + " thousand, " + sNumberAsText(number % 1000);
	return "";
}

struct NumberToText : public Convert {
	virtual Value  Format(const Value& q) const {
		int n = q;
		return n == 0 ? String("zero") : sNumberAsText(n);
	}
};

GUI_APP_MAIN
{
	ArrayCtrl array;
	array.AddRowNumColumn("number", 20);
	array.AddRowNumColumn("text", 80).SetConvert(Single<NumberToText>());
	array.SetVirtualCount(900000);
	TopWindow win;
	win.Zoomable().Sizeable();
	win.Add(array.SizePos());
	win.Run();
}


text:
// Copyright 2021 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Service for handling user contributed translations.
 */

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { downgradeInjectable } from '@angular/upgrade/static';
import { TranslatableTexts, TranslatableTextsBackendDict } from 'domain/opportunity/translatable-texts.model';
import { ImageLocalStorageService, ImagesData } from 'services/image-local-storage.service';

interface Data {
  'suggestion_type': string;
  'target_type': string;
  description: string;
  'target_id': string;
  'target_version_at_submission': string;
  change: object;
  files?: Record<string, unknown>;
}
@Injectable({
  providedIn: 'root'
})
export class TranslateTextBackendApiService {
  constructor(
    private http: HttpClient,
    private imageLocalStorageService: ImageLocalStorageService
  ) {}

  async getTranslatableTextsAsync(expId: string, languageCode: string):
    Promise<TranslatableTexts> {
    return this.http.get<TranslatableTextsBackendDict>(
      '/gettranslatabletexthandler', {
        params: {
          exp_id: expId,
          language_code: languageCode
        }
      }).toPromise().then((backendDict: TranslatableTextsBackendDict) => {
      return TranslatableTexts.createFromBackendDict(backendDict);
    });
  }

  async suggestTranslatedTextAsync(
      expId: string, expVersion: string, contentId: string, stateName: string,
      languageCode: string, contentHtml: string | string[],
      translationHtml: string | string[], imagesData: ImagesData[],
      dataFormat: string): Promise<unknown> {
    const postData: Data = {
      suggestion_type: 'translate_content',
      target_type: 'exploration',
      description: 'Adds translation',
      target_id: expId,
      target_version_at_submission: expVersion,
      change: {
        cmd: 'add_written_translation',
        content_id: contentId,
        state_name: stateName,
        language_code: languageCode,
        content_html: contentHtml,
        translation_html: translationHtml,
        data_format: dataFormat
      },
      files: (
        await this.imageLocalStorageService.getFilenameToBase64MappingAsync(
          imagesData))
    };
    const body = new FormData();
    body.append('payload', JSON.stringify(postData));
    return this.http.post(
      '/suggestionhandler/', body).toPromise();
  }
}

angular.module('oppia').factory('TranslateTextBackendApiService',
  downgradeInjectable(TranslateTextBackendApiService));


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

app.use(require('cookie-parser')());

app.get('/', (req, res, next) => {
  return req.webtaskContext.storage.get((e, data) => {
    if (e) return next(e);
    res.writeHead(200, { 'Content-Type': 'text/html' });
    var model = {
      value: data && data[req.cookies['x-nps-id']] || -1,
      filledSymbol: req.query.filledSymbol || '&#x2605',
      emptySymbol: req.query.emptySymbol || '&#x2606',
      color: req.query.color || 'orange',
      size: req.query.size || '1em',
      scale: +req.webtaskContext.secrets.SCALE || 10,
    };
    return res.end(npsView(model));
  });
});

app.get('/stats', (req, res, next) => {
  var scale = +req.webtaskContext.secrets.SCALE || 10;
  return req.webtaskContext.storage.get((e, data) => {
    if (e) return next(e);
    var stats = { histogram: {}, count: 0, avg: 0 };
    for (var i = 0; i <= scale; i++) stats.histogram[i] = 0;
    for (var id in data) {
      stats.count++;
      stats.histogram[data[id]]++;
      stats.avg += data[id];
    }
    if (stats.total > 0);
      stats.avg = stats.avg / stats.count;
    if (scale === 10) {
      stats.nps = { promoters: 0, passives: 0, detractors: 0, score: 0 };
      if (stats.count > 0) {
        for (var i = 0; i <= 6; i++) stats.nps.detractors += stats.histogram[i];
        for (var i = 7; i <= 8; i++) stats.nps.passives += stats.histogram[i];
        for (var i = 9; i <= 10; i++) stats.nps.promoters += stats.histogram[i];
        stats.nps.score = 100 * (stats.nps.promoters - stats.nps.detractors) / stats.count;
      }
    }
    return res.json(stats);
  });
});

app.post('/:value', (req, res, next) => {
  var scale = +req.webtaskContext.secrets.SCALE || 10;
  var v = +req.params.value;
  if (isNaN(v) || v < 0 || v > scale) {
    res.writeHead(400);
    return res.end();
  }
  var id = req.cookies['x-nps-id'];
  if (!id) {
    id = Math.floor((999999999 * Math.random())).toString(26);
    res.cookie('x-nps-id', id, { httpOnly: true });
  }
  return req.webtaskContext.storage.get((e, data) => {
    if (e) return next(e);
    data = data || {};
    data[id] = v;
    req.webtaskContext.storage.set(data, { force: true }, (e) => {
      if (e) return next(e);
      return res.end();
    });
  });
});

function npsView(model) {
  let fragments = [
`<body style="margin: 0; line-height: ${model.size}; font-size: ${model.size}; color: ${model.color}"><script>
  var filledSymbol = '${model.filledSymbol}';
  var emptySymbol = '${model.emptySymbol}';
  function nps(value) {
    for (var i = 0; i <= ${model.scale}; i++) {
      document.getElementById("" + i).innerHTML = i <= value ? filledSymbol : emptySymbol;
    }
    var oReq = new XMLHttpRequest();
    oReq.open('POST', window.location.pathname + '/' + value);
    oReq.send();
  }
</script>
<span style="cursor: pointer;">`
];

  for (var i = 0; i <= model.scale; i++) {
    fragments.push(`<span id="${i}" onclick="nps(${i})">${i <= model.value ? model.filledSymbol : model.emptySymbol}</span>`);
  }

  fragments.push(`</span></body>`);

  return fragments.join('');
}

module.exports = (options, cb) => cb(null, require('webtask-tools').fromExpress(app));