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

namespace GroupControl.Model
{
    public enum EnumInstallAppType
    {
        /// <summary>
        /// 安装切换输入法
        /// </summary>
        KeyBoard=1,

        ///安装微信

        InstallApp=2
    }
}

redpajama_set_name: RedPajamaGithub


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**CheckoutJson** | **string** | Checkout JSON object | [optional]
**Errors** | **List<string>** | Errors that should be displayed to the customer | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: org.apache.http.ParseException
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_PARSEEXCEPTION_HPP_DECL
#define J2CPP_ORG_APACHE_HTTP_PARSEEXCEPTION_HPP_DECL

namespace j2cpp { namespace java { namespace lang { class RuntimeException; } } }
namespace j2cpp { namespace java { namespace lang { class String; } } }

#include <java/lang/RuntimeException.hpp>
#include <java/lang/String.hpp>

namespace j2cpp {

namespace org { namespace apache { namespace http {

	class ParseException;
	class ParseException
		: public object<ParseException>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)

		explicit ParseException(jobject jobj)
		: object<ParseException>(jobj)
		{
		}

		operator local_ref<java::lang::RuntimeException>() const;

		ParseException();
		ParseException(local_ref< java::lang::String > const&);
	}; //class ParseException

} //namespace http
} //namespace apache
} //namespace org

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_PARSEEXCEPTION_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_ORG_APACHE_HTTP_PARSEEXCEPTION_HPP_IMPL
#define J2CPP_ORG_APACHE_HTTP_PARSEEXCEPTION_HPP_IMPL

namespace j2cpp {

org::apache::http::ParseException::operator local_ref<java::lang::RuntimeException>() const
{
	return local_ref<java::lang::RuntimeException>(get_jobject());
}

org::apache::http::ParseException::ParseException()
: object<org::apache::http::ParseException>(
	call_new_object<
		org::apache::http::ParseException::J2CPP_CLASS_NAME,
		org::apache::http::ParseException::J2CPP_METHOD_NAME(0),
		org::apache::http::ParseException::J2CPP_METHOD_SIGNATURE(0)
	>()
)
{
}

org::apache::http::ParseException::ParseException(local_ref< java::lang::String > const &a0)
: object<org::apache::http::ParseException>(
	call_new_object<
		org::apache::http::ParseException::J2CPP_CLASS_NAME,
		org::apache::http::ParseException::J2CPP_METHOD_NAME(1),
		org::apache::http::ParseException::J2CPP_METHOD_SIGNATURE(1)
	>(a0)
)
{
}

J2CPP_DEFINE_CLASS(org::apache::http::ParseException,"org/apache/http/ParseException")
J2CPP_DEFINE_METHOD(org::apache::http::ParseException,0,"<init>","()V")
J2CPP_DEFINE_METHOD(org::apache::http::ParseException,1,"<init>","(Ljava/lang/String;)V")

} //namespace j2cpp

#endif //J2CPP_ORG_APACHE_HTTP_PARSEEXCEPTION_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
<resources>
    <!-- Base Theme -->
    <style name="BaseTheme.Light" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- App specific attributes all APIs -->
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="colorControlHighlight">@color/selector_black_pressed</item>
    </style>

    <!-- App Theme -->
    <style name="AppTheme.Light" parent="BaseTheme.Light">

    </style>

    <style name="MyTheme">
        <item name="backgroundColor">@color/background_white</item>
        <item name="timestampTextColor">@color/text_black</item>
        <item name="localBubbleBackground">@color/background_blue</item>
        <item name="localBubbleTextColor">@color/text_white</item>
        <item name="externalBubbleBackground">@color/background_gray</item>
        <item name="externalBubbleTextColor">@color/text_black</item>
        <item name="snackbarBackground">@color/background_gray_darkest</item>
        <item name="snackbarTitleColor">@color/text_black</item>
        <item name="snackbarButtonColor">@color/text_blue_lightest</item>
    </style>

    <style name="TextStyleBase">
        <item name="font">@string/chat_font_name</item>
    </style>

    <style name="InitialsStyle" parent="TextStyleBase">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_gravity">center</item>
        <item name="android:gravity">center</item>
        <item name="android:maxLines">1</item>
        <item name="android:textAllCaps">true</item>
        <item name="android:textColor">@color/text_white</item>
        <item name="android:textSize">@dimen/initials_font_size</item>
    </style>

    <style name="AvatarStyle">
        <item name="android:layout_width">@dimen/avatar_circle_radius</item>
        <item name="android:layout_height">@dimen/avatar_circle_radius</item>
    </style>

    <style name="BubbleStyleBase">
        <item name="android:orientation">vertical</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:background">@drawable/shape_rounded_rectangle_white</item>
        <item name="android:padding">@dimen/bubble_padding</item>
        <item name="android:minWidth">@dimen/bubble_min_width</item>
    </style>

    <style name="TextBubbleStyle" parent="BubbleStyleBase"></style>

    <style name="MediaBubbleStyle" parent="BubbleStyleBase">
        <item name="android:layout_width">match_parent</item>
    </style>

    <style name="TextMessageStyle" parent="TextStyleBase">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:autoLink">all</item>
        <item name="android:textColor">@color/text_navy</item>
        <item name="android:textSize">@dimen/message_text_font_size</item>
    </style>

    <style name="MessageTimestampStyle" parent="TextStyleBase">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:maxLines">1</item>
        <item name="android:layout_marginTop">@dimen/message_timestamp_margin_top</item>
        <item name="android:textColor">@color/text_gray_darkest</item>
        <item name="android:textSize">@dimen/message_timestamp_font_size</item>
    </style>

    <style name="MessageStateStyle" parent="TextStyleBase">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:maxLines">1</item>
        <item name="android:layout_marginTop">@dimen/message_state_margin_top</item>
        <item name="android:layout_marginBottom">@dimen/message_state_margin_bottom</item>
        <item name="android:textColor">@color/text_gray_darkest</item>
        <item name="android:textSize">@dimen/message_state_font_size</item>
    </style>

    <style name="MediaMessageStyle">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:adjustViewBounds">true</item>
        <item name="android:scaleType">centerCrop</item>
        <item name="riv_corner_radius">@dimen/media_message_corner_radius</item>
    </style>
</resources>


text:
package com.codexica.s3crate.filetree.history.snapshotstore.s3

import com.codexica.s3crate.filetree.history.snapshotstore.{DataBlob}
import java.io.{InputStream, FileOutputStream, BufferedOutputStream, File}
import java.security.MessageDigest
import scala.collection.mutable
import scala.concurrent.{ExecutionContext, Future}
import java.util.UUID
import org.slf4j.LoggerFactory
import org.jets3t.service.utils.ServiceUtils
import com.jcabi.aspects.Loggable
import java.util.concurrent.TimeUnit

/**
 * @author Josh Albrecht (joshalbrecht@gmail.com)
 */
protected[s3] object S3BlobWriter {
  protected val logger = LoggerFactory.getLogger(getClass)

  /**
   * Writes data to one or more (possibly encrypted) files (as determined by chunkSize) and calculates the MD5 for each
   * and for the entire thing
   *
   * @param data The data to write out
   * @param chunkSize The maximum amount of data to upload in one part.
   * @return (The encryption details, a map from file -> the hash of the file, and a hash of all contents that were written out
   * @throws AssertionError if there is no data.
   */
  @Loggable(value = Loggable.DEBUG, limit = 1000, unit = TimeUnit.MILLISECONDS, prepend = true)
  def write(data: InputStream, uploadDirectory: File, chunkSize: Long): (List[(File, Array[Byte])], Array[Byte]) = {
    logger.debug("Writing all data to {} in chunks of {} bytes", data, chunkSize)

    def makeUploadDirectoryFile(): File = {
      new File(uploadDirectory, UUID.randomUUID().toString)
    }

    var finishedWritingData = false
    var currentFile = makeUploadDirectoryFile()
    var currentOutputStream = new BufferedOutputStream(new FileOutputStream(currentFile))
    var currentMd5Accumulator: MessageDigest = MessageDigest.getInstance("MD5")
    //TODO: feels kind of silly that we hash everything twice for the first file part (eg, most files), but there's no
    //convenient way around it that I see. Perhaps we could clone it before calling digest...
    val completeMd5Accumulator: MessageDigest = MessageDigest.getInstance("MD5")
    val files = new mutable.ListBuffer[(File, Array[Byte])]()
    val bytes = new Array[Byte](4096)
    var numBytesWritten = 0L
    while (!finishedWritingData) {
      val numBytesRead = data.read(bytes)
      if (numBytesRead == -1) {
        logger.debug("Finished reading {}", data)
        finishedWritingData = true
      } else {
        val numBytesToWrite: Int = if (numBytesWritten + numBytesRead > chunkSize) {
          logger.trace("Finishing off the current file because the input stream is larger than {}", chunkSize)
          (chunkSize - numBytesWritten).toInt
        } else {
          numBytesRead
        }
        logger.trace("Writing {} bytes", numBytesToWrite)
        currentOutputStream.write(bytes, 0, numBytesToWrite)
        currentMd5Accumulator.update(bytes, 0, numBytesToWrite)
        completeMd5Accumulator.update(bytes, 0, numBytesToWrite)
        numBytesWritten += numBytesToWrite

        //roll over the file and write the rest
        if (numBytesRead > numBytesToWrite) {
          currentOutputStream.close()
          val digest = currentMd5Accumulator.digest
          files.append((currentFile, digest))
          logger.debug("Wrote {} bytes to {}, resulting in digest of {}", numBytesWritten.toString,
            currentFile.getAbsolutePath, ServiceUtils.toBase64(digest))
          currentFile = makeUploadDirectoryFile()
          currentOutputStream = new BufferedOutputStream(new FileOutputStream(currentFile))
          currentMd5Accumulator = MessageDigest.getInstance("MD5")
          numBytesWritten = 0L

          val remainingBytes = numBytesRead - numBytesToWrite
          logger.trace("Writing remaining {} bytes from last read to new file", remainingBytes)
          currentOutputStream.write(bytes, numBytesToWrite, remainingBytes)
          currentMd5Accumulator.update(bytes, numBytesToWrite, remainingBytes)
          completeMd5Accumulator.update(bytes, numBytesToWrite, remainingBytes)
          numBytesWritten += remainingBytes
        }
      }
    }
    currentOutputStream.close()
    val digest = currentMd5Accumulator.digest
    if (currentFile.length() <= 0) {
      assert(currentFile.delete())
      assert(files.size > 0)
    } else {
      files.append((currentFile, digest))
    }
    logger.debug("Wrote {} bytes to {}, resulting in digest of {}", numBytesWritten.toString,
      currentFile.getAbsolutePath, ServiceUtils.toBase64(digest))

    (files.toList, completeMd5Accumulator.digest())
  }
}


text:
/*
 * Minio Cloud Storage, (C) 2015 Minio, Inc.
 *
 * 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 main

import (
	"net/http"
	"os"
	"runtime"

	"github.com/minio/minio/pkg/probe"
)

type serverRPCService struct{}

func (s *serverRPCService) Add(r *http.Request, arg *ServerArg, rep *ServerRep) error {
	rep.Host = "192.168.1.1:9002"
	rep.ID = "6F27CB16-493D-40FA-B035-2A2E5646066A"
	return nil
}

func (s *serverRPCService) MemStats(r *http.Request, arg *ServerArg, rep *MemStatsRep) error {
	rep.Total = 64 * 1024 * 1024 * 1024
	rep.Free = 9 * 1024 * 1024 * 1024
	return nil
}

func (s *serverRPCService) DiskStats(r *http.Request, arg *ServerArg, rep *DiskStatsRep) error {
	rep.Disks = []string{"/mnt/disk1", "/mnt/disk2", "/mnt/disk3", "/mnt/disk4", "/mnt/disk5", "/mnt/disk6"}
	return nil
}

func (s *serverRPCService) SysInfo(r *http.Request, arg *ServerArg, rep *SysInfoRep) error {
	rep.SysARCH = runtime.GOARCH
	rep.SysOS = runtime.GOOS
	rep.SysCPUS = runtime.NumCPU()
	rep.Routines = runtime.NumGoroutine()
	rep.GOVersion = runtime.Version()
	var err error
	rep.Hostname, err = os.Hostname()
	if err != nil {
		return probe.WrapError(probe.NewError(err))
	}
	return nil
}

func (s *serverRPCService) NetStats(r *http.Request, arg *ServerArg, rep *NetStatsRep) error {
	rep.Interfaces = make([]Network, 0)
	rep.Interfaces = append(rep.Interfaces, Network{Address: "192.168.1.1", NetMask: "255.255.255.0", Hostname: "hostname1", Ethernet: "eth0"})
	return nil
}

func (s *serverRPCService) Version(r *http.Request, arg *ServerArg, rep *VersionRep) error {
	rep.Version = "0.0.1"
	rep.BuildDate = minioVersion
	rep.Architecture = runtime.GOARCH
	rep.OperatingSystem = runtime.GOOS
	return nil
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
        <meta name="generator" content="Doxygen 1.8.13"/>

        <title>CubbyFlow: CubbyFlow::TypeCast< T, U > Struct Template Reference</title>

        <link href="search/search.css" rel="stylesheet" type="text/css"/>

        <link href="doxygen.css" rel="stylesheet" type="text/css" />
        <link href="customdoxygen.css" rel="stylesheet" type="text/css"/>
        <link href='https://fonts.googleapis.com/css?family=Roboto+Slab' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

        <link href="jquery.smartmenus.bootstrap.css" rel="stylesheet">

                    CubbyFlow v0.71

CubbyFlow

TypeCast

Public Member Functions |
List of all members

CubbyFlow::TypeCast< T, U > Struct Template Reference

Type casting operator.
 More...

#include <Core/Utils/Functors.hpp>

Public Member Functions

constexpr U 	operator() (const T &a) const

Detailed Description

template<typename T, typename U>

struct CubbyFlow::TypeCast< T, U >

Type casting operator.

Member Function Documentation

◆ operator()()

template<typename T , typename U >

          constexpr U CubbyFlow::TypeCast< T, U >::operator()
          (
          const T &
          a	)
           const

The documentation for this struct was generated from the following files:

Core/Utils/Functors.hpp

Core/Utils/Functors-Impl.hpp

<address class="footer">
Generated on Thu Jul 15 2021 02:18:16 for CubbyFlow by

 1.8.13
</address>


text:
package org.openntf.domino.types;

public interface DocumentDescendant extends DatabaseDescendant {

	public org.openntf.domino.Document getAncestorDocument();

}


text:
namespace ts.pxtc {
    export interface CompileResult {
        // Extend the CompileResult interface with ts specific fields
        ast?: Program;
    }

    export function getTsCompilerOptions(opts: CompileOptions) {
        let options = ts.getDefaultCompilerOptions()

        options.target = ts.ScriptTarget.ES5;
        options.module = ModuleKind.None;
        options.noImplicitAny = true;
        options.noImplicitReturns = true;
        options.allowUnreachableCode = true;
        return options
    }

    export function nodeLocationInfo(node: ts.Node) {
        let file = getSourceFileOfNode(node)
        const nodeStart = node.getStart ? node.getStart() : node.pos;
        const { line, character } = ts.getLineAndCharacterOfPosition(file, nodeStart);
        const { line: endLine, character: endChar } = ts.getLineAndCharacterOfPosition(file, node.end);
        let r: LocationInfo = {
            start: nodeStart,
            length: node.end - nodeStart,
            line: line,
            column: character,
            endLine: endLine,
            endColumn: endChar,
            fileName: file.fileName,
        }
        return r
    }

    export function patchUpDiagnostics(diags: ReadonlyArray<Diagnostic>, ignoreFileResolutionErorrs = false) {
        if (ignoreFileResolutionErorrs) {
            // Because we generate the program and the virtual file system, we can safely ignore
            // file resolution errors. They are generated by triple slash references that likely
            // have a different path format than the one our dumb file system expects. The files
            // are included, our compiler host just isn't smart enough to resolve them.
            diags = diags.filter(d => d.code !== 5012);
        }
        let highPri = diags.filter(d => d.code == 1148)
        if (highPri.length > 0)
            diags = highPri;
        return diags.map(d => {
            if (!d.file) {
                let rr: KsDiagnostic = {
                    code: d.code,
                    start: d.start,
                    length: d.length,
                    line: 0,
                    column: 0,
                    messageText: ts.flattenDiagnosticMessageText(d.messageText, "\n"),
                    category: d.category,
                    fileName: "?",
                }
                return rr
            }

            const pos = ts.getLineAndCharacterOfPosition(d.file, d.start);
            let r: KsDiagnostic = {
                code: d.code,
                start: d.start,
                length: d.length,
                line: pos.line,
                column: pos.character,
                messageText: ts.flattenDiagnosticMessageText(d.messageText, "\n"),
                category: d.category,
                fileName: d.file.fileName,
            }
            if (r.code == 1148)
                r.messageText = Util.lf("all symbols in top-level scope are always exported; please use a namespace if you want to export only some")
            return r
        })
    }

    export function py2tsIfNecessary(opts: CompileOptions): transpile.TranspileResult | undefined {
        if (opts.target.preferredEditor == pxt.PYTHON_PROJECT_NAME) {
            let res = pxtc.transpile.pyToTs(opts)
            return res
        }
        return undefined
    }

    function mkCompileResult(): CompileResult {
        return {
            outfiles: {},
            diagnostics: [],
            success: false,
            times: {},
        }
    }

    export function storeGeneratedFiles(opts: CompileOptions, res: CompileResult) {
        // save files first, in case we generated some .ts files that fail to compile
        for (let f of opts.generatedFiles || [])
            res.outfiles[f] = opts.fileSystem[f]
    }

    export function runConversionsAndStoreResults(opts: CompileOptions, res?: CompileResult): CompileResult {
        const startTime = U.cpuUs()
        if (!res) {
            res = mkCompileResult();
        }
        const convRes = py2tsIfNecessary(opts)
        if (convRes) {
            res = { ...res, diagnostics: convRes.diagnostics, sourceMap: convRes.sourceMap, globalNames: convRes.globalNames }
        }

        storeGeneratedFiles(opts, res)

        if (!opts.sourceFiles)
            opts.sourceFiles = Object.keys(opts.fileSystem)
        // ensure that main.ts is last of TS files
        const idx = opts.sourceFiles.indexOf(pxt.MAIN_TS)
        if (idx >= 0) {
            opts.sourceFiles.splice(idx, 1)
            opts.sourceFiles.push(pxt.MAIN_TS)
        }

        // run post-processing code last, if present
        const postIdx = opts.sourceFiles.indexOf(pxt.TUTORIAL_CODE_STOP)
        if (postIdx >= 0) {
            opts.sourceFiles.splice(postIdx, 1)
            opts.sourceFiles.push(pxt.TUTORIAL_CODE_STOP)
        }

        res.times["conversions"] = U.cpuUs() - startTime

        return res
    }

    export function timesToMs(res: CompileResult) {
        for (let k of Object.keys(res.times)) {
            res.times[k] = Math.round(res.times[k]) / 1000
        }
    }

    function buildProgram(opts: CompileOptions, res: CompileResult) {
        let fileText: { [index: string]: string } = {};
        for (let fileName in opts.fileSystem) {
            fileText[normalizePath(fileName)] = opts.fileSystem[fileName];
        }

        let setParentNodes = true
        let options = getTsCompilerOptions(opts)

        let host: CompilerHost = {
            getSourceFile: (fn, v, err) => {
                fn = normalizePath(fn)
                let text = ""
                if (fileText.hasOwnProperty(fn)) {
                    text = fileText[fn]
                } else {
                    if (err) err("File not found: " + fn)
                }
                if (text == null) {
                    err("File not found: " + fn)
                    text = ""
                }
                return createSourceFile(fn, text, v, setParentNodes)
            },
            fileExists: fn => {
                fn = normalizePath(fn)
                return fileText.hasOwnProperty(fn)
            },
            getCanonicalFileName: fn => fn,
            getDefaultLibFileName: () => "no-default-lib.d.ts",
            writeFile: (fileName, data, writeByteOrderMark, onError) => {
                res.outfiles[fileName] = data
            },
            getCurrentDirectory: () => ".",
            useCaseSensitiveFileNames: () => true,
            getNewLine: () => "\n",
            readFile: fn => {
                fn = normalizePath(fn)
                return fileText[fn] || "";
            },
            directoryExists: dn => true,
            getDirectories: () => []
        }

        let tsFiles = opts.sourceFiles.filter(f => U.endsWith(f, ".ts"))
        return createProgram(tsFiles, options, host);
    }

    export function isPxtModulesFilename(filename: string) {
        return U.startsWith(filename, "pxt_modules/")
    }

    export interface CompilerHooks {
        init?(opts: CompileOptions, service?: LanguageService): void;
        preBinary?(program: Program, opts: CompileOptions, res: CompileResult): void;
        postBinary?(program: Program, opts: CompileOptions, res: CompileResult): void;
    }
    export let compilerHooks: CompilerHooks

    export function compile(opts: CompileOptions, service?: LanguageService) {
        if (!compilerHooks) {
            // run the extension at most once
            compilerHooks = {}

            // The extension JavaScript code comes from target.json. It is generated from compiler/*.ts in target by 'pxt buildtarget'
            if (opts.target.compilerExtension)
                // eslint-disable-next-line
                eval(opts.target.compilerExtension)
        }

        if (compilerHooks.init)
            compilerHooks.init(opts, service)

        let startTime = U.cpuUs()
        let res = mkCompileResult()

        let program: Program

        if (service) {
            storeGeneratedFiles(opts, res)
            program = service.getProgram()
        } else {
            runConversionsAndStoreResults(opts, res)
            if (res.diagnostics.length > 0)
                return res;
            program = buildProgram(opts, res)
        }

        const entryPoint = opts.sourceFiles.filter(f => U.endsWith(f, ".ts")).pop().replace(/.*\//, "")

        // First get and report any syntactic errors.
        res.diagnostics = patchUpDiagnostics(program.getSyntacticDiagnostics(), opts.ignoreFileResolutionErrors);
        if (res.diagnostics.length > 0) {
            if (opts.forceEmit) {
                pxt.debug('syntactic errors, forcing emit')
                compileBinary(program, opts, res, entryPoint);
            }
            return res;
        }

        // If we didn't have any syntactic errors, then also try getting the global and
        // semantic errors.
        res.diagnostics = patchUpDiagnostics(program.getOptionsDiagnostics().concat(Util.toArray(program.getGlobalDiagnostics())), opts.ignoreFileResolutionErrors);

        const semStart = U.cpuUs()

        if (res.diagnostics.length == 0) {
            res.diagnostics = patchUpDiagnostics(program.getSemanticDiagnostics(), opts.ignoreFileResolutionErrors);
        }

        const emitStart = U.cpuUs()
        res.times["typescript-syn"] = semStart - startTime
        res.times["typescript-sem"] = emitStart - semStart
        res.times["typescript"] = emitStart - startTime

        if (opts.ast) {
            res.ast = program
        }

        if (opts.ast || opts.forceEmit || res.diagnostics.length == 0) {
            const binOutput = compileBinary(program, opts, res, entryPoint);
            res.times["compilebinary"] = U.cpuUs() - emitStart
            res.diagnostics = res.diagnostics.concat(patchUpDiagnostics(binOutput.diagnostics))
        }

        if (res.diagnostics.length == 0)
            res.success = true

        for (let f of opts.sourceFiles) {
            if (Util.startsWith(f, "built/"))
                res.outfiles[f.slice(6)] = opts.fileSystem[f]
        }

        res.times["all"] = U.cpuUs() - startTime;
        pxt.tickEvent(`compile`, res.times);
        return res
    }

    export function decompile(program: Program, opts: CompileOptions, fileName: string, includeGreyBlockMessages = false) {
        let file = program.getSourceFile(fileName);
        annotate(program, fileName, target || (pxt.appTarget && pxt.appTarget.compile));
        const apis = getApiInfo(program, opts.jres);
        const blocksInfo = pxtc.getBlocksInfo(apis, opts.bannedCategories);
        const decompileOpts: decompiler.DecompileBlocksOptions = {
            snippetMode: opts.snippetMode || false,
            alwaysEmitOnStart: opts.alwaysDecompileOnStart,
            includeGreyBlockMessages,
            generateSourceMap: !!opts.ast,
            allowedArgumentTypes: opts.allowedArgumentTypes || ["number", "boolean", "string"],
            errorOnGreyBlocks: !!opts.errorOnGreyBlocks
        };
        const [renameMap, _] = pxtc.decompiler.buildRenameMap(program, file, { declarations: "variables", takenNames: {} })
        const bresp = pxtc.decompiler.decompileToBlocks(blocksInfo, file, decompileOpts, renameMap);
        return bresp;
    }

    // Decompile an array of code snippets (sourceTexts) to XML strings (blocks)
    export function decompileSnippets(program: Program, opts: CompileOptions, includeGreyBlockMessages = false) {
        const apis = getApiInfo(program, opts.jres);
        const blocksInfo = pxtc.getBlocksInfo(apis, opts.bannedCategories);
        const renameMap = new pxtc.decompiler.RenameMap([]); // Don't rename for snippets

        const decompileOpts: decompiler.DecompileBlocksOptions = {
            snippetMode: opts.snippetMode || false,
            alwaysEmitOnStart: opts.alwaysDecompileOnStart,
            includeGreyBlockMessages,
            generateSourceMap: !!opts.ast,
            allowedArgumentTypes: opts.allowedArgumentTypes || ["number", "boolean", "string"],
            errorOnGreyBlocks: !!opts.errorOnGreyBlocks
        };

        let programCache: Program; // Initialize to undefined, using the input program will incorrectly mark it as stale
        const xml: string[] = [];
        if (opts.sourceTexts) {
            for (let i = 0; i < opts.sourceTexts.length; i++) {
                opts.fileSystem[pxt.MAIN_TS] = opts.sourceTexts[i];
                opts.fileSystem[pxt.MAIN_BLOCKS] = "";

                let newProgram = getTSProgram(opts, programCache);
                const file = newProgram.getSourceFile(pxt.MAIN_TS);
                const bresp = pxtc.decompiler.decompileToBlocks(blocksInfo, file, decompileOpts, renameMap);
                xml.push(bresp.outfiles[pxt.MAIN_BLOCKS]);
                programCache = newProgram;
            }
        }

        return xml;
    }

    export function getTSProgram(opts: CompileOptions, old?: ts.Program) {
        let outfiles: pxt.Map<string> = {};

        let fileText: { [index: string]: string } = {};
        for (let fileName in opts.fileSystem) {
            fileText[normalizePath(fileName)] = opts.fileSystem[fileName];
        }

        let setParentNodes = true
        let options = getTsCompilerOptions(opts)

        let host: CompilerHost = {
            getSourceFile: (fn, v, err) => {
                fn = normalizePath(fn)
                let text = ""
                if (fileText.hasOwnProperty(fn)) {
                    text = fileText[fn]
                } else {
                    if (err) err("File not found: " + fn)
                }
                if (text == null) {
                    err("File not found: " + fn)
                    text = ""
                }
                return createSourceFile(fn, text, v, setParentNodes)
            },
            fileExists: fn => {
                fn = normalizePath(fn)
                return fileText.hasOwnProperty(fn)
            },
            getCanonicalFileName: fn => fn,
            getDefaultLibFileName: () => "no-default-lib.d.ts",
            writeFile: (fileName, data, writeByteOrderMark, onError) => {
                outfiles[fileName] = data
            },
            getCurrentDirectory: () => ".",
            useCaseSensitiveFileNames: () => true,
            getNewLine: () => "\n",
            readFile: fn => {
                fn = normalizePath(fn)
                return fileText[fn] || "";
            },
            directoryExists: dn => true,
            getDirectories: () => []
        }

        if (!opts.sourceFiles)
            opts.sourceFiles = Object.keys(opts.fileSystem)

        let tsFiles = opts.sourceFiles.filter(f => U.endsWith(f, ".ts"))
        // ensure that main.ts is last of TS files
        let tsFilesNoMain = tsFiles.filter(f => f != pxt.MAIN_TS)
        let hasMain = false;
        if (tsFiles.length > tsFilesNoMain.length) {
            tsFiles = tsFilesNoMain
            tsFiles.push(pxt.MAIN_TS)
            hasMain = true;
        }

        // run post-processing code last, if present
        const post_idx = tsFiles.indexOf(pxt.TUTORIAL_CODE_STOP);
        if (post_idx >= 0) {
            tsFiles.splice(post_idx, 1)
            tsFiles.push(pxt.TUTORIAL_CODE_STOP);
        }

        // TODO: ensure that main.ts is last???
        const program = createProgram(tsFiles, options, host, old);
        annotate(program, pxt.MAIN_TS, target || (pxt.appTarget && pxt.appTarget.compile));
        return program;
    }

    function normalizePath(path: string): string {
        path = path.replace(/\\/g, "/");

        const parts: string[] = [];
        path.split("/").forEach(part => {
            if (part === ".." && parts.length) {
                parts.pop();
            }
            else if (part !== ".") {
                parts.push(part)
            }
        });

        return parts.join("/");
    }
}


text:
package com.rhythm.louie.jdbc;

import java.io.Closeable;
import java.io.IOException;

import com.rhythm.louie.jdbc.query.ResultProcessor;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.rhythm.louie.jdbc.query.ResultMapper;

/**
 * A QueryBuilder aids in constructing and executing dynamic queries. Each portion
 * of a where clause can be appended with its corresponding argument.  This allows
 * the continued use of PreparedStatements with on-the-fly construction.  PreparedStatements
 * utilize the underlying JDBC driver caching and simplify the Database parsing,
 * both of which are essential to performance.
 *

 * Each QueryClause can be added using the various add*Clause utility methods.
 *

 * Calling execute will perform the query, returning the ResultSet.  After processing
 * has been completed, you must clean up to avoid connection leaks by calling closeAll()
 */

public class QueryBuilder implements Closeable {

    private final String prefix;
    private String suffix;
    boolean whereAdded;
    boolean hasBatch = false;
    final List<QueryClause> clauses = new ArrayList<>();
    private final JdbcFactory factory;
    private JdbcService jdbc = null;

    /**
     * @param factory the factory to create the db connection from
     * @param prefix should only be up to table clause
     *
     * Defaults where clauseAdded to be false
     */
    public QueryBuilder(JdbcFactory factory, String prefix) {
        this(factory, prefix, false);
    }

    /**
     * @param factory the factory to create the db connection from
     * @param prefix should only be up to table clause
     * @param whereAdded tells the builder to add a where clause or not
     */
    public QueryBuilder(JdbcFactory factory, String prefix, boolean whereAdded) {
        this.prefix = prefix;
        this.whereAdded = whereAdded;
        this.factory = factory;
    }

    /**
     * Sets the suffix to be appended to the end of the query, such as
     * "order by 1,2"
     *
     * NOTE! Specifying a suffix for batched queries may not work as desired,
     * as each batch will specify the suffix independently, instead of the whole result.
     *
     * Cannot contain parameters
     *
     * @param suffix
     * @throws java.lang.Exception if suffix contains a ?
     */
    public void setSuffix(String suffix) throws Exception {
        if (suffix.indexOf('?')!=-1) {
            throw new Exception("Must NOT specify a ? param!");
        }
        this.suffix = suffix;
    }

    @Override
    public String toString() {
        return getQuery();
    }

     /**
     * Builds the query string, to be created as a prepared statement.
     * Will only create the porting of the query for the specific batch offset.
     *
     * @param batch the batch offset, 0 for a non-batched query returns the full query
     * @return the query string, or null of the batch offset is outside the range of values
     */
    public String getBatchedQuery(int batch) {
        if (!hasBatch) {
            if (batch==0) {
                getQuery();
            } else {
                return null;
            }
        }

        StringBuilder query = new StringBuilder(prefix);
        boolean needsWhere = !whereAdded;
        for (QueryClause clause : clauses) {
            if (needsWhere) {
                query.append(" WHERE ");
                needsWhere=false;
            } else {
                query.append(" AND ");
            }
            if (clause.isBatched()) {
                String batchClause = clause.getClauseForBatch(batch);
                if (batchClause==null) {
                    return null;
                }
                query.append(batchClause);
            } else {
                query.append(clause.getClause());
            }
        }
        if (suffix!=null) {
            query.append(" ").append(suffix);
        }
        return query.toString();
    }

    /**
     * Builds the query string, to be created as a prepared statement.
     * This does not account for batches
     * @return the query string
     */
    public String getQuery() {
        StringBuilder query = new StringBuilder(prefix);
        boolean needsWhere = !whereAdded;
        for (QueryClause clause : clauses) {
            if (needsWhere) {
                query.append(" WHERE ");
                needsWhere=false;
            } else {
                query.append(" AND ");
            }
            query.append(clause.getClause());
        }
        if (suffix!=null) {
            query.append(" ").append(suffix);
        }
        return query.toString();
    }

    /**
     * Returns true if there are no clauses
     * @return true if their are no clauses specified
     */
    public boolean isEmpty() {
        return clauses.isEmpty();
    }

     /**
     * Returns the list of clauses.  Useful if you would like to apply the same
     * clauses to a second query
     * @return an unmodifiable list of all the clauses
     */
    public List<QueryClause> getClauses() {
        return Collections.unmodifiableList(clauses);
    }

    /**
     * Adds a clause in the form of: field IN (?,?,?)
     * @param field the name of the field
     * @param values the data to be injected into the prepared statement
     * @param sqlType the java.sql.Type of the field
     * @throws java.lang.Exception
     *
     * @see java.sql.Types
     */
    public void addInClause(String field, Collection<?> values, int sqlType) throws Exception {
        addClause(QueryClause.createInClause(field, values, sqlType));
    }

    /**
     * Adds a clause in the form of: field IN (?,?,?), batch query into multiple lookups
     * @param field the name of the field
     * @param values the data to be injected into the prepared statement
     * @param sqlType the java.sql.Type of the field
     * @throws java.lang.Exception
     *
     * @see java.sql.Types
     */
    public void addBatchedInClause(String field, List<?> values, int sqlType) throws Exception {
        addClause(QueryClause.createBatchedInClause(field, values, sqlType));
    }

    /**
     * Creates a clause in the form of: (field LIKE ? OR field LIKE ?)
     * Only takes strings, automatically sets the type to VARCHAR
     * @param field
     * @param values the data to be injected into the prepared statement
     * @param useInIfPossible if this is set, it will check all values for %,
     * if none are found an IN statement will be used instead
     * @throws java.lang.Exception
     */
    public void addInLikeClause(String field, Collection<String> values, boolean useInIfPossible) throws Exception {
        addClause(QueryClause.createInLikeClause(field, values, useInIfPossible));
    }

    /**
     * Adds a clause in the form of: field IN (?,?,?)
     * @param field the name of the field, including table identifier if needed
     * @param values the data to be injected into the prepared statement
     * @param sqlType the java.sql.Type of the field
     * @throws java.lang.Exception
     *
     * @see java.sql.Types
     */
    public void addNotInClause(String field, Collection<?> values, int sqlType) throws Exception {
        addClause(QueryClause.createNotInClause(field, values, sqlType));
    }

     /**
     * Adds a custom clause
     *
     * @param clause full text of a clause with a single ? for a value
     * @param value the data to be injected into the prepared statement
     * @param sqlType the java.sql.Type of the field
     * @throws java.lang.Exception if you do not specify one and only one ?
     *
     * @see java.sql.Types
     */
    public void addClause(String clause, Object value, int sqlType) throws Exception {
        addClause(QueryClause.createClause(clause, value, sqlType));
    }

    /**
     * Adds a custom clause
     * Uses the JDBC Standard mapping to determine the SQL Type
     *
     * @param clause full text of a clause with a single ? for a value
     * @param value the data to be injected into the prepared statement
     * @throws java.lang.Exception if you do not specify one and only one ?
     *
     * @see java.sql.Types
     */
    public void addClause(String clause, Object value) throws Exception {
        addClause(QueryClause.createClause(clause, value));
    }

    /**
     * Adds a clause in the form of: field=?
     *
     * @param fieldName the name of the field
     * @param value the data to be injected into the prepared statement
     * @param sqlType the java.sql.Type of the field
     * @throws java.lang.Exception
     *
     * @see java.sql.Types
     */
    public void addFieldClause(String fieldName, Object value, int sqlType) throws Exception {
        addClause(QueryClause.createFieldClause(fieldName, value, sqlType));
    }

    /**
     * Adds a clause in the form of: field=?
     * Uses the JDBC Standard mapping to determine the SQL Type
     *
     * @param fieldName the name of the field
     * @param value the data to be injected into the prepared statement
     * @throws java.lang.Exception
     */
    public void addFieldClause(String fieldName, Object value) throws Exception {
        addClause(QueryClause.createFieldClause(fieldName, value));
    }

    /**
     * Adds a clause that does not contain any ?, such as "t.visible"
     * @param clause textual representation of a clause
     * @throws java.lang.Exception if you specify a ?
     */
    public void addNoParamClause(String clause) throws Exception {
        int param = clause.indexOf('?');
        if (param!=-1) {
            throw new Exception("Must NOT specify a ? param!");
        }
        addClause(QueryClause.createNoParamClause(clause));
    }

    /**
     * Adds a externally created clause
     * @param clause the QueryClause to be added to the statement
     * @throws Exception if there are any issues adding clauses,
     * such as more than one batched clause
     */
    public void addClause(QueryClause clause) throws Exception {
        if (clause.isBatched()) {
            if (hasBatch) {
                throw new Exception("Query already has a batched clause!");
            }
            hasBatch = true;
        }
        clauses.add(clause);
    }

    /**
     * Adds a collection of externally created clauses
     * @param clauses the QueryClauses to be added to the statement
     * @throws Exception if there are any issues adding clauses,
     * such as more than one batched clause
     */
    public void addClauses(Collection<QueryClause> clauses) throws Exception {
        for (QueryClause clause : clauses) {
            addClause(clause);
        }
    }

    /**
     * Executes the internal query using a PreparedStatement
     *

     * Upon completion of processing the results, closeAll() must be called
     * in order to cleanup the connection.
     * @return the ResultSet of the query execution
     * @throws Exception any SQL exceptions will get bubbled up
     */
    public ResultSet execute() throws Exception {
        String query = getQuery();
        jdbc = factory.newService(query);
        PreparedStatement ps = jdbc.getPreparedStatement();
        int i = 1;
        for (QueryClause f : clauses) {
            if (f.hasParam()) {
                if (f.isList()) {
                    for (Object value : f.getValuesList()) {
                        if (f.getSqlType() != Types.OTHER) {
                            ps.setObject(i++, value, f.getSqlType());
                        } else {
                            ps.setObject(i++, value);
                        }
                    }
                } else {
                    if (f.getSqlType() != Types.OTHER) {
                        ps.setObject(i++, f.getValue(), f.getSqlType());
                    } else {
                        ps.setObject(i++, f.getValue());
                    }
                }
            }
        }
        return jdbc.executeQuery();
    }

    /**
     * Executes the query in batches, if applicable.  The processor is used to
     * convert the ResultSet into objects, stored in the results collection.
     *
     * The closeAll is called automatically after execution
     *
     * @param <K> type of key in result map
     * @param <V> type of value in result map
     * @param processor the processor used to convert the ResultSet into objects
     * @return a Map created to store the results
     * @throws Exception any SQL exceptions will get bubbled up
     */
    public <K,V> Map<K,V> execute(ResultMapper<K,V> processor) throws Exception {
        Map<K,V> results = new HashMap<>();
        execute(processor, results);
        return results;
    }

    /**
     * Executes the query in batches, if applicable.  The processor is used to
     * convert the ResultSet into objects, stored in the results collection.
     *
     * The closeAll is called automatically after execution
     *
     * @param <K> type of key in result map
     * @param <V> type of value in result map
     * @param processor the processor used to convert the ResultSet into objects
     * @param results the Map to store results of processing the data
     * @throws Exception any SQL exceptions will get bubbled up
     */
    public <K,V> void execute(ResultMapper<K,V> processor, Map<K,V> results) throws Exception {
        int batch = 0;
        String query;
        while ((query = getBatchedQuery(batch)) != null) {
            try {
                processor.processResults(executeBatch(query,batch), results);
                batch++;
            } finally {
                close();
            }
        }
    }

    /**
     * Executes the query in batches, if applicable.  The processor is used to
     * convert the ResultSet into objects, stored in the results collection.
     *
     * The closeAll is called automatically after execution
     *
     * @param <T> type of results
     * @param processor the processor used to convert the ResultSet into objects
     * @return a List created to store the results
     * @throws Exception any SQL exceptions will get bubbled up
     */
    public <T> List<T> execute(ResultProcessor<T> processor) throws Exception {
        List<T> results = new ArrayList<>();
        execute(processor, results);
        return results;
    }

    /**
     * Executes the query in batches, if applicable.  The processor is used to
     * convert the ResultSet into objects, stored in the results collection.
     *
     * The closeAll is called automatically after execution
     *
     * @param <T> type of results
     * @param processor the processor used to convert the ResultSet into objects
     * @param results the List to store results of processing the data
     * @throws Exception any SQL exceptions will get bubbled up
     */
    public <T> void execute(ResultProcessor<T> processor, Collection<T> results) throws Exception {
        int batch = 0;
        String query;
        while ((query = getBatchedQuery(batch)) != null) {
            try {
                processor.processResults(executeBatch(query,batch), results);
                batch++;
            } finally {
                close();
            }
        }
    }

    private ResultSet executeBatch(String query, int batch) throws Exception {
        jdbc = factory.newService(query);
        PreparedStatement ps = jdbc.getPreparedStatement();
        int i = 1;
        for (QueryClause f : clauses) {
            if (f.hasParam()) {
                if (f.isBatched() || f.isList()) {
                    Collection<?> values = f.isBatched()
                            ? f.getValuesForBatch(batch) : f.getValuesList();
                    for (Object value : values) {
                        if (f.getSqlType() != Types.OTHER) {
                            ps.setObject(i++, value, f.getSqlType());
                        } else {
                            ps.setObject(i++, value);
                        }
                    }
                } else {
                    if (f.getSqlType() != Types.OTHER) {
                        ps.setObject(i++, f.getValue(), f.getSqlType());
                    } else {
                        ps.setObject(i++, f.getValue());
                    }
                }
            }
        }
        return jdbc.executeQuery();
    }

    /**
     * Cleans up the internal JDBC Connection, must be called after execute()
     */
    @Override
    public void close() throws IOException {
        if (jdbc != null) jdbc.close();
        jdbc = null;
    }

}


text:
using System.Web.Mvc;
using autofac110.mvc.Models;
using autofac110.shared.HelloWorld;

namespace autofac110.mvc.Controllers
{
    public class HelloController : Controller
    {
        // GET: Hello
        public ActionResult Index()
        {
            return View(new HelloModel
            {
	            Message = "Hello World!"
            });
        }
    }
}


text:
from __future__ import (absolute_import, division, print_function)
from qtpy.QtWidgets import (QFileDialog)

from addie.utilities.file_handler import FileHandler
from addie.menu.preview_ascii.preview_ascii_window import PreviewAsciiWindow

class Step3GuiHandler(object):

    def __init__(self, parent=None):
        self.parent_no_ui = parent
        self.parent = parent.ui
        self.current_folder = parent.current_folder

    def browse_file(self):
        _ascii_file = QFileDialog.getOpenFileName(parent=self.parent_no_ui,
                                                  caption='Select file to display',
                                                  directory=self.current_folder)
        if not _ascii_file:
            return
        if isinstance(_ascii_file, tuple):
            _ascii_file = _ascii_file[0]
        _ascii_file = str(_ascii_file)

        o_file_handler = FileHandler(filename=_ascii_file)
        o_file_handler.retrieve_contain()
        text_contain = o_file_handler.file_contain

        o_preview = PreviewAsciiWindow(parent=self.parent_no_ui, text=text_contain, filename=_ascii_file)
        o_preview.show()


text:
package cn.taop.simpleweb;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

import cn.taop.simpleweb.core.DefaultWebContext;

/**
 * WebContext上下文容器的生产工厂,WebContext实例必须通过工厂获得
 *
 * @author duduwolf
 */
public class WebContextFactory {

	public static WebContext get() {
		return (WebContext) user.get();
	}

	public static void set(HttpServletRequest request, HttpServletResponse response, ServletConfig config, ServletContext context) {
		try {
			WebContext wc = new DefaultWebContext(request, response, config, context);
			user.set(wc);
		} catch (Exception e) {
			log.error("严重错误,错误原因为:{}", e.getMessage());
		}
	}

	public void unset() {
		user.set(null);
	}

	private static ThreadLocal<WebContext> user = new ThreadLocal<WebContext>();
	private static final Logger log = LoggerFactory.getLogger(WebContextFactory.class);
}


text:
//
// Copyright (c) 2014 Limit Point Systems, Inc.
//
// 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 tools.SheafScope;

import bindings.java.*;
import tools.common.gui.*;

import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

/**
 * SheafScopePosetTablePane specializes the JPanel class to
 * meet the needs of the SheafScope.

 */
public class SheafScopePosetTablePane extends SheafScopeAbstractTablePane
{
  /**
   * Constructor
   *
   * @param xposetPane The SheafScopePosetPane for the table.
   * @param xmember The abstract_poset_member to traverse.
   */
  public SheafScopePosetTablePane(SheafScopePosetPane xposetPane,
                                  abstract_poset_member xmember)
  {
    super(xposetPane, xmember);
  }

  /**
   * Instantiates a new object of class SheafScopeJTable
   * with a instance of SheafScopePosetTableModel as model.

   *
   *
   */
  protected void makeTable()
  {
    tableModel = new SheafScopePosetTableModel(member);

    table = new SheafScopeJTable(tableModel);

    // Get the currently selected node.

    SheafScopeTreeNode focusNode = getFocusPane().getSelectedNode();

    // Get an enumeration over the node's children.

    Enumeration itr = focusNode.preorderEnumeration();

    // Refresh the table.

    tableModel.refresh(itr, selectedName);

    // Set some of the table attributes.

    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setRowSelectionAllowed(true);
    table.getSelectionModel()
    .addListSelectionListener(new SheafScopePosetTableSelectionListener(posetPane));

    table.setDefaultRenderer(table.getColumnClass(0),
                             new SheafScopeTableCellRenderer());

    setColumnSizes();
  }
}


text:
<?php

namespace adm\BlogBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="blog_post")
 */
class Post {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=false, unique=true) */
    private $title;

    /**
     * @ORM\Column(type="text", nullable=false) */
    private $body;

    /**
     * @ORM\ManyToMany(targetEntity="Tag", cascade={"persist"})
     * @ORM\JoinTable(name="blog_post_tag",
     * joinColumns={@ORM\JoinColumn(name="post_id", referencedColumnName="id", onDelete="CASCADE")},
     * inverseJoinColumns={@ORM\JoinColumn(name="tag_id", referencedColumnName="id", onDelete="CASCADE")})
     */
    private $tags;

    /** @ORM\OneToMany(targetEntity="Comment", mappedBy="post") */
    private $comentarios;

    /**
     * @ORM\Column(type="datetime", nullable=false) */
    private $dateAdd;

    function getId() {
        return $this->id;
    }

    function getTitle() {
        return $this->title;
    }

    function getBody() {
        return $this->body;
    }

    function getTags() {
        return $this->tags;
    }

    function getFcAdd() {
        return $this->fcAdd;
    }

    function setId($id) {
        $this->id = $id;
    }

    function setTitle($title) {
        $this->title = $title;
    }

    function setBody($body) {
        $this->body = $body;
    }

    function setTags($tags) {
        $this->tags = $tags;
    }

    function setFcAdd($fcAdd) {
        $this->fcAdd = $fcAdd;
    }

}


text:
int main(void)
{
	QString jsonText("{"
	" \"name\": \"Johnny\","
	" \"middlename\": \"B.\","
	" \"surname\": \"Goode\","
	" \"city\": \"New Orleans\""
	"}");

	QJsonParseError jsonErr;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(
		jsonText.toUtf8(),
		&jsonErr
	);

	if(jsonErr.error != QJsonParseError::NoError) {
		qDebug() << jsonErr.errorString();
		return 1;
	}

	QJsonObject jsonObj = jsonDoc.object();

	qDebug() << "name:" << jsonObj["name"].toString();
	qDebug() << "surname:" << jsonObj["surname"].toString();
	qDebug() << "city:" << jsonObj["city"].toString();

	return 0;
}


text:
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { DrawerHeader }  from '../../components/Drawer';
import { setDialogIsOpen } from '../../store/dialogs/actions';

DrawerHeader.propTypes = {
  auth: PropTypes.object,
};

const mapStateToProps = (state) => {
  const { auth, theme, locale, dialogs} = state;

  return {
    auth,
    theme,
    locale,
    dialogs
  };
};

export default connect(
  mapStateToProps,
  { setDialogIsOpen }
)(DrawerHeader);


text:
package tuwien.inso.mnsa.smssender.translator;

public class MappingException extends Exception {
	private static final long serialVersionUID = -1580509601402379906L;

	public MappingException(String message) {
		super(message);
	}
}


text:
require 'nokogiri'
require 'loofah'

module Fl::Framework::Core
  # Helper methods for HTML processing.

  module HtmlHelper
    # @!visibility private

    class AdjustURLs < Loofah::Scrubber
      def initialize
        super
      end

      def scrub(node)
        if (node.type == Nokogiri::XML::Node::ELEMENT_NODE) && (node.name == 'a')
          node['href'] = '#' unless (node['href'] =~ /^https?:/i) || (node['href'] =~ /^\//)
        elsif (node.type == Nokogiri::XML::Node::ELEMENT_NODE) && (node.name == 'img')
          node['src'] = '' unless (node['src'] =~ /^https?:/i) || (node['src'] =~ /^\//)
        end
      end
    end

    # Strip dangerous elements from HTML content.
    # This method parses the value and:
    #
    # - Removes any element that do not appear in the HTML5lib whitelist.
    # - Converts any urls in <a> to #, unless they use the HTTP/HTTPS scheme.
    # - Converts any urls in <img> to an empty string, unless they use the HTTP/HTTPS scheme.
    #
    # @param value [String] The initial value.
    #
    # @return [String] Returns the value, where all dangerous elements have been stripped as described above.

    def self.strip_dangerous_elements(value)
      if value.nil? || (value.length < 1)
        value
      else
        Loofah.fragment(value).scrub!(:prune).scrub!(AdjustURLs.new).to_s
      end
    end

    # Extract text from HTML content.
    # This method parses the value and concatenates the values of the text nodes.
    #
    # @param value [String] The initial value.
    # @param [Number] maxlen The maximum number of characters to extract. Defaults to all characters.
    #
    # @return [String] Returns the value, where all HTML tags have been stripped (well, technically,
    #  where all text nodes have been concatenated).

    def self.text_only(value, maxlen = nil)
      if value.nil? || (value.length < 1)
        value
      else
        # we add a wrapper <fl-root> element so that the code fragment is valid XML; otherwise,
        # Nokogiri puts everything inside a <p> element.
        # and we return the contents of the fl-root element.

        doc = Nokogiri::HTML("<fl-root>#{value}</fl-root>")
        b = doc.search('body fl-root')
        s = ''
        b[0].search('text()').each do |e|
          break if maxlen.is_a?(Numeric) && (s.length >= maxlen)
          s << e.serialize
        end

        # one last tweak: convert &, >, and < back to the actual characters

        s = convert_character_entities(s)

        (maxlen.is_a?(Numeric) && (s.length > maxlen)) ? s[0,maxlen] : s
      end
    end

    # Convert (some) XML/HTML character entities to text.
    # This method converts +&+, +>+, and +<+ back to the characters +&+, +>+, and +<+.
    #
    # @param t [String] The text to convert.
    #
    # @return [String] Returns a string where the character entities +&+, +>+, and +&lt+; have been
    #  converted back to characters.

    def self.convert_character_entities(t)
      t.gsub('&', '&').gsub('<', '<').gsub('>', '>')
    end
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Egan, Bryologist 90(2): 164 (1987)

#### Original name
Rinodina marysvillensis var. thujae H. Magn.

### Remarks
null


text:
struct module_state {
    PyObject *error;
};

#if PY_MAJOR_VERSION >= 3
#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
#define GETSTATE(m) (&_state)
static struct module_state _state;
#endif

static PyObject *
error_out(PyObject *m) {
    struct module_state *st = GETSTATE(m);
    PyErr_SetString(st->error, "something bad happened");
    return NULL;
}

Py_buffer *get_new_buffer(int nitems, int itemsize, char *fmt) {
    Py_buffer *buf = (Py_buffer *) malloc(sizeof(*buf));
    buf->obj = NULL;
    buf->buf = PyMem_Malloc(nitems * itemsize);
    buf->len = nitems * itemsize;
    buf->readonly = 0;
    buf->itemsize = itemsize;
    buf->format = fmt;
    buf->ndim = 1;
    buf->shape = NULL;
    buf->strides = NULL;
    buf->suboffsets = NULL;
    buf->internal = NULL;
    return buf;
}

static PyObject *
intersect_lists_extension(PyObject *m, PyObject *args) {
    PyObject* list;
    if (!PyArg_ParseTuple(args, "O", &list))
        return NULL;
    Py_INCREF(list);

    if (!PyList_Check(list)) {
        PyErr_SetString(PyExc_TypeError, "arg must be list");
        return NULL;
    }

    int i, min_len;
    Py_ssize_t lists_len;
    lists_len = PyList_Size(list);
    int **my_arrays = (int **)PyMem_Malloc(lists_len * sizeof(Py_ssize_t));
    if (my_arrays == NULL)
        return PyErr_NoMemory();

    int *pointers = (int *)PyMem_Malloc(lists_len * sizeof(Py_ssize_t));
    if (pointers == NULL)
        return PyErr_NoMemory();

    int *list_lens = (int *)PyMem_Malloc(lists_len * sizeof(Py_ssize_t));
    if (list_lens == NULL)
        return PyErr_NoMemory();

    for (i = 0; i < lists_len; i++) {
        PyObject *array = PyList_GetItem(list, i);
#if PY_MAJOR_VERSION >= 3
        Py_buffer array_buffer;
        if (PyObject_CheckBuffer(array)) {
            PyObject_GetBuffer(array, &array_buffer, PyBUF_SIMPLE);
        } else {
            PyErr_SetString(PyExc_TypeError,
                "list elements have to support the buffer protocol");
            return NULL;
        }

        int *array_ptr = array_buffer.buf;
        int array_len = array_buffer.len / array_buffer.itemsize;
#else
        PyObject *buffer_info = PyObject_CallMethod(array, "buffer_info", NULL);
        int *array_ptr = NULL, array_len;
        PyArg_ParseTuple(buffer_info, "li", &array_ptr, &array_len);
#endif
        pointers[i] = 0;
        if (array_len > 0) {
            my_arrays[i] = array_ptr;
            list_lens[i] = array_len;
            if (i == 0 || array_len < min_len)
                min_len = array_len;
        } else {
            PyMem_Free(my_arrays);
            PyMem_Free(pointers);
            PyMem_Free(list_lens);
#if PY_MAJOR_VERSION >= 3
            Py_buffer *intersection_buffer = get_new_buffer(0, sizeof(int), "d");
            return PyMemoryView_FromBuffer(intersection_buffer);
#else
            return PyList_New(0);
#endif
        }
    }

    int intersection_idx = 0;
#if PY_MAJOR_VERSION >= 3
    Py_buffer *intersection_buffer = get_new_buffer(min_len, sizeof(int), "i");
    int *intersection = intersection_buffer->buf;
#else
    PyObject *intersection = PyList_New(0);
#endif

    int min_val = -1, min_idx = -1, tmp_val = -1, all_same;

    int counter = 0;
    int not_finished = 1;
    while(not_finished) {
        all_same = 1;
        for (i = 0; i < lists_len; i++) {
            tmp_val = my_arrays[i][pointers[i]];
            if (i > 0) {
                if (tmp_val < min_val) {
                    min_val = tmp_val;
                    min_idx = i;
                    all_same = 0;
                } else {
                    if (tmp_val > min_val)
                        all_same = 0;
                }
            } else {
                min_val = tmp_val;
                min_idx = i;
            }
        }
        if (all_same == 1) {
#if PY_MAJOR_VERSION >= 3
            intersection[intersection_idx] = min_val;
#else
            PyObject *item = PyInt_FromLong(min_val);
            PyList_Append(intersection, item);
            Py_DECREF(item);
#endif
            intersection_idx++;
            for (i = 0; i < lists_len; i++) {
                pointers[i]++;
                if (pointers[i] >= list_lens[i]) {
                    not_finished = 0;
                }
            }
        } else {
            pointers[min_idx]++;
            if (pointers[min_idx] >= list_lens[min_idx]) {
                not_finished = 0;
            }
        }
        counter++;
    }

    PyMem_Free(my_arrays);
    PyMem_Free(pointers);
    PyMem_Free(list_lens);
#if PY_MAJOR_VERSION >= 3
    long nbytes = intersection_idx * intersection_buffer->itemsize;
    //PyMem_Realloc(intersection_buffer->buf, nbytes);
    intersection_buffer->len = nbytes;
    return PyMemoryView_FromBuffer(intersection_buffer);
#else
    return intersection;
#endif
}

static PyMethodDef posting_lists_extension_methods[] = {
    {"error_out", (PyCFunction)error_out, METH_NOARGS, NULL},
    {"intersect_lists_extension", (PyCFunction)intersect_lists_extension,
     METH_VARARGS, "Return intersection of lists"},
    {NULL, NULL}
};

#if PY_MAJOR_VERSION >= 3

static int posting_lists_extension_traverse(PyObject *m, visitproc visit, void *arg) {
    Py_VISIT(GETSTATE(m)->error);
    return 0;
}

static int posting_lists_extension_clear(PyObject *m) {
    Py_CLEAR(GETSTATE(m)->error);
    return 0;
}

static struct PyModuleDef moduledef = {
        PyModuleDef_HEAD_INIT,
        "posting_lists_extension",
        NULL,
        sizeof(struct module_state),
        posting_lists_extension_methods,
        NULL,
        posting_lists_extension_traverse,
        posting_lists_extension_clear,
        NULL
};

#define INITERROR return NULL

PyObject *
PyInit_posting_lists_extension(void)

#else
#define INITERROR return

void
initposting_lists_extension(void)
#endif
{
#if PY_MAJOR_VERSION >= 3
    PyObject *module = PyModule_Create(&moduledef);
#else
    PyObject *module = Py_InitModule("posting_lists_extension", posting_lists_extension_methods);
#endif

    if (module == NULL)
        INITERROR;
    struct module_state *st = GETSTATE(module);

    st->error = PyErr_NewException("posting_lists_extension.Error", NULL, NULL);
    if (st->error == NULL) {
        Py_DECREF(module);
        INITERROR;
    }

#if PY_MAJOR_VERSION >= 3
    return module;
#endif
}


text:
@interface ViewController ()
@property (strong, nonatomic) UILabel *label;
@property (strong, nonatomic) UIActivityIndicatorView *indicator;
@property (assign, nonatomic) NSUInteger index;
@end

@implementation ViewController

- (id)initWithIndex:(NSUInteger)index
{
    if (self = [super init])
    {
        _index = index;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"ViewController:%ld Load",_index);
    [self.view setBackgroundColor:[UIColor colorWithRed:(_index<=2) green:(_index<=1) blue:(_index==0) alpha:1]];
    _label = [[UILabel alloc]initWithFrame:CGRectMake(40, 30, 100, 30)];
    [_label setText:@"Loading..."];
    [_label setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:_label];
    _indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [_indicator setFrame:CGRectMake(10, 30, 30, 30)];
    [self.view addSubview:_indicator];
    [_indicator startAnimating];
    [_indicator setBackgroundColor:[UIColor clearColor]];

    for (int i=0;i<3;i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal];
        [button.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
        if (i==_index) [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [button setFrame:CGRectMake(20+i*60, 100, 60, 20)];
        [button setTag:i];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }

    [self performSelectorInBackground:@selector(loadData) withObject:nil];
}

- (void)loadData
{
    sleep(4);
    [_label setText:@"Finished!"];
    [_indicator stopAnimating];
}

- (void)btnClick:(UIButton*)sender
{
    SASwipePageViewController *swipePageViewController = (SASwipePageViewController*)self.parentViewController;
    [swipePageViewController scrollToPageAtIndex:sender.tag animation:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end


text:
package io.qameta.allure.cucumberjvm.samples;

import cucumber.api.Scenario;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;

public class AttachmentSteps
{
    private Scenario scenario;

    @Before("@attachments")
    public void setup(Scenario scenario)
    {
        this.scenario = scenario;
    }

    @Given("step with scenario write")
    public void stepWithScenarioWrite()
    {
        scenario.write("text attachment");
    }

    @Given("step with scenario embed")
    public void stepWithScenarioEmbed()
    {
        scenario.embed("image attachment".getBytes(), "image/png");
    }
}


text:
I have some amazing photos on my computer that I would like to display using my old projector. But my PC uses HDMI and my projector uses VGA.

# Problem

HDMI and VGA are not compatible interfaces. HDMI can handle images and sound through a digital signal whereas VGA can only handle images through an analog signal.

# Solution

Adapter is a well-known solution in this kind of situation. We need:

  * Abstract representations (generally interfaces) of the problem. Here we easily see that a digital interface is not compatible with an analog one.
  * Concrete implementations of these abstractions: e.g. HDMIToVGAAdapter & VGA. Here the adapter should be able to delegate some work to the adapted entity.

![Adapter (classic)](Adapter.png)


text:
/*
Passes a context menu template to the main process (where the menu is created)
and listens for click events on it.
*/

var menuCallbacks = {}

var nextMenuId = 0

function open (menuTemplate, x, y) {
  nextMenuId++
  menuCallbacks[nextMenuId] = {}
  var nextItemId = 0
  function prepareToSend (menuPart) {
    if (menuPart instanceof Array) {
      return menuPart.map(item => prepareToSend(item))
    } else {
      if (menuPart.submenu) {
        menuPart.submenu = prepareToSend(menuPart.submenu)
      }
      if (typeof menuPart.click === 'function') {
        menuCallbacks[nextMenuId][nextItemId] = menuPart.click
        menuPart.click = nextItemId
        nextItemId++
      }
      return menuPart
    }
  }

  ipc.send('open-context-menu', {
    id: nextMenuId,
    template: prepareToSend(menuTemplate),
    x,
    y
  })
}

ipc.on('context-menu-item-selected', function (e, data) {
  menuCallbacks[data.menuId][data.itemId]()
})

ipc.on('context-menu-will-close', function (e, data) {
  // delay close event until after selected event has been received
  setTimeout(function () {
    delete menuCallbacks[data.menuId]
  }, 16)
})

module.exports = { open }


text:
import {Map, fromJS} from 'immutable';

// Initial state
const initialState = Map({
  isLoggedIn: false,
  currentUser: null,
  authenticationToken: null
});

// Actions
const USER_LOGIN_SUCCESS = 'AppState/USER_LOGIN_SUCCESS';
const USER_LOGIN_ERROR = 'AppState/USER_LOGIN_ERROR';

export function onUserLoginSuccess(profile, token) {
  return {
    type: USER_LOGIN_SUCCESS
    /*
    payload: {
      profile: fromJS(profile),
      token: fromJS(token)
    }
    */
  };
}

export function onUserLoginError(error) {
  return {
    type: USER_LOGIN_ERROR
    /*,
    payload: error,
    error: true
    */
  };
}

// Reducer
export default function AuthStateReducer(state = initialState, action = {}) {
  switch (action.type) {
    case USER_LOGIN_SUCCESS:
      return state
        .set('isLoggedIn', true);
        //.set('currentUser', action.payload.profile)
        //.set('authenticationToken', action.payload.token);
    case USER_LOGIN_ERROR:
      return initialState;
    default:
      return state;
  }
}


text:
import hashlib
import hmac
import logging
try:
    from urllib.parse import parse_qs, urlencode, urljoin, urlunparse
except ImportError:
    from urllib import urlencode
    from urlparse import parse_qs, urljoin, urlunparse

from django.core.urlresolvers import reverse
from django.conf import settings
import requests

GOOGLE, FACEBOOK = 'google', 'facebook'
JSON_MIME_TYPE = 'application/json'
logger = logging.getLogger('saleor.registration')

def get_local_host(request):
    scheme = 'http' + ('s' if request.is_secure() else '')
    return url(scheme=scheme, host=request.get_host())

def url(scheme='', host='', path='', params='', query='', fragment=''):
    return urlunparse((scheme, host, path, params, query, fragment))

def get_client_class_for_service(service):
    return {GOOGLE: GoogleClient, FACEBOOK: FacebookClient}[service]

def get_google_login_url(local_host):
    if settings.GOOGLE_CLIENT_ID:
        client_class = get_client_class_for_service(GOOGLE)(local_host)
        return client_class.get_login_uri()

def get_facebook_login_url(local_host):
    print('In get facebook function')
    print(settings.FACEBOOK_APP_ID)
    if settings.FACEBOOK_APP_ID:

        client_class = get_client_class_for_service(FACEBOOK)(local_host)
        return client_class.get_login_uri()

def parse_response(response):
    if JSON_MIME_TYPE in response.headers['Content-Type']:
        return response.json()
    else:
        content = parse_qs(response.text)
        content = dict((x, y[0] if len(y) == 1 else y)
                       for x, y in content.items())
        return content

class OAuth2RequestAuthorizer(requests.auth.AuthBase):

    def __init__(self, access_token):
        self.access_token = access_token

    def __call__(self, request):
        request.headers['Authorization'] = 'Bearer %s' % (self.access_token,)
        return request

class OAuth2Client(object):

    service = None

    client_id = None
    client_secret = None

    auth_uri = None
    token_uri = None
    user_info_uri = None

    scope = None

    def __init__(self, local_host, code=None,
                 client_id=None, client_secret=None):
        self.local_host = local_host

        if client_id and client_secret:
            self.client_id = client_id
            self.client_secret = client_secret

        if code:
            access_token = self.get_access_token(code)
            self.authorizer = OAuth2RequestAuthorizer(
                access_token=access_token)
        else:
            self.authorizer = None

    def get_redirect_uri(self):
        kwargs = {'service': self.service}
        path = reverse('registration:oauth_callback', kwargs=kwargs)
        return urljoin(self.local_host, path)

    def get_login_uri(self):
        data = {'response_type': 'code',
                'scope': self.scope,
                'redirect_uri': self.get_redirect_uri(),
                'client_id': self.client_id}
        query = urlencode(data)
        return urljoin(self.auth_uri, url(query=query))

    def get_access_token(self, code):
        data = {'grant_type': 'authorization_code',
                'client_id': self.client_id,
                'client_secret': self.client_secret,
                'code': code,
                'redirect_uri': self.get_redirect_uri(),
                'scope': self.scope}
        response = self.post(self.token_uri, data=data, authorize=False)
        return response['access_token']

    def get_user_info(self):
        return self.get(self.user_info_uri)

    def get_request_params(self, data=None, authorize=True):
        auth = self.authorizer if authorize else None
        return data, auth

    def get(self, address, params=None, authorize=True):
        params, auth = self.get_request_params(params, authorize)
        response = requests.get(address, params=params, auth=auth)
        return self.handle_response(response)

    def post(self, address, data=None, authorize=True):
        data, auth = self.get_request_params(data, authorize)
        response = requests.post(address, data=data, auth=auth)
        return self.handle_response(response)

    def handle_response(self, response):
        response_content = parse_response(response)
        if response.status_code == requests.codes.ok:
            return response_content
        else:
            logger.error('[%s]: %s', response.status_code, response.text)
            error = self.extract_error_from_response(response_content)
            raise ValueError(error)

    def extract_error_from_response(self, response_content):
        raise NotImplementedError()

class GoogleClient(OAuth2Client):

    service = GOOGLE

    auth_uri = 'https://accounts.google.com/o/oauth2/auth'
    token_uri = 'https://accounts.google.com/o/oauth2/token'
    user_info_uri = 'https://www.googleapis.com/oauth2/v1/userinfo'

    scope = ' '.join(['https://www.googleapis.com/auth/userinfo.email',
                      'https://www.googleapis.com/auth/plus.me'])

    def __init__(self, *args, **kwargs):
        if not self.client_id and not self.client_secret:
            self.client_id = settings.GOOGLE_CLIENT_ID
            self.client_secret = settings.GOOGLE_CLIENT_SECRET
        super(GoogleClient, self).__init__(*args, **kwargs)

    def get_user_info(self):
        response = super(GoogleClient, self).get_user_info()
        if response.get('verified_email'):
            return response
        else:
            raise ValueError('Google account not verified.')

    def extract_error_from_response(self, response_content):
        return response_content['error']

class FacebookClient(OAuth2Client):

    service = FACEBOOK

    auth_uri = 'https://www.facebook.com/dialog/oauth'
    token_uri = 'https://graph.facebook.com/oauth/access_token'
    user_info_uri = 'https://graph.facebook.com/me?fields=name,email,verified'

    scope = ','.join(['email'])

    def __init__(self, *args, **kwargs):
        if not self.client_id and not self.client_secret:
            self.client_id = settings.FACEBOOK_APP_ID
            self.client_secret = settings.FACEBOOK_SECRET
        super(FacebookClient, self).__init__(*args, **kwargs)

    def get_request_params(self, data=None, authorize=True):
        data = data or {}
        if authorize:
            data.update({'appsecret_proof': hmac.new(
                settings.FACEBOOK_SECRET.encode('utf8'),
                msg=self.authorizer.access_token.encode('utf8'),
                digestmod=hashlib.sha256).hexdigest()})
        return super(FacebookClient, self).get_request_params(data, authorize)

    def get_user_info(self):
        response = super(FacebookClient, self).get_user_info()
        if not response.get('verified'):
            raise ValueError('Facebook account not verified.')
        if not response.get('email'):
            raise ValueError('Access to your email address is required.')
        return response

    def extract_error_from_response(self, response_content):
        return response_content['error']['message']


text:
Recipes
       New recipe

      <input type="text" ng-model="search.name" class="form-control" placeholder="Search...">

        <button type="button" class="btn btn-default" ng-click="hideAdvSearch=!hideAdvSearch">Advanced Search </button>

Author

                    <input type="text" class="form-control" ng-model="search.author.fullname" ng-disabled="search.author._id" placeholder="Author...">

                      <input type="checkbox" ng-model="search.author._id" ng-true-value="'{{user._id}}'" ng-false-value="undefined" ng-change="disableAndClearAuthor()">Show only my own recipes

Tags

                      <input type="checkbox" ng-model="tagfilter[tag.text]">{{tag.text}} ({{tag.count}})

	      				{{recipe.author.fullname}}

{{recipe.name}}

          	<button type="button" class="btn btn-link" ng-click="switchFavorite(recipe)"></button>

    		  	<button type="button" class="btn btn-link margin-top-10" ui-sref=".scheduleadd({recipe: recipe})"></button>


text:
package org.zv.fintrack.pd;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.GenerationType;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.SqlResultSetMapping;
/*
import javax.persistence.EntityResult;
import javax.persistence.FieldResult;
*/
import javax.persistence.ColumnResult;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * Income entity.
 *
 * @author arvid.juskaitis
 */
@SuppressWarnings("serial")
@Entity
@Table(schema = "public", name = "incomes")
@SequenceGenerator(name = "INCOME_SEQ", sequenceName = "income_seq", allocationSize = 10)
@SqlResultSetMapping(name = "incomeSummarySimpleResults",
	columns = {
		@ColumnResult(name = "count"),
		@ColumnResult(name = "amount")
	}
/*	entities = {
		@EntityResult(entityClass = org.zv.fintrack.pd.bean.IncomeSummaryBean.class, fields = {
	        @FieldResult(name = "count", column = "count"),
	        @FieldResult(name = "amount", column = "amount")
		})
	} */
)
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(namespace="http://fintrack.zv.org/rest")
public class Income implements Serializable {
	private final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

	@Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "INCOME_SEQ")
	@Column(name = "income_id")
    private	Integer		incomeId;

	@Column(name = "user_id")
	private String		userId;

	@Column(name = "create_date")
	private	Date		createDate;

	private float		amount;

	private String		descr;

	@XmlElement(name="incomeId")
	public Integer getIncomeId() {
		return incomeId;
	}

	public void setIncomeId(Integer incomeId) {
		this.incomeId = incomeId;
	}

	@XmlElement(name="userId")
	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		if (userId == null) {
			userId = "none";
		}
		this.userId = userId;
	}

	public Date getCreateDate() {
		return createDate;
	}

	@XmlElement(name="createDate")
	public String getCreateDateAsString() {
        return (createDate != null) ? simpleDateFormat.format(createDate) : null;
    }

	public void setCreateDate(Date createDate) {
		this.createDate = createDate;
	}

	@XmlElement(name="amount")
	public float getAmount() {
		return amount;
	}

	public void setAmount(float amount) {
		this.amount = amount;
	}

	@XmlElement(name="descr")
	public String getDescr() {
		return descr;
	}

	public void setDescr(String descr) {
		this.descr = descr;
	}

	public String toString() {
		return incomeId + ", " + userId + ", " + createDate + ", " + amount + ", " + descr;
	}
}


text:
package net.akehurst.app.dotEditor.application.web.vertx.angular;

import net.akehurst.application.framework.realisation.ApplicationFramework;

public class DotEditorVertxAngularMain {

	public static void main(String[] args) {
		ApplicationFramework.start(DotEditorVertxAngularApplication.class, args);
	}

}


text:
import { GraphQLError } from 'graphql';
import { always } from 'ramda';

import { loginRequired, checkUserIsAuthorOrThrow } from './permissions';

describe('loginRequired()', () => {
  it("should throw if user isn't logged in", () => {
    const resolver = jest.fn();
    const loginRequiredTest = loginRequired(resolver);
    const ctx = { user: null };
    expect(() => loginRequiredTest(null, null, ctx)).toThrow(GraphQLError);
  });

  it('should call the resolver if the user is logged in', () => {
    const resolver = jest.fn();
    const loginRequiredTest = loginRequired(resolver);
    const ctx = { user: { firstName: 'test' } };
    const args = [null, null, ctx, null];
    loginRequiredTest(...args);

    expect(resolver).toHaveBeenCalledWith(...args);
  });
});

describe('checkUserIsAuthorOrThrow()', () => {
  it('should throw if the user is not the author of the document', () => {
    const userId = 'user_id';
    const doc = { author: { equals: jest.fn(always(false)) } };
    const args = { doc, userId };
    expect(() => checkUserIsAuthorOrThrow(args)).toThrow(GraphQLError);
  });

  it('should not throw if the user is the author of the document', () => {
    const userId = 'user_id';
    const doc = { author: { equals: jest.fn(always(true)) } };
    const args = { doc, userId };
    expect(() => checkUserIsAuthorOrThrow(args)).not.toThrow(GraphQLError);
  });
});


text:
**Note:  This documentation is for FAKE.exe before version 5 (or the non-netcore version). The documentation needs te be updated, please help! **

Starting with version `4.0.0` of FAKE, the first time a script is run the
compiled assembly that is generated is saved into the hidden `.fake` directory. This
allows FAKE to start in milliseconds instead of seconds. Your script files are
cached with a crc32 key generated from the first scripts contents, and then each
`#load`ed scripts contents. This prevents you from having to manually clear the
cache whenever you are working on your script or pulling in changes from a
remote repository. If for some reason you would like to disable saving the
compiled assembly to disk, you can call FAKE with the `--nocache` argument,
which stops FAKE from dumping the compiled assembly to disk. Do note that the
assembly is still being compiled by FSI, all you are disabling is the saving
to disk.

You should add the `.fake` folder to your `.gitignore` file.


text:
using System.Linq;
using Diadoc.Api.Proto.Events;

namespace Diadoc.Console.Command
{
	class ListEventsCommand : ConsoleCommandBase
	{
		public ListEventsCommand(ConsoleContext consoleContext, string command = "list")
			: base(consoleContext, command, CommandType.AuthenticationRequired)
		{
			Usage = "[ <afterEventId> ]";
			Description = "List events";
		}

		protected override void PerformRunCommand(string[] args)
		{
			var afterEventId = args.Length > 0 ? args[0] : null;

			var eventIdCurrent = afterEventId;
			do
			{
				ConsoleContext.Events = ConsoleContext.DiadocApi.GetNewEvents(ConsoleContext.CurrentToken, ConsoleContext.CurrentBoxId, eventIdCurrent);
				foreach (var boxEvent in ConsoleContext.Events.Events)
				{
					System.Console.Write("{0} {1} {2}", boxEvent.Timestamp, boxEvent.EventId, boxEvent.MessageId);
					if (boxEvent.Message != null)
						System.Console.WriteLine(" [{0} -> {1}]", boxEvent.Message.FromTitle, boxEvent.Message.ToTitle);
					else
						System.Console.WriteLine();
					var attachments = boxEvent.Entities
						.Where(e => e.EntityType == EntityType.Attachment && e.AttachmentType != AttachmentType.AttachmentComment);
					foreach (var attach in attachments)
						System.Console.WriteLine("\t{0} [{1}]", attach.FileName, attach.AttachmentType);
				}

				if (ConsoleContext.Events.TotalCount <= ConsoleContext.Events.Events.Count) break;
				eventIdCurrent = ConsoleContext.Events.Events.Last().EventId;
			} while (InputHelpers.YesNoChoice(false, "...Есть ещё письма... Показать следующую страницу?"));
		}
	}
}


text:
package net.zwj.bili.model;

public class JsonVideo {
	private String aid;
	private String title;
	private String play;
	private String review;
	private String video_review;
	private String favorites;
	private String mid;
	private String author;
	private String description;
	private String create;
	private String pic;
	private String coins;
	private String duration;

	public String getAid() {
		return aid;
	}

	public void setAid(String aid) {
		this.aid = aid;
	}

	public String getTitle() {
		return title;
	}

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

	public String getPlay() {
		return play;
	}

	public void setPlay(String play) {
		this.play = play;
	}

	public String getReview() {
		return review;
	}

	public void setReview(String review) {
		this.review = review;
	}

	public String getVideo_review() {
		return video_review;
	}

	public void setVideo_review(String video_review) {
		this.video_review = video_review;
	}

	public String getFavorites() {
		return favorites;
	}

	public void setFavorites(String favorites) {
		this.favorites = favorites;
	}

	public String getMid() {
		return mid;
	}

	public void setMid(String mid) {
		this.mid = mid;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getDescription() {
		return description;
	}

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

	public String getCreate() {
		return create;
	}

	public void setCreate(String create) {
		this.create = create;
	}

	public String getPic() {
		return pic;
	}

	public void setPic(String pic) {
		this.pic = pic;
	}

	public String getCoins() {
		return coins;
	}

	public void setCoins(String coins) {
		this.coins = coins;
	}

	public String getDuration() {
		return duration;
	}

	public void setDuration(String duration) {
		this.duration = duration;
	}
}


text:
<!DOCTYPE html>

Tests paint invalidation when a skewed element is resized. Passes if there is no red.


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link href="{{ asset('/css/app.css') }}" rel="stylesheet">

    <!-- Fonts -->
    <link href='//fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
@yield('content')

<!-- Scripts -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/js/bootstrap.min.js"></script>
@yield('js')
</body>
</html>


text:
package alexwilton.handwritingAssistant;

import com.myscript.cloud.sample.ws.api.*;
import com.myscript.cloud.sample.ws.api.Stroke;

import java.util.*;

/**
 * Stroke Analyser takes strokes from the canvas, divides them into stroke words (potential words) and analyses each
 * stroke group separately. The analysis results are then sent to the current exercise which determines how to
 * appropriately display feedback to the learner.
 */
public class StrokeAnalyser {
    private ExerciseManager exerciseManager;
    private MyScriptConnection myScriptConnection;
    private Canvas canvas;

    /**
     * Maximum allowed distance in pixels between strokes in order than a collection of
     * strokes is considered a stroke group for analysing as a word.
     */
    private int wordSeparatingDistance = 35;

    public StrokeAnalyser(ExerciseManager exerciseManager, MyScriptConnection myScriptConnection) {
        this.exerciseManager = exerciseManager;
        this.myScriptConnection = myScriptConnection;
    }

    /**
     * Strokes are extracted from the canvas. They are then divided them into stroke words (potential words) and each
     * stroke group are analysed separately. The analysis results are then sent to the current exercise which
     * determines how to appropriately display feedback to the learner.
     * @param recordFailedWordAttempts Should failed word attempts be recorded.
     */
    public void analyseStrokes(final boolean recordFailedWordAttempts){
        final List<Word> recognisedWords = new ArrayList<>();
        ArrayList<ArrayList<Stroke>> strokeSetList = divideStrokesIntoWords();
        for(ArrayList<Stroke> wordStrokes : strokeSetList){
            Stroke[] sArray = wordStrokes.toArray(new Stroke[wordStrokes.size()]);
            try {
                myScriptConnection.recognizeStrokes(sArray, new MyScriptConnection.MessageHandler() {
                    private Stroke[] strokesToAnalyse;
                    @Override
                    public void handleMessage(String recognisedTextFromMyscript) {
                        recognisedWords.add(extractWordFromStrokes(strokesToAnalyse, recognisedTextFromMyscript));
                        canvas.repaint();
                    }

                    private MyScriptConnection.MessageHandler init(Stroke[] strokeToAnalyse){
                        this.strokesToAnalyse = strokeToAnalyse;
                        return this;
                    }
                }.init(sArray));

            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("Couldn't recognise strokes. Exception: " + e.getClass().getSimpleName() + " Message: " + e.getMessage());
            }
        }
        if(strokeSetList.size() > 0) myScriptConnection.waitUntilFinished();
        exerciseManager.getCurrentExercise().generateFeedback(recognisedWords, StrokeAnalyser.this, recordFailedWordAttempts);
        canvas.repaint();
    }

    /**
     * Divide strokes into stroke groups. Any stroke which is less than the 'wordSeparatingDistance' to another stroke
     * are in the same stroke group. A stroke group is represented by a List of Strokes.
     * @return A List of Stroke groups.
     */
    private ArrayList<ArrayList<Stroke>> divideStrokesIntoWords(){
        Stroke[] strokes = canvas.getStrokes().toArray(new Stroke[canvas.getStrokes().size()]);
        ArrayList<ArrayList<Stroke>> strokeGroups = new ArrayList<>();
        for(Stroke stroke : strokes){
            ArrayList<Stroke> closetStrokeGroup = null;
            double closetStrokeDist = Double.MAX_VALUE;
            for(ArrayList<Stroke> sGroup : strokeGroups){
                for(Stroke s : sGroup){
                    double dist = minDistanceBetweenStrokes(stroke, s);
                    if(dist < closetStrokeDist){
                        closetStrokeDist = dist;
                        closetStrokeGroup = sGroup;
                    }
                }
            }
            if(closetStrokeDist > wordSeparatingDistance){
                ArrayList<Stroke> newGroup = new ArrayList<>();
                newGroup.add(stroke);
                strokeGroups.add(newGroup);
            }else{
                if(closetStrokeGroup == null){
                    closetStrokeGroup = new ArrayList<>();
                    strokeGroups.add(closetStrokeGroup);
                }
                closetStrokeGroup.add(stroke);
            }
        }
        return strokeGroups;
    }

    /**
     * Calculate minimum distance between two strokes.
     * @param s1 First Stroke.
     * @param s2 Second Stroke.
     * @return Minimum distance between the two strokes.
     */
    private double minDistanceBetweenStrokes(Stroke s1, Stroke s2){
        double minDistance  = Double.MAX_VALUE;
        for(Point pt1 : s1.getPoints()){
            for(Point pt2 : s2.getPoints()){
                double dist = Math.hypot(pt1.x - pt2.x, pt1.y - pt2.y);
                if(dist < minDistance) minDistance = dist;
            }
        }
        return minDistance;
    }

    /**
     * Construct a word object which comprises of its strokes and the recognised text from MyScript for the strokes.
     * @param strokes Strokes.
     * @param text Recognised text from MyScript for the strokes.
     * @return Word.
     */
    private Word extractWordFromStrokes(Stroke[] strokes, String text) {
        int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, maxX = 0, maxY = 0;
        for(Stroke stroke : strokes){
            Box box = stroke.getBoundingBox();
            if(box.x < minX) minX = box.x;
            if(box.y < minY) minY = box.y;
            if(box.x + box.width > maxX) maxX = box.x + box.width;
            if(box.y + box.height > maxY) maxY = box.y + box.height;
        }
        return new Word(minX, minY, maxX-minX, maxY-minY, text);
    }

    public void setCanvas(Canvas canvas) {
        this.canvas = canvas;
    }

    public int getWordSeparatingDistance() {
        return wordSeparatingDistance;
    }

    public void setWordSeparatingDistance(int wordSeparatingDistance) {
        this.wordSeparatingDistance = wordSeparatingDistance;
    }
}