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

  <modelVersion>4.0.0</modelVersion>

  <groupId>com.google.api-ads.examples</groupId>
  <artifactId>adwords-axis-utility-extension-examples</artifactId>
  <version>1.35.1-beta</version>

  <packaging>jar</packaging>
  <name>Examples using AdWords Axis Utility Extension - Beta</name>
  <description>
    This project contains examples of using the AdWords Axis Utility Extension (Beta),
    Utility is a higher level client library on top of the new Java Client library.
    It allows you to forget selectors, services, fields, mutates, gets.
  </description>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <smokeMainClass>adwords.axis.utility.extension.basicoperations.GetCampaigns</smokeMainClass>
  </properties>

  <build>
    <plugins>
     <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>versions-maven-plugin</artifactId>
        <version>1.3.1</version>
        <configuration>
          <generateBackupPoms>false</generateBackupPoms>
          <includes>
            <include>com.google.http-client:*</include>
          </includes>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
          <source>1.5</source>
          <target>1.5</target>
          <compilerId>eclipse</compilerId>
        </configuration>
        <dependencies>
          <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-compiler-eclipse</artifactId>
            <version>1.6</version>
          </dependency>
        </dependencies>
      </plugin>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <executions>
          <execution>
            <goals>
              <goal>java</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <descriptors>
            <descriptor>src/main/assembly/dependencies.xml</descriptor>
          </descriptors>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <!-- Ads client library dependencies -->
    <dependency>
      <groupId>com.google.api-ads</groupId>
      <artifactId>ads-lib</artifactId>
      <version>1.35.1</version>
    </dependency>
    <dependency>
      <groupId>com.google.api-ads</groupId>
      <artifactId>adwords-axis</artifactId>
      <version>1.35.1</version>
    </dependency>
    <dependency>
      <groupId>com.google.api-ads</groupId>
      <artifactId>adwords-axis-utility-extension</artifactId>
      <version>1.35.1-beta</version>
    </dependency>
    <dependency>
      <groupId>com.google.api-client</groupId>
      <artifactId>google-api-client</artifactId>
      <version>RELEASE</version>
    </dependency>

    <!-- Third party dependencies -->
    <dependency>
      <groupId>com.google.http-client</groupId>
      <artifactId>google-http-client-jackson2</artifactId>
      <version>1.19.0</version>
    </dependency>

    <!-- Configuration to use log4j for logging -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.7</version>
    </dependency>
  </dependencies>

  <profiles>
    <profile>
      <id>smoketest</id>
      <properties>
        <exec.mainClass>${smokeMainClass}</exec.mainClass>
      </properties>
    </profile>
  </profiles>
</project>


text:
import { mean, deviation } from 'd3-array';
import { rebind } from '@d3fc/d3fc-rebind';
import _slidingWindow from './slidingWindow';
import { convertNaN } from './fn';

export default function() {

    let multiplier = 2;

    const slidingWindow = _slidingWindow()
        .accumulator(values => {
            const stdDev = values && deviation(values);
            const average = values && mean(values);
            return {
                average: average,
                upper: convertNaN(average + multiplier * stdDev),
                lower: convertNaN(average - multiplier * stdDev)
            };
        });

    const bollingerBands = data => slidingWindow(data);

    bollingerBands.multiplier = (...args) => {
        if (!args.length) {
            return multiplier;
        }
        multiplier = args[0];
        return bollingerBands;
    };

    rebind(bollingerBands, slidingWindow, 'period', 'value');

    return bollingerBands;
}

redpajama_set_name: RedPajamaGithub


text:
package edu.ur.hibernate.ir.statistics.db;

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

import org.springframework.context.ApplicationContext;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.testng.annotations.Test;

import edu.ur.hibernate.ir.test.helper.ContextHolder;
import edu.ur.ir.statistics.FileDownloadInfo;
import edu.ur.ir.statistics.FileDownloadInfoDAO;
import edu.ur.ir.statistics.FileDownloadRollUpProcessingRecord;
import edu.ur.ir.statistics.FileDownloadRollUpProcessingRecordDAO;
import edu.ur.ir.statistics.IgnoreIpAddress;
import edu.ur.ir.statistics.IgnoreIpAddressDAO;

/**
 * File download Processing record DAO test.
 *
 * @author Nathan Sarr
 *
 */
public class FileDownloadRollUpProcessingRecordDAOTest
{

	/** get the application context */
	ApplicationContext ctx = ContextHolder.getApplicationContext();

	/** transaction management  */
	PlatformTransactionManager tm = (PlatformTransactionManager) ctx
	.getBean("transactionManager");

    /** transaction definition  */
    TransactionDefinition td = new DefaultTransactionDefinition(
	TransactionDefinition.PROPAGATION_REQUIRED);

	/** file roll up statistics */
	FileDownloadRollUpProcessingRecordDAO fileDownloadRollUpProcessingRecordDAO = (FileDownloadRollUpProcessingRecordDAO) ctx
	.getBean("fileDownloadRollUpProcessingRecordDAO");

	/**  file download info DAO */
	FileDownloadInfoDAO fileDownloadInfoDAO = (FileDownloadInfoDAO) ctx
	.getBean("fileDownloadInfoDAO");

	/** persistance for dealing with ignoring ip addesses */
	IgnoreIpAddressDAO ignoreIpAddressDAO = (IgnoreIpAddressDAO) ctx
	.getBean("ignoreIpAddressDAO");

	/**
	 * Test download file roll up persistance
	 */
	@Test
	public void fileDownloadRollUpProcessingRecordDAOTest() throws Exception{

	    TransactionStatus ts = tm.getTransaction(td);
	    FileDownloadRollUpProcessingRecord rollUpProcessingRecord = new FileDownloadRollUpProcessingRecord(22l);

        fileDownloadRollUpProcessingRecordDAO.makePersistent(rollUpProcessingRecord);
 	    tm.commit(ts);

 	    ts = tm.getTransaction(td);
 	    FileDownloadRollUpProcessingRecord other = fileDownloadRollUpProcessingRecordDAO.getById(rollUpProcessingRecord.getId(), false);
        assert other.equals(rollUpProcessingRecord) : "File download info should be equal other = \n" +
        other + "\n downloadInfo1 = " + rollUpProcessingRecord;
        tm.commit(ts);

        ts = tm.getTransaction(td);
        other = fileDownloadRollUpProcessingRecordDAO.getByIrFileId(22l);
        assert other != null : "Should be able to find record by irFileId";
        fileDownloadRollUpProcessingRecordDAO.makeTransient(other);
        assert  fileDownloadRollUpProcessingRecordDAO.getById(other.getId(), false) == null : "Should no longer be able to find file processing record";
	    tm.commit(ts);
	}

}


text:
typedef void(^CompletionBlock)(CLLocation* location, NSError* error);

@interface MCMStatsLocatorService ()

@property (nonatomic, copy) CompletionBlock completionBlock;

@end

@implementation MCMStatsLocatorService SYNTHESIZE_SINGLETON_FOR_CLASS(MCMStatsLocatorService);

@synthesize currentLocation, locating, locationSuccessful, locationAllowed;

- (id) init {
	self = [super init];
	if (self != nil) {
		locationManager = [[[CLLocationManager alloc] init] retain];
		locationManager.delegate = self; // Tells the location manager to send updates to this object
		self.currentLocation = nil;
		desiredPrecisions = [[NSArray alloc] initWithObjects:[NSNumber numberWithInt:10000], [NSNumber numberWithInt:4000], [NSNumber numberWithInt:2000],[NSNumber numberWithInt:MIN_MOVEMENT * 2], nil];
		desiredAccuracies = [[NSArray alloc] initWithObjects:[NSNumber numberWithDouble:kCLLocationAccuracyThreeKilometers], [NSNumber numberWithDouble:kCLLocationAccuracyKilometer], [NSNumber numberWithDouble:kCLLocationAccuracyHundredMeters],[NSNumber numberWithDouble:kCLLocationAccuracyBest], nil];
		self.locationSuccessful = NO;
		self.locationAllowed = YES;
		self.locating = YES;
		desiredIndex = 0;
	}
	return self;
}

- (void) startUpdates {

	locationManager.desiredAccuracy = [self desiredAccuracy];
	// Set a movement threshold for new events
	locationManager.distanceFilter = kCLDistanceFilterNone;
	[self setLocating: YES];
	[locationManager startUpdatingLocation];

}

- (CLLocationAccuracy) desiredAccuracy {
	return [[desiredAccuracies objectAtIndex:desiredIndex] doubleValue];
}

- (double) desiredPrecision {
	return	[[desiredPrecisions objectAtIndex:desiredIndex] doubleValue];
}

- (void)updateLocation:(void(^)(CLLocation* location, NSError* error))completion {

	self.completionBlock = completion;

    [self startUpdates];
}

#pragma mark - CLLocationManagerDelegate methods
// Delegate method from the CLLocationManagerDelegate protocol. Called when the location is updated
- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{

#if TARGET_IPHONE_SIMULATOR
    //Set the location for simulator
    newLocation = [[[CLLocation alloc] initWithLatitude:HARDCODED_LAT longitude:HARDCODED_LNG] autorelease];

    MCMLog(@"Hardcoded location: %f,%f",newLocation.coordinate.latitude,newLocation.coordinate.longitude);
#endif

    //Check if there is not completition block to update the location
    if (self.completionBlock == nil) {

		[[MCMStatsManager sharedInstance] setLocation:newLocation];
		[self setCurrentLocation:newLocation];

    } else {

        //Stop the location updates
        [self cancelUpdates];

        //Calls the completition block with the location
        self.completionBlock(newLocation,nil);
    }

    Class klass = NSClassFromString(@"CLGeocoder");

    if (klass != nil) {

        CLGeocoder *geocoder = [[[CLGeocoder alloc] init] autorelease];
        [geocoder reverseGeocodeLocation:newLocation
                       completionHandler:^(NSArray *placemarks, NSError *error) {

                           if (error){
                               MCMLog(@"Geocode failed with error: %@", error);
                               return;
                           }

                           if(placemarks && placemarks.count > 0){
                               //do something
                               CLPlacemark *topResult = [placemarks objectAtIndex:0];

                               [[MCMStatsManager sharedInstance] setCity:[topResult locality]];

                           }
                       }];

    }

    MCMLog(@"Location updated");

	// If it's a relatively recent event, turn off updates to save power
	NSDate* eventDate = newLocation.timestamp;
	NSTimeInterval howRecent = [eventDate timeIntervalSinceNow];

	// Horizontal coordinates
	if (signbit(newLocation.horizontalAccuracy)) {
		// Negative accuracy means an invalid or unavailable measurement
		// CoreLocation returns positive for North & East, negative for South & West

        MCMLog(@"invalid or unavailable measurement");
		[self setLocationSuccessful:NO];
		return;
	}

	if (abs(howRecent) < 5.0 && newLocation.horizontalAccuracy < [self desiredPrecision]) //< 100)
	{
		// if its fresh stop updating
        MCMLog(@"stop updating location latitude %+.6f, longitude %+.6f\n, DesiredIndex:%d", newLocation.coordinate.latitude, newLocation.coordinate.longitude, desiredIndex);

		[manager stopUpdatingLocation];
		[self setLocationSuccessful:YES];
		[self setLocating: NO];
		if (desiredIndex < [desiredPrecisions count] - 1) { desiredIndex++; }
	} else
	{
		[self setLocationSuccessful:NO];
	}

}

// Called when there is an error getting the location
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
	MCMLog(@"Error updating location: %@", [error description]);

	//	[delegate localizationError: error];
	[self setLocationAllowed: NO];
	[self cancelUpdates];

    //Calls the completition block with the error
    if (self.completionBlock != nil) {

        self.completionBlock(nil,error);

    }
}

- (void) cancelUpdates {
	[locationManager stopUpdatingLocation];
	[self setLocating: NO];

    //    self.completionBlock = nil;

}

- (BOOL) locationEnabledAndAllowed {

    return [CLLocationManager locationServicesEnabled] && locationAllowed;
}

@end


text:
package com.linklist.doubly;

public class DoublyLinkList {
	private Link first;
	private Link last;
	public DoublyLinkList(){
		first = null;
		last = null;
	}
	public boolean isEmpty(){
		return first==null;
	}

	public void insertFirst(long dd){
		Link newLink = new Link(dd);
		if(isEmpty()){
			last = newLink;
		}else{
			first.previous = newLink;
		}
		newLink.next = first;
		first = newLink;
	}

	public void insertLast(long dd){
		Link newLink = new Link(dd);
		if(isEmpty())
			first = newLink;
		else{
			last.next=newLink;
			newLink.previous = last;
		}
		last = newLink;
	}

	//²åÈëµ½Ö¸¶¨Êý¾ÝÏîµÄºóÃæ
	public Link deleteFirst(){
		Link temp = first;
		if(first.next==null)
			last=null;
		else
			first.next.previous = null;
		first = first.next;
		return temp;
	}

	public Link deleteLast(){
		Link temp = last;
		if(first.next==null)
			first = null;
		else
			last.previous.next = null;
		last = last.previous;
		return temp;
	}

	public boolean insertAfter(long key, long dd){
		Link current = first;
		while(current.dData != key){
			current = current.next;
			if(current == null)
				return false;//Í˳ö·½·¨£¬Ã»ÓÐÕÒµ½²åÈëµÄλÖã¬Ã»ÓвåÈë³É¹¦
		}
		Link newLink = new Link(dd);
		if(current == last){
			newLink.next = null;
			last = newLink;
		}else{
			newLink.next = current.next;
			current.next.previous = newLink;
		}
		newLink.previous = current;
		current.next = newLink;
		return true;
	}

	public Link deleteKey(long key){
		Link current = first;
		while(current.dData != key){
			current = current.next;
			if(current == null)
				return null;//Í˳ö·½·¨£¬Ã»ÓÐÕÒµ½É¾³ýµÄλÖã¬Ã»ÓÐɾ³ý³É¹¦
		}
		if(current==first){
			first=current.next;
		}else{
			current.previous.next = current.next;
		}
		if(current==last)
			last=current.previous;
		else
			current.next.previous = current.previous;
		return current;
	}

	public void displayForward(){//´ÓÇ°Íùºó´òÓ¡
		System.out.print("List(first-->last): ");
		Link current = first;
		while(current!=null){
			current.displayLink();
			current = current.next;
		}
		System.out.println();
	}

	public void displayBackward(){//´ÓºóÍùÇ°´òÓ¡
		System.out.print("List(last-->first): ");
		Link current = last;
		while(current!=null){
			current.displayLink();
			current = current.previous;
		}
		System.out.println();
	}
}


text:
<?php
use Df\Core\Exception as DFE;
use Df\Qa\Method as Q;
use Exception as E;

/**
 * 2016-11-10
 * @used-by df_con_heir()
 * @used-by df_con_hier()
 * @used-by df_eav_update()
 * @used-by df_load()
 * @used-by df_newa()
 * @used-by df_trans()
 * @used-by dfpex_args()
 * @used-by \Df\Payment\Choice::f()
 * @used-by \Df\Payment\Operation\Source\Creditmemo::cm()
 * @used-by \Df\Payment\Operation\Source\Order::ii()
 * @used-by \Df\Payment\Operation\Source\Quote::ii()
 * @used-by \Df\Payment\W\Strategy::handle()
 * @used-by \Df\Payment\W\Strategy::m()
 * @used-by \Df\Payment\W\Strategy\Refund::_handle()
 * @param string|object $v
 * @param string|object|null $c [optional]
 * @param string|E|null $m [optional]
 * @return string|object
 * @throws DFE
 */
function df_ar($v, $c = null, $m = null) {return dfcf(function($v, $c = null, $m = null) {
	if ($c) {
		$c = df_cts($c);
		!is_null($v) ?: df_error($m ?: "Expected class: «{$c}», given `null`.");
		is_object($v) || is_string($v) ?: df_error($m ?: "Expected class: «{$c}», given: %s.", df_type($v));
		$cv = df_assert_class_exists(df_cts($v)); /** @var string $cv */
		if (!is_a($cv, $c, true)) {
			df_error($m ?: "Expected class: «{$c}», given class: «{$cv}».");
		}
	}
	return $v;
}, func_get_args());}

/**
 * 2019-12-14
 * If you do not want the exception to be logged via @see df_bt_log(),
 * then you can pass an empty string (instead of `null`) as the second argument:
 * @see \Df\Core\Exception::__construct():
 *		if (is_null($m)) {
 *			$m = __($prev ? df_xts($prev) : 'No message');
 *			# 2017-02-20 To facilite the «No message» diagnostics.
 *			if (!$prev) {
 *				df_bt_log();
 *			}
 *		}
 * https://github.com/mage2pro/core/blob/5.5.7/Core/Exception.php#L61-L67
 * @used-by df_assert_qty_supported()
 * @used-by df_config_field()
 * @used-by df_module_dir()
 * @used-by df_oqi_amount()
 * @used-by dfaf()
 * @used-by \Dfe\AlphaCommerceHub\Method::charge()
 * @used-by \Inkifi\Mediaclip\API\Entity\Order\Item::mProduct()
 * @used-by \Inkifi\Mediaclip\Event::oi()
 * @used-by \RWCandy\Captcha\Assert::email()
 * @used-by \RWCandy\Captcha\Assert::name()
 * @used-by \RWCandy\Captcha\Observer\CustomerAccountCreatePost::execute()
 * @used-by \RWCandy\Captcha\Observer\CustomerSaveBefore::execute()
 * @param mixed $cond
 * @param string|E|null $m [optional]
 * @return mixed
 * @throws DFE
 */
function df_assert($cond, $m = null) {return $cond ?: df_error($m);}

/**
 * @used-by df_wishlist_item_candidates()
 * @used-by \Df\GoogleFont\Fonts\Sprite::datumPoints()
 * @used-by \Df\Xml\X::importArray()
 * @param array $v
 * @param int $sl [optional]
 * @throws DFE
 */
function df_assert_array($v, $sl = 0):array {return Q::assertValueIsArray($v, ++$sl);}

/**
 * 2017-02-18
 * @used-by df_clean_keys()
 * @param array $a
 * @return array(string => mixed)
 * @throws DFE
 */
function df_assert_assoc(array $a):array {return df_is_assoc($a) ? $a : df_error('The array should be associative.');}

/**
 * 2021-03-22
 * @used-by df_date_create()
 * @param int|float $v
 * @param int|float|null $min
 * @param int|float|null $max
 * @param bool $inclusive [optional]
 * @return int|float
 * @throws DFE
 */
function df_assert_between($v, $min, $max, $inclusive = true) {
	if (!df_between($v, $min, $max, $inclusive)) {
		list($o1, $o2) = !$inclusive ? ['>', '<'] : ['≥', '≤']; /** @var string $o1 */ /** @var string $o2 */
		df_error("The value «{$v}» is not allowed. An allowed value should be $o1 $min and $o2 $max.");
	}
	return $v;
}

/**
 * 2016-08-03
 * @used-by df_ar()
 * @used-by \Df\Config\Backend\Serialized::entityC()
 * @param string $c
 * @param string|E $m [optional]
 * @throws DFE
 */
function df_assert_class_exists($c, $m = null):string {
	df_param_sne($c, 0);
	return df_class_exists($c) ? $c : df_error($m ?: "The required class «{$c}» does not exist.");
}

/**
 * 2017-01-14 Отныне функция возвращает $v: это позволяет нам значительно сократить код вызова функции.
 * @used-by df_date_from_timestamp_14()
 * @used-by \Df\Zoho\App::title()
 * @used-by \Dfe\Omise\W\Event\Charge\Complete::isPending()
 * @param string|float|int|bool|null $v
 * @param array(string|float|int|bool|null) $a
 * @param string|E $m [optional]
 * @return string|float|int|bool|null
 * @throws DFE
 */
function df_assert_in($v, array $a, $m = null) {
	if (!in_array($v, $a, true)) {
		df_error($m ?: "The value «{$v}» is rejected" . (
			10 >= count($a)
				? sprintf(". Allowed values: «%s».", df_csv_pretty($a))
				: " because it is absent in the list of allowed values."
		));
	}
	return $v;
}

/**
 * 2017-01-14
 * @used-by \Df\GoogleFont\Font\Variant\Preview::box()
 * @used-by \Df\GoogleFont\Fonts\Png::colorAllocateAlpha()
 * @used-by \Df\GoogleFont\Fonts\Png::image()
 * @used-by \Df\GoogleFont\Fonts\Sprite::draw()
 * @used-by \Df\Xml\X::asXMLPart()
 * @param mixed $v
 * @param string|E $m [optional]
 * @return mixed
 * @throws DFE
 */
function df_assert_nef($v, $m = null) {return false !== $v ? $v : df_error($m ?:
	'The «false» value is rejected, any others are allowed.'
);}

/**
 * @used-by df_currency_base()
 * @used-by df_file_name()
 * @used-by df_json_decode()
 * @used-by \CanadaSatellite\Bambora\Action\Authorize::p() (canadasatellite.ca, https://github.com/canadasatellite-ca/bambora/issues/1)
 * @used-by \CanadaSatellite\Bambora\Action\_Void::p() (canadasatellite.ca, https://github.com/canadasatellite-ca/bambora/issues/1)
 * @used-by \Df\PaypalClone\Charge::p()
 * @used-by \Df\StripeClone\Payer::newCard()
 * @used-by \Df\Xml\X::addAttributes()
 * @used-by \Dfe\Stripe\Controller\CustomerReturn\Index::isSuccess()
 * @used-by \Dfe\Stripe\Init\Action::redirectUrl()
 * @param string $v
 * @param int $sl [optional]
 * @throws DFE
 */
function df_assert_sne($v, $sl = 0):string {
	$sl++;
	Q::assertValueIsString($v, $sl);
	# The previous code `if (!$v)` was wrong because it rejected the '0' string.
	return '' !== strval($v) ? $v : Q::raiseErrorVariable(__FUNCTION__, $ms = [Q::NES], $sl);
}

/**
 * 2016-08-09
 * @used-by dfaf()
 * @param Traversable|array $v
 * @param string|E $m [optional]
 * @return Traversable|array
 * @throws DFE
 */
function df_assert_traversable($v, $m = null) {return is_iterable($v) ? $v : df_error($m ?:
	'A variable is expected to be a Traversable or an array, ' . 'but actually it is %s.', df_type($v)
);}

/**
 * @used-by \Df\Config\Settings::b()
 * @used-by \Df\Payment\Comment\Description::locations()
 * @used-by \Df\Payment\Comment\Description::getCommentText()
 * @used-by \Df\Shipping\Settings::enable()
 * @used-by \Dfe\Moip\FE\Webhooks::onFormInitialized()
 * @used-by \Dfe\YandexKassa\Source\Option::map()
 * @param mixed $v
 */
function df_bool($v):bool {
	/**
	 * Unfortunately, we can not replace @uses in_array() with @see array_flip() + @see isset() to speedup the execution,
	 * because it could lead to the warning: «Warning: array_flip(): Can only flip STRING and INTEGER values!».
	 * Moreover, @see array_flip() + @see isset() fails the following test:
	 *	$a = array(null => 3, 0 => 4, false => 5);
	 *	$this->assertNotEquals($a[0], $a[false]);
	 * Though, @see array_flip() + @see isset() does not fail the tests:
	 * $this->assertNotEquals($a[null], $a[0]);
	 * $this->assertNotEquals($a[null], $a[false]);
	 */
	static $no = [0, '0', 'false', false, null, 'нет', 'no', 'off', '']; /** @var mixed[] $no */
	static $yes = [1, '1', 'true', true, 'да', 'yes', 'on']; /** @var mixed[] $yes */
	/**
	 * Passing $strict = true to the @uses in_array() call is required here,
	 * otherwise any true-compatible value (e.g., a non-empty string) will pass the check.
	 */
	return in_array($v, $no, true) ? false : (in_array($v, $yes, true) ? true : df_error(
		'A boolean value is expected, but got «%s».', df_dump($v)
	));
}

/**
 * 2015-03-04
 * Эта функция проверяет, принадлежит ли переменная $v хотя бы к одному из классов $class.
 * Обратите внимание, что т.к. алгоритм функции использует стандартный оператор instanceof,
 * то переменная $v может быть не только объектом,
 * а иметь произвольный тип: https://php.net/manual/language.operators.type.php#example-146
 * Если $variable не является объектом, то функция просто вернёт false.
 *
 * Наша функция не загружает при этом $class в память интерпретатора PHP.
 * Если $class ещё не загружен в память интерпретатора PHP, то функция вернёт false.
 * В принципе, это весьма логично!
 * Если проверяемый класс ещё не был загружен в память интерпретатора PHP,
 * то проверяемая переменная $v гарантированно не может принадлежать данному классу!
 * http://3v4l.org/KguI5
 * Наша функция отличается по сфере применения
 * как от оператора instanceof, так и от функции @see is_a() тем, что:
 * 1) Умеет проводить проверку на приналежность не только одному конкретному классу, а и хотя бы одному из нескольких.
 * 2) @is_a() приводит к предупреждению уровня E_DEPRECATED интерпретатора PHP версий ниже 5.3:
 * https://php.net/manual/function.is-a.php
 * 3) Даже при проверке на принадлежность одному классу код с @see df_is() получается короче,
 * чем при применении instanceof в том случае, когда мы не уверены, существует ли класс
 * и загружен ли уже класс интерпретатором PHP.
 * Например, нам приходилось писать так:
 *		class_exists('Df_1C_Cml2Controller', $autoload = false)
 *	&&
 *		df_state()->getController() instanceof Df_1C_Cml2Controller
 * Или так:
 *		$controllerClass = 'Df_1C_Cml2Controller';
 *		$result = df_state()->getController() instanceof $controllerClass;
 * При этом нельзя писать
 *		df_state()->getController() instanceof 'Df_1C_Cml2Controller'
 * потому что правый операнд instanceof может быть строковой переменной, но не может быть просто строкой!
 * https://php.net/manual/language.operators.type.php#example-148
 * 2021-05-31 @deprecated It is unused.
 * 2022-11-26
 * `object` as an argument type is not supported by PHP < 7.2:
 * https://github.com/mage2pro/core/issues/174#user-content-object
 * @param object $v
 */
function df_is($v, string ...$cc):bool {return !!df_find($cc, function(string $c) use($v):bool {return $v instanceof $c;});}


text:
<?php

namespace RobRogers\CommandBus;

use Exception;

class CommandTranslator
{
    /**
     * @param $command
     * PostJobListCommand => PostJabListingCommandHandler
     * @return mixed
     * @throws Exception
     */
    public function toCommandHandler($command)
    {
        $handler = str_replace('Command','CommandHandler', get_class($command));

        if (!class_exists($handler)) {
            $message = "Command handler [$handler] does not exist.";

            throw new Exception($message);
        }

        return $handler;
    }
}


text:
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;

namespace Kudu.Core.Infrastructure
{
    [SuppressUnmanagedCodeSecurity]
    internal static class MiniDumpNativeMethods
    {
        [DllImport("dbghelp.dll",
            EntryPoint = "MiniDumpWriteDump",
            CallingConvention = CallingConvention.StdCall,
            CharSet = CharSet.Unicode,
            ExactSpelling = true,
            SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool MiniDumpWriteDump(
            IntPtr hProcess,
            uint processId,
            SafeHandle hFile,
            MINIDUMP_TYPE dumpType,
            IntPtr expParam,
            IntPtr userStreamParam,
            IntPtr callbackParam);
    }

    [Flags]
    [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue", Justification = "")]
    [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames", Justification = "")]
    public enum MINIDUMP_TYPE : int
    {
        // From dbghelp.h:
        Normal                          = 0x00000000,
        WithDataSegs                    = 0x00000001,
        WithFullMemory                  = 0x00000002,
        WithHandleData                  = 0x00000004,
        FilterMemory                    = 0x00000008,
        ScanMemory                      = 0x00000010,
        WithUnloadedModules             = 0x00000020,
        WithIndirectlyReferencedMemory  = 0x00000040,
        FilterModulePaths               = 0x00000080,
        WithProcessThreadData           = 0x00000100,
        WithPrivateReadWriteMemory      = 0x00000200,
        WithoutOptionalData             = 0x00000400,
        WithFullMemoryInfo              = 0x00000800,
        WithThreadInfo                  = 0x00001000,
        WithCodeSegs                    = 0x00002000,
        WithoutAuxiliaryState           = 0x00004000,
        WithFullAuxiliaryState          = 0x00008000,
        WithPrivateWriteCopyMemory      = 0x00010000,
        IgnoreInaccessibleMemory        = 0x00020000,
        [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", Justification = "")]
        ValidTypeFlags                  = 0x0003ffff,
    };
}