text:
import datetime
import scrapy
from amazon.items import BookItem

def safe_list_get(l, idx, default=''):
    return l[idx] if len(l) > idx else default

class AmazonSpider(scrapy.Spider):
    name = "amazon"
    allowed_domains = ["amazon.cn"]
    cat = None
    start_url = None
    start_urls = {
        '文学巨匠': 'https://www.amazon.cn/s/?node=1851470071&ie=UTF8',
        '外国文学': 'https://www.amazon.cn/s/?node=1851471071&ie=UTF8',
        '秋乏冬眠': 'https://www.amazon.cn/s/?node=1851472071&ie=UTF8',
        '文艺青年': 'https://www.amazon.cn/s/?node=1851473071&ie=UTF8',
        '诺贝尔奖': 'https://www.amazon.cn/s/?node=1851474071&ie=UTF8',
    }

    def __init__(self, cat=None, url=None, node=None):
        if cat is None:
            self.cat = datetime.datetime.today().strftime('%Y%m%d')
        if node or url:
            if url:
                self.start_url = url
            else:
                self.start_url = 'https://www.amazon.cn/s/?node=%s' % (node)

    def start_requests(self):
        if self.cat and self.start_url:
            return [scrapy.Request(
                self.start_url,
                meta={'category': self.cat},
                callback=self.parse_book_follow_next_page
            )]

    def parse_book_follow_next_page(self, response):
        lis = response.xpath('//ul[contains(@class, "s-result-list")]/li') or \
            response.xpath('//div[contains(@class, "s-result-list")]/div[contains(@class, "s-result-item")]')
        for li in lis:
            item = BookItem()
            item['title'] = safe_list_get(li.xpath('.//h2/@data-attribute').extract() or \
                                          li.xpath('.//h2//span/text()').extract(),
                                          0, '')
            if item['title'] == '':
                continue
            item['date'] = safe_list_get(li.xpath('.//div[@class="a-row a-spacing-none"][1]/span/text()').extract(), 0, 'Unknown')
            item['author'] = safe_list_get(li.xpath('.//div[@class="a-row a-spacing-none"][2]/span/text()').extract(), 0, 'Unknown')
            item['author_date'] = ''.join(li.xpath('.//div[@class="a-row a-size-base a-color-secondary"][1]/span/text()').extract())
            # price = li.xpath('.//span[contains(@class, "s-price")]/text()').extract()
            # if len(price) == 0:
            # price = li.xpath('.//span[contains(@class, "a-color-price")]/text()').extract()
            # item['price'] = price[-1] if len(price) > 0 else '-1.0'
            item['price'] = ''.join(li.xpath('.//span[contains(@class, "price")]/text()')[-3:].extract())
            item['rating'] = float(safe_list_get(li.xpath('.//i[contains(@class, "a-icon-star")]/span/text()').re('[\d\.]+'), 0, 0.0))
            item['rating_num'] = int(safe_list_get(li.xpath('.//a[contains(@class, "a-size-small")]/text()').re('\d+') or \
                                                   li.xpath('.//div[contains(@class,"a-size-small")]/span[2]//span/text()').re('\d+'), 0, 0))
            item['url'] = safe_list_get(li.xpath('.//a[contains(@class, "s-access-detail-page")]/@href').extract() or \
                                        li.xpath('.//a[contains(@class, "a-link-normal")]/@href').extract(), 0, '')
            if self.allowed_domains[0] not in item['url']:
                item['url'] = self.allowed_domains[0] + item['url']
            item['category'] = response.meta['category']
            yield item

        next_page = response.xpath('//li[contains(@class, "a-last")]/a/@href') or \
            response.xpath('//a[@id="pagnNextLink"]/@href')
        self.logger.debug(next_page)
        if next_page:
            url = response.urljoin(next_page[0].extract())
            yield scrapy.Request(url, self.parse_book_follow_next_page, meta=response.meta)


text:
package co.uk.niadel.napi.util;

import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.audio.ISound;
import net.minecraft.init.Blocks;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation;
import net.minecraft.world.World;

/**
 * Utillities to do stuff relating to Minecraft.
 *
 * @author Niadel
 */
public final class MCUtils
{
	public static Block[] getBlocksRelativeToCoords(World world, int x, int y, int z)
	{
		return new Block[]
				{
					world.getBlock(x + 1, y, z), //left
					world.getBlock(x - 1, y, z), //right
					world.getBlock(x, y + 1, z), //up
					world.getBlock(x, y - 1, z), //down
					world.getBlock(x, y, z + 1), //forward
					world.getBlock(x, y, z - 1), //backwards
					world.getBlock(x + 1, y + 1, z),//left-up
					world.getBlock(x + 1, y - 1, z),//left-down
					world.getBlock(x - 1, y + 1, z),//right-up
					world.getBlock(x - 1, y - 1, z),//right-down
					world.getBlock(x, y + 1, x + 1),//forwards-up
					world.getBlock(x, y - 1, x + 1),//forwards-down
					world.getBlock(x, y + 1, x - 1),//backwards-up
					world.getBlock(x, y - 1, x - 1)//backwards-down
				};
	}

	/**
	 * Gets the coords of a Tile Entity as an int[].
	 * @param theTE The tile entity to get the coords of.
	 * @return The coordinates of theTE.
	 */
	public static int[] getCoordsOfTE(TileEntity theTE)
	{
		return new int[] {theTE.field_145848_d, theTE.field_145849_e, theTE.field_145851_c};
	}

	/**
	 * Removes all blocks in a vertical column above the block specified by the coords
	 * that are of the Block specified.
	 *
	 * @param world The world object to use to remove the blocks.
	 * @param blockToRemove The Block type to remove.
	 * @param xCoord
	 * @param yCoord
	 * @param zCoord
	 * @param limit
	 */
	public static final void removeSimilarBlocksInColumn(World world, Block blockToRemove, int xCoord, int yCoord, int zCoord, int limit)
	{
		if (!world.isClient)
		{
			for (int i = yCoord; i == limit - yCoord; i++)
			{
				Block currBlock = world.getBlock(xCoord, i, zCoord);

				// Because there's no easy way to compare Blocks, I kind of cheated and compared the unlocalised names. They're usually the same between types.
				if (currBlock.getUnlocalizedName() == blockToRemove.getUnlocalizedName())
				{
					world.setBlock(xCoord, i, zCoord, Blocks.air);
				}
			}
		}
	}

	/**
	 * Removes all blocks in a vertical column above the block specified by the coords.
	 * @param world
	 * @param xCoord
	 * @param yCoord
	 * @param zCoord
	 * @param limit
	 */
	public static final void removeBlocksInColumn(World world, int xCoord, int yCoord, int zCoord, int limit)
	{
		if (!world.isClient)
		{
			for (int i = yCoord; i == limit - yCoord; i++)
			{
				world.setBlock(xCoord, i, zCoord, Blocks.air);
			}
		}
	}

	/**
	 * Removes all blocks in a vertical column up to the limit.
	 * @param world
	 * @param xCoord
	 * @param zCoord
	 * @param limit
	 */
	public static final void removeAllBlocksInColumn(World world, int xCoord, int zCoord, int limit)
	{
		if (!world.isClient)
		{
			for (int i = 1; i == limit; i++)
			{
				world.setBlock(xCoord, i, zCoord, Blocks.air);
			}
		}
	}

	/**
	 * Removes all blocks in a vertical column.
	 * @param world
	 * @param xCoord
	 * @param zCoord
	 */
	public static final void removeAllBlocksInColumn(World world, int xCoord, int zCoord)
	{
		removeAllBlocksInColumn(world, xCoord, zCoord, 256);
	}

	/**
	 * Adds a message to the server chat.
	 *
	 * @param message The message to send.
	 * @param shouldTranslate Whether or not to translate message.
	 */
	public static final void addMessageToChat(String message, boolean shouldTranslate)
	{
		if (MCData.isServerSide())
		{
			if (!shouldTranslate)
			{
				MinecraftServer.getServer().addChatMessage(new ChatComponentText(message));
			}
			else
			{
				MinecraftServer.getServer().addChatMessage(new ChatComponentTranslation(message));
			}
		}
		else
		{
			if (!shouldTranslate)
			{
				Minecraft.getMinecraft().thePlayer.sendChatMessage(message);
			}
			else
			{
				Minecraft.getMinecraft().thePlayer.sendChatMessage(new ChatComponentTranslation(message).getUnformattedTextForChat());
			}
		}
	}

	/**
	 * Plays a sound.
	 * @param sound The sound to play.
	 */
	public static final void playSound(ISound sound)
	{
		if (MCData.isClientSide())
		{
			Minecraft.getMinecraft().getSoundHandler().playSound(sound);
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * filename   :    cornix_agg.h
 * author     :    Kathryn Dahlgren
 * date       :    27 Feb 2016
 * Description:
 *     Definitions of Cornix
 *     aggregation operations
 */

#ifndef CORNIX_AGG_H
#define CORNIX_AGG_H

#include "cornix_includes.h"

// READ DATA
// input key
// output value for the key
std::string read_data(rocksdb::DB* db, rocksdb::Status status, std::string key)
{
  std::string value ;
  status = db->rocksdb::DB::Get(ReadOptions(), key, &value);
  if( status.ok() )
    return value ;
  else
    return "" ;
    //return "No data for key: " + key ;
}

// AVG
// Assume one field in key list
double avg(rocksdb::DB* db, rocksdb::Status status, std::vector<std::string> keyList, std::vector<std::string> idList)
{
  std::vector<double> valList ;

  // Get field from keyList
  std::string key = keyList[0] ;
  // Get value at the key
  std::string value = read_data(db, status, key) ;
  // Get tuple List from value
  std::vector<std::string> tupleList = parseList(value) ;

  // Get valid values
  for(unsigned int i = 0 ; i < tupleList.size() ; i++)
  {
    std::string tupleID = getID( tupleList[i] ) ;
    std::string tupleVal = getValue( tupleList[i] ) ;
    bool check = std::find(idList.begin(), idList.end(), tupleID) != idList.end() ;
    if( check == true )
    {
      // Convert value from string to number
      double newValue = std::stod (tupleVal) ;
      // Append to end of valList
      valList.push_back(newValue) ;
    }
  }

  int numElements = valList.size() ;
  double sumElements = std::accumulate(valList.begin(), valList.end(), 0);

  if(value == "No data for key: "+key)
    return (-999999999) ;
  else
    return sumElements/numElements ;
}

// MIN
// Assume one field in key list
double min(rocksdb::DB* db, rocksdb::Status status, std::vector<std::string> keyList, std::vector<std::string> idList)
{
  std::vector<double> valList ;

  // Get field from keyList
  std::string key = keyList[0] ;
  // Get value at the key
  std::string value = read_data(db, status, key) ;
  // Get tuple List from value
  std::vector<std::string> tupleList = parseList(value) ;

  // Get valid values
  for(unsigned int i = 0 ; i < tupleList.size() ; i++)
  {
    std::string tupleID = getID( tupleList[i] ) ;
    std::string tupleVal = getValue( tupleList[i] ) ;
    bool check = std::find(idList.begin(), idList.end(), tupleID) != idList.end() ;
    if( check == true )
    {
      // Convert value from string to number
      double newValue = std::stod (tupleVal) ;
      // Append to end of valList
      valList.push_back(newValue) ;
    }
  }

  // get min
  if(value == "No data for key: "+key)
    return (-999999999) ;
  else
  {
    std::vector<double>::iterator result = std::min_element(std::begin(valList), std::end(valList)) ;
    double min = *result ;
    return min ;
  }
}

// MAX
// Assume one field in key list
double max(rocksdb::DB* db, rocksdb::Status status, std::vector<std::string> keyList, std::vector<std::string> idList)
{
  std::vector<double> valList ;

  // Get field from keyList
  std::string key = keyList[0] ;
  // Get value at the key
  std::string value = read_data(db, status, key) ;
  // Get tuple List from value
  std::vector<std::string> tupleList = parseList(value) ;

  // Get valid values
  for(unsigned int i = 0 ; i < tupleList.size() ; i++)
  {
    std::string tupleID = getID( tupleList[i] ) ;
    std::string tupleVal = getValue( tupleList[i] ) ;
    bool check = std::find(idList.begin(), idList.end(), tupleID) != idList.end() ;
    if( check == true )
    {
      // Convert value from string to number
      double newValue = std::stod (tupleVal) ;
      // Append to end of valList
      valList.push_back(newValue) ;
    }
  }

  // get min
  if(value == "No data for key: "+key)
    return (-999999999) ;
  else
  {
    std::vector<double>::iterator result = std::max_element(std::begin(valList), std::end(valList)) ;
    double max = *result ;
    return max ;
  }
}

// SUM
// Assume one field in key list
double sum(rocksdb::DB* db, rocksdb::Status status, std::vector<std::string> keyList, std::vector<std::string> idList)
{
  std::vector<double> valList ;

  // Get field from keyList
  std::string key = keyList[0] ;
  // Get value at the key
  std::string value = read_data(db, status, key) ;
  // Get tuple List from value
  std::vector<std::string> tupleList = parseList(value) ;

  // Get valid values
  for(unsigned int i = 0 ; i < tupleList.size() ; i++)
  {
    std::string tupleID = getID( tupleList[i] ) ;
    std::string tupleVal = getValue( tupleList[i] ) ;    bool check = std::find(idList.begin(), idList.end(), tupleID) != idList.end() ;
    if( check == true )
    {
      // Convert value from string to number
      double newValue = std::stod (tupleVal) ;
      // Append to end of valList
      valList.push_back(newValue) ;
    }
  }
  // get sum
  if(value == "No data for key: "+key)
    return (-999999999) ;
  else
  {
    double sum = std::accumulate(valList.begin(), valList.end(), 0);
    return sum ;
  }
}

// COUNT
// Assume one field in key list
double count(rocksdb::DB* db, rocksdb::Status status, std::vector<std::string> keyList, std::vector<std::string> idList)
{
  std::vector<double> valList ;

  // Get field from keyList
  std::string key = keyList[0] ;
  // Get value at the key
  std::string value = read_data(db, status, key) ;
  // Get tuple List from value
  std::vector<std::string> tupleList = parseList(value) ;

  // Get valid values
  for(unsigned int i = 0 ; i < tupleList.size() ; i++)
  {
    std::string tupleID = getID( tupleList[i] ) ;
    std::string tupleVal = getValue( tupleList[i] ) ;
    bool check = std::find(idList.begin(), idList.end(), tupleID) != idList.end() ;
    if( check == true )
    {
      // Convert value from string to number
      double newValue = std::stod (tupleVal) ;
      // Append to end of valList
      valList.push_back(newValue) ;
    }
  }
  // get count
  if(value == "No data for key: "+key)
    return (-999999999) ;
  else
  {
    double count = valList.size() ;
    return count ;
  }
}

#endif


text:
package org.wyttenbach.dale.document.dto;

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

public class DocumentDTO implements Serializable {
	private static final long serialVersionUID = -594350689811651714L;

	private Long id;

	private String busSeg;

	private String externalId;

	private String note;

	private Date receivedDate;

	private Long size;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getBusSeg() {
		return busSeg;
	}

	public void setBusSeg(String busSeg) {
		this.busSeg = busSeg;
	}

	public String getExternalId() {
		return externalId;
	}

	public void setExternalId(String externalId) {
		this.externalId = externalId;
	}

	public String getNote() {
		return note;
	}

	public void setNote(String note) {
		this.note = note;
	}

	public Date getReceivedDate() {
		return receivedDate;
	}

	public void setReceivedDate(Date receivedDate) {
		this.receivedDate = receivedDate;
	}

	public Long getSize() {
		return size;
	}

	public void setSize(Long size) {
		this.size = size;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<!-- Log4J配置文件路径 -->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.xml</param-value>
	</context-param>

	<!-- Spring刷新Log4J配置文件的间隔,单位为毫秒(应用环境需要去掉) -->
	<context-param>
		<param-name>log4jRefreshInterval</param-name>
		<param-value>60000</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>

	<!-- Spring的XML配置文件的路径 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/*.xml,classpath:spring/*/*.xml</param-value>
	</context-param>

	<!-- 加载应用上下文监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 清除Introspector缓冲监听器,防止内存泄漏  -->
	<listener>
		<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
	</listener>

	<listener>
		<listener-class>org.springframework.web.util.WebAppRootListener</listener-class>
	</listener>
	<!--	设置配置webAppRootKey的值,默认是webapp.root-->
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>webapp.sun</param-value>
	</context-param>

	<listener>
		<listener-class>com.sun.core.bean.BeanManagerListener</listener-class>
	</listener>

	<!--spring的编码转换过滤器-->
	<filter>
		<filter-name>EncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>EncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!--核心控制器DispatcherServlet-->
	<servlet>
		<servlet-name>Dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/dispatcherServlet.xml</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>
	</servlet>
	<servlet>
		<servlet-name>XhEditor</servlet-name>
		<servlet-class>com.sun.core.util.UploadFileServlet</servlet-class>
	</servlet>
    <servlet>
        <servlet-name>Upload</servlet-name>
        <servlet-class>com.sun.core.util.UploadifyUploadFileServlet</servlet-class>
    </servlet>

	<servlet-mapping>
		<servlet-name>XhEditor</servlet-name>
		<url-pattern>/servlet/UploadFileServlet</url-pattern>
	</servlet-mapping>
    <servlet-mapping>
        <servlet-name>Upload</servlet-name>
        <url-pattern>/servlet/Upload</url-pattern>
    </servlet-mapping>
	<servlet-mapping>
		<servlet-name>Dispatcher</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

	<!--验证码servlet-->
	<!--	<servlet>-->
	<!--		<servlet-name>checkImage</servlet-name>-->
	<!--
		<servlet-class>com.roiland.web.servlet.CheckImageServlet</servlet-class>
	-->
	<!--	</servlet>-->
	<!--	<servlet-mapping>-->
	<!--		<servlet-name>checkImage</servlet-name>-->
	<!--		<url-pattern>/image.do</url-pattern>-->
	<!--	</servlet-mapping>-->
	<!--	<servlet-mapping>-->
	<!--		<servlet-name>checkImage</servlet-name>-->
	<!--		<url-pattern>/check/image.jpg</url-pattern>-->
	<!--	</servlet-mapping>-->

	<!-- CKEditor Upload File Servlet -->
	<servlet>
		<servlet-name>SimpleUploader</servlet-name>
		<servlet-class>com.sun.core.util.CKEditorUploadServlet</servlet-class>
		<init-param>
			<param-name>baseDir</param-name>
			<param-value>/UserUpload/</param-value>
		</init-param>
		<init-param>
			<param-name>debug</param-name>
			<param-value>false</param-value>
		</init-param>
		<init-param>
			<param-name>enabled</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<param-name>AllowedExtensionsFile</param-name>
			<param-value></param-value>
		</init-param>
		<init-param>
			<param-name>DeniedExtensionsFile</param-name>
			<param-value>
				html|htm|php|php2|php3|php4|php5|phtml|pwml|inc|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|com|dll|vbs|js|reg|cgi|htaccess|asis|ftl
			</param-value>
		</init-param>
		<init-param>
			<param-name>AllowedExtensionsImage</param-name>
			<param-value>jpg|gif|jpeg|png|bmp</param-value>
		</init-param>
		<init-param>
			<param-name>DeniedExtensionsImage</param-name>
			<param-value></param-value>
		</init-param>
		<init-param>
			<param-name>AllowedExtensionsFlash</param-name>
			<param-value>swf|fla</param-value>
		</init-param>
		<init-param>
			<param-name>DeniedExtensionsFlash</param-name>
			<param-value></param-value>
		</init-param>
		<load-on-startup>3</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>SimpleUploader</servlet-name>
		<url-pattern>/ckeditor/uploader</url-pattern>
	</servlet-mapping>

	<!--错误码和对应文件-->
	<!--	<error-page>-->
	<!--		<error-code>500</error-code>-->
	<!--		<location>/attachment/500.jsp</location>-->
	<!--	</error-page>-->
	<error-page>
		<error-code>404</error-code>
		<location>/attachment/404.jsp</location>
	</error-page>

	<!--Session超时时间:分钟-->
	<session-config>
		<session-timeout>60</session-timeout>
	</session-config>

	<!--欢迎文件-->
	<welcome-file-list>
		<welcome-file>login.do</welcome-file>
		<welcome-file>index.do</welcome-file>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>

</web-app>


text:
package de.domisum.pistonjammer.register;

import org.bukkit.Chunk;
import org.bukkit.World;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Keeps track of the current number of piston in each chunk of the worlds that are supplied in the constructor.
 */
public class ChunkPistonRegister
{

	private Map<World, WorldChunkPistonRegister> registers = new HashMap<>();

	// INIT
	public ChunkPistonRegister(List<World> worlds)
	{
		for(World world : worlds)
			this.registers.put(world, new WorldChunkPistonRegister(world));
	}

	// GETTERS
	public int getChunkPistons(Chunk chunk)
	{
		WorldChunkPistonRegister register = getRegister(chunk.getWorld());

		return register.getChunkPistons(chunk);
	}

	private WorldChunkPistonRegister getRegister(World world)
	{
		if(!this.registers.containsKey(world))
			throw new IllegalArgumentException("The world '"+world+"' is not tracked in this ChunkPistonRegister");

		return this.registers.get(world);
	}

	// CHANGERS
	public void changeChunkPistons(Chunk chunk, int delta)
	{
		WorldChunkPistonRegister register = getRegister(chunk.getWorld());

		register.changeChunkPistons(chunk.getX(), chunk.getZ(), delta);
	}

	public void unloadChunkPistonCount(Chunk chunk)
	{
		WorldChunkPistonRegister register = getRegister(chunk.getWorld());
		register.unloadChunkPistonCount(chunk);
	}

}


text:
const errors = {
  missingAuthFieldError: function(field, method, msg) {
    return new TypeError(msg || "socialAuth() is missing the authentication method or an unknown method was passed: " + method);
  },
  missingMethodsError: function(msg) {
    return new TypeError(msg || "socialAuhPlugin() options is missing an array of authentication methods");
  }
};

const socialAuhPlugin = function(schema, opt) {
  if(!Array.isArray(opt.methods)) {
    throw errors.missingMethodsError();
  }

  schema.statics.socialAuth = function(method) {

    if(!method || opt.methods.indexOf(method) === -1) {
      throw errors.missingAuthFieldError();
    }

    const self = this;

    return function(token, tokenSecret, profile, done) {
      self.findOneAndUpdate(
        { [method + ".id"]: profile.id },
        {
          $set: {
            [method + ".username"]: profile.displayName,
            [method + ".image_url"]: profile.photos[0].value.replace("_normal", "")
          }
        },
        { new: true },
        (err, user) => {
          if(err) {
            return done(err);
          }
          if(!user) {
            const newUser = new self({
              login_method: method,
              [method]: {
                id: profile.id,
                username: profile.displayName,
                image_url: profile.photos[0].value.replace("_normal", "")
              }
            });

            newUser.save((err) => {
              if(err) {
                return done(err);
              }
              done(null, newUser);
            });
          }
          else {
            done(null, user);
          }
        }
      );
    };
  };
};

module.exports = socialAuhPlugin;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cercospora ligustri Roum.

### Remarks
null


text:
from app import app
from flask import request
import socket, errno

import os

app.debug=True

if os.geteuid():
  app.run(host='0.0.0.0', port=5000)
else:
  app.run(host='0.0.0.0', port=80)


text:
import abc
from typing import Awaitable, Callable, Dict, Optional, Sequence, Union

import google.api_core
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_core import retry as retries
import google.auth  # type: ignore
from google.auth import credentials as ga_credentials  # type: ignore
from google.oauth2 import service_account  # type: ignore
from google.protobuf import empty_pb2  # type: ignore
import pkg_resources

from google.area120.tables_v1alpha1.types import tables

try:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
        gapic_version=pkg_resources.get_distribution(
            "google-area120-tables",
        ).version,
    )
except pkg_resources.DistributionNotFound:
    DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()

class TablesServiceTransport(abc.ABC):
    """Abstract transport class for TablesService."""

    AUTH_SCOPES = (
        "https://www.googleapis.com/auth/drive",
        "https://www.googleapis.com/auth/drive.file",
        "https://www.googleapis.com/auth/drive.readonly",
        "https://www.googleapis.com/auth/spreadsheets",
        "https://www.googleapis.com/auth/spreadsheets.readonly",
        "https://www.googleapis.com/auth/tables",
    )

    DEFAULT_HOST: str = "area120tables.googleapis.com"

    def __init__(
        self,
        *,
        host: str = DEFAULT_HOST,
        credentials: Optional[ga_credentials.Credentials] = None,
        credentials_file: Optional[str] = None,
        scopes: Optional[Sequence[str]] = None,
        quota_project_id: Optional[str] = None,
        client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
        always_use_jwt_access: Optional[bool] = False,
        api_audience: Optional[str] = None,
        **kwargs,
    ) -> None:
        """Instantiate the transport.

        Args:
            host (Optional[str]):
                 The hostname to connect to.
            credentials (Optional[google.auth.credentials.Credentials]): The
                authorization credentials to attach to requests. These
                credentials identify the application to the service; if none
                are specified, the client will attempt to ascertain the
                credentials from the environment.
            credentials_file (Optional[str]): A file with credentials that can
                be loaded with :func:`google.auth.load_credentials_from_file`.
                This argument is mutually exclusive with credentials.
            scopes (Optional[Sequence[str]]): A list of scopes.
            quota_project_id (Optional[str]): An optional project to use for billing
                and quota.
            client_info (google.api_core.gapic_v1.client_info.ClientInfo):
                The client info used to send a user-agent string along with
                API requests. If ``None``, then default info will be used.
                Generally, you only need to set this if you're developing
                your own client library.
            always_use_jwt_access (Optional[bool]): Whether self signed JWT should
                be used for service account credentials.
        """

        scopes_kwargs = {"scopes": scopes, "default_scopes": self.AUTH_SCOPES}

        # Save the scopes.
        self._scopes = scopes

        # If no credentials are provided, then determine the appropriate
        # defaults.
        if credentials and credentials_file:
            raise core_exceptions.DuplicateCredentialArgs(
                "'credentials_file' and 'credentials' are mutually exclusive"
            )

        if credentials_file is not None:
            credentials, _ = google.auth.load_credentials_from_file(
                credentials_file, **scopes_kwargs, quota_project_id=quota_project_id
            )
        elif credentials is None:
            credentials, _ = google.auth.default(
                **scopes_kwargs, quota_project_id=quota_project_id
            )
            # Don't apply audience if the credentials file passed from user.
            if hasattr(credentials, "with_gdch_audience"):
                credentials = credentials.with_gdch_audience(
                    api_audience if api_audience else host
                )

        # If the credentials are service account credentials, then always try to use self signed JWT.
        if (
            always_use_jwt_access
            and isinstance(credentials, service_account.Credentials)
            and hasattr(service_account.Credentials, "with_always_use_jwt_access")
        ):
            credentials = credentials.with_always_use_jwt_access(True)

        # Save the credentials.
        self._credentials = credentials

        # Save the hostname. Default to port 443 (HTTPS) if none is specified.
        if ":" not in host:
            host += ":443"
        self._host = host

    def _prep_wrapped_messages(self, client_info):
        # Precompute the wrapped methods.
        self._wrapped_methods = {
            self.get_table: gapic_v1.method.wrap_method(
                self.get_table,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.list_tables: gapic_v1.method.wrap_method(
                self.list_tables,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.get_workspace: gapic_v1.method.wrap_method(
                self.get_workspace,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.list_workspaces: gapic_v1.method.wrap_method(
                self.list_workspaces,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.get_row: gapic_v1.method.wrap_method(
                self.get_row,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.list_rows: gapic_v1.method.wrap_method(
                self.list_rows,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.create_row: gapic_v1.method.wrap_method(
                self.create_row,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.batch_create_rows: gapic_v1.method.wrap_method(
                self.batch_create_rows,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.update_row: gapic_v1.method.wrap_method(
                self.update_row,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.batch_update_rows: gapic_v1.method.wrap_method(
                self.batch_update_rows,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.delete_row: gapic_v1.method.wrap_method(
                self.delete_row,
                default_timeout=60.0,
                client_info=client_info,
            ),
            self.batch_delete_rows: gapic_v1.method.wrap_method(
                self.batch_delete_rows,
                default_timeout=60.0,
                client_info=client_info,
            ),
        }

    def close(self):
        """Closes resources associated with the transport.

        .. warning::
             Only call this method if the transport is NOT shared
             with other clients - this may cause errors in other clients!
        """
        raise NotImplementedError()

    @property
    def get_table(
        self,
    ) -> Callable[
        [tables.GetTableRequest], Union[tables.Table, Awaitable[tables.Table]]
    ]:
        raise NotImplementedError()

    @property
    def list_tables(
        self,
    ) -> Callable[
        [tables.ListTablesRequest],
        Union[tables.ListTablesResponse, Awaitable[tables.ListTablesResponse]],
    ]:
        raise NotImplementedError()

    @property
    def get_workspace(
        self,
    ) -> Callable[
        [tables.GetWorkspaceRequest],
        Union[tables.Workspace, Awaitable[tables.Workspace]],
    ]:
        raise NotImplementedError()

    @property
    def list_workspaces(
        self,
    ) -> Callable[
        [tables.ListWorkspacesRequest],
        Union[tables.ListWorkspacesResponse, Awaitable[tables.ListWorkspacesResponse]],
    ]:
        raise NotImplementedError()

    @property
    def get_row(
        self,
    ) -> Callable[[tables.GetRowRequest], Union[tables.Row, Awaitable[tables.Row]]]:
        raise NotImplementedError()

    @property
    def list_rows(
        self,
    ) -> Callable[
        [tables.ListRowsRequest],
        Union[tables.ListRowsResponse, Awaitable[tables.ListRowsResponse]],
    ]:
        raise NotImplementedError()

    @property
    def create_row(
        self,
    ) -> Callable[[tables.CreateRowRequest], Union[tables.Row, Awaitable[tables.Row]]]:
        raise NotImplementedError()

    @property
    def batch_create_rows(
        self,
    ) -> Callable[
        [tables.BatchCreateRowsRequest],
        Union[
            tables.BatchCreateRowsResponse, Awaitable[tables.BatchCreateRowsResponse]
        ],
    ]:
        raise NotImplementedError()

    @property
    def update_row(
        self,
    ) -> Callable[[tables.UpdateRowRequest], Union[tables.Row, Awaitable[tables.Row]]]:
        raise NotImplementedError()

    @property
    def batch_update_rows(
        self,
    ) -> Callable[
        [tables.BatchUpdateRowsRequest],
        Union[
            tables.BatchUpdateRowsResponse, Awaitable[tables.BatchUpdateRowsResponse]
        ],
    ]:
        raise NotImplementedError()

    @property
    def delete_row(
        self,
    ) -> Callable[
        [tables.DeleteRowRequest], Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]]
    ]:
        raise NotImplementedError()

    @property
    def batch_delete_rows(
        self,
    ) -> Callable[
        [tables.BatchDeleteRowsRequest],
        Union[empty_pb2.Empty, Awaitable[empty_pb2.Empty]],
    ]:
        raise NotImplementedError()

    @property
    def kind(self) -> str:
        raise NotImplementedError()

__all__ = ("TablesServiceTransport",)


text:
Not all of the solutions in this directory are known to be passing.

## Puzzles with Correct Solutions

## Credits

* Kanwei Li (<http://kanwei.com/>) for peaktraffic, smallworld, swarm, usrbincrash


text:
const { readFileSync, writeFileSync } = require('fs');

function packageSchema(schemaSourcePath, schemaTargetPath) {
    const schema = readFileSync(schemaSourcePath, { encoding: 'utf-8' });
    writeFileSync(
        schemaTargetPath,
        `// Auto-generated, instead of using a webpack-loader...
// Just wrapping schema/schema.graphql
export const typeDefs = \`
${schema}
\`;
`
    );

    console.log(`Wrapped schema from ${schemaSourcePath} into ${schemaTargetPath} . Use import it via:
    import { typeDefs } from './${schemaTargetPath}' // adapt path!`);
}
packageSchema('schema/schema.graphql', 'lib/localSchema.ts');


text:
from apscheduler.scheduler import Scheduler

from brie.config import ldap_config
from brie.lib.ldap_helper import *
from brie.lib.aurore_helper import *
from brie.lib.log_helper import BrieLogging
from brie.model.ldap import *
import sys
import datetime
import brie.config.credentials as credentials

def admin_user():
    bind = Ldap.connect(credentials.scheduler_user, credentials.scheduler_pass)
    dn = "dc=aurore,dc=u-psud,dc=fr"

    user = User(bind,None, dn)
    result = Member.get_by_dn(user, "uid=admin,ou=Administrators,ou=TopologyManagement,o=netscaperoot")
    user.attrs = result

    return user
#end def

sched = Scheduler()

def disconnect_members_from_residence(admin_user, residence_dn):
    members =  Member.get_all_non_admin(admin_user, residence_dn)
    BrieLogging.get().debug(CotisationComputes.current_year())
    date_actuelle = datetime.datetime.now()

    for member in members:

        machines_tuples = Machine.get_machine_tuples_of_member(admin_user, member.dn)
        if machines_tuples != []:

            if not CotisationComputes.is_cotisation_paid(member.dn, admin_user, residence_dn):
                dhcps = Machine.get_dhcps(admin_user, member.dn)
                machine_membre_tag = "machine_membre" # FIXME move to config

                for dhcp_item in dhcps:
                    if dhcp_item.uid.first() == machine_membre_tag:
                        BrieLogging.get().info("scheduler disable machine " + dhcp_item.get("dhcpHWAddress").values[0] + " pour l'utilisateur "+ member.dn + " -- "+ dhcp_item.dn)
                        dhcp_item.uid.replace(machine_membre_tag, machine_membre_tag + "_disabled")
                        admin_user.ldap_bind.save(dhcp_item)
                    #end if
                #end for
            #end if

        #end if

        # FIXME on retire la suppression pendant quelques jours le temps que les anciens mauvais payeurs soient pas supprimes
        if False and CotisationComputes.is_member_to_delete(member, admin_user, residence_dn):
            # supprime les machines mais pas le membre (il pourrait avoir besoin du compte ex : Yohan, le LDAP d'Aurores, etc)
            # alors test a ajouter pour ne supprimer que si membre d'aucun groupe
            # duplication de code avec class MachineDeleteController
            machine_dn = ldap_config.machine_base_dn + member.dn
            machines = admin_user.ldap_bind.search(machine_dn, "(objectClass=organizationalRole)", scope = ldap.SCOPE_ONELEVEL)
            for machine in machines:
                    dns = Machine.get_dns_by_id(admin_user, machine.dn)
                    if dns is None:
                        BrieLogging.get().info("Suppression machine erreur (dns is None): " + machine.dn)
                        continue
                    #end if
                    ip = IpReservation.get_ip(admin_user, residence_dn, dns.dlzData.first())
                    BrieLogging.get().info("suppression machine " + Machine.get_dhcps(admin_user, machine.dn)[0].get("dhcpHWAddress").values[0] + " pour l'utilisateur "+ member.dn + " par le scheduler")
                    #sys.stdout.flush()
                    admin_user.ldap_bind.delete_entry_subtree(machine.dn)
                    if ip is not None:
                        taken_attribute = ip.get("x-taken").first()
                        if taken_attribute is not None:
                            BrieLogging.get().debug("deleting taken_attribute for this IP address")
                            admin_user.ldap_bind.delete_attr(ip.dn, IpReservation.taken_attr(taken_attribute))
                        #end if
                    #end if
            #end for
        #end if

    #end for

#end def

@sched.interval_schedule(days=1, start_date="2013-09-30 22:14:37")
#@sched.interval_schedule(minutes=1, start_date="2013-09-30 22:14:37")
def disconnect_members_job():
    user = admin_user()

    residences = Residences.get_residences(user)

    for residence in residences:
        BrieLogging.get().info("Disconnect job on : " + residence.uniqueMember.first())
        try:
            disconnect_members_from_residence(user, residence.uniqueMember.first())
        except Exception as inst:
            BrieLogging.get().info("Exception sur le scheduler ("+ residence.uniqueMember.first() +")")
            BrieLogging.get().debug(type(inst))
    #end for

#    user.ldap_bind.disconnect()
#end def


text:
\section{Aplicação Distribuidora - Gateway}
\label{sec:app-gw}

Para a construção do \emph{Gateway} foi feita a instalação e a configuração do
MQTT \emph{Broker} Mosquitto em um dos RPI3.

\begin{citacao}

	Eclipse Mosquitto™ é um distribuidor de mensagens de código aberto (EPL/EDL
	licenciado) que implementa o protocolo MQTT versões 3.1 e 3.1.1. O MQTT
	fornece um método leve de transmitir mensagens usando um modelo de
	publicação/inscrição. Isso o torna adequado para mensagens "Internet das
	Coisas", como com sensores de baixa potência ou dispositivos móveis, como
	telefones, computadores embutidos ou microcontroladores como o Arduino. \

	\citeonline{mosquitto} Tradução Nossa.
\end{citacao}

A instalação é realizada com o gerenciador de pacotes \emph{apt-get} padrão do
raspbian como mostrado na primeira linha do \autoref{code-mosquitto}.

Nas linhas 2 e 3, adiciona-se ao arquivo padrão de configuração padrão do
\emph{Mosquitto} a linha \texttt{``password\_file /etc/mosquitto/passwd''} que
indica o arquivo de senhas a ser utilizado para autenticação. Na linha 4, é
adicionado o usuário ``user'' ao arquivo, a senha é solicitada  nas
linhas 5 e 6.

\begin{lstlisting}[language=bash,caption={Instalação e configuração do Mosquitto},label=code-mosquitto]
pi@broker:~ $ sudo apt-get install mosquitto
pi@broker:~ $ sudo sh -c 'echo "password_file /etc/mosquitto/passwd"
	>> /etc/mosquitto/mosquitto.conf'
pi@broker:~ $ sudo mosquitto_passwd -c /etc/mosquitto/passwd user
Password:
Reenter password:
pi@broker:~ $
\end{lstlisting}

Feito isso, o acesso ao \emph{Broker} está limitado aos usuários e senhas
configurados neste processo. As demais configurações permaneceram sem alterações.

Na configuração do sensor, deve ser adicionado o endereço (nome ou IP), a porta
\texttt{1883} e o par usuário e senha para que o sensor acesse o \emph{Gateway} com
sucesso.

Para verificar o funcionamento do conjunto sensor e distribuidor (\emph{Gateway}), utiliza-se um
cliente \emph{MQTT}, como o aplicativo para a plataforma Android ``MQTT Dashboard''
\cite{mqttdash} ou os aplicativos para as plataformas Java ``mqtt-spy''
\cite{mqttspy} e Windows ``MQTT.fx'' \cite{mqttfx}.

Nas figuras \ref{fig-ad-publish}, \ref{fig-ad-home-ack} e \ref{fig-ad-admin-ack},
o aplicativo ``MQTT Dashboard'' é utilizado para verificar quais sensores
estão online com a mensagem \texttt{``echo''} publicada no tópico \texttt{``ADMIN''}. Na
\autoref{fig-ad-publish}, os botões enviam mensagens com simplicidade. Na
\autoref{fig-ad-home-ack}, é visível a lista de tópicos e a última mensagem
recebida em cada um deles. Na \autoref{fig-ad-admin-ack}, fica evidente a
resposta de confirmação (\texttt{ack}) de cada um dos sensores.

\begin{figure}[htb]
	\centering
	\begin{minipage}{0.49\textwidth}
		\centering
		\caption{\label{fig-ad-publish}MQTT Dashboard: Envio de mensagens}
		\includegraphics[width=1\textwidth]{052-gateway/mqtt/ad-publish.jpg}
		\legend{Fonte: Produzido pelo autor}
	\end{minipage}
	\hfill
	\begin{minipage}{0.49\textwidth}
		\centering
		\caption{\label{fig-ad-home-ack}MQTT Dashboard: Lista de inscrições}
		\includegraphics[width=1\textwidth]{052-gateway/mqtt/ad-home-ack.jpg}
		\legend{Fonte: Produzido pelo autor}
	\end{minipage}
\end{figure}

\begin{figure}[htb]
	\centering
	\begin{minipage}{0.49\textwidth}
		\centering
		\caption{\label{fig-ad-admin-ack}MQTT Dashboard: Lista de mensagens no tópico}
		\includegraphics[width=1\textwidth]{052-gateway/mqtt/ad-admin-ack.jpg}
		\legend{Fonte: Produzido pelo autor}
	\end{minipage}
	\hfill
	\begin{minipage}{0.49\textwidth}
		\centering
		\caption{\label{fig-ad-devices-list}MQTT Dashboard: Mensagem de relatório completo do sensor}
		\includegraphics[width=1\textwidth]{052-gateway/mqtt/ad-devices-list.jpg}
		\legend{Fonte: Produzido pelo autor}
	\end{minipage}
\end{figure}

\FloatBarrier

A aplicação ``MQTT.fx'', em especial a tela mostrada na
\autoref{fig-mqttfx-stats}, revela estatísticas do \emph{Broker}, como a versão,
tempo \emph{online}, número de clientes, mensagens e utilização de rede.

\begin{figure}[htb]
	\centering
	\caption{\label{fig-mqttfx-stats}MQTT.fx: Estatísticas do \emph{Broker}}
	\includegraphics[width=1\textwidth]{052-gateway/mqtt/mqttfx-stats.png}
	\legend{Fonte: Produzido pelo autor}
\end{figure}

Para demonstrar a utilização da aplicação ``mqtt-spy'', o comando de listagem
(mencionado na \autopageref{code-mqttjs-client}) é demonstrado na
\autoref{fig-mqtt-spy-list}.

\begin{figure}[htb]
	\centering
	\caption{\label{fig-mqtt-spy-list}mqtt-spy: Listagem de dispositivos}
	\includegraphics[width=1\textwidth]{052-gateway/mqtt/mqtt-spy-list.png}
	\legend{Fonte: Produzido pelo autor}
\end{figure}


text:
/**
 * This module provides an implementation of a subset of the W3C[Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for
 * Node.js-specific performance measurements.
 *
 * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/):
 *
 * * [High Resolution Time](https://www.w3.org/TR/hr-time-2)
 * * [Performance Timeline](https://w3c.github.io/performance-timeline/)
 * * [User Timing](https://www.w3.org/TR/user-timing/)
 *
 * ```js
 * const { PerformanceObserver, performance } = require('perf_hooks');
 *
 * const obs = new PerformanceObserver((items) => {
 *   console.log(items.getEntries()[0].duration);
 *   performance.clearMarks();
 * });
 * obs.observe({ type: 'measure' });
 * performance.measure('Start to Now');
 *
 * performance.mark('A');
 * doSomeLongRunningProcess(() => {
 *   performance.measure('A to Now', 'A');
 *
 *   performance.mark('B');
 *   performance.measure('A to B', 'A', 'B');
 * });
 * ```
 * @see [source](https://github.com/nodejs/node/blob/v16.7.0/lib/perf_hooks.js)
 */
declare module 'perf_hooks' {
    import { AsyncResource } from 'node:async_hooks';
    type EntryType = 'node' | 'mark' | 'measure' | 'gc' | 'function' | 'http2' | 'http';
    interface NodeGCPerformanceDetail {
        /**
         * When `performanceEntry.entryType` is equal to 'gc', `the performance.kind` property identifies
         * the type of garbage collection operation that occurred.
         * See perf_hooks.constants for valid values.
         */
        readonly kind?: number | undefined;
        /**
         * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags`
         * property contains additional information about garbage collection operation.
         * See perf_hooks.constants for valid values.
         */
        readonly flags?: number | undefined;
    }
    /**
     * @since v8.5.0
     */
    class PerformanceEntry {
        protected constructor();
        /**
         * The total number of milliseconds elapsed for this entry. This value will not
         * be meaningful for all Performance Entry types.
         * @since v8.5.0
         */
        readonly duration: number;
        /**
         * The name of the performance entry.
         * @since v8.5.0
         */
        readonly name: string;
        /**
         * The high resolution millisecond timestamp marking the starting time of the
         * Performance Entry.
         * @since v8.5.0
         */
        readonly startTime: number;
        /**
         * The type of the performance entry. It may be one of:
         *
         * * `'node'` (Node.js only)
         * * `'mark'` (available on the Web)
         * * `'measure'` (available on the Web)
         * * `'gc'` (Node.js only)
         * * `'function'` (Node.js only)
         * * `'http2'` (Node.js only)
         * * `'http'` (Node.js only)
         * @since v8.5.0
         */
        readonly entryType: EntryType;
        /**
         * Additional detail specific to the `entryType`.
         * @since v16.0.0
         */
        readonly details?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type.
    }
    /**
     * _This property is an extension by Node.js. It is not available in Web browsers._
     *
     * Provides timing details for Node.js itself. The constructor of this class
     * is not exposed to users.
     * @since v8.5.0
     */
    class PerformanceNodeTiming extends PerformanceEntry {
        /**
         * The high resolution millisecond timestamp at which the Node.js process
         * completed bootstrapping. If bootstrapping has not yet finished, the property
         * has the value of -1.
         * @since v8.5.0
         */
        readonly bootstrapComplete: number;
        /**
         * The high resolution millisecond timestamp at which the Node.js environment was
         * initialized.
         * @since v8.5.0
         */
        readonly environment: number;
        /**
         * The high resolution millisecond timestamp of the amount of time the event loop
         * has been idle within the event loop's event provider (e.g. `epoll_wait`). This
         * does not take CPU usage into consideration. If the event loop has not yet
         * started (e.g., in the first tick of the main script), the property has the
         * value of 0.
         * @since v14.10.0, v12.19.0
         */
        readonly idleTime: number;
        /**
         * The high resolution millisecond timestamp at which the Node.js event loop
         * exited. If the event loop has not yet exited, the property has the value of -1\.
         * It can only have a value of not -1 in a handler of the `'exit'` event.
         * @since v8.5.0
         */
        readonly loopExit: number;
        /**
         * The high resolution millisecond timestamp at which the Node.js event loop
         * started. If the event loop has not yet started (e.g., in the first tick of the
         * main script), the property has the value of -1.
         * @since v8.5.0
         */
        readonly loopStart: number;
        /**
         * The high resolution millisecond timestamp at which the V8 platform was
         * initialized.
         * @since v8.5.0
         */
        readonly v8Start: number;
    }
    interface EventLoopUtilization {
        idle: number;
        active: number;
        utilization: number;
    }
    /**
     * @param util1 The result of a previous call to eventLoopUtilization()
     * @param util2 The result of a previous call to eventLoopUtilization() prior to util1
     */
    type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization;
    interface MarkOptions {
        /**
         * Additional optional detail to include with the mark.
         */
        detail?: unknown | undefined;
        /**
         * An optional timestamp to be used as the mark time.
         * @default `performance.now()`.
         */
        startTime?: number | undefined;
    }
    interface MeasureOptions {
        /**
         * Additional optional detail to include with the mark.
         */
        detail?: unknown | undefined;
        /**
         * Duration between start and end times.
         */
        duration?: number | undefined;
        /**
         * Timestamp to be used as the end time, or a string identifying a previously recorded mark.
         */
        end?: number | string | undefined;
        /**
         * Timestamp to be used as the start time, or a string identifying a previously recorded mark.
         */
        start?: number | string | undefined;
    }
    interface TimerifyOptions {
        /**
         * A histogram object created using
         * `perf_hooks.createHistogram()` that will record runtime durations in
         * nanoseconds.
         */
        histogram?: RecordableHistogram | undefined;
    }
    interface Performance {
        /**
         * If name is not provided, removes all PerformanceMark objects from the Performance Timeline.
         * If name is provided, removes only the named mark.
         * @param name
         */
        clearMarks(name?: string): void;
        /**
         * Creates a new PerformanceMark entry in the Performance Timeline.
         * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark',
         * and whose performanceEntry.duration is always 0.
         * Performance marks are used to mark specific significant moments in the Performance Timeline.
         * @param name
         */
        mark(name?: string, options?: MarkOptions): void;
        /**
         * Creates a new PerformanceMeasure entry in the Performance Timeline.
         * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure',
         * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark.
         *
         * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify
         * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist,
         * then startMark is set to timeOrigin by default.
         *
         * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp
         * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown.
         * @param name
         * @param startMark
         * @param endMark
         */
        measure(name: string, startMark?: string, endMark?: string): void;
        measure(name: string, options: MeasureOptions): void;
        /**
         * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones.
         */
        readonly nodeTiming: PerformanceNodeTiming;
        /**
         * @return the current high resolution millisecond timestamp
         */
        now(): number;
        /**
         * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured.
         */
        readonly timeOrigin: number;
        /**
         * Wraps a function within a new function that measures the running time of the wrapped function.
         * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed.
         * @param fn
         */
        timerify<T extends (...params: any[]) => any>(fn: T, options?: TimerifyOptions): T;
        /**
         * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time.
         * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait).
         * No other CPU idle time is taken into consideration.
         */
        eventLoopUtilization: EventLoopUtilityFunction;
    }
    interface PerformanceObserverEntryList {
        /**
         * Returns a list of `PerformanceEntry` objects in chronological order
         * with respect to `performanceEntry.startTime`.
         *
         * ```js
         * const {
         *   performance,
         *   PerformanceObserver
         * } = require('perf_hooks');
         *
         * const obs = new PerformanceObserver((perfObserverList, observer) => {
         *   console.log(perfObserverList.getEntries());
         *
         *    * [
         *    *   PerformanceEntry {
         *    *     name: 'test',
         *    *     entryType: 'mark',
         *    *     startTime: 81.465639,
         *    *     duration: 0
         *    *   },
         *    *   PerformanceEntry {
         *    *     name: 'meow',
         *    *     entryType: 'mark',
         *    *     startTime: 81.860064,
         *    *     duration: 0
         *    *   }
         *    * ]
         *
         *   observer.disconnect();
         * });
         * obs.observe({ type: 'mark' });
         *
         * performance.mark('test');
         * performance.mark('meow');
         * ```
         * @since v8.5.0
         */
        getEntries(): PerformanceEntry[];
        /**
         * Returns a list of `PerformanceEntry` objects in chronological order
         * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is
         * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`.
         *
         * ```js
         * const {
         *   performance,
         *   PerformanceObserver
         * } = require('perf_hooks');
         *
         * const obs = new PerformanceObserver((perfObserverList, observer) => {
         *   console.log(perfObserverList.getEntriesByName('meow'));
         *
         *    * [
         *    *   PerformanceEntry {
         *    *     name: 'meow',
         *    *     entryType: 'mark',
         *    *     startTime: 98.545991,
         *    *     duration: 0
         *    *   }
         *    * ]
         *
         *   console.log(perfObserverList.getEntriesByName('nope')); // []
         *
         *   console.log(perfObserverList.getEntriesByName('test', 'mark'));
         *
         *    * [
         *    *   PerformanceEntry {
         *    *     name: 'test',
         *    *     entryType: 'mark',
         *    *     startTime: 63.518931,
         *    *     duration: 0
         *    *   }
         *    * ]
         *
         *   console.log(perfObserverList.getEntriesByName('test', 'measure')); // []
         *   observer.disconnect();
         * });
         * obs.observe({ entryTypes: ['mark', 'measure'] });
         *
         * performance.mark('test');
         * performance.mark('meow');
         * ```
         * @since v8.5.0
         */
        getEntriesByName(name: string, type?: EntryType): PerformanceEntry[];
        /**
         * Returns a list of `PerformanceEntry` objects in chronological order
         * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType`is equal to `type`.
         *
         * ```js
         * const {
         *   performance,
         *   PerformanceObserver
         * } = require('perf_hooks');
         *
         * const obs = new PerformanceObserver((perfObserverList, observer) => {
         *   console.log(perfObserverList.getEntriesByType('mark'));
         *
         *    * [
         *    *   PerformanceEntry {
         *    *     name: 'test',
         *    *     entryType: 'mark',
         *    *     startTime: 55.897834,
         *    *     duration: 0
         *    *   },
         *    *   PerformanceEntry {
         *    *     name: 'meow',
         *    *     entryType: 'mark',
         *    *     startTime: 56.350146,
         *    *     duration: 0
         *    *   }
         *    * ]
         *
         *   observer.disconnect();
         * });
         * obs.observe({ type: 'mark' });
         *
         * performance.mark('test');
         * performance.mark('meow');
         * ```
         * @since v8.5.0
         */
        getEntriesByType(type: EntryType): PerformanceEntry[];
    }
    type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void;
    class PerformanceObserver extends AsyncResource {
        constructor(callback: PerformanceObserverCallback);
        /**
         * Disconnects the `PerformanceObserver` instance from all notifications.
         * @since v8.5.0
         */
        disconnect(): void;
        /**
         * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes`or `options.type`:
         *
         * ```js
         * const {
         *   performance,
         *   PerformanceObserver
         * } = require('perf_hooks');
         *
         * const obs = new PerformanceObserver((list, observer) => {
         *   // Called three times synchronously. `list` contains one item.
         * });
         * obs.observe({ type: 'mark' });
         *
         * for (let n = 0; n < 3; n++)
         *   performance.mark(`test${n}`);
         * ```
         * @since v8.5.0
         */
        observe(
            options:
                | {
                      entryTypes: ReadonlyArray<EntryType>;
                  }
                | {
                      type: EntryType;
                  }
        ): void;
    }
    namespace constants {
        const NODE_PERFORMANCE_GC_MAJOR: number;
        const NODE_PERFORMANCE_GC_MINOR: number;
        const NODE_PERFORMANCE_GC_INCREMENTAL: number;
        const NODE_PERFORMANCE_GC_WEAKCB: number;
        const NODE_PERFORMANCE_GC_FLAGS_NO: number;
        const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number;
        const NODE_PERFORMANCE_GC_FLAGS_FORCED: number;
        const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number;
        const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number;
        const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number;
        const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number;
    }
    const performance: Performance;
    interface EventLoopMonitorOptions {
        /**
         * The sampling rate in milliseconds.
         * Must be greater than zero.
         * @default 10
         */
        resolution?: number | undefined;
    }
    interface Histogram {
        /**
         * Returns a `Map` object detailing the accumulated percentile distribution.
         * @since v11.10.0
         */
        readonly percentiles: Map<number, number>;
        /**
         * The number of times the event loop delay exceeded the maximum 1 hour event
         * loop delay threshold.
         * @since v11.10.0
         */
        readonly exceeds: number;
        /**
         * The minimum recorded event loop delay.
         * @since v11.10.0
         */
        readonly min: number;
        /**
         * The maximum recorded event loop delay.
         * @since v11.10.0
         */
        readonly max: number;
        /**
         * The mean of the recorded event loop delays.
         * @since v11.10.0
         */
        readonly mean: number;
        /**
         * The standard deviation of the recorded event loop delays.
         * @since v11.10.0
         */
        readonly stddev: number;
        /**
         * Resets the collected histogram data.
         * @since v11.10.0
         */
        reset(): void;
        /**
         * Returns the value at the given percentile.
         * @since v11.10.0
         * @param percentile A percentile value in the range (0, 100].
         */
        percentile(percentile: number): number;
    }
    interface IntervalHistogram extends Histogram {
        /**
         * Enables the update interval timer. Returns `true` if the timer was
         * started, `false` if it was already started.
         * @since v11.10.0
         */
        enable(): boolean;
        /**
         * Disables the update interval timer. Returns `true` if the timer was
         * stopped, `false` if it was already stopped.
         * @since v11.10.0
         */
        disable(): boolean;
    }
    interface RecordableHistogram extends Histogram {
        /**
         * @since v15.9.0
         * @param val The amount to record in the histogram.
         */
        record(val: number | bigint): void;
        /**
         * Calculates the amount of time (in nanoseconds) that has passed since the
         * previous call to `recordDelta()` and records that amount in the histogram.
         *
         * ## Examples
         * @since v15.9.0
         */
        recordDelta(): void;
    }
    /**
     * _This property is an extension by Node.js. It is not available in Web browsers._
     *
     * Creates an `IntervalHistogram` object that samples and reports the event loop
     * delay over time. The delays will be reported in nanoseconds.
     *
     * Using a timer to detect approximate event loop delay works because the
     * execution of timers is tied specifically to the lifecycle of the libuv
     * event loop. That is, a delay in the loop will cause a delay in the execution
     * of the timer, and those delays are specifically what this API is intended to
     * detect.
     *
     * ```js
     * const { monitorEventLoopDelay } = require('perf_hooks');
     * const h = monitorEventLoopDelay({ resolution: 20 });
     * h.enable();
     * // Do something.
     * h.disable();
     * console.log(h.min);
     * console.log(h.max);
     * console.log(h.mean);
     * console.log(h.stddev);
     * console.log(h.percentiles);
     * console.log(h.percentile(50));
     * console.log(h.percentile(99));
     * ```
     * @since v11.10.0
     */
    function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram;
    interface CreateHistogramOptions {
        /**
         * The minimum recordable value. Must be an integer value greater than 0.
         * @default 1
         */
        min?: number | bigint | undefined;
        /**
         * The maximum recordable value. Must be an integer value greater than min.
         * @default Number.MAX_SAFE_INTEGER
         */
        max?: number | bigint | undefined;
        /**
         * The number of accuracy digits. Must be a number between 1 and 5.
         * @default 3
         */
        figures?: number | undefined;
    }
    /**
     * Returns a `RecordableHistogram`.
     * @since v15.9.0
     */
    function createHistogram(options?: CreateHistogramOptions): RecordableHistogram;
}
declare module 'node:perf_hooks' {
    export * from 'perf_hooks';
}


text:
package net.bytebuddy.agent.builder;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.loading.ClassInjector;

import java.lang.instrument.ClassFileTransformer;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * This class serves as a dispatcher for creating lambda expression objects when Byte Buddy is configured to instrument the
 * {@code java.lang.invoke.LambdaMetafactory}. For this purpose, this class is injected into the class path to serve as a VM-global
 * singleton and for becoming reachable from the JVM's meta factory. This class keeps a reference to all registered transformers which need
 * to be explicitly deregistered in order to avoid a memory leak.
 */
@HashCodeAndEqualsPlugin.Enhance
public class LambdaFactory {

    /**
     * The name of the field to access.
     */
    private static final String FIELD_NAME = "CLASS_FILE_TRANSFORMERS";

    /**
     * A mapping of all registered class file transformers and their lambda factories, linked in their application order.
     * This field <b>must not</b> be accessed directly but only by reading this class from the system class loader.
     */
    @SuppressFBWarnings(value = "MS_MUTABLE_COLLECTION_PKGPROTECT", justification = "The field must be accessible by different class loader instances.")
    public static final Map<ClassFileTransformer, LambdaFactory> CLASS_FILE_TRANSFORMERS = new ConcurrentHashMap<ClassFileTransformer, LambdaFactory>();

    /**
     * The target instance that is a factory for creating lambdas.
     */
    private final Object target;

    /**
     * The dispatcher method to invoke for creating a new lambda instance.
     */
    private final Method dispatcher;

    /**
     * Creates a new lambda factory.
     *
     * @param target     The target instance that is a factory for creating lambdas.
     * @param dispatcher The dispatcher method to invoke for creating a new lambda instance.
     */
    public LambdaFactory(Object target, Method dispatcher) {
        this.target = target;
        this.dispatcher = dispatcher;
    }

    /**
     * Registers a class file transformer together with a factory for creating a lambda expression. It is possible to call this method independently
     * of the class loader's context as the supplied injector makes sure that the manipulated collection is the one that is held by the system class
     * loader.
     *
     * @param classFileTransformer The class file transformer to register.
     * @param classFileFactory     The lambda class file factory to use. This factory must define a visible instance method with the signature
     *                             {@code byte[] make(Object, String, Object, Object, Object, Object, boolean, List, List, Collection}. The arguments provided
     *                             are the invokedynamic call site's lookup object, the lambda method's name, the factory method's type, the lambda method's
     *                             type, the target method's handle, the specialized method type of the lambda expression, a boolean to indicate
     *                             serializability, a list of marker interfaces, a list of additional bridges and a collection of class file transformers to
     *                             apply.
     * @return {@code true} if this is the first registered transformer. This indicates that the {@code LambdaMetafactory} must be instrumented to delegate
     * to this alternative factory.
     */
    @SuppressWarnings("all")
    public static boolean register(ClassFileTransformer classFileTransformer, Object classFileFactory) {
        try {
            TypeDescription typeDescription = TypeDescription.ForLoadedType.of(LambdaFactory.class);
            Class<?> lambdaFactory = ClassInjector.UsingReflection.ofSystemClassLoader()
                    .inject(Collections.singletonMap(typeDescription, ClassFileLocator.ForClassLoader.read(LambdaFactory.class)))
                    .get(typeDescription);
            @SuppressWarnings("unchecked")
            Map<ClassFileTransformer, Object> classFileTransformers = (Map<ClassFileTransformer, Object>) lambdaFactory
                    .getField(FIELD_NAME)
                    .get(null);
            synchronized (classFileTransformers) {
                try {
                    return classFileTransformers.isEmpty();
                } finally {
                    classFileTransformers.put(classFileTransformer, lambdaFactory
                            .getConstructor(Object.class, Method.class)
                            .newInstance(classFileFactory, classFileFactory.getClass().getMethod("make",
                                    Object.class,
                                    String.class,
                                    Object.class,
                                    Object.class,
                                    Object.class,
                                    Object.class,
                                    boolean.class,
                                    List.class,
                                    List.class,
                                    Collection.class)));
                }
            }
        } catch (RuntimeException exception) {
            throw exception;
        } catch (Exception exception) {
            throw new IllegalStateException("Could not register class file transformer", exception);
        }
    }

    /**
     * Releases a class file transformer.
     *
     * @param classFileTransformer The class file transformer to release.
     * @return {@code true} if the removed transformer was the last class file transformer registered. This indicates that the {@code LambdaMetafactory} must
     * be instrumented to no longer delegate to this alternative factory.
     */
    @SuppressWarnings("all")
    public static boolean release(ClassFileTransformer classFileTransformer) {
        try {
            @SuppressWarnings("unchecked")
            Map<ClassFileTransformer, ?> classFileTransformers = (Map<ClassFileTransformer, ?>) ClassLoader.getSystemClassLoader()
                    .loadClass(LambdaFactory.class.getName())
                    .getField(FIELD_NAME)
                    .get(null);
            synchronized (classFileTransformers) {
                return classFileTransformers.remove(classFileTransformer) != null && classFileTransformers.isEmpty();
            }
        } catch (RuntimeException exception) {
            throw exception;
        } catch (Exception exception) {
            throw new IllegalStateException("Could not release class file transformer", exception);
        }
    }

    /**
     * Applies this lambda meta factory.
     *
     * @param caller                 A lookup context representing the creating class of this lambda expression.
     * @param invokedName            The name of the lambda expression's represented method.
     * @param invokedType            The type of the lambda expression's factory method.
     * @param samMethodType          The type of the lambda expression's represented method.
     * @param implMethod             A handle representing the target of the lambda expression's method.
     * @param instantiatedMethodType A specialization of the type of the lambda expression's represented method.
     * @param serializable           {@code true} if the lambda expression should be serializable.
     * @param markerInterfaces       A list of interfaces for the lambda expression to represent.
     * @param additionalBridges      A list of additional bridge methods to be implemented by the lambda expression.
     * @param classFileTransformers  A collection of class file transformers to apply when creating the class.
     * @return A binary representation of the transformed class file.
     */
    private byte[] invoke(Object caller,
                          String invokedName,
                          Object invokedType,
                          Object samMethodType,
                          Object implMethod,
                          Object instantiatedMethodType,
                          boolean serializable,
                          List<Class<?>> markerInterfaces,
                          List<?> additionalBridges,
                          Collection<ClassFileTransformer> classFileTransformers) {

        try {
            return (byte[]) dispatcher.invoke(target,
                    caller,
                    invokedName,
                    invokedType,
                    samMethodType,
                    implMethod,
                    instantiatedMethodType,
                    serializable,
                    markerInterfaces,
                    additionalBridges,
                    classFileTransformers);
        } catch (RuntimeException exception) {
            throw exception;
        } catch (Exception exception) {
            throw new IllegalStateException("Cannot create class for lambda expression", exception);
        }
    }

    /**
     * Dispatches the creation of a new class representing a class file.
     *
     * @param caller                 A lookup context representing the creating class of this lambda expression.
     * @param invokedName            The name of the lambda expression's represented method.
     * @param invokedType            The type of the lambda expression's factory method.
     * @param samMethodType          The type of the lambda expression's represented method.
     * @param implMethod             A handle representing the target of the lambda expression's method.
     * @param instantiatedMethodType A specialization of the type of the lambda expression's represented method.
     * @param serializable           {@code true} if the lambda expression should be serializable.
     * @param markerInterfaces       A list of interfaces for the lambda expression to represent.
     * @param additionalBridges      A list of additional bridge methods to be implemented by the lambda expression.
     * @return A binary representation of the transformed class file.
     */
    public static byte[] make(Object caller,
                              String invokedName,
                              Object invokedType,
                              Object samMethodType,
                              Object implMethod,
                              Object instantiatedMethodType,
                              boolean serializable,
                              List<Class<?>> markerInterfaces,
                              List<?> additionalBridges) {
        return CLASS_FILE_TRANSFORMERS.values().iterator().next().invoke(caller,
                invokedName,
                invokedType,
                samMethodType,
                implMethod,
                instantiatedMethodType,
                serializable,
                markerInterfaces,
                additionalBridges,
                CLASS_FILE_TRANSFORMERS.keySet());
    }
}


text:
#ifndef _SLG_NULLMAT_H
#define	_SLG_NULLMAT_H

#include "slg/materials/material.h"

namespace slg {

//------------------------------------------------------------------------------
// Null material
//------------------------------------------------------------------------------

class NullMaterial : public Material {
public:
	NullMaterial() : Material(NULL, NULL) { }

	virtual MaterialType GetType() const { return NULLMAT; }
	virtual BSDFEvent GetEventTypes() const { return SPECULAR | TRANSMIT; };

	virtual bool IsDelta() const { return true; }
	virtual bool IsPassThrough() const { return true; }
	virtual luxrays::Spectrum GetPassThroughTransparency(const HitPoint &hitPoint,
		const luxrays::Vector &localFixedDir, const float passThroughEvent) const { return luxrays::Spectrum(1.f); }

	virtual luxrays::Spectrum Evaluate(const HitPoint &hitPoint,
		const luxrays::Vector &localLightDir, const luxrays::Vector &localEyeDir, BSDFEvent *event,
		float *directPdfW = NULL, float *reversePdfW = NULL) const;
	virtual luxrays::Spectrum Sample(const HitPoint &hitPoint,
		const luxrays::Vector &localFixedDir, luxrays::Vector *localSampledDir,
		const float u0, const float u1, const float passThroughEvent,
		float *pdfW, float *absCosSampledDir, BSDFEvent *event,
		const BSDFEvent requestedEvent) const;
	virtual void Pdf(const HitPoint &hitPoint,
		const luxrays::Vector &localLightDir, const luxrays::Vector &localEyeDir,
		float *directPdfW, float *reversePdfW) const {
		if (directPdfW)
			*directPdfW = 0.f;
		if (reversePdfW)
			*reversePdfW = 0.f;
	}

	virtual luxrays::Properties ToProperties() const;
};

}

#endif	/* _SLG_NULLMAT_H */


text:
/**
 * Test suite created by Maxime LUCE <https://github.com/SomaticIT>
 *
 * Created by using code samples from https://github.com/auth0/node-jsonwebtoken.
 */

/// <reference types="node" />

import jwt = require("jsonwebtoken");
import fs = require("fs");

var token: string;
var cert: Buffer;

/**
 * jwt.sign
 * https://github.com/auth0/node-jsonwebtoken#usage
 */
// sign with default (HMAC SHA256)
token = jwt.sign({ foo: 'bar' }, 'shhhhh');

// sign with RSA SHA256
cert = fs.readFileSync('private.key');  // get private key
token = jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256'});

// sign asynchronously
jwt.sign({ foo: 'bar' }, cert, { algorithm: 'RS256' }, function(err: Error, token: string) {
  console.log(token);
});

/**
 * jwt.verify
 * https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback
 */
// verify a token symmetric
jwt.verify(token, 'shhhhh', function(err, decoded) {
  console.log(decoded.foo) // bar
});

// invalid token
jwt.verify(token, 'wrong-secret', function(err, decoded) {
  // err
  // decoded undefined
});

// verify a token asymmetric
cert = fs.readFileSync('public.pem');  // get public key
jwt.verify(token, cert, function(err, decoded) {
  console.log(decoded.foo) // bar
});

// verify audience
cert = fs.readFileSync('public.pem');  // get public key
jwt.verify(token, cert, { audience: 'urn:foo' }, function(err, decoded) {
  // if audience mismatch, err == invalid audience
});

// verify issuer
cert = fs.readFileSync('public.pem');  // get public key
jwt.verify(token, cert, { audience: 'urn:foo', issuer: 'urn:issuer' }, function(err, decoded) {
  // if issuer mismatch, err == invalid issuer
});

// verify algorithm
cert = fs.readFileSync('public.pem');  // get public key
jwt.verify(token, cert, { algorithms: ['RS256'] }, function(err, decoded) {
  // if algorithm mismatch, err == invalid algorithm
});

// verify without expiration check
cert = fs.readFileSync('public.pem');  // get public key
jwt.verify(token, cert, { ignoreExpiration: true }, function(err, decoded) {
  // if ignoreExpration == false and token is expired, err == expired token
});

/**
 * jwt.decode
 * https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken
 */
var decoded = jwt.decode(token);

decoded = jwt.decode(token, { complete: false });

decoded = jwt.decode(token, { json: false });

decoded = jwt.decode(token, { complete: false, json: false });


text:
(function () {
    'use strict';

    angular.module('App').component('login', {
        templateUrl: 'static/views/login.html',
        controller: 'LoginController'
    });
})();


text:
package jp.ac.nii.prl.mape.autoscaling.service;

import jp.ac.nii.prl.mape.autoscaling.model.Adaptation;
import jp.ac.nii.prl.mape.autoscaling.model.Deployment;

public class PlanningServiceImpl implements PlanningService {

	@Override
	public Deployment plan(final Deployment deployment, final Adaptation adaptation) {
		assert(deployment != null && adaptation != null);

		if (!adaptation.isAdapt()) {
			return deployment;
		}
		return null;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.oneandone</groupId>
        <artifactId>typedrest-parent</artifactId>
        <version>0.31-SNAPSHOT</version>
        <relativePath>../parent</relativePath>
    </parent>
    <artifactId>typedrest-archetype</artifactId>
    <packaging>maven-archetype</packaging>

    <name>TypedRest Archetype</name>
    <description>Archetype for building TypedRest web applications that can run standalone or be consumed as a library.</description>

    <build>
        <extensions>
            <extension>
                <groupId>org.apache.maven.archetype</groupId>
                <artifactId>archetype-packaging</artifactId>
                <version>2.4</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <artifactId>maven-archetype-plugin</artifactId>
                <version>2.4</version>
                <extensions>true</extensions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.7</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <escapeString>\</escapeString>
                </configuration>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
                <includes>
                    <include>archetype-resources/parent/pom.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>false</filtering>
                <excludes>
                    <exclude>archetype-resources/parent/pom.xml</exclude>
                </excludes>
            </resource>
        </resources>
    </build>
</project>


text:
"""The DoorBird integration constants."""
from homeassistant.const import Platform

DOMAIN = "doorbird"
PLATFORMS = [Platform.BUTTON, Platform.CAMERA]
DOOR_STATION = "door_station"
DOOR_STATION_INFO = "door_station_info"
DOOR_STATION_EVENT_ENTITY_IDS = "door_station_event_entity_ids"

CONF_EVENTS = "events"
MANUFACTURER = "Bird Home Automation Group"
DOORBIRD_OUI = "1CCAE3"

DOORBIRD_INFO_KEY_FIRMWARE = "FIRMWARE"
DOORBIRD_INFO_KEY_BUILD_NUMBER = "BUILD_NUMBER"
DOORBIRD_INFO_KEY_DEVICE_TYPE = "DEVICE-TYPE"
DOORBIRD_INFO_KEY_RELAYS = "RELAYS"
DOORBIRD_INFO_KEY_PRIMARY_MAC_ADDR = "PRIMARY_MAC_ADDR"
DOORBIRD_INFO_KEY_WIFI_MAC_ADDR = "WIFI_MAC_ADDR"

UNDO_UPDATE_LISTENER = "undo_update_listener"


text:
#ifndef INSTRUMENT_FUNCTION_VIEWS_H
#define INSTRUMENT_FUNCTION_VIEWS_H

#include "ModelView.h"

#include <QWidget>

class QLabel;
class ComboBox;
class GroupBox;
class Knob;
class TempoSyncKnob;

class InstrumentFunctionArpeggio;
class InstrumentFunctionNoteStacking;

class InstrumentFunctionNoteStackingView : public QWidget, public ModelView
{
	Q_OBJECT
public:
	InstrumentFunctionNoteStackingView( InstrumentFunctionNoteStacking* cc, QWidget* parent = NULL );
	virtual ~InstrumentFunctionNoteStackingView();

private:
	virtual void modelChanged();

	InstrumentFunctionNoteStacking * m_cc;

	GroupBox * m_chordsGroupBox;
	ComboBox * m_chordsComboBox;
	Knob * m_chordRangeKnob;

} ;

class InstrumentFunctionArpeggioView : public QWidget, public ModelView
{
	Q_OBJECT
public:
	InstrumentFunctionArpeggioView( InstrumentFunctionArpeggio* arp, QWidget* parent = NULL );
	virtual ~InstrumentFunctionArpeggioView();

private:
	virtual void modelChanged();

	InstrumentFunctionArpeggio * m_a;
	GroupBox * m_arpGroupBox;
	ComboBox * m_arpComboBox;
	Knob * m_arpRangeKnob;
	Knob * m_arpCycleKnob;
	Knob * m_arpSkipKnob;
	Knob * m_arpMissKnob;
	TempoSyncKnob * m_arpTimeKnob;
	Knob * m_arpGateKnob;

	ComboBox * m_arpDirectionComboBox;
	ComboBox * m_arpModeComboBox;

} ;

#endif


text:
package org.retrostore.data.app;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.annotation.Cache;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;

/**
 * A media image that could e.g. contain disk or cassette data.
 */
@Entity
@Cache
public class MediaImage {
  @Id
  public Long id;

  @Index
  public String appId;

  /** The timestamp of when this image was uploaded. */
  public long uploadTime;
  /**
   * The filename, including the extension. Some emulator use parts of the filename to determine how
   * to handle it.
   */
  public String filename;
  /** An optional note for this image to describe it. */
  public String description;
  /** Will become a GAE blob structure. */
  public byte[] data;

  public static Key<MediaImage> key(long id) {
    return Key.create(MediaImage.class, id);
  }

}


text:
if (typeof define !== 'function') { var define = require('amdefine')(module) }
define( function(require,exports,module) {

var _ = require('underscore');
var $ = require('jquery');
var Events = require('backbone').Events;
var SockJS = require('sockjs-client');

var Socket = module.exports = function(channel,socket_id,websocket){
  this.open_handler = function(){};
  this.close_handler = function(){
    $('#es-modal-box').html("
Your connection to the server has been lost, please refresh the page.
");
    $('#es-modal-overlay').show();
  };
  this.error_handler = function(){};
  this.message_handler = function(){};
  this.initWebsocket(channel,socket_id,websocket);
};

_.extend(Socket.prototype, Events,{

  initWebsocket: function(channel,socket_id,websocket){
    var socket = this;
    this.ws = websocket || new SockJS(window.location.protocol + '//' + window.location.host +'/'+ channel +'/pubsub/',{debug:true,devel:true});

    this.ws.onopen = _.bind(this.open,this);
    this.ws.onerror= _.bind(this.error,this);
    this.ws.onclose = _.bind(this.close,this);
    this.ws.onmessage = _.bind(this.message,this);
  },

  onMessage: function(handler){
    this.message_handler = handler;
  },

  message: function(e){
    this.message_handler(e);
  },

  onOpen: function(handler){
    this.open_handler = handler;
  },

  open: function(e){
    this.open_handler(e);
  },

  onClose: function(handler){
    this.close_handler = handler;
  },

  close: function(e){
    this.close_handler(e);
  },

  onError: function(handler){
    this.error_handler = handler;
  },

  error: function(e){
    this.error_handler(e);
  },

  send: function(msg){
    this.ws.send(msg);
  }
});

});


text:
package hudson.slaves;

import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.TimeUnit;

import hudson.model.Computer;
import hudson.model.Queue;
import jenkins.model.Jenkins;
import hudson.model.Node;
import hudson.model.PeriodicWork;
import hudson.Extension;
import org.jenkinsci.Symbol;

/**
 * Periodically checks the agents and try to reconnect dead agents.
 *
 * @author Kohsuke Kawaguchi
 * @author Stephen Connolly
 */
@Extension @Symbol("computerRetention")
public class ComputerRetentionWork extends PeriodicWork {

    /**
     * Use weak hash map to avoid leaking {@link Computer}.
     */
    private final Map<Computer, Long> nextCheck = new WeakHashMap<>();

    public long getRecurrencePeriod() {
        return MIN;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void doRun() {
        final long startRun = System.currentTimeMillis();
        for (final Computer c : Jenkins.get().getComputers()) {
            Queue.withLock(new Runnable() {
                @Override
                public void run() {
                    Node n = c.getNode();
                    if (n!=null && n.isHoldOffLaunchUntilSave())
                        return;
                    if (!nextCheck.containsKey(c) || startRun > nextCheck.get(c)) {
                        // at the moment I don't trust strategies to wait more than 60 minutes
                        // strategies need to wait at least one minute
                        final long waitInMins = Math.max(1, Math.min(60, c.getRetentionStrategy().check(c)));
                        nextCheck.put(c, startRun + TimeUnit.MINUTES.toMillis(waitInMins));
                    }
                }
            });
        }
    }
}


text:
using System;

using NewRelic.Microsoft.SqlServer.Plugin.Core;

namespace NewRelic.Microsoft.SqlServer.Plugin
{
    public interface IMetricQuery
    {
        string QueryName { get; }
        Type QueryType { get; }
        string MetricPattern { get; }
        string ResultTypeName { get; }
        void AddMetrics(QueryContext context);
    }
}


text:
#import "NSObject.h"

#import "NSCopying-Protocol.h"

// Not exported
@interface TSDWrapPolygon : NSObject <NSCopying>
{
    void *mPolygon;
    _Bool mIntersectsSelf;
    _Bool mComputedSelfIntersection;
    struct CGRect mBounds;
    _Bool mComputedBounds;
}

- (id).cxx_construct;
- (struct CGPoint)intersectionPointBetween:(struct CGPoint)arg1 and:(struct CGPoint)arg2;
- (void)transformUsingAffineTransform:(struct CGAffineTransform)arg1;
- (id)bezierPath;
- (struct CGRect)bounds;
- (void *)polygon;
- (_Bool)intersectsSelf;
- (void)setIntersectsSelf:(_Bool)arg1;
- (void)setPath:(id)arg1;
- (void)dealloc;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)initWithPath:(id)arg1;

@end


text:
#ifndef MDSEARCH_BUCKETKDTREE_H
#define MDSEARCH_BUCKETKDTREE_H

#include "IndexStructure.h"

namespace mdsearch
{

	struct BucketKDNode
	{
		enum NodeType
		{
			TYPE_LEAF = 0,
			TYPE_SPLIT
		};

		NodeType type;
		BucketKDNode* parent;
		// For leaves
		IndexList points;
		// For non-leaves
		int cuttingDim;
		Real cuttingVal;
		BucketKDNode* leftChild;
		BucketKDNode* rightChild;

		/* Constructs empty leaf node. */
		BucketKDNode(BucketKDNode* parent);
		/* Constructs split node. */
		BucketKDNode(BucketKDNode* parent, int cuttingDim, Real cuttingVal,
			BucketKDNode* leftChild, BucketKDNode* rightChild);

		virtual ~BucketKDNode();
	};

	class BucketKDTree : public IndexStructure
	{

	public:
		BucketKDTree(unsigned int numDimensions, int maxPointsUntilSplit, int minPointsUntilMerge);
		virtual ~BucketKDTree();

		virtual void clear();
		virtual bool insert(const Point& p);
		virtual bool remove(const Point& p);
		virtual bool update(const Point& oldPoint, const Point& newPoint);
		virtual bool pointExists(const Point& p);

		double computeBalanceFactor() const;
		BucketKDNode* rootNode() const;

		virtual std::string toString() const;

	private:
		BucketKDNode* findLeafForPoint(const Point& p) const;
		BucketKDNode* findLeafForPoint(const Point& p, int& level) const; // returns level of tree leaf is on too
		int getPointIndexInBucket(const IndexList& bucketIndices, const Point& p) const;
		bool containsPoint(const BucketKDNode* leaf, const Point& p) const;
		void mergeSiblingLeaves(BucketKDNode* leaf, BucketKDNode* sibling);

		std::string nodeToString(const std::string& title,
			const BucketKDNode* node, unsigned int level = 0) const;

		PointList allPoints;
		RealList allPointSums;
		BucketKDNode* root;
		/* Maximum number of nodes allowed to be stored in a leaf node.
		 * If the number of points in a leaf exceeds this number, the
		 * leaf is split. */
		int maxPointsUntilSplit;
		/* Minimum total number of points two LEAF children of a node can
		 * store before merging the two children into a single leaf. */
		int minPointsUntilMerge;

	};

}

#endif


text:
package com.ecommerce.ecommercepizza.fragment;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.ecommerce.ecommercepizza.R;
import com.ecommerce.ecommercepizza.common.BaseFragment;

/**
 * Created by Asus on 25/03/2017.
 */

public class FragmentLogin extends BaseFragment{
    private static Context contexts;
    private static Activity activity;
    private Button saveBtn;
    EditText textUserName;

    @Override
    public void initView() {
        view = inflater.inflate(R.layout.login, container, false);
        contexts = getContext();
        fragmentManager= getFragmentManager();
        activity = getActivity();

    }

}


text:
$:.unshift File.join(File.dirname(__FILE__), "../../lib/")

require 'sqlpostgres'
include SqlPostgres

Connection.open do |connection|

  connection.exec("create temporary table person (name text)")

  # Example: ../manual.dbk
  insert = Insert.new('person')
  insert.insert('name', 'Fred')
  insert.exec(connection)
  # End example

end


text:
<?php
/****** Maintenance Mode *********/
session_start();

// Turns ON test CSS. Used for bug fixing to check if CSS used is
if ($_REQUEST['mln'] == 'testcss_on') {$_SESSION['mln_testcss'] = 'on';}
// Turns OFF test CSS. Used for bug fixing to check if CSS used is
if ($_REQUEST['mln'] == 'testcss_off') {$_SESSION['mln_testcss'] = '';}

/*
// Turns keyboard accessibility on and off
if ($_REQUEST['mln'] == 'keyboard_on') {update_option('suckerfish_keyboard', 'on');}
elseif ($_REQUEST['mln'] == 'keyboard_off') {update_option('suckerfish_keyboard', '');}

// Sets Superfish speed
if ($_REQUEST['mln'] == 'superfish_instant') {update_option('suckerfish_superfish_speed', 'instant');}
elseif ($_REQUEST['mln'] == 'superfish_fast') {update_option('suckerfish_superfish_speed', 'fast');}
elseif ($_REQUEST['mln'] == 'superfish_normal') {update_option('suckerfish_superfish_speed', 'normal');}
elseif ($_REQUEST['mln'] == 'superfish_slow') {update_option('suckerfish_superfish_speed', 'slow');}

// Disable and enable built in CSS file
if ($_REQUEST['mln'] == 'disablecss_on') {update_option('suckerfish_disablecss', 'on');}
elseif ($_REQUEST['mln'] == 'disablecss_off') {update_option('suckerfish_disablecss', '');}

// Turns inline CSS on and off
if ($_REQUEST['mln'] == 'inlinecss_on') {update_option('suckerfish_inlinecss', 'on');}
elseif ($_REQUEST['mln'] == 'inlinecss_off') {update_option('suckerfish_inlinecss', '');}
*/

// If menu manually turned off while in maintenance mode then switches off plugin
if ($_REQUEST['mln'] == 'off') {$_SESSION['mln'] = '';}

// If menu manually activated while in maintenance mode then loads plugin
if ($_REQUEST['mln'] == 'on' || $_SESSION['mln'] == 'on') {$_SESSION['mln'] = 'on';require('core.php');}

?>


text:
<?php

namespace AppBundle\Entity;

use DateTime;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Table(name="lag_project")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ProjectRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Project
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer")
     * @var int
     */
    protected $id;

    /**
     * @ORM\Column(name="name", type="string", length=255)
     * @var string
     */
    protected $name;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Customer", inversedBy="projects")
     */
    protected $customer;

    /**
     * @ORM\Column(name="created_at", type="datetime")
     * @Gedmo\Timestampable(on="create")
     * @var DateTime
     */
    protected $createdAt;

    /**
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     * @Gedmo\Timestampable(on="update")
     * @var DateTime
     */
    protected $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\GeorgeProfile", mappedBy="project", fetch="EAGER")
     */
    protected $profiles;

    /**
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @param int $id
     * @return Project
     */
    public function setId($id)
    {
        $this->id = $id;
        return $this;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     * @return Project
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCustomer()
    {
        return $this->customer;
    }

    /**
     * @param mixed $customer
     * @return Project
     */
    public function setCustomer($customer)
    {
        $this->customer = $customer;
        return $this;
    }

    /**
     * @return DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param DateTime $createdAt
     * @return Project
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
        return $this;
    }

    /**
     * @return DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * @param DateTime $updatedAt
     * @return Project
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;
        return $this;
    }

    /**
     * @return GeorgeProfile[]|Collection
     */
    public function getProfiles()
    {
        return $this->profiles;
    }

    /**
     * @param mixed $profiles
     * @return Project
     */
    public function setProfiles($profiles)
    {
        $this->profiles = $profiles;
        return $this;
    }
}