text:
import { expect } from 'chai';
import * as sinon from 'sinon';

import { makeFakeApp } from './testing-utils/make-fake-app';
import { makeFakeSWReg } from './testing-utils/make-fake-sw-reg';

import {
  manifestCheck,
  WindowController
} from '../src/controllers/window-controller';
import { base64ToArrayBuffer } from '../src/helpers/base64-to-array-buffer';
import { DEFAULT_PUBLIC_VAPID_KEY } from '../src/models/fcm-details';

import { describe } from './testing-utils/messaging-test-runner';

const VALID_VAPID_KEY =
  'BJzVfWqLoALJdgV20MYy6lrj0OfhmE16PI1qLIIYx2ZZL3FoQWJJL8L0rf7rS7tqd92j_3xN3fmejKK5Eb7yMYw';

describe('Firebase Messaging > *WindowController', () => {
  const sandbox = sinon.sandbox.create();
  const app = makeFakeApp({
    messagingSenderId: '12345'
  });

  const cleanup = () => {
    sandbox.restore();
  };

  beforeEach(() => {
    return cleanup();
  });

  after(() => {
    return cleanup();
  });

  describe('manifestCheck()', () => {
    it("should resolve when the tag isn't defined", () => {
      sandbox
        .stub(document, 'querySelector')
        .withArgs('link[rel="manifest"]')
        .returns(null);

      return manifestCheck();
    });

    it('should fetch the manifest if defined and resolve when no gcm_sender_id', () => {
      sandbox
        .stub(document, 'querySelector')
        .withArgs('link[rel="manifest"]')
        .returns({
          href: 'https://firebase.io/messaging/example'
        });

      sandbox
        .stub(window, 'fetch')
        .withArgs('https://firebase.io/messaging/example')
        .returns(
          Promise.resolve({
            json: () => {
              return {};
            }
          })
        );

      return manifestCheck();
    });

    it('should fetch the manifest if defined and resolve with expected gcm_sender_id', () => {
      sandbox
        .stub(document, 'querySelector')
        .withArgs('link[rel="manifest"]')
        .returns({
          href: 'https://firebase.io/messaging/example'
        });

      sandbox
        .stub(window, 'fetch')
        .withArgs('https://firebase.io/messaging/example')
        .returns(
          Promise.resolve({
            json: () => {
              return {
                gcm_sender_id: '103953800507'
              };
            }
          })
        );

      return manifestCheck();
    });

    it('should fetch the manifest if defined and reject when using wrong gcm_sender_id', () => {
      sandbox
        .stub(document, 'querySelector')
        .withArgs('link[rel="manifest"]')
        .returns({
          href: 'https://firebase.io/messaging/example'
        });

      sandbox
        .stub(window, 'fetch')
        .withArgs('https://firebase.io/messaging/example')
        .returns(
          Promise.resolve({
            json: () => {
              return {
                gcm_sender_id: 'incorrect-sender-id'
              };
            }
          })
        );

      return manifestCheck().then(
        () => {
          throw new Error('Expected error to be thrown.');
        },
        err => {
          expect(err.code).to.equal('messaging/incorrect-gcm-sender-id');
        }
      );
    });

    it('should fetch the manifest and resolve if the request fails', () => {
      sandbox
        .stub(document, 'querySelector')
        .withArgs('link[rel="manifest"]')
        .returns({
          href: 'https://firebase.io/messaging/example'
        });

      sandbox
        .stub(window, 'fetch')
        .withArgs('https://firebase.io/messaging/example')
        .returns(Promise.reject(new Error('Injected Failure.')));

      return manifestCheck();
    });
  });

  describe('requestPermission', () => {
    it('should resolve if the permission is already granted', () => {
      sandbox.stub(Notification as any, 'permission').value('granted');

      const controller = new WindowController(app);
      return controller.requestPermission();
    });

    it('should reject if the requestPermission() is denied', () => {
      sandbox.stub(Notification as any, 'permission').value('denied');
      sandbox
        .stub(Notification, 'requestPermission')
        .returns(Promise.resolve('denied'));

      const controller = new WindowController(app);
      return controller.requestPermission().then(
        () => {
          throw new Error('Expected an error.');
        },
        err => {
          expect(err.code).to.equal('messaging/permission-blocked');
        }
      );
    });

    it('should reject if the requestPermission() is default', () => {
      sandbox.stub(Notification as any, 'permission').value('default');
      sandbox
        .stub(Notification, 'requestPermission')
        .returns(Promise.resolve('default'));

      const controller = new WindowController(app);
      return controller.requestPermission().then(
        () => {
          throw new Error('Expected an error.');
        },
        err => {
          expect(err.code).to.equal('messaging/permission-default');
        }
      );
    });

    it('should resolve if the requestPermission() is granted', () => {
      sandbox.stub(Notification as any, 'permission').value('default');
      sandbox
        .stub(Notification, 'requestPermission')
        .returns(Promise.resolve('granted'));

      const controller = new WindowController(app);
      return controller.requestPermission();
    });
  });

  describe('useServiceWorker()', () => {
    it(`should throw on invalid input`, () => {
      const controller = new WindowController(app);
      let thrownError;
      try {
        controller.useServiceWorker(null as any);
      } catch (err) {
        thrownError = err;
      }
      expect(thrownError).to.exist;
      expect(thrownError.code).to.equal('messaging/sw-registration-expected');
    });

    it(`should only be callable once`, () => {
      const registration = makeFakeSWReg();
      const controller = new WindowController(app);
      controller.useServiceWorker(registration);

      let thrownError;
      try {
        controller.useServiceWorker(registration);
      } catch (err) {
        thrownError = err;
      }

      expect(thrownError).to.exist;
      expect(thrownError.code).to.equal('messaging/use-sw-before-get-token');
    });
  });

  describe('onMessage()', () => {
    it(`should call through to private function`, () => {
      const nextFunc = () => {};
      const errFunc = () => {};
      const compFunc = () => {};

      const controller = new WindowController(app);
      const onMessageStub = sandbox.stub(controller as any, 'onMessage');
      controller.onMessage(nextFunc, errFunc, compFunc);

      expect(onMessageStub.callCount).to.equal(1);
      expect(onMessageStub.args[0][0]).to.equal(nextFunc);
      expect(onMessageStub.args[0][1]).to.equal(errFunc);
      expect(onMessageStub.args[0][2]).to.equal(compFunc);
    });
  });

  describe('onTokenRefresh()', () => {
    it(`should call through to private function`, () => {
      const nextFunc = () => {};
      const errFunc = () => {};
      const compFunc = () => {};

      const controller = new WindowController(app);
      const onTokenRefreshStub = sandbox.stub(
        controller as any,
        'onTokenRefresh'
      );
      controller.onTokenRefresh(nextFunc, errFunc, compFunc);

      expect(onTokenRefreshStub.callCount).to.equal(1);
      expect(onTokenRefreshStub.args[0][0]).to.equal(nextFunc);
      expect(onTokenRefreshStub.args[0][1]).to.equal(errFunc);
      expect(onTokenRefreshStub.args[0][2]).to.equal(compFunc);
    });
  });

  describe('usePublicVapidKey()', () => {
    it('should throw an error when passing in an invalid value', () => {
      const controller = new WindowController(app);

      let thrownError;
      try {
        controller.usePublicVapidKey({} as any);
      } catch (err) {
        thrownError = err;
      }
      expect(thrownError).to.exist;
      expect(thrownError.code).to.equal('messaging/invalid-public-vapid-key');
    });

    it('should throw an error when called twice', () => {
      const controller = new WindowController(app);
      controller.usePublicVapidKey(VALID_VAPID_KEY);

      let thrownError;
      try {
        controller.usePublicVapidKey(VALID_VAPID_KEY);
      } catch (err) {
        thrownError = err;
      }
      expect(thrownError).to.exist;
      expect(thrownError.code).to.equal(
        'messaging/use-public-key-before-get-token'
      );
    });

    it('should throw when decrypting to invalid value', () => {
      const controller = new WindowController(app);

      let thrownError;
      try {
        controller.usePublicVapidKey(
          VALID_VAPID_KEY.substring(0, VALID_VAPID_KEY.length - 1)
        );
      } catch (err) {
        thrownError = err;
      }
      expect(thrownError).to.exist;
      expect(thrownError.code).to.equal(
        'messaging/public-vapid-key-decryption-failed'
      );
    });
  });

  describe('getPublicVapidKey_()', () => {
    it('should return the default key by default', () => {
      const controller = new WindowController(app);
      return controller.getPublicVapidKey_().then(pubKey => {
        expect(pubKey).to.equal(DEFAULT_PUBLIC_VAPID_KEY);
      });
    });

    it('should return the custom key if set', () => {
      const controller = new WindowController(app);
      controller.usePublicVapidKey(VALID_VAPID_KEY);
      return controller.getPublicVapidKey_().then(pubKey => {
        expect(pubKey).deep.equal(base64ToArrayBuffer(VALID_VAPID_KEY));
      });
    });
  });

  describe('setupSWMessageListener_()', () => {
    it('should add listener when supported', () => {
      const spy = sandbox.spy();
      sandbox.stub(navigator, 'serviceWorker').value({
        addEventListener: spy
      });

      const controller = new WindowController(app);
      controller.setupSWMessageListener_();

      expect(spy.args[0][0]).to.equal('message');
    });

    it('should do nothing when non-fcm message is passed in', () => {
      const spy = sandbox.spy();
      const onMessageSpy = sandbox.spy();

      sandbox.stub(navigator, 'serviceWorker').value({
        addEventListener: spy
      });

      const controller = new WindowController(app);
      controller.onMessage(onMessageSpy, null as any, null as any);
      controller.setupSWMessageListener_();

      const callback = spy.args[0][1];
      // New message without data
      callback({});
      expect(onMessageSpy.callCount).to.equal(0);

      // Not FCM data
      callback({
        data: {}
      });
      expect(onMessageSpy.callCount).to.equal(0);

      // Even with FCM data, if the type isn't known - do nothing.
      callback({
        data: {
          'firebase-messaging-msg-type': 'unknown'
        }
      });
      expect(onMessageSpy.callCount).to.equal(0);
    });

    it('should not throw when message observer is not defined', () => {
      const messageCallbackSpy = sandbox.spy();
      sandbox.stub(navigator, 'serviceWorker').value({
        addEventListener: messageCallbackSpy
      });

      const controller = new WindowController(app);
      controller.setupSWMessageListener_();
      const callback = messageCallbackSpy.args[0][1];

      // Ensure it's not defined
      controller['messageObserver'] = null;

      callback({
        data: {
          'firebase-messaging-msg-type': 'push-msg-received'
        }
      });
    });

    it('should call onMessage for push msg received event', async () => {
      const messageCallbackSpy = sandbox.spy();
      const onMessageSpy = sandbox.spy();

      sandbox.stub(navigator, 'serviceWorker').value({
        addEventListener: messageCallbackSpy
      });

      const controller = new WindowController(app);

      // The API for the observables means it's async and so we kind have to
      // hope that everything is set up after a task skip
      return new Promise(resolve => setTimeout(resolve, 500))
        .then(() => {
          controller.onMessage(onMessageSpy);
          controller.setupSWMessageListener_();

          const callback = messageCallbackSpy.args[0][1];

          // Even with FCM data, if the type isn't known - do nothing.
          callback({
            data: {
              'firebase-messaging-msg-type': 'push-msg-received'
            }
          });

          // Apparently triggering an event is also async - so another timeout.
          return new Promise(resolve => setTimeout(resolve, 500));
        })
        .then(() => {
          expect(onMessageSpy.callCount).to.equal(1);
          expect(onMessageSpy.args[0][0]).to.equal(undefined);
        });
    });
  });

  describe('waitForRegistrationToActivate_', () => {
    it('should handle service worker lifecycle', () => {
      let changeListener = () => {};
      const swValue = {
        state: 'installing',
        addEventListener: (eventName: string, cb: () => void) => {
          expect(eventName).to.equal('statechange');
          changeListener = cb;
        },
        removeEventListener: (eventName: string, cb: () => void) => {
          expect(eventName).to.equal('statechange');
          expect(cb).to.equal(changeListener);
        }
      };

      const fakeReg = makeFakeSWReg('installing', swValue);

      const messagingService = new WindowController(app);
      const waitPromise = messagingService.waitForRegistrationToActivate_(
        fakeReg
      );

      changeListener();

      swValue.state = 'activated';

      changeListener();

      return waitPromise.then(reg => {
        expect(reg).to.equal(fakeReg);
      });
    });
  });
});


text:
package de.fau.cs.mad.kwikshop.server.api;

import de.fau.cs.mad.kwikshop.common.ArgumentNullException;
import de.fau.cs.mad.kwikshop.common.rest.annotations.RequiresClientId;
import de.fau.cs.mad.kwikshop.common.rest.annotations.RequiresLease;

import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.Provider;

@Provider
public class RequiresLeaseFeature extends DynamicFeatureBase {

    private final RequiresLeaseFilter filterInstance;

    public RequiresLeaseFeature(RequiresLeaseFilter filterInstance) {

        if(filterInstance == null) {
            throw new ArgumentNullException("filterInstance");
        }

        this.filterInstance = filterInstance;
    }

    @Override
    public void configure(ResourceInfo resourceInfo, FeatureContext context) {

        if (hasAnnotation(resourceInfo, RequiresLease.class)) {

            if(!hasAnnotation(resourceInfo, RequiresClientId.class)) {
                throw new InvalidAnnotationException("@RequiresLease cannot we used without @RequiresClientId");
            }

            context.register(filterInstance);
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
<?

include_once ("include/rearrange_title.php");

function show_option($selected_show) {
    echo "<select name='show_id'><option value=''></option>\n";
    $show_select = mysql_query("SELECT ID,title,year FROM shows where title is not null ORDER by title,year");
    while ($shows = mysql_fetch_array($show_select)) {
	$title=stripslashes($shows[1]);
	$title=rearrange_title($title);
	echo "      <option value='$shows[0]'";
	if (isset($selected_show) && ($selected_show==$shows[0])) { echo " selected"; }
	echo ">$title ($shows[2])</option>\n";
    }
    echo "</select>\n";
}

?>


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>Header Property</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

LayoutSkeleton.Header Property

 The header for the layout format.

        [Visual Basic]

Overridable Public Property Header As String _
    Implements ILayout.Header

        [C#]

public virtual string Header {get; set;}

Property Value

the layout header

Implements

        ILayout.Header

Remarks

 The Header text will be appended before any logging events are formatted and appended.

See Also

LayoutSkeleton Class | log4net.Layout Namespace
<object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"><param name="Keyword" value="Header property"></param><param name="Keyword" value="Header property, LayoutSkeleton class"></param><param name="Keyword" value="LayoutSkeleton.Header property"></param></object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
'use strict';

/**
 * StripeError is the base error from which all other more specific Stripe errors derive.
 * Specifically for errors returned from Stripe's REST API.
 */
class StripeError extends Error {
  constructor(raw = {}) {
    super(raw.message);
    this.type = this.constructor.name;

    this.raw = raw;
    this.rawType = raw.type;
    this.code = raw.code;
    this.doc_url = raw.doc_url;
    this.param = raw.param;
    this.detail = raw.detail;
    this.headers = raw.headers;
    this.requestId = raw.requestId;
    this.statusCode = raw.statusCode;
    this.message = raw.message;

    this.charge = raw.charge;
    this.decline_code = raw.decline_code;
    this.payment_intent = raw.payment_intent;
    this.payment_method = raw.payment_method;
    this.setup_intent = raw.setup_intent;
    this.source = raw.source;
  }

  /**
   * Helper factory which takes raw stripe errors and outputs wrapping instances
   */
  static generate(rawStripeError) {
    switch (rawStripeError.type) {
      case 'card_error':
        return new StripeCardError(rawStripeError);
      case 'invalid_request_error':
        return new StripeInvalidRequestError(rawStripeError);
      case 'api_error':
        return new StripeAPIError(rawStripeError);
      case 'authentication_error':
        return new StripeAuthenticationError(rawStripeError);
      case 'rate_limit_error':
        return new StripeRateLimitError(rawStripeError);
      case 'idempotency_error':
        return new StripeIdempotencyError(rawStripeError);
      case 'invalid_grant':
        return new StripeInvalidGrantError(rawStripeError);
      default:
        return new GenericError('Generic', 'Unknown Error');
    }
  }
}

// Specific Stripe Error types:

/**
 * CardError is raised when a user enters a card that can't be charged for
 * some reason.
 */
class StripeCardError extends StripeError {}

/**
 * InvalidRequestError is raised when a request is initiated with invalid
 * parameters.
 */
class StripeInvalidRequestError extends StripeError {}

/**
 * APIError is a generic error that may be raised in cases where none of the
 * other named errors cover the problem. It could also be raised in the case
 * that a new error has been introduced in the API, but this version of the
 * Node.JS SDK doesn't know how to handle it.
 */
class StripeAPIError extends StripeError {}

/**
 * AuthenticationError is raised when invalid credentials are used to connect
 * to Stripe's servers.
 */
class StripeAuthenticationError extends StripeError {}

/**
 * PermissionError is raised in cases where access was attempted on a resource
 * that wasn't allowed.
 */
class StripePermissionError extends StripeError {}

/**
 * RateLimitError is raised in cases where an account is putting too much load
 * on Stripe's API servers (usually by performing too many requests). Please
 * back off on request rate.
 */
class StripeRateLimitError extends StripeError {}

/**
 * StripeConnectionError is raised in the event that the SDK can't connect to
 * Stripe's servers. That can be for a variety of different reasons from a
 * downed network to a bad TLS certificate.
 */
class StripeConnectionError extends StripeError {}

/**
 * SignatureVerificationError is raised when the signature verification for a
 * webhook fails
 */
class StripeSignatureVerificationError extends StripeError {}

/**
 * IdempotencyError is raised in cases where an idempotency key was used
 * improperly.
 */
class StripeIdempotencyError extends StripeError {}

/**
 * InvalidGrantError is raised when a specified code doesn't exist, is
 * expired, has been used, or doesn't belong to you; a refresh token doesn't
 * exist, or doesn't belong to you; or if an API key's mode (live or test)
 * doesn't match the mode of a code or refresh token.
 */
class StripeInvalidGrantError extends StripeError {}

module.exports.generate = StripeError.generate;
module.exports.StripeError = StripeError;
module.exports.StripeCardError = StripeCardError;
module.exports.StripeInvalidRequestError = StripeInvalidRequestError;
module.exports.StripeAPIError = StripeAPIError;
module.exports.StripeAuthenticationError = StripeAuthenticationError;
module.exports.StripePermissionError = StripePermissionError;
module.exports.StripeRateLimitError = StripeRateLimitError;
module.exports.StripeConnectionError = StripeConnectionError;
module.exports.StripeSignatureVerificationError = StripeSignatureVerificationError;
module.exports.StripeIdempotencyError = StripeIdempotencyError;
module.exports.StripeInvalidGrantError = StripeInvalidGrantError;


text:
package com.castlemock.web.mock.soap.model;

import com.castlemock.model.mock.soap.domain.SoapOperationIdentifyStrategy;
import com.castlemock.model.mock.soap.domain.SoapOperationStatus;
import com.castlemock.model.mock.soap.domain.SoapResponseStrategy;

import java.util.Objects;

/**
 * @author Karl Dahlgren
 * @since 1.52
 */
public class UpdateSoapOperationRequest {

    private SoapResponseStrategy responseStrategy;
    private SoapOperationStatus status;
    private String forwardedEndpoint;
    private Boolean simulateNetworkDelay;
    private Long networkDelay;
    private String defaultMockResponseId;
    private Boolean mockOnFailure;
    private SoapOperationIdentifyStrategy identifyStrategy;

    public UpdateSoapOperationRequest(){

    }

    private UpdateSoapOperationRequest(final Builder builder){
        this.responseStrategy = Objects.requireNonNull(builder.responseStrategy);
        this.status = Objects.requireNonNull(builder.status);
        this.forwardedEndpoint = Objects.requireNonNull(builder.forwardedEndpoint);
        this.simulateNetworkDelay = Objects.requireNonNull(builder.simulateNetworkDelay);
        this.networkDelay = Objects.requireNonNull(builder.networkDelay);
        this.defaultMockResponseId = builder.defaultMockResponseId;
        this.mockOnFailure = Objects.requireNonNull(builder.mockOnFailure);
        this.identifyStrategy = Objects.requireNonNull(builder.identifyStrategy);
    }

    public SoapResponseStrategy getResponseStrategy() {
        return responseStrategy;
    }

    public void setResponseStrategy(SoapResponseStrategy responseStrategy) {
        this.responseStrategy = responseStrategy;
    }

    public SoapOperationStatus getStatus() {
        return status;
    }

    public void setStatus(SoapOperationStatus status) {
        this.status = status;
    }

    public String getForwardedEndpoint() {
        return forwardedEndpoint;
    }

    public void setForwardedEndpoint(String forwardedEndpoint) {
        this.forwardedEndpoint = forwardedEndpoint;
    }

    public Boolean getSimulateNetworkDelay() {
        return simulateNetworkDelay;
    }

    public void setSimulateNetworkDelay(Boolean simulateNetworkDelay) {
        this.simulateNetworkDelay = simulateNetworkDelay;
    }

    public Long getNetworkDelay() {
        return networkDelay;
    }

    public void setNetworkDelay(Long networkDelay) {
        this.networkDelay = networkDelay;
    }

    public Boolean getMockOnFailure() {
        return mockOnFailure;
    }

    public void setMockOnFailure(Boolean mockOnFailure) {
        this.mockOnFailure = mockOnFailure;
    }

    public SoapOperationIdentifyStrategy getIdentifyStrategy() {
        return identifyStrategy;
    }

    public void setIdentifyStrategy(SoapOperationIdentifyStrategy identifyStrategy) {
        this.identifyStrategy = identifyStrategy;
    }

    public String getDefaultMockResponseId() {
        return defaultMockResponseId;
    }

    public void setDefaultMockResponseId(String defaultMockResponseId) {
        this.defaultMockResponseId = defaultMockResponseId;
    }

    public static Builder builder() {
        return new Builder();
    }

    public static final class Builder {

        private SoapResponseStrategy responseStrategy;
        private SoapOperationStatus status;
        private String forwardedEndpoint;
        private Boolean simulateNetworkDelay;
        private Long networkDelay;
        private String defaultMockResponseId;
        private Boolean mockOnFailure;
        private SoapOperationIdentifyStrategy identifyStrategy;

        private Builder() {
        }

        public Builder responseStrategy(final SoapResponseStrategy responseStrategy) {
            this.responseStrategy = responseStrategy;
            return this;
        }

        public Builder status(final SoapOperationStatus status) {
            this.status = status;
            return this;
        }

        public Builder forwardedEndpoint(final String forwardedEndpoint) {
            this.forwardedEndpoint = forwardedEndpoint;
            return this;
        }

        public Builder simulateNetworkDelay(final Boolean simulateNetworkDelay) {
            this.simulateNetworkDelay = simulateNetworkDelay;
            return this;
        }

        public Builder networkDelay(final Long networkDelay) {
            this.networkDelay = networkDelay;
            return this;
        }

        public Builder defaultMockResponseId(final String defaultMockResponseId) {
            this.defaultMockResponseId = defaultMockResponseId;
            return this;
        }

        public Builder mockOnFailure(final Boolean mockOnFailure) {
            this.mockOnFailure = mockOnFailure;
            return this;
        }

        public Builder identifyStrategy(final SoapOperationIdentifyStrategy identifyStrategy) {
            this.identifyStrategy = identifyStrategy;
            return this;
        }

        public UpdateSoapOperationRequest build() {
            return new UpdateSoapOperationRequest(this);
        }
    }
}


text:
import { TransactionT } from '../../core/transaction';
import { ModelT } from '../../core/model';

class MyClass {
    id: number;

    name: string;

    static db: any;
}

export interface WherePGStatement {
    $any: Array<string | number>;
    $all: Array<string | number>;
}

export type WhereLogic = Partial<{
    $ne: string | number | WhereLogic;
    $in: Array<string | number>;
    $not: boolean | string | number;
    $notIn: Array<string | number>;
    $gte: number | string | Date;
    $gt: number | string | Date;
    $lte: number | string | Date;
    $lt: number | string | Date;
    $like: string | WherePGStatement;
    $iLike: string | WherePGStatement;
    $ilike: string | WherePGStatement;
    $notLike: string | WherePGStatement;
    $notILike: string | WherePGStatement;
    $between: [number, number];
    "..": [number, number];
    $notBetween: [number, number];
    "!..": [number, number];
    $overlap: [number, number];
    "&&": [number, number];
    $contains: any;
    "@>": any;
    $contained: any;
    "<@": any;
}>;

export type WhereClauseSimpleValue<T> = T | null;
export type WhereClauseComplexValue<T> =
        { $not: WhereClauseSimpleValue<T> }
      | { $in: WhereClauseSimpleValue<T>[] }
      | { $notIn: WhereClauseSimpleValue<T>[] }
      | { $gt: T } //...when T extends number, Date
      | { $gte: T } //...when T extends number, Date
      | { $lt: T } //...when T extends number, Date
      | { $lte: T } //...when T extends number, Date
      | { $between: [T, T] } //...when T extends number, Date
      | { $notBetween: [T, T] } //...when T extends number, Date
      | { $like: string } //...when T extends string
      | WhereClauseT<T>; //...when T extends ModelT<any>
export type WhereClauseValueT<T> = WhereClauseSimpleValue<T> | WhereClauseComplexValue<T>;
export type WhereClauseT<T> = { //T extends ModelT<any>
    [K in keyof(T)]?: WhereClauseValueT<T[K]>
} & {
    $and?: WhereClauseT<T>[]
    $or?: WhereClauseT<T>[]
};
export type WhereOptions<T> = WhereClauseT<T>;

export type IncludeClauseT<T> = string[];
export type OrderingT<T> = [keyof(T), 'ASC' | 'DESC'];
export type OrderClauseT<T> = OrderingT<T>[];
export type QueryT<T> = {
    where?: WhereClauseT<T>,
    include?: IncludeClauseT<T>,
    order?: OrderClauseT<T>,
    limit?: number,
    offset?: number,
    transaction?: TransactionT
}

type WhereMyClass = WhereClauseT<MyClass>;

export type DefaultsClauseT<T> = {
    [K in keyof(T)]: T[K] | null
};
export interface FindOrCreateQueryT<T> extends QueryT<T> {
    defaults?: DefaultsClauseT<T>
}

export type CountQueryT<T> = {
    where?: WhereClauseT<T>,
    include?: IncludeClauseT<T>,
    transaction?: TransactionT
};

export type DestroyQueryT<T> = {
    where?: WhereClauseT<T>,
    limit?: number
};


text:
package com.logginghub.utils;

import java.util.concurrent.CountDownLatch;

/**
 * A resuable latch that returns true if the latch was opened, false if it
 * stayed close, or throws a runtime exception if interupted. The latch is reset
 * after the wait... which makes it completely unsafe (it wont be clear which
 * instance is actually being used by different threads) to use it with more
 * than one thread waiting, so be careful!
 *
 * @author James
 *
 */
public class QuietLatch {

    private Timeout timeout = Timeout.defaultTimeout;
    private CountDownLatch latch;
    private int locks;

    public QuietLatch(int locks) {
        this.locks = locks;
        resetLatch();
    }

    public void resetLatch() {
        this.latch = new CountDownLatch(locks);
    }

    public void setLocks(int locks) {
        this.locks = locks;
        resetLatch();
    }

    public void setTimeout(Timeout timeout) {
        this.timeout = timeout;
    }

    public boolean await() {
        try {
            if (latch.await(timeout.getTime(), timeout.getUnits())) {
                // All good
                resetLatch();
                return true;
            }
            else {
                resetLatch();
                return false;
            }

        }
        catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void countDown() {
        latch.countDown();
    }

}


text:
id: 846
title: rue de la loi
date: 2009-02-21T18:07:49+00:00
author: admin6059
layout: pages
guid: http://localhost/wordpress/?p=846
permalink: /index.php/2009/02/21/rue-de-la-loi/
categories:
  - Appunti
  - photographies (mine)
  - Schuman_City
---
[<img class="aligncenter wp-image-845 size-full" title="shumann" src="http://blog.martasmaldone.eu/wp-content/uploads/2009/07/shumann.jpeg" alt="shumann" width="417" height="261" srcset="http://blog.martasmaldone.eu/wp-content/uploads/2009/07/shumann.jpeg 417w, http://blog.martasmaldone.eu/wp-content/uploads/2009/07/shumann-300x188.jpeg 300w" sizes="(max-width: 417px) 100vw, 417px" />](http://blog.martasmaldone.eu/wp-content/uploads/2009/07/shumann.jpeg)


text:
<?php

namespace Ibrows\LoggableBundle\Tests\Loggable\Fixture\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Ibrows\LoggableBundle\Model\ScheduledChangeablePartially;

/**
 * @ORM\Entity
 * @ORM\Table(name="fix_user")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt")
 */
class User implements ScheduledChangeablePartially
{
    /**
     * @var Article[]
     * @ORM\ManyToMany(targetEntity="Article", cascade="all")
     * @ORM\JoinTable(name="fix_user_articele",
     *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="article_id", referencedColumnName="id")}
     *      )
     */
    protected $articles;
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;
    /**
     * @ORM\Column(name="title", type="string", length=8)
     */
    private $name;

    /**
     * @ORM\Column(name="company", type="string", length=100, nullable=true)
     */
    private $company;

    /**
     * @var $deletedAt \DateTime
     * @ORM\Column(name="deleted_at", type="datetime", nullable=true)
     */

    private $deletedAt;

    /**
     * @var $scheduledChangeDate \DateTime
     */
    private $scheduledChangeDate;

    /**
     * @param \DateTime $scheduledChangeDate
     */
    public function setScheduledChangeDate($scheduledChangeDate)
    {
        $this->scheduledChangeDate = $scheduledChangeDate;
    }

    /**
     * @return \DateTime
     */
    public function getScheduledChangeDate()
    {
        return $this->scheduledChangeDate;
    }

    /**
     * set changeDate 2 null
     */
    public function removeScheduledChangeDate()
    {
        $this->setScheduledChangeDate(null);
    }

    /**
     * @return \DateTime
     */
    public function getDeletedAt()
    {
        return $this->deletedAt;
    }

    /**
     * @param \DateTime $deletedAt
     */
    public function setDeletedAt($deletedAt = null)
    {
        $this->deletedAt = $deletedAt;
    }

    public function getId()
    {
        return $this->id;
    }

    public function addArticle(Article $article)
    {
        if (!$this->getArticles()->contains($article)) {
            $this->getArticles()->add($article);
        }

        return $this;
    }

    public function getArticles()
    {
        return $this->articles ? : $this->articles = new ArrayCollection();
    }

    public function removeArticle(Article $article)
    {
        if ($this->getArticles()->contains($article)) {
            $removed = $this->getArticles()->removeElement($article);
        }

        return $this;
    }

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

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

    /**
     * @return array
     */
    public function getFieldsToSchedule()
    {
        return array('name');
    }

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

    /**
     * @param mixed $company
     */
    public function setCompany($company)
    {
        $this->company = $company;
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `set_current_dir` fn in crate `std`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, set_current_dir">

    <title>std::env::set_current_dir - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../rustdoc.css">
    <link rel="stylesheet" type="text/css" href="../../main.css">

    <link rel="shortcut icon" href="https://doc.rust-lang.org/favicon.ico">

std::<wbr>env

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options…"
                       type="search">

        </form>

Function std::<wbr>env::<wbr>set_current_dir1.0.0

                       [−]

               [src]

pub fn set_current_dir<P: AsRef<Path>>(p: P) -> Result<()>

Changes the current working directory to the specified path, returning
whether the change was completed successfully or not.

Examples

fn main() {
    use std::env;
use std::path::Path;

let root = Path::new("/");
assert!(env::set_current_dir(&root).is_ok());
println!("Successfully changed working directory to {}!", root.display());
}

use std::env;
use std::path::Path;

let root = Path::new("/");
assert!(env::set_current_dir(&root).is_ok());
println!("Successfully changed working directory to {}!", root.display());Run

Help

Keyboard Shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

+

Collapse/expand all sections

Search Tricks

                    Prefix searches with a type followed by a colon (e.g.
                    fn:) to restrict the search to a given type.

                    Accepted types are: fn, mod,
                    struct, enum,
                    trait, type, macro,
                    and const.

                    Search functions by type signature (e.g.
                    vec -> usize or * -> vec)


text:
#include "msp_joint_universal.h"
#include "msp_world.h"

/*
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    Variables
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/

const dFloat MSP::Universal::DEFAULT_MIN(-180.0f * M_DEG_TO_RAD);
const dFloat MSP::Universal::DEFAULT_MAX(180.0f * M_DEG_TO_RAD);
const bool MSP::Universal::DEFAULT_LIMITS_ENABLED(false);
const dFloat MSP::Universal::DEFAULT_FRICTION(0.0f);
const dFloat MSP::Universal::DEFAULT_CONTROLLER(1.0f);

/*
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    Callback Functions
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/

void MSP::Universal::submit_constraints(const NewtonJoint* joint, dFloat timestep, int thread_index) {
    MSP::Joint::JointData* joint_data = reinterpret_cast<MSP::Joint::JointData*>(NewtonJointGetUserData(joint));
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);

    dFloat inv_timestep = 1.0f / timestep;

    // Calculate position of pivot points and Jacobian direction vectors in global space.
    dMatrix matrix0, matrix1;
    MSP::Joint::c_calculate_global_matrix(joint_data, matrix0, matrix1);

    // Restrict movement on the pivot point along all three orthonormal directions
    NewtonUserJointAddLinearRow(joint, &matrix0.m_posit[0], &matrix1.m_posit[0], &matrix0.m_front[0]);
    NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);

    NewtonUserJointAddLinearRow(joint, &matrix0.m_posit[0], &matrix1.m_posit[0], &matrix0.m_up[0]);
    NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);

    NewtonUserJointAddLinearRow(joint, &matrix0.m_posit[0], &matrix1.m_posit[0], &matrix0.m_right[0]);
    NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);

    // Construct an orthogonal coordinate system with these two vectors
    dMatrix matrix1_1;
    matrix1_1.m_front = matrix1.m_front;
    matrix1_1.m_up = matrix0.m_right.CrossProduct(matrix1.m_front);
    matrix1_1.m_up = matrix1_1.m_up.Scale(1.0f / dSqrt(matrix1_1.m_up.DotProduct3(matrix1_1.m_up)));
    matrix1_1.m_right = matrix1_1.m_front.CrossProduct(matrix1_1.m_up);

    // Override the normal right side because the joint is too week due two centripetal accelerations
    dVector omega0(0.0f);
    dVector omega1(0.0f);
    NewtonBodyGetOmega(joint_data->m_child, &omega0[0]);
    if (joint_data->m_parent != nullptr)
        NewtonBodyGetOmega(joint_data->m_parent, &omega1[0]);
    dVector rel_omega(omega0 - omega1);

    dFloat angle = -MSP::Joint::c_calculate_angle2(matrix0.m_right, matrix1_1.m_right, matrix1_1.m_up);
    dFloat omega = rel_omega.DotProduct3(matrix1_1.m_up);
    dFloat alpha_error = -(angle + omega * timestep) / (timestep * timestep);

    NewtonUserJointAddAngularRow(joint, -angle, &matrix1_1.m_up[0]);
    NewtonUserJointSetRowAcceleration(joint, alpha_error);
    NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);

    dFloat sin_angle1, cos_angle1;
    MSP::Joint::c_calculate_angle(matrix1_1.m_front, matrix0.m_front, matrix1_1.m_right, sin_angle1, cos_angle1);
    dFloat cur_angle1 = cj_data->m_ai1->update(cos_angle1, sin_angle1);
    dFloat last_omega1 = cj_data->m_cur_omega1;
    cj_data->m_cur_omega1 = rel_omega.DotProduct3(matrix1_1.m_right);
    cj_data->m_cur_alpha1 = (cj_data->m_cur_omega1 - last_omega1) * inv_timestep;

    dFloat sin_angle2, cos_angle2;
    MSP::Joint::c_calculate_angle(matrix1.m_right, matrix1_1.m_right, matrix1_1.m_front, sin_angle2, cos_angle2);
    dFloat cur_angle2 = cj_data->m_ai2->update(cos_angle2, sin_angle2);
    dFloat last_omega2 = cj_data->m_cur_omega2;
    cj_data->m_cur_omega2 = rel_omega.DotProduct3(matrix1_1.m_front);
    cj_data->m_cur_alpha2 = (cj_data->m_cur_omega2 - last_omega2) * inv_timestep;

    // Add angular limits and friction 1.
    bool bcontinue = false;
    if (cj_data->m_limits1_enabled) {
        if (cj_data->m_min1 > cj_data->m_max1) {
            NewtonUserJointAddAngularRow(joint, (cj_data->m_min1 + cj_data->m_max1) * 0.5f - cur_angle1, &matrix0.m_right[0]);
            NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
        }
        else if (cj_data->m_max1 - cj_data->m_min1 < Joint::ANGULAR_LIMIT_EPSILON2) {
            NewtonUserJointAddAngularRow(joint, -cur_angle1, &matrix0.m_right[0]);
            NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
        }
        else if (cur_angle1 < cj_data->m_min1) {
            NewtonUserJointAddAngularRow(joint, cj_data->m_min1 - cur_angle1 + Joint::ANGULAR_LIMIT_EPSILON, &matrix0.m_right[0]);
            NewtonUserJointSetRowMinimumFriction(joint, 0.0f);
            NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
        }
        else if (cur_angle1 > cj_data->m_max1) {
            NewtonUserJointAddAngularRow(joint, cj_data->m_max1 - cur_angle1 - Joint::ANGULAR_LIMIT_EPSILON, &matrix0.m_right[0]);
            NewtonUserJointSetRowMaximumFriction(joint, 0.0f);
            NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
        }
        else
            bcontinue = true;
    }
    else
        bcontinue = true;
    if (bcontinue) {
        NewtonUserJointAddAngularRow(joint, 0.0f, &matrix0.m_right[0]);
        NewtonUserJointSetRowAcceleration(joint, -cj_data->m_cur_omega1 * inv_timestep);
        dFloat power = cj_data->m_friction * dAbs(cj_data->m_controller);
        NewtonUserJointSetRowMinimumFriction(joint, -power);
        NewtonUserJointSetRowMaximumFriction(joint, power);
        NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
    }

    // Add angular limits and friction 2.
    bcontinue = false;
    if (cj_data->m_limits2_enabled) {
        if (cj_data->m_min2 > cj_data->m_max2) {
            NewtonUserJointAddAngularRow(joint, (cj_data->m_min2 + cj_data->m_max2) * 0.5f - cur_angle2, &matrix0.m_front[0]);
            NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
        }
        else if (cj_data->m_max2 - cj_data->m_min2 < Joint::ANGULAR_LIMIT_EPSILON2) {
            NewtonUserJointAddAngularRow(joint, -cur_angle2, &matrix0.m_front[0]);
            NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
        }
        else if (cur_angle2 < cj_data->m_min2) {
            NewtonUserJointAddAngularRow(joint, cj_data->m_min2 - cur_angle2 + Joint::ANGULAR_LIMIT_EPSILON, &matrix0.m_front[0]);
            NewtonUserJointSetRowMinimumFriction(joint, 0.0f);
            NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
        }
        else if (cur_angle2 > cj_data->m_max2) {
            NewtonUserJointAddAngularRow(joint, cj_data->m_max2 - cur_angle2 - Joint::ANGULAR_LIMIT_EPSILON, &matrix0.m_front[0]);
            NewtonUserJointSetRowMaximumFriction(joint, 0.0f);
            NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
        }
        else
            bcontinue = true;
    }
    else
        bcontinue = true;
    if (bcontinue) {
        NewtonUserJointAddAngularRow(joint, 0.0f, &matrix0.m_front[0]);
        NewtonUserJointSetRowAcceleration(joint, -cj_data->m_cur_omega2 * inv_timestep);
        dFloat power = cj_data->m_friction * dAbs(cj_data->m_controller);
        NewtonUserJointSetRowMinimumFriction(joint, -power);
        NewtonUserJointSetRowMaximumFriction(joint, power);
        NewtonUserJointSetRowStiffness(joint, joint_data->m_stiffness);
    }
}

void MSP::Universal::get_info(const NewtonJoint* const joint, NewtonJointRecord* const info) {
    MSP::Joint::JointData* joint_data = reinterpret_cast<MSP::Joint::JointData*>(NewtonJointGetUserData(joint));
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);

    info->m_minLinearDof[0] = -0.0f;
    info->m_maxLinearDof[0] = 0.0f;
    info->m_minLinearDof[1] = -0.0f;
    info->m_maxLinearDof[1] = 0.0f;
    info->m_minLinearDof[2] = -0.0f;
    info->m_maxLinearDof[2] = 0.0f;

    if (cj_data->m_limits2_enabled) {
        info->m_minAngularDof[0] = (cj_data->m_min2 - cj_data->m_ai2->get_angle()) * M_RAD_TO_DEG;
        info->m_maxAngularDof[0] = (cj_data->m_max2 - cj_data->m_ai2->get_angle()) * M_RAD_TO_DEG;
    }
    else {
        info->m_minAngularDof[0] = -Joint::CUSTOM_LARGE_VALUE;
        info->m_maxAngularDof[0] = Joint::CUSTOM_LARGE_VALUE;
    }

    info->m_minAngularDof[1] = -0.0f;
    info->m_maxAngularDof[1] = 0.0f;

    if (cj_data->m_limits1_enabled) {
        info->m_minAngularDof[2] = (cj_data->m_min1 - cj_data->m_ai1->get_angle()) * M_RAD_TO_DEG;
        info->m_maxAngularDof[2] = (cj_data->m_max1 - cj_data->m_ai1->get_angle()) * M_RAD_TO_DEG;
    }
    else {
        info->m_minAngularDof[2] = -Joint::CUSTOM_LARGE_VALUE;
        info->m_maxAngularDof[2] = Joint::CUSTOM_LARGE_VALUE;
    }
}

void MSP::Universal::on_destroy(MSP::Joint::JointData* joint_data) {
    delete (reinterpret_cast<UniversalData*>(joint_data->m_cj_data));
}

void MSP::Universal::on_disconnect(MSP::Joint::JointData* joint_data) {
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    cj_data->m_ai1->set_angle(0.0f);
    cj_data->m_cur_omega1 = 0.0f;
    cj_data->m_cur_alpha1 = 0.0f;
    cj_data->m_ai2->set_angle(0.0f);
    cj_data->m_cur_omega2 = 0.0f;
    cj_data->m_cur_alpha2 = 0.0f;
}

/*
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    Ruby Functions
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/

VALUE MSP::Universal::rbf_is_valid(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* address = reinterpret_cast<MSP::Joint::JointData*>(Util::value_to_ull(v_joint));
    return (MSP::Joint::c_is_joint_valid(address) && address->m_jtype == MSP::Joint::UNIVERSAL) ? Qtrue : Qfalse;
}

VALUE MSP::Universal::rbf_create(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::NONE);
    joint_data->m_dof = 6;
    joint_data->m_jtype = MSP::Joint::UNIVERSAL;
    joint_data->m_cj_data = new UniversalData();
    joint_data->m_submit_constraints = submit_constraints;
    joint_data->m_get_info = get_info;
    joint_data->m_on_destroy = on_destroy;
    joint_data->m_on_disconnect = on_disconnect;

    return MSP::Joint::c_joint_to_value(joint_data);
}

VALUE MSP::Universal::rbf_get_cur_angle1(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_ai1->get_angle());
}

VALUE MSP::Universal::rbf_get_cur_omega1(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_cur_omega1);
}

VALUE MSP::Universal::rbf_get_cur_alpha1(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_cur_alpha1);
}

VALUE MSP::Universal::rbf_get_min1(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_min1);
}

VALUE MSP::Universal::rbf_set_min1(VALUE self, VALUE v_joint, VALUE v_min) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    cj_data->m_min1 = Util::value_to_dFloat(v_min);
    return Qnil;
}

VALUE MSP::Universal::rbf_get_max1(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_max1);
}

VALUE MSP::Universal::rbf_set_max1(VALUE self, VALUE v_joint, VALUE v_max) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    cj_data->m_max1 = Util::value_to_dFloat(v_max);
    return Qnil;
}

VALUE MSP::Universal::rbf_enable_limits1(VALUE self, VALUE v_joint, VALUE v_state) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    cj_data->m_limits1_enabled = Util::value_to_bool(v_state);
    return Qnil;
}

VALUE MSP::Universal::rbf_limits1_enabled(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_limits1_enabled);
}

VALUE MSP::Universal::rbf_get_cur_angle2(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_ai2->get_angle());
}

VALUE MSP::Universal::rbf_get_cur_omega2(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_cur_omega2);
}

VALUE MSP::Universal::rbf_get_cur_alpha2(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_cur_alpha2);
}

VALUE MSP::Universal::rbf_get_min2(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_min2);
}

VALUE MSP::Universal::rbf_set_min2(VALUE self, VALUE v_joint, VALUE v_min) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    cj_data->m_min2 = Util::value_to_dFloat(v_min);
    return Qnil;
}

VALUE MSP::Universal::rbf_get_max2(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_max2);
}

VALUE MSP::Universal::rbf_set_max2(VALUE self, VALUE v_joint, VALUE v_max) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    cj_data->m_max2 = Util::value_to_dFloat(v_max);
    return Qnil;
}

VALUE MSP::Universal::rbf_enable_limits2(VALUE self, VALUE v_joint, VALUE v_state) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    cj_data->m_limits2_enabled = Util::value_to_bool(v_state);
    return Qnil;
}

VALUE MSP::Universal::rbf_limits2_enabled(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_limits2_enabled);
}

VALUE MSP::Universal::rbf_get_friction(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_friction * M_INCH2_TO_METER2);
}

VALUE MSP::Universal::rbf_set_friction(VALUE self, VALUE v_joint, VALUE v_friction) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    cj_data->m_friction = Util::max_float(Util::value_to_dFloat(v_friction) * M_METER2_TO_INCH2, 0.0f);
    return Qnil;
}

VALUE MSP::Universal::rbf_get_controller(VALUE self, VALUE v_joint) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    return Util::to_value(cj_data->m_controller);
}

VALUE MSP::Universal::rbf_set_controller(VALUE self, VALUE v_joint, VALUE v_controller) {
    MSP::Joint::JointData* joint_data = MSP::Joint::c_value_to_joint2(v_joint, MSP::Joint::UNIVERSAL);
    UniversalData* cj_data = reinterpret_cast<UniversalData*>(joint_data->m_cj_data);
    dFloat desired_controller = Util::value_to_dFloat(v_controller);
    if (cj_data->m_controller != desired_controller) {
        cj_data->m_controller = desired_controller;
        if (joint_data->m_connected)
            NewtonBodySetSleepState(joint_data->m_child, 0);
    }
    return Qnil;
}

/*
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  Main
 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
*/

void MSP::Universal::init_ruby(VALUE mNewton) {
    VALUE mUniversal = rb_define_module_under(mNewton, "Universal");

    rb_define_module_function(mUniversal, "is_valid?", VALUEFUNC(MSP::Universal::rbf_is_valid), 1);
    rb_define_module_function(mUniversal, "create", VALUEFUNC(MSP::Universal::rbf_create), 1);
    rb_define_module_function(mUniversal, "get_cur_angle1", VALUEFUNC(MSP::Universal::rbf_get_cur_angle1), 1);
    rb_define_module_function(mUniversal, "get_cur_omega1", VALUEFUNC(MSP::Universal::rbf_get_cur_omega1), 1);
    rb_define_module_function(mUniversal, "get_cur_alpha1", VALUEFUNC(MSP::Universal::rbf_get_cur_alpha1), 1);
    rb_define_module_function(mUniversal, "get_min1", VALUEFUNC(MSP::Universal::rbf_get_min1), 1);
    rb_define_module_function(mUniversal, "set_min1", VALUEFUNC(MSP::Universal::rbf_set_min1), 2);
    rb_define_module_function(mUniversal, "get_max1", VALUEFUNC(MSP::Universal::rbf_get_max1), 1);
    rb_define_module_function(mUniversal, "set_max1", VALUEFUNC(MSP::Universal::rbf_set_max1), 2);
    rb_define_module_function(mUniversal, "enable_limits1", VALUEFUNC(MSP::Universal::rbf_enable_limits1), 2);
    rb_define_module_function(mUniversal, "limits1_enabled?", VALUEFUNC(MSP::Universal::rbf_limits1_enabled), 1);

    rb_define_module_function(mUniversal, "get_cur_angle2", VALUEFUNC(MSP::Universal::rbf_get_cur_angle2), 1);
    rb_define_module_function(mUniversal, "get_cur_omega2", VALUEFUNC(MSP::Universal::rbf_get_cur_omega2), 1);
    rb_define_module_function(mUniversal, "get_cur_alpha2", VALUEFUNC(MSP::Universal::rbf_get_cur_alpha2), 1);
    rb_define_module_function(mUniversal, "get_min2", VALUEFUNC(MSP::Universal::rbf_get_min2), 1);
    rb_define_module_function(mUniversal, "set_min2", VALUEFUNC(MSP::Universal::rbf_set_min2), 2);
    rb_define_module_function(mUniversal, "get_max2", VALUEFUNC(MSP::Universal::rbf_get_max2), 1);
    rb_define_module_function(mUniversal, "set_max2", VALUEFUNC(MSP::Universal::rbf_set_max2), 2);
    rb_define_module_function(mUniversal, "enable_limits2", VALUEFUNC(MSP::Universal::rbf_enable_limits2), 2);
    rb_define_module_function(mUniversal, "limits2_enabled?", VALUEFUNC(MSP::Universal::rbf_limits2_enabled), 1);

    rb_define_module_function(mUniversal, "get_friction", VALUEFUNC(MSP::Universal::rbf_get_friction), 1);
    rb_define_module_function(mUniversal, "set_friction", VALUEFUNC(MSP::Universal::rbf_set_friction), 2);
    rb_define_module_function(mUniversal, "get_controller", VALUEFUNC(MSP::Universal::rbf_get_controller), 1);
    rb_define_module_function(mUniversal, "set_controller", VALUEFUNC(MSP::Universal::rbf_set_controller), 2);
}


text:
``mediahandler``
============================================

.. |MHObject| replace:: :class:`mediahandler.MHObject`

.. automodule:: mediahandler
    :members:
    :undoc-members:
    :show-inheritance:


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>STTR Phase I: High power, High energy density, Nanostructured bulk Li-ion Battery</AwardTitle>
    <AwardEffectiveDate>07/01/2009</AwardEffectiveDate>
    <AwardExpirationDate>09/30/2010</AwardExpirationDate>
    <AwardAmount>150000</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      07070000
      <Directorate>
        <LongName>Directorate For Engineering</LongName>
      </Directorate>
      <Division>
        <LongName>Div Of Industrial Innovation & Partnersh</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Grace Jinliu Wang</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>This award is funded under the American Recovery and Reinvestment Act of 2009 (Public Law 111-5).<br/><br/>This Small business Technology Transfer Phase I project is to demonstrate the technology for a high power; high energy density nanostructured Li-ion battery. Many of the new applications of lithium ion batteries require high energy and power densities, quick recharging time, and safe operation at varying ambient temperatures. <br/><br/>Lithium ion cells are essential building blocks for a wide range of batteries used in consumer electronics and military applications, as well as in next generation hybrid electric vehicles. If successful this research will help provide improved performance for these applications.</AbstractNarration>
    <MinAmdLetterDate>06/23/2009</MinAmdLetterDate>
    <MaxAmdLetterDate>06/23/2009</MaxAmdLetterDate>
    <ARRAAmount>150000</ARRAAmount>
    <AwardID>0930626</AwardID>
    <Investigator>
      <FirstName>Suvankar</FirstName>
      <LastName>Sengupta</LastName>
      <EmailAddress>ssengupta@metamateria.com</EmailAddress>
      <StartDate>06/23/2009</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>John</FirstName>
      <LastName>Lannutti</LastName>
      <EmailAddress>lannuttj@matsceng.ohio-state.edu</EmailAddress>
      <StartDate>06/23/2009</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>METAMATERIA PARTNERS LLC</Name>
      <CityName>COLUMBUS</CityName>
      <ZipCode>432122115</ZipCode>
      <PhoneNumber>6143401690</PhoneNumber>
      <StreetAddress>1275 KINNEAR RD</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Ohio</StateName>
      <StateCode>OH</StateCode>
    </Institution>
    <FoaInformation>
      0308000
      <Name>Industrial Technology</Name>
    </FoaInformation>
    <ProgramElement>
      1505
      <Text>STTR PHASE I</Text>
    </ProgramElement>
    <ProgramElement>
      5371
      <Text>SMALL BUSINESS PHASE I</Text>
    </ProgramElement>
    <ProgramReference>
      1517
      <Text>ELECT, PHOTONICS, & DEVICE TEC</Text>
    </ProgramReference>
    <ProgramReference>
      1676
      <Text>NANOSCALE: EXPLORATORY RSRCH</Text>
    </ProgramReference>
    <ProgramReference>
      1775
      <Text>ELECTRONIC/PHOTONIC MATERIALS</Text>
    </ProgramReference>
    <ProgramReference>
      6890
      <Text>RECOVERY ACT ACTION</Text>
    </ProgramReference>
    <ProgramReference>
      9139
      <Text>INFORMATION INFRASTRUCTURE & TECH APPL</Text>
    </ProgramReference>
    <ProgramReference>
      HPCC
      <Text>HIGH PERFORMANCE COMPUTING & COMM</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
<!DOCTYPE HTML>

	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>RatingIndicator - sap.ui.commons</title>
	<link rel="shortcut icon" type="image/x-icon" href="../images/controls/sap.ui.commons.RatingIndicator.gif">

	<link rel="stylesheet" href="../../../../../resources/sap/ui/thirdparty/qunit.css" type="text/css" media="screen">

QUnit tests: sap.ui.commons.RatingIndicator


text:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>Chapter1 Example8</title>

Game setup

Player 1

    Name:
    <input type="text" placeholder="Please enter player 1 name" ng-model="name" ng-focus="onNameFocused()">

Player 1 name is {{name}}.

Previous Player 1 name was {{previousName}}.

Player 2

    Name:
    <input type="text" placeholder="Please enter player 2 name" ng-model="name" ng-focus="onNameFocused()">

Player 2 name is {{name}}.

Previous Player 2 name was {{previousName}}.


text:
/*global expect */
/* jshint expr:true */

import Ember from 'ember';
import startApp from '../helpers/start-app';
import { it } from 'ember-mocha';
import { beforeEach, afterEach, describe } from '../test-helper';
import { bastion, stanley, charles } from 'dummy/mixins/folks';

var App;

describe('XSelect: Multiple Selection', function() {
  var select, controller;
  beforeEach(function() {
    App = startApp();
    visit("/multiple");
  });
  beforeEach(function() {
    var el = Ember.$('select');
    select = Ember.View.views[el.attr('id')];
    this.$ = function() {
      return select.$.apply(select, arguments);
    };
    controller = App.__container__.lookup('controller:multiple');
  });

  afterEach(function() {
    Ember.run(App, 'destroy');
  });

  it("does not fire any actions on didInsertElement", function() {
    expect(controller.get('changedSelections')).not.to.be.ok();
  });

  it('marks all selected values', function() {
    expect(this.$('option:eq(1)')).to.be.selected;
    expect(this.$('option:eq(2)')).to.be.selected;
  });

  describe('choosing the last option', function() {
    beforeEach(function() {
      this.$().prop('selectedIndex', 2).trigger('change');
    });

    it('invokes action', function() {
      expect(controller.get('currentSelections.length')).to.equal(1);
      expect(controller.get('currentSelections.firstObject.name')).to.deep.equal('Stanley');
    });
  });

  describe('manually setting the selected binding', function() {
    beforeEach(function() {
      controller.set('selections', [controller.get('charles'), controller.get('stanley')]);
    });
    it('updates the selected option', function() {
      expect(this.$('option:first')).to.be.selected;
      expect(this.$('option:eq(2)')).to.be.selected;
    });
  });

  describe("when no option is selected", function() {
    beforeEach(function() {
      this.$().prop('selectedIndex', 3).trigger('change');
    });
    it("has the empty array as a value", function() {
      expect(controller.get('currentSelections.length')).to.equal(0);
    });
  });

  describe("trying to set the value to a non-array", function() {
    beforeEach(function() {
      try {
        Ember.run(function() {
          controller.set('selections', 'OHAI!');
        });
      } catch (e) {
        this.exception = e;
      }
    });
    it("throws an error", function() {
      expect(this.exception).not.to.be.undefined;
      expect(this.exception.message).to.match(/enumerable/);
    });

  });

});


text:
export interface Listener<T> {
    (payload?: T): void;
}

export interface ObservableDelegate {
    addListener?: <T>(observable: string, listener: Listener<T>) => Listener<T>;
    removeListener?: <T>(observable: string, listener: Listener<T>) => void;
}

export interface ObservableCollection {
    [key: string]: Observable<any>;
}

class Observable<T> {

    static delegate(instance: ObservableDelegate, collection: ObservableCollection) {
        instance.addListener = <T>(observable: string, listener: Listener<T>): Listener<T> => {
            if (!collection[observable]) {
                throw new Error('no observable' + observable);
            }

            return collection[observable].addListener(listener);
        };

        instance.removeListener = <T>(observable: string, listener: Listener<T>): void => {
            if (!collection[observable]) {
                throw new Error('no observable ' + observable);
            }

            collection[observable].removeListener(listener);
        };
    }

    addListener(listener: Listener<T>): Listener<T> {
        this._listeners.push(listener);

        return listener;
    }

    removeListener(listener: Listener<T>): this {
        const i = this._listeners.indexOf(listener);

        if (i >= 0) {
            this._listeners.splice(i, 1);
        }

        return this;
    }

    fire(payload?: T): this {
        const len = this._listeners.length;

        for (let i = 0; i < len; i++) {
            this._listeners[i](payload);
        }

        return this;
    }

    private _listeners: Array<Listener<T>> = [];
}

export default Observable;


text:
require 'rubygems' # This line not needed for ruby > 1.8
require 'twilio-ruby'

# Get your Account Sid and Auth Token from twilio.com/user/account
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Twilio::REST::Client.new account_sid, auth_token

# Get an object from its sid. If you do not have a sid,
# check out the list resource examples on this page
member = client.account
               .queues.get('QU5ef8732a3c49700934481addd5ce1659')
               .members.get('Front')
               .update(url: 'http://demo.twilio.com/docs/voice.xml',
                       method: 'POST')
puts member.wait_time


text:
extern Ast::Functions program;
extern int yyparse();
extern "C" FILE *yyin;

void printSyntaxTree()
{
    for (auto st : program)
        std::cerr << st->toString();
}

void check()
{
    Checks::NameChecker nc;
    nc.run(program);
}

int main(int argc, char *argv[])
{
    if (argc < 2)
        Msg::error("No input file passed");

    yyin = 0;
    yyin = fopen(argv[1], "r");
    if (not yyin)
        Msg::error(std::string("Invalid input file: ") + argv[1]);

    Msg::log(std::string("Compiling: '") + argv[1] + "'...\n");

    yyparse();
    printSyntaxTree();
    check();
    translate();
    for (auto st : program)
        delete st;
    return 0;
}


text:
Queries principales previstas en el sistema, y dónde:

* FIND all Targets (Aggregator start)
* FIND all AggregationOptions for a target (Aggregator.Worker start)
* UPDATE detected_specs for a Target (Aggregator.Worker start)
* INSERT Aggregation for a metric,target,type,tag (Aggregator.Metric.* loop)
* DELETE size capped Aggregations for a metric,target,type,tag
(Aggregator.Metric.* loop)
* FIND all ReactionTargets (Reactor start)
* FIND last Aggregation for a metric,target,type (Reactor.Reaction.* loop)
* FINDandMODIFY some Aggregations for a metric,target,type (Reactor.Reaction.*
loop)
* INSERT Notification for a target,type (Reactor.Reaction.* loop)
* FINDandMODIFY first pending or stranded Notification (Notificator.Worker loop)
* FIND NotificationOptions for a target,type (Notificator.Worker loop)
* DELETE Notification (Notificator.Worker loop)

## ReactionTargets

Key fields:  reaction, target
Data fields:  updated, options

Example:
```
    { "reaction":"range","target":"1.1.1.1",
      "updated":ISODate("2015-02-15T09:16:24.848Z"),
      "options":{
        "metrics":["cpu","ram","disk"],
        "ram_max":0.8
      } }
```

Collection para mantener la vinculación y las opciones de cada Reaction para un
Target. Opcionalmente se pueden fijar opciones para ese target en particular.
Por defecto se usarán las opciones del Reaction.

## Notifications

Key fields:    reaction, target, type
Data fields:    payload, updated

Email Notification example:
```
    { "reaction":"range","target":"8.8.8.8","type":"email",
      "payload":{"from":"asdf@sdf","to":"asfgadfg@sdfgsd",
                 "subject":"...","body":"..."},
      "updated":ISODate("2015-02-15T09:16:24.848Z") }
```

El módulo Reactor.Reaction genera un Notification en base de datos cuando se cumplen las condiciones para ello, usando los módulos del namespace Notification para ello. El módulo Notificator.Worker lee y consume la Notification de base de datos usando los mismo módulos.

## Aggregations

Key fields:    metric, target, type, tag
Data fields:    value, updated

Values for type:
* numeric:
  * RT                        capped by size(*)
  * variable (5min)          capped by TTL(*)
  * hour                        "
  * day                        "
* event                                capped by size

CPU RT example:
```
    { "metric":"cpu","target":"8.8.8.8","type":"RT","tag":20150215091624,
      "value":60.43,"updated":ISODate("2015-02-15T09:16:24.848Z") }
```

Log error example:
```
    { "metric":"log_error","target":"8.8.8.8","type":"event",
      "tag":20150215091624,"updated":ISODate("2015-02-15T09:16:24.848Z"),
      "value":{
        "data":"This is an error line in logs blah blah",
        "line":1234,
        "file":"production.log",
        "context":["njsdfkjbsdfgkjsbdfg","fasdfasd",...]
      } }
```

El módulo Aggregation que genera los datos es el que sabe qué necesita guardarse
para su métrica específica. Del mismo modo el Reaction que los lee también sabe
en qué formato se han guardado.

Todos los tipos de Aggregation están limitados, ya sea por size o TTL. Dada una
configuración y el tiempo suficiente, el sistema debe llegar un tamaño máximo
estable.

## AggregationOptions

Key fields:    metric, target(default: "generic")
Data fields:    options, updated

Example:
```
    { "metric":"cpu","target":"generic",
      "updated":ISODate("2015-02-15T09:16:24.848Z"),
      "options":{
        "limits":{"RT":100,"variable":3600,"hour":72*3600,"day":30*86400},
        "variable":300
      } }
```

Collection para mantener las opciones de cada Aggregation para un Target, en
caso de que los necesite. Por ejemplo los límites ( size o TTL ) de cada type.
Por defecto el target puede ser generic para tener opciones comunes a todos
ellos. Opcionalmente los parámetros se pueden fijar para algún target en
particular. Podría estar vacía. Los valores por defecto en código deberían ser
razonables.

## Targets

Key fields:   target(IP)
Data fields:    user, detected_specs, updated

Example:
```
    { "target":"8.8.8.8","user":"myuser",
      "updated":ISODate("2015-02-15T09:16:24.848Z"),
      "detected_specs":{
        "ram":4096,
        "cpu_cores":4,
        "disk":50000,
        "swap":512
      } }
```

Los detected_specs se irán actualizando periódicamente, y pueden ir ampliándose
cuando se implemente la detección de más (ej. nginx version, kernel version, OS
distribution, etc.)


text:
"""

  fs.tests.test_expose:  testcases for fs.expose and associated FS classes

"""

import unittest
import sys
import os, os.path
import socket
import threading
import time

from fs.tests import FSTestCases, ThreadingTestCases
from fs.tempfs import TempFS
from fs.osfs import OSFS
from fs.memoryfs import MemoryFS
from fs.path import *
from fs.errors import *

from fs import rpcfs
from fs.expose.xmlrpc import RPCFSServer

import six
from six import PY3, b

class TestRPCFS(unittest.TestCase, FSTestCases, ThreadingTestCases):

    def makeServer(self,fs,addr):
        return RPCFSServer(fs,addr,logRequests=False)

    def startServer(self):
        port = 3000
        self.temp_fs = TempFS()
        self.server = None

        self.serve_more_requests = True
        self.server_thread = threading.Thread(target=self.runServer)
        self.server_thread.setDaemon(True)

        self.start_event = threading.Event()
        self.end_event = threading.Event()

        self.server_thread.start()

        self.start_event.wait()

    def runServer(self):
        """Run the server, swallowing shutdown-related execptions."""

        port = 3000
        while not self.server:
            try:
                self.server = self.makeServer(self.temp_fs,("127.0.0.1",port))
            except socket.error, e:
                if e.args[1] == "Address already in use":
                    port += 1
                else:
                    raise
        self.server_addr = ("127.0.0.1", port)

        self.server.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

#        if sys.platform != "win32":
#            try:
#                self.server.socket.settimeout(1)
#            except socket.error:
#                pass
#
        self.start_event.set()

        try:
            #self.server.serve_forever()
            while self.serve_more_requests:
                self.server.handle_request()
        except Exception, e:
            pass

        self.end_event.set()

    def setUp(self):
        self.startServer()
        self.fs = rpcfs.RPCFS("http://%s:%d" % self.server_addr)

    def tearDown(self):
        self.serve_more_requests = False
        #self.server.socket.close()
#            self.server.socket.shutdown(socket.SHUT_RDWR)
#            self.server.socket.close()
#            self.temp_fs.close()
        #self.server_thread.join()

        #self.end_event.wait()
        #return

        try:
            self.bump()
            self.server.server_close()
        except Exception:
            pass
        #self.server_thread.join()
        self.temp_fs.close()

    def bump(self):
        host, port = self.server_addr
        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
            af, socktype, proto, cn, sa = res
            sock = None
            try:
                sock = socket.socket(af, socktype, proto)
                sock.settimeout(.1)
                sock.connect(sa)
                sock.send(b("\n"))
            except socket.error, e:
                pass
            finally:
                if sock is not None:
                    sock.close()

try:
    from fs import sftpfs
    from fs.expose.sftp import BaseSFTPServer
except ImportError:
    if not PY3:
        raise
class TestSFTPFS(TestRPCFS):

    __test__ = not PY3

    def makeServer(self,fs,addr):
        return BaseSFTPServer(addr,fs)

    def setUp(self):
        self.startServer()
        self.fs = sftpfs.SFTPFS(self.server_addr, no_auth=True)

    #def runServer(self):
    #    self.server.serve_forever()
    #
    #def tearDown(self):
    #    self.server.shutdown()
    #    self.server_thread.join()
    #    self.temp_fs.close()

    def bump(self):
        # paramiko doesn't like being bumped, just wait for it to timeout.
        # TODO: do this using a paramiko.Transport() connection
        pass

try:
    from fs.expose import fuse
except ImportError:
    pass
else:
    from fs.osfs import OSFS
    class TestFUSE(unittest.TestCase,FSTestCases,ThreadingTestCases):

        def setUp(self):
            self.temp_fs = TempFS()
            self.temp_fs.makedir("root")
            self.temp_fs.makedir("mount")
            self.mounted_fs = self.temp_fs.opendir("root")
            self.mount_point = self.temp_fs.getsyspath("mount")
            self.fs = OSFS(self.temp_fs.getsyspath("mount"))
            self.mount_proc = fuse.mount(self.mounted_fs,self.mount_point)

        def tearDown(self):
            self.mount_proc.unmount()
            try:
                self.temp_fs.close()
            except OSError:
                # Sometimes FUSE hangs onto the mountpoint if mount_proc is
                # forcibly killed.  Shell out to fusermount to make sure.
                fuse.unmount(self.mount_point)
                self.temp_fs.close()

        def check(self,p):
            return self.mounted_fs.exists(p)

from fs.expose import dokan
if dokan.is_available:
    from fs.osfs import OSFS
    class DokanTestCases(FSTestCases):
        """Specialised testcases for filesystems exposed via Dokan.

        This modifies some of the standard tests to work around apparent
        bugs in the current Dokan implementation.
        """

        def test_remove(self):
            self.fs.createfile("a.txt")
            self.assertTrue(self.check("a.txt"))
            self.fs.remove("a.txt")
            self.assertFalse(self.check("a.txt"))
            self.assertRaises(ResourceNotFoundError,self.fs.remove,"a.txt")
            self.fs.makedir("dir1")
            #  This appears to be a bug in Dokan - DeleteFile will happily
            #  delete an empty directory.
            #self.assertRaises(ResourceInvalidError,self.fs.remove,"dir1")
            self.fs.createfile("/dir1/a.txt")
            self.assertTrue(self.check("dir1/a.txt"))
            self.fs.remove("dir1/a.txt")
            self.assertFalse(self.check("/dir1/a.txt"))

        def test_open_on_directory(self):
            #  Dokan seems quite happy to ask me to open a directory and
            #  then treat it like a file.
            pass

        def test_settimes(self):
            #  Setting the times does actually work, but there's some sort
            #  of caching effect which prevents them from being read back
            #  out.  Disabling the test for now.
            pass

        def test_safety_wrapper(self):
            rawfs = MemoryFS()
            safefs = dokan.Win32SafetyFS(rawfs)
            rawfs.setcontents("autoRun.inf", b("evilcodeevilcode"))
            self.assertTrue(safefs.exists("_autoRun.inf"))
            self.assertTrue("autoRun.inf" not in safefs.listdir("/"))
            safefs.setcontents("file:stream",b("test"))
            self.assertFalse(rawfs.exists("file:stream"))
            self.assertTrue(rawfs.exists("file__colon__stream"))
            self.assertTrue("file:stream" in safefs.listdir("/"))

    class TestDokan(unittest.TestCase,DokanTestCases,ThreadingTestCases):

        def setUp(self):
            self.temp_fs = TempFS()
            self.drive = "K"
            while os.path.exists(self.drive+":\\") and self.drive <= "Z":
                self.drive = chr(ord(self.drive) + 1)
            if self.drive > "Z":
                raise RuntimeError("no free drive letters")
            fs_to_mount = OSFS(self.temp_fs.getsyspath("/"))
            self.mount_proc = dokan.mount(fs_to_mount,self.drive)#,flags=dokan.DOKAN_OPTION_DEBUG|dokan.DOKAN_OPTION_STDERR,numthreads=1)
            self.fs = OSFS(self.mount_proc.path)

        def tearDown(self):
            self.mount_proc.unmount()
            for _ in xrange(10):
                try:
                    if self.mount_proc.poll() is None:
                        self.mount_proc.terminate()
                except EnvironmentError:
                    time.sleep(0.1)
                else:
                    break
            else:
                if self.mount_proc.poll() is None:
                    self.mount_proc.terminate()
            self.temp_fs.close()

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


text:
/
#endregion

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Xml.Serialization;

namespace TVA.Historian.Services
{
    #region [ Enumerations ]

    /// <summary>
    /// Indicates the format of <see cref="Object"/> serialization or deserialization.
    /// </summary>
    public enum SerializationFormat
    {
        /// <summary>
        /// <see cref="Object"/> is serialized or deserialized using <see cref="DataContractJsonSerializer"/> to JSON (JavaScript Object Notation) format.
        /// </summary>
        Json,
        /// <summary>
        /// <see cref="Object"/> is serialized or deserialized using <see cref="XmlSerializer"/> to ASMX (.NET Web Service) compatible XML (eXtensible Markup Language) format.
        /// </summary>
        PoxAsmx,
        /// <summary>
        /// <see cref="Object"/> is serialized or deserialized using <see cref="DataContractSerializer"/> to REST (Representational State Transfer) compatible XML (eXtensible Markup Language) format.
        /// </summary>
        PoxRest
    }

    #endregion

    /// <summary>
    /// Helper class to serialize and deserialize <see cref="Object"/>s to web service compatible <see cref="SerializationFormat"/>s.
    /// </summary>
    /// <seealso cref="SerializationFormat"/>
    public static class Serialization
    {
        #region [ Methods ]

        /// <summary>
        /// Serializes an <see cref="Object"/>.
        /// </summary>
        /// <typeparam name="T"><see cref="Type"/> of the <paramref name="serializableObject"/>.</typeparam>
        /// <param name="serializedOutput"><see cref="Stream"/> where the <paramref name="serializableObject"/> is to be serialized.</param>
        /// <param name="serializableObject"><see cref="Object"/> to be serialized.</param>
        /// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializableObject"/> is to be serialized.</param>
        /// <exception cref="ArgumentNullException"><paramref name="serializedOutput"/> or <paramref name="serializableObject"/> is null.</exception>
        /// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
        public static void Serialize<T>(ref Stream serializedOutput, T serializableObject, SerializationFormat serializationFormat)
        {
            if (serializedOutput == null)
                throw new ArgumentNullException("serializedOutput");

            if (serializableObject == null)
                throw new ArgumentNullException("serializableObject");

            // Serialize object to the provided stream.
            if (serializationFormat == SerializationFormat.PoxAsmx)
            {
                // Serialize to ASMX XML format.
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(serializedOutput, serializableObject);
            }
            else if (serializationFormat == SerializationFormat.PoxRest)
            {
                // Serialize to REST XML format.
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                serializer.WriteObject(serializedOutput, serializableObject);
            }
            else if (serializationFormat == SerializationFormat.Json)
            {
                // Serialize to JSON format.
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(serializedOutput, serializableObject);
            }
            else
            {
                // Serialization format is not supported.
                throw new NotSupportedException(string.Format("{0} serialization is not supported", serializationFormat));
            }

            // Seek to the beginning of the serialized output stream.
            serializedOutput.Position = 0;
        }

        /// <summary>
        /// Deserializes a serialized <see cref="Object"/>.
        /// </summary>
        /// <typeparam name="T"><see cref="Type"/> of the deserialized <see cref="Object"/> to be returned.</typeparam>
        /// <param name="serializedObject"><see cref="Stream"/> contaning the serialized <see cref="Object"/> that is to be deserialized.</param>
        /// <param name="serializationFormat"><see cref="SerializationFormat"/> in which the <paramref name="serializedObject"/> was serialized.</param>
        /// <returns>The deserialized <see cref="Object"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="serializedObject"/> is null.</exception>
        /// <exception cref="NotSupportedException">Specified <paramref name="serializationFormat"/> is not supported.</exception>
        public static T Deserialize<T>(Stream serializedObject, SerializationFormat serializationFormat)
        {
            if (serializedObject == null)
                throw new ArgumentNullException("serializedObject");

            // Deserialize the serialized object.
            T deserializedObject;
            if (serializationFormat == SerializationFormat.PoxAsmx)
            {
                // Object was serialized to ASMX XML format.
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                deserializedObject = (T)serializer.Deserialize(serializedObject);
            }
            else if (serializationFormat == SerializationFormat.PoxRest)
            {
                // Object was serialized to REST XML format.
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                deserializedObject = (T)serializer.ReadObject(serializedObject);
            }
            else if (serializationFormat == SerializationFormat.Json)
            {
                // Object was serialized to JSON format.
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
                deserializedObject = (T)serializer.ReadObject(serializedObject);
            }
            else
            {
                // Serialization format is not supported.
                throw new NotSupportedException(string.Format("{0} serialization is not supported", serializationFormat));
            }

            return deserializedObject;
        }

        #endregion
    }
}


text:
{-# OPTIONS_GHC -Wall -fno-warn-warnings-deprecations   #-}
{-# LANGUAGE DoRec                           #-}
{-# LANGUAGE MultiParamTypeClasses  #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances      #-}

-- | The class definition of a Tardis,
-- as well as a few straightforward combinators
-- based on its primitives.
--
-- See Control.Monad.Tardis for the general explanation
-- of what a Tardis is and how to use it.
module Control.Monad.Tardis.Class
  ( -- * The MonadTardis class
    MonadTardis (..)
    -- * Composite Tardis operations
  , modifyForwards
  , modifyBackwards
  , getsPast
  , getsFuture
  ) where

import Control.Applicative
import Control.Monad.Fix

import qualified Control.Monad.Trans.Tardis as T

-- | A Tardis is parameterized by two state streams:
-- a 'backwards-traveling' state and a 'forwards-traveling' state.
-- This library consistently puts the backwards-traveling state first
-- whenever the two are seen together.
--
-- Minimal complete definition:
-- ("tardis") or
-- ("getPast", "getFuture", "sendPast", and "sendFuture").
class (Applicative m, MonadFix m) => MonadTardis bw fw m | m -> bw, m -> fw where
  -- | Retrieve the current value of the 'forwards-traveling' state,
  -- which therefore came forwards from the past.
  -- You can think of forwards-traveling state as traveling
  -- 'downwards' through your code.
  getPast    :: m fw

  -- | Retrieve the current value of the 'backwards-traveling' state,
  -- which therefore came backwards from the future.
  -- You can think of backwards-traveling state as traveling
  -- 'upwards' through your code.
  getFuture  :: m bw

  -- | Set the current value of the 'backwards-traveling' state,
  -- which will therefore be sent backwards to the past.
  -- This value can be retrieved by calls to "getFuture"
  -- located 'above' the current location,
  -- unless it is overwritten by an intervening "sendPast".
  sendPast   :: bw -> m ()

  -- | Set the current value of the 'forwards-traveling' state,
  -- which will therefore be sent forwards to the future.
  -- This value can be retrieved by calls to "getPast"
  -- located 'below' the current location,
  -- unless it is overwritten by an intervening "sendFuture".
  sendFuture :: fw -> m ()

  getPast        = tardis $ \ ~(bw, fw)  -> (fw, (bw, fw))
  getFuture      = tardis $ \ ~(bw, fw)  -> (bw, (bw, fw))
  sendPast   bw' = tardis $ \ ~(_bw, fw) -> ((), (bw', fw))
  sendFuture fw' = tardis $ \ ~(bw, _fw) -> ((), (bw, fw'))

  -- | A Tardis is merely a pure state transformation.
  tardis :: ((bw, fw) -> (a, (bw, fw))) -> m a
  tardis f = do
    rec
      let (a, (future', past')) = f (future, past)
      sendPast future'
      past <- getPast
      future <- getFuture
      sendFuture past'
    return a

-- | Modify the forwards-traveling state
-- as it passes through from past to future.
modifyForwards :: MonadTardis bw fw m => (fw -> fw) -> m ()
modifyForwards f = getPast >>= sendFuture . f

-- | Modify the backwards-traveling state
-- as it passes through from future to past.
modifyBackwards :: MonadTardis bw fw m => (bw -> bw) -> m ()
modifyBackwards f = do
  rec
    sendPast (f x)
    x <- getFuture
  return ()

-- | Retrieve a specific view of the forwards-traveling state.
getsPast :: MonadTardis bw fw m => (fw -> a) -> m a
getsPast f = f <$> getPast

-- | Retrieve a specific view of the backwards-traveling state.
getsFuture :: MonadTardis bw fw m => (bw -> a) -> m a
getsFuture f = f <$> getFuture

instance MonadFix m => MonadTardis bw fw (T.TardisT bw fw m) where
  getPast    = T.getPast
  getFuture  = T.getFuture
  sendPast   = T.sendPast
  sendFuture = T.sendFuture
  tardis     = T.tardis


text:
"""
This provides an example for asking a manual question without using human strings.

It uses the Computer Name and Folder Contents sensors.

The second sensor has a single parameter, folderPath, with a value of 'c:\Program Files'.

The second sensor also has 3 sensor filter options that set the max data age to 3600 seconds, does NOT ignore case, and treats all values as string.

There is also a question filter supplied that limits the rows that are displayed to computers that match an Operating System that contains Windows, and has 3 question filter options supplied that set the max data age to 3600 seconds, does NOT ignore case, and uses 'and' to join all question filters.
"""
# import the basic python packages we need
import os
import sys
import tempfile
import pprint
import traceback

# disable python from generating a .pyc file
sys.dont_write_bytecode = True

# change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API
pytan_loc = "~/gh/pytan"
pytan_static_path = os.path.join(os.path.expanduser(pytan_loc), 'lib')

# Determine our script name, script dir
my_file = os.path.abspath(sys.argv[0])
my_dir = os.path.dirname(my_file)

# try to automatically determine the pytan lib directory by assuming it is in '../../lib/'
parent_dir = os.path.dirname(my_dir)
pytan_root_dir = os.path.dirname(parent_dir)
lib_dir = os.path.join(pytan_root_dir, 'lib')

# add pytan_loc and lib_dir to the PYTHONPATH variable
path_adds = [lib_dir, pytan_static_path]
[sys.path.append(aa) for aa in path_adds if aa not in sys.path]

# import pytan
import pytan

# create a dictionary of arguments for the pytan handler
handler_args = {}

# establish our connection info for the Tanium Server
handler_args['username'] = "Administrator"
handler_args['password'] = "Tanium2015!"
handler_args['host'] = "10.0.1.240"
handler_args['port'] = "443"  # optional
handler_args['trusted_certs'] = "certs"

# optional, level 0 is no output except warnings/errors
# level 1 through 12 are more and more verbose
handler_args['loglevel'] = 1

# optional, use a debug format for the logging output (uses two lines per log entry)
handler_args['debugformat'] = False

# optional, this saves all response objects to handler.session.ALL_REQUESTS_RESPONSES
# very useful for capturing the full exchange of XML requests and responses
handler_args['record_all_requests'] = True

# instantiate a handler using all of the arguments in the handler_args dictionary
print "...CALLING: pytan.handler() with args: {}".format(handler_args)
handler = pytan.Handler(**handler_args)

# print out the handler string
print "...OUTPUT: handler string: {}".format(handler)

# setup the arguments for the handler() class
kwargs = {}
kwargs["question_filter_defs"] = [{u'filter': {u'not_flag': 0,
              u'operator': u'RegexMatch',
              u'value': u'.*Windows.*'},
  u'name': u'Operating System'}]
kwargs["sensor_defs"] = [u'Computer Name',
 {u'filter': {u'not_flag': 0,
              u'operator': u'RegexMatch',
              u'value': u'.*Shared.*'},
  u'name': u'Folder Contents',
  u'options': {u'ignore_case_flag': 0,
               u'max_age_seconds': 3600,
               u'value_type': u'string'},
  u'params': {u'folderPath': u'C:\\Program Files'}}]
kwargs["question_option_defs"] = {u'and_flag': 0, u'ignore_case_flag': 0, u'max_age_seconds': 3600}
kwargs["qtype"] = u'_manual'

print "...CALLING: handler.ask with args: {}".format(kwargs)
response = handler.ask(**kwargs)

print "...OUTPUT: Type of response: ", type(response)

print "...OUTPUT: Pretty print of response:"
print pprint.pformat(response)

print "...OUTPUT: Equivalent Question if it were to be asked in the Tanium Console: "
print response['question_object'].query_text

if response['question_results']:
    # call the export_obj() method to convert response to CSV and store it in out
    export_kwargs = {}
    export_kwargs['obj'] = response['question_results']
    export_kwargs['export_format'] = 'csv'

    print "...CALLING: handler.export_obj() with args {}".format(export_kwargs)
    out = handler.export_obj(**export_kwargs)

    # trim the output if it is more than 15 lines long
    if len(out.splitlines()) > 15:
        out = out.splitlines()[0:15]
        out.append('..trimmed for brevity..')
        out = '\n'.join(out)

    print "...OUTPUT: CSV Results of response: "
    print out

'''STDOUT from running this:
...CALLING: pytan.handler() with args: {'username': 'Administrator', 'record_all_requests': True, 'loglevel': 1, 'debugformat': False, 'host': '10.0.1.240', 'password': 'Tanium2015!', 'port': '443'}
...OUTPUT: handler string: PyTan v2.1.4 Handler for Session to 10.0.1.240:443, Authenticated: True, Platform Version: 6.5.314.4301
...CALLING: handler.ask with args: {'qtype': u'_manual', 'sensor_defs': [u'Computer Name', {u'filter': {u'operator': u'RegexMatch', u'not_flag': 0, u'value': u'.*Shared.*'}, u'params': {u'folderPath': u'C:\\Program Files'}, u'name': u'Folder Contents', u'options': {u'ignore_case_flag': 0, u'max_age_seconds': 3600, u'value_type': u'string'}}], 'question_option_defs': {u'ignore_case_flag': 0, u'max_age_seconds': 3600, u'and_flag': 0}, 'question_filter_defs': [{u'filter': {u'operator': u'RegexMatch', u'not_flag': 0, u'value': u'.*Windows.*'}, u'name': u'Operating System'}]}
2015-09-14 20:15:07,346 INFO     pytan.pollers.QuestionPoller: ID 812: Reached Threshold of 99% (3 of 3)
...OUTPUT: Type of response:  <type 'dict'>
...OUTPUT: Pretty print of response:
{'poller_object': <pytan.pollers.QuestionPoller object at 0x10c433a90>,
 'poller_success': True,
 'question_object': <taniumpy.object_types.question.Question object at 0x10c433e10>,
 'question_results': <taniumpy.object_types.result_set.ResultSet object at 0x10c44b5d0>}
...OUTPUT: Equivalent Question if it were to be asked in the Tanium Console:
Get Computer Name and Folder Contents[C:\Program Files] containing "Shared" matching case from all machines with Operating System containing "Windows" matching case
...CALLING: handler.export_obj() with args {'export_format': 'csv', 'obj': <taniumpy.object_types.result_set.ResultSet object at 0x10c44b5d0>}
...OUTPUT: CSV Results of response:
Computer Name,Folder Contents[C:\Program Files]
WIN-6U71ED4M23D,[current result unavailable]
TPT1.pytanlab.com,[current result unavailable]

'''

'''STDERR from running this:

'''


text:
module.exports =
[{"site":"https://www.hackster.io/vr/projects","reason":"an interested and ecelectic collections of VR projects"}]


text:
layout: home
---
# Welcome

"The goal is to reach a level of functionality that breeds it's own aesthetic" - Casey  Neistat

My blog posts are cringy...but I won't delete them because future Yazan needs to learn from his humiliation!

*The site is still under construction*


text:
package main

import (
	"flag"
	"log"
	"runtime"
	"time"

	"github.com/nats-io/go-nats"
)

// NOTE: Can test with demo servers.
// nats-rply -s demo.nats.io <subject> <response>
// nats-rply -s demo.nats.io:4443 <subject> <response> (TLS version)

func usage() {
	log.Printf("Usage: nats-rply [-s server] [-creds file] [-t] <subject> <response>\n")
	flag.PrintDefaults()
}

func printMsg(m *nats.Msg, i int) {
	log.Printf("[#%d] Received on [%s]: '%s'\n", i, m.Subject, string(m.Data))
}

func main() {
	var urls = flag.String("s", nats.DefaultURL, "The nats server URLs (separated by comma)")
	var userCreds = flag.String("creds", "", "User Credentials File")
	var showTime = flag.Bool("t", false, "Display timestamps")

	log.SetFlags(0)
	flag.Usage = usage
	flag.Parse()

	args := flag.Args()
	if len(args) < 2 {
		usage()
	}

	// Connect Options.
	opts := []nats.Option{nats.Name("NATS Sample Responder")}
	opts = setupConnOptions(opts)

	// Use UserCredentials
	if *userCreds != "" {
		opts = append(opts, nats.UserCredentials(*userCreds))
	}

	// Connect to NATS
	nc, err := nats.Connect(*urls, opts...)
	if err != nil {
		log.Fatal(err)
	}

	subj, reply, i := args[0], args[1], 0

	nc.Subscribe(subj, func(msg *nats.Msg) {
		i++
		printMsg(msg, i)
		nc.Publish(msg.Reply, []byte(reply))
	})
	nc.Flush()

	if err := nc.LastError(); err != nil {
		log.Fatal(err)
	}

	log.Printf("Listening on [%s]", subj)
	if *showTime {
		log.SetFlags(log.LstdFlags)
	}

	runtime.Goexit()
}

func setupConnOptions(opts []nats.Option) []nats.Option {
	totalWait := 10 * time.Minute
	reconnectDelay := time.Second

	opts = append(opts, nats.ReconnectWait(reconnectDelay))
	opts = append(opts, nats.MaxReconnects(int(totalWait/reconnectDelay)))
	opts = append(opts, nats.DisconnectHandler(func(nc *nats.Conn) {
		log.Printf("Disconnected: will attempt reconnects for %.0fm", totalWait.Minutes())
	}))
	opts = append(opts, nats.ReconnectHandler(func(nc *nats.Conn) {
		log.Printf("Reconnected [%s]", nc.ConnectedUrl())
	}))
	opts = append(opts, nats.ClosedHandler(func(nc *nats.Conn) {
		log.Fatal("Exiting, no servers available")
	}))
	return opts
}