text:
package com.jetbrains.python.console;

import java.util.Arrays;

import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.actionSystem.EditorActionManager;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.DocumentUtil;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.psi.PyStatementListContainer;
import com.jetbrains.python.psi.PyStringLiteralExpression;
import com.jetbrains.python.psi.PyTryPart;
import com.jetbrains.python.psi.impl.PyPsiUtils;
import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl;

/**
 * @author VISTALL
 * @since 09-Nov-16
 */
public class PyConsoleEnterHandler
{
	public boolean handleEnterPressed(EditorEx editor)
	{
		Project project = editor.getProject();
		if(project == null)
		{
			throw new IllegalArgumentException();
		}

		int lineCount = editor.getDocument().getLineCount();
		if(lineCount > 0)
		{ // move to end of line
			editor.getSelectionModel().removeSelection();
			LogicalPosition caretPosition = editor.getCaretModel().getLogicalPosition();
			if(caretPosition.line == lineCount - 1)
			{
				// we can move caret if only it's on the last line of command
				int lineEndOffset = editor.getDocument().getLineEndOffset(caretPosition.line);
				editor.getCaretModel().moveToOffset(lineEndOffset);
			}
			else
			{
				// otherwise just process enter action
				executeEnterHandler(project, editor);
				return false;
			}
		}
		else
		{
			return true;
		}
		PsiDocumentManager psiMgr = PsiDocumentManager.getInstance(project);
		psiMgr.commitDocument(editor.getDocument());

		int caretOffset = editor.getExpectedCaretOffset();
		PsiElement atElement = findFirstNoneSpaceElement(psiMgr.getPsiFile(editor.getDocument()), caretOffset);
		if(atElement == null)
		{
			executeEnterHandler(project, editor);
			return false;
		}

		String firstLine = getLineAtOffset(editor.getDocument(), DocumentUtil.getFirstNonSpaceCharOffset(editor.getDocument(), 0));
		boolean isCellMagic = firstLine.trim().startsWith("%%") && !StringUtil.trimEnd(firstLine, ' ').endsWith("?");
		String prevLine = getLineAtOffset(editor.getDocument(), caretOffset);

		boolean isLineContinuation = StringUtil.endsWithChar(prevLine.trim(), '\\');
		boolean insideDocString = isElementInsideDocString(atElement, caretOffset);
		boolean isMultiLineCommand = PsiTreeUtil.getParentOfType(atElement, PyStatementListContainer.class) != null || isCellMagic;
		boolean isAtTheEndOfCommand = editor.getDocument().getLineNumber(caretOffset) == editor.getDocument().getLineCount() - 1;

		boolean hasCompleteStatement = !insideDocString && !isLineContinuation && checkComplete(atElement);

		executeEnterHandler(project, editor);

		return isAtTheEndOfCommand && hasCompleteStatement && ((isMultiLineCommand && prevLine.isEmpty()) || (!isMultiLineCommand));
	}

	private boolean checkComplete(PsiElement el)
	{
		PyStatementListContainer compoundStatement = PsiTreeUtil.getParentOfType(el, PyStatementListContainer.class);
		if(compoundStatement != null && !(compoundStatement instanceof PyTryPart))
		{
			return compoundStatement.getStatementList().getStatements().length != 0;
		}
		PsiElement topLevel = PyPsiUtils.getParentRightBefore(el, el.getContainingFile());
		return topLevel != null && !PsiTreeUtil.hasErrorElements(topLevel);
	}

	private boolean isElementInsideDocString(PsiElement atElement, int caretOffset)
	{
		return atElement.getContext() instanceof PyStringLiteralExpression &&
				(PyTokenTypes.TRIPLE_NODES.contains(atElement.getNode().getElementType()) || atElement.getNode().getElementType() == PyTokenTypes.DOCSTRING) &&
				isMultilineString(atElement.getText()) &&
				(atElement.getTextRange().getEndOffset() > caretOffset || !isCompleteDocString(atElement.getText()));
	}

	private boolean isMultilineString(String str)
	{
		String text = str.substring(PyStringLiteralExpressionImpl.getPrefixLength(str));
		return text.startsWith("\"\"\"") || text.startsWith("'''");
	}

	private boolean isCompleteDocString(String str)
	{
		int prefixLen = PyStringLiteralExpressionImpl.getPrefixLength(str);
		String text = str.substring(prefixLen);
		for(String token : Arrays.asList("\"\"\"", "'''"))
		{
			if(text.length() >= 2 * token.length() && text.startsWith(token) && text.endsWith(token))
			{
				return true;
			}
		}

		return false;
	}

	private PsiElement findFirstNoneSpaceElement(PsiFile psiFile, int offset)
	{
		for(int i = offset; i <= 0; i--)
		{
			PsiElement el = psiFile.findElementAt(i);
			if(el != null && !(el instanceof PsiWhiteSpace))
			{
				return el;
			}
		}
		return null;
	}

	private String getLineAtOffset(Document doc, int offset)
	{
		int line = doc.getLineNumber(offset);
		int start = doc.getLineStartOffset(line);
		int end = doc.getLineEndOffset(line);
		return doc.getText(new TextRange(start, end));
	}

	private void executeEnterHandler(Project project, EditorEx editor)
	{
		EditorActionHandler enterHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER);
		new WriteCommandAction<Void>(project)
		{
			@Override
			protected void run(Result<Void> result) throws Throwable
			{
				enterHandler.execute(editor, null, DataManager.getInstance().getDataContext(editor.getComponent()));

			}
		}.execute();
	}

}


text:
import { enableDebugTools, disableDebugTools } from '@angular/platform-browser';
import { enableProdMode, ApplicationRef } from '@angular/core';

// Angular debug tools in the dev console
// https://github.com/angular/angular/blob/86405345b781a9dc2438c0fbe3e9409245647019/TOOLS_JS.md
let _decorateModuleRef = function identity<T>(value: T): T { return value; };

if ('production' === ENV) {
  // Production
  //disableDebugTools();
  enableProdMode();

} else {

  _decorateModuleRef = (modRef: any) => {
    const appRef = modRef.injector.get(ApplicationRef);
    const cmpRef = appRef.components[0];

    let _ng = (<any>window).ng;
    enableDebugTools(cmpRef);
    (<any>window).ng.probe = _ng.probe;
    (<any>window).ng.coreTokens = _ng.coreTokens;
    return modRef;
  };
}

export const decorateModuleRef = _decorateModuleRef;

redpajama_set_name: RedPajamaGithub


text:
package com.intel.ssg.dcst.panthera.parse.sql.transformer;

import java.util.LinkedList;
import java.util.List;

import org.antlr.runtime.tree.CommonTree;

import com.intel.ssg.dcst.panthera.parse.sql.PantheraExpParser;
import com.intel.ssg.dcst.panthera.parse.sql.SqlXlateException;
import com.intel.ssg.dcst.panthera.parse.sql.TranslateContext;

/**
 * handle MINUS and INTERSECT in the same transformer, in case there are both MINUS and INTERSECT
 * under SUBQUERY node.
 *
 * MinusIntersectTransformer.
 *
 */
public class MinusIntersectTransformer extends BaseSqlASTTransformer {
  SqlASTTransformer tf;
  MinusTransformer minusTransformer = null;
  IntersectTransformer intersectTransformer = null;

  public MinusIntersectTransformer(SqlASTTransformer tf) {
    this.tf = tf;
    minusTransformer = new MinusTransformer();
    intersectTransformer = new IntersectTransformer();
  }

  @Override
  protected void transform(CommonTree tree, TranslateContext context) throws SqlXlateException {
    tf.transformAST(tree, context);
    trans(tree, context);
  }

  private void trans(CommonTree node, TranslateContext context) throws SqlXlateException {
    List<CommonTree> childList = new LinkedList<CommonTree> ();
    // store every child into a list, since these node might be changed during transforming
    for (int i = 0; i < node.getChildCount(); i++) {
      childList.add((CommonTree) node.getChild(i));
    }
    for (int i = 0; i < childList.size(); i++) {
      trans(childList.get(i), context);
    }
    if (node.getType() == PantheraExpParser.PLSQL_RESERVED_MINUS) {
      minusTransformer.processIntersect(node, context);
    }
    if (node.getType() == PantheraExpParser.SQL92_RESERVED_INTERSECT) {
      intersectTransformer.processIntersect(node, context);
    }
  }

}


text:
using System.Collections.Generic;

namespace Palmmedia.ReportGenerator.Core.Reporting.Builders.Rendering
{
    /// <summary>
    /// Represents a card in the HTML report.
    /// </summary>
    public class Card
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Card" /> class.
        /// </summary>
        /// <param name="title">The title.</param>
        public Card(string title)
        {
            this.Title = title;
            this.ProRequired = true;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Card" /> class.
        /// </summary>
        /// <param name="title">The title.</param>
        /// <param name="subtitle">The sub title.</param>
        /// <param name="subTitlePercentage">The percentage for the left border.</param>
        /// <param name="rows">The rows.</param>
        public Card(string title, string subtitle, decimal? subTitlePercentage, params CardLineItem[] rows)
        {
            this.Title = title;
            this.SubTitle = subtitle;
            this.SubTitlePercentage = subTitlePercentage;
            this.Rows = rows;
        }

        /// <summary>
        /// Gets or sets a value indicating whether PRO version is required.
        /// </summary>
        public bool ProRequired { get; set; }

        /// <summary>
        /// Gets the title.
        /// </summary>
        public string Title { get; }

        /// <summary>
        /// Gets the sub title.
        /// </summary>
        public string SubTitle { get; }

        /// <summary>
        /// Gets the percentage for the left border.
        /// </summary>
        public decimal? SubTitlePercentage { get; }

        /// <summary>
        /// Gets the rows.
        /// </summary>
        public IReadOnlyCollection<CardLineItem> Rows { get; } = new List<CardLineItem>();
    }
}


text:
'use strict';

const AnimatedNode = require('./AnimatedNode');
const NativeAnimatedHelper = require('../NativeAnimatedHelper');

class AnimatedWithChildren extends AnimatedNode {
  _children: Array<AnimatedNode>;

  constructor() {
    super();
    this._children = [];
  }

  __makeNative() {
    if (!this.__isNative) {
      this.__isNative = true;
      for (const child of this._children) {
        child.__makeNative();
        NativeAnimatedHelper.API.connectAnimatedNodes(
          this.__getNativeTag(),
          child.__getNativeTag(),
        );
      }
    }
    super.__makeNative();
  }

  __addChild(child: AnimatedNode): void {
    if (this._children.length === 0) {
      this.__attach();
    }
    this._children.push(child);
    if (this.__isNative) {
      // Only accept "native" animated nodes as children
      child.__makeNative();
      NativeAnimatedHelper.API.connectAnimatedNodes(
        this.__getNativeTag(),
        child.__getNativeTag(),
      );
    }
  }

  __removeChild(child: AnimatedNode): void {
    const index = this._children.indexOf(child);
    if (index === -1) {
      console.warn("Trying to remove a child that doesn't exist");
      return;
    }
    if (this.__isNative && child.__isNative) {
      NativeAnimatedHelper.API.disconnectAnimatedNodes(
        this.__getNativeTag(),
        child.__getNativeTag(),
      );
    }
    this._children.splice(index, 1);
    if (this._children.length === 0) {
      this.__detach();
    }
  }

  __getChildren(): Array<AnimatedNode> {
    return this._children;
  }

  __callListeners(value: number): void {
    super.__callListeners(value);
    if (!this.__isNative) {
      for (const child of this._children) {
        // $FlowFixMe[method-unbinding] added when improving typing for this parameters
        if (child.__getValue) {
          child.__callListeners(child.__getValue());
        }
      }
    }
  }
}

module.exports = AnimatedWithChildren;


text:
import assert from 'assert'
import { remove } from 'yourchoice'
import { REMOVE } from './actionTypes'

const removeActionCreator = (selectionName, itemId) => ({
  type: REMOVE,
  payload: {
    selectionName,
    itemId,
  },
})

const removeReducer = ({ itemId }, currentSelection) => {
  assert(itemId, `No item id ('${itemId}') to remove`)
  return remove(itemId, currentSelection)
}

export {
  removeActionCreator,
  removeReducer,
}


text:
import { Injectable } from '@angular/core';
import * as fs from 'fs';
import * as path from 'path';

export interface TextReplacement {
  path: string;
  searchText: string;
  replacementText: string;
}

export interface Config {
  cwd: string;
  exclude: string[];
  installProdNodeModules?: string[];
  textReplacements?: TextReplacement[];
}

@Injectable()
export class ConfigService {
  getCommonConfig(): Config {
    return this.readConfigFile(require.resolve('../../common.deploy.json'));
  }

  getConfigs(dir: string): Config[] {
    console.log('finding configs...');

    const filePaths = this.getConfigPaths(dir, []);

    return filePaths
      .map(filePath => this.readConfigFile(filePath));
  }

  private getConfigPaths(dir: string, filelist: string[] = []): string[] {
    const filePaths = fs.readdirSync(dir);
    for (const filePath of filePaths) {
      const absolutePath = path.join(dir, filePath);
      if (fs.statSync(absolutePath).isDirectory() && !absolutePath.includes('node_modules')) {
        filelist = this.getConfigPaths(absolutePath, filelist);
      } else if (absolutePath.endsWith('deploy.json')) {
        filelist = filelist.concat(absolutePath);
      }
    }

    return filelist;
  }

  private readConfigFile(filePath: string): Config {
    const configJson = fs.readFileSync(filePath).toString();
    const config = JSON.parse(configJson);
    return Object.assign(config, { cwd: path.dirname(filePath) });
  }
}


text:
#ifndef HALIDE_IMAGE_H
#define HALIDE_IMAGE_H

/** \file
 * Defines Halide's Image data type
 */

#include "Var.h"
#include "Tuple.h"

namespace Halide {

/** A base class for Images, which are typed accessors on
 * Buffers. This exists to make the implementations of certain methods
 * of Image private, so that they can safely throw errors without the
 * risk of being inlined (which in turns messes up reporting of line
 * numbers). */
class ImageBase {
protected:
    /** The underlying memory object */
    Buffer buffer;

    /** The address of the zero coordinate. The buffer_t stores the
     * address of the min coordinate, but it's easier to index off the
     * zero coordinate. */
    void *origin;

    /** The strides. These fields are also stored in the buffer, but
     * they're cached here in the handle to make operator() fast. This
     * is safe to do because the buffer is never modified.
     */
    int stride_0, stride_1, stride_2, stride_3;

    /** The dimensionality. */
    int dims;

    /** The size of each element. */
    int elem_size;

    /** Prepare the buffer to be used as an image. Makes sure that the
     * cached strides are correct, and that the image data is on the
     * host. */
    void prepare_for_direct_pixel_access();

    bool add_implicit_args_if_placeholder(std::vector<Expr> &args,
                                          Expr last_arg,
                                          int total_args,
                                          bool placeholder_seen) const;
public:
    /** Construct an undefined image handle */
    ImageBase() : origin(NULL), stride_0(0), stride_1(0), stride_2(0), stride_3(0), dims(0) {}

    /** Allocate an image with the given dimensions. */
    EXPORT ImageBase(Type t, int x, int y = 0, int z = 0, int w = 0, const std::string &name = "");

    /** Wrap a buffer in an Image object, so that we can directly
     * access its pixels in a type-safe way. */
    EXPORT ImageBase(Type t, const Buffer &buf);

    /** Wrap a single-element realization in an Image object. */
    EXPORT ImageBase(Type t, const Realization &r);

    /** Wrap a buffer_t in an Image object, so that we can access its
     * pixels. */
    EXPORT ImageBase(Type t, const buffer_t *b, const std::string &name = "");

    /** Get the name of this image. */
    EXPORT const std::string &name();

    /** Manually copy-back data to the host, if it's on a device. This
     * is done for you if you construct an image from a buffer, but
     * you might need to call this if you realize a gpu kernel into an
     * existing image */
    EXPORT void copy_to_host();

    /** Mark the buffer as dirty-on-host.  is done for you if you
     * construct an image from a buffer, but you might need to call
     * this if you realize a gpu kernel into an existing image, or
     * modify the data via some other back-door. */
    EXPORT void set_host_dirty(bool dirty = true);

    /** Check if this image handle points to actual data */
    EXPORT bool defined() const;

    /** Get the dimensionality of the data. Typically two for grayscale images, and three for color images. */
    EXPORT int dimensions() const;

    /** Get the size of a dimension */
    EXPORT int extent(int dim) const;

    /** Get the min coordinate of a dimension. The top left of the
     * image represents this point in a function that was realized
     * into this image. */
    EXPORT int min(int dim) const;

    /** Set the min coordinates of a dimension. */
    EXPORT void set_min(int m0, int m1 = 0, int m2 = 0, int m3 = 0);

    /** Get the number of elements in the buffer between two adjacent
     * elements in the given dimension. For example, the stride in
     * dimension 0 is usually 1, and the stride in dimension 1 is
     * usually the extent of dimension 0. This is not necessarily true
     * though. */
    EXPORT int stride(int dim) const;

    /** Get the extent of dimension 0, which by convention we use as
     * the width of the image. Unlike extent(0), returns one if the
     * buffer is zero-dimensional. */
    EXPORT int width() const;

    /** Get the extent of dimension 1, which by convention we use as
     * the height of the image. Unlike extent(1), returns one if the
     * buffer has fewer than two dimensions. */
    EXPORT int height() const;

    /** Get the extent of dimension 2, which by convention we use as
     * the number of color channels (often 3). Unlike extent(2),
     * returns one if the buffer has fewer than three dimensions. */
    EXPORT int channels() const;

    /** Get the minimum coordinate in dimension 0, which by convention
     * is the coordinate of the left edge of the image. Returns zero
     * for zero-dimensional images. */
    EXPORT int left() const;

    /** Get the maximum coordinate in dimension 0, which by convention
     * is the coordinate of the right edge of the image. Returns zero
     * for zero-dimensional images. */
    EXPORT int right() const;

    /** Get the minimum coordinate in dimension 1, which by convention
     * is the top of the image. Returns zero for zero- or
     * one-dimensional images. */
    EXPORT int top() const;

    /** Get the maximum coordinate in dimension 1, which by convention
     * is the bottom of the image. Returns zero for zero- or
     * one-dimensional images. */
    EXPORT int bottom() const;

    /** Construct an expression which loads from this image. The
     * location is extended with enough implicit variables to match
     * the dimensionality of the image (see \ref Var::implicit) */
    // @{
    EXPORT Expr operator()() const;
    EXPORT Expr operator()(Expr x) const;
    EXPORT Expr operator()(Expr x, Expr y) const;
    EXPORT Expr operator()(Expr x, Expr y, Expr z) const;
    EXPORT Expr operator()(Expr x, Expr y, Expr z, Expr w) const;
    EXPORT Expr operator()(std::vector<Expr>) const;
    EXPORT Expr operator()(std::vector<Var>) const;
    // @}

    /** Get a pointer to the raw buffer_t that this image holds */
    EXPORT buffer_t *raw_buffer() const;

    /** Get the address of a particular pixel. */
    void *address_of(int x, int y = 0, int z = 0, int w = 0) const {
        uint8_t *ptr = (uint8_t *)origin;
        size_t offset = x*stride_0 + y*stride_1 + z*stride_2 + w*stride_3;
        return (void *)(ptr + offset * elem_size);
    }
};

/** A reference-counted handle on a dense multidimensional array
 * containing scalar values of type T. Can be directly accessed and
 * modified. May have up to four dimensions. Color images are
 * represented as three-dimensional, with the third dimension being
 * the color channel. In general we store color images in
 * color-planes, as opposed to packed RGB, because this tends to
 * vectorize more cleanly. */
template<typename T>
class Image : public ImageBase {
public:
    /** Construct an undefined image handle */
    Image() : ImageBase() {}

    /** Allocate an image with the given dimensions. */
    // @{
    NO_INLINE Image(int x, int y = 0, int z = 0, int w = 0, const std::string &name = "") :
        ImageBase(type_of<T>(), x, y, z, w, name) {}

    NO_INLINE Image(int x, int y, int z, const std::string &name) :
        ImageBase(type_of<T>(), x, y, z, 0, name) {}

    NO_INLINE Image(int x, int y, const std::string &name) :
        ImageBase(type_of<T>(), x, y, 0, 0, name) {}

    NO_INLINE Image(int x, const std::string &name) :
        ImageBase(type_of<T>(), x, 0, 0, 0, name) {}
    // @}

    /** Wrap a buffer in an Image object, so that we can directly
     * access its pixels in a type-safe way. */
    NO_INLINE Image(const Buffer &buf) : ImageBase(type_of<T>(), buf) {}

    /** Wrap a single-element realization in an Image object. */
    NO_INLINE Image(const Realization &r) : ImageBase(type_of<T>(), r) {}

    /** Wrap a buffer_t in an Image object, so that we can access its
     * pixels. */
    NO_INLINE Image(const buffer_t *b, const std::string &name = "") :
        ImageBase(type_of<T>(), b, name) {}

    /** Get a pointer to the element at the min location. */
    NO_INLINE T *data() const {
        user_assert(defined()) << "data of undefined Image\n";
        return (T *)buffer.host_ptr();
    }

    using ImageBase::operator();

    /** Assuming this image is one-dimensional, get the value of the
     * element at position x */
    const T &operator()(int x) const {
        return *((T *)(address_of(x)));
    }

    /** Assuming this image is two-dimensional, get the value of the
     * element at position (x, y) */
    const T &operator()(int x, int y) const {
        return *((T *)(address_of(x, y)));
    }

    /** Assuming this image is three-dimensional, get the value of the
     * element at position (x, y, z) */
    const T &operator()(int x, int y, int z) const {
        return *((T *)(address_of(x, y, z)));
    }

    /** Assuming this image is four-dimensional, get the value of the
     * element at position (x, y, z, w) */
    const T &operator()(int x, int y, int z, int w) const {
        return *((T *)(address_of(x, y, z, w)));
    }

    /** Assuming this image is one-dimensional, get a reference to the
     * element at position x */
    T &operator()(int x) {
        return *((T *)(address_of(x)));
    }

    /** Assuming this image is two-dimensional, get a reference to the
     * element at position (x, y) */
    T &operator()(int x, int y) {
        return *((T *)(address_of(x, y)));
    }

    /** Assuming this image is three-dimensional, get a reference to the
     * element at position (x, y, z) */
    T &operator()(int x, int y, int z) {
        return *((T *)(address_of(x, y, z)));
    }

    /** Assuming this image is four-dimensional, get a reference to the
     * element at position (x, y, z, w) */
    T &operator()(int x, int y, int z, int w) {
        return *((T *)(address_of(x, y, z, w)));
    }

    /** Get a handle on the Buffer that this image holds */
    operator Buffer() const {
        return buffer;
    }

    /** Convert this image to an argument to a halide pipeline. */
    operator Argument() const {
        return Argument(buffer);
    }

    /** Convert this image to an argument to an extern stage. */
    operator ExternFuncArgument() const {
        return ExternFuncArgument(buffer);
    }

    /** Treating the image as an Expr is equivalent to call it with no
     * arguments. For example, you can say:
     *
     \code
     Image im(10, 10);
     Func f;
     f = im*2;
     \endcode
     *
     * This will define f as a two-dimensional function with value at
     * position (x, y) equal to twice the value of the image at the
     * same location.
     */
    operator Expr() const {
        return (*this)(_);
    }

};

}

#endif


text:
<?php defined('BX_DOL') or die('hack attempt');

bx_import('BxDolPrivacy');

class BxNtfsConfig extends BxBaseModNotificationsConfig
{
    protected $_iOwnerNameMaxLen;
    protected $_iContentMaxLen;
    protected $_iPushMaxLen;

    protected $_aHandlersHiddenEmail;
    protected $_aHandlersHiddenPush;

    /**
     * Group settings by action. Enabled by default.
     */
    protected $_bSettingsGrouped;
    protected $_aSettingsTypes;

    protected $_aModulesProfiles;
    protected $_aModulesContexts;

    protected $_iDeliveryTimeout;
    protected $_iProcessedEvent;

    protected $_bEventsGrouped;

    /**
     * Constructor
     */
    public function __construct($aModule)
    {
        parent::__construct($aModule);

        $this->CNF = array (
            // page URIs
            'URL_HOME' => 'page.php?i=notifications-view',

            // some params
            'PARAM_QUEUE_ADD_THRESHOLD' => 0,
            'PARAM_COMMENT_POST_EXT' => 'bx_notifications_enable_comment_post_ext',

            // objects
            'OBJECT_MENU_SUBMENU' => 'bx_notifications_submenu', // main module submenu
            'OBJECT_MENU_SETTINGS' => 'bx_notifications_settings', // settings submenu
            'OBJECT_GRID_SETTINGS_ADMINISTRATION' => 'bx_notifications_settings_administration',
            'OBJECT_GRID_SETTINGS_COMMON' => 'bx_notifications_settings_common',

            // some language keys
            'T' => array(
                'setting_personal' => '_bx_ntfs_setting_type_personal',
                'setting_follow_member' => '_bx_ntfs_setting_type_follow_member',
                'setting_follow_context' => '_bx_ntfs_setting_type_follow_context',
                'setting_other' => '_bx_ntfs_setting_type_other',
            )
        );

        $this->_aPrefixes = array(
            'style' => 'bx-ntfs',
            'language' => '_bx_ntfs',
            'option' => 'bx_notifications_'
        );

        $this->_iOwnerNameMaxLen = 21;
        $this->_iContentMaxLen = 32;
        $this->_iPushMaxLen = 190;

        $this->_aHandlerDescriptor = array('module_name' => '', 'module_method' => '', 'module_class' => '');
        $this->_sHandlersMethod = 'get_notifications_data';
        $this->_aHandlersHiddenEmail = array();
        $this->_aHandlersHiddenPush = array();

        $this->_bSettingsGrouped = true;
        $this->_aSettingsTypes = array(
            BX_NTFS_STYPE_PERSONAL,
            BX_NTFS_STYPE_FOLLOW_MEMBER,
            BX_NTFS_STYPE_FOLLOW_CONTEXT,
            //BX_NTFS_STYPE_OTHER           //TODO: May be it can be removed, because there is no events(alerts) for this type.
        );

        $this->_aModulesProfiles = false;
        $this->_aModulesContexts = false;

        $this->_aJsClasses = array(
            'main' => 'BxNtfsMain',
            'view' => 'BxNtfsView',
        );
        $this->_aJsObjects = array(
            'main' => 'oBxNtfsMain',
            'view' => 'oBxNtfsView',
        );

        $sHtmlPrefix = str_replace('_', '-', $this->_sName);
        $this->_aHtmlIds = array(
            'view' => array(
                'block' => $sHtmlPrefix,
                'events' => $sHtmlPrefix . '-events',
                'event' => $sHtmlPrefix . '-event-'
            )
        );
    }

    public function init(&$oDb)
    {
    	parent::init($oDb);

    	$sOptionPrefix = $this->getPrefix('option');
    	$this->_aPerPage = array(
            'default' => (int)getParam($sOptionPrefix . 'events_per_page'),
    	    'preview' => (int)getParam($sOptionPrefix . 'events_per_preview')
    	);

        $this->_bSettingsGrouped = getParam($sOptionPrefix . 'enable_group_settings') == 'on';

    	$aSettings = array(
    	    'site' => '',
    	    'email' => 'Email',
    	    'push' => 'Push'
    	);
    	foreach($aSettings as $sSetting => $sVariable) {
    	    $sHideTimeline = getParam($sOptionPrefix . 'events_hide_' . $sSetting);
            if(!empty($sHideTimeline))
                $this->{'_aHandlersHidden' . $sVariable} = explode(',', $sHideTimeline);
    	}

        $this->_iDeliveryTimeout = (int)getParam($sOptionPrefix . 'delivery_timeout');
        $this->_iProcessedEvent = (int)getParam($sOptionPrefix . 'processed_event');

        $this->_bEventsGrouped = getParam($sOptionPrefix . 'enable_group_events') == 'on';
    }

    public function getOwnerNameMaxLen()
    {
        return $this->_iOwnerNameMaxLen;
    }

    public function getContentMaxLen()
    {
        return $this->_iContentMaxLen;
    }

    public function getPushMaxLen()
    {
        return $this->_iPushMaxLen;
    }

    public function getHandlersHidden($sType = '')
    {
        if(!in_array($sType, array('', 'email', 'push')))
            return array();

        return $this->{'_aHandlersHidden' . ucfirst($sType)};
    }

    public function isSettingsGrouped()
    {
        return $this->_bSettingsGrouped;
    }

    public function getSettingsTypes()
    {
        return $this->_aSettingsTypes;
    }

    public function getDeliveryTimeout()
    {
        return $this->_iDeliveryTimeout;
    }

    public function isEventsGrouped()
    {
        return $this->_bEventsGrouped;
    }

    public function getProcessedEvent()
    {
        return $this->_iProcessedEvent;
    }

    public function setProcessedEvent($iEvent)
    {
        $this->_iProcessedEvent = $iEvent;

        setParam($this->getPrefix('option') . 'processed_event', $iEvent);
    }

    /**
     * Ancillary functions
     */
    public function getViewUrl()
    {
        return BX_DOL_URL_ROOT . BxDolPermalinks::getInstance()->permalink('page.php?i=notifications-view');
    }

    public function getContentModule(&$aEvent)
    {
        $sModule = $aEvent['type'];
        if($this->_oDb->isEnabledByName($sModule))
            return $sModule;

        $sModule = str_replace(array('_media', '_reactions'), array('', ''), $sModule);
        if($this->_oDb->isEnabledByName($sModule))
            return $sModule;

        return '';
    }

    public function getContentObjectId(&$aEvent)
    {
        return !empty($aEvent['content']['object_id']) ? (int)$aEvent['content']['object_id'] : (int)$aEvent['object_id'];
    }

    public function getProfileBasedModules()
    {
        if ($this->_aModulesProfiles !== false && $this->_aModulesContexts !== false)
            return array($this->_aModulesProfiles, $this->_aModulesContexts);

        if (getParam('sys_db_cache_enable')) {
            $oDb = BxDolDb::getInstance();
            $oCache = $oDb->getDbCacheObject();
            $sCacheKey = $oDb->genDbCacheKey('bx_ntfs_profile_based_modules');
            $aData = $oCache->getData($sCacheKey);
            if (null === $aData) {
                $aData = $this->_getProfileBasedModulesData();
                $oCache->setData ($sCacheKey, $aData);
            }
        }
        else {
            $aData = $this->_getProfileBasedModulesData();
        }

        return $aData;
    }

    protected function _getProfileBasedModulesData()
    {
        $this->_aModulesProfiles = [];
        $this->_aModulesContexts = [];

        $aModules = BxDolModuleQuery::getInstance()->getModulesBy(['type' => 'modules']);
        foreach($aModules as $aModule) {
            if(!bx_is_srv($aModule['name'], 'act_as_profile'))
                continue;

            if(bx_srv($aModule['name'], 'act_as_profile'))
                $this->_aModulesProfiles[] = $aModule['name'];
            else
                $this->_aModulesContexts[] = $aModule['name'];
        }

        return [$this->_aModulesProfiles, $this->_aModulesContexts];
    }
}

/** @} */


text:
package org.robolectric.shadows;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.telephony.TelephonyManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.TestRunners;
import org.robolectric.annotation.Config;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
import static org.robolectric.Shadows.shadowOf;

@RunWith(TestRunners.MultiApiWithDefaults.class)
public class ShadowConnectivityManagerTest {
  private ConnectivityManager connectivityManager;
  private ShadowNetworkInfo shadowOfActiveNetworkInfo;
  private ShadowConnectivityManager shadowConnectivityManager;

  @Before
  public void setUp() throws Exception {
    connectivityManager = (ConnectivityManager) RuntimeEnvironment.application.getSystemService(Context.CONNECTIVITY_SERVICE);
    shadowConnectivityManager = shadowOf(connectivityManager);
    shadowOfActiveNetworkInfo = shadowOf(connectivityManager.getActiveNetworkInfo());
  }

  @Test
  public void getActiveNetworkInfo_shouldInitializeItself() {
    assertThat(connectivityManager.getActiveNetworkInfo()).isNotNull();
  }

  @Test
  public void getActiveNetworkInfo_shouldReturnTrueCorrectly() {
    shadowOfActiveNetworkInfo.setConnectionStatus(true);
    assertThat(connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()).isTrue();
    assertTrue(connectivityManager.getActiveNetworkInfo().isConnected());

    shadowOfActiveNetworkInfo.setConnectionStatus(false);
    assertThat(connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting()).isFalse();
    assertThat(connectivityManager.getActiveNetworkInfo().isConnected()).isFalse();
  }

  @Test
  public void getNetworkInfo_shouldReturnDefaultNetworks() throws Exception {
    NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    assertThat(wifi.getDetailedState()).isEqualTo(NetworkInfo.DetailedState.DISCONNECTED);

    NetworkInfo mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
    assertThat(mobile.getDetailedState()).isEqualTo(NetworkInfo.DetailedState.CONNECTED);
  }

  @Test
  public void setConnectionType_shouldReturnTypeCorrectly() {
    shadowOfActiveNetworkInfo.setConnectionType(ConnectivityManager.TYPE_MOBILE);
    assertThat(ConnectivityManager.TYPE_MOBILE).isEqualTo(shadowOfActiveNetworkInfo.getType());

    shadowOfActiveNetworkInfo.setConnectionType(ConnectivityManager.TYPE_WIFI);
    assertThat(ConnectivityManager.TYPE_WIFI).isEqualTo(shadowOfActiveNetworkInfo.getType());
  }

  @Test
  public void shouldGetAndSetBackgroundDataSetting() throws Exception {
    assertThat(connectivityManager.getBackgroundDataSetting()).isFalse();
    shadowConnectivityManager.setBackgroundDataSetting(true);
    assertThat(connectivityManager.getBackgroundDataSetting()).isTrue();
  }

  @Test
  public void setActiveNetworkInfo_shouldSetActiveNetworkInfo() throws Exception {
    shadowConnectivityManager.setActiveNetworkInfo(null);
    assertThat(connectivityManager.getActiveNetworkInfo()).isNull();
    shadowConnectivityManager.setActiveNetworkInfo(ShadowNetworkInfo.newInstance(null,
        ConnectivityManager.TYPE_MOBILE_HIPRI,
        TelephonyManager.NETWORK_TYPE_EDGE, true, false));

    NetworkInfo info = connectivityManager.getActiveNetworkInfo();

    assertThat(ConnectivityManager.TYPE_MOBILE_HIPRI).isEqualTo(info.getType());
    assertThat(TelephonyManager.NETWORK_TYPE_EDGE).isEqualTo(info.getSubtype());
    assertThat(info.isAvailable()).isTrue();
    assertThat(info.isConnected()).isFalse();
  }

  @Test
  public void getAllNetworkInfo_shouldReturnAllNetworkInterfaces() throws Exception {
    NetworkInfo[] infos = connectivityManager.getAllNetworkInfo();
    assertThat(infos).hasSize(2);
    assertThat(connectivityManager.getActiveNetworkInfo()).isSameAs(infos[0]);

    shadowConnectivityManager.setActiveNetworkInfo(null);
    assertThat(connectivityManager.getAllNetworkInfo()).isEmpty();
  }

  @Test
  public void getNetworkPreference_shouldGetDefaultValue() throws Exception {
    assertThat(connectivityManager.getNetworkPreference()).isEqualTo(ConnectivityManager.DEFAULT_NETWORK_PREFERENCE);
  }

  @Test
  public void setNetworkPreference_shouldSetDefaultValue() throws Exception {
    connectivityManager.setNetworkPreference(ConnectivityManager.TYPE_MOBILE);
    assertThat(connectivityManager.getNetworkPreference()).isEqualTo(connectivityManager.getNetworkPreference());
    connectivityManager.setNetworkPreference(ConnectivityManager.TYPE_WIFI);
    assertThat(connectivityManager.getNetworkPreference()).isEqualTo(ConnectivityManager.TYPE_WIFI);
  }

  @Test @Config(sdk = 21)
  public void getNetworkCallbacks_shouldHaveEmptyDefault() throws Exception {
    assertEquals(0, shadowConnectivityManager.getNetworkCallbacks().size());
  }

  private static ConnectivityManager.NetworkCallback createSimpleCallback() {
    return new ConnectivityManager.NetworkCallback() {
      @Override
      public void onAvailable(Network network) {}
      @Override
      public void onLost(Network network) {}
    };
  }

  @Test @Config(sdk = 21)
  public void registerCallback_shouldAddCallback() throws Exception {
    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    ConnectivityManager.NetworkCallback callback = createSimpleCallback();
    connectivityManager.registerNetworkCallback(builder.build(), callback);
    assertEquals(1, shadowConnectivityManager.getNetworkCallbacks().size());
  }

  @Test @Config(sdk = 21)
  public void unregisterCallback_shouldRemoveCallbacks() throws Exception {
    NetworkRequest.Builder builder = new NetworkRequest.Builder();
    // Add two different callbacks.
    ConnectivityManager.NetworkCallback callback1 = createSimpleCallback();
    ConnectivityManager.NetworkCallback callback2 = createSimpleCallback();
    connectivityManager.registerNetworkCallback(builder.build(), callback1);
    connectivityManager.registerNetworkCallback(builder.build(), callback2);
    // Remove one at the time.
    assertEquals(2, shadowConnectivityManager.getNetworkCallbacks().size());
    connectivityManager.unregisterNetworkCallback(callback2);
    assertEquals(1, shadowConnectivityManager.getNetworkCallbacks().size());
    connectivityManager.unregisterNetworkCallback(callback1);
    assertEquals(0, shadowConnectivityManager.getNetworkCallbacks().size());
  }

  @Test(expected=IllegalArgumentException.class) @Config(sdk = 21)
  public void unregisterCallback_shouldNotAllowNullCallback() throws Exception {
    // Verify that exception is thrown.
    connectivityManager.unregisterNetworkCallback(null);
  }
}


text:
import json
import math
import numbers

from django.utils.html import escape

from desktop.lib.i18n import smart_unicode

# Materialize and HTML escape results
def escape_rows(rows, nulls_only=False):
  data = []

  for row in rows:
    escaped_row = []
    for field in row:
      if isinstance(field, numbers.Number):
        if math.isnan(field) or math.isinf(field):
          escaped_field = json.dumps(field)
        else:
          escaped_field = field
      elif field is None:
        escaped_field = 'NULL'
      else:
        escaped_field = smart_unicode(field, errors='replace') # Prevent error when getting back non utf8 like charset=iso-8859-1
        if not nulls_only:
          escaped_field = escape(escaped_field).replace(' ', ' ')
      escaped_row.append(escaped_field)
    data.append(escaped_row)

  return data


text:
package com.java110.api.smo.parkingArea;

import com.java110.core.context.IPageData;
import org.springframework.http.ResponseEntity;

/**
 * 添加停车场接口
 *
 * add by wuxw 2019-06-30
 */
public interface IAddParkingAreaSMO {

    /**
     * 添加停车场
     * @param pd 页面数据封装
     * @return ResponseEntity 对象
     */
    ResponseEntity<String> saveParkingArea(IPageData pd);
}


text:
import React from 'react';

import Badge from './Badge';

const I18nStatus = (props: React.FunctionComponent) => {
	return (
		<Badge {...props} icon="i18next">
			i18n
		</Badge>
	);
};

export default React.memo(I18nStatus);


text:
<bill session="114" type="hc" number="1" updated="2017-02-14T20:05:58Z">
  <state datetime="2015-01-06T18:32:50-05:00">PASS_OVER:HOUSE</state>
  <status>
    <unknown datetime="2015-01-06T18:32:50-05:00"/>
  </status>
  <introduced datetime="2015-01-06"/>
  <titles>
    <title type="official" as="introduced">Regarding consent to assemble outside the seat of government.</title>
    <title type="display">Regarding consent to assemble outside the seat of government.</title>
  </titles>
  <sponsor bioguide_id="S000250"/>
  <cosponsors/>
  <actions>
    <action datetime="2015-01-06">
      <text>Introduced in House</text>
    </action>
    <action datetime="2015-01-06T18:32:37-05:00">
      <text>Considered as privileged matter.</text>
      <reference ref="CR H32" label="consideration"/>
    </action>
    <vote how="without objection" type="vote" datetime="2015-01-06T18:32:50-05:00" where="h" result="pass" state="PASS_OVER:HOUSE">
      <text>On agreeing to the resolution Agreed to without objection.</text>
      <reference ref="CR H32" label="text"/>
    </vote>
    <action datetime="2015-01-06T18:33:25-05:00">
      <text>Motion to reconsider laid on the table Agreed to without objection.</text>
    </action>
    <action datetime="2015-01-07">
      <text>Received in the Senate.</text>
    </action>
  </actions>
  <committees/>
  <relatedbills/>
  <subjects>
    <term name="Congress"/>
    <term name="Congressional operations and organization"/>
  </subjects>
  <amendments/>
  <summary date="2015-01-06T20:45:01Z" status="Passed House without amendment">(This measure has not been amended since it was introduced. The summary of that version is repeated here.)

Authorizes the Speaker of the House and the Majority Leader of the Senate, or their respective designees, to notify the Members of the House and the Senate, respectively, to assemble at a place outside the District of Columbia whenever, in their opinion, the public interest shall warrant it.</summary>
  <committee-reports/>
</bill>


text:
using namespace aff3ct;
using namespace aff3ct::module;

template <typename B, typename R>
Decoder_maximum_likelihood_std<B,R>
::Decoder_maximum_likelihood_std(const int K, const int N, const Encoder<B> &encoder, const bool hamming)
: Decoder_maximum_likelihood<B,R>(K, N, encoder),
  hamming(hamming),
  u_max(0),
  min_euclidean_dist(std::numeric_limits<float>::max()),
  min_hamming_dist(std::numeric_limits<uint32_t>::max())
{
	const std::string name = "Decoder_maximum_likelihood_std";
	this->set_name(name);

	if (K > 64)
	{
		std::stringstream message;
		message << "'K' has to be smaller or equal to 64 ('K' = " << K << ").";
		throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
	}

	// determine the maximum sequence 'u' of information bits
	if (K == 64)
		this->u_max = std::numeric_limits<uint64_t>::max();
	else
		this->u_max = ((uint64_t)1 << (uint64_t)(K)) -1;
}

template <typename B, typename R>
Decoder_maximum_likelihood_std<B,R>* Decoder_maximum_likelihood_std<B,R>
::clone() const
{
	auto m = new Decoder_maximum_likelihood_std(*this);
	m->deep_copy(*this);
	return m;
}

template <typename B, typename R>
int Decoder_maximum_likelihood_std<B,R>
::_decode_siho(const R *Y_N, B *V_K, const size_t frame_id)
{
	auto status = this->_decode_siho_cw(Y_N, this->best_X_N.data(), frame_id);
	std::copy(this->best_U_K.begin(), this->best_U_K.end(), V_K);

	return status;
}

template <typename B, typename R>
int Decoder_maximum_likelihood_std<B,R>
::_decode_siho_cw(const R *Y_N, B *V_N, const size_t frame_id)
{
	// compute Hamming distance instead of Euclidean distance
	if (hamming)
	{
		tools::hard_decide(Y_N, this->hard_Y_N.data(), this->N);
		auto status = this->_decode_hiho_cw(this->hard_Y_N.data(), V_N, frame_id);
		return status;
	}
	else
	{
		this->min_euclidean_dist = std::numeric_limits<float>::max();

		// for all the possible sequences of information bits
		for (uint64_t u = 0; u <= this->u_max; u++)
		{
			// convert the information bits to the codeword
			std::fill(this->U_K.begin(), this->U_K.end(), (B)0);
			auto data = (uint64_t*)this->U_K.data();
			data[0] = u;
			tools::Bit_packer::unpack(this->U_K.data(), this->K);
			this->encoder->encode(this->U_K.data(), this->X_N.data(), 0);

			// compute the Euclidean distance between the input LLR and the current codeword
			auto cur_euclidean_dist = this->compute_euclidean_dist(this->X_N.data(), Y_N);

			// update the best codeword
			if (cur_euclidean_dist < this->min_euclidean_dist)
			{
				this->min_euclidean_dist = cur_euclidean_dist;
				std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
				std::copy(this->U_K.begin(), this->U_K.begin() + this->K, this->best_U_K.begin());
			}

			// trick to avoid infinite loop when u_max is the max 64-bit unsigned integer
			if (this->u_max == std::numeric_limits<uint64_t>::max())
				break;
		}

		return 0;
	}
}

template <typename B, typename R>
int Decoder_maximum_likelihood_std<B,R>
::_decode_hiho(const B *Y_N, B *V_K, const size_t frame_id)
{
	auto status = this->_decode_hiho_cw(Y_N, this->best_X_N.data(), frame_id);
	std::copy(this->best_U_K.begin(), this->best_U_K.end(), V_K);
	return status;
}

template <typename B, typename R>
int Decoder_maximum_likelihood_std<B,R>
::_decode_hiho_cw(const B *Y_N, B *V_N, const size_t frame_id)
{
	this->min_hamming_dist = std::numeric_limits<uint32_t>::max();

	// for all the possible sequences of information bits
	for (uint64_t u = 0; u <= this->u_max; u++)
	{
		// convert the information bits to the codeword
		std::fill(this->U_K.begin(), this->U_K.end(), (B)0);
		auto data = (uint64_t*)this->U_K.data();
		data[0] = u;
		tools::Bit_packer::unpack(this->U_K.data(), this->K);
		this->encoder->encode(this->U_K.data(), this->X_N.data(), 0);

		// compute the Hamming distance between the input bits and the current codeword
		auto cur_hamming_dist = this->compute_hamming_dist(this->X_N.data(), Y_N);

		// update the best codeword
		if (cur_hamming_dist < this->min_hamming_dist)
		{
			this->min_hamming_dist = cur_hamming_dist;
			std::copy(this->X_N.begin(), this->X_N.begin() + this->N, V_N);
			std::copy(this->U_K.begin(), this->U_K.begin() + this->K, this->best_U_K.begin());
		}

		// trick to avoid infinite loop when u_max is the max 64-bit unsigned integer
		if (u_max == std::numeric_limits<uint64_t>::max())
			break;
	}

	return 0;
}

// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef AFF3CT_MULTI_PREC
template class aff3ct::module::Decoder_maximum_likelihood_std<B_8,Q_8>;
template class aff3ct::module::Decoder_maximum_likelihood_std<B_16,Q_16>;
template class aff3ct::module::Decoder_maximum_likelihood_std<B_32,Q_32>;
template class aff3ct::module::Decoder_maximum_likelihood_std<B_64,Q_64>;
#else
template class aff3ct::module::Decoder_maximum_likelihood_std<B,Q>;
#endif
// ==================================================================================== explicit template instantiation


text:
<!DOCTYPE html>

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

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Poke your teacher</title>

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

    <link href="css/cover.css" rel="stylesheet">

COCOON.FI

Home

Vote

Contact

          <button type="button" class="btn btn-default btn-lg btn-block">Create your room</button>

OR

<input type="text" class="form-control lead" placeholder="Insert code number">
              Learn more

Product of CoCoon team


text:
angular.module('myApp1', [])
    .controller('HelloController1', function ($scope) {
        $scope.greeting = {message: "Hello"};
    });


text:
import scroll from "../../src"

import "./index.html"

document.querySelector("#To1000")
  .addEventListener("click", () => scroll({ y: 1000 }))

document.querySelector("#To20002000")
  .addEventListener("click", () => scroll({ x: 2000, y: 2000 }))

document.querySelector("#To50000")
  .addEventListener("click", () => scroll({ x: 0, y: 5000 }))

document.querySelector("#To50005000")
  .addEventListener("click", () => scroll({ x: 5000, y: 5000 }))

document.querySelector("#To05000")
  .addEventListener("click", () => scroll({ x: 0, y: 5000 }, 2000))

document.querySelector("#To30004000")
  .addEventListener("click", () => scroll({ x: 3000, y: 4000 }, 2000))


text:
package eu.impact_project.resultsrepository.report;

import java.util.ArrayList;
import java.util.List;

public class OcrEvalTool extends Tool {

	private String evaluationId;
	private List<Evaluation> evals = new ArrayList<Evaluation>();
	private boolean error = false;

	public OcrEvalTool(String name, String evaluationId) {
		this.name = name;
		this.evaluationId = evaluationId;
	}

	public String getName() {
		return name;
	}

	public String getEvaluationId() {
		return evaluationId;
	}

	public boolean hasError() {
		return error;
	}

	public void addEvaluation(boolean error) {
		Evaluation eval = new Evaluation(error);
		evals.add(eval);
	}

	public void addEvaluation(String chars, String errors, String accuracy,
			String words, String misrecognized, String wordAccuracy) {
		Evaluation eval = new Evaluation();
		eval.characters = chars;
		eval.errors = errors;
		eval.accuracy = accuracy;
		eval.words = words;
		eval.misrecognized = misrecognized;
		eval.wordAccuracy = wordAccuracy;
		evals.add(eval);
	}

	public List<Evaluation> getEvaluations() {
		return evals;
	}

	public class Evaluation {
		public String characters;
		public String errors;
		public String accuracy;
		public String words;
		public String misrecognized;
		public String wordAccuracy;

		private boolean error = false;

		public Evaluation() {
		}
		public Evaluation(boolean error) {
			this.error = error;
		}

		public boolean hasError() {
			return error;
		}

	}
}


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

namespace KompetansetorgetXamarin
{
    public static class BackendAdresses
    {
        public static string apiUri = "http://kompetansetorgetserver1.azurewebsites.net/api/";
        public static string apiVersion = "v1";
    }
}


text:
/**
 * @fileoverview Blocks for ComputerCraft Gps API
 * @author Edgar (AnotherFoxGuy)
 */

/* global Blockly*/

goog.provide('Blockly.Blocks.Gps');

goog.require('Blockly.Blocks');

Blockly.Blocks['gps_locate'] = {
  init: function() {
    this.appendDummyInput()
        .appendField("gps locate");
    this.appendDummyInput()
        .appendField("Debug")
        .appendField(new Blockly.FieldDropdown([["no", "false"], ["yes", "true"]]), "debug");
    this.appendValueInput("timeout")
        .setCheck("Number")
        .appendField("Timeout");
    this.setOutput(true, "vector");
    this.setColour(120);
    this.setTooltip('Tries to retrieve the computer or turtles own location. On success, returns the location of the turtle's modem. On failure (if no responses are received for timeout seconds, by default 2), returns nil. If debug is true, debug messages are printed.');
    this.setHelpUrl('http://www.computercraft.info/wiki/Gps_(API)');
  }
};


text:
package org.jetbrains.jps.model.serialization;

import com.intellij.openapi.util.io.FileUtil;
import com.intellij.testFramework.PlatformTestUtil;
import org.jdom.Element;
import org.jetbrains.jps.model.artifact.JpsArtifact;
import org.jetbrains.jps.model.artifact.JpsArtifactService;
import org.jetbrains.jps.model.serialization.artifact.JpsArtifactSerializer;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

import static org.jetbrains.jps.model.serialization.JpsProjectSerializationTest.SAMPLE_PROJECT_PATH;

/**
 * @author nik
 */
public class JpsArtifactSerializationTest extends JpsSerializationTestCase {
  public void testLoadProject() {
    loadProject(SAMPLE_PROJECT_PATH);
    List<JpsArtifact> artifacts = getService().getSortedArtifacts(myProject);
    assertEquals(2, artifacts.size());
    assertEquals("dir", artifacts.get(0).getName());
    assertEquals("jar", artifacts.get(1).getName());
  }

  public void testSaveProject() {
    loadProject(SAMPLE_PROJECT_PATH);
    File[] artifactFiles = new File(getTestDataFileAbsolutePath(SAMPLE_PROJECT_PATH + "/.idea/artifacts")).listFiles();
    assertNotNull(artifactFiles);
    for (File file : artifactFiles) {
      JpsArtifact artifact = getService().createReference(FileUtil.getNameWithoutExtension(file)).asExternal(myModel).resolve();
      assertNotNull(artifact);
      doTestSaveArtifact(artifact, file);
    }
  }

  private void doTestSaveArtifact(JpsArtifact artifact, File expectedFile) {
    try {
      Element actual = new Element("component").setAttribute("name", "ArtifactManager");
      JpsArtifactSerializer.saveArtifact(artifact, actual);
      JpsMacroExpander
        expander = JpsProjectLoader.createProjectMacroExpander(Collections.<String, String>emptyMap(), new File(getTestDataFileAbsolutePath(SAMPLE_PROJECT_PATH)));
      Element expected = JpsLoaderBase.loadRootElement(expectedFile, expander);
      PlatformTestUtil.assertElementsEqual(expected, actual);
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static JpsArtifactService getService() {
    return JpsArtifactService.getInstance();
  }
}


text:
// Copyright (C) 2012 The Android Open Source Project
//
// 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.

package com.google.gerrit.server.util;

import com.google.gerrit.server.config.RequestScopedReviewDbProvider;
import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.google.inject.Scope;
import java.util.concurrent.Callable;

/**
 * {@link RequestScopePropagator} implementation for request scopes based on a {@link ThreadLocal}
 * context.
 *
 * @param <C> "context" type stored in the {@link ThreadLocal}.
 */
public abstract class ThreadLocalRequestScopePropagator<C> extends RequestScopePropagator {

  private final ThreadLocal<C> threadLocal;

  protected ThreadLocalRequestScopePropagator(
      Scope scope,
      ThreadLocal<C> threadLocal,
      ThreadLocalRequestContext local,
      Provider<RequestScopedReviewDbProvider> dbProviderProvider) {
    super(scope, local, dbProviderProvider);
    this.threadLocal = threadLocal;
  }

  /** @see RequestScopePropagator#wrap(Callable) */
  @Override
  protected final <T> Callable<T> wrapImpl(Callable<T> callable) {
    C ctx = continuingContext(requireContext());
    return () -> {
      C old = threadLocal.get();
      threadLocal.set(ctx);
      try {
        return callable.call();
      } finally {
        if (old != null) {
          threadLocal.set(old);
        } else {
          threadLocal.remove();
        }
      }
    };
  }

  private C requireContext() {
    C context = threadLocal.get();
    if (context == null) {
      throw new OutOfScopeException("Cannot access scoped object");
    }
    return context;
  }

  /**
   * Returns a new context object based on the passed in context that has no request scoped objects
   * initialized.
   *
   * <p>Note that some code paths expect request-scoped objects like {@code CurrentUser} to be
   * constructible starting from just the context object returned by this method. For example, in
   * the SSH scope, the context includes the {@code SshSession}, which is used by {@code
   * SshCurrentUserProvider} to construct a new {@code CurrentUser} in the new thread.
   *
   * @param ctx the context to continue.
   * @return a new context.
   */
  protected abstract C continuingContext(C ctx);
}


text:
---
title: "JavaScriptでルールを書けるテキスト/Markdownの校正ツール textlint を作った"
author: azu
layout: post
date : 2014-12-30T14:17
category: JavaScript
tags:
    - Node.js
    - JavaScript
    - lint
    - tools
    - textlint

---

# [azu/textlint](https://github.com/azu/textlint "azu/textlint")

![lint result](http://monosnap.com/image/9FeIQr95kXjGPWFjZFRq6ZFG16YscF.png)

[textlint][] というテキスト(plain textとMarkdown)の校正をするためのコマンドラインツールを書きました。textlintはNode.jsで書かれていて、Node.jsモジュールとしての利用することもできます。

一番の特徴は校正するルールをJavaScriptで書くことで拡張可能な作りになっています。

> The pluggable linting tool for text(plain text and markdown).

逆にデフォルトではルールはサンプル扱いの`no-todo`というTODOが含まれてることを検知するルールしか今のところ入れていません。

- [Example: creating no-todo rules.](https://github.com/azu/textlint/blob/master/docs/create-rules.md#example-creating-no-todo-rules "Example: creating no-todo rules.")

デフォルトでルールが用意されていて、それの設定を変更することでLintする場合はRedPenなどがお勧めです。

- [RedPen: a document checker](http://redpen.cc/ "RedPen: a document checker")
- [RedPenを使って技術文書を手軽に校正しよう:連載|gihyo.jp … 技術評論社](http://gihyo.jp/lifestyle/serial/01/redpen "RedPenを使って技術文書を手軽に校正しよう:連載|gihyo.jp … 技術評論社")

## 使い方

たとえば、自分が書いた技術用語のチェックをするルール(WEB+DB PRESS表記ルールベース)を使いたい場合は以下のようにして利用できます。

```sh
npm install textlint -g
npm install spellcheck-tech-word-textlint-rule --save-dev
```

という感じでtextlint本体とルールはnpmでも公開してるので、npmでいれて以下のように`--rulesdir`というオプションでルールファイルがあるディレクトリを指定すれば、そのルールファイルが読み込んで実行できます。

```sh
textlint --rulesdir ./node_modules/spellcheck-tech-word-textlint-rule file.md
```

![rule指定での実行例](http://efcl.info/wp-content/uploads/2014/12/30-1419923294.jpg)

`textlint --rulesdir A/ --rulesdir B/` という複数のディレクトリも指定可能です。

細かいコマンドラインオプションは`-h`で確認出来ます。

```sh
$ textlint -h
textlint [options] file.md [file.txt] [dir]

Options:
  -h, --help                 Show help.
  --rulesdir [path::String]  Set rules from this directory and set all default rules to off.
  -f, --format String        Use a specific output format. - default: stylish
  -v, --version              Outputs the version number.
  --ext [String]             Specify text file extensions.
  --no-color                 Enable color in piped output.
  -o, --output-file path::String  Enable report to be written to a file.
  --quiet                    Report errors only. - default: false
  --stdin                    Lint code provided on <STDIN>. - default: false
```

### formatters

Lintした結果の出力方法はいろいろ用意してあって "stylish" (デフォルト), "compact", "checkstyle", "jslint-xml", "junit", "tap", "pretty-error"が利用できます。(スクリーンショットとかは"pretty-error"ですが、 East Asian Widthの問題でまだイマイチ不安定…)

`-o` と合わせれば、ファイルとして出力できます。(`checkstyle`とかはWebStormがESLint連携で使ったりしてるっぽいです)

これは[ESLint](http://eslint.org/ "ESLint")と互換性のあるformattersの実装になっているため、[ESLint](http://eslint.org/ "ESLint")で使われてるformattersをそのまま利用しました。

また、pluggable linting toolでわかるかもしれませんが [textlint][] 自体が全体的にESLintを真似て作ってあります。(オプションとか一部意味が変わったり省いていますが)

## ルールの作り方

[textlint][] の最大の特徴であるルールをJavaScriptで書ける点についてです。

正直、正確な校正ツールを求めるならば、自然言語をちゃんと解釈してMarkdownもサポートしてる[RedPen](http://redpen.cc/ "RedPen: a document checker")とかを利用したほうが質がいいと思います。
textlintはあくまでも自分でルール作りが手軽に出来るようにするのが目的です。

ルールの書き方も[ESLint](http://eslint.org/ "ESLint")と同じなので、ESLintのドキュメントも見てもらうといいかもしれません。

- [ESLint - Working with Rules](http://eslint.org/docs/developer-guide/working-with-rules.html "Working with Rules")
- [Maintaining JavaScript Code Quality with ESLint | PayPal Engineering Blog](https://www.paypal-engineering.com/2014/12/12/maintaining-javascript-code-quality-with-eslint/ "Maintaining JavaScript Code Quality with ESLint | PayPal Engineering Blog")
- [コードのバグはコードで見つけよう!|サイバーエージェント 公式エンジニアブログ](http://ameblo.jp/principia-ca/entry-11837554210.html "コードのバグはコードで見つけよう!|サイバーエージェント 公式エンジニアブログ")

<map id="map_6i2yv7gy" name="map_6i2yv7gy"><area coords="18,252,452,267" href="http://ameblo.jp/principia-ca/image-11837554210-12924937434.html" alt="" shape="rect" /><area coords="88,344,139,359" href="https://github.com/ariya/esprima" alt="" shape="rect" /><area coords="364,344,431,359" href="https://github.com/Constellation/estraverse" alt="" shape="rect" /></map>
コードのバグはコードで見つけよう!|サイバーエージェント 公式エンジニアブログ via kwout

ESLintはJavaScriptをASTにしてLintをしますが、textlintはテキストやMarkdownをASTにしてLintをします。

MarkdownのASTは[CommonMark](https://github.com/jgm/CommonMark "CommonMark")を元にして正規化したものを、plain textのASTはそれっぽくパースして、両方共[TxtNode interface](https://github.com/azu/textlint/blob/master/docs/txtnode.md "TxtNode interface")というものに則った形になります。(`type`の種類に差がありますが、文字列や改行などは共通しています)

MarkdownのASTは安定したものはまだないので、[wooorm/mdast](https://github.com/wooorm/mdast "wooorm/mdast")というプロジェクトが[range/location](https://github.com/wooorm/mdast/issues/2 "range/location")をサポートしてくれたらこっちに移行するかもしれません。
ただし、その場合もできるだけルールの互換性はとるようにするつもりです。

ルールの作成方法に話を戻すと、基本的な作り方については[create-rules.md](https://github.com/azu/textlint/blob/master/docs/create-rules.md "create-rules.md")にかいてあります。

### ルールの実装について

> [create-rules.md](https://github.com/azu/textlint/blob/master/docs/create-rules.md "create-rules.md") に同様のことが書いてあります

ルールとなるJavaScriptはひとつの関数を`exports`します。

その関数にはutilsなど入った`RuleContext`というもとが渡されます。
この`RuleContext`には、Nodeから元ファイルのテキストを取得する`context.getSource`などがあります。
またNode自体は[TxtNode interface](https://github.com/azu/textlint/blob/master/docs/txtnode.md "TxtNode interface")に沿った`type`や`loc`などの情報が入っています。
(まだparentなどが未完です => 実装 [textlint 1.4 パーサの安定化、ルールの自由度の改善をして現実的に使えるLintツールへ | Web Scratch](http://efcl.info/2015/01/07/textlint1.4/ "textlint 1.4 パーサの安定化、ルールの自由度の改善をして現実的に使えるLintツールへ | Web Scratch"))

```javascript
/**
 * @param {RuleContext} context
 */
module.exports = function (context) {
    var exports = {};
    // root object
    exports[context.Syntax.Document] = function (node) {
    };
    exports[context.Syntax.Paragraph] = function (node) {
    };
    // 文字列のNodeごとにこの関数がよばれる
    exports[context.Syntax.Str] = function (node) {
    	// そのNodeの文字列(内容)をみてよくないと思ったら`context.report`で報告する
        var text = context.getSource(node);
        if(/found wrong use-case/.test(text)){
            // report error
            context.report(node, new context.RuleError("found wrong"));
        }
    };
    exports[context.Syntax.Break] = function (node) {
    };
    return exports;
};
```

たとえば、`no-todo`というルールを作りたいときは`no-todo.js`というファイル名で以下のようにルールを書きます。(ファイル名 == ルールIDなので揃える)

このルールは`- [ ]`や`todo:`のような文字列を見つけたらエラーにするということを目的にします。

`context.Syntax.Str` というのは普通の文字列がやってくるので(パラグラフやリストの中、ラベルなどのタイミング)、それを正規表現で`/todo:/i.test(text)`という感じでチェックするだけですね。

また、Markdownは`- item`や`* item`といったリスト記法があるので、それらのリストアイテムが来た時に呼びたいチェック関数は`context.Syntax.ListItem`に定義しておけば問題ありません。

Nodeにどのようなtypeがあるかは[union-syntax.js](https://github.com/azu/textlint/blob/master/lib/parse/union-syntax.js "union-syntax.js")を参照して下さい。

ただし、plain textには`ListItem`というタイプはないので、その場合は呼ばれることはありません。
ファイル種類ごとにどのようなtypeがあるかは以下に書かれています。

- [textlint/txtnode.md at master · azu/textlint](https://github.com/azu/textlint/blob/master/docs/txtnode.md#type "textlint/txtnode.md at master · azu/textlint")

```javascript
"use strict"
/**
 * @param {RuleContext} context
 */
module.exports = function (context) {
    var exports = {};
    // When `node`'s type is `Str` come, call this callback.
    /*
    e.g.)
        # Header

        this is Str.

        Todo: quick fix this.
    */
    // `Str` is "this is Str." and "Todo: quick fix this.", so called this callback twice.
    exports[context.Syntax.Str] = function (node) {
        // get text from node
        var text = context.getSource(node);
        // does text contain "todo:"?
        if (/todo:/i.test(text)) {
            context.report(node, new context.RuleError("found Todo: " + text));
        }
    };
    // When `node`'s type is `ListItem` come, call this callback.
    /*
    e.g.)
        # Header

        - list 1
        - [ ] todo
    */
    // `List` is "- list 1" and - [ ] todo", so called this callback twice.
    exports[context.Syntax.ListItem] = function (node) {
        var text = context.getSource(node);
        if (/\[\s*?\]\s/i.test(text)) {
            context.report(node, new context.RuleError("found Todo: " + text));
        }
    };
    return exports;
};
```

こうして作ったルールをnpmやGitHubなどに公開して、先ほど紹介した`--rulesdir`などで指定すればすぐに利用できます。

公開するときに`textlint`というキーワードをつけておけば発見しやすいのでつけておくといいかもしれません。

- [Publish info](https://github.com/azu/textlint/blob/master/docs/create-rules.md#publish-info "Publish info")

実際に作った技術用語のLint(このルールは[WEB+DB PRESS用語統一ルール等を使った技術用語のLintをするCodeMirrorアドオンを書いた | Web Scratch](http://efcl.info/2014/10/20/lint-tech-word/ "WEB+DB PRESS用語統一ルール等を使った技術用語のLintをするCodeMirrorアドオンを書いた | Web Scratch")と同じやつです)

- [azu/spellcheck-tech-word-textlint-rule](https://github.com/azu/spellcheck-tech-word-textlint-rule "azu/spellcheck-tech-word-textlint-rule")

## textlintのモチベーション

[spellcheck-tech-word](https://github.com/azu/spellcheck-tech-word-textlint-rule "spellcheck-tech-word")のようなルールでチェックするためのコマンドラインツールとNode.jsモジュールがなかったので作ったというのが始まりですが、
実際にMarkdownなどのテキストやJSONの中にあるテキストをLintするためには、それ専用のものを書く必要があって不毛な感じがしました。(ルール自体に汎用性がない)

なので、[textlint][]が特定のフォーマットをパースしたり面倒なところをやって、ルールはどのフォーマットが来るかをあまり気にしないで書けるようにするのが目的です。

書いたあとに気づきましたが、[SCG: TextLint](http://scg.unibe.ch/research/textlint "SCG: TextLint")というプロジェクトがやってることがとても似ていると思います。(名前も同じだった…)

![concept](http://monosnap.com/image/Gr9CGbkSjl1FXEL0LIWzNDAj3c24JT.png)

via [Natural Language Checking with Program Checking Tools](http://www.slideshare.net/renggli/text-lint "Natural Language Checking with Program Checking Tools")

まだ正確なルールを書くにはちょっと必要なプロパティがたりてないですが、正規表現でざっとエラーチェックするみたいなことがだいぶ簡単に書けるようになってると思います。

Contributingも歓迎しています!

- [azu/textlint](https://github.com/azu/textlint "azu/textlint")

追記: [textlint 1.4 パーサの安定化、ルールの自由度の改善をして現実的に使えるLintツールへ | Web Scratch](http://efcl.info/2015/01/07/textlint1.4/ "textlint 1.4 パーサの安定化、ルールの自由度の改善をして現実的に使えるLintツールへ | Web Scratch")

----

基本的な思想やコードの一部を[ESLint](http://eslint.org/ "ESLint")プロジェクトのMITライセンスのものを利用しています。ESLintに感謝を

[textlint]: https://github.com/azu/textlint  "azu/textlint"


text:
/** @jsx jsx */
import { useQuery } from "@apollo/react-hooks";
import { RouteComponentProps } from "@reach/router";
import { Container } from "@theme-ui/components";
import { graphql } from "gatsby";
import { Fragment, useContext } from "react";
import { FormattedMessage } from "react-intl";
import { jsx } from "theme-ui";

import { useLoginState } from "../../app/profile/hooks";
import { Alert } from "../../components/alert";
import { LoginForm } from "../../components/login-form";
import { MetaTags } from "../../components/meta-tags";
import { useConference } from "../../context/conference";
import { SubmissionQuery as FallbackSubmissionQuery } from "../../generated/graphql";
import {
  IsVotingClosedQuery,
  IsVotingClosedQueryVariables,
  SubmissionQuery,
  SubmissionQueryVariables,
} from "../../generated/graphql-backend";
import IS_VOTING_CLOSED_QUERY from "./is-voting-closed.graphql";
import { Submission } from "./submission";
import SUBMISSION_QUERY from "./submission.graphql";

type PageContext = {
  id: string;
  socialCard: string;
  socialCardTwitter: string;
};

const NotLoggedIn: React.SFC<{
  title?: string;
  socialCard?: string;
  socialCardTwitter?: string;
}> = ({ title, socialCard, socialCardTwitter }) => (
  <Container>
    {title ? (
      <MetaTags
        title={title}
        imageUrl={socialCard}
        twitterImageUrl={socialCardTwitter}
      />
    ) : (
      <FormattedMessage id="submission.notFound">
        {text => <MetaTags title={text} />}
      </FormattedMessage>
    )}

    <Alert variant="info">
      You need to logged in and have a ticket to see this submission
    </Alert>

    <LoginForm />
  </Container>
);

const Loading = () => (
  <FormattedMessage id="submission.loading">
    {text => (
      <Fragment>
        <MetaTags title={text} />

        <Alert variant="info">{text}</Alert>
      </Fragment>
    )}
  </FormattedMessage>
);

const NotFound = () => (
  <FormattedMessage id="submission.notFound">
    {text => (
      <Fragment>
        <MetaTags title={text} />

        <Alert variant="alert">{text}</Alert>
      </Fragment>
    )}
  </FormattedMessage>
);

const Content = ({
  title,
  submission,
  pageContext,
}: {
  submission?: SubmissionQuery["submission"];
  pageContext?: PageContext;
  title: string;
}) => {
  const [loggedIn, _] = useLoginState();
  const { code } = useConference();

  const { data } = useQuery<IsVotingClosedQuery, IsVotingClosedQueryVariables>(
    IS_VOTING_CLOSED_QUERY,
    {
      variables: { conference: code },
    },
  );

  if (!data?.conference.isVotingClosed && !loggedIn) {
    return (
      <NotLoggedIn
        title={submission?.title || title}
        socialCard={pageContext?.socialCard}
        socialCardTwitter={pageContext?.socialCardTwitter}
      />
    );
  }

  if (!submission) {
    return <NotFound />;
  }

  return <Submission submission={submission} pageContext={pageContext} />;
};

type Props = {
  pageContext?: PageContext;
  data?: FallbackSubmissionQuery;
} & RouteComponentProps<{ id: string }>;

export const SubmissionPage: React.SFC<Props> = ({
  id,
  pageContext,
  data: fallbackData,
}) => {
  const { loading, data } = useQuery<SubmissionQuery, SubmissionQueryVariables>(
    SUBMISSION_QUERY,
    {
      errorPolicy: "all",
      variables: {
        id: pageContext?.id || id!,
      },
      skip: typeof window === "undefined",
    },
  );

  return (
    <Container sx={{ maxWidth: "container", px: 3 }}>
      {loading && <Loading />}
      {!loading && (
        <Content
          title={fallbackData?.backend.submission?.title!}
          submission={data?.submission}
          pageContext={pageContext}
        />
      )}
    </Container>
  );
};

export default SubmissionPage;

export const query = graphql`
  query Submission($id: ID!) {
    backend {
      submission(id: $id) {
        title
      }
    }
  }
`;


text:
from io import StringIO

from unittest.mock import patch  # pylint: disable=no-name-in-module, import-error

from gitlint.tests.base import BaseTestCase
from gitlint.lint import GitLinter
from gitlint.rules import RuleViolation, TitleMustNotContainWord
from gitlint.config import LintConfig, LintConfigBuilder

class LintTests(BaseTestCase):
    def test_lint_sample1(self):
        linter = GitLinter(LintConfig())
        gitcontext = self.gitcontext(self.get_sample("commit_message/sample1"))
        violations = linter.lint(gitcontext.commits[-1])
        # fmt: off
        expected_errors = [
            RuleViolation("T3", "Title has trailing punctuation (.)",
                                "Commit title contåining 'WIP', as well as trailing punctuation.", 1),
            RuleViolation("T5", "Title contains the word 'WIP' (case-insensitive)",
                            "Commit title contåining 'WIP', as well as trailing punctuation.", 1),
            RuleViolation("B4", "Second line is not empty", "This line should be empty", 2),
            RuleViolation("B1", "Line exceeds max length (135>80)",
                            "This is the first line of the commit message body and it is meant to test " +
                            "a line that exceeds the maximum line length of 80 characters.", 3),
            RuleViolation("B2", "Line has trailing whitespace", "This line has a tråiling space. ", 4),
            RuleViolation("B2", "Line has trailing whitespace", "This line has a trailing tab.\t", 5),
            RuleViolation("B3", "Line contains hard tab characters (\\t)",
                            "This line has a trailing tab.\t", 5)
        ]
        # fmt: on

        self.assertListEqual(violations, expected_errors)

    def test_lint_sample2(self):
        linter = GitLinter(LintConfig())
        gitcontext = self.gitcontext(self.get_sample("commit_message/sample2"))
        violations = linter.lint(gitcontext.commits[-1])
        expected = [
            RuleViolation("T5", "Title contains the word 'WIP' (case-insensitive)", "Just a title contåining WIP", 1),
            RuleViolation("B6", "Body message is missing", None, 3),
        ]

        self.assertListEqual(violations, expected)

    def test_lint_sample3(self):
        linter = GitLinter(LintConfig())
        gitcontext = self.gitcontext(self.get_sample("commit_message/sample3"))
        violations = linter.lint(gitcontext.commits[-1])

        # fmt: off
        title = " Commit title containing 'WIP', \tleading and tråiling whitespace and longer than 72 characters."
        expected = [
            RuleViolation("T1", "Title exceeds max length (95>72)", title, 1),
            RuleViolation("T3", "Title has trailing punctuation (.)", title, 1),
            RuleViolation("T4", "Title contains hard tab characters (\\t)", title, 1),
            RuleViolation("T5", "Title contains the word 'WIP' (case-insensitive)", title, 1),
            RuleViolation("T6", "Title has leading whitespace", title, 1),
            RuleViolation("B4", "Second line is not empty", "This line should be empty", 2),
            RuleViolation("B1", "Line exceeds max length (101>80)",
                            "This is the first line is meånt to test a line that exceeds the maximum line " +
                            "length of 80 characters.", 3),
            RuleViolation("B2", "Line has trailing whitespace", "This line has a trailing space. ", 4),
            RuleViolation("B2", "Line has trailing whitespace", "This line has a tråiling tab.\t", 5),
            RuleViolation("B3", "Line contains hard tab characters (\\t)",
                            "This line has a tråiling tab.\t", 5)
        ]
        # fmt: on

        self.assertListEqual(violations, expected)

    def test_lint_sample4(self):
        commit = self.gitcommit(self.get_sample("commit_message/sample4"))
        config_builder = LintConfigBuilder()
        config_builder.set_config_from_commit(commit)
        linter = GitLinter(config_builder.build())
        violations = linter.lint(commit)
        # expect no violations because sample4 has a 'gitlint: disable line'
        expected = []
        self.assertListEqual(violations, expected)

    def test_lint_sample5(self):
        commit = self.gitcommit(self.get_sample("commit_message/sample5"))
        config_builder = LintConfigBuilder()
        config_builder.set_config_from_commit(commit)
        linter = GitLinter(config_builder.build())
        violations = linter.lint(commit)

        title = " Commit title containing 'WIP', \tleading and tråiling whitespace and longer than 72 characters."
        # expect only certain violations because sample5 has a 'gitlint-ignore: T3, T6, body-max-line-length'
        expected = [
            RuleViolation("T1", "Title exceeds max length (95>72)", title, 1),
            RuleViolation("T4", "Title contains hard tab characters (\\t)", title, 1),
            RuleViolation("T5", "Title contains the word 'WIP' (case-insensitive)", title, 1),
            RuleViolation("B4", "Second line is not empty", "This line should be ëmpty", 2),
            RuleViolation("B2", "Line has trailing whitespace", "This line has a tråiling space. ", 4),
            RuleViolation("B2", "Line has trailing whitespace", "This line has a trailing tab.\t", 5),
            RuleViolation("B3", "Line contains hard tab characters (\\t)", "This line has a trailing tab.\t", 5),
        ]
        self.assertListEqual(violations, expected)

    def test_lint_meta(self):
        """Lint sample2 but also add some metadata to the commit so we that gets linted as well"""
        linter = GitLinter(LintConfig())
        gitcontext = self.gitcontext(self.get_sample("commit_message/sample2"))
        gitcontext.commits[0].author_email = "foo bår"
        violations = linter.lint(gitcontext.commits[-1])
        expected = [
            RuleViolation("M1", "Author email for commit is invalid", "foo bår", None),
            RuleViolation("T5", "Title contains the word 'WIP' (case-insensitive)", "Just a title contåining WIP", 1),
            RuleViolation("B6", "Body message is missing", None, 3),
        ]

        self.assertListEqual(violations, expected)

    def test_lint_ignore(self):
        lint_config = LintConfig()
        lint_config.ignore = ["T1", "T3", "T4", "T5", "T6", "B1", "B2"]
        linter = GitLinter(lint_config)
        violations = linter.lint(self.gitcommit(self.get_sample("commit_message/sample3")))

        expected = [
            RuleViolation("B4", "Second line is not empty", "This line should be empty", 2),
            RuleViolation("B3", "Line contains hard tab characters (\\t)", "This line has a tråiling tab.\t", 5),
        ]

        self.assertListEqual(violations, expected)

    def test_lint_configuration_rule(self):
        # Test that all rules are ignored because of matching regex
        lint_config = LintConfig()
        lint_config.set_rule_option("I1", "regex", "^Just a title(.*)")

        linter = GitLinter(lint_config)
        violations = linter.lint(self.gitcommit(self.get_sample("commit_message/sample2")))
        self.assertListEqual(violations, [])

        # Test ignoring only certain rules
        lint_config = LintConfig()
        lint_config.set_rule_option("I1", "regex", "^Just a title(.*)")
        lint_config.set_rule_option("I1", "ignore", "B6")

        linter = GitLinter(lint_config)
        violations = linter.lint(self.gitcommit(self.get_sample("commit_message/sample2")))

        # Normally we'd expect a B6 violation, but that one is skipped because of the specific ignore set above
        expected = [
            RuleViolation("T5", "Title contains the word 'WIP' (case-insensitive)", "Just a title contåining WIP", 1)
        ]

        self.assertListEqual(violations, expected)

        # Test ignoring body lines
        lint_config = LintConfig()
        linter = GitLinter(lint_config)
        lint_config.set_rule_option("I3", "regex", "(.*)tråiling(.*)")
        violations = linter.lint(self.gitcommit(self.get_sample("commit_message/sample1")))
        # fmt: off
        expected_errors = [
            RuleViolation("T3", "Title has trailing punctuation (.)",
                                "Commit title contåining 'WIP', as well as trailing punctuation.", 1),
            RuleViolation("T5", "Title contains the word 'WIP' (case-insensitive)",
                            "Commit title contåining 'WIP', as well as trailing punctuation.", 1),
            RuleViolation("B4", "Second line is not empty", "This line should be empty", 2),
            RuleViolation("B1", "Line exceeds max length (135>80)",
                            "This is the first line of the commit message body and it is meant to test " +
                            "a line that exceeds the maximum line length of 80 characters.", 3),
            RuleViolation("B2", "Line has trailing whitespace", "This line has a trailing tab.\t", 4),
            RuleViolation("B3", "Line contains hard tab characters (\\t)",
                            "This line has a trailing tab.\t", 4)
        ]
        # fmt: on
        self.assertListEqual(violations, expected_errors)

    def test_lint_special_commit(self):
        for commit_type in ["merge", "revert", "squash", "fixup", "fixup_amend"]:
            commit = self.gitcommit(self.get_sample(f"commit_message/{commit_type}"))
            lintconfig = LintConfig()
            linter = GitLinter(lintconfig)
            violations = linter.lint(commit)
            # Even though there are a number of violations in the commit message, they are ignored because
            # we are dealing with a merge commit
            self.assertListEqual(violations, [])

            # Check that we do see violations if we disable 'ignore-merge-commits'
            setattr(lintconfig, f"ignore_{commit_type}_commits", False)
            linter = GitLinter(lintconfig)
            violations = linter.lint(commit)
            self.assertTrue(len(violations) > 0)

    def test_lint_regex_rules(self):
        """Additional test for title-match-regex, body-match-regex"""
        commit = self.gitcommit(self.get_sample("commit_message/no-violations"))
        lintconfig = LintConfig()
        linter = GitLinter(lintconfig)
        violations = linter.lint(commit)
        # No violations by default
        self.assertListEqual(violations, [])

        # Matching regexes shouldn't be a problem
        rule_regexes = [("title-match-regex", "Tïtle$"), ("body-match-regex", "Sïgned-Off-By: (.*)$")]
        for rule_regex in rule_regexes:
            lintconfig.set_rule_option(rule_regex[0], "regex", rule_regex[1])
            violations = linter.lint(commit)
            self.assertListEqual(violations, [])

        # Non-matching regexes should return violations
        rule_regexes = [("title-match-regex",), ("body-match-regex",)]
        lintconfig.set_rule_option("title-match-regex", "regex", "^Tïtle")
        lintconfig.set_rule_option("body-match-regex", "regex", "Sügned-Off-By: (.*)$")
        expected_violations = [
            RuleViolation("T7", "Title does not match regex (^Tïtle)", "Normal Commit Tïtle", 1),
            RuleViolation("B8", "Body does not match regex (Sügned-Off-By: (.*)$)", None, 6),
        ]
        violations = linter.lint(commit)
        self.assertListEqual(violations, expected_violations)

    def test_print_violations(self):
        violations = [
            RuleViolation("RULE_ID_1", "Error Messåge 1", "Violating Content 1", None),
            RuleViolation("RULE_ID_2", "Error Message 2", "Violåting Content 2", 2),
        ]
        linter = GitLinter(LintConfig())

        # test output with increasing verbosity
        with patch("gitlint.display.stderr", new=StringIO()) as stderr:
            linter.config.verbosity = 0
            linter.print_violations(violations)
            self.assertEqual("", stderr.getvalue())

        with patch("gitlint.display.stderr", new=StringIO()) as stderr:
            linter.config.verbosity = 1
            linter.print_violations(violations)
            expected = "-: RULE_ID_1\n2: RULE_ID_2\n"
            self.assertEqual(expected, stderr.getvalue())

        with patch("gitlint.display.stderr", new=StringIO()) as stderr:
            linter.config.verbosity = 2
            linter.print_violations(violations)
            expected = "-: RULE_ID_1 Error Messåge 1\n2: RULE_ID_2 Error Message 2\n"
            self.assertEqual(expected, stderr.getvalue())

        with patch("gitlint.display.stderr", new=StringIO()) as stderr:
            linter.config.verbosity = 3
            linter.print_violations(violations)
            expected = (
                '-: RULE_ID_1 Error Messåge 1: "Violating Content 1"\n'
                + '2: RULE_ID_2 Error Message 2: "Violåting Content 2"\n'
            )
            self.assertEqual(expected, stderr.getvalue())

    def test_named_rules(self):
        """Test that when named rules are present, both them and the original (non-named) rules executed"""

        lint_config = LintConfig()
        for rule_name in ["my-ïd", "another-rule-ïd"]:
            rule_id = TitleMustNotContainWord.id + ":" + rule_name
            lint_config.rules.add_rule(TitleMustNotContainWord, rule_id)
            lint_config.set_rule_option(rule_id, "words", ["Föo"])
            linter = GitLinter(lint_config)

        violations = [
            RuleViolation("T5", "Title contains the word 'WIP' (case-insensitive)", "WIP: Föo bar", 1),
            RuleViolation("T5:another-rule-ïd", "Title contains the word 'Föo' (case-insensitive)", "WIP: Föo bar", 1),
            RuleViolation("T5:my-ïd", "Title contains the word 'Föo' (case-insensitive)", "WIP: Föo bar", 1),
        ]
        self.assertListEqual(violations, linter.lint(self.gitcommit("WIP: Föo bar\n\nFoo bår hur dur bla bla")))

    def test_ignore_named_rules(self):
        """Test that named rules can be ignored"""

        # Add named rule to lint config
        config_builder = LintConfigBuilder()
        rule_id = TitleMustNotContainWord.id + ":my-ïd"
        config_builder.set_option(rule_id, "words", ["Föo"])
        lint_config = config_builder.build()
        linter = GitLinter(lint_config)
        commit = self.gitcommit("WIP: Föo bar\n\nFoo bår hur dur bla bla")

        # By default, we expect both the violations of the regular rule as well as the named rule to show up
        violations = [
            RuleViolation("T5", "Title contains the word 'WIP' (case-insensitive)", "WIP: Föo bar", 1),
            RuleViolation("T5:my-ïd", "Title contains the word 'Föo' (case-insensitive)", "WIP: Föo bar", 1),
        ]
        self.assertListEqual(violations, linter.lint(commit))

        # ignore regular rule: only named rule violations show up
        lint_config.ignore = ["T5"]
        self.assertListEqual(violations[1:], linter.lint(commit))

        # ignore named rule by id: only regular rule violations show up
        lint_config.ignore = [rule_id]
        self.assertListEqual(violations[:-1], linter.lint(commit))

        # ignore named rule by name: only regular rule violations show up
        lint_config.ignore = [TitleMustNotContainWord.name + ":my-ïd"]
        self.assertListEqual(violations[:-1], linter.lint(commit))


text:
if(!dojo._hasResource["dojox.widget.DocTester"]){
dojo._hasResource["dojox.widget.DocTester"]=true;
dojo.provide("dojox.widget.DocTester");
dojo.require("dojo.string");
dojo.require("dijit._Widget");
dojo.require("dijit._Templated");
dojo.require("dojox.form.BusyButton");
dojo.require("dojox.testing.DocTest");
dojo.declare("dojox.widget.DocTester",[dijit._Widget,dijit._Templated],{templateString:dojo.cache("dojox.widget","DocTester/DocTester.html","
\n\t

\n\t<button dojoType=\"dojox.form.BusyButton\" busyLabel=\"Testing...\" dojoAttachPoint=\"runButtonNode\">Run tests</button>\n\t<button dojoType=\"dijit.form.Button\" dojoAttachPoint=\"resetButtonNode\" style=\"display:none;\">Reset</button>\n\t\n\t\t0 tests,\n\t\t0 passed,\n\t\t0 failed\n\t\n
\n"),widgetsInTemplate:true,_fillContent:function(_1){
var _2=_1.innerHTML;
this.doctests=new dojox.testing.DocTest();
this.tests=this.doctests.getTestsFromString(this._unescapeHtml(_2));
var _3=dojo.map(this.tests,"return item.line-1");
var _4=_2.split("\n");
var _5="
FAILED, actual result was:
";
var _6="
";
for(var i=0;i<_4.length;i++){
var _7=dojo.indexOf(_3,i);
if(_7>0&&_7!=-1){
var _8=_7%2?"even":"odd";
_6+=_5;
_6+="

";
}
_6+=_4[i].replace(/^\s+/,"")+"\n";
}
_6+=_5+"
";
this.containerNode.innerHTML=_6;
},postCreate:function(){
this.inherited("postCreate",arguments);
dojo.connect(this.runButtonNode,"onClick",dojo.hitch(this,"runTests"));
dojo.connect(this.resetButtonNode,"onClick",dojo.hitch(this,"reset"));
this.numTestsNode.innerHTML=this.tests.length;
},runTests:function(){
var _9={ok:0,nok:0};
for(var i=0;i<this.tests.length;i++){
var _a=this.doctests.runTest(this.tests[i].commands,this.tests[i].expectedResult);
dojo.query(".testNum"+i,this.domNode).addClass(_a.success?"resultOk":"resultNok");
if(!_a.success){
_9.nok++;
this.numTestsNokNode.innerHTML=_9.nok;
var _b=dojo.query(".testNum"+i+" .actualResult",this.domNode)[0];
dojo.style(_b,"display","inline");
dojo.query(".result",_b)[0].innerHTML=dojo.toJson(_a.actualResult);
}else{
_9.ok++;
this.numTestsOkNode.innerHTML=_9.ok;
}
}
this.runButtonNode.cancel();
dojo.style(this.runButtonNode.domNode,"display","none");
dojo.style(this.resetButtonNode.domNode,"display","");
},reset:function(){
dojo.style(this.runButtonNode.domNode,"display","");
dojo.style(this.resetButtonNode.domNode,"display","none");
this.numTestsOkNode.innerHTML="0";
this.numTestsNokNode.innerHTML="0";
dojo.query(".actualResult",this.domNode).style("display","none");
dojo.query(".testCase",this.domNode).removeClass("resultOk").removeClass("resultNok");
},_unescapeHtml:function(_c){
_c=String(_c).replace(/&/gm,"&").replace(/</gm,"<").replace(/>/gm,">").replace(/"/gm,"\"");
return _c;
}});
}


text:
package com.studio4plus.homerplayer.service;

import android.content.Context;

import com.studio4plus.homerplayer.model.AudioBookManager;

import dagger.Module;
import dagger.Provides;

@Module
public class AudioBookPlayerModule {
    @Provides AudioBookPlayer provideAudioBookPlayer(Context context, AudioBookManager audioBookManager) {
        return new AudioBookPlayer(context, audioBookManager);
    }
}


text:
namespace Fixtures.SwaggerBatBodyDate
{
    using System;
    using System.Collections.Generic;
    using System.Net.Http;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Rest;
    using Models;

    /// <summary>
    /// Test Infrastructure for AutoRest
    /// </summary>
    public partial interface IAutoRestDateTestService
    {
        /// <summary>
        /// The base URI of the service.
        /// </summary>
        Uri BaseUri { get; set; }

        IDate Date { get; }

        }
}


text:
using Avalonia.Platform;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Gdk;

namespace Avalonia.Gtk
{
    class IconImpl : IWindowIconImpl
    {
        public IconImpl(Pixbuf pixbuf)
        {
            Pixbuf = pixbuf;
        }

        public Pixbuf Pixbuf { get; }
    }
}


text:
Go HTTP Tutorials
====

Example Go programs using the `net/http` package.

This is not an introduction to the Go programming language. If you're an experienced programmer looking to learn Go, I recommend starting with [Effective Go](https://golang.org/doc/effective_go.html). If you're new to programming, check out [this list of learning resources](https://github.com/golang/go/wiki/Learn).

1. [A simple HTTP server](/01_handler/)
1. [Requests](/02_request/)
1. [Response](/03_response/)

Happy hacking!

aodin, 2012-2021


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta name="generator"

content="HTML Tidy for Mac OS, see www.w3.org" />

<title>XHTML Functional -- kbd</title>

This is regular text.

 This sentence inside the KBD tags should be displayed in a

fixed-width font.