text:
package org.opencb.cellbase.server.rest.clinical;

import io.swagger.annotations.*;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.cellbase.core.api.ClinicalVariantQuery;
import org.opencb.cellbase.core.api.query.QueryException;
import org.opencb.cellbase.core.common.clinical.ClinicalVariant;
import org.opencb.cellbase.core.exception.CellBaseException;
import org.opencb.cellbase.core.result.CellBaseDataResult;
import org.opencb.cellbase.core.utils.SpeciesUtils;
import org.opencb.cellbase.lib.managers.ClinicalManager;
import org.opencb.cellbase.server.rest.GenericRestWSServer;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;

import static org.opencb.cellbase.core.ParamConstants.*;

/**
 * Created by fjlopez on 06/12/16.
 */
@Path("/{apiVersion}/{species}/clinical")
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "Clinical", description = "Clinical RESTful Web Services API")
public class ClinicalWSServer extends GenericRestWSServer {

    private ClinicalManager clinicalManager;

    public ClinicalWSServer(@PathParam("apiVersion") @ApiParam(name = "apiVersion", value = VERSION_DESCRIPTION,
            defaultValue = DEFAULT_VERSION) String apiVersion,
                            @PathParam("species") @ApiParam(name = "species", value = SPECIES_DESCRIPTION) String species,
                            @ApiParam(name = "assembly", value = ASSEMBLY_DESCRIPTION) @DefaultValue("") @QueryParam("assembly")
                                    String assembly,
                            @ApiParam(name = "dataRelease", value = DATA_RELEASE_DESCRIPTION) @DefaultValue("0") @QueryParam("dataRelease")
                                    int dataRelease,
                            @Context UriInfo uriInfo, @Context HttpServletRequest hsr)
            throws QueryException, IOException, CellBaseException {
        super(apiVersion, species, uriInfo, hsr);
        if (assembly == null) {
            assembly = SpeciesUtils.getDefaultAssembly(cellBaseConfiguration, species).getName();
        }

        clinicalManager = cellBaseManagerFactory.getClinicalManager(species, assembly);
    }

    @GET
    @Path("/variant/search")
    @ApiOperation(httpMethod = "GET", notes = "No more than 1000 objects are allowed to be returned at a time. "
            + DOT_NOTATION_NOTE,
            value = "Retrieves all clinical variants", response = Variant.class, responseContainer = "QueryResponse")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "count", value = COUNT_DESCRIPTION,
                    required = false, dataType = "boolean", paramType = "query", defaultValue = "false",
                    allowableValues = "false,true"),
            @ApiImplicitParam(name = SOURCE_PARAM, value = SOURCE_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = "region", value = REGION_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = SEQUENCE_ONTOLOGY_PARAM, value = SEQUENCE_ONTOLOGY_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = FEATURE_IDS_PARAM, value = FEATURE_IDS_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = TRAITS_PARAM, value = TRAITS_DESCRIPTION,
                    required = false, dataType = "String", paramType = "query"),
//            @ApiImplicitParam(name = ParamConstants.VARIANT_ACCESSIONS_PARAM, value = ParamConstants.VARIANT_ACCESSIONS_DESCRIPTION,
//                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = VARIANT_IDS_PARAM, value = VARIANT_IDS_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = VARIANT_TYPES_PARAM, value = VARIANT_TYPES_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = CONSISTENCY_STATUS_PARAM, value = CONSISTENCY_STATUS_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = CLINICAL_SIGNFICANCE_PARAM, value = CLINICAL_SIGNFICANCE_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = MODE_INHERITANCE_PARAM, value = MODE_INHERITANCE_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = ALLELE_ORIGIN_PARAM, value = ALLELE_ORIGIN_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = "exclude", value = EXCLUDE_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = "include", value = INCLUDE_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = SORT_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query"),
            @ApiImplicitParam(name = "order", value = ORDER_DESCRIPTION,
                    required = false, dataType = "java.util.List", paramType = "query",
                    defaultValue = "", allowableValues="ASCENDING,DESCENDING"),
            @ApiImplicitParam(name = "limit", value = LIMIT_DESCRIPTION,
                    required = false, defaultValue = DEFAULT_LIMIT, dataType = "java.util.List",
                    paramType = "query"),
            @ApiImplicitParam(name = "skip", value = SKIP_DESCRIPTION,
                    required = false, defaultValue = DEFAULT_SKIP, dataType = "java.util.List",
                    paramType = "query")
    })
    public Response getAll() {
        try {
            ClinicalVariantQuery query = new ClinicalVariantQuery(uriParams);
            CellBaseDataResult<ClinicalVariant> queryResults = clinicalManager.search(query);
            return createOkResponse(queryResults);
        } catch (Exception e) {
            return createErrorResponse(e);
        }
    }

    @GET
    @Path("/variant/alleleOriginLabels")
    @ApiOperation(httpMethod = "GET", notes = "",
            value = "Retrieves all available allele origin labels", response = Variant.class,
            responseContainer = "QueryResponse")
    public Response getAlleleOriginLabels() {
        try {
            return createOkResponse(clinicalManager.getAlleleOriginLabels());
        } catch (Exception e) {
            return createErrorResponse(e);
        }
    }

    @GET
    @Path("/variant/modeInheritanceLabels")
    @ApiOperation(httpMethod = "GET", notes = "",
            value = "Retrieves all available mode of inheritance labels", response = Variant.class,
            responseContainer = "QueryResponse")
    public Response getModeInheritanceLabels() {
        try {
            return createOkResponse(clinicalManager.getModeInheritanceLabels());
        } catch (Exception e) {
            return createErrorResponse(e);
        }
    }

    @GET
    @Path("/variant/clinsigLabels")
    @ApiOperation(httpMethod = "GET", notes = "",
            value = "Retrieves all available clinical significance labels", response = Variant.class,
            responseContainer = "QueryResponse")
    public Response getClinicalSignificanceLabels() {
        try {
            return createOkResponse(clinicalManager.getClinsigLabels());
        } catch (Exception e) {
            return createErrorResponse(e);
        }
    }

    @GET
    @Path("/variant/consistencyLabels")
    @ApiOperation(httpMethod = "GET", notes = "",
            value = "Retrieves all available consistency labels", response = Variant.class,
            responseContainer = "QueryResponse")
    public Response getConsistencyLabels() {
        try {
            return createOkResponse(clinicalManager.getConsistencyLabels());
        } catch (Exception e) {
            return createErrorResponse(e);
        }
    }

    @GET
    @Path("/variant/type")
    @ApiOperation(httpMethod = "GET", notes = "",
            value = "Retrieves all available variant types", response = Variant.class,
            responseContainer = "QueryResponse")
    public Response getVariantTypes() {
        try {
            return createOkResponse(clinicalManager.getVariantTypes());
        } catch (Exception e) {
            return createErrorResponse(e);
        }
    }

}


text:
<?php

class Logout extends CI_Controller {

    	public function __construct() {
       	parent::__construct();

     		$this->load->helper('url');
    	}

 	public function index()
	{
		$this->load->view('welcome_message');

		redirect('Login');

	}
}

?>

redpajama_set_name: RedPajamaGithub


text:
/*
 * Created by SharpDevelop.
 * User: Brendan
 * Date: 7/16/2009
 * Time: 6:08 PM
 *
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;

namespace Atlana.Interpret
{
    /// <summary>
    /// Description of ICommandCollection.
    /// </summary>
    public interface ICommandCollection
    {
        string[] Commands{get;}
        Atlana.Interpret.CommandHandler GetCommand(string id);
    }
}


text:
using System;

namespace System.Text.LALR
{
    public class Rule
    {
        public Symbol LHSymbol;
        public string LHSymbolAlias;
        internal int LHSymbolStart;
        public int RuleLineno;
        public Symbol[] RHSymbols;
        public string[] RHSymbolsAlias;
        public int Lineno;
        public string Code;
        internal Symbol PrecedenceSymbol;
        public int ID;
        internal bool CanReduce;
        internal Rule NextLHSymbol;
        public Rule Next;
    }
}


text:
namespace {

const wchar_t kWindowTitle[] = L"Content Shell";
const wchar_t kWindowClass[] = L"CONTENT_SHELL";

const int kButtonWidth = 72;
const int kURLBarHeight = 24;

const int kMaxURLLength = 1024;

static base::StringPiece GetRawDataResource(HMODULE module, int resource_id) {
  void* data_ptr;
  size_t data_size;
  return base::win::GetDataResourceFromModule(module, resource_id, &data_ptr,
                                              &data_size)
      ? base::StringPiece(static_cast<char*>(data_ptr), data_size)
      : base::StringPiece();
}

}  // namespace

namespace content {

HINSTANCE Shell::instance_handle_;

void Shell::PlatformInitialize() {
  _setmode(_fileno(stdout), _O_BINARY);
  _setmode(_fileno(stderr), _O_BINARY);
  INITCOMMONCONTROLSEX InitCtrlEx;
  InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
  InitCtrlEx.dwICC  = ICC_STANDARD_CLASSES;
  InitCommonControlsEx(&InitCtrlEx);
  RegisterWindowClass();
}

base::StringPiece Shell::PlatformResourceProvider(int key) {
  return GetRawDataResource(::GetModuleHandle(NULL), key);
}

void Shell::PlatformExit() {
  std::vector<Shell*> windows = windows_;
  for (std::vector<Shell*>::iterator it = windows.begin();
       it != windows.end(); ++it)
    DestroyWindow((*it)->window_);
}

void Shell::PlatformCleanUp() {
  // When the window is destroyed, tell the Edit field to forget about us,
  // otherwise we will crash.
  ui::SetWindowProc(url_edit_view_, default_edit_wnd_proc_);
  ui::SetWindowUserData(url_edit_view_, NULL);
}

void Shell::PlatformEnableUIControl(UIControl control, bool is_enabled) {
  int id;
  switch (control) {
    case BACK_BUTTON:
      id = IDC_NAV_BACK;
      break;
    case FORWARD_BUTTON:
      id = IDC_NAV_FORWARD;
      break;
    case STOP_BUTTON:
      id = IDC_NAV_STOP;
      break;
    default:
      NOTREACHED() << "Unknown UI control";
      return;
  }
  EnableWindow(GetDlgItem(window_, id), is_enabled);
}

void Shell::PlatformSetAddressBarURL(const GURL& url) {
  std::wstring url_string = UTF8ToWide(url.spec());
  SendMessage(url_edit_view_, WM_SETTEXT, 0,
              reinterpret_cast<LPARAM>(url_string.c_str()));
}

void Shell::PlatformSetIsLoading(bool loading) {
}

void Shell::PlatformCreateWindow(int width, int height) {
  window_ = CreateWindow(kWindowClass, kWindowTitle,
                         WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
                         CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
                         NULL, NULL, instance_handle_, NULL);
  ui::SetWindowUserData(window_, this);

  HWND hwnd;
  int x = 0;

  hwnd = CreateWindow(L"BUTTON", L"Back",
                      WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON ,
                      x, 0, kButtonWidth, kURLBarHeight,
                      window_, (HMENU) IDC_NAV_BACK, instance_handle_, 0);
  x += kButtonWidth;

  hwnd = CreateWindow(L"BUTTON", L"Forward",
                      WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON ,
                      x, 0, kButtonWidth, kURLBarHeight,
                      window_, (HMENU) IDC_NAV_FORWARD, instance_handle_, 0);
  x += kButtonWidth;

  hwnd = CreateWindow(L"BUTTON", L"Reload",
                      WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON ,
                      x, 0, kButtonWidth, kURLBarHeight,
                      window_, (HMENU) IDC_NAV_RELOAD, instance_handle_, 0);
  x += kButtonWidth;

  hwnd = CreateWindow(L"BUTTON", L"Stop",
                      WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON ,
                      x, 0, kButtonWidth, kURLBarHeight,
                      window_, (HMENU) IDC_NAV_STOP, instance_handle_, 0);
  x += kButtonWidth;

  // This control is positioned by PlatformResizeSubViews.
  url_edit_view_ = CreateWindow(L"EDIT", 0,
                                WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT |
                                ES_AUTOVSCROLL | ES_AUTOHSCROLL,
                                x, 0, 0, 0, window_, 0, instance_handle_, 0);

  default_edit_wnd_proc_ = ui::SetWindowProc(url_edit_view_,
                                             Shell::EditWndProc);
  ui::SetWindowUserData(url_edit_view_, this);

  ShowWindow(window_, SW_SHOW);

  SizeTo(width, height);
}

void Shell::PlatformSetContents() {
  SetParent(web_contents_->GetView()->GetNativeView(), window_);
}

void Shell::SizeTo(int width, int height) {
  RECT rc, rw;
  GetClientRect(window_, &rc);
  GetWindowRect(window_, &rw);

  int client_width = rc.right - rc.left;
  int window_width = rw.right - rw.left;
  window_width = (window_width - client_width) + width;

  int client_height = rc.bottom - rc.top;
  int window_height = rw.bottom - rw.top;
  window_height = (window_height - client_height) + height;

  // Add space for the url bar.
  window_height += kURLBarHeight;

  if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpRenderTree)) {
    SetWindowPos(window_, NULL, -window_width, -window_height,
                 window_width, window_height, SWP_NOZORDER);
  } else {
    SetWindowPos(window_, NULL, 0, 0, window_width, window_height,
                 SWP_NOMOVE | SWP_NOZORDER);
  }
}

void Shell::PlatformResizeSubViews() {
  RECT rc;
  GetClientRect(window_, &rc);

  int x = kButtonWidth * 4;
  MoveWindow(url_edit_view_, x, 0, rc.right - x, kURLBarHeight, TRUE);

  MoveWindow(GetContentView(), 0, kURLBarHeight, rc.right,
             rc.bottom - kURLBarHeight, TRUE);
}

void Shell::Close() {
  DestroyWindow(window_);
}

ATOM Shell::RegisterWindowClass() {
  WNDCLASSEX window_class;
  base::win::InitializeWindowClass(
      kWindowClass,
      &Shell::WndProc,
      CS_HREDRAW | CS_VREDRAW,
      0,
      0,
      LoadCursor(NULL, IDC_ARROW),
      NULL,
      MAKEINTRESOURCE(IDC_CONTENTSHELL),
      NULL,
      NULL,
      &window_class);
  instance_handle_ = window_class.hInstance;
  return RegisterClassEx(&window_class);
}

LRESULT CALLBACK Shell::WndProc(HWND hwnd, UINT message, WPARAM wParam,
                                LPARAM lParam) {
  Shell* shell = static_cast<Shell*>(ui::GetWindowUserData(hwnd));

  switch (message) {
    case WM_COMMAND: {
      int id = LOWORD(wParam);
      switch (id) {
        case IDM_NEW_WINDOW:
          CreateNewWindow(
              shell->web_contents()->GetBrowserContext(),
              GURL(), NULL, MSG_ROUTING_NONE, NULL);
          break;
        case IDM_CLOSE_WINDOW:
          DestroyWindow(hwnd);
          break;
        case IDM_EXIT:
          PlatformExit();
          break;
        case IDC_NAV_BACK:
          shell->GoBackOrForward(-1);
          break;
        case IDC_NAV_FORWARD:
          shell->GoBackOrForward(1);
          break;
        case IDC_NAV_RELOAD:
          shell->Reload();
          break;
        case IDC_NAV_STOP:
          shell->Stop();
          break;
      }
      break;
    }
    case WM_DESTROY: {
      delete shell;
      return 0;
    }

    case WM_SIZE: {
      if (shell->GetContentView())
        shell->PlatformResizeSubViews();
      return 0;
    }

    case WM_WINDOWPOSCHANGED: {
      // Notify the content view that the window position of its parent window
      // has been changed by sending window message
      gfx::NativeView native_view = shell->GetContentView();
      if (native_view) {
        SendMessage(native_view, message, wParam, lParam);
      }
      break;
   }
  }

  return DefWindowProc(hwnd, message, wParam, lParam);
}

LRESULT CALLBACK Shell::EditWndProc(HWND hwnd, UINT message,
                                    WPARAM wParam, LPARAM lParam) {
  Shell* shell = static_cast<Shell*>(ui::GetWindowUserData(hwnd));

  switch (message) {
    case WM_CHAR:
      if (wParam == VK_RETURN) {
        wchar_t str[kMaxURLLength + 1];  // Leave room for adding a NULL;
        *(str) = kMaxURLLength;
        LRESULT str_len = SendMessage(hwnd, EM_GETLINE, 0, (LPARAM)str);
        if (str_len > 0) {
          str[str_len] = 0;  // EM_GETLINE doesn't NULL terminate.
          GURL url(str);
          if (!url.has_scheme())
            url = GURL(std::wstring(L"http://") + std::wstring(str));
          shell->LoadURL(url);
        }

        return 0;
      }
  }

  return CallWindowProc(shell->default_edit_wnd_proc_, hwnd, message, wParam,
                        lParam);
}

void Shell::PlatformSetTitle(const string16& text) {
  ::SetWindowText(window_, text.c_str());
}

}  // namespace content


text:
// -----------------------------------------------------------------------
// <copyright file="DateTimeExtensions.cs" company="Nodine Legal, LLC">
// Licensed to Nodine Legal, LLC under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  Nodine Legal, LLC licenses this file
// to you 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.
// </copyright>
// -----------------------------------------------------------------------

namespace OpenLawOffice.Data
{
    using System;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public static class DateTimeExtensions
    {
        public static DateTime ToSystemTime(this DateTime value)
        {
            TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(Common.Settings.Manager.Instance.System.Timezone);
            return TimeZoneInfo.ConvertTimeFromUtc(value, tzi);
        }

        public static DateTime? ToSystemTime(this DateTime? value)
        {
            if (!value.HasValue) return null;
            TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(Common.Settings.Manager.Instance.System.Timezone);
            return TimeZoneInfo.ConvertTimeFromUtc(value.Value, tzi);
        }

        public static DateTime ToDbTime(this DateTime value)
        {
            return TimeZoneInfo.ConvertTimeToUtc(value);
        }

        public static DateTime? ToDbTime(this DateTime? value)
        {
            if (!value.HasValue) return null;
            return TimeZoneInfo.ConvertTimeToUtc(value.Value);
        }
    }
}


text:
#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package}.${toolNameShort}.service;

import static org.junit.Assert.*;

import org.apache.log4j.Logger;
import org.junit.*;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;

/**
 * Unit test for the ${fileNamePrefix}Service
 * @author Kuali Mobility Team (mobility.collab@kuali.org)
 * @since ${version}
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:/${fileNamePrefix}SpringBeans.xml")
public class ${fileNamePrefix}ServiceImplTest {
	private static final Logger LOG = Logger.getLogger( ${fileNamePrefix}ServiceImplTest.class );

	@Resource(name="${toolNameShort}Service")
	private ${fileNamePrefix}Service service;

	@BeforeClass
	public static void setUpClass() throws Exception {
	}

	@AfterClass
	public static void tearDownClass() throws Exception {
	}

	@Before
	public void setUp() {
	}

	@After
	public void tearDown() {
	}

	@Test
	public void test() {
		fail("Not implemented yet.");
	}

	public void setDao(${fileNamePrefix}Service service) {
			this.service = service;
	}

	public ${fileNamePrefix}Service getService() {
			return service;
	}
}


text:
<html>
<body>
Reports usage of multiple urls per repository(maven or ivy) block.
The problem is that no more than one url will be picked up for the repo and others will be ignored.
</body>
</html>


text:
package com.acervera.osmfacts.fact6

import java.io.FileInputStream

import com.acervera.osm4scala.EntityIterator
import com.acervera.osm4scala.model.{NodeEntity, OSMEntity, WayEntity}
import io.tmos.arm.ArmMethods._
import org.roaringbitmap.longlong.Roaring64NavigableMap
import org.slf4j.LoggerFactory

import scala.annotation.tailrec

object Fact6Driver {

  var log = LoggerFactory.getLogger("com.acervera.osmfacts.fact6.Fact6Driver")

  /**
    *
    * @param args Input
    */
  def main(args: Array[String]): Unit = {
    val input = args(0)

    log.info(s"Checking presence order of ids from [$input]. The party has begun!!!")
    searchFirstNotFound(args(0)) match {
      case Some((entity, id)) => println(s"Node $id not found at the moment, but used in the way ${entity.id}")
      case None               => println("All nodes found before to be used.")
    }
  }

  @tailrec
  private def rec(ids: Roaring64NavigableMap, entities: EntityIterator): Option[(OSMEntity, Long)] = {

    if (entities.hasNext) {
      entities.next() match {
        case osmEntity: NodeEntity =>
          ids.add(osmEntity.id)
          rec(ids, entities)
        case osmEntity: WayEntity =>
          osmEntity.nodes.find(!ids.contains(_)) match {
            case Some(id) => Some((osmEntity, id))
            case _        => rec(ids, entities)
          }
        case _ => rec(ids, entities)
      }
    } else {
      None
    }
  }

  def searchFirstNotFound(pbfFilePath: String): Option[(OSMEntity, Long)] =
    for {
      pbfIS <- manage(new FileInputStream(pbfFilePath))
    } yield {
      rec(new Roaring64NavigableMap(), EntityIterator.fromPbf(pbfIS))
    }

}


text:
""" Class for the Methods """

#################################
import pyvisa as visa   # interface with NI-Visa
import numpy as np  # module for array manipulation
import matplotlib.pyplot as plt
import os   # module for general OS manipulation
import time # module for time related funtions
import pandas as pd # module for general data analysis
import pylef
################################

#bibliotecas para atualizacoa de grafico
from IPython.core.display import clear_output
from IPython.display import display, Javascript

'''
--------------------------
Funções para graficar ao vivo e adquirir dados
NÃO ALTERE NADA NESTA CÉLULA
--------------------------
'''
#***********************************************
#***********************************************
def plot_bode(freq,phase,T,T_dB,spacing='log'):
    '''
    Função para graficar transmistância e fase
    ===============
    Uso simples:
    >>> figure = plot_bode(freq,phase,T,T_dB,spacing)
    entrada:
    --------
    freq: vetor de frequências (lista ou numpy.array)
    phase: vetor de fases (lista ou numpy.array)
    T: vetor de transmitância linear (lista ou numpy.array)
    T_dB: vetor de transmitância em decibéis (lista ou numpy.array)
    spacing (opcional): 'linear' (espaçamento linear) ou 'log' (espaçamento logarítmico); por padrao o espaçamento é linear
    --------
    saída:
    figure:objeto gráfico do Matplotlib
    '''
    #Identificando se é linear ou log
    npt = len(T_dB)
    fig, ax = plt.subplots(2, sharex=True)
    if spacing=='log':
        y=T_dB
        y_label='Transmissão (dB)'
    elif spacing=='linear':
        y=T
        y_label='Transmissão'
    #-----------------------------------
    #TRANSMISSION PLOT
    #-----------------------------------
    ax[0] = plt.subplot(211)  # define um eixo
    ax[0].plot(freq[0:npt], y[0:npt], 'ro')   # plota a transmissão
    ax[0].set_xscale(spacing)   # seta a escala de x para logaritmica
    # Por que não usamos escala log no eixo y também?
    #ax[0].set_xlabel('frequência (Hz)')   # seta escala do eixo x
    ax[0].set_ylabel(y_label)   # seta escala do eixo y
    plt.xlim((freq.min(),freq.max()))
    #-----------------------------------
    #PHASE PLOT
    #-----------------------------------
    ax[1] = plt.subplot(212)  # define um eixo
    ax[1].plot(freq[0:npt], phase[0:npt], 'bo')   # plota a transmissão
    ax[1].set_xscale(spacing)   # seta a escala de x para logaritmica
    # Por que não usamos escala log no eixo y também?
    ax[1].set_xlabel('frequência (Hz)')   # seta escala do eixo x
    ax[1].set_ylabel('Fase (graus)')   # seta escala do eixo y
    plt.xlim((freq.min(),freq.max()))
    plt.ylim((-180,180))
    #------------------------------------
    clear_output(True)
    display(fig)
    plt.close()
    return fig
#***********************************************
#***********************************************
def sweep_frequency(freq0, freq1, Nfreq, path = '', fname='', spacing = 'linear', average = 4):
    '''
    Função para realizar um sweep e fazer gráfico
    ===============
    Uso simples:
    >>> figure, freq, vpp1, vpp2, phase = sweep_frequency(freq0,freq1,Nfreq,spacing = 'linear')
    figure: figura
    freq0: frequência inicial (Hz)
    freq1: frequencia final (Hz)
    Nfreq: número de pontos no vetor de frequências
    spacing (opcional): 'linear' (espaçamento linear) ou 'log' (espaçamento logarítmico)
    average: número de médias a serem realizadas
    '''
    # display(Javascript("""
    # require(
    # ["base/js/dialog"],
    # function(dialog) {
    #     dialog.modal({
    #         title: 'Hello world',
    #         body: 'Hi, lorem ipsum and such',
    #         buttons: {
    #             'kthxbye': {}
    #             }
    #         });
    #     }
    # );"""))

    func_gen = pylef.BK4052()  # definição do gerador de funções
    scope = pylef.TektronixTBS1062()  # definição do osciloscópio
    #------------------
    #constroi vetor de frequencias
    #------------------
    if spacing == 'linear':
        freq = np.linspace(freq0, freq1, Nfreq, endpoint = True)  # varredura logaritmica
    elif spacing == 'log':
        freq = np.logspace(np.log10(freq0), np.log10(freq1), Nfreq, endpoint = True)  # varredura logaritmica
    else:
        raise ValueError('O espaçamento entre os pontos deve ser linear ou log')
    #### Aquisição de dados!! ####
    scope.set_average_number(average)  # ajusta o número de médias
    scope.set_average()    # turn average ON
    #-----------------
    Vpp1, Vpp2 = [], []    # listas para guardar as variáveis
    #phase1, phase2 = [], []    # listas para guardar as variáveis
    phase = []   # listas para guardar as variáveis
    ### aquisição de dados no gerador com varredura de frequência
    scope.write('MEASUREment:MEAS1:TYPE NONE')
    scope.write('MEASUREment:MEAS2:TYPE NONE')
    scope.write('MEASUREment:MEAS3:TYPE NONE')
    scope.write('MEASUREment:MEAS4:TYPE NONE')
    scope.write('MEASUREment:MEAS5:TYPE NONE')
    for m, freqP in enumerate(list(freq)):  # loop de aquisição
        #print('Medida ' + str(m + 1))
        print('Frequencia atual={:2g} Hz'.format(freq[m]))
        start=time.time()
        ### ajuste dos instrumentos
        func_gen.ch1.set_frequency(freqP)   # muda a frequência
        periodP = 1./freqP   # período da onda
        scope.set_horizontal_scale(periodP/4.)  # escala horizontal = 1/4 período (2.5 oscilações em tela)
        scope.ch1.set_smart_scale()    #  rescala o canal 1
        scope.ch2.set_smart_scale()    #  rescala o canal 2
        ### aquisição de dados
        Vpp1.append(scope.ch1.measure.Vpp()) # acumula a medida do Vpp no canal 1
        phase.append(-scope.ch1.measure.phase()) # acumula a medida da fase no canal 1
        Vpp2.append(scope.ch2.measure.Vpp())  # acumula a medida do Vpp no canal 2
        #---------plotting stuff-------
        T = (np.array(Vpp2)/np.array(Vpp1))**2   # cálculo da transmissão
        T_dB = 10*np.log10(T)  # transmissão em dB
        # plota o diagrama de bode para a transmissão e exporta em png
        fig = plot_bode(freq,phase,T,T_dB,spacing)
        #-------
    print('Fim! Tempo total de medida={:2g} s'.format(time.time()-start))
    Vpp1 = np.array(Vpp1)  # convete a lista em array
    Vpp2 = np.array(Vpp2)  # convete a lista em array
    phase = np.array(phase)  # convete a lista em array
    ''' encerra a comunicação osciloscópio e o gerador de funções '''
    scope.close()
    func_gen.close()
    ''' organizando dados'''
    # calculando a transmitância
    T = Vpp2 / Vpp1  # cálculo da transmissão
    T_dB = 20 * np.log10(T)  # transmissão em dB
    # gerando tabelas
    dados = pd.DataFrame()  # inicializa um dataframe do pandas
    dados['Vpp1 (V)'], dados['Vpp2 (V)'] = Vpp1, Vpp2
    dados['fase (Ch2-Ch1) (graus)'] = phase
    dados['frequencia (Hz)'], dados['T'], dados['T_dB'] = freq, T, T_dB
    ## parametros de varredura
    path0 = '/Users/usuario/F429/'  # pasta onde salvar todos os arquivos
    datapasta = time.strftime('dia_%D_hora_%H', time.localtime(time.time())).replace('/','-')
    path = path0+datapasta
    if fname=='':
        fname = 'sweep'
    ##--------------------------------------------------------
    # Cria a pasta no computador, veja a variável PATH
    try:
        os.makedirs(path)  # make new directory unless it already exists
    except OSError:
        if not os.path.isdir(path):
            raise
    # qual pasta estou?
    print('Pasta dos arquivos:', os.path.abspath(path))
    time_suf = time.strftime('_%H_%M_%S', time.localtime(time.time()))
    nome_fig = os.path.join(path,fname + '_bode' + time_suf + '.png')
    nome_csv = os.path.join(path,fname + '_dados' + time_suf + '.dat')
    # Salvando
    fig.savefig(nome_fig, bbox_inches='tight')  # salva figura na pasta de trabalho
    dados.to_csv(nome_csv, sep='\t', index=False)  # \t significa que o separador é uma tabulação, index=False remove os indices da coluna
    return fig, dados


text:
/*
 * Created on 05-Jan-2006
 */
package uk.org.ponder.rsf.flow.support;

import java.util.Collections;

import uk.org.ponder.rsf.flow.FlowIDHolder;
import uk.org.ponder.rsf.state.LockGetter;
import uk.org.ponder.stringutil.StringList;
import uk.org.ponder.util.Logger;
import uk.org.ponder.util.RunnableInvoker;

/**
 * An alteration wrapper designed to prevent simultaneous access to flow or
 * scoped data. Only incurs a synchronized overhead if there is actually an
 * active flow or scope for the current request, i.e. in the case of a scope, it
 * successfully restored a bean from the scope. If another request in in the
 * flow, this wrapper will simply block - in practice this is no real burden
 * since this condition could only be triggered by multiple simultaneous
 * requests from the same user/browser. Could be a liability however if under
 * some (possibly failure) condition, normal request handling might take an
 * unbounded time - in this case you may want to replace this wrapper with an
 * implementation performing wait/notify with a timeout.
 * <p>
 * If operating in a clustered environment where handling of different requests
 * belonging to the same flow cannot be guaranteed to be passed to the same JVM,
 * you will certainly require to replace this implementation.
 *
 * @author Antranig Basman (amb26@ponder.org.uk)
 *
 */

public class BasicScopedAlterationWrapper implements RunnableInvoker {
  private LockGetter lockgetter;
  private FlowIDHolder flowidholder;
  private StringList scopelocks;

  public void setLockGetter(LockGetter flowlockgetter) {
    this.lockgetter = flowlockgetter;
  }

  public void setFlowIDHolder(FlowIDHolder flowidholder) {
    this.flowidholder = flowidholder;
  }

  public void setScopeLocks(StringList scopelocks) {
    this.scopelocks = scopelocks;
  }

  public void invokeRunnable(Runnable towrap) {
    String flowtoken = flowidholder.getFlowToken();
    final StringList completelocks = new StringList();
    if (flowtoken != null) {
      completelocks.add(flowtoken);
    }
    completelocks.addAll(scopelocks);
    if (completelocks.size() == 0) {
      towrap.run();
      return;
    }
    Collections.sort(completelocks); // Avoid potential Dedlocks!
    try {
      lockUUPP(completelocks, towrap, 0);
    }
    finally {
      lockgetter.returnLock(flowtoken);
    }
  }

  private void lockUUPP(StringList completelocks, Runnable towrap, int i) {
    if (i >= completelocks.size()) {
      towrap.run();
    }
    else {
      String lockname = completelocks.stringAt(i);
      Object lock = lockgetter.getLock(lockname);
      Logger.log.info("Acquiring lock " + lock + " for scope name " + lockname);
      synchronized (lock) {
        lockUUPP(completelocks, towrap, i + 1);
      }
    }
  }

}


text:
#ifndef DISPLAY_FACTORY_H
#define DISPLAY_FACTORY_H

#include "rviz/display.h"
#include "rviz/pluginlib_factory.h"

#include <QIcon>
#include <QSet>
#include <QString>
#include <QMap>

namespace rviz
{

class DisplayFactory: public PluginlibFactory<Display>
{
public:
  DisplayFactory();

  /** @brief Get all supported message types for the given class id. */
  virtual QSet<QString> getMessageTypes( const QString& class_id );

protected:
  /** @brief Overridden from PluginlibFactory<Display> to set the icon of the Display. */
  virtual Display* makeRaw( const QString& class_id, QString* error_return = NULL );

  QMap< QString, QSet<QString> > message_type_cache_;
};

} // end namespace rviz

#endif // DISPLAY_FACTORY_H


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Folia geobot. phytotax. 10: 425 (1975)

#### Original name
Byssoloma fadenii Vezda

### Remarks
null


text:
package org.vitrivr.cthulhu.rest;

import static spark.Spark.delete;
import static spark.Spark.get;
import static spark.Spark.port;
import static spark.Spark.post;
import static spark.Spark.put;
import static spark.Spark.staticFileLocation;
import static spark.Spark.stop;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.servlet.MultipartConfigElement;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.vitrivr.cthulhu.jobs.CineastJob;
import org.vitrivr.cthulhu.jobs.Job;
import org.vitrivr.cthulhu.jobs.util.StreamUtils;
import org.vitrivr.cthulhu.scheduler.CthulhuScheduler;
import org.vitrivr.cthulhu.worker.Worker;

public class CthulhuRest {

  private static final Logger LOGGER = LogManager.getLogger("r.m.api");
  private String workspace;
  private CthulhuScheduler ms;
  private ObjectMapper mapper;
  private Gson gson;

  /**
   * Constructor that instantiates the Json mapper.
   */
  public CthulhuRest() {
    this.mapper = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .registerModule(new Jdk8Module());
  }

  /**
   * Initializes all the REST services for this agent (worker/coordinator).
   *

   * If no port can be determined to listen on, an exception will be thrown
   *

   *
   * @param ms This is the scheduler that is in charge of managing microservice REST calls
   * @param prop This is a properties object with all runtime properties of the agent
   *     (worker/coord)
   */
  public void init(CthulhuScheduler ms, Properties prop) {
    this.gson = new Gson();
    this.ms = ms;
    LOGGER.info("Creating REST paths");
    String sf = prop.getProperty("staticfiles");
    workspace = prop.getProperty("workspace");
    int port = Integer.parseInt(prop.getProperty("port"));
    setupRestCalls(sf, port);
    LOGGER.info("Ready!");
  }

  /**
   * Stops the REST service.
   *

   * Stops the Jetty server that is in charge of running the REST service.
   *

   */
  public void stopServer() {
    stop();
  }

  private void setupRestCalls(String staticFilesDir, int listenPort) {
    port(listenPort);
    LOGGER.info("Static files are served from: " + staticFilesDir);
    staticFileLocation(staticFilesDir);
    post("/jobs", (req, res) -> {
      Job j = ms.registerJob(req.body());
      if (j == null) {
        res.status(400);
      }
      return "";
    });
    post("/jobs/cineast", (req, res) -> {
      Job requestJob = mapper.readValue(req.body(), CineastJob.class);
      if (requestJob == null) {
        res.status(400);
      }
      ms.registerJob(requestJob);
      return "";
    });
    get("/jobs", (req, res) -> ms.getJobs());
    get("/jobsjackson", (req, res) -> mapper.writeValueAsString(ms.getJobs()));
    get("/jobs/:id", (req, res) -> {
      String id = req.params(":id");
      if (id.isEmpty()) {
        res.status(400);
      }
      return ms.getJobs(id);
    });
    put("/jobs", (req, res) -> {
      Job old = ms.updateJob(req.body());
      if (old == null) {
        res.status(400);
      }
      return "";
    });
    delete("/jobs/:id", (req, res) -> {
      String id = req.params(":id");
      boolean force = false;
      if (req.queryParams("force") != null) {
        force = Boolean.parseBoolean(req.queryParams("force"));
      } else if (req.params("force") != null) {
        force = Boolean.parseBoolean(req.params("force"));
      }
      Job job;
      try {
        job = ms.deleteJob(id, force);
      } catch (Exception e) {
        res.status(400);
        return e.getMessage();
      }
      if (job == null) {
        res.status(400);
      }
      return "";
    });
    post("/workers", (req, res) -> {
      String address = req.queryParams("address");
      int port = Integer.parseInt(req.queryParams("port"));
      String ip = req.ip();
      if (address == null || address.isEmpty()) {
        address = ip;
      }
      int st = ms.registerWorker(address, port);
      if (st != 0) {
        res.status(400);
      }
      return "";
    });
    get("/workers", (req, res) -> ms.getWorkers());
    get("/workers/:id", (req, res) -> {
      String id = req.params(":id");
      if (id.isEmpty()) {
        res.status(400);
      }
      return ms.getWorkers(id);
    });
    delete("/workers/:id", (req, res) -> {
      String id = req.params(":id");
      Worker worker = ms.deleteWorker(id);
      if (worker == null) {
        res.status(400);
      }
      return "";
    });
    post("/data/:file", (req, res) -> {
      String fname = req.params(":file");
      System.out.println("Receiving a file back: " + fname);
      File fout = new File(workspace, fname);
      if (fout.exists()) {
        System.out.println("File exists. Not saving");
        res.status(400);
        //return "";
      }
      req.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
      try (InputStream is = req.raw().getPart("file").getInputStream()) {
        // Use the input stream to create a file
        FileOutputStream fos = new FileOutputStream(fout);
        StreamUtils.copy(is, fos);
      }
      return "";
    });
    get("/data/:file", (req, res) -> {
      String fname = req.params(":file");
      String acceptHeader = fetchAcceptHeader(fname);
      if (acceptHeader != null) {
        res.header("Content-Type", acceptHeader);
      }
      InputStream is;
      try {
        File infile = new File(workspace, fname);
        is = new FileInputStream(infile);
        //res.type(getContentType(fname));
        res.status(200);

        byte[] buf = new byte[1024];
        OutputStream os = res.raw().getOutputStream();
        int count;
        while ((count = is.read(buf)) >= 0) {
          os.write(buf, 0, count);
        }
        is.close();
        os.close();
      } catch (IOException e) {
        e.printStackTrace();
        return null;
      }
      return "";
    });
  }

  private static String fetchAcceptHeader(String fileName) {
    String[] nameParts = fileName.split("\\.");
    String fileType = nameParts[nameParts.length - 1].toLowerCase();
    switch (fileType) {
      case "gif":
      case "png":
      case "bmp":
      case "jpg":
      case "jpeg":
        return "image/" + fileType;
        case "mp4":
      case "3gpp":
        return "video/" + fileType;
      case "avi":
        return "video/x-msvideo";
      default:
        return null;
    }
  }
}


text:
<?php
namespace StaticKidz\BedcaAPI\Tests;

use PHPUnit_Framework_TestCase;
use StaticKidz\BedcaAPI\BedcaClient;

/**
 * @property BedcaClient api
 */
class TestFoodGroups extends PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        $this->api = new BedcaClient();
    }
}


text:
# webham/drupalrest

[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
[![Build Status][ico-build]][link-build]
[![Coverage Status][ico-scrutinizer]][link-scrutinizer]
[![Quality Score][ico-code-quality]][link-code-quality]
[![Total Downloads][ico-downloads]][link-downloads]

This is a drupal rest component that currently works with drupal 7 instance eqiped with the services module. You should first setup
the drupal application and then with the help of this package you should be able to access the data via the user name and the password
of a created user.

## Install

Via Composer

``` bash
$ composer require webham/drupalrest
```

## Usage

``` php

$request = new DrupalRest('http://yoursite.com/', '/rest', 'user', 'pass', 0);

print_r($request);

/**
 * Login.
 */
$request->login();
print_r($request);

```

## Change log

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

## Testing

``` bash
$ composer test
```

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

## Security

If you discover any security related issues, please email nikolay.r.borisov@gmail.com instead of using the issue tracker.

## Credits

- [Nikolay Borisov][link-author]

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

[ico-version]: https://img.shields.io/packagist/v/:vendor/:package_name.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/flesheater/drupal_rest_server_class.svg?style=flat-square
[ico-build]: https://scrutinizer-ci.com/g/flesheater/drupal_rest_server_class/badges/build.png?b=master
[ico-code-quality]: https://img.shields.io/scrutinizer/g/flesheater/drupal_rest_server_class.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/:vendor/:package_name.svg?style=flat-square

[link-packagist]: https://packagist.org/packages/:vendor/:package_name
[link-scrutinizer]: https://scrutinizer-ci.com/g/flesheater/drupal_rest_server_class/code-structure
[link-build]: https://scrutinizer-ci.com/g/flesheater/drupal_rest_server_class/
[link-code-quality]: https://scrutinizer-ci.com/g/flesheater/drupal_rest_server_class
[link-downloads]: https://packagist.org/packages/:vendor/:package_name
[link-author]: https://github.com/flesheater
[link-contributors]: ../../contributors


text:
require 'chef/dsl/recipe'
require 'chef/dsl/data_query'
require 'chef/dsl/platform_introspection'
require 'chef/dsl/include_recipe'
require 'chef/dsl/registry_helper'
require 'chef/dsl/reboot_pending'

require 'chef/mixin/from_file'

require 'chef/mixin/deprecation'

class Chef
  # == Chef::Recipe
  # A Recipe object is the context in which Chef recipes are evaluated.
  class Recipe

    include Chef::DSL::DataQuery
    include Chef::DSL::PlatformIntrospection
    include Chef::DSL::IncludeRecipe
    include Chef::DSL::Recipe
    include Chef::DSL::RegistryHelper
    include Chef::DSL::RebootPending

    include Chef::Mixin::FromFile
    include Chef::Mixin::Deprecation

    attr_accessor :cookbook_name, :recipe_name, :recipe, :params, :run_context

    # Parses a potentially fully-qualified recipe name into its
    # cookbook name and recipe short name.
    #
    # For example:
    #   "aws::elastic_ip" returns [:aws, "elastic_ip"]
    #   "aws" returns [:aws, "default"]
    #--
    # TODO: Duplicates functionality of RunListItem
    def self.parse_recipe_name(recipe_name)
      rmatch = recipe_name.match(/(.+?)::(.+)/)
      if rmatch
        [ rmatch[1].to_sym, rmatch[2] ]
      else
        [ recipe_name.to_sym, "default" ]
      end
    end

    def initialize(cookbook_name, recipe_name, run_context)
      @cookbook_name = cookbook_name
      @recipe_name = recipe_name
      @run_context = run_context
      # TODO: 5/19/2010 cw/tim: determine whether this can be removed
      @params = Hash.new
      @node = deprecated_ivar(run_context.node, :node, :warn)
    end

    # Used in DSL mixins
    def node
      run_context.node
    end

    # Used by the DSL to look up resources when executing in the context of a
    # recipe.
    def resources(*args)
      run_context.resource_collection.find(*args)
    end

    # This was moved to Chef::Node#tag, redirecting here for compatability
    def tag(*tags)
      run_context.node.tag(*tags)
    end

    # Returns true if the node is tagged with *all* of the supplied +tags+.
    #
    # === Parameters
    # tags<Array>:: A list of tags
    #
    # === Returns
    # true<TrueClass>:: If all the parameters are present
    # false<FalseClass>:: If any of the parameters are missing
    def tagged?(*tags)
      tags.each do |tag|
        return false unless run_context.node[:tags].include?(tag)
      end
      true
    end

    # Removes the list of tags from the node.
    #
    # === Parameters
    # tags<Array>:: A list of tags
    #
    # === Returns
    # tags<Array>:: The current list of run_context.node[:tags]
    def untag(*tags)
      tags.each do |tag|
        run_context.node.normal[:tags].delete(tag)
      end
    end

  end
end


text:
/* global describe, expect, test */

const Reader = require('../../src/reader');

describe('Reader', () => {
  describe('Reader.ap', () => {
    test('it should apply a regular function in an Apply and return a new Reader with the result', () => {
      const reader = Reader.of('foo');
      const toBaz = Reader.of(() => 'baz');

      expect(Reader.ap(toBaz, reader).run('bar')).toBe('baz');
    });
  });

  describe('Reader#ap', () => {
    test('it should apply a regular function in an Apply and return a new Reader with the result', () => {
      const reader = Reader.of('foo');
      const toBaz = Reader.of(() => 'baz');

      expect(reader.ap(toBaz).run('bar')).toBe('baz');
    });
  });
});


text:
var numCorrect = 0;

var questions = ['Do I have a cat named Minerva?',
'Do I have a Corgi named Sherwood?',
'Do I have a little brother?',
'Is this my first class at CodeFellows?',
'Did I train to be a Dietitian in college?'];

var correctAnswer = ['Y', 'N', 'Y', 'N', 'Y'];

var response = [['Correct! I have a cat named Minerva.', 'Incorrect! I have a cat named Minerva.'],
['Correct! I do not have a Corgie...YET!!!!', 'Incorrect! I do not have a Corgie...YET!!!!'],
['Correct! Skyler is my little bro.', 'Incorrect! Skyler is my little bro.'],
['Correct! I took classes last year!', 'Incorrect! I took classes last year!'],
['Correct! I am a Registered Dietitian.', 'Incorrect! I am a Registered Dietitian.']];

function oneToFive(question, solution, userSees) {
  for (var i = 0; i < question.length; i++) {
    var answer = prompt(question[i]);
    if (answer.toUpperCase() === solution[i]) {
      alert(userSees[i][0]);
      numCorrect++;
      console.log(userSees[i][0]);
    } else {
      alert(userSees[i][1]);
      console.log(userSees[i][1]);
    }
  }
}

var name = prompt('What is your name?');
console.log('Welcome ' + name + ' to my little quiz.');
alert('Hello, ' + name + ' lets play this quiz to see how well you know me!');
alert('For the first five questions, please answer with a simple Y or N');

oneToFive(questions, correctAnswer, response);

alert('A different format for the next question. The rules here change a bit. For this next question, I will present the question and you will have four guesses to get it right. Please enter a numerical value between 1 - 20 Good Luck!');

var qSixCounter = 1;
var max = 4;
var answer6;
var numJobs = 4;
while (qSixCounter <= max) {
  answer6 = prompt('How many jobs have I had?');
  if (isNaN(answer6) === false) {
    if (parseInt(answer6) === numJobs) {
      alert('Correct, I have had four jobs! You got it right on your attempt # ' + qSixCounter + '!' );
      console.log('Yah it only too you ' + qSixCounter + ' tries!');
      numCorrect++;
      qSixCounter = max + 1;
    } else {
      if (parseInt(answer6) >= numJobs){
        alert('Incorrect. That was too high.');
      } else if (parseInt(answer6) <= numJobs) {
        alert('Incorrect. Too low.');
      }
      console.log('That was attempt # ' + qSixCounter + '. You have ' + (max - qSixCounter) + ' tries left.' );
      if (qSixCounter === max) {
        alert('Sorry, you did not quess correctly. I have had 4 jobs.');
        console.log('FAILLLLLLLLLLL');
      }
      qSixCounter++;
    }
  } else {
    alert('That is not a valid number. Please try again.');
    answer6;
  }
}

var countries = ['belize', 'france', 'germany', 'hungary', 'liechtenstein', 'italy', 'switzerland', 'poland'];
var countriesCombined = countries.join(', ');
var tries = 6;
var qSevenCounter = 1;
var isCorrect = false;

alert('For this last question, please type in a word for your answer.');

while (qSevenCounter <= tries) {
  var answer7 = prompt('Name a country I have visited.').toLowerCase();
  for (var i = 0; i < countries.length; i++) {
    console.log(countries[i]);
    if (answer7 === countries[i]) {
      alert('Correct. I have been to ' + answer7 + '. Here is a partial list of countries I have visited: ' + countriesCombined);
      console.log(countriesCombined);
      numCorrect++;
      isCorrect = true;
      break;
    } else {
      console.log('current guess is not at ' + i + ' continuing to check');
    }
  }
  if (isCorrect === false) {
    alert('Incorrect. Please try again.');
    console.log('Nope, you have ' + (tries - qSevenCounter) + ' left.');
    qSevenCounter++;
    if (qSevenCounter === (tries + 1)) {
      alert('Nope. Here is a partial list of countries I have visited: ' + countriesCombined);
      console.log('FAILL');
      break;
    }
  } else {
    break;
  }
}

alert('You got ' + numCorrect + ' answers right ' + name + '. Congrats!');

var endOfQuiz = alert(name + ' thanks for playing. Hope you enjoy my page!');
console.log('Hello ' + name + ', thanks for visiting and playing around with my basic JavaScript program! Improvements coming soon!!');


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/simple_sever"
        android:onClick="onSimpleServerBtnClick" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/custom_sever"
        android:onClick="onCustomServerBtnClick"  />

</LinearLayout>


text:
package hipi.tool;

import hipi.image.ImageHeader.ImageType;
import hipi.imagebundle.AbstractImageBundle;
import hipi.imagebundle.HipiImageBundle;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;

public class CreateHipiImageBundle {

  public static void main(String[] args) throws IOException
  {
      if (args.length < 2) {
	  System.out.println("Usage: hibimport <input directory on local file system> <output HIB file on HDFS>");
	  System.exit(0);
      }

      File folder = new File(args[0]);
      File[] files = folder.listFiles();

      Configuration conf = new Configuration();
      HipiImageBundle hib = new HipiImageBundle(new Path(args[1]), conf);
      hib.open(AbstractImageBundle.FILE_MODE_WRITE, true);

      for (File file : files)
	  {
	      FileInputStream fis = new FileInputStream(file);
	      String fileName = file.getName().toLowerCase();
	      String suffix = fileName.substring(fileName.lastIndexOf('.'));
	      if (suffix.compareTo(".jpg") == 0 || suffix.compareTo(".jpeg") == 0)
		  {
		      hib.addImage(fis, ImageType.JPEG_IMAGE);
		  }
	      else if (suffix.compareTo(".png") == 0)
		  {
		      hib.addImage(fis, ImageType.PNG_IMAGE);
		  }
	      System.out.println(" ** added: " + fileName);
	  }

      hib.close();

      System.out.println("Created: " + args[1] + " and " + args[1] + ".dat");
  }

}


text:
package com.advancedpwr.record;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Set;

import junit.framework.TestCase;

public class ClassWriterTest extends TestCase
{
	ClassWriter writer;
	StringWriter out;

	@Override
	protected void setUp() throws Exception
	{
		writer = new ClassWriter()
		{

			protected Set<Class> classes()
			{
				return null;
			}

			protected ClassDescriptor createDefaultDescriptor()
			{
				return null;
			}

			protected void writeObjectBuilderMethod()
			{
			}};
		out = new StringWriter();
		writer.setWriter( new PrintWriter( out ) );
	}

	public void testWriteLine()
	{
		writer.writeLine( "package com.advancedpwr.foo" );
		assertResult( "package com.advancedpwr.foo;\n" );
	}

	public void assertResult( String inString )
	{
		assertEquals( inString, out.toString().replaceAll( "\r\n", "\n" ) );
	}
	public void testWrite()
	{
		writer.write( "if ( foo == null )" );
		assertResult( "if ( foo == null )\n");
	}

	public void testOpenCloseBrace()
	{
		writer.openBrace();
		writer.write( "if ( foo == null )" );
		writer.openBrace();
		writer.writeLine( "bar" );
		writer.closeBrace();
		writer.closeBrace();

		assertResult( "{\n" +
				"\tif ( foo == null )\n" +
				"\t{\n" +
				"\t\tbar;\n" +
				"\t}\n" +
				"}\n");

		try
		{
			writer.closeBrace();
			fail( "Should have thrown an exception");
		}
		catch (Exception e)
		{
			assertTrue( e instanceof ClassWriterException );
		}
	}

	public void testSetClassName()
	{
		writer.setClassName( "com.company.BusinessFactory" );
		assertEquals( "com.company", writer.getDescriptor().getPackageName() );
		assertEquals( "BusinessFactory", writer.getDescriptor().getClassName() );
	}

}


text:
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy

class ErrorY(_BaseTraceHierarchyType):

    # class properties
    # --------------------
    _parent_path_str = "scattergl"
    _path_str = "scattergl.error_y"
    _valid_props = {
        "array",
        "arrayminus",
        "arrayminussrc",
        "arraysrc",
        "color",
        "symmetric",
        "thickness",
        "traceref",
        "tracerefminus",
        "type",
        "value",
        "valueminus",
        "visible",
        "width",
    }

    # array
    # -----
    @property
    def array(self):
        """
        Sets the data corresponding the length of each error bar.
        Values are plotted relative to the underlying data.

        The 'array' property is an array that may be specified as a tuple,
        list, numpy array, or pandas Series

        Returns
        -------
        numpy.ndarray
        """
        return self["array"]

    @array.setter
    def array(self, val):
        self["array"] = val

    # arrayminus
    # ----------
    @property
    def arrayminus(self):
        """
        Sets the data corresponding the length of each error bar in the
        bottom (left) direction for vertical (horizontal) bars Values
        are plotted relative to the underlying data.

        The 'arrayminus' property is an array that may be specified as a tuple,
        list, numpy array, or pandas Series

        Returns
        -------
        numpy.ndarray
        """
        return self["arrayminus"]

    @arrayminus.setter
    def arrayminus(self, val):
        self["arrayminus"] = val

    # arrayminussrc
    # -------------
    @property
    def arrayminussrc(self):
        """
        Sets the source reference on Chart Studio Cloud for  arrayminus
        .

        The 'arrayminussrc' property must be specified as a string or
        as a plotly.grid_objs.Column object

        Returns
        -------
        str
        """
        return self["arrayminussrc"]

    @arrayminussrc.setter
    def arrayminussrc(self, val):
        self["arrayminussrc"] = val

    # arraysrc
    # --------
    @property
    def arraysrc(self):
        """
        Sets the source reference on Chart Studio Cloud for  array .

        The 'arraysrc' property must be specified as a string or
        as a plotly.grid_objs.Column object

        Returns
        -------
        str
        """
        return self["arraysrc"]

    @arraysrc.setter
    def arraysrc(self, val):
        self["arraysrc"] = val

    # color
    # -----
    @property
    def color(self):
        """
        Sets the stoke color of the error bars.

        The 'color' property is a color and may be specified as:
          - A hex string (e.g. '#ff0000')
          - An rgb/rgba string (e.g. 'rgb(255,0,0)')
          - An hsl/hsla string (e.g. 'hsl(0,100%,50%)')
          - An hsv/hsva string (e.g. 'hsv(0,100%,100%)')
          - A named CSS color:
                aliceblue, antiquewhite, aqua, aquamarine, azure,
                beige, bisque, black, blanchedalmond, blue,
                blueviolet, brown, burlywood, cadetblue,
                chartreuse, chocolate, coral, cornflowerblue,
                cornsilk, crimson, cyan, darkblue, darkcyan,
                darkgoldenrod, darkgray, darkgrey, darkgreen,
                darkkhaki, darkmagenta, darkolivegreen, darkorange,
                darkorchid, darkred, darksalmon, darkseagreen,
                darkslateblue, darkslategray, darkslategrey,
                darkturquoise, darkviolet, deeppink, deepskyblue,
                dimgray, dimgrey, dodgerblue, firebrick,
                floralwhite, forestgreen, fuchsia, gainsboro,
                ghostwhite, gold, goldenrod, gray, grey, green,
                greenyellow, honeydew, hotpink, indianred, indigo,
                ivory, khaki, lavender, lavenderblush, lawngreen,
                lemonchiffon, lightblue, lightcoral, lightcyan,
                lightgoldenrodyellow, lightgray, lightgrey,
                lightgreen, lightpink, lightsalmon, lightseagreen,
                lightskyblue, lightslategray, lightslategrey,
                lightsteelblue, lightyellow, lime, limegreen,
                linen, magenta, maroon, mediumaquamarine,
                mediumblue, mediumorchid, mediumpurple,
                mediumseagreen, mediumslateblue, mediumspringgreen,
                mediumturquoise, mediumvioletred, midnightblue,
                mintcream, mistyrose, moccasin, navajowhite, navy,
                oldlace, olive, olivedrab, orange, orangered,
                orchid, palegoldenrod, palegreen, paleturquoise,
                palevioletred, papayawhip, peachpuff, peru, pink,
                plum, powderblue, purple, red, rosybrown,
                royalblue, rebeccapurple, saddlebrown, salmon,
                sandybrown, seagreen, seashell, sienna, silver,
                skyblue, slateblue, slategray, slategrey, snow,
                springgreen, steelblue, tan, teal, thistle, tomato,
                turquoise, violet, wheat, white, whitesmoke,
                yellow, yellowgreen

        Returns
        -------
        str
        """
        return self["color"]

    @color.setter
    def color(self, val):
        self["color"] = val

    # symmetric
    # ---------
    @property
    def symmetric(self):
        """
        Determines whether or not the error bars have the same length
        in both direction (top/bottom for vertical bars, left/right for
        horizontal bars.

        The 'symmetric' property must be specified as a bool
        (either True, or False)

        Returns
        -------
        bool
        """
        return self["symmetric"]

    @symmetric.setter
    def symmetric(self, val):
        self["symmetric"] = val

    # thickness
    # ---------
    @property
    def thickness(self):
        """
        Sets the thickness (in px) of the error bars.

        The 'thickness' property is a number and may be specified as:
          - An int or float in the interval [0, inf]

        Returns
        -------
        int|float
        """
        return self["thickness"]

    @thickness.setter
    def thickness(self, val):
        self["thickness"] = val

    # traceref
    # --------
    @property
    def traceref(self):
        """
        The 'traceref' property is a integer and may be specified as:
          - An int (or float that will be cast to an int)
            in the interval [0, 9223372036854775807]

        Returns
        -------
        int
        """
        return self["traceref"]

    @traceref.setter
    def traceref(self, val):
        self["traceref"] = val

    # tracerefminus
    # -------------
    @property
    def tracerefminus(self):
        """
        The 'tracerefminus' property is a integer and may be specified as:
          - An int (or float that will be cast to an int)
            in the interval [0, 9223372036854775807]

        Returns
        -------
        int
        """
        return self["tracerefminus"]

    @tracerefminus.setter
    def tracerefminus(self, val):
        self["tracerefminus"] = val

    # type
    # ----
    @property
    def type(self):
        """
        Determines the rule used to generate the error bars. If
        *constant`, the bar lengths are of a constant value. Set this
        constant in `value`. If "percent", the bar lengths correspond
        to a percentage of underlying data. Set this percentage in
        `value`. If "sqrt", the bar lengths correspond to the sqaure of
        the underlying data. If "data", the bar lengths are set with
        data set `array`.

        The 'type' property is an enumeration that may be specified as:
          - One of the following enumeration values:
                ['percent', 'constant', 'sqrt', 'data']

        Returns
        -------
        Any
        """
        return self["type"]

    @type.setter
    def type(self, val):
        self["type"] = val

    # value
    # -----
    @property
    def value(self):
        """
        Sets the value of either the percentage (if `type` is set to
        "percent") or the constant (if `type` is set to "constant")
        corresponding to the lengths of the error bars.

        The 'value' property is a number and may be specified as:
          - An int or float in the interval [0, inf]

        Returns
        -------
        int|float
        """
        return self["value"]

    @value.setter
    def value(self, val):
        self["value"] = val

    # valueminus
    # ----------
    @property
    def valueminus(self):
        """
        Sets the value of either the percentage (if `type` is set to
        "percent") or the constant (if `type` is set to "constant")
        corresponding to the lengths of the error bars in the bottom
        (left) direction for vertical (horizontal) bars

        The 'valueminus' property is a number and may be specified as:
          - An int or float in the interval [0, inf]

        Returns
        -------
        int|float
        """
        return self["valueminus"]

    @valueminus.setter
    def valueminus(self, val):
        self["valueminus"] = val

    # visible
    # -------
    @property
    def visible(self):
        """
        Determines whether or not this set of error bars is visible.

        The 'visible' property must be specified as a bool
        (either True, or False)

        Returns
        -------
        bool
        """
        return self["visible"]

    @visible.setter
    def visible(self, val):
        self["visible"] = val

    # width
    # -----
    @property
    def width(self):
        """
        Sets the width (in px) of the cross-bar at both ends of the
        error bars.

        The 'width' property is a number and may be specified as:
          - An int or float in the interval [0, inf]

        Returns
        -------
        int|float
        """
        return self["width"]

    @width.setter
    def width(self, val):
        self["width"] = val

    # Self properties description
    # ---------------------------
    @property
    def _prop_descriptions(self):
        return """\
        array
            Sets the data corresponding the length of each error
            bar. Values are plotted relative to the underlying
            data.
        arrayminus
            Sets the data corresponding the length of each error
            bar in the bottom (left) direction for vertical
            (horizontal) bars Values are plotted relative to the
            underlying data.
        arrayminussrc
            Sets the source reference on Chart Studio Cloud for
            arrayminus .
        arraysrc
            Sets the source reference on Chart Studio Cloud for
            array .
        color
            Sets the stoke color of the error bars.
        symmetric
            Determines whether or not the error bars have the same
            length in both direction (top/bottom for vertical bars,
            left/right for horizontal bars.
        thickness
            Sets the thickness (in px) of the error bars.
        traceref

        tracerefminus

        type
            Determines the rule used to generate the error bars. If
            *constant`, the bar lengths are of a constant value.
            Set this constant in `value`. If "percent", the bar
            lengths correspond to a percentage of underlying data.
            Set this percentage in `value`. If "sqrt", the bar
            lengths correspond to the sqaure of the underlying
            data. If "data", the bar lengths are set with data set
            `array`.
        value
            Sets the value of either the percentage (if `type` is
            set to "percent") or the constant (if `type` is set to
            "constant") corresponding to the lengths of the error
            bars.
        valueminus
            Sets the value of either the percentage (if `type` is
            set to "percent") or the constant (if `type` is set to
            "constant") corresponding to the lengths of the error
            bars in the bottom (left) direction for vertical
            (horizontal) bars
        visible
            Determines whether or not this set of error bars is
            visible.
        width
            Sets the width (in px) of the cross-bar at both ends of
            the error bars.
        """

    def __init__(
        self,
        arg=None,
        array=None,
        arrayminus=None,
        arrayminussrc=None,
        arraysrc=None,
        color=None,
        symmetric=None,
        thickness=None,
        traceref=None,
        tracerefminus=None,
        type=None,
        value=None,
        valueminus=None,
        visible=None,
        width=None,
        **kwargs
    ):
        """
        Construct a new ErrorY object

        Parameters
        ----------
        arg
            dict of properties compatible with this constructor or
            an instance of
            :class:`plotly.graph_objs.scattergl.ErrorY`
        array
            Sets the data corresponding the length of each error
            bar. Values are plotted relative to the underlying
            data.
        arrayminus
            Sets the data corresponding the length of each error
            bar in the bottom (left) direction for vertical
            (horizontal) bars Values are plotted relative to the
            underlying data.
        arrayminussrc
            Sets the source reference on Chart Studio Cloud for
            arrayminus .
        arraysrc
            Sets the source reference on Chart Studio Cloud for
            array .
        color
            Sets the stoke color of the error bars.
        symmetric
            Determines whether or not the error bars have the same
            length in both direction (top/bottom for vertical bars,
            left/right for horizontal bars.
        thickness
            Sets the thickness (in px) of the error bars.
        traceref

        tracerefminus

        type
            Determines the rule used to generate the error bars. If
            *constant`, the bar lengths are of a constant value.
            Set this constant in `value`. If "percent", the bar
            lengths correspond to a percentage of underlying data.
            Set this percentage in `value`. If "sqrt", the bar
            lengths correspond to the sqaure of the underlying
            data. If "data", the bar lengths are set with data set
            `array`.
        value
            Sets the value of either the percentage (if `type` is
            set to "percent") or the constant (if `type` is set to
            "constant") corresponding to the lengths of the error
            bars.
        valueminus
            Sets the value of either the percentage (if `type` is
            set to "percent") or the constant (if `type` is set to
            "constant") corresponding to the lengths of the error
            bars in the bottom (left) direction for vertical
            (horizontal) bars
        visible
            Determines whether or not this set of error bars is
            visible.
        width
            Sets the width (in px) of the cross-bar at both ends of
            the error bars.

        Returns
        -------
        ErrorY
        """
        super(ErrorY, self).__init__("error_y")

        if "_parent" in kwargs:
            self._parent = kwargs["_parent"]
            return

        # Validate arg
        # ------------
        if arg is None:
            arg = {}
        elif isinstance(arg, self.__class__):
            arg = arg.to_plotly_json()
        elif isinstance(arg, dict):
            arg = _copy.copy(arg)
        else:
            raise ValueError(
                """\
The first argument to the plotly.graph_objs.scattergl.ErrorY
constructor must be a dict or
an instance of :class:`plotly.graph_objs.scattergl.ErrorY`"""
            )

        # Handle skip_invalid
        # -------------------
        self._skip_invalid = kwargs.pop("skip_invalid", False)
        self._validate = kwargs.pop("_validate", True)

        # Populate data dict with properties
        # ----------------------------------
        _v = arg.pop("array", None)
        _v = array if array is not None else _v
        if _v is not None:
            self["array"] = _v
        _v = arg.pop("arrayminus", None)
        _v = arrayminus if arrayminus is not None else _v
        if _v is not None:
            self["arrayminus"] = _v
        _v = arg.pop("arrayminussrc", None)
        _v = arrayminussrc if arrayminussrc is not None else _v
        if _v is not None:
            self["arrayminussrc"] = _v
        _v = arg.pop("arraysrc", None)
        _v = arraysrc if arraysrc is not None else _v
        if _v is not None:
            self["arraysrc"] = _v
        _v = arg.pop("color", None)
        _v = color if color is not None else _v
        if _v is not None:
            self["color"] = _v
        _v = arg.pop("symmetric", None)
        _v = symmetric if symmetric is not None else _v
        if _v is not None:
            self["symmetric"] = _v
        _v = arg.pop("thickness", None)
        _v = thickness if thickness is not None else _v
        if _v is not None:
            self["thickness"] = _v
        _v = arg.pop("traceref", None)
        _v = traceref if traceref is not None else _v
        if _v is not None:
            self["traceref"] = _v
        _v = arg.pop("tracerefminus", None)
        _v = tracerefminus if tracerefminus is not None else _v
        if _v is not None:
            self["tracerefminus"] = _v
        _v = arg.pop("type", None)
        _v = type if type is not None else _v
        if _v is not None:
            self["type"] = _v
        _v = arg.pop("value", None)
        _v = value if value is not None else _v
        if _v is not None:
            self["value"] = _v
        _v = arg.pop("valueminus", None)
        _v = valueminus if valueminus is not None else _v
        if _v is not None:
            self["valueminus"] = _v
        _v = arg.pop("visible", None)
        _v = visible if visible is not None else _v
        if _v is not None:
            self["visible"] = _v
        _v = arg.pop("width", None)
        _v = width if width is not None else _v
        if _v is not None:
            self["width"] = _v

        # Process unknown kwargs
        # ----------------------
        self._process_kwargs(**dict(arg, **kwargs))

        # Reset skip_invalid
        # ------------------
        self._skip_invalid = False


text:
<?php namespace Fisharebest\Localization\Locale;

use Fisharebest\Localization\Territory\TerritoryBi;

class LocaleEnBi extends LocaleEn {
	public function territory() {
		return new TerritoryBi;
	}
}


text:
SYNCANO_INSTANCE_NAME = 'morning-violet-433730'
# Syncano api key
SYNCANO_API_KEY = 'f8c7f8700a4bcc1cf272ad775865d725a3482380'

# Collection used for Syncano::ActiveRecord
SYNCANO_ACTIVERECORD_COLLECTION = Syncano.client.projects.first.collections.first


text:
class Program
{
  static void Main()
  {
    System.Console.WriteLine("Hello World");
  }
}


text:
<?php
/**
 * Loop
 *
 * This is the default loop file, containing the looping logic for use in all templates
 * where a loop is required.
 *
 * To override this loop in a particular context (in all archives, for example), create a
 * duplicate of this file and rename it to `loop-archive.php`. Make any changes to this
 * new file and they will be reflected on all your archive screens.
 *
 * @package WooFramework
 * @subpackage Template
 */
 global $more; $more = 0;

woo_loop_before();

if (have_posts()) { $count = 0;
?>

<?php
	while (have_posts()) { the_post(); $count++;

		woo_get_template_part( 'content', get_post_type() );

	} // End WHILE Loop
} else {
	get_template_part( 'content', 'noposts' );
} // End IF Statement

woo_loop_after();

woo_pagenav();
?>


text:
<?php

namespace SMARTASK\HomeBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SMARTASKHomeBundle extends Bundle
{
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Hangfire.SqlServer;

namespace Hangfire.Azure.ServiceBusQueue
{
    internal class ServiceBusQueueMonitoringApi : IPersistentJobQueueMonitoringApi
    {
        private readonly ServiceBusManager _manager;
        private readonly string[] _queues;

        public ServiceBusQueueMonitoringApi(ServiceBusManager manager, string[] queues)
        {
            _manager = manager ?? throw new ArgumentNullException(nameof(manager));
            _queues  = queues ?? throw new ArgumentNullException(nameof(queues));
        }

        public IEnumerable<string> GetQueues()
        {
            return _queues;
        }

        public IEnumerable<long> GetEnqueuedJobIds(string queue, int from, int perPage)
        {
            return AsyncHelper.RunSync(() => GetEnqueuedJobIdsAsync(queue, from, perPage));
        }

        private async Task<IEnumerable<long>> GetEnqueuedJobIdsAsync(string queue, int from, int perPage)
        {
            var receiver = await _manager.GetReceiverAsync(queue).ConfigureAwait(false);

            var jobIds = new List<long>();

            // Hangfire api require a 0 based index for @from, but PeekMessageAsync is 1 based
            var messages = await receiver.PeekMessagesAsync(perPage, from + 1).ConfigureAwait(false);

            foreach (var msg in messages)
            {
                if (long.TryParse(msg.Body.ToString(), out var longJobId))
                {
                    jobIds.Add(longJobId);
                }
            }

            return jobIds;
        }

        public IEnumerable<long> GetFetchedJobIds(string queue, int from, int perPage)
        {
            return Enumerable.Empty<long>();
        }

        public EnqueuedAndFetchedCountDto GetEnqueuedAndFetchedCount(string queue)
        {
            return AsyncHelper.RunSync(() => GetEnqueuedAndFetchedCountAsync(queue));
        }

        private async Task<EnqueuedAndFetchedCountDto> GetEnqueuedAndFetchedCountAsync(string queue)
        {
            var queueRuntimeInfo = await _manager.GetQueueRuntimeInfoAsync(queue).ConfigureAwait(false);

            return new EnqueuedAndFetchedCountDto
            {
                EnqueuedCount = (int)queueRuntimeInfo.Value.ActiveMessageCount,
                FetchedCount  = null
            };
        }
    }
}


text:
package de.julianrupp.jsudoku;

public class Filter
{
	Boolean[][] filter;

	public Filter(int sideLength)
	{
		this.filter = new Boolean[sideLength][sideLength];

		for(int y=0; y<this.getSideLength(); y++)
		{
			for(int x=0; x<this.getSideLength(); x++)
			{
				this.filter[y][x] = true;
			}
		}
	}

	int getSideLength()
	{
		return this.filter.length;
	}

	boolean areXYCoordinatesOutOfBounds(int x, int y)
	{
		return !(x >= 0 && x < this.getSideLength() && y >= 0 && y < this.getSideLength());
	}

	public void setFilterAtXYCoordinates(int x, int y, boolean pKeepNumber)
	{
		if(this.areXYCoordinatesOutOfBounds(x, y)) throw new IndexOutOfBoundsException("Trying to set filter at x="+x+" y="+y);
		this.filter[y][x] = pKeepNumber;
	}

	public boolean getFilterAtXYCoordinates(int x, int y)
	{
		if(this.areXYCoordinatesOutOfBounds(x, y)) throw new IndexOutOfBoundsException("Trying to get filter at x="+x+" y="+y);
		return this.filter[y][x];
	}

	public Filter rotatePatternInMultiplesOf90DegClockwise(int pTimes)
	{
		pTimes = pTimes % 4; // Cut unnecessary iterations

		for(int i=0; i<pTimes; i++)
		{
			Boolean[][] rotatedFilter = new Boolean[this.getSideLength()][this.getSideLength()];

			for(int dstY=0; dstY<this.getSideLength(); dstY++)
			{
				for(int dstX=0; dstX<this.getSideLength(); dstX++)
				{
					int srcY = this.getSideLength()-1-dstX;
					int srcX = dstY;

					rotatedFilter[dstY][dstX] = this.filter[srcY][srcX];
				}
			}

			this.filter = rotatedFilter;
		}

		return this;
	}

	public Filter flipHorizontally()
	{
		Boolean[][] flippedFilter = new Boolean[this.getSideLength()][this.getSideLength()];

		for(int dstY=0; dstY<this.getSideLength(); dstY++)
		{
			for(int dstX=0; dstX<this.getSideLength(); dstX++)
			{
				int srcY = dstY;
				int srcX = this.getSideLength()-1-dstX;

				flippedFilter[dstY][dstX] = this.filter[srcY][srcX];
			}
		}

		this.filter = flippedFilter;

		return this;
	}

	public Filter flipVertically()
	{
		Boolean[][] flippedFilter = new Boolean[this.getSideLength()][this.getSideLength()];

		for(int dstY=0; dstY<this.getSideLength(); dstY++)
		{
			for(int dstX=0; dstX<this.getSideLength(); dstX++)
			{
				int srcY = this.getSideLength()-1-dstY;
				int srcX = dstX;

				flippedFilter[dstY][dstX] = this.filter[srcY][srcX];
			}
		}

		this.filter = flippedFilter;

		return this;
	}

	public Filter flipDiagonallyUpperLeftToLowerRight()
	{
		Boolean[][] flippedFilter = new Boolean[this.getSideLength()][this.getSideLength()];

		for(int dstY=0; dstY<this.getSideLength(); dstY++)
		{
			for(int dstX=0; dstX<this.getSideLength(); dstX++)
			{
				int srcY = dstX;
				int srcX = dstY;

				flippedFilter[dstY][dstX] = this.filter[srcY][srcX];
			}
		}

		this.filter = flippedFilter;

		return this;
	}

	public Filter flipDiagonallyUpperRightToLowerLeft()
	{
		Boolean[][] flippedFilter = new Boolean[this.getSideLength()][this.getSideLength()];

		for(int dstY=0; dstY<this.getSideLength(); dstY++)
		{
			for(int dstX=0; dstX<this.getSideLength(); dstX++)
			{
				int srcY = this.getSideLength()-1-dstX;
				int srcX = this.getSideLength()-1-dstY;

				flippedFilter[dstY][dstX] = this.filter[srcY][srcX];
			}
		}

		this.filter = flippedFilter;

		return this;
	}

	public String toString()
	{
		return this.getString(false);
	}

	public String getString(boolean humanReadable)
	{
		StringBuilder sb = new StringBuilder();

		for(int y=0; y<this.getSideLength(); y++)
		{
			for(int x=0; x<this.getSideLength(); x++)
			{
				sb.append(this.getFilterAtXYCoordinates(x, y) ? "#" : " ");
			}

			if(humanReadable && y < this.getSideLength()-1) sb.append("\n");
		}

		return sb.toString();
	}

	public Filter clone()
	{
		Filter duplicate = new Filter(this.getSideLength());

		for(int y=0; y<this.getSideLength(); y++)
		{
			for(int x=0; x<this.getSideLength(); x++)
			{
				duplicate.setFilterAtXYCoordinates(x, y, this.getFilterAtXYCoordinates(x, y));
			}
		}

		return duplicate;
	}
}


text:
BOT_NAME = 'report_crawler'

SPIDER_MODULES = ['report_crawler.spiders']
NEWSPIDER_MODULE = 'report_crawler.spiders'

# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'

# Obey robots.txt rules
ROBOTSTXT_OBEY = False

# Configure maximum concurrent requests performed by Scrapy (default: 16)
#CONCURRENT_REQUESTS = 32

# Configure a delay for requests for the same website (default: 0)
# See http://scrapy.readthedocs.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 1
# The download delay setting will honor only one of:
#CONCURRENT_REQUESTS_PER_DOMAIN = 16
#CONCURRENT_REQUESTS_PER_IP = 16

# Disable cookies (enabled by default)
COOKIES_ENABLED = False

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
# DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html, application/xhtml+xml, application/xml',
#   'Accept-Language': 'zh-CN,zh;q=0.8',
#   'Host':'ip84.com',
#   'Referer':'http://ip84.com/',
#   'X-XHR-Referer':'http://ip84.com/'
# }

# Enable or disable spider middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'report_crawler.middlewares.ReportCrawlerSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
# DOWNLOADER_MIDDLEWARES = {
# 	'report_crawler.useragent.UserAgent': 1,
# 	'report_crawler.proxymiddlewares.ProxyMiddleware': 100,
# 	'scrapy.downloadermiddleware.useragent.UserAgentMiddleware' : None,
# }

# Enable or disable extensions
# See http://scrapy.readthedocs.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See http://scrapy.readthedocs.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'report_crawler.pipelines.ReportCrawlerPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See http://doc.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'


text:
"""
The MIT License (MIT)

Copyright (c) 2014 - 2015 Jos "Zarthus" Ahrens and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

ForceException by Zarthus
Licensed under MIT

This module allows you to reproduce a traceback by raising an exception for debugging purposes.
"""

from core import moduletemplate

class ForceException(moduletemplate.BotModule):

    def on_module_load(self):
        self.register_command("forceexception", None, "Force an Exception to occur.", self.PRIV_ADMIN)

    def on_command(self, target, nick, command, commandtext, mod, admin):
        if command == "forceexception" and admin:
            raise Exception("Requested exception by administrator {} in {}".format(nick, target))
            return True
        return False


text:
export const PROCESSOR_TYPES = ['request', 'imp', 'bidResponse', 'response'];
export const PROCESSOR_DIALECTS = ['default', 'pbs'];
export const [REQUEST, IMP, BID_RESPONSE, RESPONSE] = PROCESSOR_TYPES;
export const [DEFAULT, PBS] = PROCESSOR_DIALECTS;

const types = new Set(PROCESSOR_TYPES);

export function processorRegistry() {
  const processors = {};

  return {
    registerOrtbProcessor({type, name, fn, priority = 0, dialects = [DEFAULT]}) {
      if (!types.has(type)) {
        throw new Error(`ORTB processor type must be one of: ${PROCESSOR_TYPES.join(', ')}`)
      }
      dialects.forEach(dialect => {
        if (!processors.hasOwnProperty(dialect)) {
          processors[dialect] = {};
        }
        if (!processors[dialect].hasOwnProperty(type)) {
          processors[dialect][type] = {};
        }
        processors[dialect][type][name] = {
          priority,
          fn
        }
      })
    },
    getProcessors(dialect) {
      return processors[dialect] || {};
    }
  }
}

export const {registerOrtbProcessor, getProcessors} = processorRegistry();


text:
/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <limits.h>
#include <semaphore.h>
#include <sched.h>
#include <nuttx/arch.h>

#include "os_internal.h"
#include "sem_internal.h"

/****************************************************************************
 * Definitions
 ****************************************************************************/

/****************************************************************************
 * Private Type Declarations
 ****************************************************************************/

/****************************************************************************
 * Global Variables
 ****************************************************************************/

/****************************************************************************
 * Private Variables
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: sem_post
 *
 * Description:
 *   When a task has finished with a semaphore, it will call sem_post().
 *   This function unlocks the semaphore referenced by sem by performing the
 *   semaphore unlock operation on that semaphore.
 *
 *   If the semaphore value resulting from this operation is positive, then
 *   no tasks were blocked waiting for the semaphore to become unlocked; the
 *   semaphore is simply incremented.
 *
 *   If the value of the semaphore resulting from this operation is zero,
 *   then one of the tasks blocked waiting for the semaphore shall be
 *   allowed to return successfully from its call to sem_wait().
 *
 * Parameters:
 *   sem - Semaphore descriptor
 *
 * Return Value:
 *   0 (OK) or -1 (ERROR) if unsuccessful
 *
 * Assumptions:
 *   This function cannot be called from an interrupt handler.
 *   It assumes the currently executing task is the one that
 *   is performing the unlock.
 *
 ****************************************************************************/

int sem_post(FAR sem_t *sem)
{
  FAR struct tcb_s *stcb = NULL;
  irqstate_t saved_state;
  int ret = ERROR;

  /* Make sure we were supplied with a valid semaphore. */

  if (sem)
    {
      /* The following operations must be performed with interrupts
       * disabled because sem_post() may be called from an interrupt
       * handler.
       */

      saved_state = irqsave();

      /* Perform the semaphore unlock operation. */

      ASSERT(sem->semcount < SEM_VALUE_MAX);
      sem_releaseholder(sem);
      sem->semcount++;

#ifdef CONFIG_PRIORITY_INHERITANCE
      /* Don't let any unblocked tasks run until we complete any priority
       * restoration steps.  Interrupts are disabled, but we do not want
       * the head of the read-to-run list to be modified yet.
       *
       * NOTE: If this sched_lock is called from an interrupt handler, it
       * will do nothing.
       */

      sched_lock();
#endif
      /* If the result of of semaphore unlock is non-positive, then
       * there must be some task waiting for the semaphore.
       */

      if (sem->semcount <= 0)
        {
          /* Check if there are any tasks in the waiting for semaphore
           * task list that are waiting for this semaphore. This is a
           * prioritized list so the first one we encounter is the one
           * that we want.
           */

          for (stcb = (FAR struct tcb_s*)g_waitingforsemaphore.head;
               (stcb && stcb->waitsem != sem);
               stcb = stcb->flink);

          if (stcb)
            {
              /* It is, let the task take the semaphore */

              stcb->waitsem = NULL;

              /* Restart the waiting task. */

              up_unblock_task(stcb);
            }
        }

      /* Check if we need to drop the priority of any threads holding
       * this semaphore.  The priority could have been boosted while they
       * held the semaphore.
       */

#ifdef CONFIG_PRIORITY_INHERITANCE
      sem_restorebaseprio(stcb, sem);
      sched_unlock();
#endif
      ret = OK;

      /* Interrupts may now be enabled. */

      irqrestore(saved_state);
    }

  return ret;
}


text:
sb.include('effect');
sb.include('browser.getScrollPosition');
/**
@Name:  sb.browser.scrollTo
@Author: Paul Visco
@Description: Used to gradually scroll the browser somewhere
@Param: Object with the following properties
integer y Where to scroll to on the y axis
integer x Where to scroll to on the x axis
integer duration The time milliseconds to scroll over
function onEnd Fires if it successfully completes scrolling
function onStopped Fires if the user stops the scrolling by initiating their own scrolling
@Example:
//scrolls to y 500, x: 200 and alerts 'done' when complete or stopped of the user scrolls
var scrollTo = sb.browser.scrollTo({
	y : 500,
	x : 200,
	duration : 24,
	onEnd : function(){
		alert('done');
	},
	onStopped : function(){
		alert('stopped');
	});

*/
sb.browser.scrollTo = function(o){

	var scrollPos = sb.browser.getScrollPosition();
	var x = scrollPos[0];
	var y = scrollPos[1];
	o.x = typeof o.x == 'undefined' ? x : Math.round(o.x);

	o.y = typeof o.y == 'undefined' ? y : Math.round(o.y);
	var stopScroll = function(complete){
		stop.remove();
		stop2.remove();
		window.clearTimeout(scrolling);
		if(complete){
			if(typeof o.onEnd == 'function'){
				o.onEnd();
			}
		} else {
			if(typeof o.onStopped == 'function'){
				o.onStopped();
			}
		}

	};
	var time = 0;
	var duration = o.duration || 15;
	var beginX = x
	var changeX = o.x-x;
	var tweenX = changeX < 1 ? 'outQuart': 'inQuart';
	var beginY = y;
	var changeY = o.y-y;
	var tweenY = changeY < 1 ? 'outQuart': 'inQuart';
	if(o.debug){
		document.title = [beginX, changeX, beginY, changeY];
	}
	var scrolling = window.setInterval(function(){
		if(time >= duration){
			stopScroll();
			return;
		}
		time++;

		if(y != o.y){
			y = sb.effects.tween[tweenY](time,beginY,changeY,duration);
		}

		if(x != o.x){
			x = sb.effects.tween[tweenX](time,beginX,changeX,duration);
		}

		x = Math.round(x);
		y = Math.round(y);

		window.scrollTo(x, y);
		if(x == o.x && y == o.y){
			stopScroll(true);
		}

	}, 10);

	var stop = sb.events.add(document, 'DOMMouseScroll', function(){stopScroll(false);});
	var stop2 = sb.events.add(document, 'mousewheel', function(){stopScroll(false);});

	scrolling.stop = stopScroll;
	return scrolling;
};


text:
package com.mpobjects.rtcalltree.report;

import java.util.Collection;
import java.util.List;

import com.mpobjects.rtcalltree.CalltreeEntry;

/**
 * This reporter simply forwards the report requests to a set of reporters.
 */
public class CompositeCalltreeReporter extends AbstractCalltreeReporter {

	protected Collection<? extends CalltreeReporter> reporters;

	public CompositeCalltreeReporter() {
		super();
		minimumReportDepth = 0;
		minimumReportSize = 0;
	}

	public CompositeCalltreeReporter(Collection<? extends CalltreeReporter> aReporters) {
		this();
		setReporters(aReporters);
	}

	/**
	 * @return the reporters
	 */
	public Collection<? extends CalltreeReporter> getReporters() {
		return reporters;
	}

	@Override
	public void reportEndOfTree(String aThreadName, List<? extends CalltreeEntry> aCallTree) {
		if (reporters == null) {
			return;
		}
		if (!shouldReport(aCallTree)) {
			return;
		}
		for (CalltreeReporter rep : reporters) {
			if (rep == null) {
				continue;
			}
			rep.reportEndOfTree(aThreadName, aCallTree);
		}
	}

	/**
	 * @param aReporters
	 *            the reporters to call
	 */
	public void setReporters(Collection<? extends CalltreeReporter> aReporters) {
		reporters = aReporters;
	}

}


text:
import pytest
import webs
import models
from gevent import monkey
monkey.patch_socket()

class TestVideoSpider():
    def test_entry_points(self):
        webs.douban.parsers.movie
        webs.douban.parsers.celebrity
        webs.douban.parsers.douban_api
        webs.douban.parsers.movie_photo
        webs.douban.tasks.get_main_movies_base_data
        webs.douban.tasks.get_main_movies_full_data
        webs.douban.tasks.get_celebrities_full_data
        webs.douban.tasks.down_video_images
        webs.douban.tasks.down_celebrity_images

        webs.bilibili.parsers.bilibili_api
        webs.bilibili.parsers.animation
        webs.bilibili.tasks.get_animations_base_data
        webs.bilibili.tasks.get_animations_full_data

    def test_douban_movie_base_data(self, session):
        douban_movie_ids = webs.douban.tasks.get_main_movies_base_data.task(
            20,
            types=['movie'],
            sorts=['recommend'],
            tags_dict={
                'movie': ['热门']
            }
        )

    def test_douban_movie_full_data(self, session, douban_movie_ids):
        webs.douban.tasks.get_main_movies_full_data.task(
            douban_movie_ids[:10],
            5
        )

        videos = session.query(models.Video).filter_by(is_detail=True).all()

        assert len(videos) == 10

    def test_douban_celebrity_full_data(self, session, douban_celebrity_ids):
        webs.douban.tasks.get_celebrities_full_data.task(
            douban_celebrity_ids[:10],
            5
        )

        celebrities = session.query(
            models.Celebrity
        ).filter_by(is_detail=True).all()

        assert len(celebrities) == 10

    def test_bilibili_animation_base_data(self, session):
        webs.bilibili.tasks.get_animations_base_data.task(20, [1])

    def test_bilibili_animation_full_data(self,
                                          session,
                                          bilibili_animation_ids):
        webs.bilibili.tasks.get_animations_full_data.task(
            bilibili_animation_ids[:10],
            5
        )

        animations = session.query(
            models.Animation
        ).filter_by(is_detail=True).all()

        assert len(animations) == 10