text:
const mockDevice = {
  moveRelative: jest.fn(() => { return Promise.resolve(); }),
};

jest.mock("../../../device", () => ({
  getDevice: () => (mockDevice)
}));

import * as React from "react";
import { mount } from "enzyme";
import {
  DirectionButton, directionDisabled, calculateDistance,
} from "../direction_button";
import { DirectionButtonProps } from "../interfaces";

function fakeButtonProps(): DirectionButtonProps {
  return {
    axis: "y",
    direction: "up",
    directionAxisProps: {
      isInverted: false,
      stopAtHome: false,
      stopAtMax: false,
      axisLength: 0,
      negativeOnly: false,
      position: undefined
    },
    steps: 1000,
    disabled: false
  };
}

describe("<DirectionButton/>", function () {
  const buttonProps = fakeButtonProps();

  beforeEach(function () {
    buttonProps.disabled = false;
  });

  it("calls move command", () => {
    const btn = mount(<DirectionButton {...buttonProps} />);
    btn.simulate("click");
    expect(mockDevice.moveRelative).toHaveBeenCalledTimes(1);
  });

  it("is disabled", () => {
    buttonProps.disabled = true;
    const btn = mount(<DirectionButton {...buttonProps} />);
    btn.simulate("click");
    expect(mockDevice.moveRelative).not.toHaveBeenCalled();
  });

  it("call has correct args", () => {
    const btn = mount(<DirectionButton {...buttonProps} />);
    btn.simulate("click");
    expect(mockDevice.moveRelative)
      .toHaveBeenCalledWith({ x: 0, y: 1000, z: 0 });
  });
});

describe("calculateDistance()", () => {
  it("normal", () => {
    const p = fakeButtonProps();
    p.steps = 100;
    p.direction = "up";
    p.directionAxisProps.isInverted = false;
    expect(calculateDistance(p)).toEqual(100);
  });

  it("inverted", () => {
    const p = fakeButtonProps();
    p.steps = 100;
    p.direction = "up";
    p.directionAxisProps.isInverted = true;
    expect(calculateDistance(p)).toEqual(-100);
  });

  it("opposite direction", () => {
    const p = fakeButtonProps();
    p.steps = 100;
    p.direction = "down";
    p.directionAxisProps.isInverted = false;
    expect(calculateDistance(p)).toEqual(-100);
  });

  it("opposite direction and inverted", () => {
    const p = fakeButtonProps();
    p.steps = 100;
    p.direction = "down";
    p.directionAxisProps.isInverted = true;
    expect(calculateDistance(p)).toEqual(100);
  });
});

describe("directionDisabled()", () => {
  it("disabled at max", () => {
    const p = fakeButtonProps();
    p.direction = "up";
    p.steps = 100;
    p.directionAxisProps = {
      position: 10,
      isInverted: false,
      stopAtHome: true,
      stopAtMax: true,
      axisLength: 10,
      negativeOnly: false
    };
    expect(directionDisabled(p)).toBeTruthy();
  });

  it("not disabled at max", () => {
    const p = fakeButtonProps();
    p.direction = "up";
    p.steps = 100;
    p.directionAxisProps = {
      position: 10,
      isInverted: false,
      stopAtHome: false,
      stopAtMax: false,
      axisLength: 10,
      negativeOnly: false
    };
    expect(directionDisabled(p)).toBeFalsy();
  });

  it("disabled at min: positive", () => {
    const p = fakeButtonProps();
    p.direction = "down";
    p.steps = 100;
    p.directionAxisProps = {
      position: 0,
      isInverted: false,
      stopAtHome: true,
      stopAtMax: true,
      axisLength: 10,
      negativeOnly: false
    };
    expect(directionDisabled(p)).toBeTruthy();
  });

  it("disabled at min: negative", () => {
    const p = fakeButtonProps();
    p.direction = "up";
    p.steps = 100;
    p.directionAxisProps = {
      position: 0,
      isInverted: false,
      stopAtHome: true,
      stopAtMax: true,
      axisLength: 10,
      negativeOnly: true
    };
    expect(directionDisabled(p)).toBeTruthy();
  });

  it("not disabled at min", () => {
    const p = fakeButtonProps();
    p.direction = "down";
    p.steps = 100;
    p.directionAxisProps = {
      position: 0,
      isInverted: false,
      stopAtHome: false,
      stopAtMax: false,
      axisLength: 0,
      negativeOnly: false
    };
    expect(directionDisabled(p)).toBeFalsy();
  });
});


text:
<!doctype html>
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE
The complete set of authors may be found at http://polymer.github.io/AUTHORS
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS
-->
<html>
<head>

  <script src="../webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="../iron-component-page/iron-component-page.html">
  <title>Firebase Elements</title>
</head>
<body>

  <iron-component-page src="firebase-collection.html"></iron-component-page>

</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
import { IOperationsService } from './operations.service.interface';
import { IAuthenticationService } from './authentication.service.interface';

export class OperationsService implements IOperationsService {
	$http : ng.IHttpService;
	authentication : IAuthenticationService;

	constructor($http: ng.IHttpService, authenticationService: IAuthenticationService) {
		this.$http = $http;
		this.authentication = authenticationService;
	}

	public getOperations( travelId : any ) {
		return this.$http.get(`/api/account/${travelId}/operations`,{
						  headers: { Authorization: 'Bearer '+ this.authentication.getToken() }
						  })
			.then( response => response.data['operations'] )
			.catch( error => console.log("Erreur getOperations" + error.data) );
	}

	public addOperation(operation : any ) {
		this.cleanForDB(operation);
		return this.$http.post(`/api/operations`, operation,{
						  headers: { Authorization: 'Bearer '+ this.authentication.getToken() }
						  })
			.then( response => response.data )
			.catch( error => console.log("Erreur addOperation" + error.data) );
	}

	public deleteOperation(id: any) {
		return this.$http.delete(`/api/operations/${id}`,{
						  headers: { Authorization: 'Bearer '+ this.authentication.getToken() }
						  })
			.then( response => response.data )
			.catch( error => console.log("Erreur deleteOperation" + error.data) );
	}

	public updateOperation(operation : any ) {
		this.cleanForDB(operation);
		return this.$http.put(`/api/operations`, operation,{
						  headers: { Authorization: 'Bearer '+ this.authentication.getToken() }
						  })
			.then( response => response.data )
			.catch( error => console.log("Erreur updateOperation" + error.data) );
	}

	public updateAccount(account : any ) {
		return this.$http.put(`/api/accounts/${account._id}`, account,{
						  headers: { Authorization: 'Bearer '+ this.authentication.getToken() }
						  })
			.then( response => response.data )
			.catch( error => console.log("Erreur updateAccount" + error.data) );
	}

	private cleanForDB(operation) {
		operation.accountCredit = operation.accountCredit.code;
		operation.accountDebit = operation.accountDebit.code;
		operation.deviseDebit = operation.deviseDebit.code;
		if(operation.deviseCredit) {
			operation.deviseCredit = operation.deviseCredit.code;
		} else {
			operation.deviseCredit = operation.deviseDebit;
		}
	}
}


text:
package org.uberfire.ext.wires.bpmn.backend.todo;

import org.jboss.errai.config.rebind.EnvUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * When Bpmn moves to KIE-WB this class can be removed.
 */
public class ExceptionUtilities {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionUtilities.class);

    /**
     * Helper to return a @Portable RuntimeException.
     * @param e
     * @return
     */
    public static RuntimeException handleException(final Exception e) {
        logger.debug("Exception thrown: " + e.getMessage(),
                     e);
        if (EnvUtil.isPortableType(e.getClass())) {
            if (e instanceof RuntimeException) {
                return (RuntimeException) e;
            } else {
                return new GenericPortableException(e.getMessage(),
                                                    e);
            }
        }
        return new GenericPortableException(e.getMessage(),
                                            e);
    }
}


text:
package org.knopflerfish.bundle.consoletelnet;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;

import org.knopflerfish.service.log.LogRef;

/**
 * The telnet console server listens to a port for connections and upon accept,
 * creates a telnet session to handle that connection.
 */
public class TelnetServer
  implements BundleActivator, Runnable, ManagedService {

  private static BundleContext bc;
  private static LogRef log = null;
  private static TelnetConfig telnetConfig = null;
  private static ServiceRegistration<ManagedService> configServReg = null;
  private static Thread telnetServerThread;
  private static Hashtable<TelnetSession, Thread> telnetSessions = null;
  private boolean accept = true; // control of main loop running
  private boolean updated = true; // control of main loop server update
  private boolean first = true; // first time server start

  public TelnetServer()
  {

  }

  // BundleActivator methods implementation
  @Override
  public void start(BundleContext bc)
  {
    TelnetServer.bc = bc;

    log = new LogRef(bc, true);

    telnetSessions = new Hashtable<>();

    final Dictionary<String, String> conf = new Hashtable<>();
    try {
      telnetConfig = new TelnetConfig(bc);
      conf.put(Constants.SERVICE_PID, getClass().getName());

      configServReg =
        bc.registerService(ManagedService.class, this, conf);
    } catch (final ConfigurationException cexp) {
      log.error("Consoletelnet configuration error " + cexp.toString());
    }

    telnetServerThread = new Thread(this, "ConsoleTelnetServer");
    telnetServerThread.setDaemon(true);
    telnetServerThread.start();
  }

  @Override
  public void stop(BundleContext bc)
  {
    // Stop accepting new connections
    accept = false;
    telnetServerThread.interrupt();

    // Close all pending sessions

    final Enumeration<TelnetSession> e = telnetSessions.keys();
    while (e.hasMoreElements()) {
      TelnetSession telnetSession = e.nextElement();
      telnetSession.close();
    }

    configServReg.unregister();
    configServReg = null;

    log.close();
    log = null;
  }

  // Telnet server main loop, listen for connections and
  // also look for configuration updates.

  @Override
  public void run()
  {
    ServerSocket serverSocket = null;
    // int socketTimeout = 10000;
    // int backlog = 100;

    boolean bFailed = false;

    while (accept && !bFailed) {
      if (updated) {
        log.info("updating in server main loop");
        if (serverSocket != null) {
          try {
            serverSocket.close();
          } catch (final IOException e) {
            log.error("Server socket exception for "
                          + telnetConfig.getAddress() + ":"
                          + telnetConfig.getPort() + ": " + e, e);
            bFailed = true;
          }
        }
        try {
          serverSocket =
            new ServerSocket(telnetConfig.getPort(), telnetConfig.getBacklog(),
                             telnetConfig.getAddress());

          log.info("Listening on " + telnetConfig.getAddress() + ":"
                   + telnetConfig.getPort());

          updated = false;
        } catch (final IOException iox) {
          log.error("Server socket exception for "
              + telnetConfig.getAddress() + ":"
              + telnetConfig.getPort() + ": " + iox, iox);
          updated = true;
          bFailed = true;
        }
      } else {
        try {
          serverSocket.setSoTimeout(telnetConfig.getSocketTimeout());
          final Socket socket = serverSocket.accept();

          final TelnetSession telnetSession =
            new TelnetSession(socket, telnetConfig, log, bc, this);
          final Thread telnetSessionThread =
            new Thread(telnetSession, "TelnetConsoleSession");
          telnetSessions.put(telnetSession, telnetSessionThread);
          telnetSessionThread.setDaemon(false);
          telnetSessionThread.start();
        } catch (final InterruptedIOException e) { // Timeout
          // iox.printStackTrace();
        } catch (final IOException e) {
          // iox.printStackTrace();
          log.error("Server exception", e);
        }
      }
    } // end while (accept)

    // Accept no connections, shut down server socket

    if (serverSocket != null) {
      try {
        serverSocket.close();
      } catch (final IOException e) {
        log.error("Server socket exception for " + telnetConfig.getAddress()
                  + ":" + telnetConfig.getPort() + ": " + e, e);
      }
    }
  } // end run

  public void removeSession(TelnetSession tels)
  {
    telnetSessions.remove(tels);
  }

  public TelnetConfig getTelnetConfig()
  {
    return telnetConfig;
  }

  @Override
  public void updated(Dictionary<String, ?> dict)
  {
    // Get port and host if present config
    // If they differ from the new configuration,
    // set semaphore updated = true
    // so that the main loop may detect the change and
    // close and reopen the server socket

    try {
      boolean portupdated;
      boolean hostupdated;

      final int oldport = telnetConfig.getPort();
      final InetAddress oldinet = telnetConfig.getAddress();

      telnetConfig.updated(dict);

      final int port = telnetConfig.getPort();
      final InetAddress inet = telnetConfig.getAddress();

      // port change check
      portupdated = oldport != port;

      // inet address change check
      if (oldinet == null && inet == null) {
        hostupdated = false;
      } else if (oldinet == null || inet == null) {
        hostupdated = true;
      } else {
        hostupdated = !oldinet.equals(inet);
      }

      // Set updated to true if we need to open a new server socket.
      updated = portupdated || hostupdated || first;
      first = false;

      log.info("New config: " + (portupdated ? "port changed " : "")
               + (hostupdated ? "host changed " : "")
               + (updated ? "new server socket needed." : ""));
    } catch (final Exception ex) {
      log.error("Consoltelnet config exception " + ex, ex);
    }
  }
} // TelnetServer


text:
//[-------------------------------------------------------]
//[ Includes                                              ]
//[-------------------------------------------------------]
#include "Renderer/Public/Resource/Skeleton/SkeletonResource.h"

// Disable warnings in external headers, we can't fix them
PRAGMA_WARNING_PUSH
	PRAGMA_WARNING_DISABLE_MSVC(4127)	// warning C4127: conditional expression is constant
	PRAGMA_WARNING_DISABLE_MSVC(4201)	// warning C4201: nonstandard extension used: nameless struct/union
	PRAGMA_WARNING_DISABLE_MSVC(4464)	// warning C4464: relative include path contains '..'
	PRAGMA_WARNING_DISABLE_MSVC(5214)	// warning C5214: applying '*=' to an operand with a volatile qualified type is deprecated in C++20 (compiling source file E:\private\unrimp\Source\RendererToolkit\Private\AssetCompiler\TextureAssetCompiler.cpp)
	#include <glm/glm.hpp>
	#include <glm/gtx/dual_quaternion.hpp>
PRAGMA_WARNING_POP

//[-------------------------------------------------------]
//[ Namespace                                             ]
//[-------------------------------------------------------]
namespace Renderer
{

	//[-------------------------------------------------------]
	//[ Public methods                                        ]
	//[-------------------------------------------------------]
	uint32_t SkeletonResource::getBoneIndexByBoneId(uint32_t boneId) const
	{
		// TODO(co) Maybe it makes sense to store the bone IDs in some order to speed up the following
		for (uint8_t boneIndex = 0; boneIndex < mNumberOfBones; ++boneIndex)
		{
			if (mBoneIds[boneIndex] == boneId)
			{
				return boneIndex;
			}
		}
		return getInvalid<uint32_t>();
	}

	void SkeletonResource::localToGlobalPose()
	{
		// The root has no parent
		mGlobalBoneMatrices[0] = mLocalBoneMatrices[0];

		// Due to cache friendly depth-first rolled up bone hierarchy, the global parent bone pose is already up-to-date
		// TODO(co) Ensure that in the end SIMD intrinsics in GLM are used in here
		for (uint8_t i = 1; i < mNumberOfBones; ++i)
		{
			mGlobalBoneMatrices[i] = mGlobalBoneMatrices[mBoneParentIndices[i]] * mLocalBoneMatrices[i];
		}

		/*
		{ // Linear blend skinning (LBS) using matrices; there's no runtime switch by intent since dual quaternion skinning (DQS) is the way to go, don't remove this reference comment
			glm::mat3x4* boneSpaceMatrices = reinterpret_cast<glm::mat3x4*>(mBoneSpaceData);
			for (uint8_t i = 0; i < mNumberOfBones; ++i)
			{
				boneSpaceMatrices[i] = glm::transpose(mGlobalBoneMatrices[i] * mBoneOffsetMatrices[i]);
			}
		}
		*/

		{ // The dual quaternion skinning (DQS) implementation is basing on https://gamedev.stackexchange.com/questions/164423/help-with-dual-quaternion-skinning
			glm::dualquat* boneSpaceDualQuaternions = reinterpret_cast<glm::dualquat*>(mBoneSpaceData);
			for (uint8_t i = 0; i < mNumberOfBones; ++i)
			{
				const glm::mat4 boneSpaceMatrix = mGlobalBoneMatrices[i] * mBoneOffsetMatrices[i];
				const glm::quat rotationQuaternion = glm::quat_cast(boneSpaceMatrix);
				const glm::vec4& translation = boneSpaceMatrix[3];
				glm::dualquat& boneSpaceDualQuaternion = boneSpaceDualQuaternions[i];
				boneSpaceDualQuaternion[0] = rotationQuaternion;
				boneSpaceDualQuaternion[1] = glm::quat(0.0f, translation.x, translation.y, translation.z) * rotationQuaternion * 0.5f;
			}
		}
	}

//[-------------------------------------------------------]
//[ Namespace                                             ]
//[-------------------------------------------------------]
} // Renderer


text:
package com.toparchy.molecule.push.baidu.model;

import com.toparchy.molecule.push.baidu.core.annotation.JSonPath;

public class KeyValueForTopic {

	@JSonPath(path="key")
	private String timestamp;

	@JSonPath(path="value")
	private TopicStatUnit value = null;

	public void setKey (String key) {
		this.timestamp = key;
	}

	public void setValue (TopicStatUnit value) {
		this.value = value;
	}
	// get
	public String getKey () {
		return timestamp;
	}
	public TopicStatUnit getValue () {
		return value;
	}
}


text:
<?php

namespace Kunstmaan\AdminBundle\Tests\Helper\AdminPanel;

use Kunstmaan\AdminBundle\Helper\AdminPanel\AdminPanelAction;
use PHPUnit\Framework\TestCase;

/**
 * Class AdminPanelActionTest
 */
class AdminPanelActionTest extends TestCase
{
    public function testGetSetRole()
    {
        $object = new AdminPanelAction(['http://fbi.gov'], 'FBI', 'fa-user', 'some.twig');
        $this->assertEquals('http://fbi.gov', $object->getUrl()[0]);
        $this->assertEquals('FBI', $object->getLabel());
        $this->assertEquals('fa-user', $object->getIcon());
        $this->assertEquals('some.twig', $object->getTemplate());
    }
}