text:
//
// HomeBridgePlatform.js
//
// Copyright (C) 2016-2017 Mitsuru Nakada
// This software is released under the MIT License, see license file.
//

'use strict';

const init = require("hap-nodejs").init;
const uuid = require("hap-nodejs").uuid;
const Bridge = require("hap-nodejs").Bridge;
const HomeBridgeAccessory = require('./HomeBridgeAccessory');

class HomeBridgePlatform {

  constructor(common) {

    this.common = common;
    this.statusChangeEvents = {};
    this.status = [];
    this.published = false;
    this.Bridge = null;

    this.API = {
      SendCommand: this.SendCommand.bind(this),
      GetStatus: this.GetStatus.bind(this),
      GetUITable: this.GetUITable.bind(this),
      AddStatusChangeEvent: this.AddStatusChangeEvent.bind(this),
      RemoveStatusChangeEvent: this.RemoveStatusChangeEvent.bind(this),
      SetLastCommand: this.SetLastCommand.bind(this),
      GetLastCommand: this.GetLastCommand.bind(this),
    };

    /*eslint no-unused-vars: ["error", { "argsIgnorePattern": "^_" }]*/
    this.common.on('initializeAfterSetUID', (_caller) => {
      init(this.common.config.basePath + '/homeBridge');
    });
    this.common.on('changeUITable', this.UITableNotify.bind(this));
    this.common.on('changeRemocon', this.UITableNotify.bind(this));
    this.common.on('statusNotify', this.StatusNotify.bind(this));
    this.common.on('changeSystemConfig', (_caller) => {
      if(!this.common.systemConfig) return;
      if(!this.common.systemConfig.platform) return;
      if(!this.common.systemConfig.bridge) return;
      if(!this.common.systemConfig.bridge.name) return;
      if(!this.common.systemConfig.bridge.changeState) return;

      console.log("%s HomeBridge initialize", this.common.systemConfig.platform.name);
      if(this.Bridge && this.Bridge._server) {
        this.Bridge._server._httpServer._tcpServer.close(() => {
          this.Bridge = new Bridge(this.common.systemConfig.bridge.name, uuid.generate(this.common.systemConfig.bridge.name));
          this.published = false;
          this.UITableNotify();
        });
      } else {
        this.Bridge = new Bridge(this.common.systemConfig.bridge.name, uuid.generate(this.common.systemConfig.bridge.name));
        this.UITableNotify();
      }
      this.common.systemConfig.bridge.changeState = false;
    });
  }

  SendCommand(deviceName, command) {
    console.log('_SendCommand : [%s] %s', deviceName, command);
    this.common.emit('sendControllerCommand', this, {deviceName: deviceName, command: command});
  }

  GetStatus(deviceName, func) {
    let val = null;
    for(const st of this.common.status) {
      if((st.deviceName == deviceName) &&
         (st.func == func)) {
        return st.valueName;
      }
    }
    if(('lastCommand' in this.common.internalStatus) &&
       (deviceName in this.common.internalStatus.lastCommand) &&
       (func in this.common.internalStatus.lastCommand[deviceName])) {
      val = this.common.internalStatus.lastCommand[deviceName][func];
      return val;
    }
    return null;
  }

  GetUITable(table) {
    return this.UITable.TableList[table];
  }

  StatusNotify(_caller) {
    for(const d of this.common.status) {
      if(this.statusChangeEvents[d.deviceName + ':' + d.func] != undefined) {
        this.statusChangeEvents[d.deviceName + ':' + d.func].forEach((event) => {
          event.callback(event.service, d);
        });
      }
    }
  }

  AddStatusChangeEvent(deviceName, func, uuid, service, callback) {
    if(this.statusChangeEvents[deviceName + ':' + func] == undefined) this.statusChangeEvents[deviceName + ':' + func] = [];
    this.statusChangeEvents[deviceName + ':' + func].push({uuid: uuid, service:service, callback:callback});
  }

  SetLastCommand(deviceName, func, mode) {
    if(!('lastCommand' in this.common.internalStatus)) this.common.internalStatus.lastCommand = {};
    if(!(deviceName in this.common.internalStatus.lastCommand)) this.common.internalStatus.lastCommand[deviceName] = {};
    this.common.internalStatus.lastCommand[deviceName][func] = mode;
    this.common.emit('changeInternalStatus', this);
  }

  GetLastCommand(deviceName, func) {
    if(('lastCommand' in this.common.internalStatus) &&
       (deviceName in this.common.internalStatus.lastCommand) &&
       (func in this.common.internalStatus.lastCommand[deviceName])) {
      return this.common.internalStatus.lastCommand[deviceName][func];
    }
  }

  RemoveStatusChangeEvent(uuid) {
    for(const name in this.statusChangeEvents) {
      for(const i in this.statusChangeEvents[name]) {
        if(this.statusChangeEvents[name][i].uuid == uuid) {
          this.statusChangeEvents[name].splice(i, i + 1);
        }
      }
    }
  }

  UITableNotify(_caller) {
    if(!this.Bridge) return;
    this.UITable = { RoomList:this.common.uiTable.RoomList, ItemList:this.common.uiTable.ItemList, TableList:this.common.remocon.remoconGroup, System:this.common.uiTable.System};
    this.Bridge.removeBridgedAccessories(this.Bridge.bridgedAccessories);
    this.Bridge.bridgedAccessories = [];
    if(this.UITable.ItemList == null) this.UITable.ItemList = [];
    for(const d of this.UITable.ItemList) {
      if(['onOff', 'openClose', 'hue', 'light', 'lock', 'window', 'brind', 'shutter', 'aircon', 'tv'].indexOf(d.type) >= 0) {
        if(d.label != undefined) this.AddAccessory(d, d.room, d.label);
      }
      if(d.type == 'tv') {
        if((d.table != null) && (this.UITable.TableList != null)) {
          for(const band in this.UITable.TableList[d.table.prefix]) {
            if(!this.UITable.TableList[d.table.prefix][band].display) continue;
            for(const ch in this.UITable.TableList[d.table.prefix][band]) {
              if(!this.UITable.TableList[d.table.prefix][band][ch].display) continue;
              let item = {};
              item.type = 'tv';
              item.buttons = [{deviceName: d.table.deviceName, command:[d.table.prefix + '_' + band, d.table.prefix + '_' + ch]}, {deviceName: d.table.deviceName, command:[d.table.prefix + '_off']}];
              this.AddAccessory(item, d.room, this.UITable.TableList[d.table.prefix][band][ch].label);
            }
          }
        }
      }
      if(d.status != undefined) {
        for(const s of d.status) {
          if(['temp', 'humidity', 'battery'].indexOf(s.type) >= 0) {
            if(s.label != undefined) {
              this.AddAccessory(s, d.room, s.label);
            }
          }
        }
      }
    }
    if(!this.published) {
      console.log('HomeBridge publish');
      console.log('HomeBridge PIN-code : ', this.common.systemConfig.bridge.pin);
      console.log('HomeBridge setupURI : ', this.common.systemConfig.bridge.setupURI);
      const publishInfo = {
        username: this.common.systemConfig.bridge.username,
        port: this.common.systemConfig.bridge.port,
        pincode: this.common.systemConfig.bridge.pin,
        category: HomeBridgeAccessory.Categories.BRIDGE,
        setupID: this.common.systemConfig.bridge.setupID,
      };
      this.Bridge.publish(publishInfo, false);
      this.published = true;
    }
  }

  AddAccessory(itemConfig, room, name) {

    const accessory = new HomeBridgeAccessory(room, name, itemConfig, this.common.systemConfig, this.API);
    try {
      this.Bridge.addBridgedAccessory(accessory);
    } catch(e) {
      console.log(e);
    }
  }
}

module.exports = HomeBridgePlatform;


text:
"""
The MultiJob Project module handles creating MultiJob Jenkins projects.
You may specify ``multijob`` in the ``project-type`` attribute of
the :ref:`Job` definition.

This project type may use :py:func:`jenkins_jobs.modules.builders.multijob` \
builders.

Requires the Jenkins `Multijob Plugin.
<https://wiki.jenkins-ci.org/display/JENKINS/Multijob+Plugin>`_

Example::

  job:
    name: test_job
    project-type: multijob
    builders:
      - multijob:
          name: PhaseOne
          condition: SUCCESSFUL
          projects:
            - name: PhaseOneJobA
              current-parameters: true
              git-revision: true
            - name: PhaseOneJobB
              current-parameters: true
              property-file: build.props
      - multijob:
          name: PhaseTwo
          condition: UNSTABLE
          projects:
            - name: PhaseTwoJobA
              current-parameters: true
              predefined-parameters: foo=bar
            - name: PhaseTwoJobB
              current-parameters: false
"""

import xml.etree.ElementTree as XML
import jenkins_jobs.modules.base

class MultiJob(jenkins_jobs.modules.base.Base):
    sequence = 0

    def root_xml(self, data):
        xml_parent = XML.Element('com.tikal.jenkins.plugins.multijob.'
                                 'MultiJobProject')
        return xml_parent

redpajama_set_name: RedPajamaGithub


text:
```
PLPlayer.h
```
- *Added* `@property (nonatomic, assign) NSTimeInterval    timeoutIntervalForMediaPackets;`


text:
#include "SkBitmapDevice.h"
#include "SkCanvas.h"
#include "SkData.h"
#include "SkNoSaveLayerCanvas.h"
#include "SkPictureUtils.h"
#include "SkPixelRef.h"
#include "SkRRect.h"
#include "SkShader.h"

class PixelRefSet {
public:
    PixelRefSet(SkTDArray<SkPixelRef*>* array) : fArray(array) {}

    // This does a linear search on existing pixelrefs, so if this list gets big
    // we should use a more complex sorted/hashy thing.
    //
    void add(SkPixelRef* pr) {
        uint32_t genID = pr->getGenerationID();
        if (fGenID.find(genID) < 0) {
            *fArray->append() = pr;
            *fGenID.append() = genID;
//            SkDebugf("--- adding [%d] %x %d\n", fArray->count() - 1, pr, genID);
        } else {
//            SkDebugf("--- already have %x %d\n", pr, genID);
        }
    }

private:
    SkTDArray<SkPixelRef*>* fArray;
    SkTDArray<uint32_t>     fGenID;
};

static void not_supported() {
    SkDEBUGFAIL("this method should never be called");
}

static void nothing_to_do() {}

/**
 *  This device will route all bitmaps (primitives and in shaders) to its PRSet.
 *  It should never actually draw anything, so there need not be any pixels
 *  behind its device.
 */
class GatherPixelRefDevice : public SkBaseDevice {
public:
    SK_DECLARE_INST_COUNT(GatherPixelRefDevice)

    GatherPixelRefDevice(int width, int height, PixelRefSet* prset) {
        fSize.set(width, height);
        fEmptyBitmap.setInfo(SkImageInfo::MakeUnknown(width, height));
        fPRSet = prset;
    }

    virtual int width() const SK_OVERRIDE { return fSize.width(); }
    virtual int height() const SK_OVERRIDE { return fSize.height(); }
    virtual bool isOpaque() const SK_OVERRIDE { return false; }
#ifdef SK_SUPPORT_LEGACY_DEVICE_CONFIG
    virtual SkBitmap::Config config() const SK_OVERRIDE {
        return SkBitmap::kNo_Config;
    }
#endif
    virtual GrRenderTarget* accessRenderTarget() SK_OVERRIDE { return NULL; }
    virtual bool filterTextFlags(const SkPaint& paint, TextFlags*) SK_OVERRIDE {
        return false;
    }
    // TODO: allow this call to return failure, or move to SkBitmapDevice only.
    virtual const SkBitmap& onAccessBitmap() SK_OVERRIDE {
        return fEmptyBitmap;
    }
    virtual void lockPixels() SK_OVERRIDE { nothing_to_do(); }
    virtual void unlockPixels() SK_OVERRIDE { nothing_to_do(); }
    virtual bool allowImageFilter(const SkImageFilter*) SK_OVERRIDE { return false; }
    virtual bool canHandleImageFilter(const SkImageFilter*) SK_OVERRIDE { return false; }
    virtual bool filterImage(const SkImageFilter*, const SkBitmap&, const SkImageFilter::Context&,
                             SkBitmap* result, SkIPoint* offset) SK_OVERRIDE {
        return false;
    }

    virtual void clear(SkColor color) SK_OVERRIDE {
        nothing_to_do();
    }

    virtual void drawPaint(const SkDraw&, const SkPaint& paint) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawPoints(const SkDraw&, SkCanvas::PointMode mode, size_t count,
                            const SkPoint[], const SkPaint& paint) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawRect(const SkDraw&, const SkRect&,
                          const SkPaint& paint) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawRRect(const SkDraw&, const SkRRect&,
                           const SkPaint& paint) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawOval(const SkDraw&, const SkRect&,
                          const SkPaint& paint) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawPath(const SkDraw&, const SkPath& path,
                          const SkPaint& paint, const SkMatrix* prePathMatrix,
                          bool pathIsMutable) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawBitmap(const SkDraw&, const SkBitmap& bitmap,
                            const SkMatrix&, const SkPaint& paint) SK_OVERRIDE {
        this->addBitmap(bitmap);
        if (kAlpha_8_SkColorType == bitmap.colorType()) {
            this->addBitmapFromPaint(paint);
        }
    }
    virtual void drawBitmapRect(const SkDraw&, const SkBitmap& bitmap,
                                const SkRect* srcOrNull, const SkRect& dst,
                                const SkPaint& paint,
                                SkCanvas::DrawBitmapRectFlags flags) SK_OVERRIDE {
        this->addBitmap(bitmap);
        if (kAlpha_8_SkColorType == bitmap.colorType()) {
            this->addBitmapFromPaint(paint);
        }
    }
    virtual void drawSprite(const SkDraw&, const SkBitmap& bitmap,
                            int x, int y, const SkPaint& paint) SK_OVERRIDE {
        this->addBitmap(bitmap);
    }
    virtual void drawText(const SkDraw&, const void* text, size_t len,
                          SkScalar x, SkScalar y,
                          const SkPaint& paint) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawPosText(const SkDraw&, const void* text, size_t len,
                             const SkScalar pos[], SkScalar constY,
                             int, const SkPaint& paint) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawTextOnPath(const SkDraw&, const void* text, size_t len,
                                const SkPath& path, const SkMatrix* matrix,
                                const SkPaint& paint) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawVertices(const SkDraw&, SkCanvas::VertexMode, int vertexCount,
                              const SkPoint verts[], const SkPoint texs[],
                              const SkColor colors[], SkXfermode* xmode,
                              const uint16_t indices[], int indexCount,
                              const SkPaint& paint) SK_OVERRIDE {
        this->addBitmapFromPaint(paint);
    }
    virtual void drawDevice(const SkDraw&, SkBaseDevice*, int x, int y,
                            const SkPaint&) SK_OVERRIDE {
        nothing_to_do();
    }

protected:
    virtual void replaceBitmapBackendForRasterSurface(const SkBitmap&) SK_OVERRIDE {
        not_supported();
    }
    virtual SkBaseDevice* onCreateDevice(const SkImageInfo& info, Usage usage) SK_OVERRIDE {
        // we expect to only get called via savelayer, in which case it is fine.
        SkASSERT(kSaveLayer_Usage == usage);
        return SkNEW_ARGS(GatherPixelRefDevice, (info.width(), info.height(), fPRSet));
    }
    virtual void flush() SK_OVERRIDE {}

private:
    PixelRefSet*  fPRSet;
    SkBitmap fEmptyBitmap;  // legacy -- need to remove the need for this guy
    SkISize fSize;

    void addBitmap(const SkBitmap& bm) {
      fPRSet->add(bm.pixelRef());
    }

    void addBitmapFromPaint(const SkPaint& paint) {
      SkShader* shader = paint.getShader();
      if (shader) {
          SkBitmap bm;
          // Check whether the shader is a gradient in order to short-circuit
          // call to asABitmap to prevent generation of bitmaps from
          // gradient shaders, which implement asABitmap.
          if (SkShader::kNone_GradientType == shader->asAGradient(NULL) &&
              shader->asABitmap(&bm, NULL, NULL)) {
              fPRSet->add(bm.pixelRef());
          }
      }
    }

    typedef SkBaseDevice INHERITED;
};

SkData* SkPictureUtils::GatherPixelRefs(SkPicture* pict, const SkRect& area) {
    if (NULL == pict) {
        return NULL;
    }

    // this test also handles if either area or pict's width/height are empty
    if (!SkRect::Intersects(area,
                            SkRect::MakeWH(SkIntToScalar(pict->width()),
                                           SkIntToScalar(pict->height())))) {
        return NULL;
    }

    SkTDArray<SkPixelRef*> array;
    PixelRefSet prset(&array);

    GatherPixelRefDevice device(pict->width(), pict->height(), &prset);
    SkNoSaveLayerCanvas canvas(&device);

    canvas.clipRect(area, SkRegion::kIntersect_Op, false);
    canvas.drawPicture(pict);

    SkData* data = NULL;
    int count = array.count();
    if (count > 0) {
        data = SkData::NewFromMalloc(array.detach(), count * sizeof(SkPixelRef*));
    }
    return data;
}


text:
from django.conf import settings
from django.contrib.auth.models import User

class MissingSuperuserException(Exception):
    pass

try:
    first_superuser = User.objects.filter(is_superuser=True)[0]
except:
    raise MissingSuperuserException('django-todo requires at least one superuser in the database')

STAFF_ONLY = getattr(settings, 'TODO_STAFF_ONLY', False)
DEFAULT_ASSIGNEE = getattr(settings, 'TODO_DEFAULT_ASSIGNEE', first_superuser.username)
DEFAULT_LIST_ID = getattr(settings, 'TODO_DEFAULT_LIST_ID', 1)
PUBLIC_SUBMIT_REDIRECT = getattr(settings, 'TODO_PUBLIC_SUBMIT_REDIRECT', '/')


text:
package org.eclipse.jetty.embedded;

import java.lang.management.ManagementFactory;

import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandlerCollection;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.log.Log;

public class ManyServletContexts
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);

        // Setup JMX
        MBeanContainer mbContainer=new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
        mbContainer.start();
        server.getContainer().addEventListener(mbContainer);
        server.addBean(mbContainer,true);

        ContextHandlerCollection contexts = new ContextHandlerCollection();
        server.setHandler(contexts);

        ServletContextHandler root = new ServletContextHandler(contexts,"/",ServletContextHandler.SESSIONS);
        root.addServlet(new ServletHolder(new HelloServlet("Hello")),"/");
        root.addServlet(new ServletHolder(new HelloServlet("Ciao")),"/it/*");
        root.addServlet(new ServletHolder(new HelloServlet("Bonjoir")),"/fr/*");

        ServletContextHandler other = new ServletContextHandler(contexts,"/other",ServletContextHandler.SESSIONS);
        other.addServlet(DefaultServlet.class.getCanonicalName(),"/");
        other.addServlet(new ServletHolder(new HelloServlet("YO!")),"*.yo");

        server.start();
        System.err.println(server.dump());
        server.join();
    }
}


text:
	var   Class 		= require( "ee-class" )
		, Events 		= require( "ee-event-emitter" )
		, log 			= require( "ee-log" )
		, crypto 		= require( "crypto" );

	module.exports = new Class( {
		inherits: Events

		, nodes: []
		, index: 0

		, init: function( cluster ){
			this.cluster = cluster;
			this.cluster.on( "nodeAdded", this.handleAddedNode.bind( this ) );
			this.cluster.on( "nodeRemoved", this.handleRemovedNode.bind( this ) );
		}

		, getNode: function(){
			this.index++;
			if ( this.index === this.nodes.length ) this.index = 0;
			return this.nodes[ this.index ];
		}

		, handleRemovedNode: function( node ){
			this.nodes.push( node );
		}

		, handleAddedNode: function( node ){
			var idx = this.nodes.indexOf( node );
			if ( idx >= 0 ) this.nodes.splice( idx, 1 );
		}
	} );


text:
@echo OFF
REM Runs PeriodSource
set CLASSPATH=..\samples\lib\quarks.samples.topology.jar
java quarks.samples.topology.PeriodicSource


text:
roachdemo
=========

A small web application to start a local cockroach cluster. You will
need `cockroach` in your `PATH`.


text:
const assert = require("chai").assert;

const FileBaser = require("./../../src/FileBaser");

describe("AsyncFileBaserTest", () => {
  let db = new FileBaser("file-baser-async.json");
  db.addCollection("datalist");
  db.addCollection("listdata");

  describe("testGettingCollections", () => {
    it("Should get a list of all collections", done => {
      db.getCollectionsAsync().then(collections => {
        assert.isTrue(Array.isArray(collections));

        done();
      });
    });
  });

  describe("testDropppingCollection", () => {
    it("Should drop defined collection and delete all its data", done => {
      db.dropCollectionAsync("listdata").then(response => {
        assert.isTrue(response);

        done();
      });
    });
  });

  describe("testDroppingDatabase", () => {
    it("Should drop database completely and remove it's files", done => {
      db.dropDatabaseAsync().then(response => {
        assert.isTrue(response);

        done();
      });
    });
  });
});


text:
L.Control.ZoomMin = L.Control.Zoom.extend({
  options: {
    position: "topleft",
    zoomInText: "+",
    zoomInTitle: "Zoom in",
    zoomOutText: "-",
    zoomOutTitle: "Zoom out",
    zoomMinText: "Zoom min",
    zoomMinTitle: "Zoom to full extent"
  },

  onAdd: function (map) {
    var zoomName = "leaflet-control-zoom"
      , container = L.DomUtil.create("div", zoomName + " leaflet-bar")
      , options = this.options

    this._map = map

    this._zoomInButton = this._createButton(options.zoomInText, options.zoomInTitle,
     zoomName + '-in', container, this._zoomIn, this)

    this._zoomOutButton = this._createButton(options.zoomOutText, options.zoomOutTitle,
     zoomName + '-out', container, this._zoomOut, this)

    this._zoomMinButton = this._createButton(options.zoomMinText, options.zoomMinTitle,
     zoomName + '-min', container, this._zoomMin, this)

    this._updateDisabled()
    map.on('zoomend zoomlevelschange', this._updateDisabled, this)

    return container
  },

  _zoomMin: function () {
    //this._map.setZoom(this._map.getMinZoom())
	this._map.setView([20,10],this._map.getMinZoom())
  },

  _updateDisabled: function () {
    var map = this._map
      , className = "leaflet-disabled"

    L.DomUtil.removeClass(this._zoomInButton, className)
    L.DomUtil.removeClass(this._zoomOutButton, className)
    L.DomUtil.removeClass(this._zoomMinButton, className)

    if (map._zoom === map.getMinZoom()) {
      L.DomUtil.addClass(this._zoomOutButton, className)
    }

    if (map._zoom === map.getMaxZoom()) {
      L.DomUtil.addClass(this._zoomInButton, className)
    }

    if (map._zoom === map.getMinZoom()) {
      L.DomUtil.addClass(this._zoomMinButton, className)
    }
  }
})


text:
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NBitcoin;
using Newtonsoft.Json.Linq;
using WalletWasabi.Blockchain.Keys;
using WalletWasabi.Wallets;

namespace WalletWasabi.Helpers
{
	public static class ImportWalletHelper
	{
		private const string WalletExistsErrorMessage = "Wallet with the same fingerprint already exists!";

		public static async Task<KeyManager> ImportWalletAsync(WalletManager walletManager, string walletName, string filePath)
		{
			var walletFullPath = walletManager.WalletDirectories.GetWalletFilePaths(walletName).walletFilePath;

			string jsonString = await File.ReadAllTextAsync(filePath).ConfigureAwait(false);
			var jsonWallet = JObject.Parse(jsonString);

			// Older CC wallet file does not contain 'ColdCardFirmwareVersion' but contains the same keys as Wasabi, so we are checking the number
			var isColdcardJson = jsonWallet.Count <= 3;

			KeyManager km = isColdcardJson
				? GetKeyManagerByColdcardJson(walletManager, jsonWallet, walletFullPath)
				: GetKeyManagerByWasabiJson(walletManager, filePath, walletFullPath);

			if (isColdcardJson)
			{
				km.SetIcon(WalletType.Coldcard);
			}

			return km;
		}

		private static KeyManager GetKeyManagerByWasabiJson(WalletManager manager, string filePath, string walletFullPath)
		{
			var km = KeyManager.FromFile(filePath);

			if (manager.WalletExists(km.MasterFingerprint))
			{
				throw new InvalidOperationException(WalletExistsErrorMessage);
			}

			km.SetFilePath(walletFullPath);

			return km;
		}

		private static KeyManager GetKeyManagerByColdcardJson(WalletManager manager, JObject jsonWallet, string walletFullPath)
		{
			var xpubString = jsonWallet["ExtPubKey"].ToString();
			var mfpString = jsonWallet["MasterFingerprint"].ToString();

			// https://github.com/zkSNACKs/WalletWasabi/pull/1663#issuecomment-508073066
			// Coldcard 2.1.0 improperly implemented Wasabi skeleton fingerprint at first, so we must reverse byte order.
			// The solution was to add a ColdCardFirmwareVersion json field from 2.1.1 and correct the one generated by 2.1.0.
			var coldCardVersionString = jsonWallet["ColdCardFirmwareVersion"]?.ToString();
			var reverseByteOrder = false;
			if (coldCardVersionString is null)
			{
				reverseByteOrder = true;
			}
			else
			{
				Version coldCardVersion = new(coldCardVersionString);

				if (coldCardVersion == new Version("2.1.0")) // Should never happen though.
				{
					reverseByteOrder = true;
				}
			}

			var bytes = ByteHelpers.FromHex(Guard.NotNullOrEmptyOrWhitespace(nameof(mfpString), mfpString, trim: true));
			HDFingerprint mfp = reverseByteOrder ? new HDFingerprint(bytes.Reverse().ToArray()) : new HDFingerprint(bytes);

			if (manager.WalletExists(mfp))
			{
				throw new InvalidOperationException(WalletExistsErrorMessage);
			}

			ExtPubKey extPubKey = NBitcoinHelpers.BetterParseExtPubKey(xpubString);

			return KeyManager.CreateNewHardwareWalletWatchOnly(mfp, extPubKey, walletFullPath);
		}
	}
}


text:
@implementation GITUtilityBeltTests
@synthesize unpackedSHA1;
@synthesize packedSHA1Data;
@synthesize packedSHA1String;

- (void)setUp
{
    [super setUp];
    self.unpackedSHA1 = @"bed4001738fa8dad666d669867afaf9f2c2b8c6a";
    self.packedSHA1Data = [NSData dataWithBytes:"\276\324\000\0278\372\215\255fmf\230g\257\257\237,+\214j" length:20];
    self.packedSHA1String = [[NSString alloc] initWithData:self.packedSHA1Data encoding:NSASCIIStringEncoding];
}
- (void)tearDown
{
    self.unpackedSHA1 = nil;
    self.packedSHA1Data = nil;
    self.packedSHA1String = nil;
    [super tearDown];
}
- (void)testPackedSHA1String
{
    GHAssertEquals([packedSHA1String length], (NSUInteger)20, nil);
}
- (void)testShouldPackSHA1FromString
{
    NSData * packed = packSHA1(unpackedSHA1);
    GHAssertEquals([packed length], (NSUInteger)20, nil);
    GHAssertEqualObjects(packed, packedSHA1Data, nil);
}
- (void)testShouldUnpackSHA1FromString
{
    NSString * sha1 = unpackSHA1FromString(packedSHA1String);
    GHAssertEqualObjects(sha1, unpackedSHA1, nil);
}
- (void)testShouldUnpackSHA1FromData
{
    NSString * sha1 = unpackSHA1FromData(packedSHA1Data);
    GHAssertEqualObjects(sha1, unpackedSHA1, nil);
}
- (void)testShouldConvertBinaryToInteger
{   // Contents similar to PACK File version
    uint8_t bytes[4] = { 0x0, 0x0, 0x0, 0x2 };
    NSUInteger val = integerFromBytes(bytes, 4);
    GHAssertEquals(val, (NSUInteger)2, nil);
}
- (void)testShouldConvertBinaryToInteger2
{
    uint8_t bytes[] = { 0x0, 0x0, 0x0, 0xFE };
    NSUInteger val = integerFromBytes(bytes, 4);
    GHAssertEquals(val, (NSUInteger)254, nil);
}
@end


text:
/**
 * @author mrdoob / http://mrdoob.com/
 */

Sidebar.Project = function ( editor ) {

	var config = editor.config;
	var signals = editor.signals;

	var rendererTypes = {

		'WebGLRenderer': THREE.WebGLRenderer,
		'CanvasRenderer': THREE.CanvasRenderer,
		'SVGRenderer': THREE.SVGRenderer,
		'SoftwareRenderer': THREE.SoftwareRenderer,
		'RaytracingRenderer': THREE.RaytracingRenderer

	};

	var container = new UI.CollapsiblePanel();
	container.setCollapsed( config.getKey( 'ui/sidebar/project/collapsed' ) );
	container.onCollapsedChange( function ( boolean ) {

		config.setKey( 'ui/sidebar/project/collapsed', boolean );

	} );

	container.addStatic( new UI.Text( 'PROJECT' ) );
	container.add( new UI.Break() );

	// class

	var options = {};

	for ( var key in rendererTypes ) {

		if ( key.indexOf( 'WebGL' ) >= 0 && System.support.webgl === false ) continue;

		options[ key ] = key;

	}

	var rendererTypeRow = new UI.Panel();
	var rendererType = new UI.Select().setOptions( options ).setWidth( '150px' ).onChange( function () {

		var value = this.getValue();

		if ( value === 'WebGLRenderer' ) {

			rendererPropertiesRow.setDisplay( '' );

		} else {

			rendererPropertiesRow.setDisplay( 'none' );

		}

		config.setKey( 'project/renderer', value );
		updateRenderer();

	} );

	rendererTypeRow.add( new UI.Text( 'Renderer' ).setWidth( '90px' ) );
	rendererTypeRow.add( rendererType );

	container.add( rendererTypeRow );

	if ( config.getKey( 'project/renderer' ) !== undefined ) {

		rendererType.setValue( config.getKey( 'project/renderer' ) );

	}

	// antialiasing

	var rendererPropertiesRow = new UI.Panel();
	rendererPropertiesRow.add( new UI.Text( '' ).setWidth( '90px' ) );

	var rendererAntialiasSpan = new UI.Span().setMarginRight( '10px' );
	var rendererAntialias = new UI.Checkbox( config.getKey( 'project/renderer/antialias' ) ).setLeft( '100px' ).onChange( function () {

		config.setKey( 'project/renderer/antialias', this.getValue() );
		updateRenderer();

	} );

	rendererAntialiasSpan.add( rendererAntialias );
	rendererAntialiasSpan.add( new UI.Text( 'antialias' ).setMarginLeft( '3px' ) );

	rendererPropertiesRow.add( rendererAntialiasSpan );

	// shadow

	var rendererShadowsSpan = new UI.Span();
	var rendererShadows = new UI.Checkbox( config.getKey( 'project/renderer/shadows' ) ).setLeft( '100px' ).onChange( function () {

		config.setKey( 'project/renderer/shadows', this.getValue() );
		updateRenderer();

	} );

	rendererShadowsSpan.add( rendererShadows );
	rendererShadowsSpan.add( new UI.Text( 'shadows' ).setMarginLeft( '3px' ) );

	rendererPropertiesRow.add( rendererShadowsSpan );

	container.add( rendererPropertiesRow );

	// VR

	var vrRow = new UI.Panel();
	var vr = new UI.Checkbox( config.getKey( 'project/vr' ) ).setLeft( '100px' ).onChange( function () {

		config.setKey( 'project/vr', this.getValue() );
		// updateRenderer();

	} );

	vrRow.add( new UI.Text( 'VR' ).setWidth( '90px' ) );
	vrRow.add( vr );

	container.add( vrRow );

	//

	function updateRenderer() {

		createRenderer( rendererType.getValue(), rendererAntialias.getValue(), rendererShadows.getValue() );

	}

	function createRenderer( type, antialias, shadows ) {

		if ( type === 'WebGLRenderer' && System.support.webgl === false ) {

			type = 'CanvasRenderer';

		}

		var renderer = new rendererTypes[ type ]( { antialias: antialias } );
		if ( shadows && renderer.shadowMap ) renderer.shadowMap.enabled = true;
		signals.rendererChanged.dispatch( renderer );

	}

	createRenderer( config.getKey( 'project/renderer' ), config.getKey( 'project/renderer/antialias' ), config.getKey( 'project/renderer/shadows' ) );

	return container;

}


text:
'use strict';

var _ = require('lodash');

var ConditionLockedException = require('../exception/ConditionLockedException'),
    ConditionViolationException = require('../exception/ConditionViolationException'),
    IllegalParameterException = require('../exception/IllegalParameterException');

/**
 * @abstract
 * @class lewd.condition.Condition
 * @constructor
 * @param {string} type
 */
function Condition(type) {
    this._coerce = false;
    this._customError = null;
    this._default = undefined;
    this._locked = false;
    this._name = null;
    this._state = null;
    this._type = type;
    this._wrapper = null;
}

/**
 * Constants used by `setPropertyState`.
 *
 * @type {Object.<string, string>}
 */
Condition.PROPERTY_STATE = {
    UNSPECIFIED: 'unspecified',
    FORBIDDEN: 'forbidden',
    REQUIRED: 'required',
    OPTIONAL: 'optional'
};

/* eslint-disable no-unused-expressions */
/**
 * Internal flag to indicate whether coercion is enabled.
 *
 * @protected
 * @type {boolean}
 */
Condition.prototype._coerce;

/**
 * The custom error message or `null` if the default message is to be used.
 *
 * @protected
 * @type {(string|null)}
 */
Condition.prototype._customError;

/**
 * The default value for object properties.
 *
 * @private
 * @type {*}
 */
Condition.prototype._default;

/**
 * The "locked" flag.
 *
 * @private
 * @type {boolean}
 */
Condition.prototype._locked;

/**
 * The user-defined name of the condition.
 *
 * @private
 * @type {?string}
 */
Condition.prototype._name;

/**
 * The required/optional state for object properties.
 *
 * @private
 * @type {string}
 */
Condition.prototype._state;

/**
 * The (hopefully unique) type of the condition.
 *
 * @readonly
 * @protected
 * @type {string}
 */
Condition.prototype._type;

/**
 * The consumer wrapper.
 *
 * @private
 * @type {?lewd.condition.ConsumerWrapper}
 */
Condition.prototype._wrapper;
/* eslint-enable no-unused-expressions */

/**
 * Asserts that the condition has not been locked.
 *
 * @private
 * @throws {lewd.exception.ConditionLockedException}
 */
Condition.prototype._assertNotLocked = function () {
    if (this._locked) {
        throw new ConditionLockedException();
    }
};

/**
 * Returns this condition's internal type.
 *
 * @return {string}
 */
Condition.prototype.getType = function () {
    return this._type;
};

/**
 * The actual validation function. Must return the input value (or its coerced version).
 *
 * @abstract
 * @param {*} value
 * @param {Array.<(string|number)>} path
 * @return {*}
 * @throws {lewd.exception.ConditionViolationException}
 */
Condition.prototype.validate = function (value, path) {
    throw new Error('Condition must overwrite its validate() method');
};

/**
 * Wrapper function for rejecting a value by throwing the appropriate exception.
 * Takes care of overriding the passed message with the custom message if needed.
 *
 * @param {*} value
 * @param {Array.<(string|number)>} path
 * @param {string} messageTemplate
 * @param {Object.<string, *>=} templateData
 * @throws {lewd.exception.ConditionViolationException}
 */
Condition.prototype.reject = function (value, path, messageTemplate, templateData) {
    var data = templateData || {},
        error = this._customError ? this._customError : messageTemplate;

    if (this._customError) {
        data.originalMessage = messageTemplate;
    }

    throw new ConditionViolationException(value, path, error, data);
};

/**
 * Get a condition by its user-assigned name. Returns an array containing this instance if the name matches and an empty
 * array otherwise.
 *
 * @param {string} name
 * @return {Array.<lewd.condition.ConsumerWrapper>}
 */
Condition.prototype.find = function (name) {
    return this._name === name ? [this.consumer()] : [];
};

/**
 * Locks the condition to prevent it or its nested conditions from being modified (e.g., changing the default value).
 *
 * @return {lewd.condition.Condition}
 */
Condition.prototype.lock = function () {
    this._locked = true;
    return this;
};

/**
 * Set a custom error message.
 *
 * @param {?string} messageTemplate
 * @return {lewd.condition.Condition}
 * @throws {lewd.exception.ConditionLockedException}
 */
Condition.prototype.setCustomMessage = function (messageTemplate) {
    this._assertNotLocked();
    this._customError = messageTemplate;
    return this;
};

/**
 * Sets the conditions user-defined name.
 *
 * @param {string} name
 * @return {lewd.condition.Condition}
 * @throws {lewd.exception.ConditionLockedException}
 */
Condition.prototype.setName = function (name) {
    this._assertNotLocked();
    this._name = name;
    return this;
};

/**
 * Check whether coercion is enabled.
 *
 * @return {boolean}
 */
Condition.prototype.isCoercionEnabled = function () {
    return this._coerce;
};

/**
 * Enable or disable coercion.
 *
 * @param {boolean} enabled
 * @return {lewd.condition.Condition}
 * @throws {lewd.exception.ConditionLockedException}
 */
Condition.prototype.setCoercionEnabled = function (enabled) {
    this._assertNotLocked();

    if (!this.supportsCoercion) {
        throw new IllegalParameterException('Condition does not support coercion');
    }

    this._coerce = !!enabled;
    return this;
};

/**
 * Gets the property state.
 *
 * @return {string}
 */
Condition.prototype.getPropertyState = function () {
    return this._state;
};

/**
 * Sets the property state, i.e. whether the value associated with this condition is required or optional (or neither)
 * when used as an object property (ignored if it is not).
 *
 * @param {string} state
 * @return {lewd.condition.Condition}
 * @throws {lewd.exception.ConditionLockedException}
 */
Condition.prototype.setPropertyState = function (state) {
    this._assertNotLocked();
    this._state = state;
    return this;
};

/**
 * Gets the default value when used as an object property.
 *
 * @return {*}
 */
Condition.prototype.getDefaultValue = function () {
    return this._default;
};

/**
 * Sets the default value when used as an object property (ignored if it is not).
 *
 * @param {*} value
 * @return {lewd.condition.Condition}
 * @throws {lewd.exception.ConditionLockedException}
 */
Condition.prototype.setDefaultValue = function (value) {
    this._assertNotLocked();
    this._default = value;
    return this;
};

/**
 * Returns a "consumer" object of this condition that hides away the internals and provides convenience methods.
 *
 * @return {lewd.condition.ConsumerWrapper}
 */
Condition.prototype.consumer = function () {
    if (!this._wrapper) {
        this._wrapper = require('./ConsumerWrapper').wrap(this);
    }

    return this._wrapper;
};

module.exports = Condition;


text: {{ctrlError.message}}


text:
package turbofinance.com.turbofinance;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
<?php

declare(strict_types=1);

namespace setasign\SetaPDF\Signer\Module\SwisscomAIS;

class BatchAsyncModule extends AbstractAsyncModule
{
    /**
     * @var DocumentData[]
     */
    protected $documentsData;

    /**
     * @var bool
     */
    protected $updateDss;

    /**
     * The byte length of the reserved space for the signature content
     *
     * @var int
     */
    protected $signatureConentLength = 36000;

    /**
     * Set the signature content length that will be used to reserve space for the final signature.
     *
     * @param int $signatureContentLength The length of the signature content.
     */
    public function setSignatureContentLength(int $signatureContentLength)
    {
        $this->signatureConentLength = $signatureContentLength;
    }

    /**
     * Get the signature content length that will be used to reserve space for the final signature.
     *
     * @return int
     */
    public function getSignatureContentLength(): int
    {
        return $this->signatureConentLength;
    }

    /**
     * @param BatchProcessData $processData
     */
    public function setProcessData(BatchProcessData $processData): void
    {
        $this->pendingResponseId = $processData->getPendingResponseId();
        $this->currentRequestId = $processData->getPendingRequestId();
        $this->documentsData = $processData->getDocumentsData();
        $this->updateDss = $processData->getUpdateDss();
    }

    /**
     * Inititates an asynchronous signature batch process.
     *
     * The documents have to be passed as an array with the following structure:
     *
     * <code>
     * $documents = [
     *     [
     *         'in' => 'local/path/non-signed.pdf', // or an instance of \SetaPDF_Core_Reader_String|\SetaPDF_Core_Reader_File
     *         'out' => 'local/path/to/resulting.pdf', // or an instance implementing \SetaPDF_Core_Writer_WriterInterface
     *         'tmp' => 'local/path/to/a/temporary.file', // or an instance of \SetaPDF_Core_Writer_FileInterface
     *         'metadata' => [ // you can pass any foreign data related to your own process which can be accessed later
     *             'custom' => 'data',
     *             'document-id' => 12345
     *         ]
     *     ],
     *     // ...
     * ];
     * </code>
     *
     * @param array{in:string|\SetaPDF_Core_Reader_String|\SetaPDF_Core_Reader_File, out: string|\SetaPDF_Core_Writer_WriterInterface, tmp: string|\SetaPDF_Core_Writer_FileInterface, metadata: array}[] $documents
     * @param bool $updateDss Defines wether the revocation information should be added via DSS or not.
     * @param array $signatureProperties
     * @return BatchProcessData
     * @throws Exception
     * @throws \SetaPDF_Core_Exception
     * @throws \SetaPDF_Signer_Exception
     * @throws \SetaPDF_Signer_Exception_ContentLength
     */
    public function initSignature(array $documents, bool $updateDss = true, array $signatureProperties = []): BatchProcessData
    {
        if ($this->pendingResponseId !== null) {
            throw new \BadMethodCallException(
                'Cannot use AsyncModule::initSignature() after setting process data.
                 Use AsyncModule::processPendingSignature() instead.'
            );
        }

        $digestMethod = $this->getDigestMethod();

        $data = [];
        $files = [];

        $no = 0;
        foreach ($documents as $documentData) {
            if (!$documentData['in'] instanceof \SetaPDF_Core_Reader_ReaderInterface) {
                $reader = new \SetaPDF_Core_Reader_File($documentData['in']);
            } else {
                $reader = $documentData['in'];
            }

            $serializedReader = \serialize($reader);

            if (!$documentData['out'] instanceof \SetaPDF_Core_Writer_WriterInterface) {
                $documentData['out'] = new \SetaPDF_Core_Writer_File($documentData['out']);
            }

            if (!$documentData['tmp'] instanceof \SetaPDF_Core_Writer_FileInterface) {
                $documentData['tmp'] = new \SetaPDF_Core_Writer_File($documentData['tmp']);
            }

            $document = \SetaPDF_Core_Document::load($reader);
            $signer = new \SetaPDF_Signer($document);
            $signer->setAllowSignatureContentLengthChange(false);
            $signer->setSignatureContentLength($this->getSignatureContentLength());
            $fieldName = $signer->addSignatureField()->getQualifiedName();
            $signer->setSignatureFieldName($fieldName);

            foreach ($signatureProperties as $name => $value) {
                $signer->setSignatureProperty($name, $value);
            }

            // prepare the PDF
            $tmpDocument = $signer->preSign($documentData['tmp'], $this);

            $data[$no] = new DocumentData($serializedReader, $documentData['out'], $tmpDocument, $fieldName);
            if (isset($documentData['metadata'])) {
                $data[$no]->setMetadata($documentData['metadata']);
            }

            $files[] = [
                'algorithm' => $digestMethod,
                'digest' => \base64_encode($this->generateHash($tmpDocument->getHashFile()))
            ];

            $no++;
        }

        $requestId = \uniqid();
        $requestData = $this->buildSignRequestData(
            $requestId,
            $files
        );

        $responseData = $this->callUrl('https://ais.swisscom.com/AIS-Server/rs/v1.0/sign', $requestData);
        $this->lastResponseData = $responseData;
        if ($responseData['SignResponse']['@RequestID'] !== $requestId) {
            throw new Exception(\sprintf(
                'Invalid request id from response! Expected "%s" but got "%s"',
                $requestId,
                $responseData['SignResponse']['@RequestID']
            ));
        }

        $result = $responseData['SignResponse']['Result']['ResultMajor'];
        if ($result === 'urn:oasis:names:tc:dss:1.0:profiles:asynchronousprocessing:resultmajor:Pending') {
            $this->pendingResponseId = $responseData['SignResponse']['OptionalOutputs']['async.ResponseID'];
            return new BatchProcessData($requestId, $this->pendingResponseId, $updateDss, ...$data);
        }

        throw new SignException($requestData, $responseData);
    }

    /**
     * @return bool False if the signature process is still pending.
     * @throws Exception
     * @throws SignException
     * @throws \SetaPDF_Core_Exception
     * @throws \SetaPDF_Signer_Asn1_Exception
     * @throws \SetaPDF_Signer_Exception
     * @throws \SetaPDF_Signer_Exception_ContentLength
     */
    public function processPendingSignature(): bool
    {
        if ($this->pendingResponseId === null) {
            throw new \BadMethodCallException(
                'Cannot use AsyncModule::processPendingSignature() without setting process data.'
            );
        }

        $requestData = [
            'async.PendingRequest' => [
                '@Profile' => 'http://ais.swisscom.ch/1.1',
                'OptionalInputs' => [
                    'ClaimedIdentity' => [
                        'Name' => $this->identity
                    ],
                    'async.ResponseID' => $this->pendingResponseId
                ]
            ]
        ];

        $responseData = $this->callUrl('https://ais.swisscom.com/AIS-Server/rs/v1.0/pending', $requestData);

        if (isset($responseData['Response'])) {
            throw new Exception(\sprintf(
                'Unexpected response! Result major "%s". Result minor "%s". Result message: %s',
                $responseData['Response']['Result']['ResultMajor'],
                $responseData['Response']['Result']['ResultMinor'],
                $responseData['Response']['Result']['ResultMessage']['$']
            ));
        }

        if (!isset($responseData['SignResponse']['@RequestID'])) {
            throw new Exception('Invalid response!');
        }

        if ($responseData['SignResponse']['@RequestID'] !== $this->currentRequestId) {
            throw new Exception(\sprintf(
                'Invalid request id from response! Expected "%s" but got "%s"',
                $this->currentRequestId,
                $responseData['SignResponse']['@RequestID']
            ));
        }

        $result = $responseData['SignResponse']['Result']['ResultMajor'];
        if ($result === 'urn:oasis:names:tc:dss:1.0:profiles:asynchronousprocessing:resultmajor:Pending') {
            return false;
        }

        if ($result !== 'urn:oasis:names:tc:dss:1.0:resultmajor:Success') {
            throw new SignException($requestData, $responseData);
        }

        if (\count($this->documentsData) > 1) {
            $signatureObjects = $responseData['SignResponse']['SignatureObject']['Other']['sc.SignatureObjects']['sc.ExtendedSignatureObject'];
            $multipleSignatures = true;
        } else {
            $signatureObjects = [$responseData['SignResponse']['SignatureObject']];
            $multipleSignatures = false;
        }

        foreach ($signatureObjects as $signatureObject) {
            if ($multipleSignatures) {
                if (!\preg_match('~^' . \preg_quote($this->currentRequestId, '~') . '-(?P<no>\d+)' . '~', $signatureObject['@WhichDocument'], $matches)) {
                    throw new Exception(\sprintf('Unknown document id "%s"', $signatureObject['@WhichDocument']));
                }
                $no = $matches['no'];
            } else {
                $no = 0;
            }
            $documentData = $this->documentsData[$no];

            $signatureResponse = $signatureObject['Base64Signature']['$'];
            $signatureValue = \base64_decode($signatureResponse);

            $document = \SetaPDF_Core_Document::load($documentData->getReader());
            $signer = new \SetaPDF_Signer($document);

            if (!$this->updateDss) {
                $document->setWriter($documentData->getWriter());
                $signer->saveSignature($documentData->getTmpDocument(), $signatureValue);
            } else {
                $tempWriter  = new \SetaPDF_Core_Writer_TempFile();
                $document->setWriter($tempWriter);
                $signer->saveSignature($documentData->getTmpDocument(), $signatureValue);

                $document = \SetaPDF_Core_Document::loadByFilename($tempWriter->getPath(), $documentData->getWriter());
                $this->updateDss($document, $documentData->getFieldName());
                $document->save()->finish();
            }

            // clean up temporary file
            \unlink($documentData->getTmpDocument()->getWriter()->getPath());
        }
        return true;
    }

    public function cleanupTemporaryFiles()
    {
        if ($this->pendingResponseId === null) {
            throw new \BadMethodCallException(
                'Cannot use AsyncModule::cleanupTemporaryFiles() without setting process data.'
            );
        }

        foreach ($this->documentsData as $documentData) {
            @\unlink($documentData->getTmpDocument()->getWriter()->getPath());
        }
    }
}


text:
"""Test the bulk API."""

import sys
import uuid

from pymongo.mongo_client import MongoClient

sys.path[0:0] = [""]

from test import IntegrationTest, client_context, unittest
from test.utils import (
    remove_all_users,
    rs_or_single_client_noauth,
    single_client,
    wait_until,
)

from bson.binary import Binary, UuidRepresentation
from bson.codec_options import CodecOptions
from bson.objectid import ObjectId
from pymongo.collection import Collection
from pymongo.common import partition_node
from pymongo.errors import (
    BulkWriteError,
    ConfigurationError,
    InvalidOperation,
    OperationFailure,
)
from pymongo.operations import *
from pymongo.write_concern import WriteConcern

class BulkTestBase(IntegrationTest):
    coll: Collection
    coll_w0: Collection

    @classmethod
    def setUpClass(cls):
        super(BulkTestBase, cls).setUpClass()
        cls.coll = cls.db.test
        cls.coll_w0 = cls.coll.with_options(write_concern=WriteConcern(w=0))

    def setUp(self):
        super(BulkTestBase, self).setUp()
        self.coll.drop()

    def assertEqualResponse(self, expected, actual):
        """Compare response from bulk.execute() to expected response."""
        for key, value in expected.items():
            if key == "nModified":
                self.assertEqual(value, actual["nModified"])
            elif key == "upserted":
                expected_upserts = value
                actual_upserts = actual["upserted"]
                self.assertEqual(
                    len(expected_upserts),
                    len(actual_upserts),
                    'Expected %d elements in "upserted", got %d'
                    % (len(expected_upserts), len(actual_upserts)),
                )

                for e, a in zip(expected_upserts, actual_upserts):
                    self.assertEqualUpsert(e, a)

            elif key == "writeErrors":
                expected_errors = value
                actual_errors = actual["writeErrors"]
                self.assertEqual(
                    len(expected_errors),
                    len(actual_errors),
                    'Expected %d elements in "writeErrors", got %d'
                    % (len(expected_errors), len(actual_errors)),
                )

                for e, a in zip(expected_errors, actual_errors):
                    self.assertEqualWriteError(e, a)

            else:
                self.assertEqual(
                    actual.get(key),
                    value,
                    "%r value of %r does not match expected %r" % (key, actual.get(key), value),
                )

    def assertEqualUpsert(self, expected, actual):
        """Compare bulk.execute()['upserts'] to expected value.

        Like: {'index': 0, '_id': ObjectId()}
        """
        self.assertEqual(expected["index"], actual["index"])
        if expected["_id"] == "...":
            # Unspecified value.
            self.assertTrue("_id" in actual)
        else:
            self.assertEqual(expected["_id"], actual["_id"])

    def assertEqualWriteError(self, expected, actual):
        """Compare bulk.execute()['writeErrors'] to expected value.

        Like: {'index': 0, 'code': 123, 'errmsg': '...', 'op': { ... }}
        """
        self.assertEqual(expected["index"], actual["index"])
        self.assertEqual(expected["code"], actual["code"])
        if expected["errmsg"] == "...":
            # Unspecified value.
            self.assertTrue("errmsg" in actual)
        else:
            self.assertEqual(expected["errmsg"], actual["errmsg"])

        expected_op = expected["op"].copy()
        actual_op = actual["op"].copy()
        if expected_op.get("_id") == "...":
            # Unspecified _id.
            self.assertTrue("_id" in actual_op)
            actual_op.pop("_id")
            expected_op.pop("_id")

        self.assertEqual(expected_op, actual_op)

class TestBulk(BulkTestBase):
    def test_empty(self):
        self.assertRaises(InvalidOperation, self.coll.bulk_write, [])

    def test_insert(self):
        expected = {
            "nMatched": 0,
            "nModified": 0,
            "nUpserted": 0,
            "nInserted": 1,
            "nRemoved": 0,
            "upserted": [],
            "writeErrors": [],
            "writeConcernErrors": [],
        }

        result = self.coll.bulk_write([InsertOne({})])
        self.assertEqualResponse(expected, result.bulk_api_result)
        self.assertEqual(1, result.inserted_count)
        self.assertEqual(1, self.coll.count_documents({}))

    def _test_update_many(self, update):

        expected = {
            "nMatched": 2,
            "nModified": 2,
            "nUpserted": 0,
            "nInserted": 0,
            "nRemoved": 0,
            "upserted": [],
            "writeErrors": [],
            "writeConcernErrors": [],
        }
        self.coll.insert_many([{}, {}])

        result = self.coll.bulk_write([UpdateMany({}, update)])
        self.assertEqualResponse(expected, result.bulk_api_result)
        self.assertEqual(2, result.matched_count)
        self.assertTrue(result.modified_count in (2, None))

    def test_update_many(self):
        self._test_update_many({"$set": {"foo": "bar"}})

    @client_context.require_version_min(4, 1, 11)
    def test_update_many_pipeline(self):
        self._test_update_many([{"$set": {"foo": "bar"}}])

    def test_array_filters_validation(self):
        self.assertRaises(TypeError, UpdateMany, {}, {}, array_filters={})
        self.assertRaises(TypeError, UpdateOne, {}, {}, array_filters={})

    def test_array_filters_unacknowledged(self):
        coll = self.coll_w0
        update_one = UpdateOne({}, {"$set": {"y.$[i].b": 5}}, array_filters=[{"i.b": 1}])
        update_many = UpdateMany({}, {"$set": {"y.$[i].b": 5}}, array_filters=[{"i.b": 1}])
        self.assertRaises(ConfigurationError, coll.bulk_write, [update_one])
        self.assertRaises(ConfigurationError, coll.bulk_write, [update_many])

    def _test_update_one(self, update):
        expected = {
            "nMatched": 1,
            "nModified": 1,
            "nUpserted": 0,
            "nInserted": 0,
            "nRemoved": 0,
            "upserted": [],
            "writeErrors": [],
            "writeConcernErrors": [],
        }

        self.coll.insert_many([{}, {}])

        result = self.coll.bulk_write([UpdateOne({}, update)])
        self.assertEqualResponse(expected, result.bulk_api_result)
        self.assertEqual(1, result.matched_count)
        self.assertTrue(result.modified_count in (1, None))

    def test_update_one(self):
        self._test_update_one({"$set": {"foo": "bar"}})

    @client_context.require_version_min(4, 1, 11)
    def test_update_one_pipeline(self):
        self._test_update_one([{"$set": {"foo": "bar"}}])

    def test_replace_one(self):

        expected = {
            "nMatched": 1,
            "nModified": 1,
            "nUpserted": 0,
            "nInserted": 0,
            "nRemoved": 0,
            "upserted": [],
            "writeErrors": [],
            "writeConcernErrors": [],
        }

        self.coll.insert_many([{}, {}])

        result = self.coll.bulk_write([ReplaceOne({}, {"foo": "bar"})])
        self.assertEqualResponse(expected, result.bulk_api_result)
        self.assertEqual(1, result.matched_count)
        self.assertTrue(result.modified_count in (1, None))

    def test_remove(self):
        # Test removing all documents, ordered.
        expected = {
            "nMatched": 0,
            "nModified": 0,
            "nUpserted": 0,
            "nInserted": 0,
            "nRemoved": 2,
            "upserted": [],
            "writeErrors": [],
            "writeConcernErrors": [],
        }
        self.coll.insert_many([{}, {}])

        result = self.coll.bulk_write([DeleteMany({})])
        self.assertEqualResponse(expected, result.bulk_api_result)
        self.assertEqual(2, result.deleted_count)

    def test_remove_one(self):
        # Test removing one document, empty selector.
        self.coll.insert_many([{}, {}])
        expected = {
            "nMatched": 0,
            "nModified": 0,
            "nUpserted": 0,
            "nInserted": 0,
            "nRemoved": 1,
            "upserted": [],
            "writeErrors": [],
            "writeConcernErrors": [],
        }

        result = self.coll.bulk_write([DeleteOne({})])
        self.assertEqualResponse(expected, result.bulk_api_result)
        self.assertEqual(1, result.deleted_count)
        self.assertEqual(self.coll.count_documents({}), 1)

    def test_upsert(self):

        expected = {
            "nMatched": 0,
            "nModified": 0,
            "nUpserted": 1,
            "nInserted": 0,
            "nRemoved": 0,
            "upserted": [{"index": 0, "_id": "..."}],
        }

        result = self.coll.bulk_write([ReplaceOne({}, {"foo": "bar"}, upsert=True)])
        self.assertEqualResponse(expected, result.bulk_api_result)
        self.assertEqual(1, result.upserted_count)
        assert result.upserted_ids is not None
        self.assertEqual(1, len(result.upserted_ids))
        self.assertTrue(isinstance(result.upserted_ids.get(0), ObjectId))

        self.assertEqual(self.coll.count_documents({"foo": "bar"}), 1)

    def test_numerous_inserts(self):
        # Ensure we don't exceed server's maxWriteBatchSize size limit.
        n_docs = client_context.max_write_batch_size + 100
        requests = [InsertOne[dict]({}) for _ in range(n_docs)]
        result = self.coll.bulk_write(requests, ordered=False)
        self.assertEqual(n_docs, result.inserted_count)
        self.assertEqual(n_docs, self.coll.count_documents({}))

        # Same with ordered bulk.
        self.coll.drop()
        result = self.coll.bulk_write(requests)
        self.assertEqual(n_docs, result.inserted_count)
        self.assertEqual(n_docs, self.coll.count_documents({}))

    def test_bulk_max_message_size(self):
        self.coll.delete_many({})
        self.addCleanup(self.coll.delete_many, {})
        _16_MB = 16 * 1000 * 1000
        # Generate a list of documents such that the first batched OP_MSG is
        # as close as possible to the 48MB limit.
        docs = [
            {"_id": 1, "l": "s" * _16_MB},
            {"_id": 2, "l": "s" * _16_MB},
            {"_id": 3, "l": "s" * (_16_MB - 10000)},
        ]
        # Fill in the remaining ~10000 bytes with small documents.
        for i in range(4, 10000):
            docs.append({"_id": i})
        result = self.coll.insert_many(docs)
        self.assertEqual(len(docs), len(result.inserted_ids))

    def test_generator_insert(self):
        def gen():
            yield {"a": 1, "b": 1}
            yield {"a": 1, "b": 2}
            yield {"a": 2, "b": 3}
            yield {"a": 3, "b": 5}
            yield {"a": 5, "b": 8}

        result = self.coll.insert_many(gen())
        self.assertEqual(5, len(result.inserted_ids))

    def test_bulk_write_no_results(self):
        result = self.coll_w0.bulk_write([InsertOne({})])
        self.assertFalse(result.acknowledged)
        self.assertRaises(InvalidOperation, lambda: result.inserted_count)
        self.assertRaises(InvalidOperation, lambda: result.matched_count)
        self.assertRaises(InvalidOperation, lambda: result.modified_count)
        self.assertRaises(InvalidOperation, lambda: result.deleted_count)
        self.assertRaises(InvalidOperation, lambda: result.upserted_count)
        self.assertRaises(InvalidOperation, lambda: result.upserted_ids)

    def test_bulk_write_invalid_arguments(self):
        # The requests argument must be a list.
        generator = (InsertOne[dict]({}) for _ in range(10))
        with self.assertRaises(TypeError):
            self.coll.bulk_write(generator)  # type: ignore[arg-type]

        # Document is not wrapped in a bulk write operation.
        with self.assertRaises(TypeError):
            self.coll.bulk_write([{}])  # type: ignore[list-item]

    def test_upsert_large(self):
        big = "a" * (client_context.max_bson_size - 37)
        result = self.coll.bulk_write([UpdateOne({"x": 1}, {"$set": {"s": big}}, upsert=True)])
        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 1,
                "nInserted": 0,
                "nRemoved": 0,
                "upserted": [{"index": 0, "_id": "..."}],
            },
            result.bulk_api_result,
        )

        self.assertEqual(1, self.coll.count_documents({"x": 1}))

    def test_client_generated_upsert_id(self):
        result = self.coll.bulk_write(
            [
                UpdateOne({"_id": 0}, {"$set": {"a": 0}}, upsert=True),
                ReplaceOne({"a": 1}, {"_id": 1}, upsert=True),
                # This is just here to make the counts right in all cases.
                ReplaceOne({"_id": 2}, {"_id": 2}, upsert=True),
            ]
        )
        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 3,
                "nInserted": 0,
                "nRemoved": 0,
                "upserted": [
                    {"index": 0, "_id": 0},
                    {"index": 1, "_id": 1},
                    {"index": 2, "_id": 2},
                ],
            },
            result.bulk_api_result,
        )

    def test_upsert_uuid_standard(self):
        options = CodecOptions(uuid_representation=UuidRepresentation.STANDARD)
        coll = self.coll.with_options(codec_options=options)
        uuids = [uuid.uuid4() for _ in range(3)]
        result = coll.bulk_write(
            [
                UpdateOne({"_id": uuids[0]}, {"$set": {"a": 0}}, upsert=True),
                ReplaceOne({"a": 1}, {"_id": uuids[1]}, upsert=True),
                # This is just here to make the counts right in all cases.
                ReplaceOne({"_id": uuids[2]}, {"_id": uuids[2]}, upsert=True),
            ]
        )
        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 3,
                "nInserted": 0,
                "nRemoved": 0,
                "upserted": [
                    {"index": 0, "_id": uuids[0]},
                    {"index": 1, "_id": uuids[1]},
                    {"index": 2, "_id": uuids[2]},
                ],
            },
            result.bulk_api_result,
        )

    def test_upsert_uuid_unspecified(self):
        options = CodecOptions(uuid_representation=UuidRepresentation.UNSPECIFIED)
        coll = self.coll.with_options(codec_options=options)
        uuids = [Binary.from_uuid(uuid.uuid4()) for _ in range(3)]
        result = coll.bulk_write(
            [
                UpdateOne({"_id": uuids[0]}, {"$set": {"a": 0}}, upsert=True),
                ReplaceOne({"a": 1}, {"_id": uuids[1]}, upsert=True),
                # This is just here to make the counts right in all cases.
                ReplaceOne({"_id": uuids[2]}, {"_id": uuids[2]}, upsert=True),
            ]
        )
        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 3,
                "nInserted": 0,
                "nRemoved": 0,
                "upserted": [
                    {"index": 0, "_id": uuids[0]},
                    {"index": 1, "_id": uuids[1]},
                    {"index": 2, "_id": uuids[2]},
                ],
            },
            result.bulk_api_result,
        )

    def test_upsert_uuid_standard_subdocuments(self):
        options = CodecOptions(uuid_representation=UuidRepresentation.STANDARD)
        coll = self.coll.with_options(codec_options=options)
        ids: list = [{"f": Binary(bytes(i)), "f2": uuid.uuid4()} for i in range(3)]

        result = coll.bulk_write(
            [
                UpdateOne({"_id": ids[0]}, {"$set": {"a": 0}}, upsert=True),
                ReplaceOne({"a": 1}, {"_id": ids[1]}, upsert=True),
                # This is just here to make the counts right in all cases.
                ReplaceOne({"_id": ids[2]}, {"_id": ids[2]}, upsert=True),
            ]
        )

        # The `Binary` values are returned as `bytes` objects.
        for _id in ids:
            _id["f"] = bytes(_id["f"])

        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 3,
                "nInserted": 0,
                "nRemoved": 0,
                "upserted": [
                    {"index": 0, "_id": ids[0]},
                    {"index": 1, "_id": ids[1]},
                    {"index": 2, "_id": ids[2]},
                ],
            },
            result.bulk_api_result,
        )

    def test_single_ordered_batch(self):
        result = self.coll.bulk_write(
            [
                InsertOne({"a": 1}),
                UpdateOne({"a": 1}, {"$set": {"b": 1}}),
                UpdateOne({"a": 2}, {"$set": {"b": 2}}, upsert=True),
                InsertOne({"a": 3}),
                DeleteOne({"a": 3}),
            ]
        )
        self.assertEqualResponse(
            {
                "nMatched": 1,
                "nModified": 1,
                "nUpserted": 1,
                "nInserted": 2,
                "nRemoved": 1,
                "upserted": [{"index": 2, "_id": "..."}],
            },
            result.bulk_api_result,
        )

    def test_single_error_ordered_batch(self):
        self.coll.create_index("a", unique=True)
        self.addCleanup(self.coll.drop_index, [("a", 1)])
        requests: list = [
            InsertOne({"b": 1, "a": 1}),
            UpdateOne({"b": 2}, {"$set": {"a": 1}}, upsert=True),
            InsertOne({"b": 3, "a": 2}),
        ]
        try:
            self.coll.bulk_write(requests)
        except BulkWriteError as exc:
            result = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")

        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 0,
                "nInserted": 1,
                "nRemoved": 0,
                "upserted": [],
                "writeConcernErrors": [],
                "writeErrors": [
                    {
                        "index": 1,
                        "code": 11000,
                        "errmsg": "...",
                        "op": {
                            "q": {"b": 2},
                            "u": {"$set": {"a": 1}},
                            "multi": False,
                            "upsert": True,
                        },
                    }
                ],
            },
            result,
        )

    def test_multiple_error_ordered_batch(self):
        self.coll.create_index("a", unique=True)
        self.addCleanup(self.coll.drop_index, [("a", 1)])
        requests: list = [
            InsertOne({"b": 1, "a": 1}),
            UpdateOne({"b": 2}, {"$set": {"a": 1}}, upsert=True),
            UpdateOne({"b": 3}, {"$set": {"a": 2}}, upsert=True),
            UpdateOne({"b": 2}, {"$set": {"a": 1}}, upsert=True),
            InsertOne({"b": 4, "a": 3}),
            InsertOne({"b": 5, "a": 1}),
        ]

        try:
            self.coll.bulk_write(requests)
        except BulkWriteError as exc:
            result = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")

        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 0,
                "nInserted": 1,
                "nRemoved": 0,
                "upserted": [],
                "writeConcernErrors": [],
                "writeErrors": [
                    {
                        "index": 1,
                        "code": 11000,
                        "errmsg": "...",
                        "op": {
                            "q": {"b": 2},
                            "u": {"$set": {"a": 1}},
                            "multi": False,
                            "upsert": True,
                        },
                    }
                ],
            },
            result,
        )

    def test_single_unordered_batch(self):
        requests: list = [
            InsertOne({"a": 1}),
            UpdateOne({"a": 1}, {"$set": {"b": 1}}),
            UpdateOne({"a": 2}, {"$set": {"b": 2}}, upsert=True),
            InsertOne({"a": 3}),
            DeleteOne({"a": 3}),
        ]
        result = self.coll.bulk_write(requests, ordered=False)
        self.assertEqualResponse(
            {
                "nMatched": 1,
                "nModified": 1,
                "nUpserted": 1,
                "nInserted": 2,
                "nRemoved": 1,
                "upserted": [{"index": 2, "_id": "..."}],
                "writeErrors": [],
                "writeConcernErrors": [],
            },
            result.bulk_api_result,
        )

    def test_single_error_unordered_batch(self):
        self.coll.create_index("a", unique=True)
        self.addCleanup(self.coll.drop_index, [("a", 1)])
        requests: list = [
            InsertOne({"b": 1, "a": 1}),
            UpdateOne({"b": 2}, {"$set": {"a": 1}}, upsert=True),
            InsertOne({"b": 3, "a": 2}),
        ]

        try:
            self.coll.bulk_write(requests, ordered=False)
        except BulkWriteError as exc:
            result = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")

        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 0,
                "nInserted": 2,
                "nRemoved": 0,
                "upserted": [],
                "writeConcernErrors": [],
                "writeErrors": [
                    {
                        "index": 1,
                        "code": 11000,
                        "errmsg": "...",
                        "op": {
                            "q": {"b": 2},
                            "u": {"$set": {"a": 1}},
                            "multi": False,
                            "upsert": True,
                        },
                    }
                ],
            },
            result,
        )

    def test_multiple_error_unordered_batch(self):
        self.coll.create_index("a", unique=True)
        self.addCleanup(self.coll.drop_index, [("a", 1)])
        requests: list = [
            InsertOne({"b": 1, "a": 1}),
            UpdateOne({"b": 2}, {"$set": {"a": 3}}, upsert=True),
            UpdateOne({"b": 3}, {"$set": {"a": 4}}, upsert=True),
            UpdateOne({"b": 4}, {"$set": {"a": 3}}, upsert=True),
            InsertOne({"b": 5, "a": 2}),
            InsertOne({"b": 6, "a": 1}),
        ]

        try:
            self.coll.bulk_write(requests, ordered=False)
        except BulkWriteError as exc:
            result = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")
        # Assume the update at index 1 runs before the update at index 3,
        # although the spec does not require it. Same for inserts.
        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 2,
                "nInserted": 2,
                "nRemoved": 0,
                "upserted": [{"index": 1, "_id": "..."}, {"index": 2, "_id": "..."}],
                "writeConcernErrors": [],
                "writeErrors": [
                    {
                        "index": 3,
                        "code": 11000,
                        "errmsg": "...",
                        "op": {
                            "q": {"b": 4},
                            "u": {"$set": {"a": 3}},
                            "multi": False,
                            "upsert": True,
                        },
                    },
                    {
                        "index": 5,
                        "code": 11000,
                        "errmsg": "...",
                        "op": {"_id": "...", "b": 6, "a": 1},
                    },
                ],
            },
            result,
        )

    def test_large_inserts_ordered(self):
        big = "x" * client_context.max_bson_size
        requests = [
            InsertOne({"b": 1, "a": 1}),
            InsertOne({"big": big}),
            InsertOne({"b": 2, "a": 2}),
        ]

        try:
            self.coll.bulk_write(requests)
        except BulkWriteError as exc:
            result = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")

        self.assertEqual(1, result["nInserted"])

        self.coll.delete_many({})

        big = "x" * (1024 * 1024 * 4)
        write_result = self.coll.bulk_write(
            [
                InsertOne({"a": 1, "big": big}),
                InsertOne({"a": 2, "big": big}),
                InsertOne({"a": 3, "big": big}),
                InsertOne({"a": 4, "big": big}),
                InsertOne({"a": 5, "big": big}),
                InsertOne({"a": 6, "big": big}),
            ]
        )

        self.assertEqual(6, write_result.inserted_count)
        self.assertEqual(6, self.coll.count_documents({}))

    def test_large_inserts_unordered(self):
        big = "x" * client_context.max_bson_size
        requests = [
            InsertOne({"b": 1, "a": 1}),
            InsertOne({"big": big}),
            InsertOne({"b": 2, "a": 2}),
        ]

        try:
            self.coll.bulk_write(requests, ordered=False)
        except BulkWriteError as exc:
            details = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")

        self.assertEqual(2, details["nInserted"])

        self.coll.delete_many({})

        big = "x" * (1024 * 1024 * 4)
        result = self.coll.bulk_write(
            [
                InsertOne({"a": 1, "big": big}),
                InsertOne({"a": 2, "big": big}),
                InsertOne({"a": 3, "big": big}),
                InsertOne({"a": 4, "big": big}),
                InsertOne({"a": 5, "big": big}),
                InsertOne({"a": 6, "big": big}),
            ],
            ordered=False,
        )

        self.assertEqual(6, result.inserted_count)
        self.assertEqual(6, self.coll.count_documents({}))

class BulkAuthorizationTestBase(BulkTestBase):
    @classmethod
    @client_context.require_auth
    @client_context.require_no_api_version
    def setUpClass(cls):
        super(BulkAuthorizationTestBase, cls).setUpClass()

    def setUp(self):
        super(BulkAuthorizationTestBase, self).setUp()
        client_context.create_user(self.db.name, "readonly", "pw", ["read"])
        self.db.command(
            "createRole",
            "noremove",
            privileges=[
                {
                    "actions": ["insert", "update", "find"],
                    "resource": {"db": "pymongo_test", "collection": "test"},
                }
            ],
            roles=[],
        )

        client_context.create_user(self.db.name, "noremove", "pw", ["noremove"])

    def tearDown(self):
        self.db.command("dropRole", "noremove")
        remove_all_users(self.db)

class TestBulkUnacknowledged(BulkTestBase):
    def tearDown(self):
        self.coll.delete_many({})

    def test_no_results_ordered_success(self):
        requests: list = [
            InsertOne({"a": 1}),
            UpdateOne({"a": 3}, {"$set": {"b": 1}}, upsert=True),
            InsertOne({"a": 2}),
            DeleteOne({"a": 1}),
        ]
        result = self.coll_w0.bulk_write(requests)
        self.assertFalse(result.acknowledged)
        wait_until(lambda: 2 == self.coll.count_documents({}), "insert 2 documents")
        wait_until(lambda: self.coll.find_one({"_id": 1}) is None, 'removed {"_id": 1}')

    def test_no_results_ordered_failure(self):
        requests: list = [
            InsertOne({"_id": 1}),
            UpdateOne({"_id": 3}, {"$set": {"b": 1}}, upsert=True),
            InsertOne({"_id": 2}),
            # Fails with duplicate key error.
            InsertOne({"_id": 1}),
            # Should not be executed since the batch is ordered.
            DeleteOne({"_id": 1}),
        ]
        result = self.coll_w0.bulk_write(requests)
        self.assertFalse(result.acknowledged)
        wait_until(lambda: 3 == self.coll.count_documents({}), "insert 3 documents")
        self.assertEqual({"_id": 1}, self.coll.find_one({"_id": 1}))

    def test_no_results_unordered_success(self):
        requests: list = [
            InsertOne({"a": 1}),
            UpdateOne({"a": 3}, {"$set": {"b": 1}}, upsert=True),
            InsertOne({"a": 2}),
            DeleteOne({"a": 1}),
        ]
        result = self.coll_w0.bulk_write(requests, ordered=False)
        self.assertFalse(result.acknowledged)
        wait_until(lambda: 2 == self.coll.count_documents({}), "insert 2 documents")
        wait_until(lambda: self.coll.find_one({"_id": 1}) is None, 'removed {"_id": 1}')

    def test_no_results_unordered_failure(self):
        requests: list = [
            InsertOne({"_id": 1}),
            UpdateOne({"_id": 3}, {"$set": {"b": 1}}, upsert=True),
            InsertOne({"_id": 2}),
            # Fails with duplicate key error.
            InsertOne({"_id": 1}),
            # Should be executed since the batch is unordered.
            DeleteOne({"_id": 1}),
        ]
        result = self.coll_w0.bulk_write(requests, ordered=False)
        self.assertFalse(result.acknowledged)
        wait_until(lambda: 2 == self.coll.count_documents({}), "insert 2 documents")
        wait_until(lambda: self.coll.find_one({"_id": 1}) is None, 'removed {"_id": 1}')

class TestBulkAuthorization(BulkAuthorizationTestBase):
    def test_readonly(self):
        # We test that an authorization failure aborts the batch and is raised
        # as OperationFailure.
        cli = rs_or_single_client_noauth(
            username="readonly", password="pw", authSource="pymongo_test"
        )
        coll = cli.pymongo_test.test
        coll.find_one()
        self.assertRaises(OperationFailure, coll.bulk_write, [InsertOne({"x": 1})])

    def test_no_remove(self):
        # We test that an authorization failure aborts the batch and is raised
        # as OperationFailure.
        cli = rs_or_single_client_noauth(
            username="noremove", password="pw", authSource="pymongo_test"
        )
        coll = cli.pymongo_test.test
        coll.find_one()
        requests = [
            InsertOne({"x": 1}),
            ReplaceOne({"x": 2}, {"x": 2}, upsert=True),
            DeleteMany({}),  # Prohibited.
            InsertOne({"x": 3}),  # Never attempted.
        ]
        self.assertRaises(OperationFailure, coll.bulk_write, requests)
        self.assertEqual(set([1, 2]), set(self.coll.distinct("x")))

class TestBulkWriteConcern(BulkTestBase):
    w: Optional[int]
    secondary: MongoClient

    @classmethod
    def setUpClass(cls):
        super(TestBulkWriteConcern, cls).setUpClass()
        cls.w = client_context.w
        cls.secondary = None
        if cls.w is not None and cls.w > 1:
            for member in client_context.hello["hosts"]:
                if member != client_context.hello["primary"]:
                    cls.secondary = single_client(*partition_node(member))
                    break

    @classmethod
    def tearDownClass(cls):
        if cls.secondary:
            cls.secondary.close()

    def cause_wtimeout(self, requests, ordered):
        if not client_context.test_commands_enabled:
            self.skipTest("Test commands must be enabled.")

        # Use the rsSyncApplyStop failpoint to pause replication on a
        # secondary which will cause a wtimeout error.
        self.secondary.admin.command("configureFailPoint", "rsSyncApplyStop", mode="alwaysOn")

        try:
            coll = self.coll.with_options(write_concern=WriteConcern(w=self.w, wtimeout=1))
            return coll.bulk_write(requests, ordered=ordered)
        finally:
            self.secondary.admin.command("configureFailPoint", "rsSyncApplyStop", mode="off")

    @client_context.require_replica_set
    @client_context.require_secondaries_count(1)
    def test_write_concern_failure_ordered(self):
        # Ensure we don't raise on wnote.
        coll_ww = self.coll.with_options(write_concern=WriteConcern(w=self.w))
        result = coll_ww.bulk_write([DeleteOne({"something": "that does no exist"})])
        self.assertTrue(result.acknowledged)

        requests = [InsertOne({"a": 1}), InsertOne({"a": 2})]
        # Replication wtimeout is a 'soft' error.
        # It shouldn't stop batch processing.
        try:
            self.cause_wtimeout(requests, ordered=True)
        except BulkWriteError as exc:
            details = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")

        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 0,
                "nInserted": 2,
                "nRemoved": 0,
                "upserted": [],
                "writeErrors": [],
            },
            details,
        )

        # When talking to legacy servers there will be a
        # write concern error for each operation.
        self.assertTrue(len(details["writeConcernErrors"]) > 0)

        failed = details["writeConcernErrors"][0]
        self.assertEqual(64, failed["code"])
        self.assertTrue(isinstance(failed["errmsg"], str))

        self.coll.delete_many({})
        self.coll.create_index("a", unique=True)
        self.addCleanup(self.coll.drop_index, [("a", 1)])

        # Fail due to write concern support as well
        # as duplicate key error on ordered batch.
        requests = [
            InsertOne({"a": 1}),
            ReplaceOne({"a": 3}, {"b": 1}, upsert=True),
            InsertOne({"a": 1}),
            InsertOne({"a": 2}),
        ]
        try:
            self.cause_wtimeout(requests, ordered=True)
        except BulkWriteError as exc:
            details = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")

        self.assertEqualResponse(
            {
                "nMatched": 0,
                "nModified": 0,
                "nUpserted": 1,
                "nInserted": 1,
                "nRemoved": 0,
                "upserted": [{"index": 1, "_id": "..."}],
                "writeErrors": [
                    {"index": 2, "code": 11000, "errmsg": "...", "op": {"_id": "...", "a": 1}}
                ],
            },
            details,
        )

        self.assertTrue(len(details["writeConcernErrors"]) > 1)
        failed = details["writeErrors"][0]
        self.assertTrue("duplicate" in failed["errmsg"])

    @client_context.require_replica_set
    @client_context.require_secondaries_count(1)
    def test_write_concern_failure_unordered(self):
        # Ensure we don't raise on wnote.
        coll_ww = self.coll.with_options(write_concern=WriteConcern(w=self.w))
        result = coll_ww.bulk_write([DeleteOne({"something": "that does no exist"})], ordered=False)
        self.assertTrue(result.acknowledged)

        requests = [
            InsertOne({"a": 1}),
            UpdateOne({"a": 3}, {"$set": {"a": 3, "b": 1}}, upsert=True),
            InsertOne({"a": 2}),
        ]
        # Replication wtimeout is a 'soft' error.
        # It shouldn't stop batch processing.
        try:
            self.cause_wtimeout(requests, ordered=False)
        except BulkWriteError as exc:
            details = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")

        self.assertEqual(2, details["nInserted"])
        self.assertEqual(1, details["nUpserted"])
        self.assertEqual(0, len(details["writeErrors"]))
        # When talking to legacy servers there will be a
        # write concern error for each operation.
        self.assertTrue(len(details["writeConcernErrors"]) > 1)

        self.coll.delete_many({})
        self.coll.create_index("a", unique=True)
        self.addCleanup(self.coll.drop_index, [("a", 1)])

        # Fail due to write concern support as well
        # as duplicate key error on unordered batch.
        requests: list = [
            InsertOne({"a": 1}),
            UpdateOne({"a": 3}, {"$set": {"a": 3, "b": 1}}, upsert=True),
            InsertOne({"a": 1}),
            InsertOne({"a": 2}),
        ]
        try:
            self.cause_wtimeout(requests, ordered=False)
        except BulkWriteError as exc:
            details = exc.details
            self.assertEqual(exc.code, 65)
        else:
            self.fail("Error not raised")

        self.assertEqual(2, details["nInserted"])
        self.assertEqual(1, details["nUpserted"])
        self.assertEqual(1, len(details["writeErrors"]))
        # When talking to legacy servers there will be a
        # write concern error for each operation.
        self.assertTrue(len(details["writeConcernErrors"]) > 1)

        failed = details["writeErrors"][0]
        self.assertEqual(2, failed["index"])
        self.assertEqual(11000, failed["code"])
        self.assertTrue(isinstance(failed["errmsg"], str))
        self.assertEqual(1, failed["op"]["a"])

        failed = details["writeConcernErrors"][0]
        self.assertEqual(64, failed["code"])
        self.assertTrue(isinstance(failed["errmsg"], str))

        upserts = details["upserted"]
        self.assertEqual(1, len(upserts))
        self.assertEqual(1, upserts[0]["index"])
        self.assertTrue(upserts[0].get("_id"))

if __name__ == "__main__":
    unittest.main()


text:
package io.searchbox.core.search.aggregation;

import com.google.gson.JsonObject;

public class ChildrenAggregation extends MetricAggregation {

	protected String name;
	protected JsonObject jsonRoot;
	public static final String TYPE = "child";

	public ChildrenAggregation(String name, JsonObject childrenAggregation) {

		super(name, childrenAggregation);
	}
}


text:
package org.apache.causeway.testing.fakedata.applib.services;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.causeway.applib.value.Blob;
import org.apache.causeway.commons.internal.base._Bytes;
import org.apache.causeway.commons.internal.resources._Resources;

/**
 * Returns random {@link Blob} values, optionally constrained to either PDFs or JPGs.
 *
 * @since 2.0 {@index}
 */
public class CausewayBlobs extends AbstractRandomValueGenerator {

    public CausewayBlobs(final FakeDataService fakeDataService) {
        super(fakeDataService);
    }

    private static final List<String> fileNames = Arrays.asList(
            "image01-150x150.jpg",
            "image01-240x180.jpg",
            "image01-640x480.jpg",
            "image01-2048x1536.jpg",
            "image01-4000x3000.jpg",
            "image02-150x150.jpg",
            "image02-240x180.jpg",
            "image02-640x480.jpg",
            "image02-2048x1536.jpg",
            "image02-4000x3000.jpg",
            "Pawson-Naked-Objects-thesis.pdf",
            "rick-mugridge-paper.pdf");

    public Blob any() {
        final List<String> fileNames = CausewayBlobs.fileNames;
        return asBlob(fileNames);
    }

    public Blob anyJpg() {
        return asBlob(fileNamesEndingWith(".jpg"));
    }

    public Blob anyPdf() {
        return asBlob(fileNamesEndingWith(".pdf"));
    }

    private Blob asBlob(final List<String> fileNames) {
        final int randomIdx = fake.ints().upTo(fileNames.size());
        final String randomFileName = fileNames.get(randomIdx);
        return asBlob(randomFileName);
    }

    private static List<String> fileNamesEndingWith(final String suffix) {
        return CausewayBlobs.fileNames.stream()
                .filter(input -> input.endsWith(suffix))
                .collect(Collectors.toList());
    }

    private static Blob asBlob(final String fileName) {
        try(var is = _Resources.load(CausewayBlobs.class, "blobs/" + fileName)){
            return new Blob(fileName, mimeTypeFor(fileName), _Bytes.of(is));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static String mimeTypeFor(final String fileName) {
        if(fileName.endsWith("jpg")) {
            return "image/jpeg";
        }
        return "application/pdf";
    }

}


text:
Once inside the cart, you can select an available pipeline from the pipelines grid:

![select-a-pipeline-view.png][]

[select-a-pipeline.png]: {{ site.baseurl }}/images/tutorials/common/pipelines/select-a-pipeline.png
[select-a-pipeline-view.png]: {{ site.baseurl }}/images/tutorials/common/pipelines/select-a-pipeline-view.png


text:
from django.db import models

from .mixins import AtomicVersionMixin, CleanSaveMixin

class AsylumModel(AtomicVersionMixin, CleanSaveMixin, models.Model):
    """Baseclass for models in all Asylum apps, all the common mixins etc should be added here"""

    class Meta:
        abstract = True


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _02.Magic_Words
{
    class Program
    {
        static void Main(string[] args)
        {
            int n, newIndex,
                maxLength = 0;

            List<string> words = new List<string>();
            StringBuilder result;

            n = int.Parse(Console.ReadLine());
            for (int i = 0; i < n; i++)
            {
                words.Add(Console.ReadLine());
            }

            // Reorder
            for (int i = 0; i < n; i++)
            {
                var word = words[i];
                newIndex = word.Length % (n + 1);

                words[i] = null;
                words.Insert(newIndex, word);
                words.Remove(null);

                //if (newIndex < i)
                //    words.RemoveAt(i + 1);
                //else
                //    words.RemoveAt(i);
            }

            // Print
            result = new StringBuilder();

            // foreach (var word in words)
            //     maxLength = Math.Max(maxLength, wr.Length);
            maxLength = words.Max(word => word.Length);

            for (int i = 0; i < maxLength; i++)
            {
                foreach (var word in words)
                {
                    if (word.Length > i)
                        result.Append(word[i]);
                }
            }

            Console.WriteLine(result.ToString());
        }
    }
}


text:
module TreeNode
  class ConfigurationProfile < Node
    set_attribute(:text) { @object.name.split('|').first }
    set_attribute(:tooltip) { _("Configuration Profile: %{name}") % {:name => @object.name} }
  end
end


text:
import numpy as np
from .kern import Kern
from ...core.parameterization import Param
from ...core.parameterization.transformations import Logexp
class Poly(Kern):
    """
    Polynomial kernel
    """

    def __init__(self, input_dim, variance=1., order=3., active_dims=None, name='poly'):
        super(Poly, self).__init__(input_dim, active_dims, name)
        self.variance = Param('variance', variance, Logexp())
        self.link_parameter(self.variance)
        self.order=order

    def K(self, X, X2=None):
        return (self._dot_product(X, X2) + 1.)**self.order * self.variance

    def _dot_product(self, X, X2=None):
        if X2 is None:
            return np.dot(X, X.T)
        else:
            return np.dot(X, X2.T)

    def Kdiag(self, X):
        return self.variance*(np.square(X).sum(1) + 1.)**self.order

    def update_gradients_full(self, dL_dK, X, X2=None):
        self.variance.gradient = np.sum(dL_dK * (self._dot_product(X, X2) + 1.)**self.order)

    def update_gradients_diag(self, dL_dKdiag, X):
        raise NotImplementedError

    def gradients_X(self, dL_dK, X, X2=None):
        raise NotImplementedError

    def gradients_X_diag(self, dL_dKdiag, X):
        raise NotImplementedError


text:
package org.rapidoid.config;

import org.rapidoid.RapidoidThing;
import org.rapidoid.annotation.Authors;
import org.rapidoid.annotation.Since;
import org.rapidoid.u.U;

import java.util.List;
import java.util.Set;

@Authors("Nikolche Mihajlovski")
@Since("5.0.2")
public class ConfigOptions extends RapidoidThing {

    public static final Set<String> SERVICE_NAMES = U.set();

    public static final List<ConfigOption> ALL = configOptions();

    public static final List<ConfigOption> COMMANDS = commandOptions();

    private static List<ConfigOption> configOptions() {
        List<ConfigOption> opts = U.list();

        opts.add(opt("config", "configuration filename prefix", "config"));

        opts.add(opt("dev", "run in DEV mode", "auto-detected"));
        opts.add(opt("production", "run in PRODUCTION mode", "auto-detected"));
        opts.add(opt("test", "run in TEST mode", "auto-detected"));

        opts.add(opt("secret=<SECRET>", "configure secret key for cryptography", "random"));
        opts.add(opt("profiles=<P1,P2...>", "comma-separated list of application profiles (e.g. mysql,prod)", "the 'default' profile"));

        opts.add(opt("on.port=<P>", "the default App server will listen at port P", 8888));
        opts.add(opt("on.address=<ADDR>", "the default App server will listen at address ADDR", "0.0.0.0"));

        opts.add(opt("admin.port=<P>", "the Admin server will listen at port P", "same as on.port"));
        opts.add(opt("admin.address=<ADDR>", "the Admin server will listen at address ADDR", "on.address"));

        return opts;
    }

    private static List<ConfigOption> commandOptions() {
        List<ConfigOption> opts = U.list();

        opts.add(cmd("dev", "CLI shortcut for convenient local development setup"));
        opts.add(cmd("installer", "Print installation script for Rapidoid"));
        opts.add(cmd("password", "Generate salted password hash"));
        opts.add(cmd("help", "Show help"));

        return opts;
    }

    private static ConfigOption opt(String name, String desc, Object def) {
        return new ConfigOption(name, desc, def);
    }

    private static ConfigOption srvOpt(String name, String desc) {
        SERVICE_NAMES.add(name);
        return new ConfigOption(name, desc, null);
    }

    private static ConfigOption cmd(String name, String desc) {
        return new ConfigOption(name, desc, null);
    }

}


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Autosuggest from 'react-autosuggest';
import {
  InstantSearch,
  Configure,
  Index,
  Highlight,
  connectAutoComplete,
} from 'react-instantsearch-dom';
import algoliasearch from 'algoliasearch/lite';

const searchClient = algoliasearch(
  'latency',
  '6be0576ff61c053d5f9a3225e2a90f76'
);

const App = () => (
  <InstantSearch searchClient={searchClient} indexName="instant_search">
    <AutoComplete />
    <Configure hitsPerPage={1} />
    <Index indexName="bestbuy" />
    <Index indexName="airbnb" />
  </InstantSearch>
);

class Example extends Component {
  static propTypes = {
    hits: PropTypes.arrayOf(PropTypes.object).isRequired,
    currentRefinement: PropTypes.string.isRequired,
    refine: PropTypes.func.isRequired,
  };

  state = {
    value: this.props.currentRefinement,
  };

  onChange = (event, { newValue }) => {
    this.setState({
      value: newValue,
    });
  };

  onSuggestionsFetchRequested = ({ value }) => {
    this.props.refine(value);
  };

  onSuggestionsClearRequested = () => {
    this.props.refine();
  };

  getSuggestionValue(hit) {
    return hit.name;
  }

  renderSuggestion(hit) {
    return <Highlight attribute="name" hit={hit} tagName="mark" />;
  }

  renderSectionTitle(section) {
    return section.index;
  }

  getSectionSuggestions(section) {
    return section.hits;
  }

  render() {
    const { hits } = this.props;
    const { value } = this.state;

    const inputProps = {
      placeholder: 'Search for a product...',
      onChange: this.onChange,
      value,
    };

    return (
      <Autosuggest
        suggestions={hits}
        multiSection={true}
        onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
        onSuggestionsClearRequested={this.onSuggestionsClearRequested}
        getSuggestionValue={this.getSuggestionValue}
        renderSuggestion={this.renderSuggestion}
        inputProps={inputProps}
        renderSectionTitle={this.renderSectionTitle}
        getSectionSuggestions={this.getSectionSuggestions}
      />
    );
  }
}

const AutoComplete = connectAutoComplete(Example);

export default App;