text:
import * as React from 'react'
import * as Kb from '../../../../../common-adapters'
import * as Styles from '../../../../../styles'
import {formatTimeForPopup, formatTimeForRevoked, msToDHMS} from '../../../../../util/timestamp'
import {addTicker, removeTicker, type TickerID} from '../../../../../util/second-timer'
import {type DeviceType} from '../../../../../constants/types/devices'

const headerIconType = Styles.isMobile ? 'icon-fancy-bomb-mobile-226-96' : 'icon-fancy-bomb-desktop-150-72'
const headerIconHeight = Styles.isMobile ? 96 : 72

type Props = {
  attachTo?: () => React.Component<any> | null
  author: string
  botUsername?: string
  deviceName: string
  deviceRevokedAt?: number
  deviceType: DeviceType
  explodesAt: number
  hideTimer: boolean
  items: Kb.MenuItems
  onHidden: () => void
  position: Styles.Position
  style?: Styles.StylesCrossPlatform
  timestamp: number
  visible: boolean
  yourMessage: boolean
}

type State = {
  secondsLeft: number
}

class ExplodingPopupHeader extends React.Component<Props, State> {
  timer?: TickerID
  state = {
    secondsLeft: this.secondsLeft(),
  }

  componentDidMount() {
    if (!__STORYBOOK__) {
      this.timer = addTicker(this.tick)
    }
  }

  componentWillUnmount() {
    this.timer && removeTicker(this.timer)
  }

  secondsLeft() {
    const now = __STORYBOOK__ ? 1999999999000 : Date.now()
    let secondsLeft = Math.floor((this.props.explodesAt - now) / 1000)
    if (secondsLeft < 0) {
      // TODO remove if we end up w/ an "exploded" popup
      this.props.onHidden()
      secondsLeft = 0
    }
    return secondsLeft
  }

  tick = () => {
    this.setState({secondsLeft: this.secondsLeft()})
  }

  render() {
    const {author, botUsername, deviceName, deviceRevokedAt, hideTimer, timestamp, yourMessage} = this.props
    const whoRevoked = yourMessage ? 'You' : author
    return (
      <Kb.Box2 direction="vertical" fullWidth={true} style={styles.popupContainer}>
        <Kb.Icon style={styles.headerIcon} type={headerIconType} />
        <Kb.Box2 direction="vertical" style={styles.messageInfoContainer}>
          <Kb.Box2 direction="vertical">
            <Kb.Text type="BodySmall" style={{color: Styles.globalColors.black}}>
              EXPLODING MESSAGE
            </Kb.Text>
          </Kb.Box2>
          <Kb.Box2 direction="horizontal">
            <Kb.Text type="BodySmall">by</Kb.Text>
            <Kb.Box2 direction="horizontal" gap="xtiny" gapStart={true} style={styles.user}>
              <Kb.Avatar username={author} size={16} onClick="profile" />
              <Kb.ConnectedUsernames
                onUsernameClicked="profile"
                colorFollowing={true}
                colorYou={true}
                usernames={author}
                underline={true}
                type="BodySmallBold"
              />
            </Kb.Box2>
          </Kb.Box2>
          <Kb.Box2 direction="horizontal">
            <Kb.Text center={true} type="BodySmall">
              from device {deviceName}
            </Kb.Text>
          </Kb.Box2>
          {botUsername && (
            <Kb.Box2 direction="horizontal">
              <Kb.Text type="BodySmall">also encrypted for</Kb.Text>
              <Kb.Box2 direction="horizontal" gap="xtiny" gapStart={true} style={{alignItems: 'center'}}>
                <Kb.Avatar username={botUsername} size={16} onClick="profile" />
                <Kb.ConnectedUsernames
                  onUsernameClicked="profile"
                  colorFollowing={true}
                  colorYou={true}
                  usernames={botUsername}
                  underline={true}
                  type="BodySmallBold"
                />
              </Kb.Box2>
            </Kb.Box2>
          )}
          <Kb.Box2 direction="horizontal">
            <Kb.Text center={true} type="BodySmall">
              using exploding key
            </Kb.Text>
          </Kb.Box2>
          <Kb.Box2 direction="horizontal">
            <Kb.Text center={true} type="BodySmall">
              {formatTimeForPopup(timestamp)}
            </Kb.Text>
          </Kb.Box2>
        </Kb.Box2>
        {!!deviceRevokedAt && (
          <Kb.PopupHeaderText
            color={Styles.globalColors.white}
            backgroundColor={Styles.globalColors.blue}
            style={styles.revokedAt}
          >
            {whoRevoked} revoked this device on {formatTimeForRevoked(deviceRevokedAt)}.
          </Kb.PopupHeaderText>
        )}
        <Kb.Box2
          direction="vertical"
          gap="xsmall"
          fullWidth={true}
          gapEnd={true}
          gapStart={true}
          style={Styles.collapseStyles([
            styles.timerBox,
            {
              backgroundColor:
                this.state.secondsLeft < oneMinuteInS ? Styles.globalColors.red : Styles.globalColors.black,
            },
          ])}
        >
          {hideTimer ? (
            <Kb.ProgressIndicator white={true} style={{height: 17, width: 17}} />
          ) : (
            <Kb.Box2 direction="horizontal" gap="tiny" gapStart={true} gapEnd={true}>
              <Kb.Icon
                type="iconfont-timer"
                fontSize={Styles.isMobile ? 20 : 16}
                color={Styles.globalColors.white}
              />
              <Kb.Text style={{alignSelf: 'center', color: Styles.globalColors.white}} type="BodySemibold">
                {msToDHMS(this.props.explodesAt - Date.now())}
              </Kb.Text>
            </Kb.Box2>
          )}
        </Kb.Box2>
      </Kb.Box2>
    )
  }
}

const ExplodingPopupMenu = (props: Props) => {
  const header = <ExplodingPopupHeader {...props} />

  return (
    <Kb.FloatingMenu
      attachTo={props.attachTo}
      closeOnSelect={true}
      header={header}
      items={props.items}
      onHidden={props.onHidden}
      position={props.position}
      positionFallbacks={[]}
      containerStyle={props.style}
      visible={props.visible}
    />
  )
}

const oneMinuteInS = 60

const styles = Styles.styleSheetCreate(
  () =>
    ({
      headerIcon: {
        height: headerIconHeight,
        marginBottom: Styles.globalMargins.small,
        marginTop: Styles.globalMargins.small,
      },
      messageInfoContainer: {
        paddingLeft: Styles.globalMargins.small,
        paddingRight: Styles.globalMargins.small,
      },
      popupContainer: Styles.platformStyles({
        common: {
          alignItems: 'center',
        },
        isElectron: {
          maxWidth: 240,
          minWidth: 200,
        },
      }),
      revokedAt: {
        borderBottomLeftRadius: 3,
        borderBottomRightRadius: 3,
        marginBottom: -Styles.globalMargins.small,
        marginTop: Styles.globalMargins.small,
        minHeight: 40,
        width: '100%',
      },
      timerBox: Styles.platformStyles({
        common: {
          alignItems: 'center',
          justifyContent: 'center',
          marginTop: Styles.globalMargins.tiny,
        },
        isMobile: {
          height: 46,
        },
      }),
      user: {
        alignItems: 'center',
      },
    } as const)
)

export default ExplodingPopupMenu


text:
namespace GPUCA_NAMESPACE::gpu
{

static const char* opencl_error_string(int errorcode)
{
  switch (errorcode) {
    case CL_SUCCESS:
      return "Success!";
    case CL_DEVICE_NOT_FOUND:
      return "Device not found.";
    case CL_DEVICE_NOT_AVAILABLE:
      return "Device not available";
    case CL_COMPILER_NOT_AVAILABLE:
      return "Compiler not available";
    case CL_MEM_OBJECT_ALLOCATION_FAILURE:
      return "Memory object allocation failure";
    case CL_OUT_OF_RESOURCES:
      return "Out of resources";
    case CL_OUT_OF_HOST_MEMORY:
      return "Out of host memory";
    case CL_PROFILING_INFO_NOT_AVAILABLE:
      return "Profiling information not available";
    case CL_MEM_COPY_OVERLAP:
      return "Memory copy overlap";
    case CL_IMAGE_FORMAT_MISMATCH:
      return "Image format mismatch";
    case CL_IMAGE_FORMAT_NOT_SUPPORTED:
      return "Image format not supported";
    case CL_BUILD_PROGRAM_FAILURE:
      return "Program build failure";
    case CL_MAP_FAILURE:
      return "Map failure";
    case CL_INVALID_VALUE:
      return "Invalid value";
    case CL_INVALID_DEVICE_TYPE:
      return "Invalid device type";
    case CL_INVALID_PLATFORM:
      return "Invalid platform";
    case CL_INVALID_DEVICE:
      return "Invalid device";
    case CL_INVALID_CONTEXT:
      return "Invalid context";
    case CL_INVALID_QUEUE_PROPERTIES:
      return "Invalid queue properties";
    case CL_INVALID_COMMAND_QUEUE:
      return "Invalid command queue";
    case CL_INVALID_HOST_PTR:
      return "Invalid host pointer";
    case CL_INVALID_MEM_OBJECT:
      return "Invalid memory object";
    case CL_INVALID_IMAGE_FORMAT_DESCRIPTOR:
      return "Invalid image format descriptor";
    case CL_INVALID_IMAGE_SIZE:
      return "Invalid image size";
    case CL_INVALID_SAMPLER:
      return "Invalid sampler";
    case CL_INVALID_BINARY:
      return "Invalid binary";
    case CL_INVALID_BUILD_OPTIONS:
      return "Invalid build options";
    case CL_INVALID_PROGRAM:
      return "Invalid program";
    case CL_INVALID_PROGRAM_EXECUTABLE:
      return "Invalid program executable";
    case CL_INVALID_KERNEL_NAME:
      return "Invalid kernel name";
    case CL_INVALID_KERNEL_DEFINITION:
      return "Invalid kernel definition";
    case CL_INVALID_KERNEL:
      return "Invalid kernel";
    case CL_INVALID_ARG_INDEX:
      return "Invalid argument index";
    case CL_INVALID_ARG_VALUE:
      return "Invalid argument value";
    case CL_INVALID_ARG_SIZE:
      return "Invalid argument size";
    case CL_INVALID_KERNEL_ARGS:
      return "Invalid kernel arguments";
    case CL_INVALID_WORK_DIMENSION:
      return "Invalid work dimension";
    case CL_INVALID_WORK_GROUP_SIZE:
      return "Invalid work group size";
    case CL_INVALID_WORK_ITEM_SIZE:
      return "Invalid work item size";
    case CL_INVALID_GLOBAL_OFFSET:
      return "Invalid global offset";
    case CL_INVALID_EVENT_WAIT_LIST:
      return "Invalid event wait list";
    case CL_INVALID_EVENT:
      return "Invalid event";
    case CL_INVALID_OPERATION:
      return "Invalid operation";
    case CL_INVALID_GL_OBJECT:
      return "Invalid OpenGL object";
    case CL_INVALID_BUFFER_SIZE:
      return "Invalid buffer size";
    case CL_INVALID_MIP_LEVEL:
      return "Invalid mip-map level";
    default:
      return "Unknown Errorcode";
  }
}

#define GPUFailedMsg(x) GPUFailedMsgA(x, __FILE__, __LINE__)
#define GPUFailedMsgI(x) GPUFailedMsgAI(x, __FILE__, __LINE__)

static int GPUFailedMsgAI(int error, const char* file, int line)
{
  // Check for OPENCL Error and in the case of an error display the corresponding error string
  if (error == CL_SUCCESS) {
    return (0);
  }
  GPUError("OCL Error: %d / %s (%s:%d)", error, opencl_error_string(error), file, line);
  return 1;
}

static void GPUFailedMsgA(const long long int error, const char* file, int line)
{
  if (GPUFailedMsgAI(error, file, line)) {
    throw std::runtime_error("OpenCL Failure");
  }
}

static inline int OCLsetKernelParameters_helper(cl_kernel& k, int i) { return 0; }

template <typename T, typename... Args>
static inline int OCLsetKernelParameters_helper(cl_kernel& kernel, int i, const T& firstParameter, const Args&... restOfParameters)
{
  GPUFailedMsg(clSetKernelArg(kernel, i, sizeof(T), &firstParameter));
  return OCLsetKernelParameters_helper(kernel, i + 1, restOfParameters...);
}

template <typename... Args>
static inline int OCLsetKernelParameters(cl_kernel& kernel, const Args&... args)
{
  return OCLsetKernelParameters_helper(kernel, 0, args...);
}

static inline int clExecuteKernelA(cl_command_queue queue, cl_kernel krnl, size_t local_size, size_t global_size, cl_event* pEvent, cl_event* wait = nullptr, cl_int nWaitEvents = 1)
{
  GPUFailedMsg(clEnqueueNDRangeKernel(queue, krnl, 1, nullptr, &global_size, &local_size, wait == nullptr ? 0 : nWaitEvents, wait, pEvent));
  return 0;
}

struct GPUReconstructionOCLInternals {
  cl_platform_id platform;
  cl_device_id device;
  std::unique_ptr<cl_platform_id[]> platforms;
  std::unique_ptr<cl_device_id[]> devices;
  cl_context context;
  cl_command_queue command_queue[GPUCA_MAX_STREAMS];
  cl_mem mem_gpu;
  cl_mem mem_constant;
  cl_mem mem_host;
  cl_program program;

  std::vector<std::pair<cl_kernel, std::string>> kernels;
};

template <typename K, typename... Args>
int GPUReconstructionOCL::runKernelBackendCommon(krnlSetup& _xyz, K& k, const Args&... args)
{
  auto& x = _xyz.x;
  auto& y = _xyz.y;
  auto& z = _xyz.z;
  if (y.num <= 1) {
    if (OCLsetKernelParameters(k, mInternals->mem_gpu, mInternals->mem_constant, y.start, args...)) {
      return 1;
    }
  } else {
    if (OCLsetKernelParameters(k, mInternals->mem_gpu, mInternals->mem_constant, y.start, y.num, args...)) {
      return 1;
    }
  }

  cl_event ev;
  cl_event* evr;
  bool tmpEvent = false;
  if (z.ev == nullptr && mProcessingSettings.deviceTimers && mProcessingSettings.debugLevel > 0) {
    evr = &ev;
    tmpEvent = true;
  } else {
    evr = (cl_event*)z.ev;
  }
  int retVal = clExecuteKernelA(mInternals->command_queue[x.stream], k, x.nThreads, x.nThreads * x.nBlocks, evr, (cl_event*)z.evList, z.nEvents);
  if (mProcessingSettings.deviceTimers && mProcessingSettings.debugLevel > 0) {
    cl_ulong time_start, time_end;
    GPUFailedMsg(clWaitForEvents(1, evr));
    GPUFailedMsg(clGetEventProfilingInfo(*evr, CL_PROFILING_COMMAND_START, sizeof(time_start), &time_start, nullptr));
    GPUFailedMsg(clGetEventProfilingInfo(*evr, CL_PROFILING_COMMAND_END, sizeof(time_end), &time_end, nullptr));
    _xyz.t = (time_end - time_start) * 1.e-9;
    if (tmpEvent) {
      GPUFailedMsg(clReleaseEvent(ev));
    }
  }
  return retVal;
}

template <class T, int I>
int GPUReconstructionOCL::AddKernel(bool multi)
{
  std::string name(GetKernelName<T, I>());
  if (multi) {
    name += "_multi";
  }
  std::string kname("krnl_" + name);

  cl_int ocl_error;
  cl_kernel krnl = clCreateKernel(mInternals->program, kname.c_str(), &ocl_error);
  if (GPUFailedMsgI(ocl_error)) {
    GPUError("Error creating OPENCL Kernel: %s", name.c_str());
    return 1;
  }
  mInternals->kernels.emplace_back(krnl, name);
  return 0;
}

template <class T, int I>
inline unsigned int GPUReconstructionOCL::FindKernel(int num)
{
  std::string name(GetKernelName<T, I>());
  if (num > 1) {
    name += "_multi";
  }

  for (unsigned int k = 0; k < mInternals->kernels.size(); k++) {
    if (mInternals->kernels[k].second == name) {
      return (k);
    }
  }
  GPUError("Could not find OpenCL kernel %s", name.c_str());
  throw ::std::runtime_error("Requested unsupported OpenCL kernel");
}

static_assert(std::is_convertible<cl_event, void*>::value, "OpenCL event type incompatible to deviceEvent");
} // namespace GPUCA_NAMESPACE::gpu

#endif

redpajama_set_name: RedPajamaGithub


text:
package com.manning.sdmia.dataaccess.domain.dao.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

import com.manning.sdmia.dataaccess.domain.model.Contact;

public class ContactRowMapper implements RowMapper {

	public Object mapRow(ResultSet rs, int i) throws SQLException {
		Contact contact = new Contact();
		contact.setId(rs.getInt("id"));
		contact.setLastName(rs.getString("last_name"));
		contact.setFirstName(rs.getString("first_name"));
		return contact;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:background="@color/colorPrimary"
        android:layout_margin="15dp"
        android:padding="15dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="10dp"
            android:textSize="15sp"
            android:textColor="@color/colorAccent"
            android:text="Fruit Fetcher" />

        <RelativeLayout
            android:layout_width="200dp"
            android:layout_height="180dp"
            android:layout_margin="10dp"
            android:background="@color/colorLightGrey">

            <ProgressBar
                android:id="@+id/fruit_busy_progbar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true" />

            <LinearLayout
                android:id="@+id/fruit_detailcontainer_linearlayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:gravity="center_horizontal"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/fruit_name_textview"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="fruit name"
                    android:padding="10dp"
                    android:textStyle="bold"
                    android:textSize="25sp"
                    android:textColor="@color/colorAccent" />

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:paddingLeft="10dp"
                    android:paddingRight="10dp">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="isCitrus"
                        android:layout_centerVertical="true"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentLeft="true"
                        android:textColor="@color/colorAccent"/>

                    <ImageView
                        android:id="@+id/fruit_citrus_img"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"/>

                </RelativeLayout>

                <foo.bar.example.foreretrofit.ui.widgets.AnimatedTastyRatingBar
                    android:id="@+id/fruit_tastyrating_tastybar"
                    android:layout_width="match_parent"
                    android:layout_height="3dp"
                    android:layout_marginTop="10dp"
                    android:layout_marginBottom="4dp"
                    android:background="@color/colorAccent"/>

                <TextView
                    android:id="@+id/fruit_tastyrating_textview"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="100% tasty"
                    android:textSize="12sp"
                    android:textColor="@color/colorAccent"/>

            </LinearLayout>

        </RelativeLayout>

        <Button
            android:id="@+id/fruit_fetchsuccess_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="fetch - (success result)" />

        <Button
            android:id="@+id/fruit_fetchfailbasic_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="fetch - (fail result basic)" />

        <Button
            android:id="@+id/fruit_fetchfailadvanced_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="fetch - (fail result advanced)" />

    </LinearLayout>

</ScrollView>


text:
Programming
	Alec "Aloshi" Lofquist - http://www.aloshi.com

UI Art & Design
	Nils Bonenberger

Libraries
=========

PugiXML
	http://pugixml.org/

SDL 2
	http://www.libsdl.org/

FreeImage
	http://www.freeimage.sourceforge.net

FreeType
	http://www.freetype.org

cURL
	http://curl.haxx.se/

nanosvg
	https://github.com/memononen/nanosvg

Resources
=========

Open Sans font
	http://www.google.com/fonts/specimen/Open+Sans


text:
class CreateCartitems < ActiveRecord::Migration[5.1]
  def change
    create_table :cartitems do |t|
      t.references :cart, foreign_key: true
      t.integer :product_id
      t.float :price
      t.integer :qty

      t.timestamps
    end
  end
end


text:
<?php

namespace CmsUser\Mapping\Traits;

trait BlameableTrait
{
    use CreatableTrait,
        UpdatableTrait,
        ChangeableTrait;
}


text:
{{define "title"}}{{end}}

{{define "body"}}

Service for doing "off-site" archive of all your communications on Slack teams. Main use-case is for getting Slack messages into Gmail's history, so that you can search it alongside your email.

<form id="sign-in-form" method="POST" action="{{routeUrl "sign-in"}}">
  <input type="hidden" name="continue_url" value="{{.ContinueUrl}}">
  <input type="submit" class="action-button" value="Sign In">
</form>

{{end}}


text:
package taskschedules

import (
	"github.com/google/kf/v2/pkg/kf/commands/config"
	"github.com/google/kf/v2/pkg/kf/internal/genericcli"
	"github.com/spf13/cobra"
)

// NewDeleteJobCommand allows users to delete TaskSchedules.
func NewDeleteJobCommand(p *config.KfParams) *cobra.Command {
	cmd := genericcli.NewDeleteByNameCommand(
		resourceInfo,
		p,
		genericcli.WithDeleteByNameCommandName("delete-job"),
		genericcli.WithDeleteByNameAdditionalLongText(`
		Note: Deleting the Job will delete all associated executions,
		even executions which are still running.
		`),
	)

	return cmd
}


text:
package net.canadensys.api.narwhal.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

import net.canadensys.api.narwhal.config.NarwhalConfiguration;
import net.canadensys.api.narwhal.model.DateAPIResponse;
import net.canadensys.api.narwhal.service.APIService;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Controller handling dates processing requests.
 * @author canadensys
 *
 */
@Controller
public class DateController {

	private static final Logger LOGGER = LoggerFactory.getLogger(DateController.class);

	//Own Jackson Object Mapper to add JSONP support
	public static final ObjectMapper JACKSON_MAPPER = new ObjectMapper();

	@Autowired
	private APIService apiService;

	/**
	 * Response to HEAD request with a HTTP_OK and no content, as defined by the standard.
	 * @param response
	 */
    @RequestMapping(value="/dates", method=RequestMethod.HEAD)
    public void healthCheckHead(HttpServletResponse response) {
        response.setContentLength(0);
        response.setStatus(HttpServletResponse.SC_OK);
    }

	/**
	 * Handle dates parsing for JSONP
	 * @param data
	 * @param callback
	 * @param response
	 * @return JSONP response
	 */
	@RequestMapping(value={"/dates.json"}, method=RequestMethod.GET, params="callback")
	public void handleJSONP(@RequestParam String data, @RequestParam String callback,
			 HttpServletRequest request, HttpServletResponse response){

		//make sure the answer is set as UTF-8
		response.setCharacterEncoding("UTF-8");
		response.setContentType(ControllerHelper.JSONP_CONTENT_TYPE);

		if(ControllerHelper.JSONP_ACCEPTED_CHAR_PATTERN.matcher(callback).matches()){
			//JSONP handling
			String json = "";
			DateAPIResponse apiResponse = null;
			List<String> dataList = new ArrayList<String>();
			List<String> idList = new ArrayList<String>();

			ControllerHelper.splitIdAndData(data, dataList, idList);
			apiResponse = apiService.processDates(dataList, idList);

			try {
				json = JACKSON_MAPPER.writeValueAsString(apiResponse);

				String responseTxt = callback + "("+json+");";
				response.getWriter().print(responseTxt);
				response.setContentLength(responseTxt.length());
				response.getWriter().close();

				LOGGER.info("Date(jsonp)|{}|{}|{}", request.getMethod(), request.getRequestURI(), request.getRemoteAddr());

			} catch (JsonProcessingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		else{
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		}
	}

	/**
	 * Handle dates parsing for all requests (except JSONP)
	 * @param data
	 * @param model
	 * @param request
	 * @param response
	 * @return view name
	 */
	@RequestMapping(value={"/dates"}, method={RequestMethod.GET,RequestMethod.POST}, params="!callback")
	public String handleDatesParsing(@RequestParam(required=false) String data,
			ModelMap model, HttpServletRequest request, HttpServletResponse response){

		// only include the page model for freemarker
		if(!StringUtils.endsWith(request.getRequestURI(), ".json") &&
				!StringUtils.endsWith(request.getRequestURI(), ".xml")) {
			model.addAttribute(NarwhalConfiguration.PAGE_ROOT_MODEL_KEY, ControllerHelper.createPageModel(request));
		}

		if(StringUtils.isBlank(data)){
			return "dates";
		}

		DateAPIResponse apiResponse = null;

		response.setCharacterEncoding("UTF-8");

		List<String> dataList = new ArrayList<>();
		List<String> idList = new ArrayList<>();

		ControllerHelper.splitIdAndData(data, dataList, idList);

		apiResponse = apiService.processDates(dataList, idList);
		apiResponse.setIdProvided(ControllerHelper.containsAtLeastOneNonBlank(idList));

		LOGGER.info("Date|{}|{}|{}", request.getMethod(), request.getRequestURI(), request.getRemoteAddr());
		model.addAttribute("data", apiResponse);
		return "dates-results";
	}
}


text:
package io.opentelemetry.maven;

import static org.assertj.core.api.Assertions.assertThat;

import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.logs.GlobalLoggerProvider;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.semconv.resource.attributes.ResourceAttributes;
import org.junit.jupiter.api.Test;

public class OpenTelemetrySdkServiceTest {

  /** Verify default `service.name` */
  @Test
  public void testDefaultConfiguration() {
    testConfiguration("maven");
  }

  /** Verify overwritten `service.name` */
  @Test
  public void testOverwrittenConfiguration() {
    System.setProperty("otel.service.name", "my-maven");
    try {
      testConfiguration("my-maven");
    } finally {
      System.clearProperty("otel.service.name");
    }
  }

  void testConfiguration(String expectedServiceName) {
    OpenTelemetrySdkService openTelemetrySdkService = new OpenTelemetrySdkService();
    openTelemetrySdkService.initialize();
    try {
      Resource resource = openTelemetrySdkService.autoConfiguredOpenTelemetrySdk.getResource();
      assertThat(resource.getAttribute(ResourceAttributes.SERVICE_NAME))
          .isEqualTo(expectedServiceName);
    } finally {
      openTelemetrySdkService.dispose();
      GlobalOpenTelemetry.resetForTest();
      GlobalLoggerProvider.resetForTest();
    }
  }
}


text:
using System;
using System.Globalization;
using System.IO;
using System.Text;

namespace Support.IO
{
    public static class IOUtils
    {
        /// <summary>
        /// Gets the translation path based on the input root
        /// </summary>
        /// <param name="sRootPath">The startint path</param>
        /// <param name="sDestinationPath">The destination path</param>
        /// <returns></returns>
        public static string GetRelativePath(string sRootPath, string sDestinationPath)
        {
            if (string.IsNullOrEmpty(sRootPath))
            {
                return sDestinationPath;
            }
            if (sDestinationPath.StartsWith(sRootPath)) // check if the destination is under the core
            {
                return sDestinationPath.Remove(0,
                    sRootPath.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture))
                        ? (sRootPath.Length)
                        : (sRootPath.Length + 1));
            }
            if (sRootPath[0] != sDestinationPath[0]) // check if the drive letter differs
            {
                return sDestinationPath;
            }

            var zBuilder = new StringBuilder();

            var arrayRoot = sRootPath.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            var arrayDest = sDestinationPath.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            var nMax = (arrayRoot.Length < arrayDest.Length) ? arrayRoot.Length : arrayDest.Length;
            int nIdx;
            for (nIdx = 0; nIdx < nMax; nIdx++)
            {
                if (!arrayRoot[nIdx].Equals(arrayDest[nIdx], StringComparison.CurrentCultureIgnoreCase))
                    break;
            }
            for (int nPrevDir = 0; nPrevDir < (arrayRoot.Length - (nIdx)); nPrevDir++)
            {
                zBuilder.Append(".." + Path.DirectorySeparatorChar);
            }
            for (int nSubDir = nIdx; nSubDir < arrayDest.Length; nSubDir++)
            {
                zBuilder.Append(arrayDest[nSubDir] + Path.DirectorySeparatorChar);
            }
            var sOutput = zBuilder.ToString();

            if (!sDestinationPath.EndsWith(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture)))
                sOutput = sOutput.Remove(sOutput.Length - 1);
            return sOutput;
        }

        /// <summary>
        /// Gets the fully qualified path of an item based on the root folder and input relative path
        /// </summary>
        /// <param name="sRootPath"></param>
        /// <param name="sRelativePath"></param>
        /// <returns></returns>
        public static string GetAbsolutePath(string sRootPath, string sRelativePath)
        {
            if (File.Exists(sRelativePath))
                return sRelativePath;

            var zBuilder = new StringBuilder();
            var arrayRoot = sRootPath.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            var arrayRelative = sRelativePath.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
            int nIdx;
            for (nIdx = 0; nIdx < arrayRelative.Length; nIdx++)
            {
                if (!arrayRelative[nIdx].Equals("..", StringComparison.CurrentCultureIgnoreCase))
                    break;
            }
            for (int nRootIdx = 0; nRootIdx < (arrayRoot.Length - nIdx); nRootIdx++)
            {
                zBuilder.Append(arrayRoot[nRootIdx] + Path.DirectorySeparatorChar);
            }

            // if the relative path started with a "..\" remove it
            int nStartIdx = sRelativePath.LastIndexOf("..");
            if (-1 != nStartIdx)
                nStartIdx += 3;
            else
                nStartIdx = 0;

            zBuilder.Append(sRelativePath.Substring(nStartIdx));
            return zBuilder.ToString();
        }

        /// <summary>
        /// Updates the relative path based on the old and new root folder.
        /// </summary>
        /// <param name="sOriginalRoot">The previous root folder</param>
        /// <param name="sRelativePath">The relative path of the item from the previous root</param>
        /// <param name="sNewRoot">The new root path</param>
        /// <returns></returns>
        public static string UpdateRelativePath(string sOriginalRoot, string sRelativePath, string sNewRoot)
        {
            string sAbsolutePath = GetAbsolutePath(sOriginalRoot, sRelativePath);
            return GetRelativePath(sNewRoot, sAbsolutePath);
        }
    }

}


text:
package ninja.lifecycle;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

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

import com.google.common.collect.Lists;
import com.google.inject.Singleton;

/**
 * Register of lifecycle classes
 *
 * @author James Roper
 */
@Singleton
class LifecycleRegister {
    private static final Logger log = LoggerFactory.getLogger(LifecycleRegister.class);
    private final List<Target> startables = Collections.synchronizedList(new ArrayList<Target>());
    private final List<Target> disposables = Collections.synchronizedList(new ArrayList<Target>());
    private final AtomicBoolean started = new AtomicBoolean(false);

    public void start() {
        if (started.get()) {
            throw new FailedStartException("Ninja service is already started!");
        }
        List<Target> toStart = new ArrayList<Target>(this.startables);
        started.set(true);
        startables.clear();
        // Sort the beans to start
        Collections.sort(toStart);
        // Start them
        for (Target target : toStart) {
            invokeTarget(target);
        }
    }

    public void stop() {
        if (!started.get()) {
            throw new FailedDisposeException("Ninja service is not started!");
        }
        List<Target> toDispose = new ArrayList<Target>(this.disposables);
        started.set(false);
        disposables.clear();
        // Sort the beans to dispose
        Collections.sort(toDispose);
        for (Target target : Lists.reverse(toDispose)) {
            try {
                invokeTarget(target);
            } catch (Exception e) {
                log.warn("Error stopping service", e);
            }
        }
    }

    public boolean isStarted() {
        return started.get();
    }

    public void registerStartable(Target target) {
        if (started.get()) {
            log.warn("Startable instantiated after the application has been started: " + target.getTarget().toString());
            invokeTarget(target);
        } else {
            startables.add(target);
        }
    }

    public void registerDisposable(Target target) {
        disposables.add(target);
    }

    public void invokeTarget(Target target) {
        try {
            target.getStartMethod().invoke(target.getTarget());
        } catch (IllegalAccessException e) {
            throw new FailedStartException(e);
        } catch (InvocationTargetException e) {
            if (e.getCause() instanceof FailedStartException) {
                throw (FailedStartException) e.getCause();
            } else {
                throw new FailedStartException(e.getCause());
            }
        }
    }
}


text:
/* ###
 * IP: GHIDRA
 *
 * 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 ghidra.pcode.exec.trace;

import ghidra.pcode.emu.PcodeMachine;
import ghidra.pcode.emu.PcodeThread;
import ghidra.pcode.exec.trace.data.*;
import ghidra.trace.model.guest.TracePlatform;

/**
 * A p-code machine which sources its state from a trace and can record back into it
 *
 * @param <T> the type of values manipulated by the machine
 */
public interface TracePcodeMachine<T> extends PcodeMachine<T> {

	/**
	 * Create a shared state
	 *
	 * @return the shared state
	 */
	TracePcodeExecutorState<T> createSharedState();

	/**
	 * Create a local state
	 *
	 * @param thread the thread whose state is being created
	 * @return the local state
	 */
	TracePcodeExecutorState<T> createLocalState(PcodeThread<T> thread);

	/**
	 * Write the accumulated emulator state via the given trace access shim
	 *
	 *

	 * NOTE: This method requires a transaction to have already been started on the
	 * destination trace. The destination threads must have equal names/paths at the given
	 * threadsSnap. When using scratch space, threadsSnap should be the source snap. If populating a
	 * new trace, threadsSnap should probably be the destination snap.
	 *
	 * @param into the destination trace-data access shim
	 */
	default void writeDown(PcodeTraceAccess into) {
		TracePcodeExecutorState<T> sharedState = (TracePcodeExecutorState<T>) getSharedState();
		sharedState.writeDown(into.getDataForSharedState());
		for (PcodeThread<T> emuThread : getAllThreads()) {
			PcodeTraceDataAccess localInto = into.getDataForLocalState(emuThread, 0);
			if (localInto == null) {
				throw new IllegalArgumentException(
					"Given trace does not have thread with name/path '" + emuThread.getName() +
						"' at source snap");
			}
			TracePcodeExecutorState<T> localState =
				(TracePcodeExecutorState<T>) emuThread.getState().getLocalState();
			localState.writeDown(localInto);
		}
	}

	/**
	 * @see #writeDown(PcodeTraceAccess)
	 * @param platform the platform whose trace to modify
	 * @param destSnap the destination snap within the trace
	 * @param threadsSnap the snap at which to find corresponding threads, usually the same as
	 *            {@link #getSnap()}
	 */
	default void writeDown(TracePlatform platform, long destSnap, long threadsSnap) {
		writeDown(new DefaultPcodeTraceAccess(platform, destSnap, threadsSnap));
	}
}


text:
using System;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;

internal static partial class Interop
{
    internal static partial class Winsock
    {
        [DllImport(Interop.Libraries.Ws2_32, ExactSpelling = true, SetLastError = true)]
        internal static extern void freeaddrinfo([In] IntPtr info);
    }
}


text:
var informacionPersonal = {
    // Application Constructor
    initialize: function() {
        $("#nombre").val(window.localStorage.getItem("nombre"));
        $("#email").val(window.localStorage.getItem("email"));
        $("#telefono").val(window.localStorage.getItem("telefono"));
    },

	guardar: function () {

		window.localStorage.setItem("nombre", $("#nombre").val());
		window.localStorage.setItem("email", $("#email").val());
		window.localStorage.setItem("telefono", $("#telefono").val());

		alert('Guardado!');

		window.location = 'empresas.html';
	}
};


text:
/*
This question is from https://leetcode.com/problems/binary-tree-level-order-traversal/
Difficulty: medium

Given a binary tree, return the level order traversal of its nodes' values.
(ie, from left to right, level by level).

For example:
Given binary tree {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal,
where '#' signifies a path terminator where no node exists below.

Here's an example:
   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

Time Complexity: O(N) , N: the elements in the tree
*/

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new LinkedList<List<Integer>>();
        if(root == null) return result;
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.add(root);
        while(!q.isEmpty()){
        	List<Integer> level = new LinkedList<Integer>();
        	int length = q.size();
        	for(int i = 0; i < length; i++){
        		TreeNode node = q.poll();
        		level.add(node.val);
        		if(node.left != null) q.add(node.left);
        		if(node.right != null) q.add(node.right);
        	}
        	result.add(level);
        }
        return result;
    }
}


text:
<?php

namespace App\UserBundle\Controller;

use App\CoreBundle\Controller\BaseController;
use App\StorageBundle\Entity\Image;
use App\UserBundle\Form\ImageType;
use App\UserBundle\Form\UserType;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use App\UserBundle\Entity\User;

/**
 * Profile controller.
 *
 * @Route("/")
 */
class ProfileController extends BaseController
{
    /**
     * Finds and displays a User entity.
     *
     * @Route("/pk{id}", name="profile.show")
     * @Method("GET")
     * @Template()
     */
    public function showAction(Request $request, $id)
    {
        if (null == $entity = $this->getDoctrine()->getManager()->getRepository('UserBundle:User')->find($id)) {
            return $this->redirect($this->generateUrl('profile.show', ['id'=>$this->getUser()->getId()]));
        }

        return array(
            'user' => $entity
        );
    }

    /**
     * Creates a form to edit a User entity.
     *
     * @param User $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createEditForm(User $entity)
    {
//        $image = new Image();
        $form = $this->createForm(
            new UserType(),
            $entity,
            array(
                'action' => $this->generateUrl('profile.edit'),
                'method' => 'PUT',
            )
        );

        $form->add('submit', 'submit', array('label' => 'action.edit'));

        return $form;
    }

    /**
     * Edits an existing User entity.
     *
     * @Route("/settings", name="profile.edit")
     * @Method({"GET", "POST", "PUT"})
     * @Template("UserBundle:Profile:edit.html.twig")
     */
    public function editAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        if (null == $entity = $this->getUser()) {
            return $this->redirect($this->generateUrl('fos_user_security_login'));
        }

        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        try {
            if (true == $request->isMethod("PUT")) {
                if (true == $editForm->isValid()) {

                    $this->getDoctrine()->getManager()->persist($entity);
                    $this->getDoctrine()->getManager()->flush();

                    $this->get('session')->getFlashBag()->add('success', 'form.save.success');

                    return $this->redirect($this->generateUrl('profile.edit', array('id' => $entity->getId())));
                } else {
                    $this->get('session')->getFlashBag()->set('warning', 'form.validate.error');
                }
            }
        } catch (\Exception $e) {
            $this->get('session')->getFlashBag()->set('danger', 'form.save.error');
        }

        return array (
            'entity' => $entity,
            'form' => $editForm->createView()
        );
    }

    /**
     *
     * @var Request $request
     * @Route("/profile_upload_image", name="profile_upload_image", options={"expose"=true})
     * @return Response
     */
    public function uploadImageAction(Request $request)
    {
        if (null == $image = $this->getUser()->getImage()) {
            $image = new Image();
            $image->setUser($this->getUser());
        }

        $em = $this->getDoctrine()->getManager();
        $imageForm = $this->createForm(new ImageType(), $image);

        if (true === $request->isXmlHttpRequest()) {
            $imageForm->handleRequest($request);
            $json = [];
            if ($imageForm->isValid()) {
                $em->persist($image);
                $em->flush();

                $json['status'] = 'success';
                $json['image'] = $this->container->get('templating.helper.assets')->getUrl($image->getWebPath());
            } else {

            }

            return new JsonResponse($json);
        }

        return new Response($this->get('templating')->render('@User/Profile/uploadImage.html.twig', [
            'form' => $imageForm->createView(),
            'image' => $image
        ]));
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Annales de la Société des Sciences Naturelles et d'Archéologie de Toulon et du Var 37(4): 234 (1985)

#### Original name
Coryneum dacicum Savul. & Hulea

### Remarks
null


text:
export default ({ source }, { jscodeshift: j }) => {
  const root = j(source)

  const classContextTypesHistory = root
    .find(j.ClassProperty, { key: { name: 'contextTypes' } })
    .find(j.Property, { key: { name: 'history' } })
  const constructorContextTypesHistory = root
    .find(
      j.AssignmentExpression, { left: { property: { name: 'contextTypes' } } }
    )
    .find(j.Property, { key: { name: 'history' } })
  const getContextTypesHistory = root
    .find(j.Property, { key: { name: 'getContextTypes' } })
    .find(j.Property, { key: { name: 'history' } })

  if (!(
    classContextTypesHistory.size() ||
    constructorContextTypesHistory.size() ||
    getContextTypesHistory.size())
  ) {
    return source
  }

  return root
    .find(j.Identifier, { name: 'history' })
    .replaceWith(() => j.identifier('router'))
    .toSource()
}


text:
@interface SLTitleViewWithViewController : SLViewController

@property (nonatomic,strong) UISlider * slider;

@end


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

namespace GoAhead.Core
{
    public interface IDocumentsManager
    {
        Document GetDocument(GetDocument documentInfo);
        IEnumerable<Reference> GetReferences(GetReferences referencesInfo);
    }
}


text:
//
//  BKPhotoItem.h
//  BKPhotoBrowser
//
//  Created by BestKai on 16/5/30.
//  Copyright © 2016年 BestKai. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface BKPhotoItem : NSObject

/**
 点击某个放大的View 可以不传
 */
@property (strong,nonatomic) UIView *thumbView;

/**
 图片原始链接
 */
@property (strong,nonatomic) NSURL *originImageUrl;

/**
 缩略图  (可以传placeHolder)
 */
@property (nonatomic, strong) UIImage *thumbImage;

@property (nonatomic, readonly) BOOL thumbClippedToTop;

@end


text:
package com.google.cloud.genomics.dataflow.readers.bam;

import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Collections;

import htsjdk.samtools.Chunk;

@RunWith(JUnit4.class)
public class ShardingPolicyTest {
  @Test
  public void testShardPolicyBytes() {
    BAMShard shard = new BAMShard("f","chr20",1);
    Chunk chunk = new Chunk(1,11L*1024L*1024L << 16);
    shard.addBin(Collections.singletonList(chunk),90000);
    Assert.assertTrue(
    		"Shard of size " + shard.approximateSizeInBytes() +
    		" is NOT big enough but it should be",
    		ShardingPolicy.BYTE_SIZE_POLICY.shardBigEnough(shard));

    shard = new BAMShard("f","chr20",1);
    chunk = new Chunk(1,1L*1024L*1024L << 16);
    shard.addBin(Collections.singletonList(chunk),90000);
    Assert.assertFalse(
    		"Shard of size " + shard.approximateSizeInBytes() +
    		" is big enough but it should NOT be",
    		ShardingPolicy.BYTE_SIZE_POLICY.shardBigEnough(shard));
  }

  @Test
  public void testShardPolicyLoci() {
    BAMShard shard = new BAMShard("f","chr20",1);
    Chunk chunk = new Chunk(1,9*1024*1024);
    shard.addBin(Collections.singletonList(chunk),110000);
    Assert.assertTrue(
    		"Shard of size " + shard.sizeInLoci() +
    		" is NOT big enough but it should be",
    		ShardingPolicy.LOCI_SIZE_POLICY.shardBigEnough(shard));

    shard = new BAMShard("f","chr20",1);
    chunk = new Chunk(1,9*1024*1024);
    shard.addBin(Collections.singletonList(chunk),90000);
    Assert.assertFalse(
    		"Shard of size " + shard.sizeInLoci() +
    		" is big enough but it should NOT be",
    		ShardingPolicy.LOCI_SIZE_POLICY.shardBigEnough(shard));
  }
}


text:
from pyflink.common import *
from pyflink.dataset import *
from pyflink.datastream import *
from pyflink.table import *
from pyflink.table.catalog import *
from pyflink.table.descriptors import *
from pyflink.table.window import *
from pyflink.table.udf import *

import pyflink

from py4j.java_gateway import java_import

intp = gateway.entry_point

pyflink.java_gateway._gateway = gateway
pyflink.java_gateway.import_flink_view(gateway)
pyflink.java_gateway.install_exception_handler()

b_env = pyflink.dataset.ExecutionEnvironment(intp.getJavaExecutionEnvironment())
bt_env = BatchTableEnvironment(intp.getJavaBatchTableEnvironment("blink"), True)
bt_env_2 = BatchTableEnvironment(intp.getJavaBatchTableEnvironment("flink"), False)
s_env = StreamExecutionEnvironment(intp.getJavaStreamExecutionEnvironment())
st_env = StreamTableEnvironment(intp.getJavaStreamTableEnvironment("blink"), True)
st_env_2 = StreamTableEnvironment(intp.getJavaStreamTableEnvironment("flink"), False)

from zeppelin_context import PyZeppelinContext

#TODO(zjffdu) merge it with IPyFlinkZeppelinContext
class PyFlinkZeppelinContext(PyZeppelinContext):

  def __init__(self, z, gateway):
    super(PyFlinkZeppelinContext, self).__init__(z, gateway)

  def show(self, obj, **kwargs):
    from pyflink.table import Table
    if isinstance(obj, Table):
      if 'stream_type' in kwargs:
        self.z.show(obj._j_table, kwargs['stream_type'], kwargs)
      else:
        print(self.z.showData(obj._j_table))
    else:
      super(PyFlinkZeppelinContext, self).show(obj, **kwargs)

z = __zeppelin__ = PyFlinkZeppelinContext(intp.getZeppelinContext(), gateway)
__zeppelin__._setup_matplotlib()


text:
package v1

import (
	"strings"

	"code.gitea.io/gitea/models"
	"code.gitea.io/gitea/modules/auth"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/routers/api/v1/admin"
	"code.gitea.io/gitea/routers/api/v1/misc"
	"code.gitea.io/gitea/routers/api/v1/org"
	"code.gitea.io/gitea/routers/api/v1/repo"
	_ "code.gitea.io/gitea/routers/api/v1/swagger" // for swagger generation
	"code.gitea.io/gitea/routers/api/v1/user"
	"code.gitea.io/gitea/routers/api/v1/utils"
	api "code.gitea.io/sdk/gitea"

	"github.com/go-macaron/binding"
	"gopkg.in/macaron.v1"
)

func repoAssignment() macaron.Handler {
	return func(ctx *context.APIContext) {
		userName := ctx.Params(":username")
		repoName := ctx.Params(":reponame")

		var (
			owner *models.User
			err   error
		)

		// Check if the user is the same as the repository owner.
		if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
			owner = ctx.User
		} else {
			owner, err = models.GetUserByName(userName)
			if err != nil {
				if models.IsErrUserNotExist(err) {
					ctx.Status(404)
				} else {
					ctx.Error(500, "GetUserByName", err)
				}
				return
			}
		}
		ctx.Repo.Owner = owner

		// Get repository.
		repo, err := models.GetRepositoryByName(owner.ID, repoName)
		if err != nil {
			if models.IsErrRepoNotExist(err) {
				redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
				if err == nil {
					context.RedirectToRepo(ctx.Context, redirectRepoID)
				} else if models.IsErrRepoRedirectNotExist(err) {
					ctx.Status(404)
				} else {
					ctx.Error(500, "LookupRepoRedirect", err)
				}
			} else {
				ctx.Error(500, "GetRepositoryByName", err)
			}
			return
		}
		repo.Owner = owner

		if ctx.IsSigned && ctx.User.IsAdmin {
			ctx.Repo.AccessMode = models.AccessModeOwner
		} else {
			mode, err := models.AccessLevel(utils.UserID(ctx), repo)
			if err != nil {
				ctx.Error(500, "AccessLevel", err)
				return
			}
			ctx.Repo.AccessMode = mode
		}

		if !ctx.Repo.HasAccess() {
			ctx.Status(404)
			return
		}

		ctx.Repo.Repository = repo
	}
}

// Contexter middleware already checks token for user sign in process.
func reqToken() macaron.Handler {
	return func(ctx *context.Context) {
		if !ctx.IsSigned {
			ctx.Error(401)
			return
		}
	}
}

func reqBasicAuth() macaron.Handler {
	return func(ctx *context.Context) {
		if !ctx.IsBasicAuth {
			ctx.Error(401)
			return
		}
	}
}

func reqAdmin() macaron.Handler {
	return func(ctx *context.Context) {
		if !ctx.IsSigned || !ctx.User.IsAdmin {
			ctx.Error(403)
			return
		}
	}
}

func reqRepoWriter() macaron.Handler {
	return func(ctx *context.Context) {
		if !ctx.Repo.IsWriter() {
			ctx.Error(403)
			return
		}
	}
}

func reqOrgMembership() macaron.Handler {
	return func(ctx *context.APIContext) {
		var orgID int64
		if ctx.Org.Organization != nil {
			orgID = ctx.Org.Organization.ID
		} else if ctx.Org.Team != nil {
			orgID = ctx.Org.Team.OrgID
		} else {
			ctx.Error(500, "", "reqOrgMembership: unprepared context")
			return
		}

		if !models.IsOrganizationMember(orgID, ctx.User.ID) {
			if ctx.Org.Organization != nil {
				ctx.Error(403, "", "Must be an organization member")
			} else {
				ctx.Status(404)
			}
			return
		}
	}
}

func reqOrgOwnership() macaron.Handler {
	return func(ctx *context.APIContext) {
		var orgID int64
		if ctx.Org.Organization != nil {
			orgID = ctx.Org.Organization.ID
		} else if ctx.Org.Team != nil {
			orgID = ctx.Org.Team.OrgID
		} else {
			ctx.Error(500, "", "reqOrgOwnership: unprepared context")
			return
		}

		if !models.IsOrganizationOwner(orgID, ctx.User.ID) {
			if ctx.Org.Organization != nil {
				ctx.Error(403, "", "Must be an organization owner")
			} else {
				ctx.Status(404)
			}
			return
		}
	}
}

func orgAssignment(args ...bool) macaron.Handler {
	var (
		assignOrg  bool
		assignTeam bool
	)
	if len(args) > 0 {
		assignOrg = args[0]
	}
	if len(args) > 1 {
		assignTeam = args[1]
	}
	return func(ctx *context.APIContext) {
		ctx.Org = new(context.APIOrganization)

		var err error
		if assignOrg {
			ctx.Org.Organization, err = models.GetOrgByName(ctx.Params(":orgname"))
			if err != nil {
				if models.IsErrOrgNotExist(err) {
					ctx.Status(404)
				} else {
					ctx.Error(500, "GetOrgByName", err)
				}
				return
			}
		}

		if assignTeam {
			ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid"))
			if err != nil {
				if models.IsErrUserNotExist(err) {
					ctx.Status(404)
				} else {
					ctx.Error(500, "GetTeamById", err)
				}
				return
			}
		}
	}
}

func mustEnableIssues(ctx *context.APIContext) {
	if !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) {
		ctx.Status(404)
		return
	}
}

func mustAllowPulls(ctx *context.Context) {
	if !ctx.Repo.Repository.AllowsPulls() {
		ctx.Status(404)
		return
	}
}

// RegisterRoutes registers all v1 APIs routes to web application.
// FIXME: custom form error response
func RegisterRoutes(m *macaron.Macaron) {
	bind := binding.Bind

	m.Get("/swagger", misc.Swagger) //Render V1 by default

	m.Group("/v1", func() {
		// Miscellaneous
		m.Get("/swagger", misc.Swagger)
		m.Get("/version", misc.Version)
		m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
		m.Post("/markdown/raw", misc.MarkdownRaw)

		// Users
		m.Group("/users", func() {
			m.Get("/search", user.Search)

			m.Group("/:username", func() {
				m.Get("", user.GetInfo)

				m.Get("/repos", user.ListUserRepos)
				m.Group("/tokens", func() {
					m.Combo("").Get(user.ListAccessTokens).
						Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
				}, reqBasicAuth())
			})
		})

		m.Group("/users", func() {
			m.Group("/:username", func() {
				m.Get("/keys", user.ListPublicKeys)
				m.Get("/gpg_keys", user.ListGPGKeys)

				m.Get("/followers", user.ListFollowers)
				m.Group("/following", func() {
					m.Get("", user.ListFollowing)
					m.Get("/:target", user.CheckFollowing)
				})

				m.Get("/starred", user.GetStarredRepos)

				m.Get("/subscriptions", user.GetWatchedRepos)
			})
		}, reqToken())

		m.Group("/user", func() {
			m.Get("", user.GetAuthenticatedUser)
			m.Combo("/emails").Get(user.ListEmails).
				Post(bind(api.CreateEmailOption{}), user.AddEmail).
				Delete(bind(api.DeleteEmailOption{}), user.DeleteEmail)

			m.Get("/followers", user.ListMyFollowers)
			m.Group("/following", func() {
				m.Get("", user.ListMyFollowing)
				m.Combo("/:username").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow)
			})

			m.Group("/keys", func() {
				m.Combo("").Get(user.ListMyPublicKeys).
					Post(bind(api.CreateKeyOption{}), user.CreatePublicKey)
				m.Combo("/:id").Get(user.GetPublicKey).
					Delete(user.DeletePublicKey)
			})

			m.Group("/gpg_keys", func() {
				m.Combo("").Get(user.ListMyGPGKeys).
					Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey)
				m.Combo("/:id").Get(user.GetGPGKey).
					Delete(user.DeleteGPGKey)
			})

			m.Combo("/repos").Get(user.ListMyRepos).
				Post(bind(api.CreateRepoOption{}), repo.Create)

			m.Group("/starred", func() {
				m.Get("", user.GetMyStarredRepos)
				m.Group("/:username/:reponame", func() {
					m.Get("", user.IsStarring)
					m.Put("", user.Star)
					m.Delete("", user.Unstar)
				}, repoAssignment())
			})
			m.Get("/times", repo.ListMyTrackedTimes)

			m.Get("/subscriptions", user.GetMyWatchedRepos)
		}, reqToken())

		// Repositories
		m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)

		m.Group("/repos", func() {
			m.Get("/search", repo.Search)
		})

		m.Combo("/repositories/:id", reqToken()).Get(repo.GetByID)

		m.Group("/repos", func() {
			m.Post("/migrate", reqToken(), bind(auth.MigrateRepoForm{}), repo.Migrate)

			m.Group("/:username/:reponame", func() {
				m.Combo("").Get(repo.Get).Delete(reqToken(), repo.Delete)
				m.Group("/hooks", func() {
					m.Combo("").Get(repo.ListHooks).
						Post(bind(api.CreateHookOption{}), repo.CreateHook)
					m.Combo("/:id").Get(repo.GetHook).
						Patch(bind(api.EditHookOption{}), repo.EditHook).
						Delete(repo.DeleteHook)
				}, reqToken(), reqRepoWriter())
				m.Group("/collaborators", func() {
					m.Get("", repo.ListCollaborators)
					m.Combo("/:collaborator").Get(repo.IsCollaborator).
						Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
						Delete(repo.DeleteCollaborator)
				}, reqToken())
				m.Get("/raw/*", context.RepoRefByType(context.RepoRefAny), repo.GetRawFile)
				m.Get("/archive/*", repo.GetArchive)
				m.Combo("/forks").Get(repo.ListForks).
					Post(reqToken(), bind(api.CreateForkOption{}), repo.CreateFork)
				m.Group("/branches", func() {
					m.Get("", repo.ListBranches)
					m.Get("/*", context.RepoRefByType(context.RepoRefBranch), repo.GetBranch)
				})
				m.Group("/keys", func() {
					m.Combo("").Get(repo.ListDeployKeys).
						Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
					m.Combo("/:id").Get(repo.GetDeployKey).
						Delete(repo.DeleteDeploykey)
				}, reqToken(), reqRepoWriter())
				m.Group("/times", func() {
					m.Combo("").Get(repo.ListTrackedTimesByRepository)
					m.Combo("/:timetrackingusername").Get(repo.ListTrackedTimesByUser)

				}, mustEnableIssues)
				m.Group("/issues", func() {
					m.Combo("").Get(repo.ListIssues).
						Post(reqToken(), bind(api.CreateIssueOption{}), repo.CreateIssue)
					m.Group("/comments", func() {
						m.Get("", repo.ListRepoIssueComments)
						m.Combo("/:id", reqToken()).
							Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment)
					})
					m.Group("/:index", func() {
						m.Combo("").Get(repo.GetIssue).
							Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue)

						m.Group("/comments", func() {
							m.Combo("").Get(repo.ListIssueComments).
								Post(reqToken(), bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment)
							m.Combo("/:id", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment).
								Delete(repo.DeleteIssueComment)
						})

						m.Group("/labels", func() {
							m.Combo("").Get(repo.ListIssueLabels).
								Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels).
								Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels).
								Delete(reqToken(), repo.ClearIssueLabels)
							m.Delete("/:id", reqToken(), repo.DeleteIssueLabel)
						})

						m.Group("/times", func() {
							m.Combo("").Get(repo.ListTrackedTimes).
								Post(reqToken(), bind(api.AddTimeOption{}), repo.AddTime)
						})
					})
				}, mustEnableIssues)
				m.Group("/labels", func() {
					m.Combo("").Get(repo.ListLabels).
						Post(reqToken(), bind(api.CreateLabelOption{}), repo.CreateLabel)
					m.Combo("/:id").Get(repo.GetLabel).
						Patch(reqToken(), bind(api.EditLabelOption{}), repo.EditLabel).
						Delete(reqToken(), repo.DeleteLabel)
				})
				m.Group("/milestones", func() {
					m.Combo("").Get(repo.ListMilestones).
						Post(reqToken(), reqRepoWriter(), bind(api.CreateMilestoneOption{}), repo.CreateMilestone)
					m.Combo("/:id").Get(repo.GetMilestone).
						Patch(reqToken(), reqRepoWriter(), bind(api.EditMilestoneOption{}), repo.EditMilestone).
						Delete(reqToken(), reqRepoWriter(), repo.DeleteMilestone)
				})
				m.Get("/stargazers", repo.ListStargazers)
				m.Get("/subscribers", repo.ListSubscribers)
				m.Group("/subscription", func() {
					m.Get("", user.IsWatching)
					m.Put("", reqToken(), user.Watch)
					m.Delete("", reqToken(), user.Unwatch)
				})
				m.Group("/releases", func() {
					m.Combo("").Get(repo.ListReleases).
						Post(reqToken(), reqRepoWriter(), bind(api.CreateReleaseOption{}), repo.CreateRelease)
					m.Combo("/:id").Get(repo.GetRelease).
						Patch(reqToken(), reqRepoWriter(), bind(api.EditReleaseOption{}), repo.EditRelease).
						Delete(reqToken(), reqRepoWriter(), repo.DeleteRelease)
				})
				m.Post("/mirror-sync", reqToken(), reqRepoWriter(), repo.MirrorSync)
				m.Get("/editorconfig/:filename", context.RepoRef(), repo.GetEditorconfig)
				m.Group("/pulls", func() {
					m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests).
						Post(reqToken(), reqRepoWriter(), bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
					m.Group("/:index", func() {
						m.Combo("").Get(repo.GetPullRequest).
							Patch(reqToken(), reqRepoWriter(), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
						m.Combo("/merge").Get(repo.IsPullRequestMerged).
							Post(reqToken(), reqRepoWriter(), repo.MergePullRequest)
					})

				}, mustAllowPulls, context.ReferencesGitRepo())
				m.Group("/statuses", func() {
					m.Combo("/:sha").Get(repo.GetCommitStatuses).
						Post(reqToken(), reqRepoWriter(), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
				})
				m.Group("/commits/:ref", func() {
					m.Get("/status", repo.GetCombinedCommitStatusByRef)
					m.Get("/statuses", repo.GetCommitStatusesByRef)
				})
			}, repoAssignment())
		})

		// Organizations
		m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
		m.Get("/users/:username/orgs", org.ListUserOrgs)
		m.Group("/orgs/:orgname", func() {
			m.Get("/repos", user.ListOrgRepos)
			m.Combo("").Get(org.Get).
				Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit)
			m.Group("/members", func() {
				m.Get("", org.ListMembers)
				m.Combo("/:username").Get(org.IsMember).
					Delete(reqToken(), reqOrgOwnership(), org.DeleteMember)
			})
			m.Group("/public_members", func() {
				m.Get("", org.ListPublicMembers)
				m.Combo("/:username").Get(org.IsPublicMember).
					Put(reqToken(), reqOrgMembership(), org.PublicizeMember).
					Delete(reqToken(), reqOrgMembership(), org.ConcealMember)
			})
			m.Combo("/teams", reqToken(), reqOrgMembership()).Get(org.ListTeams).
				Post(bind(api.CreateTeamOption{}), org.CreateTeam)
			m.Group("/hooks", func() {
				m.Combo("").Get(org.ListHooks).
					Post(bind(api.CreateHookOption{}), org.CreateHook)
				m.Combo("/:id").Get(org.GetHook).
					Patch(reqOrgOwnership(), bind(api.EditHookOption{}), org.EditHook).
					Delete(reqOrgOwnership(), org.DeleteHook)
			}, reqToken(), reqOrgMembership())
		}, orgAssignment(true))
		m.Group("/teams/:teamid", func() {
			m.Combo("").Get(org.GetTeam).
				Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam).
				Delete(reqOrgOwnership(), org.DeleteTeam)
			m.Group("/members", func() {
				m.Get("", org.GetTeamMembers)
				m.Combo("/:username").
					Put(reqOrgOwnership(), org.AddTeamMember).
					Delete(reqOrgOwnership(), org.RemoveTeamMember)
			})
			m.Group("/repos", func() {
				m.Get("", org.GetTeamRepos)
				m.Combo("/:orgname/:reponame").
					Put(org.AddTeamRepository).
					Delete(org.RemoveTeamRepository)
			})
		}, orgAssignment(false, true), reqToken(), reqOrgMembership())

		m.Any("/*", func(ctx *context.Context) {
			ctx.Error(404)
		})

		m.Group("/admin", func() {
			m.Group("/users", func() {
				m.Post("", bind(api.CreateUserOption{}), admin.CreateUser)
				m.Group("/:username", func() {
					m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser).
						Delete(admin.DeleteUser)
					m.Post("/keys", bind(api.CreateKeyOption{}), admin.CreatePublicKey)
					m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
					m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
				})
			})
		}, reqAdmin())
	}, context.APIContexter())
}


text:
require "opendata/catalogue/builder/toronto/version"
require "mongo"
require "nokogiri"
require "open-uri"
require "uri"
require "ruby-progressbar"

module Opendata
  module Catalogue
    module Builder
      module Toronto

        extend self
        include Mongo

        @@base_url ="http://www1.toronto.ca"

        attr_reader :catalogue_list, :passed, :failed

        def add_datasets
          make_datasets(@catalogue_list)
          self
        end

        def get_datasets(url)
          dataset = []
          doc = scrape(url)
          links = doc.css('.single-item dd').last.css('li a').to_a ||= []

          if !links.empty?
            links.each do |item|
              title = item.text
              href = URI.encode(item.attr('href'))
              uri = URI.parse(href)

              link = !!uri.host ? "#{item.attr('href')}" : "#{@@base_url}#{href}"

              if link.include?("google.com")
                google_doc = URI.parse(link)
                file_name = google_doc.query
                file_type = google_doc.path.split('/')[1]
                if file_type === "fusiontables"
                  file_type = "Google Fusion Table"

                elsif file_type === "spreadsheet"
                  file_type = "Google Spread Sheet"
                else
                  file_type = "Google Doc"
                end
              else
                file_name = Pathname.new(href).basename.to_s
                file_type = File.extname(file_name)
              end

              dataset.push({
                title: title,
                file: {
                  file_name: file_name,
                  file_type: file_type,
                  link: link
                }
              })
            end
          end

          dataset.empty? ? nil : dataset
        end

        def make_datasets(list)
          @passed = 0
          @failed = {}

          puts "Getting datasets...process may pause briefly..."

          progressbar = progress(list, "Datasets Completed")

          list.each do |(guid, document)|
            progressbar.increment
            dataset = get_datasets(document[:portal_page])

            if dataset
              document[:datasets] = dataset
              @catalogue_list[guid] = document

              @passed += 1
            else
              @failed[guid] = document

            end
          end
          puts "Complete: #{@passed} passed | #{@failed.size} failed."

        end

        def make_list
          @catalogue_list = {}
          first = make_list_xml
          second = make_list_html

          if first && second
            second.each do |guid, values|
              @catalogue_list[guid] = first[guid].merge(second[guid])
            end
          end

          @catalogue_list ? self : nil
        end

        def make_list_html
          url = "#{@@base_url}/wps/portal/contentonly?vgnextoid=1a66e03bb8d1e310VgnVCM10000071d60f89RCRD"
          list = {}
          doc = scrape(url)
          doc = doc.css('.alpha .article').to_a

          puts "Scraping HTML..."

          if doc
            progressbar = progress(doc, "Done Scraping HTML")

            doc.each do |item|
              # title = item.css('h4 a').text
              # description = item.css('.description p').text
              portal_page = item.css('h4 a').attr('href').text
              query = URI.parse(portal_page).query
              guid = CGI::parse(query)
              guid = guid["vgnextoid"].first
              format = file_formats(item)

              list[guid] = {
                formats: format
              }

              progressbar.increment
            end
          else
            nil
          end

          puts "Finished scraping HTML.\n\r"

          list
        end

        def make_list_xml

          url = "#{@@base_url}/cot-templating/views/rss20view.jsp?vgnextoid=1a66e03bb8d1e310VgnVCM10000071d60f89RCRD&compid=1b4eadba5a72e310VgnVCM10000071d60f89RCRD"
          list = {}
          doc = scrape(url, :xml)
          doc= doc.css('item').to_a

          puts "Parsing XML..."

          if doc
            progressbar = progress(doc, "Done Parsing XML")

            doc.each do |item|
              title = item.css('title').text
              description = item.css('description').text
              portal_page = item.css('link').text
              guid = item.css('guid').text
              updated = item.css('pubDate').text

              list[guid] = {
                title: title,
                guid: guid,
                description: description,
                portal_page: portal_page,
                updated: updated
              }

              progressbar.increment
            end
          else
            nil
          end

          puts "Finished parsing XML.\n\r"

          list
        end

        def run
          system "clear" unless system "cls"

          make_list
          add_datasets
          save
        end

        def save
          @saved = 0
          @errors = {}

          database = database_connect

          puts "Saving to database..."

          progressbar = progress(@catalogue_list, "Saved")

          @catalogue_list.each do |(guid, document)|
            database.connection.reconnect
            if database.collection('toronto').update({guid: document[:guid]} , document, {upsert: true})
              progressbar.increment
              @saved += 1
            else
              @errors[guid] = document
              puts "There was a save error."
              next
            end
            database.connection.close
          end

          puts "Completed: #{@saved} saved  | #{@errors.size} errors.\n\r"
          self
        end

        def scrape(url, type=:html, options={})
          attempts = 0
          max_attempts = options[:max_attempts] ||= 2
          connection = nil

          type = type.downcase.to_sym

          begin
            if type === :xml
              connection = Nokogiri::XML(open(url)) do |config|
                config.noblanks
              end
            else
              connection = Nokogiri::HTML(open(url)) do |config|
                config.noblanks
              end
            end
          rescue Exception => ex
            attempts += 1
            retry if(attempts < max_attempts)
          end

          connection
        end

        private

        def database_connect
          connection = MongoClient.new(ENV['MONGO_URL'], ENV['MONGO_PORT']).db('opendata_catalogue')
          connection.authenticate(ENV['MONGO_USERNAME'], ENV['MONGO_PASSWORD'])
          connection
        end

        def file_formats(object)
          format = object.css('.format').text.strip.split(", ")

          format.each_with_index do |value, key|
            value.strip!
            if value.include?("/")
              format[key] = value.split("/").flatten
            elsif value.include?(" and ")
              format[key] = value.split(" and ")
            elsif value === "CSV File"
              format[key] = value = "CSV"
            elsif value === "XLS File"
              format[key] = value = "XLS"
            end
          end

          format.flatten
        end

        def progress(array, title)
          return ProgressBar.create(
            :title => title,
            :total => array.size,
            :format => '%a %E |%b>>%i| %c of %C / %p%% %t',
            :smoothing => 0.6
          )
        end

      end
    end
  end
end


text:
'''
    Front end flask implementation
'''

import flask
import os
import json
import sqlite3
import uuid

import calculate
import helpers
import runner

DB = "./assets/exac.db"
RUNNER_DB = "./assets/runner.db"

EXAC_POPULATION = 53105.0
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['vcf'])

app = flask.Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024 * 1024 # 1G

### database access
def db():
    db_instance = getattr(flask.g, '_database', None)
    if db_instance is None:
        db_instance = flask.g._database = sqlite3.connect(DB)
    return db_instance

def query_db(query, args=(), one=False):
    cur = db().execute(query, args)
    rv = cur.fetchall()
    cur.close()
    return (rv[0] if rv else None) if one else rv

@app.teardown_appcontext
def close_connection(exception):
    db_instance = getattr(flask.g, '_database', None)
    if db_instance is not None:
        db_instance.close()

### business logic
def process():
    '''
        analysis when details provided as gene/burden
    '''

    # is it the vcf?
    if flask.request.form['analysis_type'] == 'vcf' and flask.request.files['vcf'] is not None and flask.request.files['vcf'].filename is not None and flask.request.files['vcf'].filename != '':
        return process_upload()

    # try the csv
    settings = helpers.parse_settings(flask.request.form)

    if len(settings['errors']) > 0:
        flask.render_template('main.html', errors=settings['errors'], form=flask.request.form)

    # input variants per gene count
    burdens = flask.request.form['burdens'].split('\n')

    result = []
    warnings = []
    for line, burden in enumerate(burdens):
        fields = burden.strip().split(',')
        if len(fields) != 2:
            settings['errors'].append('Incorrect burden format on line {}'.format(line + 1))
            continue

        try:
            case_burden = float(fields[1])
            if case_burden <= 0:
                settings['errors'].append('Incorrect burden format on line {}: burden count {} is less than 0'.format(line + 1, fields[1]))
                continue
        except ValueError:
            settings['errors'].append('Incorrect burden format on line {}: burden count "{}" is not numeric'.format(line + 1, fields[1]))
            continue

        # --- determine exac count for this gene
        matches = helpers.get_exac_detail(query_db=query_db, gene=fields[0], settings=settings)

        if matches[1] is not None:
            statistics = calculate.calculate_burden_statistics(case_burden=case_burden, total_cases=settings['cases'], population_burden=matches[0], total_population=EXAC_POPULATION)
            result.append({'gene': fields[0], 'burden': fields[1], 'matches': matches[0], 'protein_length': matches[1], \
                'z_test': statistics[0], 'binomial_test': statistics[1], 'relative_risk': statistics[2], 'rr_conf_interval': statistics[3]})
        else:
            # gene is no good
            warnings.append( 'Gene "{}" or variants not found in the selected database'.format(fields[0]))

    if len(settings['errors']) == 0:
        return flask.render_template('results.html',
            result=result,
            filter_type=settings['filter_type'],
            filter_value=settings['filter_value'],
            filter_af_pop=','.join(settings['filter_af_pop']),
            filter_af_value=settings['filter_af_value'],
            cases=settings['cases'],
            include_impacts=', '.join(settings['include_impacts']),
            gene_list = ','.join(["'{}'".format(item['gene'].replace("'", "\\'")) for item in result if item['protein_length'] is not None]),
            protein_lengths = ','.join([ str(item['protein_length']) for item in result if item['protein_length'] is not None]),
            binomial_pvalues = ','.join([ '{0:0.3e}'.format(item['binomial_test']) for item in result if item['protein_length'] is not None]),
            relative_risk = ','.join([ '{0:0.3e}'.format(item['relative_risk']) for item in result if item['protein_length'] is not None]),
            rr_conf_interval = ','.join([ str(item['rr_conf_interval']) for item in result if item['protein_length'] is not None]),
            warnings = warnings,
            is_vcf = False
        )
    else:
        return flask.render_template('main.html', errors=settings['errors'], form=flask.request.form)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

def generate_id():
    return str(uuid.uuid4())

def process_upload():
    '''
        adds the annotation job to the queue
    '''
    errors = []
    if 'vcf' not in flask.request.files:
        errors.append('Please specify a file')
        return flask.render_template('main.html', errors=errors, form=flask.request.form)

    vcf_file = flask.request.files['vcf']
    # if user does not select file, browser also
    # submit a empty part without filename
    if vcf_file.filename == '':
        errors.append('No selected file')
        return flask.render_template('main.html', errors=errors, form=flask.request.form)

    if not allowed_file(vcf_file.filename):
        errors.append('Invalid file extension')
        return flask.render_template('main.html', errors=errors, form=flask.request.form)

    settings = helpers.parse_settings(flask.request.form)

    if len(settings['errors']) > 0:
        return flask.render_template('main.html', errors=errors, form=flask.request.form)

    # looks ok

    job_id = generate_id()
    filename = os.path.join(app.config['UPLOAD_FOLDER'], '{}.vcf'.format(job_id))
    vcf_file.save(filename)
    file_size = os.stat(filename).st_size

    # start processing
    runner.add_to_queue(RUNNER_DB, job_id, os.path.join(app.config['UPLOAD_FOLDER'], '{}.vcf'.format(job_id)), os.path.join(app.config['UPLOAD_FOLDER'], '{}.out'.format(job_id)), json.dumps(settings), file_size)
    redirect = flask.redirect(flask.url_for('process_vcf', job=job_id))
    response = flask.current_app.make_response(redirect)
    return response

### front end
@app.route('/', methods=['GET', 'POST'])
def main():
    '''
        main entry point
    '''
    if flask.request.method == 'POST':
        return process()
    else:
        return flask.render_template('main.html', form=flask.request.form)

@app.route('/vcf_result/<job>')
def vcf_result(job):
    '''
        redirected to this after annotation has finished
    '''
    status = runner.job_status(RUNNER_DB, job) # ensure it's a real job
    if status is None: # no output
        return flask.render_template('main.html', errors=['Job not found'], form=flask.request.form)

    # determine counts for genes
    settings = json.loads(status['settings'])
    result = []
    warnings = []
    current = [None, 0]
    skip = 2
    for line in open(os.path.join(app.config['UPLOAD_FOLDER'], '{}.out'.format(job)), 'r'):
        if skip > 0: # skip header
            if skip == 2:
                settings['cases'] = int(line.strip())
            skip -=1
            continue
        fields = line.strip('\n').split('\t')
        if current[0] == fields[0]: # same gene
            current[1] += helpers.get_vcf_match(fields, settings)
        else: # new gene
            if current[0] is not None and current[1] > 0: # an actual gene
                matches = helpers.get_exac_detail(query_db=query_db, gene=current[0], settings=settings)
                if matches[1] is not None:
                    statistics = calculate.calculate_burden_statistics(case_burden=current[1], total_cases=settings['cases'], population_burden=matches[0], total_population=EXAC_POPULATION)
                    result.append({'gene': current[0], 'burden': current[1], 'matches': matches[0], 'protein_length': matches[1], \
                        'z_test': statistics[0], 'binomial_test': statistics[1], 'relative_risk': statistics[2], 'rr_conf_interval': statistics[3]})
                else:
                    # gene is no good
                    warnings.append( 'Gene "{}" or variants not found in the selected database'.format(current[0]))
            # start counting new gene
            current = [fields[0], helpers.get_vcf_match(fields, settings)]
    if current[1] > 0:
        matches = helpers.get_exac_detail(query_db=query_db, gene=current[0], settings=settings)
        if matches[1] is not None:
            statistics = calculate.calculate_burden_statistics(case_burden=current[1], total_cases=settings['cases'], population_burden=matches[0], total_population=EXAC_POPULATION)
            result.append({'gene': current[0], 'burden': current[1], 'matches': matches[0], 'protein_length': matches[1], \
                'z_test': statistics[0], 'binomial_test': statistics[1], 'relative_risk': statistics[2], 'rr_conf_interval': statistics[3]})
        else:
            # gene is no good
            warnings.append( 'Gene "{}" or variants not found in the selected database'.format(current[0]))

    return flask.render_template('results.html',
        result=result,
        filter_type=settings['filter_type'],
        filter_value=settings['filter_value'],
        filter_af_pop=','.join(settings['filter_af_pop']),
        filter_af_value=settings['filter_af_value'],
        cases=settings['cases'],
        include_impacts=', '.join(settings['include_impacts']),
        gene_list = ','.join(["'{}'".format(item['gene'].replace("'", "\\'")) for item in result if item['protein_length'] is not None]),
        protein_lengths = ','.join([ str(item['protein_length']) for item in result if item['protein_length'] is not None]),
        binomial_pvalues = ','.join([ '{0:0.3e}'.format(item['binomial_test']) for item in result if item['protein_length'] is not None]),
        relative_risk = ','.join([ '{0:0.3e}'.format(item['relative_risk']) for item in result if item['protein_length'] is not None]),
        rr_conf_interval = ','.join([ str(item['rr_conf_interval']) for item in result if item['protein_length'] is not None]),
        warnings = warnings,
        is_vcf = True,
        job = job
    )

@app.route('/gene_result/<job>/<gene>')
def gene_result(job, gene):
    '''
        find AF details for a requested gene in a job
    '''
    status = runner.job_status(RUNNER_DB, job) # ensure it's a real job
    if status is None: # no output
        return flask.render_template('main.html', errors=['Job not found'], form=flask.request.form)

    skip = 2
    # determine counts for genes
    settings = json.loads(status['settings'])

    result = {'x': [], 'y': [], 'pass': [], 'text': []}
    for line in open(os.path.join(app.config['UPLOAD_FOLDER'], '{}.out'.format(job)), 'r'):
        if skip > 0: # skip header
            if skip == 2:
                cases = float(line.strip())
            skip -=1
            continue

        fields = line.strip('\n').split('\t')
        if fields[helpers.OUTPUT_FIELDS['gene']] == gene:
            ac = float(fields[helpers.OUTPUT_FIELDS['allele_count']])
            an = float(fields[helpers.OUTPUT_FIELDS['allele_number']])
            exac_ac = float(fields[helpers.OUTPUT_FIELDS['exac_all_pop_ac']])
            exac_an = float(fields[helpers.OUTPUT_FIELDS['exac_all_pop_an']])
            if an != 0:
                result['y'].append( ac / an )
                if exac_an != 0:
                    result['x'].append( exac_ac / exac_an )
                else:
                    result['x'].append( 0 )
                result['pass'].append( helpers.get_vcf_match(fields, settings)>0)
                result['text'].append('AC={} {}'.format(fields[helpers.OUTPUT_FIELDS['allele_count']], fields[helpers.OUTPUT_FIELDS['impact_type']]))

    return flask.jsonify(result)

@app.route('/process_vcf/<job>')
def process_vcf(job):
    '''
        wait for the annotation job to finish by continually checking the job status
    '''
    status = runner.job_status(RUNNER_DB, job)
    if status is None:
        return flask.render_template('main.html', errors=['Job not found'], form=flask.request.form)
    elif status['status'] == 'F': # finished
        return flask.redirect(flask.url_for("vcf_result", job=job))
    else: # still in progress
        return flask.render_template('process_vcf.html', job=job, status=status)

@app.route('/job_status/<job>/')
def job_status(job):
    status = runner.job_status(RUNNER_DB, job)
    if status is None:
        return flask.render_template('main.html', form=flask.request.form)
    else: # still in progress
        return flask.jsonify(status)

@app.route('/about')
def about():
    return flask.render_template('about.html')

@app.route('/contact')
def contact():
    return flask.render_template('contact.html')

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


text:
import React from 'react';

export default class Dashboard extends React.Component {
    render() {
        return
Welcome to the app!

    }
}


text:
import { makeString } from 'utils/str-utils';
import { FIELD } from 'app/page/workspace-edit-page';

// Question #1: What is the primary purpose of your project?
export const defaultAnswersPrimaryPurpose = [
  {
    id: FIELD.PRIMARY_PURPOSE.diseaseFocusedResearchCheckbox,
    selected: true,
    value: 'diabetic cataract'
  },
  {
    id: FIELD.PRIMARY_PURPOSE.methodsDevelopmentValidationStudyCheckbox,
    selected: true
  },
  {
    id: FIELD.PRIMARY_PURPOSE.researchControlCheckbox,
    selected: true
  },
  {
    id: FIELD.PRIMARY_PURPOSE.geneticResearchCheckbox,
    selected: true
  },
  {
    id: FIELD.PRIMARY_PURPOSE.socialBehavioralResearchCheckbox,
    selected: true
  },
  {
    id: FIELD.PRIMARY_PURPOSE.populationHealthCheckbox,
    selected: true
  },
  {
    id: FIELD.PRIMARY_PURPOSE.ethicalLegalSocialImplicationsResearchCheckbox,
    selected: true
  },
  {
    id: FIELD.PRIMARY_PURPOSE.drugTherapeuticsDevelopmentResearchCheckbox,
    selected: true
  },
  {
    id: FIELD.PRIMARY_PURPOSE.educationPurposeCheckbox,
    selected: true
  },
  {
    id: FIELD.PRIMARY_PURPOSE.forProfitPurposeCheckbox,
    selected: true
  },
  {
    id: FIELD.PRIMARY_PURPOSE.otherPurposeCheckbox,
    selected: true,
    value: makeString(50)
  }
];

// Question #2: Please provide a summary of your research purpose by responding to the question.
export const defaultAnswersResearchPurposeSummary = [
  {
    id: FIELD.RESEARCH_PURPOSE_SUMMARY.scientificQuestionsIntentToStudyTextarea,
    value: makeString(100)
  },
  {
    id: FIELD.RESEARCH_PURPOSE_SUMMARY.scientificApproachesToUseTextarea,
    value: makeString(100)
  },
  {
    id: FIELD.RESEARCH_PURPOSE_SUMMARY.anticipatedFindingsFromStudyTextarea,
    value: makeString(100)
  }
];

// Question #3: Please tell us how you plan to disseminate your research findings.
export const defaultAnswersDisseminateResearchFindings = [
  {
    id: FIELD.DISSEMINATE_RESEARCH_FINDINGS.publicationInScientificJournalsCheckbox,
    selected: true
  },
  {
    id: FIELD.DISSEMINATE_RESEARCH_FINDINGS.socialMediaCheckbox,
    selected: true
  },
  {
    id: FIELD.DISSEMINATE_RESEARCH_FINDINGS.presentationAtScientificConferencesCheckbox,
    selected: true
  },
  {
    id: FIELD.DISSEMINATE_RESEARCH_FINDINGS.presentationAtCommunityForumsCheckbox,
    selected: true
  },
  {
    id: FIELD.DISSEMINATE_RESEARCH_FINDINGS.pressReleaseCheckbox,
    selected: true
  },
  {
    id: FIELD.DISSEMINATE_RESEARCH_FINDINGS.publicationInCommunityJournalsCheckbox,
    selected: true
  },
  {
    id: FIELD.DISSEMINATE_RESEARCH_FINDINGS.publicationInPersonalBlogCheckbox,
    selected: true
  },
  {
    id: FIELD.DISSEMINATE_RESEARCH_FINDINGS.otherCheckbox,
    selected: true,
    value: makeString(20)
  }
];

// Question #4: Please select all of the statements below that describe the outcomes you anticipate from your research.
export const defaultAnswersAnticipatedOutcomesFromResearch = [
  {
    id: FIELD.DESCRIBE_ANTICIPATED_OUTCOMES.seeksIncreaseWellnessCheckbox,
    selected: true
  },
  {
    id: FIELD.DESCRIBE_ANTICIPATED_OUTCOMES.seeksToReduceHealthDisparitiesCheckbox,
    selected: true
  },
  {
    id: FIELD.DESCRIBE_ANTICIPATED_OUTCOMES.seeksToDevelopRiskAssessmentCheckbox,
    selected: true
  },
  {
    id: FIELD.DESCRIBE_ANTICIPATED_OUTCOMES.seeksToProvideEarlierDiagnosisCheckbox,
    selected: true
  },
  {
    id: FIELD.DESCRIBE_ANTICIPATED_OUTCOMES.seeksToReduceBurdenCheckbox,
    selected: true
  }
];

// Question #5: Population of interest
export const defaultAnswersPopulationOfInterest = [
  {
    id: FIELD.POPULATION_OF_INTEREST.yesRadiobutton,
    selected: true
  },
  {
    id: FIELD.POPULATION_OF_INTEREST.raceMultiAncestryCheckbox,
    selected: true
  },
  {
    id: FIELD.POPULATION_OF_INTEREST.ageGroupsAdolescentsCheckbox,
    selected: true
  },
  {
    id: FIELD.POPULATION_OF_INTEREST.sexAtBirthCheckbox,
    selected: true
  },
  {
    id: FIELD.POPULATION_OF_INTEREST.genderIdentityCheckbox,
    selected: true
  },
  {
    id: FIELD.POPULATION_OF_INTEREST.geographyRuralCheckbox,
    selected: true
  },
  {
    id: FIELD.POPULATION_OF_INTEREST.educationLevelHighSchoolCheckbox,
    selected: true
  },
  {
    id: FIELD.POPULATION_OF_INTEREST.disabilityStatusWithDisabilityCheckbox,
    selected: true
  }
];

// Question #6: Request for Review of Research Purpose Description
export const defaultAnswersRequestForReview = [
  {
    id: FIELD.REQUEST_FOR_REVIEW.noRequestReviewRadiobutton,
    selected: true
  }
];


text:
require_relative '../spec_helper'

ruby_version_is "3.0" do
  describe "The --backtrace-limit command line option" do
    it "limits top-level backtraces to a given number of entries" do
      file = fixture(__FILE__ , "backtrace.rb")
      out = ruby_exe(file, options: "--backtrace-limit=2", args: "top 2>&1", exit_status: 1)
      out = out.gsub(__dir__, '')

      out.should == <<-MSG
top
/fixtures/backtrace.rb:2:in `a': oops (RuntimeError)
\tfrom /fixtures/backtrace.rb:6:in `b'
\tfrom /fixtures/backtrace.rb:10:in `c'
\t ... 2 levels...
      MSG
    end

    it "affects Exception#full_message" do
      file = fixture(__FILE__ , "backtrace.rb")
      out = ruby_exe(file, options: "--backtrace-limit=2", args: "full_message 2>&1")
      out = out.gsub(__dir__, '')

      out.should == <<-MSG
full_message
/fixtures/backtrace.rb:2:in `a': oops (RuntimeError)
\tfrom /fixtures/backtrace.rb:6:in `b'
\tfrom /fixtures/backtrace.rb:10:in `c'
\t ... 2 levels...
      MSG
    end

    it "does not affect Exception#backtrace" do
      file = fixture(__FILE__ , "backtrace.rb")
      out = ruby_exe(file, options: "--backtrace-limit=2", args: "backtrace 2>&1")
      out = out.gsub(__dir__, '')

      out.should == <<-MSG
backtrace
/fixtures/backtrace.rb:2:in `a'
/fixtures/backtrace.rb:6:in `b'
/fixtures/backtrace.rb:10:in `c'
/fixtures/backtrace.rb:14:in `d'
/fixtures/backtrace.rb:29:in `<main>'
      MSG
    end
  end
end


text:
<?php
namespace ez\core;

/**
 * 应用程序类
 *
 * @author lxj
 */
class Application
{
    /**
     * 初始化应用
     *
     * @param array $config
     */
    public function __construct()
    {
        if (empty($config['route'])) {
            new Route();
        } else {
            $route = $config['route'];
            new $route();
        }
    }

    /**
     * 执行应用
     *
     * @access public
     */
    public function run()
    {
        $controllerName = '\\' . APP_PATH_NAME . '\\' . APP_NAME . '\\controller\\' . ucfirst(CONTROLLER_NAME) . 'Controller';

        if (class_exists($controllerName)) {
            $controller = new $controllerName();
            $action = ACTION_NAME;
            if (method_exists($controller, $action)) {
                $controller->$action();
            } else {
                throw new \Exception('not exist Action ' . ACTION_NAME);
            }
        } else {
            throw new \Exception('not exist Controller ' . $controllerName);
        }
    }

}


text:
package won.bot.framework.eventbot.action.impl.wonmessage;

import java.lang.invoke.MethodHandles;
import java.util.function.BiFunction;
import java.util.stream.Stream;

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

import won.bot.framework.eventbot.EventListenerContext;
import won.bot.framework.eventbot.action.BaseEventBotAction;
import won.bot.framework.eventbot.event.Event;
import won.bot.framework.eventbot.event.MessageEvent;
import won.bot.framework.eventbot.event.impl.wonmessage.WonMessageSentEvent;
import won.bot.framework.eventbot.listener.EventListener;
import won.protocol.message.WonMessage;

public class PrintWonMessageAction extends BaseEventBotAction {
    private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

    public PrintWonMessageAction(EventListenerContext eventListenerContext) {
        super(eventListenerContext);
    }

    @Override
    protected void doRun(Event event, EventListener executingListener) throws Exception {
        if (!(event instanceof MessageEvent)) {
            return;
        }
        WonMessage msg = ((MessageEvent) event).getWonMessage();
        if (msg.getMessageType().isResponseMessage()) {
            // we don't print responses
            return;
        }
        if (event instanceof WonMessageSentEvent) {
            handleSentMessage(msg);
        } else {
            handleReceivedMessage(msg);
        }
    }

    private void handleReceivedMessage(WonMessage msg) {
        System.out.println(makeMessageBox("                <---- Received Message <---- ", msg.toStringForDebug(true),
                        120));
    }

    private void handleSentMessage(WonMessage msg) {
        System.out.println(
                        makeMessageBox(" ----> Sent Message ---->                ", msg.toStringForDebug(true), 120));
    }

    private BiFunction<String, Integer, String> centerLayout = (text, width) -> {
        if (text == null) {
            return null;
        }
        if (text.length() >= width) {
            return text;
        }
        int spare = width - text.length();
        int half = spare / 2;
        int rightHalf = (half * 2) == spare ? half : half + 1;
        return rep(' ', half) +
                        text +
                        rep(' ', rightHalf);
    };
    private BiFunction<String, Integer, String> leftLayout = (text, width) -> {
        if (text == null) {
            return null;
        }
        if (text.length() >= width) {
            return text;
        }
        int spare = width - text.length();
        StringBuilder sb = new StringBuilder();
        sb
                        .append(text)
                        .append(rep(' ', spare));
        return sb.toString();
    };

    private String rep(char character, int times) {
        StringBuilder sb = new StringBuilder();
        Stream.generate(() -> character).limit(times).forEach(sb::append);
        return sb.toString();
    }

    protected String makeMessageBox(String header, String body, int textWidth) {
        int padding = 2;
        int width = textWidth + 2 * padding;
        StringBuilder box = new StringBuilder();
        // header upper border
        box
                        .append('+')
                        .append(rep('=', width))
                        .append('+')
                        .append('\n');
        // header
        box.append(surround(lineBreaks(header, textWidth, centerLayout), ' ', '|', padding));
        // header lower border
        box
                        .append('+')
                        .append(rep('-', width))
                        .append('+')
                        .append('\n');
        // body
        box.append(surround(lineBreaks(body, textWidth, leftLayout), ' ', '|', padding));
        box
                        .append('+')
                        .append(rep('=', width))
                        .append('+')
                        .append('\n');
        return "\n" + box.toString() + "\n";
    }

    private String lineBreaks(String text, int textWidth, BiFunction<String, Integer, String> layout) {
        String[] lines = text.split("\\r?\\n");
        StringBuilder formatted = new StringBuilder();
        for (int i = 0; i < lines.length; i++) {
            String line = lines[i];
            if (line.length() <= textWidth) {
                formatted
                                .append(layout.apply(line, textWidth))
                                .append('\n');
            } else {
                formatted
                                .append(line, 0, textWidth)
                                .append('\n');
                lines[i] = line.substring(textWidth);
                i--; // process same array item again
            }
        }
        return formatted.toString();
    }

    private String surround(String text, char filler, char border, int padding) {
        String[] lines = text.split("\\r?\\n");
        StringBuilder formatted = new StringBuilder();
        for (String line : lines) {
            formatted
                            .append(border)
                            .append(rep(filler, padding))
                            .append(line)
                            .append(rep(filler, padding))
                            .append(border)
                            .append('\n');
        }
        return formatted.toString();
    }
}


text: Ecclesiastical Management System