Пример #1
0
    def select_channel(self, **kwargs):
        """
        This function lets the user choose one of the channels from the channels.py
        module. This choice is essential to the program because the channel's
        properties define number of syringes and volume to be dispensed.
        The target channel can also be passed to the function via the **kwargs
        argument. Example: Kwarg: channel = "Single meander channel"
        """
        def error_message(error_number):
            """ nested function that defines the error message to be given when the
            kwargs are wrong."""
            print(
                "Error number: {}\n".format(error_number),
                "Error in keyword arguments provided.",
                "\nProvided {}.\n".format(kwargs),
                "Expected:\n'channel' = {}".format(
                    self.print_dict_keys(c.channel_dict)),
                "\nProgram aborted.",
            )
            p.logger_pump.debug(
                "Error message {}: ".format(number),
                "Function 'select_channel()' aborted",
                " due to errors in the kwargs: {}.".format(kwargs))
            raise SystemExit("Program aborted.")

        if kwargs:
            channel = kwargs.get("channel", None)
            if channel is None:
                error_message(1)
            else:
                if channel not in c.channel_dict.keys():
                    error_message(2)
                else:
                    self.channel_used = channel
                    self.channel = c.Channel(c.channel_dict[self.channel_used])
                    self.max_flowrate = self.channel.max_flowrate
                    p.logger_pump.info("Selected channel: {}.".format(
                        self.channel_used))
        else:
            print("Select channel:")
            for item in sorted(c.channel_dict):
                print("{}: {}".format(
                    sorted(c.channel_dict).index(item) + 1, item))
            channel_number = input("> ")
            try:
                number = int(channel_number)
                if number <= len(sorted(c.channel_dict)):
                    self.channel_used = sorted(c.channel_dict)[number - 1]
                    self.channel = c.Channel(c.channel_dict[self.channel_used])
                    self.max_flowrate = self.channel.max_flowrate
                    p.logger_pump.info("Selected channel: {}.".format(
                        self.channel_used))
                else:
                    print("There is no channel with number {}.".format(number))
                    return self.select_channel()
            except ValueError:
                print("Please select a number between 1 and {}.".format(
                    len(sorted(c.channel_dict))))
                return self.select_channel()
Пример #2
0
 def get(self, name=False):
     self.response.headers.add_header("Access-Control-Allow-Origin", "*")
     user = auth.getCurrentUser()
     response = {}
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         if not name:
             name = "Chrome"
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except models.DeviceDoesNotExistError:
             device = models.DeviceData(user=user_data, name=name).save()
         try:
             channel = channels.Channel(device.address,
                                        override_quota=user_data.immune())
             response['token'] = channel.token
             if channel.cached:
                 response['code'] = 304
             else:
                 response['code'] = 200
         except channels.OverQuotaError:
             response['code'] = 503
             response['token'] = 'overquota'
             response['message'] = "Server is over quota."
     else:
         response['code'] = 401
         response['message'] = 'Not logged in.'
     self.response.out.write(simplejson.dumps(response))
Пример #3
0
def run_django(channel, models, transaction, framework):
    client = docker.from_env()

    executor = [e for e in constants.EXECUTORS if e.key == framework][0]

    try:
        result = client.containers.run(executor.image,
                                       remove=True,
                                       environment=[
                                           'MODELS={}'.format(models),
                                           'TRANSACTION={}'.format(transaction)
                                       ])
    except ContainerError as error:  # Do some logging
        reply = json.dumps(
            dict(event=constants.JOB_CODE_ERROR_EVENT,
                 error=error.stderr.decode('utf-8')))
    except ImageNotFound as error:
        reply = json.dumps(
            dict(event=constants.JOB_IMAGE_NOT_FOUND_ERROR_EVENT,
                 error=f'Executor for {executor.verbose} not found!'))
    except APIError as error:  # Do some logging
        reply = json.dumps(
            dict(event=constants.JOB_INTERNAL_ERROR_EVENT,
                 error=error.explanation))
    else:
        decoded = result.decode('utf-8')

        # TODO: too much encoding/decoding, should revisit
        reply = json.dumps(
            dict(event=constants.JOB_DONE_EVENT, result=json.loads(decoded)))
    finally:
        channels.Channel(channel).send(dict(text=reply))
Пример #4
0
    def dispatch(self, request, *args, **kwargs):
        session_config_name = kwargs['session_config']
        try:
            session_config = SESSION_CONFIGS_DICT[session_config_name]
        except KeyError:
            msg = ("Session config '{}' not found").format(session_config_name)
            raise Http404(msg)
        # check that it divides evenly
        # need to check here so that the user knows upfront
        session_lcm = otree.session.get_lcm(session_config)
        num_participants = session_config['num_demo_participants']
        if num_participants % session_lcm:
            msg = ('Session Config {}: Number of participants ({}) does not '
                   'divide evenly into group size ({})').format(
                       session_config_name, num_participants, session_lcm)
            raise Http404(msg)

        pre_create_id = uuid.uuid4().hex
        kwargs = {
            'special_category': constants.session_special_category_demo,
            'session_config_name': session_config_name,
            '_pre_create_id': pre_create_id,
        }

        channels_group_name = channels_create_session_group_name(pre_create_id)
        channels.Channel('otree.create_session').send({
            'kwargs':
            kwargs,
            'channels_group_name':
            channels_group_name
        })

        wait_for_session_url = reverse('wait_for_session',
                                       args=(pre_create_id, ))
        return HttpResponseRedirect(wait_for_session_url)
Пример #5
0
    def form_valid(self, form):
        pre_create_id = uuid.uuid4().hex
        kwargs = {
            'session_config_name': form.cleaned_data['session_config'],
            '_pre_create_id': pre_create_id,
            'for_mturk': self.for_mturk
        }
        if self.for_mturk:
            kwargs['num_participants'] = (
                form.cleaned_data['num_participants'] *
                settings.MTURK_NUM_PARTICIPANTS_MULT)

        else:
            kwargs['num_participants'] = form.cleaned_data['num_participants']

        # TODO:
        # Refactor when we upgrade to push
        if hasattr(self, "room"):
            kwargs['room'] = self.room

        channels_group_name = channels_create_session_group_name(pre_create_id)
        channels.Channel('otree.create_session').send({
            'kwargs':
            kwargs,
            'channels_group_name':
            channels_group_name
        })

        wait_for_session_url = reverse('wait_for_session',
                                       args=(pre_create_id, ))
        return HttpResponseRedirect(wait_for_session_url)
Пример #6
0
def post_save_handler(sender, instance, created, **kwargs):
    if (created):
        print("question created : ", instance.slug)
        channels.Channel('question-list').send({
            'type': 'new',
            'slug': instance.slug,
        })
Пример #7
0
    def __init__(self, stream_data):
        """
        :params: stream_data - stream data in JSON
        """
        if stream_data is None:
            raise AssertionError('received empty data')
        self._data = stream_data

        # stream is offline
        if self._data is None:
            self.online = False
            self.channel = None
            self.broadcaster = None
            self.preview = None
            self.stream_id = None
            self.viewers = 0
            self.display_name = None
            self.status = None
            self.game = None
            self.url = None

        # stream is online
        else:
            self.online = True
            self.channel = channels.Channel(self._data['channel'])
            self.broadcaster = str(self._data.get('broadcaster'))
            self.preview = str(self._data.get('preview'))
            self.stream_id = str(self._data.get('_id'))
            self.viewers = int(self._data.get('viewers', 0))
            self.display_name = str(self.channel.display_name)
            self.status = self.channel.status
            self.game = str(self._data.get('game'))
            self.url = str(self.channel.url)
Пример #8
0
 def get(self):
     user = auth.getCurrentUser()
     name = "Web"
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except models.DeviceDoesNotExistError:
             device = models.DeviceData(user=user_data, name=name).save()
         over_quota = False
         try:
             channel = channels.Channel(device.address,
                                        override_quota=user_data.immune())
             channel_token = channel.token
         except channels.OverQuotaError:
             over_quota = True
             channel_token = 'overquota'
         template_values = {
             'channel_id': channel_token,
             'device': device.address,
             'device_name': device.name,
             'devices': user_data.getDevices(),
             'over_quota': over_quota
         }
         path = os.path.join(os.path.dirname(__file__),
                             'devlinks_index.html')
         self.response.out.write(template.render(path, template_values))
     else:
         self.redirect(users.create_login_url(self.request.uri))
Пример #9
0
def incident_post_save(sender, **kwargs):
    print('GROUP MODEL HAS BEEN JUST SAVED YOUPTA!:::', sender)
    channels.Channel("braintree_process").send({
        "group_pk": 'sender.pk',
        "price": 'sender.price',
    })
    print('SENDING MESSAGE TO GROUP>>>>>>{}')
Пример #10
0
 def _tubing_volume():
     """
     get the volume of each tubing connecting the syringes to
     the channel's inlets.
     """
     used_channel = c.Channel(c.channel_dict[channel])
     self.max_flowrate = used_channel.max_flowrate
     for key in used_channel.tubing_x.keys():
         if used_channel.tubing_x[key] > 0:
             self.dict_tubing_volume[key] = used_channel.volume_tubing(key)
Пример #11
0
    def onMessage(self, payload, isBinary):
        """
        Send the payload onto the {slack.[payload['type]'} channel.
        The message is transalated from IDs to human-readable identifiers.

        Note: The slack API only sends JSON, isBinary will always be false.
        """
        msg = self.translate(unpack(payload))
        if 'type' in msg:
            channel_name = 'slack.{}'.format(msg['type'])
            print('Sending on {}'.format(channel_name))
            channels.Channel(channel_name).send({'text': pack(msg)})
Пример #12
0
    def washing(self):
        """
        This function needs to be called in the beginning and end of each program to
        wash the channel. The program assumes that all inlets of the chosen channel
        from select_channel() are connected to the same syringe type from
        select_syringe_washing(). Each pump will run with self.max_flowrate /
        number of inlets. After washing has finished, syringes need to be changed.
        """
        self.number_of_active_pumps = sum(
            value == True for value in self.pumps_active.values())
        channel = c.Channel(c.channel_dict[self.channel_used])
        volume_tubing_total = 0
        for key in channel.tubing_x:
            volume_tubing_total += channel.volume_tubing(key)
        # wash twice channel volume
        volume_per_syr = (channel.volume_total +
                          volume_tubing_total) * 2 / channel.inlets_number
        rate = self.max_flowrate / channel.inlets_number
        washing_time = round(volume_per_syr / rate * 3600)

        # write variables to the pumps
        if self.pumps_active["LA120"]:
            self.LA120.diameter(self.syringes.syringes[self.syringe_washing])
            self.LA120.volume(volume_per_syr, "ul")
            self.LA120.rate(rate, "ul/h")

        if self.pumps_active["LA122"]:
            self.LA122.diameter(self.syringes.syringes[self.syringe_washing])
            self.LA122.volume(volume_per_syr, "ul")
            self.LA122.rate(rate, "ul/h")

        if self.pumps_active["LA160"]:
            self.LA160.diameter(self.syringes.syringes[self.syringe_washing])
            self.LA160.volume(volume_per_syr, "ul")
            self.LA160.rate(rate, "ul/h")
        # the start command is issued separately because pumps will not start at the same time otherwise.
        if self.pumps_active["LA120"]:
            self.LA120.start()
        if self.pumps_active["LA122"]:
            self.LA122.start()
        if self.pumps_active["LA160"]:
            self.LA160.start()

        countdown(washing_time, "washing")

        if self.pumps_active["LA120"]:
            self.LA120.stop()
        if self.pumps_active["LA122"]:
            self.LA122.stop()
        if self.pumps_active["LA160"]:
            self.LA160.stop()
Пример #13
0
def create_session_and_redirect(session_kwargs):
    pre_create_id = uuid.uuid4().hex
    session_kwargs['_pre_create_id'] = pre_create_id
    channels_group_name = channels_create_session_group_name(pre_create_id)
    channels.Channel('otree.create_session').send({
        'kwargs':
        session_kwargs,
        'channels_group_name':
        channels_group_name
    })

    wait_for_session_url = reverse('WaitUntilSessionCreated',
                                   args=(pre_create_id, ))
    return HttpResponseRedirect(wait_for_session_url)
Пример #14
0
 def channel_choise(self):
     self.channels = channels.Channel()
     self.channels.get_channels()
     self.channels.display_channels()
     self.channel_id = raw_input("input id of channels: ")
     if self.channel_id == 0:
         result = self.login()
         while not result:
             chose = raw_input('''error login, enter r to try again or
                                 g to give up''')
             if chose == 'g':
                 result = 1
             elif chose == 'r':
                 result = self.login()
     self.song_list = self.get_play_list('NEW')
Пример #15
0
def create_session_and_redirect(session_kwargs, *, use_browser_bots):
    pre_create_id = uuid.uuid4().hex
    session_kwargs['pre_create_id'] = pre_create_id
    channels_group_name = channel_utils.create_session_group_name(
        pre_create_id)
    channels.Channel('otree.create_session').send({
        'kwargs':
        session_kwargs,
        'channels_group_name':
        channels_group_name,
        'use_browser_bots':
        use_browser_bots,
    })

    return redirect('WaitUntilSessionCreated', pre_create_id)
Пример #16
0
def ws_pad_receive(message):
    """Handles a websocket message by putting it on the message channel.
    The message channel is separated from websocket.message so that the sending
    process/consumer can move on immediately and not spend time waiting for the
    database save and the (slow on some backends) Group.send() call.

    Connected to "websocket.receive".
    """

    # This message will be send with channel to the right pad consumer
    message_data = json.loads(message['text'])
    message_data['document'] = message.channel_session['document']
    message_data['user'] = message.user

    # Send the message to the right channel
    channels.Channel("pad.receive").send(message_data)
Пример #17
0
def ws_chat_receive(message):
    """Handles a websocket message by putting it on the message channel.
    The message channel is separated from websocket.message so that the sending
    process/consumer can move on immediately and not spend time waiting for the
    database save and the (slow on some backends) Group.send() call.

    Connected to "websocket.receive".
    """
    # Refuse empty message
    if len(message['text']) > 0:
        # Stick the message onto the processing queue
        channels.Channel("chat.receive").send({
            'group': message.channel_session['group'],
            'text': message['text'],
            'user': message.user
        })
Пример #18
0
 def get(self):
     user = users.User('*****@*****.**')
     try:
         user_data = models.getUser(user)
     except models.UserDoesNotExistError:
         user_data = models.UserData(user=user).save()
     try:
         device = models.getDevice("%s/%s" % (user.email(), "Web"))
     except models.DeviceDoesNotExistError:
         device = models.DeviceData(user=user_data, name="Web").save()
     channel = channels.Channel(device.address, override_quota=True)
     path = os.path.join(os.path.dirname(__file__), 'dashboard.html')
     stats_data = models.StatsData.all().order("-date").fetch(1000)
     template_values = {'channel_id': channel.token, 'stats': {}}
     stats = template_values['stats']
     for datapoint in stats_data:
         datestamp = int(
             time.mktime(datapoint.date.date().timetuple()) * 1000)
         hour = datapoint.date.hour
         if datestamp not in stats:
             stats[datestamp] = {
                 'datestamp': datestamp,
                 'date': datapoint.date,
                 'datapoints': {}
             }
         if datapoint.datapoint not in stats[datestamp]['datapoints']:
             stats[datestamp]['datapoints'][datapoint.datapoint] = {
                 'datapoint': datapoint.datapoint,
                 'values': {}
             }
         point_id = "%s" % hour
         if datapoint.duration == "day":
             point_id = "total"
         dp = datapoint.datapoint
         stats[datestamp]['datapoints'][dp]['values'][point_id] = {
             'datapoint': datapoint.datapoint,
             'datestamp': datestamp,
             'hour': hour,
             'count': int(datapoint.count),
             'duration': datapoint.duration
         }
     template_values['stats'] = stats
     logging.info(template_values)
     self.response.out.write(template.render(path, template_values))
Пример #19
0
    def before_next_page(self):
        self.subsession.room_busy = False
        self.subsession.save()
        channel_name = get_group_name(self.subsession.pk, 1)
        channel_layer = get_channel_layer()
        ch_group_list = channel_layer.group_channels(channel_name)
        if len(ch_group_list) > 0:
            if isinstance(ch_group_list, list):
                curname = ch_group_list[0]
            elif isinstance(ch_group_list, dict):
                curname = next(iter(ch_group_list.keys()))
            else:
                return None

            mychannel = channels.Channel(curname)
            mychannel.send({'text': json.dumps({'status': 'ready'})})

        self.player.decision_order = len(
            [p for p in self.subsession.get_players() if p.choice_of_urn])
Пример #20
0
 def post(self):
     self.response.headers.add_header("Access-Control-Allow-Origin", "*")
     user = auth.getCurrentUser()
     response = {}
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         name = self.request.get('name')
         if not name:
             name = "Chrome"
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except models.DeviceDoesNotExistError:
             device = models.DeviceData(name=name, user=user_data).save()
         receiver = None
         if self.request.get("receiver"):
             try:
                 receiver = models.getDevice(
                     "%s/%s" % (user.email(), self.request.get("receiver")))
             except models.DeviceDoesNotExistError:
                 receiver = models.DeviceData(
                     name=self.request.get("receiver"),
                     user=user_data).save()
         if receiver == None:
             receiver = device
         link = models.LinkData(url=self.request.get('link'),
                                sender=device,
                                receiver=receiver).save()
         if models.getQuota().amount >= models.getStats(
                 'channels').count or user_data.immune():
             channel = channels.Channel(receiver.address, False)
             channel.sendLink(link)
             response['code'] = 200
             response['link'] = link.url
         else:
             response['code'] = 503
             response['link'] = link.url
     else:
         response['code'] = 401
         response['link'] = self.request.get('link')
     self.response.out.write(simplejson.dumps(response))
Пример #21
0
 def post(self, name="Chrome"):
     self.response.headers.add_header("Access-Control-Allow-Origin", "*")
     user = auth.getCurrentUser()
     device = None
     if user:
         try:
             user_data = models.getUser(user)
         except models.UserDoesNotExistError:
             user_data = models.UserData(user=user).save()
         try:
             device = models.getDevice("%s/%s" % (user.email(), name))
         except:
             device = models.DeviceData(user=user_data, name=name).save()
         last_links = models.getUnreadLinks(device)
         channel = channels.Channel(device.address, False)
         for link in last_links:
             channel.queueLink(link)
         channel.send()
         stats.record("user_connected",
                      simplejson.dumps({"user": user.email()}))
         self.response.out.write(device.address)
Пример #22
0
 def post(self):
     record = prospective_search.get_document(self.request)
     record_value = simplejson.loads(record.value)
     subscriber_keys = map(db.Key, self.request.get_all('id'))
     subscribers = db.get(subscriber_keys)
     datapoints = []
     stats_json = []
     for subscriber_key, subscriber in zip(subscriber_keys, subscribers):
         if not subscriber:
             prospective_search.unsubscribe(stats.StatsRecord,
                                            subscriber_key)
         else:
             datapoints.append(
                 models.getStats(subscriber.datapoint,
                                 record.timestamp,
                                 duration='day'))
             datapoints.append(
                 models.getStats(subscriber.datapoint,
                                 record.timestamp,
                                 duration='hour'))
     for datapoint in datapoints:
         if datapoint.datapoint == 'active_users':
             try:
                 user = models.getUser(record_value['user'], False)
             except models.UserDoesNotExistError:
                 continue
             last_seen = user.last_seen
             new_last_seen = timestamp.now()
             if datapoint.duration == "day":
                 last_seen = last_seen.replace(hour=0,
                                               minute=0,
                                               second=0,
                                               microsecond=0)
                 new_last_seen = new_last_seen.replace(hour=0,
                                                       minute=0,
                                                       second=0,
                                                       microsecond=0)
             if last_seen < new_last_seen:
                 user.updateLastSeen(new_last_seen)
                 user.save()
             else:
                 continue
         if datapoint.datapoint == 'quota':
             datapoint.count = models.getQuota().amount
         else:
             datapoint.increment()
         json = {
             'datapoint': datapoint.datapoint,
             'value': datapoint.count,
             'date': datapoint.date.strftime("%D, %M %d %y"),
             'datestamp':
             int(time.mktime(datapoint.date.date().timetuple())) * 1000,
             'hour': datapoint.date.hour
         }
         if datapoint.duration == "day":
             json['hour'] = "total"
         stats_json.append(json)
     db.put(datapoints)
     push = channels.Channel("[email protected]/Web", False)
     push.message = {"stats": stats_json}
     push.send()
     logging.debug(simplejson.dumps(stats_json))