text:
A simple script to convert a har file, generated on Chrome Dev Tools, to Spirent Avalanche action list

## Usage

First open Chrome DevTools an generate a HAR file from your network tab.
cf. [https://developer.chrome.com/devtools/docs/network](https://developer.chrome.com/devtools/docs/network#saving-network-data)

Then convert to a action list file for Avalanche:

```sh
./har2avalanche.rb my-file.har > avalanche.txt
```

You can check [Avalanche documentation](http://kms.spirentcom.com/CSC/Avalanche_WebHelp/index.htm#base/welcome.htm)

## Options

List the options with the --help flag:

```sh
./har2avalanche.rb --help
```

```
Usage: har2avalanche.rb [options]

    -f, --file FILE                  HAR file to be parsed
    -b, --best-try                   Tries the best to simulate reality
                                     flags --with-referer --with-headers
        --include-hosts x,y,z...     Hosts to be whitelisted
        --exclude-hosts x,y,z...     Hosts to be blacklisted
    -R, --with-referer               Add <REFERER> directive
    -H, --with-headers               Add <ADDITIONAL_HEADER> directives
        --include-headers x,y,z...   Headers to be whitelisted
                                     flags --with-headers
        --exclude-headers x,y,z...   Headers to be blacklisted
                                     flags --with-headers

    -h, --help                       Show this message
    -v, --version                    Show version
```


text:
package com.hearthsim.card.classic.minion.common;

import com.hearthsim.card.minion.Minion;

public class DamagedGolem extends Minion {

    public DamagedGolem() {
        super();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html>
  <link rel='stylesheet' type='text/css' href='style.css'>
  <body>
    <fieldset class="disabled" disabled>
      <legend id='i'>
        <textarea class="enabled"></textarea>
      </legend>
    </fieldset>
  </body>
</html>


text:
package xyz.kuori.timeseries;

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

public class Archive
{
    private String storage_path;

    public Archive (String storage_path)
    {
        this.storage_path = storage_path;
    }

    public List<String> listTimeSeries ()
    {
        List<String> listing = new ArrayList<String>();

        File[] filesList = new File (storage_path).listFiles ();

        for (File f : filesList)
        {
            if(f.isDirectory())
            {
                // Nada por enquanto
            }
            else if(f.isFile())
            {
                listing.add (f.getName());
            }
        }

        return (listing);
    }

    public static String info ()
    {
        return ("TimeSeries Online");
    }
}


text:
namespace JustinCredible.TheWeek.Services {

    export class TheWeekAPI {

        //#region Injection

        public static ID = "TheWeekAPI";

        public static get $inject(): string[] {
            return [
                "$q",
                "$http",
                Logger.ID,
            ];
        }

        constructor (
            private $q: ng.IQService,
            private $http: ng.IHttpService,
            private Logger: Services.Logger) {
        }

        //#endregion

        public retrieveIssueFeed(): ng.IPromise<Interfaces.API.Feed> {
            let q = this.$q.defer<Interfaces.API.Feed>();

            let config: Interfaces.RequestConfig = {
                method: "GET",
                url: "https://magazine.theweek.com/endpoint.xml",
                blocking: false,
            };

            this.$http(config).then((result: ng.IHttpPromiseCallbackArg<any>) => {

                let converter = new X2JS();
                let endpointResponse: Interfaces.API.EndpointResponse = converter.xml_str2json(result.data);

                this.Logger.info(TheWeekAPI.ID, "retrieveIssueFeed", "Parsed endpoint XML result.", endpointResponse);

                q.resolve(endpointResponse.feed);

            }).catch((error: any) => {

                q.reject(error);

            });

            return q.promise;
        }
    }
}


text:
package net.apexes.wsonrpc.core;

/**
 *
 * @author HeDYn
 *
 */
public interface WsonrpcErrorProcessor {

    void onError(String sessionId, Throwable error);

}


text:
/// <reference path="./types/index.d.ts" />
/// <reference path="./utils.ts" />
/// <reference path="./extensions/BORepository.ts" />
/// <reference path="./extensions/Common.ts" />
/// <reference path="./extensions/DataType.ts" />
/// <reference path="./extensions/components/Model.d.ts" />
/// <reference path="./extensions/components/Model.ts" />
/// <reference path="./extensions/components/Control.d.ts" />
/// <reference path="./extensions/components/Control.ts" />
/// <reference path="./extensions/components/Input.d.ts" />
/// <reference path="./extensions/components/Input.ts" />
/// <reference path="./extensions/components/Select.d.ts" />
/// <reference path="./extensions/components/Select.ts" />
/// <reference path="./extensions/components/Text.d.ts" />
/// <reference path="./extensions/components/Text.ts" />
/// <reference path="./extensions/components/Link.d.ts" />
/// <reference path="./extensions/components/Link.ts" />
/// <reference path="./extensions/components/List.d.ts" />
/// <reference path="./extensions/components/List.ts" />
/// <reference path="./extensions/components/CheckBox.d.ts" />
/// <reference path="./extensions/components/CheckBox.ts" />
/// <reference path="./extensions/components/ComboBox.d.ts" />
/// <reference path="./extensions/components/ComboBox.ts" />
/// <reference path="./extensions/components/DateTimePicker.d.ts" />
/// <reference path="./extensions/components/DateTimePicker.ts" />
/// <reference path="./extensions/components/SegmentedButton.d.ts" />
/// <reference path="./extensions/components/SegmentedButton.ts" />
/// <reference path="./extensions/components/Switch.d.ts" />
/// <reference path="./extensions/components/Switch.ts" />
/// <reference path="./extensions/components/Table.d.ts" />
/// <reference path="./extensions/components/Table.ts" />
/// <reference path="./extensions/components/Page.d.ts" />
/// <reference path="./extensions/components/Page.ts" />
/// <reference path="./extensions/components/AddressArea.d.ts" />
/// <reference path="./extensions/components/AddressArea.ts" />
/// <reference path="./extensions/components/ObjectPageLayout.d.ts" />
/// <reference path="./extensions/components/ObjectPageLayout.ts" />
/// <reference path="./extensions/components/ObjectIdentifier.d.ts" />
/// <reference path="./extensions/components/ObjectIdentifier.ts" />
/// <reference path="./extensions/components/ObjectAttribute.d.ts" />
/// <reference path="./extensions/components/ObjectAttribute.ts" />
/// <reference path="./extensions/components/ObjectStatus.d.ts" />
/// <reference path="./extensions/components/ObjectStatus.ts" />
/// <reference path="./extensions/components/ObjectNumber.d.ts" />
/// <reference path="./extensions/components/ObjectNumber.ts" />
/// <reference path="./extensions/components/Table.m.d.ts" />
/// <reference path="./extensions/components/Table.m.ts" />
/// <reference path="./extensions/components/HTML.d.ts" />
/// <reference path="./extensions/components/HTML.ts" />
/// <reference path="./extensions/components/MessageBox.ts" />
/// <reference path="./extensions/components/Tokenizer.d.ts" />
/// <reference path="./extensions/components/Tokenizer.ts" />
/// <reference path="./extensions/components/Wizard.d.ts" />
/// <reference path="./extensions/components/Wizard.ts" />
/// <reference path="./extensions/components/Card.d.ts" />
/// <reference path="./extensions/components/Card.ts" />
/// <reference path="./extensions/components/MessageStrip.d.ts" />
/// <reference path="./extensions/components/MessageStrip.ts" />
/// <reference path="./extensions/components/GenericTag.d.ts" />
/// <reference path="./extensions/components/GenericTag.ts" />
/// <reference path="./extensions/components/Form.d.ts" />
/// <reference path="./extensions/components/Form.ts" />
/// <reference path="./extensions/components/ObjectListItem.d.ts" />
/// <reference path="./extensions/components/ObjectListItem.ts" />
/// <reference path="./extensions/components/Toolbar.d.ts" />
/// <reference path="./extensions/components/Toolbar.ts" />
/// <reference path="./extensions/components/Factory.ts" />

namespace openui5 {
    /** 配置项目-紧缩屏幕 */
    export const CONFIG_ITEM_COMPACT_SCREEN: string = "compactScreen";
    // ui 触发错误验证
    sap.ui.getCore().attachValidationError(undefined, (oEvent: sap.ui.base.Event) => {
        let control: any = oEvent.getParameter("element");
        let message: any = oEvent.getParameter("message");
        if (control && control.setValueState) {
            control.setValueState("Error");
            if (message) {
                control.setValueStateText(message);
            }
            control.focus();
        }
    });
    // ui 触发正确验证
    sap.ui.getCore().attachValidationSuccess(undefined, (oEvent: sap.ui.base.Event) => {
        let control: any = oEvent.getParameter("element");
        if (control && control.setValueState) {
            control.setValueState("None");
        }
    });
}


text:
require 'kdb'

Kdb::Plugin.define :get_with_exception do

  def get(returned, parent)
    5.times do |i|
      k = Kdb::Key.new parent.name
      k.add_basename "key%d" % i
      k.value = "myvalue%d" % i

      returned << k
    end

    raise "Throwing that expected exception"

    return 0
  end

end


text:
from setuptools import setup

setup(
    name = 'ci_setup_check',
    version = '1.0.11',
    description = """This is a demo package used for figuring out travics-ci
 and AppVeyor""",
    packages=['ci_setup_check', 'ci_setup_check.tests'],
)


text:
import * as React from 'react';
import { SxProps } from '@material-ui/system';
import { InternalStandardProps as StandardProps, Theme } from '..';
import { TransitionProps } from '../transitions/transition';
import { PopperProps } from '../Popper/Popper';
import { TooltipClasses } from './tooltipClasses';

export interface TooltipProps extends StandardProps<React.HTMLAttributes<HTMLDivElement>, 'title'> {
  /**
   * If `true`, adds an arrow to the tooltip.
   * @default false
   */
  arrow?: boolean;
  /**
   * Tooltip reference element.
   */
  children: React.ReactElement<any, any>;
  /**
   * Override or extend the styles applied to the component.
   */
  classes?: Partial<TooltipClasses>;
  /**
   * Set to `true` if the `title` acts as an accessible description.
   * By default the `title` acts as an accessible label for the child.
   * @default false
   */
  describeChild?: boolean;
  /**
   * Do not respond to focus-visible events.
   * @default false
   */
  disableFocusListener?: boolean;
  /**
   * Do not respond to hover events.
   * @default false
   */
  disableHoverListener?: boolean;
  /**
   * Makes a tooltip not interactive, i.e. it will close when the user
   * hovers over the tooltip before the `leaveDelay` is expired.
   * @default false
   */
  disableInteractive?: boolean;
  /**
   * Do not respond to long press touch events.
   * @default false
   */
  disableTouchListener?: boolean;
  /**
   * The number of milliseconds to wait before showing the tooltip.
   * This prop won't impact the enter touch delay (`enterTouchDelay`).
   * @default 100
   */
  enterDelay?: number;
  /**
   * The number of milliseconds to wait before showing the tooltip when one was already recently opened.
   * @default 0
   */
  enterNextDelay?: number;
  /**
   * The number of milliseconds a user must touch the element before showing the tooltip.
   * @default 700
   */
  enterTouchDelay?: number;
  /**
   * If `true`, the tooltip follow the cursor over the wrapped element.
   * @default false
   */
  followCursor?: boolean;
  /**
   * This prop is used to help implement the accessibility logic.
   * If you don't provide this prop. It falls back to a randomly generated id.
   */
  id?: string;
  /**
   * The number of milliseconds to wait before hiding the tooltip.
   * This prop won't impact the leave touch delay (`leaveTouchDelay`).
   * @default 0
   */
  leaveDelay?: number;
  /**
   * The number of milliseconds after the user stops touching an element before hiding the tooltip.
   * @default 1500
   */
  leaveTouchDelay?: number;
  /**
   * Callback fired when the component requests to be closed.
   *
   * @param {object} event The event source of the callback.
   */
  onClose?: (event: React.SyntheticEvent | Event) => void;
  /**
   * Callback fired when the component requests to be open.
   *
   * @param {object} event The event source of the callback.
   */
  onOpen?: (event: React.SyntheticEvent) => void;
  /**
   * If `true`, the component is shown.
   */
  open?: boolean;
  /**
   * Tooltip placement.
   * @default 'bottom'
   */
  placement?:
    | 'bottom-end'
    | 'bottom-start'
    | 'bottom'
    | 'left-end'
    | 'left-start'
    | 'left'
    | 'right-end'
    | 'right-start'
    | 'right'
    | 'top-end'
    | 'top-start'
    | 'top';
  /**
   * The component used for the popper.
   * @default Popper
   */
  PopperComponent?: React.JSXElementConstructor<PopperProps>;
  /**
   * Props applied to the [`Popper`](/api/popper/) element.
   * @default {}
   */
  PopperProps?: Partial<PopperProps>;
  /**
   * The system prop that allows defining system overrides as well as additional CSS styles.
   */
  sx?: SxProps<Theme>;
  /**
   * Tooltip title. Zero-length titles string are never displayed.
   */
  title: NonNullable<React.ReactNode>;
  /**
   * The component used for the transition.
   * [Follow this guide](/components/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.
   * @default Grow
   */
  TransitionComponent?: React.JSXElementConstructor<
    TransitionProps & { children?: React.ReactElement<any, any> }
  >;
  /**
   * Props applied to the transition element.
   * By default, the element is based on this [`Transition`](http://reactcommunity.org/react-transition-group/transition) component.
   */
  TransitionProps?: TransitionProps;
}

/**
 *
 * Demos:
 *
 * - [Tooltips](https://material-ui.com/components/tooltips/)
 *
 * API:
 *
 * - [Tooltip API](https://material-ui.com/api/tooltip/)
 */
export default function Tooltip(props: TooltipProps): JSX.Element;


text:
package es.molabs.jdbc.handler;

import java.sql.ResultSetMetaData;
import java.sql.SQLException;

public interface DbMetaDataHandler
{
	public void handle(ResultSetMetaData resultSetMetaData) throws SQLException;
}


text:
<#PSScriptInfo
.VERSION 1.0.0
.GUID 4b63a38d-3996-41e3-886a-b4271c6ce367
.AUTHOR DSC Community
.COMPANYNAME DSC Community
.COPYRIGHT Copyright the DSC Community contributors. All rights reserved.
.TAGS DSCConfiguration
.LICENSEURI https://github.com/dsccommunity/StorageDsc/blob/main/LICENSE
.PROJECTURI https://github.com/dsccommunity/StorageDsc
.ICONURI
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES First version.
.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core
#>

#Requires -module StorageDsc

<#
    .DESCRIPTION
        This configuration will wait for disk 2 to become available, and then make the disk available as
        two new formatted volumes, 'G' and 'J', with 'J' using all available space after 'G' has been
        created. It also creates a new ReFS formated volume on Disk 3 attached as drive letter 'S'.
#>
Configuration WaitForDisk_InitializeDataDisk
{
    Import-DSCResource -ModuleName StorageDsc

    Node localhost
    {
        WaitForDisk Disk2
        {
             DiskId = 2
             RetryIntervalSec = 60
             RetryCount = 60
        }

        Disk GVolume
        {
             DiskId = 2
             DriveLetter = 'G'
             Size = 10GB
        }

        Disk JVolume
        {
             DiskId = 2
             DriveLetter = 'J'
             FSLabel = 'Data'
             DependsOn = '[Disk]GVolume'
        }

        Disk DataVolume
        {
             DiskId = 3
             DriveLetter = 'S'
             Size = 100GB
             FSFormat = 'ReFS'
             AllocationUnitSize = 64KB
        }
    }
}


text:
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;

namespace Ds3.Calls
{
    public class GetCacheFilesystemSpectraS3Request : Ds3Request
    {

        public string CacheFilesystem { get; private set; }

        public GetCacheFilesystemSpectraS3Request(string cacheFilesystem)
        {
            this.CacheFilesystem = cacheFilesystem;

        }

        internal override HttpVerb Verb
        {
            get
            {
                return HttpVerb.GET;
            }
        }

        internal override string Path
        {
            get
            {
                return "/_rest_/cache_filesystem/" + CacheFilesystem;
            }
        }
    }
}


text:
/**
 * User: bluven
 * Date: 15-7-3
 * Time: 上午9:49
 */

CloudApp.controller('ImageController',
    function($rootScope, $scope, $filter, $modal, $i18next, $ngBootbox,
             CommonHttpService, ToastrService, ngTableParams,
             Image, CheckboxGroup, ngTableHelper){

        $scope.$on('$viewContentLoaded', function(){
                Metronic.initAjax();
        });

        $scope.images = [];
        var checkboxGroup = $scope.checkboxGroup = CheckboxGroup.init($scope.images);

        $scope.image_table = new ngTableParams({
                page: 1,
                count: 10
            },{
                counts: [],
                getData: function ($defer, params) {
                    Image.query(function (data) {
                        $scope.images = ngTableHelper.paginate(data, $defer, params);
                        checkboxGroup.syncObjects($scope.images);
                    });
                }
            });

        $scope.edit = $scope.create = function(image) {

                image = image || {};

                $modal.open({
                    templateUrl: 'create.html',
                    controller: 'ImageCreateController',
                    backdrop: "static",
                    size: 'lg',
                    resolve: {
                        image_table: function () {
                            return $scope.image_table;
                        },
                        image: function(){return image;}
                    }
                });
            };

        var deleteImages = function(ids){

            $ngBootbox.confirm($i18next("image.confirm_delete")).then(function(){

                if(typeof ids == 'function'){
                    ids = ids();
                }

                CommonHttpService.post("/api/images/batch-delete/", {ids: ids}).then(function(data){
                    if (data.success) {
                        ToastrService.success(data.msg, $i18next("success"));
                        $scope.image_table.reload();
                        checkboxGroup.uncheck();
                    } else {
                        ToastrService.error(data.msg, $i18next("op_failed"));
                    }
                });
            });
        };

        $scope.batchDelete = function(){

            deleteImages(function(){
                var ids = [];

                checkboxGroup.forEachChecked(function(image){
                    if(image.checked){
                        ids.push(image.id);
                    }
                });

                return ids;
            });
        };

        $scope.delete = function(image){
            deleteImages([image.id]);
        };
    })

    .controller('ImageCreateController',
        function($rootScope, $scope, $modalInstance,
                 image_table, image, Image, User, DataCenter, ImageForm,
                 $i18next, CommonHttpService, ResourceTool, ToastrService){

            $scope.users = User.query();
            $scope.data_centers = DataCenter.query();
            $scope.image = ResourceTool.copy_only_data(image);
            $scope.os_types = [{key: 1, label: 'Windows'}, {key: 2, label: 'Linux'}];

            $modalInstance.rendered.then(ImageForm.init);

            $scope.cancel = function () {
                $modalInstance.dismiss();
            };

            $scope.submit = function(image){

                if(!$("#imageForm").valid()){
                    return;
                }

                var url = '/api/images';

                if(image.id){
                    url += "/update/";
                } else {
                    url += "/create/";
                }

                CommonHttpService.post(url, image).then(function(data){
                    if (data.success) {
                        ToastrService.success(data.msg, $i18next("success"));
                        image_table.reload();
                        $modalInstance.dismiss();
                    } else {
                        ToastrService.error(data.msg, $i18next("op_failed"));
                    }
                });
            };
        }
    ).factory('ImageForm', ['ValidationTool', function (ValidationTool) {
        return {
            init: function(){

                var config = {
                    rules: {
                        name: {
                            minlength: 2,
                            maxlength: 50,
                            required: true
                        },
                        os_type: 'required',
                        login_name: 'required',
                        data_center: 'required'
                    }
                };

                return ValidationTool.init('#imageForm', config);
              }
            }
        }]);


text:
import * as express from 'express';
import requestApi from '../../../../../../core/request-api';

module.exports = (req: express.Request, res: express.Response): void => {

	requestApi('album/tags/list', {}, req.user).then((tags: Object[]) => {
		res.locals.display({
			tags: tags
		}, 'i/album');
	});
};


text:
!install sqlite3 package in system
For install sqlite3 dependiences use: npm install https://github.com/mapbox/node-sqlite3/tarball/master


text:
@echo off
ping -n 2 127.0.0.1 > nul

echo this batch will convert ".png" using -strip option from ImageMagick.
echo please make sure you place a batch file in the right location.

ping -n 1 127.0.0.1 > nul

for %%i in (*.png) do identify %%i
for %%i in (*.png) do convert %%i -strip %%i
for %%i in (*.png) do identify %%i

echo finish..

ping -n 2 127.0.0.1 > nul
echo Press any key to terminate...
pause


text:
const int SAMPLE_SINGLES_SUDOKU_SIZE = 2;
extern const char *SAMPLE_SINGLES_SUDOKU_ARRAY[SAMPLE_SINGLES_SUDOKU_SIZE][2];

#endif // #ifndef TEST_DATA_INCLUDED


text:
// <copyright file="RockCard.cs" company="https://github.com/yangyuan">
//     Copyright (c) The Hearthrock Project. All rights reserved.
// </copyright>

namespace Hearthrock.Contracts
{
    using System.Collections.Generic;

    /// <summary>
    /// Card contract of Hearthrock
    /// Bot author is responsible to know all about a card from CardId.
    /// </summary>
    public class RockCard : IRockObject
    {
        /// <summary>
        /// Gets or sets the Id of the card.
        /// </summary>
        public int RockId { get; set; }

        /// <summary>
        /// Gets or sets the Name of the card.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the CardId of the card.
        /// </summary>
        public string CardId { get; set; }

        /// <summary>
        /// Gets or sets the damage of the card.
        /// </summary>
        public int Damage { get; set; }

        /// <summary>
        /// Gets or sets the health of the card.
        /// </summary>
        public int Health { get; set; }

        /// <summary>
        /// Gets or sets the CardType of the card.
        /// </summary>
        public RockCardType CardType { get; set; }

        /// <summary>
        /// Gets or sets the cost of the card.
        /// </summary>
        public int Cost { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the card has taunt.
        /// </summary>
        public bool HasTaunt { get; set; }

        /// <summary>
        /// Gets or sets a value indicating whether the card has charge.
        /// </summary>
        public bool HasCharge { get; set; }

        /// <summary>
        /// Gets or sets the options of this card.
        /// </summary>
        public List<RockCard> Options { get; set; }
    }
}


text:
# Sending Attachments

In here you'll see a few examples showing how you can send an attachment using discord.js.

## Sending an attachment using a URL

There are a few ways you can do this, but we'll show you the easiest.

The following examples use [MessageAttachment](/#/docs/main/master/class/MessageAttachment).

```js
// Extract the required classes from the discord.js module
const { Client, MessageAttachment } = require('discord.js');

// Create an instance of a Discord client
const client = new Client();

/**
 * The ready event is vital, it means that only _after_ this will your bot start reacting to information
 * received from Discord
 */
client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
	// If the message is '!rip'
	if (message.content === '!rip') {
		// Create the attachment using MessageAttachment
		const attachment = new MessageAttachment('https://i.imgur.com/w3duR07.png');
		// Send the attachment in the message channel
		message.channel.send(attachment);
	}
});

// Log our bot in using the token from https://discordapp.com/developers/applications/me
client.login('your token here');
```

And here is the result:

![Image showing the result](/static/attachment-example1.png)

But what if you want to send an attachment with a message content? Fear not, for it is easy to do that too! We'll recommend reading [the TextChannel's "send" function documentation](/#/docs/main/master/class/TextChannel?scrollTo=send) to see what other options are available.

```js
// Extract the required classes from the discord.js module
const { Client, MessageAttachment } = require('discord.js');

// Create an instance of a Discord client
const client = new Client();

/**
 * The ready event is vital, it means that only _after_ this will your bot start reacting to information
 * received from Discord
 */
client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
	// If the message is '!rip'
	if (message.content === '!rip') {
		// Create the attachment using MessageAttachment
		const attachment = new MessageAttachment('https://i.imgur.com/w3duR07.png');
		// Send the attachment in the message channel with a content
		message.channel.send(`${message.author},`, attachment);
	}
});

// Log our bot in using the token from https://discordapp.com/developers/applications/me
client.login('your token here');
```

And here's the result of this one:

![Image showing the result](/static/attachment-example2.png)

## Sending a local file or buffer

Sending a local file isn't hard either! We'll be using [MessageAttachment](/#/docs/main/master/class/MessageAttachment) for these examples too.

```js
// Extract the required classes from the discord.js module
const { Client, MessageAttachment } = require('discord.js');

// Create an instance of a Discord client
const client = new Client();

/**
 * The ready event is vital, it means that only _after_ this will your bot start reacting to information
 * received from Discord
 */
client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
	// If the message is '!rip'
	if (message.content === '!rip') {
		// Create the attachment using MessageAttachment
		const attachment = new MessageAttachment('./rip.png');
		// Send the attachment in the message channel with a content
		message.channel.send(`${message.author},`, attachment);
	}
});

// Log our bot in using the token from https://discordapp.com/developers/applications/me
client.login('your token here');
```

The results are the same as the URL examples:

![Image showing result](/static/attachment-example1.png)

But what if you have a buffer from an image? Or a text document? Well, it's the same as sending a local file or a URL!

In the following example, we'll be getting the buffer from a `memes.txt` file, and send it in the message channel.
You can use any buffer you want, and send it. Just make sure to overwrite the filename if it isn't an image!

```js
// Extract the required classes from the discord.js module
const { Client, MessageAttachment } = require('discord.js');

// Import the native fs module
const fs = require('fs');

// Create an instance of a Discord client
const client = new Client();

/**
 * The ready event is vital, it means that only _after_ this will your bot start reacting to information
 * received from Discord
 */
client.on('ready', () => {
  console.log('I am ready!');
});

client.on('message', message => {
	// If the message is '!memes'
	if (message.content === '!memes') {
		// Get the buffer from the 'memes.txt', assuming that the file exists
		const buffer = fs.readFileSync('./memes.txt');

		/**
		 * Create the attachment using MessageAttachment,
		 * overwritting the default file name to 'memes.txt'
		 * Read more about it over at
		 * http://discord.js.org/#/docs/main/master/class/MessageAttachment
		 */
		const attachment = new MessageAttachment(buffer, 'memes.txt');
		// Send the attachment in the message channel with a content
		message.channel.send(`${message.author}, here are your memes!`, attachment);
	}
});

// Log our bot in using the token from https://discordapp.com/developers/applications/me
client.login('your token here');
```

And of course, the results are:

![Attachment File example 3](/static/attachment-example3.png)


text:
from __future__ import unicode_literals

import warnings

try:
    from django.urls import reverse, reverse_lazy
except ImportError:
    from django.core.urlresolvers import reverse, reverse_lazy  # NOQA

class RemovedInDjango20Warning(DeprecationWarning):
    pass

class CallableBool:  # pragma: no cover
    """
    An boolean-like object that is also callable for backwards compatibility.
    """
    do_not_call_in_templates = True

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

    def __bool__(self):
        return self.value

    def __call__(self):
        warnings.warn(
            "Using user.is_authenticated() and user.is_anonymous() as a method "
            "is deprecated. Remove the parentheses to use it as an attribute.",
            RemovedInDjango20Warning, stacklevel=2
        )
        return self.value

    def __nonzero__(self):  # Python 2 compatibility
        return self.value

    def __repr__(self):
        return 'CallableBool(%r)' % self.value

    def __eq__(self, other):
        return self.value == other

    def __ne__(self, other):
        return self.value != other

    def __or__(self, other):
        return bool(self.value or other)

    def __hash__(self):
        return hash(self.value)

CallableFalse = CallableBool(False)
CallableTrue = CallableBool(True)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Biblthca Lichenol. 18: 171 (1983)

#### Original name
Megalospora isidiza Makhija & Nagarkar

### Remarks
null


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>DatabaseTest2</title>
<meta name="date" content="2013-04-14">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

test

Class DatabaseTest2

java.lang.Object

test.DatabaseTest2

public class DatabaseTest2
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

static test.DatabaseTest2.dbthread
dbt

Constructor Summary

Constructors

Constructor and Description

DatabaseTest2()

Method Summary

Methods

Modifier and Type
Method and Description

static void
main(java.lang.String[] args)

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

dbt

public static test.DatabaseTest2.dbthread dbt

Constructor Detail

DatabaseTest2

public DatabaseTest2()

Method Detail

main

public static void main(java.lang.String[] args)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
module JWE
  module Alg
    # RSA-OAEP key encryption algorithm.
    class RsaOaep
      attr_accessor :key

      def initialize(key)
        self.key = key
      end

      def encrypt(cek)
        key.public_encrypt(cek, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
      end

      def decrypt(encrypted_cek)
        key.private_decrypt(encrypted_cek, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
      end
    end
  end
end


text:
package com.speedment.common.mapstream;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.*;
import java.util.stream.*;

import static org.junit.jupiter.api.Assertions.*;

final class MapStreamTest {

    private final double EPSILON = 1e-9;

    private  Map<String, Integer> stringToInt;
    private  Map<Integer, String> intToString;
    private final Collector<Map.Entry<String, Integer>, ?, Map<String, Integer>> TO_MAP = Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
    private final Predicate<Map.Entry<String, Integer>> KEY_STARTS_WITH_D = e -> e.getKey().startsWith("d");
    private MapStream<String, Integer> instance;

    @BeforeEach
    void setup() {
        stringToInt = refStream().collect(TO_MAP);
        intToString = refStream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
        instance    = MapStream.of(refStream());
    }

    @Test
    @SuppressWarnings("unchecked")
    void of() {
        final MapStream<String, Integer> ms = MapStream.of(refStream().toArray(Map.Entry[]::new));
        assertEquals(stringToInt, ms.toMap());
    }

    @Test
    void testOf() {
        final MapStream<String, Integer> ms = MapStream.of(stringToInt);
        assertEquals(stringToInt, ms.toMap());
    }

    @Test
    void testOf1() {
        final Map.Entry<String, Integer> e = entry("pet", 5);
        final MapStream<String, Integer> ms = MapStream.of(e);
        final Map<String, Integer> expected = Stream.of(e).collect(TO_MAP);
        assertEquals(expected, ms.toMap());
    }

    @Test
    void testOf2() {
        final MapStream<String, Integer> ms = MapStream.of(refStream());
        assertEquals(stringToInt, ms.toMap());
    }

    @Test
    void testOf3() {
        final MapStream<String, Integer> msSequential = MapStream.of(stringToInt, false);
        assertEquals(stringToInt, msSequential.toMap());
        final MapStream<String, Integer> msParallel = MapStream.of(stringToInt, true);
        assertEquals(stringToInt, msParallel.toMap());
    }

    @Test
    void fromKeys() {
        final MapStream<String, Integer> ms = MapStream.fromKeys(stringToInt.keySet().stream(), stringToInt::get);
        assertEquals(stringToInt, ms.toMap());
    }

    @Test
    void fromValues() {
        final MapStream<String, Integer> ms = MapStream.fromValues(stringToInt.values().stream(), intToString::get);
        assertEquals(stringToInt, ms.toMap());
    }

    @Test
    void fromStream() {
        final MapStream<String, Integer> ms = MapStream.fromStream(stringToInt.keySet().stream(), Function.identity(), stringToInt::get);
        assertEquals(stringToInt, ms.toMap());
    }

    @Test
    void empty() {
        final MapStream<String, Integer> empty = MapStream.empty();
        assertEquals(0, empty.values().count());
    }

    @Test
    void flip() {
        final MapStream<Integer, String> ms = MapStream.flip(instance);
        assertEquals(MapStream.of(intToString).toMap(), ms.toMap());
    }

    @Test
    void filter() {
        final Map<String, Integer> expected = refStream().filter(KEY_STARTS_WITH_D).collect(TO_MAP);
        final Map<String, Integer> actual = instance.filter(KEY_STARTS_WITH_D).toMap();
        assertEquals(expected, actual);
    }

    @Test
    void testFilter() {
        final Map<String, Integer> expected = refStream().filter(KEY_STARTS_WITH_D).collect(TO_MAP);
        final Map<String, Integer> actual = instance.filter((k, v) -> k.startsWith("d")).toMap();
        assertEquals(expected, actual);
    }

    @Test
    void filterKey() {
        final Map<String, Integer> expected = refStream().filter(KEY_STARTS_WITH_D).collect(TO_MAP);
        final Map<String, Integer> actual = instance.filterKey(k -> k.startsWith("d")).toMap();
        assertEquals(expected, actual);
    }

    @Test
    void filterValue() {
        final Map<String, Integer> expected = refStream().filter(KEY_STARTS_WITH_D).collect(TO_MAP);
        final Map<String, Integer> actual = instance.filterValue(k -> k.equals(2)).toMap();
        assertEquals(expected, actual);
    }

    @Test
    void map() {
        final Set<String> expected = new HashSet<>(stringToInt.keySet());
        final Set<String> actual = instance.map(Map.Entry::getKey).collect(Collectors.toSet());
        assertEquals(expected, actual);
    }

    @Test
    void testMap() {
        final Set<String> expected = new HashSet<>(stringToInt.keySet());
        final Set<String> actual = instance.map((k, v) -> k).collect(Collectors.toSet());
        assertEquals(expected, actual);
    }

    @Test
    void mapKey() {
        final Map<String, Integer> expected = refStream().map(e -> new AbstractMap.SimpleImmutableEntry<>(e.getKey() + "A", e.getValue())).collect(TO_MAP);
        final Map<String, Integer> actual = instance.mapKey(s -> s + "A").toMap();
        assertEquals(expected, actual);
    }

    @Test
    void testMapKey() {
        final Map<String, Integer> expected = refStream().map(e -> new AbstractMap.SimpleImmutableEntry<>(e.getKey() + "A", e.getValue())).collect(TO_MAP);
        final Map<String, Integer> actual = instance.mapKey((k, v) -> k + "A").toMap();
        assertEquals(expected, actual);
    }

    @Test
    void mapValue() {
        final Map<String, Integer> expected = refStream().map(e -> new AbstractMap.SimpleImmutableEntry<>(e.getKey(), e.getValue() + 1)).collect(TO_MAP);
        final Map<String, Integer> actual = instance.mapValue(v -> v + 1).toMap();
        assertEquals(expected, actual);
    }

    @Test
    void testMapValue() {
        final Map<String, Integer> expected = refStream().map(e -> new AbstractMap.SimpleImmutableEntry<>(e.getKey(), e.getValue() + 1)).collect(TO_MAP);
        final Map<String, Integer> actual = instance.mapValue((k, v) -> v + 1).toMap();
        assertEquals(expected, actual);
    }

    @Test
    void mapToInt() {
        final int expected = refStream().mapToInt(Map.Entry::getValue).map(i -> i + 1).sum();
        final int actual = instance.mapToInt(e -> e.getValue() + 1).sum();
        assertEquals(expected, actual);
    }

    @Test
    void testMapToInt() {
        final int expected = refStream().mapToInt(Map.Entry::getValue).map(i -> i + 1).sum();
        final int actual = instance.mapToInt((k, v) -> v + 1).sum();
        assertEquals(expected, actual);
    }

    @Test
    void mapToLong() {
        final long expected = refStream().mapToLong(Map.Entry::getValue).map(i -> i + 1).sum();
        final long actual = instance.mapToLong(e -> e.getValue() + 1).sum();
        assertEquals(expected, actual);
    }

    @Test
    void testMapToLong() {
        final long expected = refStream().mapToLong(Map.Entry::getValue).map(i -> i + 1).sum();
        final long actual = instance.mapToLong((k, v) -> v + 1).sum();
        assertEquals(expected, actual);
    }

    @Test
    void mapToDouble() {
        final double expected = refStream().mapToDouble(Map.Entry::getValue).map(i -> i + 1).sum();
        final double actual = instance.mapToDouble(e -> e.getValue() + 1).sum();
        assertEquals(expected, actual);
    }

    @Test
    void testMapToDouble() {
        final double expected = refStream().mapToDouble(Map.Entry::getValue).map(i -> i + 1).sum();
        final double actual = instance.mapToDouble((k, v) -> v + 1).sum();
        assertEquals(expected, actual);
    }

    @Test
    void flatMap() {
        final long expected = refStream().flatMap(e -> e.getKey().chars().boxed()).count();
        final long actual = instance.flatMap(e -> e.getKey().chars().boxed()).count();
        assertEquals(expected, actual);
    }

    @Test
    void testFlatMap() {
        final long expected = refStream().flatMap(e -> e.getKey().chars().boxed()).count();
        final long actual = instance.flatMap((k, v) -> k.chars().boxed()).count();
        assertEquals(expected, actual);
    }

    @Test
    void flatMapKey() {
        final long expected = refStream().flatMap(e -> e.getKey().chars().boxed()).count();
        final long actual = instance.flatMapKey(e -> e.chars().boxed()).count();
        assertEquals(expected, actual);
    }

    @Test
    void testFlatMapKey() {
        final long expected = refStream().flatMap(e -> e.getKey().chars().boxed()).count();
        final long actual = instance.flatMapKey((k, v) -> k.chars().boxed()).count();
        assertEquals(expected, actual);
    }

    @Test
    void flatMapValue() {
        final long expected = refStream().flatMap(e -> IntStream.range(0, e.getValue()).boxed()).count();
        final long actual = instance.flatMapValue(v -> IntStream.range(0, v).boxed()).count();
        assertEquals(expected, actual);
    }

    @Test
    void testFlatMapValue() {
        final long expected = refStream().flatMap(e -> IntStream.range(0, e.getValue()).boxed()).count();
        final long actual = instance.flatMapValue((k, v) -> IntStream.range(0, v).boxed()).count();
        assertEquals(expected, actual);
    }

    @Test
    void flatMapToInt() {
        final int expected = refStream().flatMapToInt(e -> IntStream.range(0, e.getValue())).sum();
        final int actual = instance.flatMapToInt(e -> IntStream.range(0, e.getValue())).sum();
        assertEquals(expected, actual);
    }

    @Test
    void testFlatMapToInt() {
        final int expected = refStream().flatMapToInt(e -> IntStream.range(0, e.getValue())).sum();
        final int actual = instance.flatMapToInt((k, v) -> IntStream.range(0, v)).sum();
        assertEquals(expected, actual);
    }

    @Test
    void flatMapToLong() {
        final long expected = refStream().flatMapToLong(e -> LongStream.range(0, e.getValue())).sum();
        final long actual = instance.flatMapToLong(e -> LongStream.range(0, e.getValue())).sum();
        assertEquals(expected, actual);
    }

    @Test
    void testFlatMapToLong() {
        final long expected = refStream().flatMapToLong(e -> LongStream.range(0, e.getValue())).sum();
        final long actual = instance.flatMapToLong((k, v) -> LongStream.range(0, v)).sum();
        assertEquals(expected, actual);
    }

    @Test
    void flatMapToDouble() {
        final double expected = refStream().flatMapToDouble(e -> LongStream.range(0, e.getValue()).mapToDouble(l -> l)).sum();
        final double actual = instance.flatMapToDouble(e -> LongStream.range(0, e.getValue()).mapToDouble(l -> l)).sum();
        assertEquals(expected, actual, EPSILON);
    }

    @Test
    void testFlatMapToDouble() {
        final double expected = refStream().flatMapToDouble(e -> LongStream.range(0, e.getValue()).mapToDouble(l -> l)).sum();
        final double actual = instance.flatMapToDouble((k, v) -> LongStream.range(0, v).mapToDouble(l -> l)).sum();
        assertEquals(expected, actual, EPSILON);
    }

    @Test
    void keys() {
        final List<String> expected = refStream().map(Map.Entry::getKey).collect(Collectors.toList());
        final List<String> actual = instance.keys().collect(Collectors.toList());
        assertEquals(expected, actual);
    }

    @Test
    void values() {
        final List<Integer> expected = refStream().map(Map.Entry::getValue).collect(Collectors.toList());
        final List<Integer> actual = instance.values().collect(Collectors.toList());
        assertEquals(expected, actual);
    }

    @Test
    void distinct() {
        final MapStream<String, Integer> ms = MapStream.of(entry("Eins", 1), entry("Eins", 1));
        assertEquals(1, ms.distinct().count());
    }

    @Test
    void distinctKeys() {
        final MapStream<String, Integer> ms = MapStream.of(entry("Car", 1), entry("Car", 2));
        assertEquals(1, ms.distinctKeys().count());
        final MapStream<String, Integer> ms2 = MapStream.of(entry("Car", 1), entry("Car", 2)).parallel();
        assertEquals(1, ms2.distinctKeys().count());
    }

    @Test
    void distinctKeysParallel() {
        final MapStream<String, Integer> ms = MapStream.of(entry("Car", 1), entry("Car", 2)).parallel();
        assertEquals(1, ms.distinctKeys().count());
    }

    @Test
    void distinctValues() {
        final MapStream<String, Integer> ms = MapStream.of(entry("jedan", 1), entry("Eins", 1));
        assertEquals(1, ms.distinctValues().count());
    }

    @Test
    void testDistinctKeys() {
        final MapStream<String, Integer> ms = MapStream.of(entry("Car", 1), entry("Car", 2));
        assertEquals(3, ms.distinctKeys(Integer::sum).values().mapToInt(i -> i).sum());
    }

    @Test
    void testDistinctKeysParallel() {
        final MapStream<String, Integer> ms = MapStream.of(entry("Car", 1), entry("Car", 2)).parallel();
        assertEquals(3, ms.distinctKeys(Integer::sum).values().mapToInt(i -> i).sum());
    }

    @Test
    void testDistinctValues() {
        final Map<String, Integer> expected = MapStream.of(entry("Einsjedan", 1)).toMap();
        final MapStream<String, Integer> ms = MapStream.of(entry("jedan", 1), entry("Eins", 1));
        final Map<String, Integer> actual = ms.distinctValues((a, b) -> a + b).toMap();
        assertEquals(expected, actual);
    }

    @Test
    void sorted() {
        final List<Map.Entry<String, Integer>> expected = refStream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
        final List<Map.Entry<String, Integer>> actual = instance.sorted().toList();
        assertEquals(expected, actual);

        final MapStream<Object, Integer> ms = MapStream.of(entry(new Object(), 1), entry(new Object(), 2));
        assertThrows(UnsupportedOperationException.class, () -> ms.sorted().forEach(e -> {}));

        final MapStream<String, Integer> ms2 = MapStream.of(entry(null, 1), entry(null, 2));
        assertDoesNotThrow(() -> ms2.sorted().forEach(e -> {}));

        // Todo: Test values with both null and string values

    }

    @Test
    void testSorted() {
        final List<Map.Entry<String, Integer>> expected = refStream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList());
        final List<Map.Entry<String, Integer>> actual = instance.sorted(Map.Entry.comparingByValue()).toList();
        assertEquals(expected, actual);
    }

    @Test
    void sortedByKey() {
        final Comparator<Map.Entry<String, Integer>> comparator = Map.Entry.comparingByKey(); // Java's type inference can be improved...
        final List<Map.Entry<String, Integer>> expected = refStream().sorted(comparator.reversed()).collect(Collectors.toList());
        final List<Map.Entry<String, Integer>> actual = instance.sortedByKey(Comparator.reverseOrder()).toList();
        assertEquals(expected, actual);
    }

    @Test
    void sortedByValue() {
        final Comparator<Map.Entry<String, Integer>> comparator = Map.Entry.comparingByValue(); // Java's type inference can be improved...
        final List<Map.Entry<String, Integer>> expected = refStream().sorted(comparator.reversed()).collect(Collectors.toList());
        final List<Map.Entry<String, Integer>> actual = instance.sortedByValue(Comparator.reverseOrder()).toList();
        assertEquals(expected, actual);
    }

    @Test
    void peek() {
        final List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        instance
            .peek((Consumer<Map.Entry<String, Integer>>) entries::add)
            .forEach(unused -> {});
        assertEquals(refStream().collect(Collectors.toList()), entries);
    }

    @Test
    void testPeek() {
        final List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        instance
            .peek((k, v) -> entries.add(entry(k, v)))
            .forEach(unused -> {});
        assertEquals(refStream().collect(Collectors.toList()), entries);
    }

    @Test
    void limit() {
        assertEquals(1L, instance.limit(1).count());
    }

    @Test
    void skip() {
        assertEquals(refStream().skip(1).count(), instance.skip(1).count());
    }

    @Test
    void forEach() {
        final Set<Map.Entry<String, Integer>> entries = new HashSet<>();
        instance
            .forEach((Consumer<Map.Entry<String, Integer>>) entries::add);
        assertEquals(refStream().collect(Collectors.toSet()), entries);
    }

    @Test
    void testForEach() {
        final Set<Map.Entry<String, Integer>> entries = new HashSet<>();
        instance
            .forEach((k, v) -> entries.add(entry(k, v)));
        assertEquals(refStream().collect(Collectors.toSet()), entries);
    }

    @Test
    void forEachOrdered() {
        final List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        instance
            .forEachOrdered((Consumer<Map.Entry<String, Integer>>) entries::add);
        assertEquals(refStream().collect(Collectors.toList()), entries);
    }

    @Test
    void testForEachOrdered() {
        final List<Map.Entry<String, Integer>> entries = new ArrayList<>();
        instance
            .forEachOrdered((k, v) -> entries.add(entry(k, v)));
        assertEquals(refStream().collect(Collectors.toList()), entries);
    }

    @Test
    void toArray() {
        final Object[] expected = refStream().toArray();
        final Object[] actual = instance.toArray();
        assertArrayEquals(expected, actual);
    }

    @Test
    @SuppressWarnings("rawtypes")
    void testToArray() {
        final Map.Entry[] expected = refStream().toArray(Map.Entry[]::new);
        final Map.Entry[] actual = instance.toArray(Map.Entry[]::new);
        assertArrayEquals(expected, actual);
    }

    @Test
    void reduce() {
        final Optional<Map.Entry<String, Integer>> expected = Optional.of(entry("jedandvatri", 1 + 2 + 3));
        final Optional<Map.Entry<String, Integer>> actual = instance.reduce((e0, e1) -> entry(e0.getKey()+e1.getKey() , e0.getValue()+e1.getValue()));
        assertEquals(expected, actual);
    }

    @Test
    void testReduce() {
        final Map.Entry<String, Integer> expected = entry("jedandvatri", 1 + 2 + 3);
        final Map.Entry<String, Integer> actual = instance.reduce(entry("", 0), (e0, e1) -> entry(e0.getKey()+e1.getKey() , e0.getValue()+e1.getValue()));
        assertEquals(expected, actual);
    }

    @Test
    void testReduce1() {
        final Map.Entry<String, Integer> expected = entry("jedandvatri", 1 + 2 + 3);
        final Map.Entry<String, Integer> actual = instance.reduce(entry("", 0), (e0, e1) -> entry(e0.getKey()+e1.getKey() , e0.getValue()+e1.getValue()), (e0, e1) -> entry(e0.getKey()+e1.getKey() , e0.getValue()+e1.getValue()));
        assertEquals(expected, actual);
    }

    @Test
    void collect() {
        final List<Map.Entry<String, Integer>> expected = refStream().collect(Collectors.toList());
        final List<Map.Entry<String, Integer>> actual = instance.collect(Collectors.toList());
        assertEquals(expected, actual);
    }

    @Test
    void testCollect() {
        final Supplier<List<Map.Entry<String, Integer>>> supplier =  ArrayList::new;
        final BiConsumer<List<Map.Entry<String, Integer>>, Map.Entry<String, Integer>> accumulator = List::add;
        final BiConsumer<List<Map.Entry<String, Integer>>, List<Map.Entry<String, Integer>>> combiner = List::addAll;
        final List<Map.Entry<String, Integer>> expected = refStream().collect(supplier, accumulator, combiner);
        final List<Map.Entry<String, Integer>> actual = instance.collect(supplier, accumulator, combiner);
        assertEquals(expected, actual);
    }

    @Test
    void groupingBy() {
        final Function<Map.Entry<String, Integer>, Integer> classifier = (Map.Entry<String, Integer> e) -> e.getValue() % 2;
        final Map<Integer, List<Integer>> expected = refStream()
            .collect(Collectors.groupingBy(
                classifier,
                Collectors.mapping(Map.Entry::getValue, Collectors.toList()))
            );
        final Map<Integer, List<Integer>> actual = instance.groupingBy(v -> v % 2).toMap();
        assertEquals(expected, actual);
    }

    @Test
    void min() {
        final Optional<Map.Entry<String, Integer>> expected = refStream().min(Map.Entry.comparingByValue());
        final Optional<Map.Entry<String, Integer>> actual = instance.min(Map.Entry.comparingByValue());
        assertEquals(expected, actual);
    }

    @Test
    void minByKey() {
        final Optional<Map.Entry<String, Integer>> expected = refStream().min(Map.Entry.comparingByKey());
        final Optional<Map.Entry<String, Integer>> actual = instance.minByKey(Comparator.naturalOrder());
        assertEquals(expected, actual);
    }

    @Test
    void minByValue() {
        final Optional<Map.Entry<String, Integer>> expected = refStream().min(Map.Entry.comparingByValue());
        final Optional<Map.Entry<String, Integer>> actual = instance.minByValue(Comparator.naturalOrder());
        assertEquals(expected, actual);
    }

    @Test
    void max() {
        final Optional<Map.Entry<String, Integer>> expected = refStream().max(Map.Entry.comparingByValue());
        final Optional<Map.Entry<String, Integer>> actual = instance.max(Map.Entry.comparingByValue());
        assertEquals(expected, actual);
    }

    @Test
    void maxByKey() {
        final Optional<Map.Entry<String, Integer>> expected = refStream().max(Map.Entry.comparingByKey());
        final Optional<Map.Entry<String, Integer>> actual = instance.maxByKey(Comparator.naturalOrder());
        assertEquals(expected, actual);
    }

    @Test
    void maxByValue() {
        final Optional<Map.Entry<String, Integer>> expected = refStream().max(Map.Entry.comparingByValue());
        final Optional<Map.Entry<String, Integer>> actual = instance.maxByValue(Comparator.naturalOrder());
        assertEquals(expected, actual);
    }

    @Test
    void count() {
        final long expected = refStream().count();
        final long actual = instance.count();
        assertEquals(expected, actual);
    }

    @Test
    void anyMatch() {
        final Predicate<Map.Entry<String, Integer>> predicate = e -> e.getKey().contains("a");
        final boolean expected = refStream().anyMatch(predicate);
        final boolean actual = instance.anyMatch(predicate);
        assertEquals(expected, actual);
    }

    @Test
    void testAnyMatch() {
        final Predicate<Map.Entry<String, Integer>> predicate = e -> e.getKey().contains("a");
        final boolean expected = refStream().anyMatch(predicate);
        final boolean actual = instance.anyMatch((k, v) -> k.contains("a"));
        assertEquals(expected, actual);
    }

    @Test
    void allMatch() {
        final Predicate<Map.Entry<String, Integer>> predicate = e -> !e.getKey().isEmpty();
        final boolean expected = refStream().allMatch(predicate);
        final boolean actual = instance.allMatch(predicate);
        assertEquals(expected, actual);
    }

    @Test
    void testAllMatch() {
        final Predicate<Map.Entry<String, Integer>> predicate = e -> !e.getKey().isEmpty();
        final boolean expected = refStream().allMatch(predicate);
        final boolean actual = instance.allMatch((k, v) -> !k.isEmpty());
        assertEquals(expected, actual);
    }

    @Test
    void noneMatch() {
        final Predicate<Map.Entry<String, Integer>> predicate = e -> e.getKey().isEmpty();
        final boolean expected = refStream().noneMatch(predicate);
        final boolean actual = instance.noneMatch(predicate);
        assertEquals(expected, actual);
    }

    @Test
    void testNoneMatch() {
        final Predicate<Map.Entry<String, Integer>> predicate = e -> e.getKey().isEmpty();
        final boolean expected = refStream().noneMatch(predicate);
        final boolean actual = instance.noneMatch((k, v) -> k.isEmpty());
        assertEquals(expected, actual);
    }

    @Test
    void findFirst() {
        final Optional<Map.Entry<String, Integer>> expected = refStream().findFirst();
        final Optional<Map.Entry<String, Integer>> actual = instance.findFirst();
        assertEquals(expected, actual);
    }

    @Test
    void findAny() {
        assertTrue(instance.findAny().isPresent());
    }

    @Test
    void iterator() {
        final List<Map.Entry<String, Integer>> expected = refStream().collect(Collectors.toList());
        final List<Map.Entry<String, Integer>> actual = new ArrayList<>();
        final Iterator<Map.Entry<String, Integer>> iterator = instance.iterator();
        while (iterator.hasNext()) {
            actual.add(iterator.next());
        }
        assertEquals(expected, actual);
    }

    @Test
    void spliterator() {
        final List<Map.Entry<String, Integer>> expected = refStream().collect(Collectors.toList());
        final List<Map.Entry<String, Integer>> actual = new ArrayList<>();
        final Spliterator<Map.Entry<String, Integer>> spliterator = instance.spliterator();
        spliterator.forEachRemaining(actual::add);
        assertEquals(expected, actual);
    }

    @Test
    void isParallel() {
        assertFalse(instance.isParallel());
        assertTrue(MapStream.of(stringToInt, true).isParallel());
    }

    @Test
    void sequential() {
        assertNotNull(instance.sequential());
    }

    @Test
    void parallel() {
        assertFalse(instance.isParallel());
        assertTrue(instance.parallel().isParallel());
    }

    @Test
    void unordered() {
        assertNotNull(instance.unordered());
    }

    @Test
    void onClose() {
        final AtomicInteger cnt = new AtomicInteger();
        instance.onClose(cnt::incrementAndGet);
        instance.close();
        assertEquals(1, cnt.get());
    }

    @Test
    void close() {
        assertDoesNotThrow(instance::close);
    }

    @Test
    void toMap() {
        final Map<String, Integer> expected = refStream().collect(TO_MAP);
        final Map<String, Integer> actual = instance.toMap();
        assertEquals(expected, actual);
    }

    @Test
    void testToMap() {
        final Map<String, Integer> expected = refStream().collect(TO_MAP);
        final Map<String, Integer> actual = instance.toMap(MapStream.throwingMerger());
        assertEquals(expected, actual);
        assertThrows(IllegalStateException.class, () -> {
            final Object o = MapStream.of(entry("Olle", 1), entry("Olle", 2))
                .toMap(MapStream.throwingMerger());
        });
    }

    @Test
    void toConcurrentMap() {
        final Map<String, Integer> expected = refStream().collect(TO_MAP);
        final Map<String, Integer> actual = instance.toConcurrentMap();
        assertEquals(expected, actual);
        assertTrue(actual instanceof ConcurrentMap);
    }

    @Test
    void testToConcurrentMap() {
        final Map<String, Integer> expected = refStream().collect(TO_MAP);
        final Map<String, Integer> actual = instance.toConcurrentMap(MapStream.throwingMerger());
        assertEquals(expected, actual);
        assertTrue(actual instanceof ConcurrentMap);
        assertThrows(IllegalStateException.class, () -> {
            final Object o = MapStream.of(entry("Olle", 1), entry("Olle", 2))
                .toConcurrentMap(MapStream.throwingMerger());
        });
    }

    @Test
    void toSortedMap() {
        final Map<String, Integer> expected = refStream().collect(TO_MAP);
        final Map<String, Integer> actual = instance.toSortedMap();
        assertEquals(expected, actual);
        assertTrue(actual instanceof NavigableMap);
    }

    @Test
    void toSortedMapByKey() {
        final Comparator<String> keyComparator = Comparator.reverseOrder();
        final Map<String, Integer> expected = refStream().map(Map.Entry::getKey).sorted(keyComparator).map(k -> entry(k, stringToInt.get(k))).collect(TO_MAP);
        final Map<String, Integer> actual = instance.toSortedMapByKey(keyComparator);
        assertEquals(expected, actual);
        assertTrue(actual instanceof NavigableMap);
    }

    @Test
    void testToSortedMap() {
        final Map<String, Integer> expected = refStream().collect(TO_MAP);
        final Map<String, Integer> actual = instance.toSortedMap(MapStream.throwingMerger());
        assertEquals(expected, actual);
        assertTrue(actual instanceof NavigableMap);
        assertThrows(IllegalStateException.class, () -> {
            final Object o = MapStream.of(entry("Olle", 1), entry("Olle", 2))
                .toSortedMap(MapStream.throwingMerger());
        });
    }

    @Test
    void testToSortedMap1() {
        final Comparator<String> keyComparator = Comparator.reverseOrder();
        final Map<String, Integer> expected = refStream().map(Map.Entry::getKey).sorted(keyComparator).map(k -> entry(k, stringToInt.get(k))).collect(TO_MAP);
        final Map<String, Integer> actual = instance.toSortedMap(keyComparator, MapStream.throwingMerger());
        assertEquals(expected, actual);
        assertTrue(actual instanceof NavigableMap);
        assertThrows(IllegalStateException.class, () -> {
            final Object o = MapStream.of(entry("Olle", 1), entry("Olle", 2))
                .toSortedMap(keyComparator, MapStream.throwingMerger());
        });
    }

    @Test
    void toConcurrentNavigableMap() {
        final Map<String, Integer> expected = refStream().collect(TO_MAP);
        final Map<String, Integer> actual = instance.toConcurrentNavigableMap();
        assertEquals(expected, actual);
    }

    @Test
    void toConcurrentNavigableMapByKey() {
        final Comparator<String> keyComparator = Comparator.reverseOrder();
        final Map<String, Integer> expected = refStream().map(Map.Entry::getKey).sorted(keyComparator).map(k -> entry(k, stringToInt.get(k))).collect(TO_MAP);
        final Map<String, Integer> actual = instance.toConcurrentNavigableMapByKey(keyComparator);
        assertEquals(expected, actual);
    }

    @Test
    void testToConcurrentNavigableMap() {
        final Map<String, Integer> expected = refStream().collect(TO_MAP);
        final Map<String, Integer> actual = instance.toConcurrentNavigableMap(MapStream.throwingMerger());
        assertEquals(expected, actual);
        assertThrows(IllegalStateException.class, () -> {
            final Object o = MapStream.of(entry("Olle", 1), entry("Olle", 2))
                .toConcurrentNavigableMap(MapStream.throwingMerger());
        });
    }

    @Test
    void testToConcurrentNavigableMap1() {
        final Comparator<String> keyComparator = Comparator.reverseOrder();
        final Map<String, Integer> expected = refStream().map(Map.Entry::getKey).sorted(keyComparator).map(k -> entry(k, stringToInt.get(k))).collect(TO_MAP);
        final Map<String, Integer> actual = instance.toConcurrentNavigableMap(keyComparator, MapStream.throwingMerger());
        assertEquals(expected, actual);
        assertThrows(IllegalStateException.class, () -> {
            final Object o = MapStream.of(entry("Olle", 1), entry("Olle", 2))
                .toConcurrentNavigableMap(keyComparator, MapStream.throwingMerger());
        });
    }

    @Test
    void toList() {
        final List<Map.Entry<String, Integer>> expected = refStream().collect(Collectors.toList());
        final List<Map.Entry<String, Integer>> actual = instance.toList();
        assertEquals(expected, actual);
    }

    @Test
    void comparing() {
        final Comparator<String> comparator = MapStream.comparing(s -> s.charAt(0), s -> s.charAt(1), s -> s.charAt(2));
        final List<Map.Entry<String, Integer>> expected = refStream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
        final List<Map.Entry<String, Integer>> actual = instance.sortedByKey(comparator).collect(Collectors.toList());
        assertEquals(expected, actual);

        assertThrows(NullPointerException.class, () -> MapStream.comparing(Function.identity(), null));
    }

    @Test
    void throwingMerger() {
        final BinaryOperator<Integer> merger = MapStream.throwingMerger();
        assertThrows(IllegalStateException.class, () -> merger.apply(42, 42));
    }

    private static Stream<Map.Entry<String, Integer>> refStream() {
        return Stream.of(
            entry("jedan", 1),
            entry("dva", 2),
            entry("tri", 3)
        );
    }

    private static <K, V> Map.Entry<K, V> entry(K key, V value) {
        return new AbstractMap.SimpleImmutableEntry<>(key, value);
    }

}


text:
using System;
using System.Security.Claims;

namespace Toucan.Core.Permissions
{
    public class PermissionMapping
    {
        public string Role { get; internal set; }
        public string Model {get; internal set; }
        public string Action { get; internal set; }
        public Func<ClaimsPrincipal, object, bool> Callback { get; internal set; }

        public PermissionMapping OnModel(string modelName)
        {
            Model = modelName;
            return this;
        }

        public PermissionMapping ForRole(string roleName)
        {
            Role = roleName;
            return this;
        }

        public PermissionMapping WithAction(string action)
        {
            Action = action;
            return this;
        }
        public PermissionMapping Where(Func<ClaimsPrincipal, object, bool> callback)
        {
            Callback = callback;
            return this;
        }
    }
}


text:
foodGET allows you to order food through the command line using Postmates

## Getting Started
Install the module with: `npm install foodget -g`

## Usage
For a quote and Foursquare page of nearest venue:

```javascript
foodget --item 'Filet-o-Fish meal with large drink and 2 apple pies' --eatery 'McDonalds' --name 'Zuhayeer Musa' --address '3300 Walnut Street, Philadelphia' --phone '408-555-5555' -o
```

For actual delivery (invoke the --delivery flag):

```javascript
foodget --item 'Filet-o-Fish meal with large drink and 2 apple pies' --eatery 'McDonalds' --name 'Zuhayeer Musa' --address '3300 Walnut Street, Philadelphia' --phone '408-555-5555' --delivery
```

<!-- ## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/). -->

## Release History
_(Nothing yet)_

## License
Copyright (c) 2015 Zuhayeer Musa
Licensed under the MIT license.


text: Command line utility for large scale email campaigns


text:
license: >
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.

title: geolocationOptions
---

# geolocationOptions

地理位置情報の検索をカスタマイズするための省略可能なパラメーター`Position`.

    {maximumAge: 3000、タイムアウト: 5000、enableHighAccuracy: true};

## オプション

*   **enableHighAccuracy**: 最高の結果が、アプリケーションに必要があることのヒントを示します。 既定では、デバイスの取得を試みます、 `Position` ネットワーク ベースのメソッドを使用します。 このプロパティを設定する `true` 衛星測位などのより正確な方法を使用するためにフレームワークに指示します。 *(ブール値)*

*   **タイムアウト**: への呼び出しから通過が許可される時間 (ミリ秒単位) の最大長 `[geolocation.getCurrentPosition](../geolocation.getCurrentPosition.html)` または `[geolocation.watchPosition](../geolocation.watchPosition.html)` まで対応する、 `[geolocationSuccess](geolocationSuccess.html)` コールバックを実行します。 場合は、 `[geolocationSuccess](geolocationSuccess.html)` この時間内に、コールバックは呼び出されません、 `[geolocationError](geolocationError.html)` コールバックに渡される、 `[PositionError](../PositionError/positionError.html).TIMEOUT` のエラー コード。 (と組み合わせて使用するときに注意してください `[geolocation.watchPosition](../geolocation.watchPosition.html)` の `[geolocationError](geolocationError.html)` 間隔でコールバックを呼び出すことができますすべて `timeout` ミリ秒 !)*(数)*

*   **maximumAge**: 年齢があるミリ秒単位で指定した時間よりも大きくないキャッシュされた位置を受け入れます。*(数)*

## Android の癖

限り android 2.x エミュレーター地理位置情報の結果を返さない、 `enableHighAccuracy` オプションを設定します。`true`.


text:
package probe

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
)

// Wrapper for logging
type Logger interface {
	SetRegion(reg string)
	SetError(dest string)
	SetLog(dest string)
	LogProbe(sp *sentProbe, st string, lat int, tok string)
	LogError(desc string)
	LogErrorf(desc string, args ...interface{})
	LogFatal(desc string)
	LogFatalf(desc string, args ...interface{})
}

// Logger that sends logs to cloud logger via gcloud
type CloudLogger struct {
	Region    string // Region in which VM is located
	LogDest   string // Location in Cloud Logger where probes should be logged
	ErrorDest string // Location in Cloud Logger where errors should be logged
}

func NewCloudLogger() *CloudLogger {
	return &CloudLogger{"unspecified", "defaultLog", "defaultError"}
}

type probeLog struct {
	SendTime  string `json:"sendTime"`  // Send time of probe
	ProbeType string `json:"probeType"` // Type of probe
	Latency   int    `json:"latency"`   // Latency of probe
	State     string `json:"state"`     // State of probe
	Region    string `json:"region"`    // Region in which VM is located
	Token     string `json:"token"`     // Device token of device on which the app is located
}

type errorLog struct {
	Desc   string `json:"description"` // Error description
	Region string `json:"region"`      // Region in which VM is located
}

// Set the region in which VM is located
func (c *CloudLogger) SetRegion(reg string) {
	c.Region = reg
}

// Set error log location
func (c *CloudLogger) SetError(dest string) {
	c.ErrorDest = dest
}

// Set probe log location
func (c *CloudLogger) SetLog(dest string) {
	c.LogDest = dest
}

// Log probe information to specified log
func (c *CloudLogger) LogProbe(sp *sentProbe, st string, lat int, tok string) {
	cl := &probeLog{sp.sendTime.Format(timeLogFormat), sp.probe.config.Type.String(), lat, st,
		c.Region, tok}
	l, err := json.Marshal(cl)
	if err != nil {
		c.LogError(fmt.Sprintf("Unable to log probe: unable to marshal JSON: %v", err))
		return
	}

	err = maker.Command("gcloud", "logging", "write",
		"--payload-type=json", c.LogDest, string(l)).Run()
	if err != nil {
		c.LogError(fmt.Sprintf("Unable to log probe: unable to send to server: %v", err))
	}
}

// Log errors to specified log
func (c *CloudLogger) LogError(desc string) {
	//TODO(langenbahn) add any other useful information for errors
	el := &errorLog{desc, c.Region}
	l, err := json.Marshal(el)
	//TODO(langenbahn): in the case that an error message cannot be sent to the server,
	//send through gRPC connection if available
	if err != nil {
		log.Printf("Unable to log error: unable to marshal JSON: %v", err)
		return
	}

	err = maker.Command("gcloud", "logging", "write",
		"--payload-type=json", c.ErrorDest, string(l)).Run()
	if err != nil {
		log.Printf("Unable to log error: unable to send to server: %v", err)
	}
}

// Log errors with format
func (c *CloudLogger) LogErrorf(desc string, args ...interface{}) {
	c.LogError(fmt.Sprintf(desc, args...))
}

// Log error and terminate
func (c *CloudLogger) LogFatal(desc string) {
	c.LogError(fmt.Sprintf("fatal: %s", desc))
	os.Exit(1)
}

// Log error with format and terminate
func (c *CloudLogger) LogFatalf(desc string, args ...interface{}) {
	c.LogError(fmt.Sprintf("fatal: "+desc, args...))
	os.Exit(1)
}


text:
class IndexerProperty(object):
    r"""
    Class for representing properties that can be indexed (like dictionary)
    with source of data being user defined functions or methods.
    """
    def __init__(self, get_fun, set_fun, keys_fun):
        r"""
        Initializes new instance of IndexerProperty.

        :param get_fun: function that will be called to get items with given
            key. If None then property is considered write-only.

        :type get_fun: function, method, lambda, or any object callable
            with signature`get_fun(key)`` or None.

        :param set_fun: function that will be called to set items with given
            key and value. If None then property is considered read-only.

        :type set_fun: function, method, lambda or any object callable with
            signature ``set_fun(key,value)`` or None.

        :param keys_fun: function that will be called to get enumeration of
            possible keys or None, if property doesn't have predefined set of
            keys.'

        :type keys_fun: function, method, lambda or any object callable with
            signature ``keys_fun()``.
        """
        self.__get_fun = get_fun
        self.__set_fun = set_fun
        self.__keys_fun = keys_fun

    def __getitem__(self, key):
        r"""
        Get item associated with the given key.

        :param key: key associated with value that should be returned.

        :type key: dependent on get_fun passed to the __init__ method.

        :return: value associated with ``key``.

        :rtype: dependent on get_fun passed to the __init__ method.

        :raise: Exception if property is writeonly.
        """
        if self.__get_fun is None:
            raise Exception("Property is writeonly.")
        else:
            return self.__get_fun(key)

    def __setitem__(self, key, value):
        r"""
        Set value of item associated with given key.

        :param key: key for which value should be set.

        :type key: dependent on set_fun passed to the __init__ method.

        :param value: value to be set.

        :type value: dependent on set_fun passed to the __init__method.

        :raise: Exception if property is read-only.
        """
        if self.__set_fun is None:
            raise Exception("Property is readonly.")
        else:
            self.__set_fun(key, value)

    @property
    def keys(self):
        r"""
        Get enumeration of all possible keys for this property.

        :return: enumeration of possible keys for this property.

        :rtype: dependent on keys_fun passed to __init__ method.

        :raise: Exception if keys_fun hasn't been set.
        """
        if self.__keys_fun is None:
            raise Exception("Enumeration of possible keys is not available")
        else:
            return self.__keys_fun()


text:
<template name="homePost">
	You can post here
	<form class="newPost" method="post">
		<input type="text" name="title" placeHolder="New Post">

		<textarea name="des">
		</textarea>
		<input type="submit" name="submit" value="submit">
	</form>
</template>


text:
package elxsoft.msgt.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

import elxsoft.msgt.dao.MstSiteDao;
import elxsoft.msgt.facade.MstSiteFacade;

/**
 *
 * 系统名称(System):

 * 模块名称(Module):

 * 中文类名(Name):

 * 概要说明(Description):数据库层的访问

 *
 * @author Alex
 */
@Service
@com.alibaba.dubbo.config.annotation.Service(interfaceClass = elxsoft.msgt.facade.MstSiteFacade.class, protocol = {
		"dubbo" })
public class MstSiteService implements MstSiteFacade
{

	@Autowired
	private MstSiteDao mstSiteDao;

	public void insert(JSONObject json) throws Exception
	{
		this.mstSiteDao.insert(json);
	}

	public int update(JSONObject json) throws Exception
	{
		return this.mstSiteDao.update(json);
	}

	public List<JSONObject> getList(JSONObject jsonParam, int start, int limit) throws Exception
	{
		return this.mstSiteDao.getList(jsonParam, start, limit);
	}

	public int getTotal(JSONObject jsonParam)
	{
		return this.mstSiteDao.getTotal(jsonParam);
	}

	public JSONObject get(String siteId)
	{
		return this.mstSiteDao.get(siteId);
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Syn. generis Lentinus 10 (1836)

#### Original name
Lentinus exilis Klotzsch

### Remarks
null


text:
var ArticleDetail = React.createClass({displayName: "ArticleDetail",
  loadDataFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      beforeSend: function() {
        this.setState({loading: true});
        return true;
      }.bind(this),
      success: function(data) {
        this.setState({data: data, loading: false});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

  componentDidMount: function() {
    this.loadDataFromServer();
  },

  getInitialState: function() {
    return {data: {}};
  },

  loading: function() {
    return (
      React.createElement("div", {dangerouslySetInnerHTML: {__html: loadingDiv()}})
    )
  },
  render: function() {
    if (this.state.loading) {
      return this.loading();
    }
    return (
      React.createElement("div", null,
        React.createElement(Article, {article: this.state.data})
      )
    );
  }
});

var id = $("#article-detail").data("id");
var url = '/api/blog/articles/' + id + '/';
ReactDOM.render(
  React.createElement(ArticleDetail, {url: url}),
  document.getElementById('article-detail')
);


text:
layout: post
title:  "testing"
date:   2017-01-27 21:53:02
categories: testing
excerpt: "a note on writing tests"
tags:
  - tests
  - tdd
---
Just a quick note on the importance of testing.  Today I learned the difference between being confident in feature code, and being confident in well-tested feature code.  There really is no comparison.  Spending time to think of a test plan and execute it is essential to feeling fully confident in application code.  Not only for deployment, but also for maintenance and refactoring.

Today was also my first real exposure to smoke-testing and I am looking forward to learning more about it and writing a post about it in the future.

Also, as you may have noticed, I don't believe in spell-checking nearly as much as I believe in writing tests!


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using MathSite.Common.Entities;
using MathSite.Common.Extensions;
using Microsoft.EntityFrameworkCore;

namespace MathSite.Repository.Core
{
    /// <summary>
    ///     Implements IRepository for Entity Framework.
    /// </summary>
    /// <typeparam name="TDbContext">DbContext which contains <typeparamref name="TEntity" />.</typeparam>
    /// <typeparam name="TEntity">Type of the Entity for this repository</typeparam>
    /// <typeparam name="TPrimaryKey">Primary key of the entity</typeparam>
    public class EfCoreRepositoryBase<TDbContext, TEntity, TPrimaryKey> :
        RepositoryBase<TEntity, TPrimaryKey>
        where TEntity : class, IEntity<TPrimaryKey>
        where TDbContext : DbContext
    {
        /// <summary>
        ///     Constructor
        /// </summary>
        /// <param name="dbContext"></param>
        public EfCoreRepositoryBase(TDbContext dbContext)
        {
            Context = dbContext;
        }

        /// <summary>
        ///     Gets EF DbContext object.
        /// </summary>
        public virtual TDbContext Context { get; }

        /// <summary>
        ///     Gets DbSet for given entity.
        /// </summary>
        public virtual DbSet<TEntity> Table => Context.Set<TEntity>();

        public virtual DbConnection Connection
        {
            get
            {
                var connection = Context.Database.GetDbConnection();

                if (connection.State != ConnectionState.Open)
                    connection.Open();

                return connection;
            }
        }

        public override IQueryable<TEntity> GetAll()
        {
            return GetAllIncluding();
        }

        public override IQueryable<TEntity> GetAllIncluding(
            params Expression<Func<TEntity, object>>[] propertySelectors
        )
        {
            var query = Table.AsQueryable();

            return propertySelectors.IsNullOrEmpty()
                ? query
                : propertySelectors.Aggregate(query, (current, propertySelector) => current.Include(propertySelector));
        }

        public override async Task<List<TEntity>> GetAllListAsync()
        {
            return await GetAll().ToListAsync();
        }

        public override async Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetAll().Where(predicate).ToListAsync();
        }

        public override async Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetAll().SingleAsync(predicate);
        }

        public override async Task<TEntity> FirstOrDefaultAsync(TPrimaryKey id)
        {
            return await GetAll().FirstOrDefaultAsync(CreateEqualityExpressionForId(id));
        }

        public override async Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetAll().FirstOrDefaultAsync(predicate);
        }

        public override async Task<TEntity> LastOrDefaultAsync(TPrimaryKey id)
        {
            return await GetAll().LastOrDefaultAsync(CreateEqualityExpressionForId(id));
        }

        public override async Task<TEntity> LastOrDefaultAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetAll().LastOrDefaultAsync(predicate);
        }

        public override Task<TEntity> FirstOrDefaultOrderedByAsync<TKey>(TPrimaryKey id,
            Expression<Func<TEntity, TKey>> keySelector, bool isAscending)
        {
            return GetAll()
                .OrderBy(keySelector, isAscending)
                .FirstOrDefaultAsync(CreateEqualityExpressionForId(id));
        }

        public override Task<TEntity> FirstOrDefaultOrderedByAsync<TKey>(Expression<Func<TEntity, bool>> predicate,
            Expression<Func<TEntity, TKey>> keySelector, bool isAscending)
        {
            return GetAll()
                .OrderBy(keySelector, isAscending)
                .FirstOrDefaultAsync(predicate);
        }

        public override Task<TEntity> LastOrDefaultOrderedByAsync<TKey>(TPrimaryKey id,
            Expression<Func<TEntity, TKey>> keySelector, bool isAscending)
        {
            return GetAll()
                .OrderBy(keySelector, isAscending)
                .LastOrDefaultAsync(CreateEqualityExpressionForId(id));
        }

        public override Task<TEntity> LastOrDefaultOrderedByAsync<TKey>(Expression<Func<TEntity, bool>> predicate,
            Expression<Func<TEntity, TKey>> keySelector, bool isAscending)
        {
            return GetAll()
                .OrderBy(keySelector, isAscending)
                .LastOrDefaultAsync(predicate);
        }

        public override TEntity Insert(TEntity entity)
        {
            var givenEntity = Table.Add(entity).Entity;

            Context.SaveChanges();

            return givenEntity;
        }

        public override async Task<TEntity> InsertAsync(TEntity entity)
        {
            var givenEntity = Table.Add(entity).Entity;

            await Context.SaveChangesAsync();

            return givenEntity;
        }

        public override TPrimaryKey InsertAndGetId(TEntity entity)
        {
            entity = Insert(entity);

            if (entity.IsTransient())
                Context.SaveChanges();

            return entity.Id;
        }

        public override async Task<TPrimaryKey> InsertAndGetIdAsync(TEntity entity)
        {
            entity = await InsertAsync(entity);

            if (entity.IsTransient())
                await Context.SaveChangesAsync();

            return entity.Id;
        }

        public override TPrimaryKey InsertOrUpdateAndGetId(TEntity entity)
        {
            entity = InsertOrUpdate(entity);

            if (entity.IsTransient())
                Context.SaveChanges();

            return entity.Id;
        }

        public override async Task<TPrimaryKey> InsertOrUpdateAndGetIdAsync(TEntity entity)
        {
            entity = await InsertOrUpdateAsync(entity);

            if (entity.IsTransient())
                await Context.SaveChangesAsync();

            return entity.Id;
        }

        public override TEntity Update(TEntity entity)
        {
            AttachIfNot(entity);
            Context.Entry(entity).State = EntityState.Modified;
            Context.SaveChanges();
            return entity;
        }

        public override async Task<TEntity> UpdateAsync(TEntity entity)
        {
            AttachIfNot(entity);
            Context.Entry(entity).State = EntityState.Modified;
            await Context.SaveChangesAsync();

            return entity;
        }

        public override void Delete(TEntity entity)
        {
            AttachIfNot(entity);
            Table.Remove(entity);
            Context.SaveChanges();
        }

        public override void Delete(TPrimaryKey id)
        {
            var entity = GetFromChangeTrackerOrNull(id);
            if (entity != null)
            {
                Delete(entity);
                return;
            }

            entity = FirstOrDefault(id);
            if (entity != null)
                Delete(entity);

            Context.SaveChanges();

            //Could not found the entity, do nothing.
        }

        public override async Task<int> CountAsync()
        {
            return await GetAll().CountAsync();
        }

        public override async Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetAll().Where(predicate).CountAsync();
        }

        public override async Task<long> LongCountAsync()
        {
            return await GetAll().LongCountAsync();
        }

        public override async Task<long> LongCountAsync(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetAll().Where(predicate).LongCountAsync();
        }

        protected virtual void AttachIfNot(TEntity entity)
        {
            var entry = Context.ChangeTracker.Entries().FirstOrDefault(ent => ent.Entity == entity);
            if (entry != null)
                return;

            Table.Attach(entity);
        }

        public DbContext GetDbContext()
        {
            return Context;
        }

        public Task EnsureCollectionLoadedAsync<TProperty>(
            TEntity entity,
            Expression<Func<TEntity, IEnumerable<TProperty>>> propertyExpression,
            CancellationToken cancellationToken)
            where TProperty : class
        {
            return Context.Entry(entity).Collection(propertyExpression).LoadAsync(cancellationToken);
        }

        public Task EnsurePropertyLoadedAsync<TProperty>(
            TEntity entity,
            Expression<Func<TEntity, TProperty>> propertyExpression,
            CancellationToken cancellationToken)
            where TProperty : class
        {
            return Context.Entry(entity).Reference(propertyExpression).LoadAsync(cancellationToken);
        }

        private TEntity GetFromChangeTrackerOrNull(TPrimaryKey id)
        {
            var entry = Context.ChangeTracker.Entries()
                .FirstOrDefault(
                    ent =>
                        ent.Entity is TEntity &&
                        EqualityComparer<TPrimaryKey>.Default.Equals(id, (ent.Entity as TEntity).Id)
                );

            return entry?.Entity as TEntity;
        }
    }
}


text:
package io.clickhandler.web.reactGwt.client.action;

import io.clickhandler.web.reactGwt.client.Bus;
import io.clickhandler.web.reactGwt.client.JSON;
import io.clickhandler.web.reactGwt.client.Jso;
import io.clickhandler.web.reactGwt.client.Try;

import javax.inject.Inject;
import java.util.Date;

/**
 * Actions provide a command pattern and a standard Request/Reply
 * asynchronous messaging pattern for virtually any sort of task.
 *
 * @author Clay Molocznik
 */
public abstract class AbstractAction<IN, OUT> {
    private Bus bus;
    private long started;
    private int timeoutMillis = 10000;
    private ActionCall<IN, OUT> call;

    public AbstractAction() {
    }

    public int timeoutMillis() {
        return timeoutMillis;
    }

    @Inject
    void setBus(Bus bus) {
        this.bus = bus;
    }

    protected ActionCall<IN, OUT> build() {
        return call = new ActionCall<IN, OUT>(in -> {
            beforeDispatch(in);
        }, this::createIn);
    }

    /**
     * @param request
     */
    protected void beforeDispatch(IN request) {
        started = new Date().getTime();
        this.timeoutMillis = call.timeoutMillis();
        bus.publish(request);
        dispatch(request);
    }

    protected IN createIn() {
        return Jso.create();
    }

    protected OUT createOut() {
        return Jso.create();
    }

    /**
     * @param request
     */
    protected void dispatch(IN request) {
        Try.later(() -> handle(request));
    }

    /**
     * @param request
     */
    protected abstract void handle(IN request);

    /**
     * @param e
     */
    protected void error(Throwable e) {
        call.onError(e);
    }

    /**
     * @param response
     */
    protected void respond(OUT response) {
        call.onResponse(response);
    }

    /**
     * @param callback
     */
    protected void respond(ResponseCallback<OUT> callback) {
        final OUT out = createOut();
        try {
            if (callback != null) {
                callback.call(out);
            }
            call.onResponse(out);
        } catch (Throwable e) {
            call.failed(e);
        }
    }

    /**
     * @param json
     * @return
     */
    protected IN parseIn(String json) {
        final IN in = JSON.parse(json);
        if (in == null) {
            return null;
        }
        return JSON.parse(json, in);
    }

    /**
     * @param json
     * @return
     */
    protected OUT parseOut(String json) {
        final OUT out = JSON.parse(json);
        if (out == null) {
            return null;
        }
        return JSON.parse(json, out);
    }
}


text:
The `next/image` component's default loader uses [`squoosh`](https://www.npmjs.com/package/@squoosh/lib) because it is quick to install and suitable for a development environment. For a production environment using `next start`, it is strongly recommended you install [`sharp`](https://www.npmjs.com/package/sharp) by running `yarn add sharp` in your project directory.

You are seeing this error because Image Optimization in production mode (`next start`) was detected.

#### Possible Ways to Fix It

- Install `sharp` by running `yarn add sharp` in your project directory and then reboot the server by running `next start` again
- If `sharp` is already installed but can't be resolved, set the `NEXT_SHARP_PATH` environment variable such as `NEXT_SHARP_PATH=/tmp/node_modules/sharp next start`

> Note: This is not necessary for Vercel deployments, since `sharp` is installed automatically for you.

### Useful Links

- [Image Optimization Documentation](https://nextjs.org/docs/basic-features/image-optimization)


text:
package rabbitmqcluster

import (
	"context"
	"embed"
	"log"
	"time"

	"github.com/kelseyhightower/envconfig"
	"knative.dev/reconciler-test/pkg/feature"
	"knative.dev/reconciler-test/pkg/k8s"
	"knative.dev/reconciler-test/pkg/manifest"

	"k8s.io/apimachinery/pkg/runtime/schema"
)

//go:embed "*.yaml"
var yamls embed.FS

var EnvCfg EnvConfig

type EnvConfig struct {
	RabbitmqServerImage     string `envconfig:"RABBITMQ_SERVER_IMAGE"`
	RabbitmqImagePullSecret string `envconfig:"RABBITMQ_IMAGE_PULL_SECRET"`
}

func init() {
	// Process EventingGlobal.
	if err := envconfig.Process("", &EnvCfg); err != nil {
		log.Fatal("Failed to process env var", err)
	}
}

func WithEnvConfig() []manifest.CfgFn {
	cfg := []manifest.CfgFn{}

	if EnvCfg.RabbitmqServerImage != "" {
		cfg = append(cfg, WithRabbitmqServerImage(EnvCfg.RabbitmqServerImage))
	}

	if EnvCfg.RabbitmqImagePullSecret != "" {
		cfg = append(cfg, WithRabbitmqImagePullSecret(EnvCfg.RabbitmqImagePullSecret))
	}

	return cfg
}

func WithRabbitmqServerImage(name string) manifest.CfgFn {
	return func(cfg map[string]interface{}) {
		cfg["rabbitmqServerImage"] = name
	}
}

func WithRabbitmqImagePullSecret(name string) manifest.CfgFn {
	return func(cfg map[string]interface{}) {
		cfg["rabbitmqImagePullSecretName"] = name
	}
}

func GVR() schema.GroupVersionResource {
	return schema.GroupVersionResource{Group: "rabbitmq.com", Version: "v1beta1", Resource: "rabbitmqclusters"}
}

// Install will create a RabbitmqCluster resource, augmented with the config fn options.
func Install(name string, opts ...manifest.CfgFn) feature.StepFn {
	cfg := map[string]interface{}{
		"name": name,
	}
	for _, fn := range opts {
		fn(cfg)
	}

	return func(ctx context.Context, t feature.T) {
		if _, err := manifest.InstallYamlFS(ctx, yamls, cfg); err != nil {
			t.Fatal(err)
		}
	}
}

// IsReady tests to see if a RabbitmqCluster becomes ready within the time given.
func IsReady(name string, timing ...time.Duration) feature.StepFn {
	return k8s.IsReady(GVR(), name, timing...)
}


text:
package com.planet_ink.coffee_mud.Abilities.Druid;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Chant_ExplosiveDecompression extends Chant
{
	@Override public String ID() { return "Chant_ExplosiveDecompression"; }
	private final static String localizedName = CMLib.lang().L("Explosive Decompression");
	@Override public String name() { return localizedName; }
	@Override public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_DEEPMAGIC;}
	@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	@Override protected int canAffectCode(){return Ability.CAN_ROOMS;}
	@Override protected int canTargetCode(){return Ability.CAN_ROOMS;}
	@Override public boolean bubbleAffect(){return true;}

	@Override
	public void affectPhyStats(Physical affecting, PhyStats stats)
	{
		super.affectPhyStats(affected,stats);
		if((affected instanceof MOB)&&(((MOB)affected).charStats().getBreathables().length>0))
			stats.setSensesMask(stats.sensesMask()|PhyStats.CAN_NOT_BREATHE);
	}

	@Override
	public int castingQuality(MOB mob, Physical target)
	{
		if(mob!=null)
		{
			if((mob.location().domainType()&Room.INDOORS)==0)
				return Ability.QUALITY_INDIFFERENT;
		}
		return super.castingQuality(mob,target);
	}

	@Override
	public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final Room target=mob.location();
		if(target==null)
			return false;
		if((!auto)&&((target.domainType()&Room.INDOORS)==0))
		{
			mob.tell(L("This chant only works indoors."));
			return false;
		}

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;
		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			invoker=mob;
			final CMMsg msg=CMClass.getMsg(mob,null,this,verbalCastCode(mob,null,auto),auto?"":L("^S<S-NAME> chant(s) loudly.  A ball of fire forms around <S-NAME>.^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				if(msg.value()<=0)
				{
					mob.location().showHappens(CMMsg.MSG_OK_VISUAL,L("The ball of fire **EXPLODES**!"));
					for(int i=0;i<target.numInhabitants();i++)
					{
						final MOB M=target.fetchInhabitant(i);
						if((M!=null)&&(M!=mob))
						{
							final CMMsg msg2=CMClass.getMsg(mob,M,this,verbalCastMask(mob,target,auto)|CMMsg.TYP_FIRE,null);
							if(mob.location().okMessage(mob,msg2))
							{
								mob.location().send(mob,msg2);
								invoker=mob;
								final int numDice = adjustedLevel(mob,asLevel)+(2*super.getX1Level(mob));
								int damage = CMLib.dice().roll(numDice, 5, 25);
								if(msg2.value()>0)
									damage = (int)Math.round(CMath.div(damage,2.0));
								CMLib.combat().postDamage(mob,M,this,damage,CMMsg.MASK_ALWAYS|CMMsg.TYP_FIRE,Weapon.TYPE_BURNING,L("The flaming blast <DAMAGE> <T-NAME>!"));
							}
							if((M.charStats().getBodyPart(Race.BODY_FOOT)>0)
							&&(!CMLib.flags().isFlying(M))&&(CMLib.flags().isStanding(M)))
								mob.location().show(M,null,CMMsg.MASK_ALWAYS|CMMsg.TYP_SIT,L("<S-NAME> <S-IS-ARE> blown off <S-HIS-HER> feet!"));
						}
					}
					maliciousAffect(mob,target,asLevel,20,-1);
					mob.location().showHappens(CMMsg.MSG_OK_VISUAL,L("The fire burns off all the air here!"));
				}
			}
		}
		else
			return maliciousFizzle(mob,target,L("<S-NAME> chant(s) loudly, but nothing happens."));
		// return whether it worked
		return success;
	}
}


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.Chrome.CSS
{
	/// <summary>
	/// Returns all class names from specified stylesheet.
	/// </summary>
	[CommandResponse(ProtocolName.CSS.CollectClassNames)]
	[SupportedBy("Chrome")]
	public class CollectClassNamesCommandResponse
	{
		/// <summary>
		/// Gets or sets Class name list.
		/// </summary>
		public string[] ClassNames { get; set; }
	}
}