text:
(function() {
  var _class_instance_ChatController, _class_instance_MessageQueue, chatApp, create_file_message_to_me, create_message_from_me, create_message_to_me, getRandomHexString, log, mainFunction, onDocumentReady, startUpWithWebChannel,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

  startUpWithWebChannel = function() {
    return new QWebChannel(qt.webChannelTransport, function(channel) {
      return mainFunction(channel.objects.chat);
    });
  };

  mainFunction = function(chat) {
    var onContactsLoaded, onServerConnect, onServerError, onUserAdded, onUserChosen, onUserFileReceived, onUserMessageReceived;
    window.chat = chat;
    onUserMessageReceived = function(username, message) {
      return create_message_to_me({
        contact: username,
        message: message
      });
    };
    onUserFileReceived = function(username, message) {
      return create_file_message_to_me({
        contact: username,
        message: message
      });
    };
    onUserChosen = function() {
      var username;
      username = jQuery('#other-username').val();
      chat.connectToUser(username);
      return jQuery('#chatbox').show();
    };
    onUserAdded = function(username) {
      _class_instance_MessageQueue.$publish('add-contact', username);
      return jQuery('#chatbox').show();
    };
    onContactsLoaded = function(contactsString) {
      var contact, contacts, i, len, results;
      contacts = contactsString.split('|');
      results = [];
      for (i = 0, len = contacts.length; i < len; i++) {
        contact = contacts[i];
        results.push(onUserAdded(contact));
      }
      return results;
    };
    onServerConnect = function() {
      console.log('Connected');
      return jQuery('#submit-user-button').click(function() {
        var my_user_name, my_user_password;
        console.log('on login button clicked');
        my_user_name = jQuery('#username').val();
        my_user_password = jQuery('#password').val();
        chat.chooseUserName(my_user_name, my_user_password);
        jQuery('#userbox').hide();
        jQuery('#submit-other-user-button').click(onUserChosen);
        chat.connectionToUserEstablished.connect(onUserAdded);
        chat.contactsLoaded.connect(onContactsLoaded);
        chat.receivedUserMessage.connect(onUserMessageReceived);
        chat.receivedUserFile.connect(onUserFileReceived);
        return chat.loadContacts();
      });
    };
    onServerError = function(error) {
      return console.log(error);
    };
    chat.connected.connect(onServerConnect);
    chat.error.connect(onServerError);
    chat.connectToServer(window.CHAT_SERVER_URL, 8888);
    console.log('connected to the server');
    return jQuery('#chatbox').hide();
  };

  onDocumentReady = function() {
    return startUpWithWebChannel();
  };

  jQuery(document).ready(onDocumentReady);

  create_message_from_me = function(message) {
    return _class_instance_MessageQueue.$publish('new-message-from-me', message);
  };

  create_message_to_me = function(message) {
    return _class_instance_MessageQueue.$publish('new-message-from-other', message);
  };

  create_file_message_to_me = function(message) {
    return _class_instance_MessageQueue.$publish('new-file-from-other', message);
  };

  chatApp = angular.module('chatApp', []);

  chatApp.config([
    '$compileProvider', function($compileProvider) {
      $compileProvider.aHrefSanitizationWhitelist(/^\s*(stream):/);
      return $compileProvider.imgSrcSanitizationWhitelist(/^\s*(stream):/);
    }
  ]);

  _class_instance_MessageQueue = null;

  chatApp.factory('MessageQueue', [
    function() {
      var MessageQueue;
      MessageQueue = (function() {
        MessageQueue.prototype._channels = {};

        function MessageQueue() {

          /*
           */
        }

        MessageQueue.prototype.$subscribe = function(channel, subscriber) {

          /*
           */
          if (!this._channels.hasOwnProperty(channel)) {
            this._channels[channel] = [];
          }
          return this._channels[channel].push(subscriber);
        };

        MessageQueue.prototype.$publish = function(channel, message) {

          /*
           */
          var i, len, ref, results, subscriber;
          if (this._channels.hasOwnProperty(channel)) {
            ref = this._channels[channel];
            results = [];
            for (i = 0, len = ref.length; i < len; i++) {
              subscriber = ref[i];
              results.push(subscriber(message));
            }
            return results;
          }
        };

        MessageQueue.$instance = function() {

          /*
           */
          if (_class_instance_MessageQueue == null) {
            _class_instance_MessageQueue = new MessageQueue();
          }
          return _class_instance_MessageQueue;
        };

        return MessageQueue;

      })();
      return MessageQueue.$instance();
    }
  ]);

  log = function(message) {
    return jQuery('#message-board').append("<span>" + message + "</span>");
  };

  getRandomHexString = function() {

    /*
     Generates random hex number string

     @return {String}
     */
    return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
  };

  _class_instance_ChatController = null;

  chatApp.controller('ChatController', [
    '$rootScope', '$scope', '$sce', 'MessageQueue', function($rootScope, $scope, $sce, MessageQueue) {
      var ChatContact, ChatController, ChatMessage, controller;
      ChatMessage = (function() {
        function ChatMessage(message, from_me, from_contact, is_file) {

          /*
           */
          this.DATA_TYPES = {
            images: ['jpg', 'jpeg', 'png', 'gif'],
            audios: ['mp3'],
            movies: ['mp4', 'webm']
          };
          this.message = message;
          this.is_from_me = from_me;
          this.is_from_contact = from_contact;
          if (this.is_from_me) {
            this.message_classes = ['my-message', 'blue', 'lighten-3'];
          } else if (this.is_from_contact) {
            this.message_classes = ['partner-message', 'blue', 'darken-1'];
          }
          if (is_file) {
            this.message_type = this.getType();
          } else {
            this.message_type = 'text';
          }
        }

        ChatMessage.prototype.getType = function() {

          /*
           */
          if (this._isType('images', this.message)) {
            return 'image';
          } else if (this._isType('audios', this.message)) {
            return 'audio';
          } else if (this._isType('movies', this.message)) {
            return 'movie';
          } else {
            return 'downloadable';
          }
        };

        ChatMessage.prototype.link = function() {

          /*
           */
          return this.message;
        };

        ChatMessage.prototype.image = function() {

          /*
           */
          return this.message;
        };

        ChatMessage.prototype.audio = function() {

          /*
           */
          return $sce.trustAsResourceUrl(this.message);
        };

        ChatMessage.prototype.movie = function() {

          /*
           */
          return $sce.trustAsResourceUrl(this.message);
        };

        ChatMessage.prototype.text = function() {

          /*
           */
          return this.message;
        };

        ChatMessage.prototype._isType = function(type_name, data_string) {

          /*
           */
          var i, len, ref, type;
          ref = this.DATA_TYPES[type_name];
          for (i = 0, len = ref.length; i < len; i++) {
            type = ref[i];
            if (data_string.toLowerCase().indexOf("." + type) > -1) {
              return true;
            }
          }
          return false;
        };

        return ChatMessage;

      })();
      ChatContact = (function() {
        function ChatContact(username1) {
          this.username = username1;

          /*
           */
          this.messages = [];
          this.active = true;
        }

        return ChatContact;

      })();
      ChatController = (function() {
        ChatController.prototype.contacts = [];

        ChatController.prototype.current_contact = null;

        ChatController.prototype.current_messages = [];

        ChatController.prototype.current_typed_message = '';

        function ChatController() {
          this.onContactAdded = bind(this.onContactAdded, this);
          this.onFileFromContact = bind(this.onFileFromContact, this);
          this.onMessageFromContact = bind(this.onMessageFromContact, this);
          this.onMessageFromMe = bind(this.onMessageFromMe, this);
          this.onUploadFile = bind(this.onUploadFile, this);
          this.onMessageSend = bind(this.onMessageSend, this);

          /*
           */
          this.contacts = [];
          this.current_messages = [];
          this.is_file_chosen = false;
        }

        ChatController.prototype.onContactChanged = function(contact) {

          /*
           */
          var i, j, len, len1, message, ref, ref1;
          if (this.current_contact === contact) {
            return;
          }
          this.current_contact.messages.length = 0;
          ref = this.current_messages;
          for (i = 0, len = ref.length; i < len; i++) {
            message = ref[i];
            this.current_contact.messages.push(message);
          }
          this.current_contact.active = false;
          this.current_contact = contact;
          this.current_messages.length = 0;
          ref1 = contact.messages;
          for (j = 0, len1 = ref1.length; j < len1; j++) {
            message = ref1[j];
            this.current_messages.push(message);
          }
          return this.current_contact.active = true;
        };

        ChatController.prototype.onMessageSend = function() {

          /*
           */
          var message;
          message = this.current_typed_message;
          this.current_typed_message.length = 0;
          this.current_typed_message = '';
          chat.sendMessageToUser(this.current_contact.username, message);
          return create_message_from_me(message);
        };

        ChatController.prototype.onUploadFile = function() {

          /*
           */
          var $file_input;
          $file_input = jQuery('#file-input-button');
          $file_input.change((function(_this) {
            return function() {
              var files, reader;
              console.log('file chosen');
              reader = new FileReader();
              reader.onload = function() {
                var url;
                url = reader.result;
                console.log(url);
                return chat.sendMessageToUser(_this.current_contact.username, url);
              };
              files = $file_input[0].files;
              return reader.readAsDataURL(files[0]);
            };
          })(this));
          return $file_input.click();
        };

        ChatController.prototype.onMessageFromMe = function(message) {

          /*
           */
          this.current_messages.push(new ChatMessage(message, true, false));
          return $scope.$apply();
        };

        ChatController.prototype.onMessageFromContact = function(message) {

          /*
           */
          var contact, i, len, message_text, ref, username;
          username = message.contact;
          message_text = message.message;
          if (this.current_contact.username === username) {
            this.current_messages.push(new ChatMessage(message_text, false, true, false));
          } else {
            ref = this.contacts;
            for (i = 0, len = ref.length; i < len; i++) {
              contact = ref[i];
              if (contact.username === username) {
                contact.messages.push(new ChatMessage(message_text, false, true, false));
              }
            }
          }
          return $scope.$apply();
        };

        ChatController.prototype.onFileFromContact = function(message) {

          /*
           */
          var contact, i, len, message_text, ref, username;
          username = message.contact;
          message_text = message.message;
          if (this.current_contact.username === username) {
            this.current_messages.push(new ChatMessage(message_text, false, true, true));
          } else {
            ref = this.contacts;
            for (i = 0, len = ref.length; i < len; i++) {
              contact = ref[i];
              if (contact.username === username) {
                contact.messages.push(new ChatMessage(message_text, false, true, true));
              }
            }
          }
          return $scope.$apply();
        };

        ChatController.prototype.onContactAdded = function(username) {

          /*
           */
          var contact, i, len, ref;
          ref = this.contacts;
          for (i = 0, len = ref.length; i < len; i++) {
            contact = ref[i];
            if (contact.username === username) {
              return;
            } else {
              contact.active = false;
            }
          }
          contact = new ChatContact(username);
          this.contacts.push(contact);
          this.current_contact = contact;
          return $scope.$apply();
        };

        ChatController.$instance = function() {

          /*
           */
          if (_class_instance_ChatController == null) {
            _class_instance_ChatController = new ChatController();
          }
          return _class_instance_ChatController;
        };

        return ChatController;

      })();
      controller = ChatController.$instance();
      MessageQueue.$subscribe('add-contact', controller.onContactAdded);
      MessageQueue.$subscribe('new-message-from-me', controller.onMessageFromMe);
      MessageQueue.$subscribe('new-message-from-other', controller.onMessageFromContact);
      MessageQueue.$subscribe('new-file-from-other', controller.onFileFromContact);
      return controller;
    }
  ]);

}).call(this);

//# sourceMappingURL=app.js.map


text:
/* eslint-env mocha */

import assert from 'assert'
import getMilliseconds from './index'

describe('getMilliseconds', () => {
  it('returns the milliseconds of the given date', () => {
    const result = getMilliseconds(
      new Date(2012, 1 /* Feb */, 29, 11, 45, 5, 123)
    )
    assert(result === 123)
  })

  it('accepts a timestamp', () => {
    const result = getMilliseconds(
      new Date(2014, 3 /* Apr */, 2, 23, 30, 42, 500).getTime()
    )
    assert(result === 500)
  })

  it('returns NaN if the given date is invalid', () => {
    const result = getMilliseconds(new Date(NaN))
    assert(isNaN(result))
  })
})

redpajama_set_name: RedPajamaGithub


text:
from BaseObjects import BaseEDAPage
from EDA import eda_lex_locators
from cumulusci.robotframework.pageobjects import BasePage
from cumulusci.robotframework.pageobjects import pageobject
import time

@pageobject("System", "HEDA_Settings")
class SystemSettingsPage(BaseEDAPage, BasePage):

    def _is_current_page(self):
        """
            Verify we are on the EDA Settings page for System
            by verifying the HEDA Settings URL and the System tab
        """
        location = "/lightning/n/{}{}".format(self.eda.get_eda_namespace_prefix(), self._object_name)
        self.selenium.location_should_contain(location)

        locator_tab = eda_lex_locators["eda_settings"]["tab"].format("System")
        self.selenium.wait_until_page_contains_element(
            locator_tab,
            error=f"System tab with locator '{locator_tab}' is not available on the page"
        )

    def update_system_dropdown_value(self,**kwargs):
        """ This method will update the drop down field value passed in keyword arguments
            Pass the expected value to be set in the drop down field from the tests
        """
        for field,value in kwargs.items():
            locator = eda_lex_locators["eda_settings_relationships"]["dropdown_value"].format(field,value)
            self.selenium.wait_until_page_contains_element(locator,
                                                error=f"'{value}' as dropdown value in '{field}' field is not available ")
            self.selenium.click_element(locator)

    def enter_account_name_format(self,**kwargs):
        """ This method will enter the account name format after selecting other in the drop down
            Pass the expected value to be set in the input field as arguments
        """
        for field,value in kwargs.items():
            locator = eda_lex_locators["eda_settings_system"]["other_accname_format"].format(field)
            self.selenium.wait_until_page_contains_element(locator,
                                                error=f"'{field}' field is not available ")
            self.selenium.clear_element_text(locator)
            self.selenium.get_webelement(locator).send_keys(value)

    def select_recipient_type_value(self,**kwargs):
        """ This method will select the drop down field value passed in keyword arguments
            Pass the expected value to be selected in the drop down field from the tests
        """
        for field,value in kwargs.items():
            locator = eda_lex_locators["eda_settings_system"]["recipient_type_value"].format(field,value)
            self.selenium.wait_until_page_contains_element(locator,
                                                error=f"'{value}' as dropdown value in '{field}' field is not available ")
            self.selenium.click_element(locator)

    def select_recipient(self,**kwargs):
        """ This method will select the lookup result for the recipient notification
            Pass the expected value to be selected as arguments
        """
        for field,value in kwargs.items():
            locator = eda_lex_locators["eda_settings_system"]["recipient_name"].format(field)
            self.selenium.wait_until_page_contains_element(locator,
                                                error=f"'{field}' field is not available ")
            self.selenium.clear_element_text(locator)
            self.selenium.get_webelement(locator).send_keys(value)
            time.sleep(0.5)
            locator_lookup = eda_lex_locators["eda_settings_system"]["recipient_lookup"].format(value)
            self.selenium.wait_until_page_contains_element(locator_lookup,
                                                error=f"'{locator_lookup}'  is not available ")
            self.selenium.click_element(locator_lookup)

    def verify_admin_toast_message(self, value):
        """ Verifies the admin  toast message """
        locator = eda_lex_locators["eda_settings_system"]["admin_success_toast"]
        time.sleep(0.5) # This wait is needed for the toast message validation
        self.selenium.wait_until_page_contains_element(locator, timeout=60)
        actual_value = self.selenium.get_webelement(locator).text
        self.builtin.log("Toast message :" + actual_value)
        if not str(value).lower() == str(actual_value).lower() :
                raise Exception (f"Expected {value} but it displayed {actual_value}")

    def verify_household_toast_message(self, value):
        """ Verifies the household specific toast message """
        locator = eda_lex_locators["eda_settings_system"]["hh_success_toast"]
        time.sleep(0.5) # This wait is needed for the toast message validation
        self.selenium.wait_until_page_contains_element(locator, timeout=60)
        actual_value = self.selenium.get_webelement(locator).text
        self.builtin.log("Toast message :" + actual_value)
        if not str(value).lower() == str(actual_value).lower() :
                raise Exception (f"Expected {value} but it displayed {actual_value}")

    def verify_system_dropdown_value(self,**kwargs):
        """ This method validates the dropdown value for the field passed in kwargs
            Pass the field name and expected value to be verified from the tests using
            keyword arguments
        """
        for field,expected_value in kwargs.items():
            locator = eda_lex_locators["eda_settings_system"]["other_dropdown_value"].format(field,expected_value)
            self.selenium.page_should_contain_element(locator)
            self.selenium.wait_until_element_is_visible(locator,
                                                error= "Element is not displayed for the user")
            actual_value = self.selenium.get_webelement(locator).text
            if not str(expected_value).lower() == str(actual_value).lower() :
                raise Exception (f"Dropdown value in {field} is {actual_value} but it should be {expected_value}")


text:
from JumpScale import j

import mimeparse
import mimetypes

class PortalRest():

    def __init__(self, webserver):
        self.ws=webserver

    def validate(self, auth, ctx):
        if ctx.params == "":
            msg = 'No parameters given to actormethod.'
            ctx.start_response('400 Bad Request', [])
            return False, msg
        if auth and ctx.env['beaker.session']['user'] == 'guest':
            msg = 'NO VALID AUTHORIZATION KEY GIVEN, use get param called key (check key probably auth error).'
            ctx.start_response('401 Unauthorized', [])
            return False, msg

        paramCriteria = self.ws.routes[ctx.path][1]
        paramOptional = self.ws.routes[ctx.path][3]

        for key in paramCriteria.keys():
            criteria = paramCriteria[key]
            if key not in ctx.params:
                if key in paramOptional:
                    # means is optional
                    ctx.params[key] = None
                else:
                    ctx.start_response('400 Bad Request', [])
                    message = 'get param with name:%s is missing.' % key
                    return False, message
            elif (criteria != "" and ctx.params[key] == "")\
                    or (criteria != "" and not j.codetools.regex.matchAllText(criteria, ctx.params[key])):
                ctx.start_response('400 Bad Request', [])
                msg = 'value of param %s not correct needs to comform to regex %s' % (key, criteria)
                return False, msg
        return True, ""

    def restPathProcessor(self, path):
        """
        Function which parse a path, returning True or False depending on
        successfull parsing, a error message and a dict of parameters.
        When successfull the params dict contains the path elements otherwise it
        contains if provided the actorname  and appname.
        """
        j.logger.log("Process path %s" % path, 9)
        params = {}
        while path != "" and path[0] == "/":
            path = path[1:]
        while path != "" and path[-1] == "/":
            path = path[:-1]
        if path.strip() == "":
            return (False, "Bad input path was empty. Format of url need to be http://$ipaddr/rest/$appname/$actorname/$actormetho?...", {})
        paths = path.split("/")
        if len(paths) < 3:
            msginfo = "Format of url need to be http://$ipaddr/rest/$appname/$actorname/$actormethod?...\n\n"
            if len(paths) > 0:
                appname = paths[0]
            else:
                appname = ""
                actor = ""
            if len(paths) > 1:
                actor = paths[1]
            else:
                actor = ""
            params["appname"] = appname
            params["actorname"] = actor
            return (False, msginfo, params)
        params["paths"] = paths
        return (True, "", params)

    def restRouter(self, env, start_response, path, paths, ctx, ext=False, routekey=None, human=False):
        """
        does validaton & authorization
        returns right route key
        """
        if not routekey:
            routekey = "%s_%s_%s" % (paths[0], paths[1], paths[2])
        # j.logger.log("Execute %s %s" % (env["REMOTE_ADDR"], routekey))
        routes = self.ws.routes
        if routekey not in routes:
            self.activateActor(paths[0], paths[1])

        if routekey not in routes:
            routekey="GET_%s"%routekey

        if routekey in routes:
            if human:
                ctx.fformat = "human"
            elif("format" not in ctx.params):
                ctx.fformat = routes[routekey][6]
            else:
                ctx.fformat = ctx.params["format"]
            ctx.path = routekey
            ctx.fullpath = path
            ctx.application = paths[0]
            ctx.actor = paths[1]
            ctx.method = paths[2]
            auth = routes[routekey][5]
            resultcode, msg = self.validate(auth, ctx) #validation & authorization (but user needs to be known)
            if resultcode == False:
                if human:
                    params = {}
                    params["error"] = "Incorrect Request: %s" % msg
                    params["appname"] = ctx.application
                    params["actorname"] = ctx.actor
                    params["method"] = ctx.method
                    page = self.ws.returnDoc(ctx, start_response, "system",
                                          "restvalidationerror", extraParams=params)
                    return (False, ctx, [str(page)])
                else:
                    return (False, ctx, msg)
            else:
                return (True, ctx, routekey)
        else:
            msg = "Could not find method, path was %s" % (path)
            appname = paths[0]
            actor = paths[1]
            contentType, data = self.ws.reformatOutput(ctx, msg, restreturn=not human)
            ctx.start_response("404 Not Found", [('Content-Type', contentType)])
            if human:
                page = self.getServicesInfo(appname, actor)
                return (False, ctx, self.ws.raiseError(ctx=ctx, msg=msg,msginfo=str(page)))
            else:
                contentType, data = self.ws.reformatOutput(ctx, msg, restreturn=False)
                return (False, ctx, data)

    def execute_rest_call(self, ctx, routekey, ext=False):
        routes = self.ws.routes
        try:
            method = routes[routekey][0]
            result = method(ctx=ctx, **ctx.params)
            return (True, result)
        except Exception as errorObject:
            eco = j.errorconditionhandler.parsePythonErrorObject(errorObject)
            msg = "Execute method %s failed." % (routekey)
            return (False, self.ws.raiseError(ctx=ctx, msg=msg, errorObject=eco))

    def processor_rest(self, env, start_response, path, human=True, ctx=False):
        """
        orignal rest processor (get statements)
        e.g. http://localhost/restmachine/system/contentmanager/notifySpaceModification?name=www_openvstorage&authkey=1234
        """
        if ctx == False:
            raise RuntimeError("ctx cannot be empty")
        try:
            j.logger.log("Routing request to %s" % path, 9)

            def respond(contentType, msg):
                # j.logger.log("Responding %s" % msg, 5)
                if contentType:
                    ctx.start_response('200 OK', [('Content-Type', contentType)])
                # print msg
                return msg

            success, msg, params = self.restPathProcessor(path)
            if not success:
                params["error"] = msg
                if human:
                    page = self.ws.returnDoc(ctx, start_response, "system", "rest",
                                          extraParams=params)
                    return [str(page)]
                else:
                    httpcode = "404 Not Found"
                    contentType, data = self.ws.reformatOutput(ctx, msg, restreturn=True)
                    ctx.start_response(httpcode, [('Content-Type', contentType)])
                    return data
            paths = params['paths']

            success, ctx, routekey = self.restRouter(env, start_response, path,
                                                   paths, ctx, human=human)
            if not success:
                #in this case routekey is really the errormsg
                return routekey

            success, result = self.execute_rest_call(ctx, routekey)
            if not success:
                return result

            if human:
                ctx.format = "json"
                params = {}
                params["result"] = result
                return [str(self.ws.returnDoc(ctx, start_response, "system", "restresult", extraParams=params))]
            else:
                contentType, result = self.ws.reformatOutput(ctx, result)
                return [respond(contentType, result)]
        except Exception as errorObject:
            eco = j.errorconditionhandler.parsePythonErrorObject(errorObject)
            if ctx == False:
                print "NO webserver context yet, serious error"
                eco.process()
                print eco
            else:
                return self.ws.raiseError(ctx, errorObject=eco)

    def processor_restext(self, env, start_response, path, human=True, ctx=False):

        """
        rest processer gen 2 (not used by the original get code)
        """

        if ctx == False:
            raise RuntimeError("ctx cannot be empty")
        try:
            j.logger.log("Routing request to %s" % path, 9)

            def respond(contentType, msg):
                if contentType:
                    start_response('200 OK', [('Content-Type', contentType)])
                return msg

            success, message, params = self.restPathProcessor(path)

            if not success:
                params["error"] = message
                if human:
                    page = self.ws.returnDoc(ctx, start_response, "system", "rest",
                                          extraParams=params)
                    return [str(page)]
                else:
                    return self.ws.raiseError(ctx, message)
            paths = params['paths']
            appname = paths[0]
            actor = paths[1]
            actorfunction = None
            subobject = False
            getfind = False
            getdatatables = False
            if len(ctx.params) > 0:
                if 'query' in ctx.params:
                    getfind = True
                elif 'datatables' in ctx.params:
                    getdatatables = True
            if len(paths) == 2:
                # we have only a actor function
                if 'function' in ctx.params:
                    actorfunction = ctx.params.pop('function')
            requestmethod = ctx.env['REQUEST_METHOD']
            if len(paths) > 2:
                modelgroup = paths[2]
            if len(paths) > 3:
                objectid = paths[3]
                ctx.params['id'] = objectid
                subobject = True
            if actorfunction:
                routekey = "%s_%s_%s_%s" % (requestmethod, appname, actor,
                                            actorfunction)
            else:
                if requestmethod == 'GET':
                    if subobject:
                        routekey = "%s_%s_%s_%s_get" % (requestmethod, appname, actor,
                                                        modelgroup)
                    elif getfind:
                        routekey = "%s_%s_%s_%s_find" % (requestmethod,
                                                         appname, actor, modelgroup)
                    elif getdatatables:
                        routekey = "%s_%s_%s_%s_datatables" % (requestmethod,
                                                               appname, actor, modelgroup)
                    else:
                        routekey = "%s_%s_%s_%s_list" % (requestmethod,
                                                         appname, actor, modelgroup)

                elif requestmethod == 'OPTIONS':
                    result = 'Allow: HEAD,GET,PUT,DELETE,OPTIONS'
                    contentType, result = self.ws.reformatOutput(ctx, result)
                    return respond(contentType, result)

                else:
                    routekey = "%s_%s_%s_%s" % (requestmethod,
                                                appname, actor, modelgroup)
            success, ctx, result = self.restRouter(env, start_response, path, paths, ctx, True, routekey, human)

            if not success:
                return result
            success, result = self.execute_rest_call(ctx, result, True)
            if not success:
                return result

            if human:
                ctx.format = "json"
                params = {}
                params["result"] = result
                return [str(self.ws.returnDoc(ctx, start_response, "system", "restresult", extraParams=params))]
            else:
                contentType, result = self.ws.reformatOutput(ctx, result)
                return respond(contentType, result)
        except Exception as errorObject:
            eco = j.errorconditionhandler.parsePythonErrorObject(errorObject)
            if ctx == False:
                print "NO webserver context yet, serious error"
                eco.process()
                print eco
            else:
                return self.ws.raiseError(ctx, errorObject=eco)

    def activateActor(self, appname, actor):
        if not "%s_%s" % (appname, actor) in self.ws.actors.keys():
            # need to activate
            try:
                result = self.ws.actorsloader.getActor(appname, actor)
            except Exception, e:
                eco = j.errorconditionhandler.parsePythonErrorObject(e)
                eco.process()
                print eco
                return False
            if result == None:
                # there was no actor
                return False

    # def _getActorInfoUrl(self, appname, actor):
    #     """
    #     used for during error show links to actor in browser
    #     """
    #     if actor == "":
    #         url = "/rest/%s/" % (appname)
    #     else:
    #         url = "/rest/%s/%s/" % (appname, actor)
    #     # url="go here for more info about actor %s in %s " % (url,actor,appname)
    #     return url


text:
<?php

namespace CodeGen\Functionality;

// Possibly the stupidest name for a class ever.
trait VisibilitySettable
{
	protected $visibility = 'public';

	public function setVisibility($visibility) {

		if (! in_array($visibility, array('public', 'protected', 'private'), true)) {
			throw new \InvalidArgumentException("Visibility must be 'public', 'protected', or 'private'");
		}

		$this->visibility = $visibility;

		return $this;
	}

	public function getVisibility() {
		return $this->visibility;
	}
}


text:
// Copyright 2000
// Association for Universities for Research in Astronomy, Inc.
// Observatory Control System, Gemini Telescopes Project.
// See the file LICENSE for complete details.
//
// $Id: IConfigProvider.java 4726 2004-05-14 16:50:12Z brighton $
//

package edu.gemini.spModel.data.config;

import java.io.Serializable;

/**
 * An interface that describes a possible interface between
 * an observation component or sequence component and a
 * configuration builder matched to that component.
 *

 * The interface describes one method which allows the
 * configuration builder to request a {@link ISysConfig}
 * from the component.
 *

 * The client can also set the ISysConfig to be used for an upcoming
 * configuration build.
 *
 * @see ISysConfig
 */
public interface IConfigProvider extends Serializable {
    /**
     * Gets the ISysConfig configuration of the component.
     */
    ISysConfig getSysConfig();

    /**
     * Allows an outside source to set the ISysConfig.
     */
    void setSysConfig(ISysConfig config);
}


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

<TITLE>
ObjDumpParserConstants
</TITLE>

<META NAME="keywords" CONTENT="avrora.syntax.objdump.ObjDumpParserConstants interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

avrora.syntax.objdump

Interface ObjDumpParserConstants

All Known Implementing Classes:
ObjDumpParser, ObjDumpParserTokenManager

public interface ObjDumpParserConstants

Field Summary

static int
ADC

static int
ADD

static int
ADDRESS

static int
ADIW

static int
AND

static int
ANDI

static int
ASR

static int
BCLR

static int
BIN_LITERAL

static int
BLD

static int
BRBC

static int
BRBS

static int
BRCC

static int
BRCS

static int
BREAK

static int
BREQ

static int
BRGE

static int
BRHC

static int
BRHS

static int
BRID

static int
BRIE

static int
BRLO

static int
BRLT

static int
BRMI

static int
BRNE

static int
BRPL

static int
BRSH

static int
BRTC

static int
BRTS

static int
BRVC

static int
BRVS

static int
BSET

static int
BST

static int
BYTE2

static int
BYTE3

static int
BYTE4

static int
CALL

static int
CBI

static int
CBR

static int
CHARACTER_LITERAL

static int
CLC

static int
CLH

static int
CLI

static int
CLN

static int
CLR

static int
CLS

static int
CLT

static int
CLV

static int
CLZ

static int
COM

static int
CP

static int
CPC

static int
CPI

static int
CPSE

static int
DEC

static int
DECIMAL_LITERAL

static int
DEFAULT

static int
DIGIT

static int
DOT_IDENTIFIER

static int
EICALL

static int
EIJMP

static int
ELPM

static int
EOF

static int
EOR

static int
EXP2

static int
FMUL

static int
FMULS

static int
FMULSU

static int
HEX_LITERAL

static int
HIGH

static int
HWRD

static int
ICALL

static int
IDENTIFIER

static int
IJMP

static int
IN

static int
IN_SINGLE_LINE_COMMENT

static int
INC

static int
INTEGER_LITERAL

static int
JMP

static int
LABEL

static int
LD

static int
LDD

static int
LDI

static int
LDS

static int
LETTER

static int
LMA

static int
LOG2

static int
LOW

static int
LPM

static int
LSL

static int
LSR

static int
LWRD

static int
MOV

static int
MOVW

static int
MUL

static int
MULS

static int
MULSU

static int
NEG

static int
NOP

static int
OCTAL_LITERAL

static int
OFFSET

static int
OR

static int
ORI

static int
OUT

static int
PAGE

static int
POP

static int
PROGRAM

static int
PUSH

static int
RCALL

static int
RET

static int
RETI

static int
RJMP

static int
ROL

static int
ROR

static int
SBC

static int
SBCI

static int
SBI

static int
SBIC

static int
SBIS

static int
SBIW

static int
SBR

static int
SBRC

static int
SBRS

static int
SEC

static int
SECTION

static int
SEH

static int
SEI

static int
SEN

static int
SER

static int
SES

static int
SET

static int
SEV

static int
SEZ

static int
SINGLE_LINE_COMMENT

static int
SIZE

static int
SLEEP

static int
SPM

static int
ST

static int
START

static int
STD

static int
STRING_LITERAL

static int
STS

static int
SUB

static int
SUBI

static int
SWAP

static java.lang.String[]
tokenImage

static int
TST

static int
VMA

static int
WDR

static int
WORD

Field Detail

EOF

public static final int EOF

See Also:
Constant Field Values

SINGLE_LINE_COMMENT

public static final int SINGLE_LINE_COMMENT

See Also:
Constant Field Values

INTEGER_LITERAL

public static final int INTEGER_LITERAL

See Also:
Constant Field Values

DECIMAL_LITERAL

public static final int DECIMAL_LITERAL

See Also:
Constant Field Values

HEX_LITERAL

public static final int HEX_LITERAL

See Also:
Constant Field Values

BIN_LITERAL

public static final int BIN_LITERAL

See Also:
Constant Field Values

OCTAL_LITERAL

public static final int OCTAL_LITERAL

See Also:
Constant Field Values

CHARACTER_LITERAL

public static final int CHARACTER_LITERAL

See Also:
Constant Field Values

STRING_LITERAL

public static final int STRING_LITERAL

See Also:
Constant Field Values

LOW

public static final int LOW

See Also:
Constant Field Values

HIGH

public static final int HIGH

See Also:
Constant Field Values

BYTE2

public static final int BYTE2

See Also:
Constant Field Values

BYTE3

public static final int BYTE3

See Also:
Constant Field Values

BYTE4

public static final int BYTE4

See Also:
Constant Field Values

LWRD

public static final int LWRD

See Also:
Constant Field Values

HWRD

public static final int HWRD

See Also:
Constant Field Values

PAGE

public static final int PAGE

See Also:
Constant Field Values

EXP2

public static final int EXP2

See Also:
Constant Field Values

LOG2

public static final int LOG2

See Also:
Constant Field Values

WORD

public static final int WORD

See Also:
Constant Field Values

START

public static final int START

See Also:
Constant Field Values

SECTION

public static final int SECTION

See Also:
Constant Field Values

PROGRAM

public static final int PROGRAM

See Also:
Constant Field Values

LABEL

public static final int LABEL

See Also:
Constant Field Values

SIZE

public static final int SIZE

See Also:
Constant Field Values

VMA

public static final int VMA

See Also:
Constant Field Values

LMA

public static final int LMA

See Also:
Constant Field Values

OFFSET

public static final int OFFSET

See Also:
Constant Field Values

ADD

public static final int ADD

See Also:
Constant Field Values

ADC

public static final int ADC

See Also:
Constant Field Values

ADIW

public static final int ADIW

See Also:
Constant Field Values

AND

public static final int AND

See Also:
Constant Field Values

ANDI

public static final int ANDI

See Also:
Constant Field Values

ASR

public static final int ASR

See Also:
Constant Field Values

BCLR

public static final int BCLR

See Also:
Constant Field Values

BLD

public static final int BLD

See Also:
Constant Field Values

BRBC

public static final int BRBC

See Also:
Constant Field Values

BRBS

public static final int BRBS

See Also:
Constant Field Values

BRCC

public static final int BRCC

See Also:
Constant Field Values

BRCS

public static final int BRCS

See Also:
Constant Field Values

BREAK

public static final int BREAK

See Also:
Constant Field Values

BREQ

public static final int BREQ

See Also:
Constant Field Values

BRGE

public static final int BRGE

See Also:
Constant Field Values

BRHC

public static final int BRHC

See Also:
Constant Field Values

BRHS

public static final int BRHS

See Also:
Constant Field Values

BRID

public static final int BRID

See Also:
Constant Field Values

BRIE

public static final int BRIE

See Also:
Constant Field Values

BRLO

public static final int BRLO

See Also:
Constant Field Values

BRLT

public static final int BRLT

See Also:
Constant Field Values

BRMI

public static final int BRMI

See Also:
Constant Field Values

BRNE

public static final int BRNE

See Also:
Constant Field Values

BRPL

public static final int BRPL

See Also:
Constant Field Values

BRSH

public static final int BRSH

See Also:
Constant Field Values

BRTC

public static final int BRTC

See Also:
Constant Field Values

BRTS

public static final int BRTS

See Also:
Constant Field Values

BRVC

public static final int BRVC

See Also:
Constant Field Values

BRVS

public static final int BRVS

See Also:
Constant Field Values

BSET

public static final int BSET

See Also:
Constant Field Values

BST

public static final int BST

See Also:
Constant Field Values

CALL

public static final int CALL

See Also:
Constant Field Values

CBI

public static final int CBI

See Also:
Constant Field Values

CBR

public static final int CBR

See Also:
Constant Field Values

CLC

public static final int CLC

See Also:
Constant Field Values

CLH

public static final int CLH

See Also:
Constant Field Values

CLI

public static final int CLI

See Also:
Constant Field Values

CLN

public static final int CLN

See Also:
Constant Field Values

CLR

public static final int CLR

See Also:
Constant Field Values

CLS

public static final int CLS

See Also:
Constant Field Values

CLT

public static final int CLT

See Also:
Constant Field Values

CLV

public static final int CLV

See Also:
Constant Field Values

CLZ

public static final int CLZ

See Also:
Constant Field Values

COM

public static final int COM

See Also:
Constant Field Values

CP

public static final int CP

See Also:
Constant Field Values

CPC

public static final int CPC

See Also:
Constant Field Values

CPI

public static final int CPI

See Also:
Constant Field Values

CPSE

public static final int CPSE

See Also:
Constant Field Values

DEC

public static final int DEC

See Also:
Constant Field Values

EICALL

public static final int EICALL

See Also:
Constant Field Values

EIJMP

public static final int EIJMP

See Also:
Constant Field Values

ELPM

public static final int ELPM

See Also:
Constant Field Values

EOR

public static final int EOR

See Also:
Constant Field Values

FMUL

public static final int FMUL

See Also:
Constant Field Values

FMULS

public static final int FMULS

See Also:
Constant Field Values

FMULSU

public static final int FMULSU

See Also:
Constant Field Values

ICALL

public static final int ICALL

See Also:
Constant Field Values

IJMP

public static final int IJMP

See Also:
Constant Field Values

IN

public static final int IN

See Also:
Constant Field Values

INC

public static final int INC

See Also:
Constant Field Values

JMP

public static final int JMP

See Also:
Constant Field Values

LD

public static final int LD

See Also:
Constant Field Values

LDD

public static final int LDD

See Also:
Constant Field Values

LDI

public static final int LDI

See Also:
Constant Field Values

LDS

public static final int LDS

See Also:
Constant Field Values

LPM

public static final int LPM

See Also:
Constant Field Values

LSL

public static final int LSL

See Also:
Constant Field Values

LSR

public static final int LSR

See Also:
Constant Field Values

MOV

public static final int MOV

See Also:
Constant Field Values

MOVW

public static final int MOVW

See Also:
Constant Field Values

MUL

public static final int MUL

See Also:
Constant Field Values

MULS

public static final int MULS

See Also:
Constant Field Values

MULSU

public static final int MULSU

See Also:
Constant Field Values

NEG

public static final int NEG

See Also:
Constant Field Values

NOP

public static final int NOP

See Also:
Constant Field Values

OR

public static final int OR

See Also:
Constant Field Values

ORI

public static final int ORI

See Also:
Constant Field Values

OUT

public static final int OUT

See Also:
Constant Field Values

POP

public static final int POP

See Also:
Constant Field Values

PUSH

public static final int PUSH

See Also:
Constant Field Values

RCALL

public static final int RCALL

See Also:
Constant Field Values

RET

public static final int RET

See Also:
Constant Field Values

RETI

public static final int RETI

See Also:
Constant Field Values

RJMP

public static final int RJMP

See Also:
Constant Field Values

ROL

public static final int ROL

See Also:
Constant Field Values

ROR

public static final int ROR

See Also:
Constant Field Values

SBC

public static final int SBC

See Also:
Constant Field Values

SBCI

public static final int SBCI

See Also:
Constant Field Values

SBI

public static final int SBI

See Also:
Constant Field Values

SBIC

public static final int SBIC

See Also:
Constant Field Values

SBIS

public static final int SBIS

See Also:
Constant Field Values

SBIW

public static final int SBIW

See Also:
Constant Field Values

SBR

public static final int SBR

See Also:
Constant Field Values

SBRC

public static final int SBRC

See Also:
Constant Field Values

SBRS

public static final int SBRS

See Also:
Constant Field Values

SEC

public static final int SEC

See Also:
Constant Field Values

SEH

public static final int SEH

See Also:
Constant Field Values

SEI

public static final int SEI

See Also:
Constant Field Values

SEN

public static final int SEN

See Also:
Constant Field Values

SER

public static final int SER

See Also:
Constant Field Values

SES

public static final int SES

See Also:
Constant Field Values

SET

public static final int SET

See Also:
Constant Field Values

SEV

public static final int SEV

See Also:
Constant Field Values

SEZ

public static final int SEZ

See Also:
Constant Field Values

SLEEP

public static final int SLEEP

See Also:
Constant Field Values

SPM

public static final int SPM

See Also:
Constant Field Values

ST

public static final int ST

See Also:
Constant Field Values

STD

public static final int STD

See Also:
Constant Field Values

STS

public static final int STS

See Also:
Constant Field Values

SUB

public static final int SUB

See Also:
Constant Field Values

SUBI

public static final int SUBI

See Also:
Constant Field Values

SWAP

public static final int SWAP

See Also:
Constant Field Values

TST

public static final int TST

See Also:
Constant Field Values

WDR

public static final int WDR

See Also:
Constant Field Values

IDENTIFIER

public static final int IDENTIFIER

See Also:
Constant Field Values

LETTER

public static final int LETTER

See Also:
Constant Field Values

DIGIT

public static final int DIGIT

See Also:
Constant Field Values

DOT_IDENTIFIER

public static final int DOT_IDENTIFIER

See Also:
Constant Field Values

ADDRESS

public static final int ADDRESS

See Also:
Constant Field Values

DEFAULT

public static final int DEFAULT

See Also:
Constant Field Values

IN_SINGLE_LINE_COMMENT

public static final int IN_SINGLE_LINE_COMMENT

See Also:
Constant Field Values

tokenImage

public static final java.lang.String[] tokenImage

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package org.jboss.weld.tests.interceptors.exclusion;

import javax.interceptor.AroundConstruct;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

import org.jboss.weld.test.util.ActionSequence;

public class Interceptor1 {

    @AroundInvoke
    Object intercept(InvocationContext ctx) throws Exception {
        ActionSequence.addAction(this.getClass().getName());
        return ctx.proceed();
    }

    @AroundConstruct
    void aroundConstruct(InvocationContext ctx) {
        ActionSequence.addAction(this.getClass().getName());
        try {
            ctx.proceed();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


text:
require_relative 'exceptions/invalid_options'
require_relative 'exceptions/task_error'


text:
The Web Application that is used by Canoo WebTest to serve
as a mirror for the internal selftest.

WebTest comes with some sample tests that assume that there
is a this Web Application running somewhere, be it on
your local machine, in your intranet or even over the
internet. You can always run it against the installation
of the selftest Web Application that runs at the

canoo development site.


text:
class Task
  @@list = []

  attr_accessor :priority, :name
  attr_reader :done, :created_at

  def initialize
    @done = false
    @created_at = Time.now

    @@list << self
  end

  def self.list
    @@list
  end

  def delete_at(index)
    @@list.delete_at(index)
  end

  def toggle_status!
    @done = !@done
  end
end


text:
unzip data_part.zip
for i in {1..20}
do
   cat data_part >> data_test
done
rm data_part


text:
require File.dirname(__FILE__) + '/helper'

class TestTask < Test::Unit::TestCase
  def setup
    God.internal_init
    @task = Task.new
    @task.name = 'foo'
    @task.valid_states = [:foo, :bar]
    @task.initial_state = :foo
    @task.interval = 5
    @task.prepare
  end

  # valid?

  def test_valid_should_return_false_if_no_name
    @task.name = nil
    assert !@task.valid?
  end

  def test_valid_should_return_false_if_no_valid_states
    @task.valid_states = nil
    assert !@task.valid?
  end

  def test_valid_should_return_false_if_no_initial_state
    @task.initial_state = nil
    assert !@task.valid?
  end

  # transition

  def test_transition_should_be_always_if_no_block_was_given
    @task.transition(:foo, :bar)

    assert_equal 5, @task.metrics.size
    assert_equal Conditions::Always, @task.metrics[:foo].first.conditions.first.class
  end

  # method_missing

  def test_method_missing_should_create_accessor_for_states
    assert_nothing_raised do
      @task.foo = 'testing'
    end
  end

  def test_method_missing_should_raise_for_non_states
    assert_raise NoMethodError do
      @task.baz = 5
    end
  end

  def test_method_missing_should_raise_for_non_setters
    assert_raise NoMethodError do
      @task.baz
    end
  end

  # action

  def test_action_should_send_string_commands_to_system
    @task.foo = 'foo'
    @task.driver.stubs(:in_driver_context?).returns(true)
    @task.expects(:system).with('foo')
    @task.action(:foo, nil)
  end

  def test_action_should_call_lambda_commands
    @task.foo = lambda { }
    @task.driver.stubs(:in_driver_context?).returns(true)
    @task.foo.expects(:call)
    @task.action(:foo, nil)
  end

  def test_action_should_raise_not_implemented_on_non_string_or_lambda_action
    @task.driver.stubs(:in_driver_context?).returns(true)
    assert_raise NotImplementedError do
      @task.foo = 7
      @task.action(:foo, nil)
    end
  end

  def test_action_from_outside_driver_should_send_message_to_driver
    @task.foo = 'foo'
    @task.driver.expects(:message).with(:action, [:foo, nil])
    @task.action(:foo, nil)
  end

  # attach

  def test_attach_should_schedule_for_poll_condition
    c = Conditions::FakePollCondition.new
    @task.driver.expects(:schedule).with(c, 0)
    @task.attach(c)
  end

  def test_attach_should_regsiter_for_event_condition
    c = Conditions::FakeEventCondition.new
    c.expects(:register)
    @task.attach(c)
  end

  # detach

  def test_detach_should_reset_poll_condition
    c = Conditions::FakePollCondition.new
    c.expects(:reset)
    c.expects(:deregister).never
    @task.detach(c)
  end

  def test_detach_should_deregister_event_conditions
    c = Conditions::FakeEventCondition.new
    c.expects(:deregister).once
    @task.detach(c)
  end

  # trigger

  def test_trigger_should_send_message_to_driver
    c = Conditions::FakePollCondition.new
    @task.driver.expects(:message).with(:handle_event, [c])
    @task.trigger(c)
  end

  # handle_poll

  def test_handle_poll_no_change_should_reschedule
    c = Conditions::FakePollCondition.new
    c.watch = @task
    c.interval = 10

    m = Metric.new(@task, {true => :up})
    @task.directory[c] = m

    c.expects(:test).returns(false)
    @task.driver.expects(:schedule)
    @task.handle_poll(c)
  end

  def test_handle_poll_change_should_move
    c = Conditions::FakePollCondition.new
    c.watch = @task
    c.interval = 10

    m = Metric.new(@task, {true => :up})
    @task.directory[c] = m

    c.expects(:test).returns(true)
    @task.expects(:move).with(:up)
    @task.handle_poll(c)
  end

  def test_handle_poll_should_use_overridden_transition
    c = Conditions::Tries.new
    c.watch = @task
    c.times = 1
    c.transition = :start
    c.prepare

    m = Metric.new(@task, {true => :up})
    @task.directory[c] = m

    @task.expects(:move).with(:start)
    @task.handle_poll(c)
  end

  def test_handle_poll_should_notify_if_triggering
    c = Conditions::FakePollCondition.new
    c.watch = @task
    c.interval = 10
    c.notify = 'tom'

    m = Metric.new(@task, {true => :up})
    @task.directory[c] = m

    c.expects(:test).returns(true)
    @task.expects(:notify)
    @task.handle_poll(c)
  end

  def test_handle_poll_should_not_notify_if_not_triggering
    c = Conditions::FakePollCondition.new
    c.watch = @task
    c.interval = 10
    c.notify = 'tom'

    m = Metric.new(@task, {true => :up})
    @task.directory[c] = m

    c.expects(:test).returns(false)
    @task.expects(:notify).never
    @task.handle_poll(c)
  end

  def test_handle_poll_unexpected_exception_should_reschedule
    c = Conditions::FakePollCondition.new
    c.watch = @task
    c.interval = 10

    m = Metric.new(@task, {true => :up})
    @task.directory[c] = m

    c.expects(:test).raises(StandardError)
    @task.driver.expects(:schedule)

    @task.handle_poll(c)
  end

  # handle_event

  def test_handle_event_should_move
    c = Conditions::FakeEventCondition.new
    c.watch = @task

    m = Metric.new(@task, {true => :up})
    @task.directory[c] = m

    @task.expects(:move).with(:up)
    @task.handle_event(c)
  end

  def test_handle_event_should_notify_if_triggering
    c = Conditions::FakeEventCondition.new
    c.watch = @task
    c.notify = 'tom'

    m = Metric.new(@task, {true => :up})
    @task.directory[c] = m

    @task.expects(:notify)
    @task.handle_event(c)
  end

  def test_handle_event_should_not_notify_if_no_notify_set
    c = Conditions::FakeEventCondition.new
    c.watch = @task

    m = Metric.new(@task, {true => :up})
    @task.directory[c] = m

    @task.expects(:notify).never
    @task.handle_event(c)
  end
end


text:
import _ from 'underscore';

import {CheckBoxInputView, ColorInputView, ConfigurationEditorView, SelectInputView, TextAreaInputView, TextInputView} from 'pageflow/ui';

import {FileInputView} from 'pageflow/editor';
import {features} from 'pageflow/frontend';
import {theme} from 'pageflow-paged/frontend';

import {state} from '$state';

ConfigurationEditorView.register('audio', {
  configure: function() {
    this.tab('general', function() {
      this.group('general', {supportsTextPositionCenter: true});

      this.input('additional_title', TextInputView);
      this.input('additional_description', TextAreaInputView, {size: 'short'});
    });

    this.tab('files', function() {
      this.input('audio_file_id', FileInputView, {
        collection: state.audioFiles,
        defaultTextTrackFilePropertyName: 'default_text_track_file_id'
      });
      this.group('background');
      this.input('thumbnail_image_id', FileInputView, {
        collection: state.imageFiles,
        positioning: false
      });
    });

    this.tab('options', function() {
      if (features.isEnabled('waveform_player_controls')) {
        this.input('audio_player_controls_variant', SelectInputView, {
          values: ['default', 'waveform']
        });
      }

      this.input('waveform_color', ColorInputView, {
        visibleBinding: 'audio_player_controls_variant',
        visibleBindingValue: 'waveform',

        defaultValue: theme.mainColor(),
        swatches: usedWaveformColors()
      });

      this.input('autoplay', CheckBoxInputView);
      this.group('options', {canPauseAtmo: true});
    });

    function usedWaveformColors() {
      return _.chain(state.pages.map(function(page) {
        return page.configuration.get('waveform_color');
      })).uniq().compact().value();
    }
  }
});


text:
<?php

namespace Laratrust\Middleware;

use Closure;

class LaratrustRole extends LaratrustMiddleware
{
    /**
     * Handle incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  Closure $next
     * @param  string  $roles
     * @param  string|null  $team
     * @param  string|null  $options
     * @return mixed
     */
    public function handle($request, Closure $next, $roles, $team = null, $options = '')
    {
        if (!$this->authorization('roles', $roles, $team, $options)) {
            return $this->unauthorized();
        }

        return $next($request);
    }
}


text:
using ZKWeb.Localize;
using ZKWebStandard.Ioc;

namespace ZKWeb.Plugins.Common.Base.src.Components.Languages {
	/// <summary>
	/// 泰语
	/// </summary>
	[ExportMany]
	public class Thai : ILanguage {
		public string Name { get { return "th-TH"; } }
	}
}


text:
from .base import RepositorioEmMemoria
from domain.usuario import RepositorioUsuario

class RepositorioUsuarioEmMemoria(RepositorioEmMemoria, RepositorioUsuario):
    """Essa classe modela um Repositório de Usuários em memória, para
    armazenamento temporário e uso em mock tests."""

    def obter_por_email(self, email):
        """Busca e retorna um objeto de Usuario associado a um endereço de e-mail
        fornecido. Pode levantar uma exceção do tipo IndexError caso não seja
        encontrado nenhum Usuário associado ao e-mail dado."""
        try:
            return list(filter(lambda u: u.email == email, self.listar()))[0]
        except IndexError:
            return None


text:
package org.apache.felix.sigil.ant;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;

import org.apache.felix.sigil.common.bnd.BundleBuilder;
import org.apache.felix.sigil.common.config.BldFactory;
import org.apache.felix.sigil.common.config.IBldProject;
import org.apache.felix.sigil.common.config.IBldProject.IBldBundle;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.Path;

public class BundleTask extends Task
{
    private File[] classpath;
    private String destPattern;
    private boolean force;
    private String property;
    private String sigilFile;
    private String revision;

    @Override
    public void execute() throws BuildException
    {
        if (classpath == null)
            throw new BuildException("missing: attribute: classpathref");
        if (destPattern == null)
            throw new BuildException("missing attribute: destpattern");

        @SuppressWarnings("unchecked")
        Hashtable<String, String> projectProperties = getProject().getProperties();
        Properties antProperties = new Properties();
        antProperties.putAll(projectProperties);

        IBldProject project;
        try
        {
            project = BldFactory.getProject(getSigilFileURI(), antProperties);
        }
        catch (IOException e)
        {
            throw new BuildException("failed to get project file: " + e);
        }

        Properties env = new Properties();
        for (String key : projectProperties.keySet())
        {
            if (key.matches("^[a-z].*"))
            { // avoid props starting with Uppercase - bnd adds them to manifest
                env.setProperty(key, projectProperties.get(key));
            }
        }

        BundleBuilder bb = new BundleBuilder(project, classpath, destPattern, env);
        boolean anyModified = false;

        for (IBldBundle bundle : project.getBundles())
        {
            String id = bundle.getId();
            log("creating bundle: " + id);
            int nWarn = 0;
            int nErr = 0;
            String msg = "";

            try
            {
                boolean modified = (bb.createBundle(bundle, force,
                    new BundleBuilder.Log()
                    {
                        public void warn(String msg)
                        {
                            log(msg, Project.MSG_WARN);
                        }

                        public void verbose(String msg)
                        {
                            log(msg, Project.MSG_VERBOSE);
                        }
                    }));
                nWarn = bb.warnings().size();
                if (modified)
                {
                    anyModified = true;
                }
                else
                {
                    msg = " (not modified)";
                }
            }
            catch (Exception e)
            {
                List<String> errors = bb.errors();
                if (errors != null)
                {
                    nErr = errors.size();
                    for (String err : errors)
                    {
                        log(err, Project.MSG_ERR);
                    }
                }
                throw new BuildException("failed to create: " + id + ": " + e, e);
            }
            finally
            {
                log(id + ": " + count(nErr, "error") + ", " + count(nWarn, "warning")
                    + msg);
            }

            if (revision != null)
            {
                // FIXME: hopefully if we have multiple bundles they all have the same version
                getProject().setProperty(revision, bundle.getVersion());
            }
        }

        if (anyModified && property != null)
        {
            getProject().setProperty(property, "true");
        }
    }

    private URI getSigilFileURI()
    {
        File file = sigilFile == null ? new File(getProject().getBaseDir(),
            IBldProject.PROJECT_FILE) : new File(sigilFile);
        if (!file.isFile())
        {
            throw new BuildException("File not found " + file.getAbsolutePath());
        }
        return file.toURI();
    }

    private String count(int count, String msg)
    {
        return count + " " + msg + (count == 1 ? "" : "s");
    }

    public void setDestpattern(String pattern)
    {
        this.destPattern = pattern;
    }

    public void setForce(String force)
    {
        this.force = Boolean.parseBoolean(force);
    }

    public void setProperty(String property)
    {
        this.property = property;
    }

    public void setRevision(String revision)
    {
        this.revision = revision;
    }

    public void setClasspathref(String value)
    {
        Path p = (Path) getProject().getReference(value);
        if (p == null)
        {
            throw new BuildException(value + "is not a path reference.");
        }

        String[] paths = p.list();
        classpath = new File[paths.length];
        for (int i = 0; i < paths.length; ++i)
        {
            classpath[i] = new File(paths[i]);
        }
    }

    public void setSigilFile(String sigilFile)
    {
        this.sigilFile = sigilFile;
    }
}


text:
module PathRegistry
  module User

    def self.install_association(base)
      base.belongs_to :registered_path,
        :foreign_key => base.path_registry.foreign_key
    end

  end
end


text:
layout: default
title: Tickets
nav: tickets
---

<link rel="stylesheet" type="text/css" href="assets/css/tito.css">

Conference Tickets

Tickets for the conference are available to purchase below. We cannot wait to welcome you to the latest edition of the conference on October 21st at The Electric in Birmingham, UK. Conference ticket holders will have priority for the Hackathon tickets.

Diversity Pool

We're hoping to make it easier than ever for minorities and disadvantaged groups to attend. If you'd like to donate and help us move towards that goal, that would be incredible. If you'd like to apply for a diversity ticket just go to http://bit.ly/hackference2016diversitytickets.

Group Tickets

If you're looking to buy 3 or more tickets, then we can look at giving you a discount. Please contact Mike and start the conversation. We look to give discounts on a sliding scale, so if you are buying more tickets, you'll get a bigger discount!

Purchase Tickets

				<tito-widget event="hackference/hackference-2016"></tito-widget>

Hackathon Tickets

				<tito-widget event="hackference/hackference-2016-hackathon"></tito-widget>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>FindosgProducer — CMake 3.8.1 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="FindosgQt" href="FindosgQt.html" />
    <link rel="prev" title="FindosgPresentation" href="FindosgPresentation.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.8.1 Documentation »

cmake-modules(7) »

FindosgProducer¶

This is part of the Findosg* suite used to find OpenSceneGraph
components.  Each component is separate and you must opt in to each
module.  You must also opt into OpenGL and OpenThreads (and Producer
if needed) as these modules won’t do it for you.  This is to allow you
control over your own system piece by piece in case you need to opt
out of certain components or change the Find behavior for a particular
module (perhaps because the default FindOpenGL.cmake module doesn’t
work with your system as an example).  If you want to use a more
convenient module that includes everything, use the
FindOpenSceneGraph.cmake instead of the Findosg*.cmake modules.

Locate osgProducer This module defines

OSGPRODUCER_FOUND - Was osgProducer found? OSGPRODUCER_INCLUDE_DIR -
Where to find the headers OSGPRODUCER_LIBRARIES - The libraries to
link for osgProducer (use this)

OSGPRODUCER_LIBRARY - The osgProducer library
OSGPRODUCER_LIBRARY_DEBUG - The osgProducer debug library

$OSGDIR is an environment variable that would correspond to the
./configure –prefix=$OSGDIR used in building osg.

Created by Eric Wing.

Previous topic

FindosgPresentation

Next topic

FindosgQt

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

Navigation

          index

          next |

          previous |

    CMake »

    3.8.1 Documentation »

cmake-modules(7) »

        © Copyright 2000-2017 Kitware, Inc. and Contributors.
      Created using Sphinx 1.5.2.


text:
package aQute.service.reporter;

/**
 * A base interface to model a work in progress. Though exceptions work well for
 * major, well, exceptions, they are lousy for reporting errors/warnings in a
 * task. Logging also sucks because it is global, hard to relate to a single
 * piece of work. This small (uncoupled) interface is intended to fill this gap.
 * The idea is that different tasks can perform parts and the progress can be
 * integrated. A reporter is not mandated to track locations. Locations should
 * be seen as best effort.
 */
public interface Reporter extends Report {
	/**
	 * Fluid interface to set location data
	 */
	interface SetLocation {
		/**
		 * Set the file location
		 */
		SetLocation file(String file);

		/**
		 * Set the header/section location. This is normally the header in a
		 * manifest or properties file.
		 */
		SetLocation header(String header);

		/**
		 * Set the context in the header.
		 *
		 * @param context
		 */
		SetLocation context(String context);

		/**
		 * Set the method where the error is reported.
		 *
		 * @param methodName
		 */
		SetLocation method(String methodName);

		/**
		 * Set the line number. Line 0 is the top line.
		 */
		SetLocation line(int n);

		/**
		 * Set a reference for the error (url or so)
		 */

		SetLocation reference(String reference);

		/**
		 * Pass a DTO containing detailed information about the error. This can
		 * be recognised by other tools (e.g. bndtools) and used for further
		 * error reporting/fixing.
		 */
		SetLocation details(Object details);

		Location location();

		SetLocation length(int length);
	}

	/**
	 * Create an error. Implementations must ensure that the given args are not
	 * prevented from garbage collecting. The args must have a proper toString
	 * method.
	 *
	 * @param format The format of the error
	 * @param args The arguments of the error
	 * @return a SetLocation to set the location
	 */
	SetLocation error(String format, Object... args);

	/**
	 * Create a warning. Implementations must ensure that the given args are not
	 * prevented from garbage collecting. The args must have a proper toString
	 * method.
	 *
	 * @param format The format of the error
	 * @param args The arguments of the error
	 * @return a SetLocation to set the location
	 */
	SetLocation warning(String format, Object... args);

	/**
	 * Create a warning. Implementations must ensure that the given args are not
	 * prevented from garbage collecting. The args must have a proper toString
	 * method.
	 *
	 * @param format The format of the error
	 * @param args The arguments of the error
	 * @deprecated Use SLF4J Logger.debug instead.
	 */
	@Deprecated
	void trace(String format, Object... args);

	/**
	 * Create a warning. Implementations must ensure that the given args are not
	 * prevented from garbage collecting. The args must have a proper toString
	 * method.
	 *
	 * @param progress A value between 0 and 1 indicating the progress. 0 is
	 *            starting and >=1 is done.
	 * @param format The format of the error
	 * @param args The arguments of the error
	 * @deprecated Use SLF4J
	 *             Logger.info(aQute.libg.slf4j.GradleLogging.LIFECYCLE)
	 *             instead.
	 */
	@Deprecated
	void progress(float progress, String format, Object... args);

	/**
	 * Dedicated message for an exception.
	 *
	 * @param t The exception
	 * @param format The format of the message
	 * @param args The arguments
	 */
	public SetLocation exception(Throwable t, String format, Object... args);

	/**
	 * The provider of the reporter wants pedantic reporting, meaning every
	 * possible warning should be reported.
	 *
	 * @return if this is a pedantic reporter.
	 */
	boolean isPedantic();

}


text:
<!DOCTYPE HTML>

		<title>PathJS Test</title>

Test Suite

			    Path.js uses a very straightforward method of testing.  We manually construct
				a series of method calls that the library should execute under normal working
				conditions.  We then use JavaScript to simulate the URL changes, and compare
				the final result with what the result should actually be.  If the end result
				is anything but perfect, the test is a failure, and this version of Path.JS
				is not suitable for use. The expected test results are as follows:

Token	          Reason

A[enter]	              Enter method of A, as it is looped

A[action]	             True action of A, as it is looped

A[exit]	               Exit method of A, as we move to next route

B[enter]	              Enter method of B, as it is looped

B[action]	             True action of B, as it is looped

C[action]	             True action of C

C[exit]	               Exit method of C, as we move to next route

RESCUE	                Rescue a route that wasn't found (D1)

RESCUE	                Rescue a route that wasn't found (D2)

E[enter](parse)	       Enter method of a param parsed route

E[action](parse id=1)	 True action of the route, with param of id=1

E[enter](parse)	       Enter method of the same route again

E[action](parse id=2)	 True action of the route, with param of id=2

E[action](check id=3)	 True action of the next route, with param id=3

E[exit](check)	        Exit method of parameterized route

F[enter]	              Enter method of F again, our final route

F[action]	             True action of F, our final route

G[enter 1]	            First enter method of G

G[enter 2]	            Second enter method of G

G[enter 3]	            Third enter method of G

G[enter 4]	            Last enter method of G - Returns false, stops execution

H(one=N/A, two=N/A)	   Optional parameters with only the require part submitted

H(one=10, two=N/A)	    Optional parameters with one optional part submitted

H(one=10, two=20)	     Optional parameters two levels deep

H(one=10, two=N/A)	    Testing the "back" functionality

Expected

A[enter]::A[action]::A[exit]::B[enter]::B[action]::C[action]::C[exit]::RESCUE::RESCUE::E[enter](parse)::E[action](parse id=1)::E[enter](parse)::E[action](parse id=2)::E[action](check id=3)::E[exit](check)::F[enter]::F[action]::G[enter 1]::G[enter 2]::G[enter 3]::G[enter 4]::H(one=N/A, two=N/A)::H(one=10, two=N/A)::H(one=10, two=20)::H(one=10, two=N/A)

Actual

Grade


text:
=================================
hyperion.grid.AMRGrid
=================================

.. currentmodule:: hyperion.grid

.. autoclass:: AMRGrid

   .. rubric:: Methods

   .. autosummary::

      ~AMRGrid.read
      ~AMRGrid.read_geometry
      ~AMRGrid.read_quantities
      ~AMRGrid.write
      ~AMRGrid.write_single_array
      ~AMRGrid.add_derived_quantity

   .. rubric:: Methods (detail)

   .. automethod:: AMRGrid.read
   .. automethod:: AMRGrid.read_geometry
   .. automethod:: AMRGrid.read_quantities
   .. automethod:: AMRGrid.write
   .. automethod:: AMRGrid.write_single_array
   .. automethod:: AMRGrid.add_derived_quantity

.. autoclass:: AMRGridView

   .. rubric:: Methods

   .. autosummary::

      ~AMRGridView.append
      ~AMRGridView.add

   .. rubric:: Methods (detail)

   .. automethod:: AMRGridView.append
   .. automethod:: AMRGridView.add


text:
.class Lcom/android/internal/view/FloatingActionMode$3;
.super Ljava/lang/Object;
.source "FloatingActionMode.java"

# interfaces
.implements Lcom/android/internal/view/menu/MenuBuilder$Callback;

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/internal/view/FloatingActionMode;-><init>(Landroid/content/Context;Landroid/view/ActionMode$Callback2;Landroid/view/View;Lcom/android/internal/widget/FloatingToolbar;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/view/FloatingActionMode;

# direct methods
.method constructor <init>(Lcom/android/internal/view/FloatingActionMode;)V
    .locals 0

    iput-object p1, p0, Lcom/android/internal/view/FloatingActionMode$3;->this$0:Lcom/android/internal/view/FloatingActionMode;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onMenuItemSelected(Lcom/android/internal/view/menu/MenuBuilder;Landroid/view/MenuItem;)Z
    .locals 2

    iget-object v0, p0, Lcom/android/internal/view/FloatingActionMode$3;->this$0:Lcom/android/internal/view/FloatingActionMode;

    invoke-static {v0}, Lcom/android/internal/view/FloatingActionMode;->-get0(Lcom/android/internal/view/FloatingActionMode;)Landroid/view/ActionMode$Callback2;

    move-result-object v0

    iget-object v1, p0, Lcom/android/internal/view/FloatingActionMode$3;->this$0:Lcom/android/internal/view/FloatingActionMode;

    invoke-virtual {v0, v1, p2}, Landroid/view/ActionMode$Callback2;->onActionItemClicked(Landroid/view/ActionMode;Landroid/view/MenuItem;)Z

    move-result v0

    return v0
.end method

.method public onMenuModeChange(Lcom/android/internal/view/menu/MenuBuilder;)V
    .locals 0

    return-void
.end method


text:
package review.utils.mybe.outdated;

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

import org.apache.commons.io.FileUtils;

import scala.tools.nsc.transform.SpecializeTypes.Forward;

public class ProcessDataFromDockerMonitor {

	public static void main(String[] args) throws IOException {
		List<String> allResults = FileUtils.readLines(new File("testres/dockermonitor.txt"));

		for (String line : allResults) {
			if(line.startsWith("CONTAINER")){

			}else{
				 String unitsTo =line.replace(" MB", "MB").replace(" GB", "GB").replace(" kB", "KB").replace(" B", "B");
						String unitsToSpecial=unitsTo.replace("%", " ").replace("/", "");

			System.out.println(unitsToSpecial);
			}

		}
System.out.println(Float.parseFloat("7.385")*10);
	}

}


text:
require 'yaml'

# Class: PlatformInfo
# This class reads device specific details from the yaml file - platform_info.yaml
# These details can be used to customize unit tests for a device
class PlatformInfo
  # Default constructor for the PlatformInfo class. This class
  # requires the hostname of the device on which UTs are to run
  # to be passed in. The constructor reads platform_info.yaml
  # and stores info for this device in the instance variable
  # @platform_info_hash
  #
  # @param[in] device_name      hostname of device on which
  #                             UTs are to be run
  #
  def initialize(device_name)
    raise "device name must be specified in PlatformInfo constructor." if device_name.nil? or device_name.empty?
    @platform_info_hash = {}

    begin
      project_info_hash = YAML.load_file(File.join(File.dirname(__FILE__), "platform_info.yaml"))
    rescue Exception => e
      raise "Error - could not open platform file - platform_info.yaml"
    end

    @platform_info_hash = project_info_hash[device_name]
    raise "Error - could not find #{device_name} device specific information in platform_info.yaml" if @platform_info_hash.nil?
  end

  # The following instance method will return the value associated with
  # the specified key from the instance variable @platform_info_hash.
  #
  # @param[in] key  String value indicating the key to be searched for
  #                 in @platform_info_hash
  #
  def get_value_from_key(key)
    raise "key must be specified in the method get_value_from_key" if key.nil?

    value = @platform_info_hash[key]
    raise "no value exists for the key #{key}" if value.nil?

    value
  end
end


text:
"""Run experiment to understand coverage of CIs generated by SLOE.

Tests the SLOE estimator empirically by computing
confidence intervals (CIs) using it over a bunch of different seeds and aspect
ratios, calculating properties such as coverage and size, and storing in csv
files to be analyzed in a colab.
"""

from absl import app
from absl import flags
import apache_beam as beam
from apache_beam.options import pipeline_options
import numpy as np
import sklearn.linear_model
from sklearn.model_selection import LeaveOneOut

from sloe_logistic import probe_frontier
from sloe_logistic import unbiased_logistic_regression
import sloe_logistic.sloe_experiments.experiment_helpers as exp_helper

GAMMA_RANGE = [0.1, 1, 5]
FLAGS = flags.FLAGS

flags.DEFINE_integer('num_sims', 100, 'number of simulations to run')
flags.DEFINE_string('output_path', '/tmp/counts', 'The output file path')
flags.DEFINE_enum(
    'coverage_target', 'true_preds', ['true_preds', 'calib_ests', 'reg_ests'],
    'Which value to check coverage in prediction intervals?')
flags.DEFINE_boolean('include_bootstrap', False,
                     'Include bootstrap CIs as well? These are slow.')
flags.DEFINE_float(
    'kappa_spacing', 0.05,
    'Resolution of graph in terms of spacing between kappa evaluated.')
flags.DEFINE_float(
    'coverage_rate', 95, 'What level confidence intervals'
    'should be tested (0-100)?')

def run_sim(params):
  """Runs simulation and computes properties of the estimated CIs."""
  kappa = params[0]
  gamma = params[1]
  seed = 201216 + params[2]

  sim_params = exp_helper.SimulationParams.create_from_flags()
  sim_params.seed = seed
  sim_params.gamma = np.sqrt(gamma)
  sim_params.p = int(sim_params.training_n * kappa)
  sim = exp_helper.create_sim(sim_params)

  x1, y1 = sim.sample()

  pfr = probe_frontier.ProbeFrontierLogisticRegression()
  if pfr.is_separable(x1, y1):
    return

  # Draw test data
  x2, _ = sim.sample(int(sim_params.training_n / 4))
  true_logits = x2.dot(sim.beta)
  bias_selector = np.abs(true_logits) > 1e-2

  # Calculate coverage
  if FLAGS.coverage_target == 'true_preds':
    target = 1.0 / (1.0 + np.exp(-true_logits)).reshape(-1)
  elif FLAGS.coverage_target == 'calib_ests':
    ps_logit_model = unbiased_logistic_regression.PlattScaledLogisticRegression(
        fit_intercept=sim_params.intercept or sim_params.uncentered)
    ps_logit_model.fit(x1, y1)
    target = ps_logit_model.predict_proba(x2)[:, 1]
  elif FLAGS.coverage_target == 'reg_ests':
    ps_logit_model = sklearn.linear_model.LogisticRegressionCV(
        cv=LeaveOneOut(),
        fit_intercept=False,
        Cs=20,
        penalty='l2',
        solver='newton-cg')
    ps_logit_model.fit(x1, y1)
    target = ps_logit_model.predict_proba(x2)[:, 1]
  else:
    raise ValueError("Invalid choice of coverage target '{}'.".format(
        FLAGS.coverage_target))

  try:
    new_method_model = exp_helper.create_inference_model('newmethod')
    new_method_model.set_coverage(FLAGS.coverage_rate)
    _ = new_method_model.fit(x1, y1)
    new_pred_int = new_method_model.prediction_intervals(x2)
    new_logit_int = new_method_model.prediction_intervals(x2, logit=True)
  except ValueError as e:
    print(e)
    return

  std_method_model = exp_helper.create_inference_model('mle')
  std_method_model.set_coverage(FLAGS.coverage_rate)
  _ = std_method_model.fit(x1, y1)
  std_pred_int = std_method_model.prediction_intervals(x2)
  std_logit_int = std_method_model.prediction_intervals(x2, logit=True)

  new_coverage = np.logical_and(
      new_pred_int[:, 0].reshape(-1) <= target,
      target <= new_pred_int[:, 2].reshape(-1)).astype(float)
  std_coverage = np.logical_and(
      std_pred_int[:, 0].reshape(-1) <= target,
      target <= std_pred_int[:, 2].reshape(-1)).astype(float)

  new_width = np.abs(new_logit_int[:, 2] - new_logit_int[:, 0])
  std_width = np.abs(std_logit_int[:, 2] - std_logit_int[:, 0])

  new_bias = new_logit_int[bias_selector, 1] / true_logits[bias_selector]
  std_bias = std_logit_int[bias_selector, 1] / true_logits[bias_selector]

  results = [
      gamma, kappa, seed,
      np.mean(new_coverage),
      np.mean(new_width),
      np.mean(new_bias),
      np.mean(std_coverage),
      np.mean(std_width),
      np.mean(std_bias)
  ]

  if FLAGS.include_bootstrap:
    boot_method_model = exp_helper.create_inference_model('bootstrap')
    boot_method_model.set_coverage(FLAGS.coverage_rate)
    _ = boot_method_model.fit(x1, y1)
    boot_pred_int = boot_method_model.prediction_intervals(x2)
    boot_logit_int = boot_method_model.prediction_intervals(x2, logit=True)

    boot_coverage = np.logical_and(
        boot_pred_int[:, 0].reshape(-1) <= target,
        target <= boot_pred_int[:, 2].reshape(-1)).astype(float)
    boot_width = np.abs(boot_logit_int[:, 2] - boot_logit_int[:, 0])
    boot_bias = boot_logit_int[bias_selector, 1] / true_logits[bias_selector]

    results.append(np.mean(boot_coverage))
    results.append(np.mean(boot_width))
    results.append(np.mean(boot_bias))

  return [np.array(results)]

def main(unused_argv):
  kappa_range = np.arange(0.05, 0.5 + 0.5 * FLAGS.kappa_spacing,
                          FLAGS.kappa_spacing)

  # If you have custom beam options add them here.
  beam_options = pipeline_options.PipelineOptions()

  with beam.Pipeline(options=beam_options) as pipe:
    _ = (
        pipe
        | beam.Create(range(FLAGS.num_sims))
        | beam.FlatMap(exp_helper.multiple_sim_params, kappa_range,
                       GAMMA_RANGE)
        | 'PrepShuffle' >> beam.Reshuffle()
        | beam.FlatMap(run_sim)
        | beam.Map(exp_helper.numpy_array_to_csv)
        | beam.Reshuffle()
        |
        'WriteToText' >> beam.io.WriteToText(FLAGS.output_path, num_shards=5))

if __name__ == '__main__':
  app.run(main)


text:
import math

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import QtCore, QtGui
from PyQt4.phonon import Phonon
from pydub import AudioSegment

from main_const import *

class ExportSession():
    def __init__(self, main, gui, player):
        self.main = main
        self.gui = gui
        self.player = player
        self.exportsession()

    def exportsession(self):
        playing = (self.player.entrainmentObject.state() == Phonon.PlayingState)
        paused = (self.player.entrainmentObject.state() == Phonon.PausedState)
        if playing or paused:
            quit_msg = "Stop The Loaded Session To Export The Session?"
            reply = QtGui.QMessageBox.question(self, 'Confirmation To Stop Session For Export',
                             quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
            if reply == QtGui.QMessageBox.Yes:
                self.player.entrainmentObject.stop()
                if self.gui.AmbienceOption.isChecked():
                    self.player.ambienceObject.stop()
                self.gui.statusBar.showMessage("Session Stopped For Export")
        elif not self.main.sessioncreated:
            QtGui.QMessageBox.information(None, "No Session Created",
                                           "A Session Must Be Created In Order To Export",
                                           QtGui.QMessageBox.Ok | QtGui.QMessageBox.Default,
                                           QtGui.QMessageBox.NoButton)
        elif self.main.sessioncreated:
            self.finalentrainmentlist = self.main.entrainmentplayer.cutstoplay
            if self.gui.AmbienceOption.isChecked():
                self.finalambiencelist = self.main.ambienceplayer.finalambience
            else:
                self.finalambiencelist = None
            self.totalshittodo = (len(self.main.cutsinsession) + 1)
            self.exportfilename = QtGui.QFileDialog.getSaveFileName(self.gui, "Where Do You Want Me To Export This Session?",
                '', "Music Files (*.mp3);;All Files (*)")
            ExportSessionDialog(self.gui, self.main, self)

class ExportThread(QThread):
    def __init__(self, entrainmentfiles, ambiencefiles, cutsinsession, exportfile):
        QThread.__init__(self)
        self.entrainmentfiles = entrainmentfiles
        self.ambiencefiles = ambiencefiles
        self.exportfile = exportfile
        self.cutsinsession = cutsinsession
        self.finallist = list()
        self.settoexit = False

    def run(self):
        while True:
            totallength = int()
            if self.ambiencefiles is not None: # Ambience And Entrainment
                alertactual = AudioSegment.from_mp3(ALERTFILE)
                alertnotactual = AudioSegment.from_mp3(ALERTSILENCE)
                alertogg = alertactual.overlay(alertnotactual)
                for x, i in enumerate(self.entrainmentfiles):
                    self.emit(SIGNAL("asignal"), self.cutsinsession[x]["name"])
                    nextentrainment = AudioSegment.from_mp3(i)
                    nextambience = AudioSegment.from_mp3(self.ambiencefiles[x])
                    output = nextentrainment.overlay(nextambience)
                    tempoutputname = os.path.join(TEMPDIRECTORY, "Export", str(x) + ".mp3")
                    output.export(tempoutputname, format="mp3")
                    if x == 0:
                        finallist = output
                        finallist += alertogg
                        totallength += len(alertogg)
                    else:
                        finallist += output
                        if i != self.entrainmentfiles[-1]:
                            finallist += alertogg
                            totallength += len(alertogg)
                    totallength += len(output)
                self.emit(SIGNAL("asignal"), True)
                exportfilename = str(self.exportfile)
                finallist.export(exportfilename, format="mp3")
            else: # Entrainment Only
                alertactual = AudioSegment.from_mp3(ALERTFILE)
                alertnotactual = AudioSegment.from_mp3(ALERTSILENCE)
                alertogg = alertactual.overlay(alertnotactual)
                for x, i in enumerate(self.entrainmentfiles):
                    self.emit(SIGNAL("asignal"), self.cutsinsession[x]["name"])
                    if x == 0:
                        nextentrainment = AudioSegment.from_mp3(i)
                        nextentrainment += alertogg
                        #totallength += len(alertogg)
                    else:
                        nextentrainment += AudioSegment.from_mp3(i)
                        if i != self.entrainmentfiles[-1]:
                            nextentrainment += alertogg
                            #totallength += len(alertogg))
                    # self.emit(SIGNAL("asignal"))
                self.emit(SIGNAL("asignal"), True)
                totallength = len(nextentrainment)
                exportfilename = str(self.exportfile)
                nextentrainment.export(exportfilename, format="mp3")
            exportfiled = AudioSegment.from_mp3(exportfilename)
            exportfileminutes = math.trunc((len(exportfiled) / 1000) / 60)
            totallengthminutes = math.trunc((totallength / 1000) / 60)
            if exportfileminutes == totallengthminutes:
                self.emit(SIGNAL("asignal"), False)
                [os.remove(os.path.join(TEMPDIRECTORY, 'Export', x)) for x in os.listdir(os.path.join(TEMPDIRECTORY, 'Export'))]
                break
            else:
                print('The Exported File With Length %s Does Not Match The Totallength Variable With Length %s' %
                      (exportfileminutes, totallengthminutes))
                print("Trying Export Again...")
                continue

class ExportSessionDialog(QDialog):
    def __init__(self, maingui, mainprogram, exporter):
        QDialog.__init__(self, maingui)
        self.percentsessioncreated = int()
        self.totalshittodo = int()
        self.resize(391, 114)
        self.main = mainprogram
        self.main.sessioncreated = False
        self.gui = maingui
        self.progress = int()
        self.exporter = exporter
        self.exportsessionProgressBar = QtGui.QProgressBar(self)
        self.exportsessionProgressBar.setGeometry(QtCore.QRect(20, 40, 361, 23))
        self.exportsessionCancelButton = QtGui.QPushButton(self)
        self.exportsessionCancelButton.setGeometry(QtCore.QRect(300, 70, 84, 30))
        self.topLabel = QtGui.QLabel(self)
        self.topLabel.setGeometry(QtCore.QRect(20, 10, 351, 20))
        self.exportStatusUpdate = QtGui.QLabel(self)
        self.exportStatusUpdate.setGeometry(QtCore.QRect(20, 70, 271, 16))
        self.setWindowTitle("Exporting Session")
        self.topLabel.setText("(This May Take A While)")
        self.exportsessionCancelButton.setText("Cancel")
        self.exportsessionProgressBar.setValue(0)
        QtCore.QObject.connect(self.exportsessionCancelButton, QtCore.SIGNAL("clicked()"), self.cancelsessioncreation)
        QtCore.QObject.connect(self.exportsessionProgressBar, QtCore.SIGNAL("valueChanged(int)"), self.seeifexportdone)
        self.exec_()

    def cancelsessioncreation(self):
        self.close()

    def seeifexportdone(self):
        if self.exportsessionProgressBar.value() == 100:
            self.gui.statusBar.showMessage("Session Exported To: ( %s )" % self.exporter.exportfilename)
            self.accept()

    def callthreads(self):
        self.sessionexporter = ExportThread(self.exporter.finalentrainmentlist,
                                             self.exporter.finalambiencelist,
                                             self.main.cutsinsession,
                                             self.exporter.exportfilename)
        QObject.connect(self.sessionexporter,SIGNAL("asignal"),self.sessionexporterupdates,Qt.QueuedConnection)
        self.sessionexporter.start()
        self.gui.statusBar.showMessage("Exporting Session...")

    def sessionexporterupdates(self, cutname):
        percent = 100 / (self.exporter.totalshittodo + 1)
        self.progress += percent
        self.exportsessionProgressBar.setValue(int(self.progress))
        if isinstance(cutname, str):
            self.exportStatusUpdate.setText("Building %s..." % cutname)
        else:
            if cutname:
                self.exportStatusUpdate.setText("Building Final Session File...")
            else:
                pass
                # Reset To 0
                # Print To Label...An Error Occured, Retrying

    def showEvent(self, QShowEvent):
        self.callthreads()

    def closeEvent(self, QCloseEvent):
        self.sessionexporter.settoexit = True
        self.gui.statusBar.showMessage("Session Exporter Cancelled", 3000)
        self.accept()


text:
package ru.job4j.condition;

 import org.junit.Test;
 import static org.junit.Assert.assertThat;
 import static org.hamcrest.number.IsCloseTo.closeTo;

 /**
 * TriangleTest.
 *
 * @author Vladimir Zhirnov (harabe@yandex.ru)
 * @version $Id$
 * @since 0.1
 */
 public class TriangleTest {
  	/**
 	* Test area.
 	*/
    @Test
 	public void testTriangle() {
 		Point pointA = new Point(2, 4);
 		Point pointB = new Point(8, 6);
 		Point pointC = new Point(4, 0);
 		Triangle points = new Triangle(pointA, pointB, pointC);
 		double result = points.area();
 		double expected = 14;
 		assertThat(result, closeTo(expected, 0.01));
 	}
 }


text:
from __future__ import division
import numpy as np
import torch
import json
import logging

def setup_logger(logger_name, log_file, level=logging.INFO):
    l = logging.getLogger(logger_name)
    formatter = logging.Formatter('%(asctime)s : %(message)s')
    fileHandler = logging.FileHandler(log_file, mode='w')
    fileHandler.setFormatter(formatter)
    streamHandler = logging.StreamHandler()
    streamHandler.setFormatter(formatter)

    l.setLevel(level)
    l.addHandler(fileHandler)
    l.addHandler(streamHandler)

def read_config(file_path):
    """Read JSON config."""
    json_object = json.load(open(file_path, 'r'))
    return json_object

def norm_col_init(weights, std=1.0):
    x = torch.randn(weights.size())
    x *= std / torch.sqrt((x**2).sum(1, keepdim=True))
    return x

def ensure_shared_grads(model, shared_model):
    for param, shared_param in zip(model.parameters(),
                                   shared_model.parameters()):
        if shared_param.grad is not None:
            return
        shared_param._grad = param.grad

def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        weight_shape = list(m.weight.data.size())
        fan_in = np.prod(weight_shape[1:4])
        fan_out = np.prod(weight_shape[2:4]) * weight_shape[0]
        w_bound = np.sqrt(6. / (fan_in + fan_out))
        m.weight.data.uniform_(-w_bound, w_bound)
        m.bias.data.fill_(0)
    elif classname.find('Linear') != -1:
        weight_shape = list(m.weight.data.size())
        fan_in = weight_shape[1]
        fan_out = weight_shape[0]
        w_bound = np.sqrt(6. / (fan_in + fan_out))
        m.weight.data.uniform_(-w_bound, w_bound)
        m.bias.data.fill_(0)