Beispiel #1
0
def general_settings(request):
    """
    Returns and processes the general settings section.
    """
    npc_threshold = get_config("MAP_NPC_THRESHOLD", None)
    pvp_threshold = get_config("MAP_PVP_THRESHOLD", None)
    scan_threshold = get_config("MAP_SCAN_WARNING", None)
    interest_time = get_config("MAP_INTEREST_TIME", None)
    escalation_burn = get_config("MAP_ESCALATION_BURN", None)
    if request.method == "POST":
        scan_threshold.value = int(request.POST['scanwarn'])
        interest_time.value = int(request.POST['interesttimeout'])
        pvp_threshold.value = int(request.POST['pvpthreshold'])
        npc_threshold.value = int(request.POST['npcthreshold'])
        escalation_burn.value = int(request.POST['escdowntimes'])
        scan_threshold.save()
        interest_time.save()
        pvp_threshold.save()
        npc_threshold.save()
        escalation_burn.save()
        return HttpResponse()
    return TemplateResponse(
        request, 'general_settings.html', {
            'npcthreshold': npc_threshold.value,
            'pvpthreshold': pvp_threshold.value,
            'scanwarn': scan_threshold.value,
            'interesttimeout': interest_time.value,
            'escdowntimes': escalation_burn.value
        })
Beispiel #2
0
 def __init__(self, map, user):
     self.map = map
     self.user = user
     self.levelY = 0
     self.pvp_threshold = int(get_config("MAP_PVP_THRESHOLD", user).value)
     self.npc_threshold = int(get_config("MAP_NPC_THRESHOLD", user).value)
     self.interest_time = int(get_config("MAP_INTEREST_TIME", user).value)
Beispiel #3
0
def general_settings(request):
    """
    Returns and processes the general settings section.
    """
    npc_threshold = get_config("MAP_NPC_THRESHOLD", None)
    pvp_threshold = get_config("MAP_PVP_THRESHOLD", None)
    scan_threshold = get_config("MAP_SCAN_WARNING", None)
    interest_time = get_config("MAP_INTEREST_TIME", None)
    escalation_burn = get_config("MAP_ESCALATION_BURN", None)
    if request.method == "POST":
        scan_threshold.value = int(request.POST["scanwarn"])
        interest_time.value = int(request.POST["interesttimeout"])
        pvp_threshold.value = int(request.POST["pvpthreshold"])
        npc_threshold.value = int(request.POST["npcthreshold"])
        escalation_burn.value = int(request.POST["escdowntimes"])
        scan_threshold.save()
        interest_time.save()
        pvp_threshold.save()
        npc_threshold.save()
        escalation_burn.save()
        return HttpResponse()
    return TemplateResponse(
        request,
        "general_settings.html",
        {
            "npcthreshold": npc_threshold.value,
            "pvpthreshold": pvp_threshold.value,
            "scanwarn": scan_threshold.value,
            "interesttimeout": interest_time.value,
            "escdowntimes": escalation_burn.value,
        },
    )
Beispiel #4
0
def general_settings(request):
    """
    Returns and processes the general settings section.
    """
    npc_threshold = get_config("MAP_NPC_THRESHOLD", None)
    pvp_threshold = get_config("MAP_PVP_THRESHOLD", None)
    scan_threshold = get_config("MAP_SCAN_WARNING", None)
    interest_time = get_config("MAP_INTEREST_TIME", None)
    escalation_burn = get_config("MAP_ESCALATION_BURN", None)
    if request.method == "POST":
        scan_threshold.value = int(request.POST['scanwarn'])
        interest_time.value = int(request.POST['interesttimeout'])
        pvp_threshold.value = int(request.POST['pvpthreshold'])
        npc_threshold.value = int(request.POST['npcthreshold'])
        escalation_burn.value = int(request.POST['escdowntimes'])
        scan_threshold.save()
        interest_time.save()
        pvp_threshold.save()
        npc_threshold.save()
        escalation_burn.save()
        return HttpResponse()
    return TemplateResponse(
        request, 'general_settings.html',
        {'npcthreshold': npc_threshold.value,
         'pvpthreshold': pvp_threshold.value,
         'scanwarn': scan_threshold.value,
         'interesttimeout': interest_time.value,
         'escdowntimes': escalation_burn.value}
    )
Beispiel #5
0
def display_settings(request, user=None):
    """
    Returns and processes the display settings section.
    """
    if not user and not request.user.has_perm('Map.map_admin'):
        raise PermissionDenied
    if user:
        user = request.user
    zen_mode = get_config("MAP_ZEN_MODE", user)
    pilot_list = get_config("MAP_PILOT_LIST", user)
    details_combined = get_config("MAP_DETAILS_COMBINED", user)
    render_tags = get_config("MAP_RENDER_WH_TAGS", user)
    highlight_active = get_config("MAP_HIGHLIGHT_ACTIVE", user)
    auto_refresh = get_config("MAP_AUTO_REFRESH", user)
    scaling_factor = get_config("MAP_SCALING_FACTOR", user)
    kspace_mapping = get_config('MAP_KSPACE_MAPPING', user)
    silent_mapping = get_config("MAP_SILENT_MAPPING", user)
    render_collapsed = get_config("MAP_RENDER_COLLAPSED", user)
    saved = False
    if request.method == "POST":
        if user:
            return _process_user_display_settings(request, user)
        else:
            zen_mode.value = request.POST.get('zen_mode', 0)
            pilot_list.value = request.POST.get('pilot_list', 0)
            details_combined.value = request.POST.get('details_combined', 0)
            render_tags.value = request.POST.get('render_tags', 0)
            scaling_factor.value = request.POST.get('scaling_factor', 1)
            highlight_active.value = request.POST.get('highlight_active', 0)
            auto_refresh.value = request.POST.get('auto_refresh', 0)
            kspace_mapping.value = request.POST.get('kspace_mapping', 0)
            silent_mapping.value = request.POST.get('silent_mapping', 0)
            render_collapsed.value = request.POST.get('render_collapsed', 0)
            zen_mode.save()
            pilot_list.save()
            details_combined.save()
            render_tags.save()
            scaling_factor.save()
            highlight_active.save()
            auto_refresh.save()
            kspace_mapping.save()
            silent_mapping.save()
            render_collapsed.save()
        saved = True

    return TemplateResponse(
        request, 'display_settings.html', {
            'zen_mode': zen_mode.value,
            'pilot_list': pilot_list.value,
            'details_combined': details_combined.value,
            'render_tags': render_tags.value,
            'scaling_factor': scaling_factor.value,
            'highlight_active': highlight_active.value,
            'auto_refresh': auto_refresh.value,
            'kspace_mapping': kspace_mapping.value,
            'silent_mapping': silent_mapping.value,
            'render_collapsed': render_collapsed.value,
            'saved': saved,
            'context_user': user,
        })
Beispiel #6
0
def get_system_context(ms_id, user):
    map_system = get_object_or_404(MapSystem, pk=ms_id)
    if map_system.map.get_permission(user) == 2:
        can_edit = True
    else:
        can_edit = False
    # If map_system represents a k-space system get the relevant KSystem object
    if map_system.system.is_kspace():
        system = map_system.system.ksystem
    else:
        system = map_system.system.wsystem

    scan_threshold = datetime.now(pytz.utc) - timedelta(hours=int(get_config("MAP_SCAN_WARNING", None).value))
    interest_offset = int(get_config("MAP_INTEREST_TIME", None).value)
    interest_threshold = datetime.now(pytz.utc) - timedelta(minutes=interest_offset)

    scan_warning = system.lastscanned < scan_threshold
    if interest_offset > 0:
        interest = map_system.interesttime and map_system.interesttime > interest_threshold
    else:
        interest = map_system.interesttime
        # Include any SiteTracker fleets that are active
    st_fleets = map_system.system.stfleets.filter(ended=None).all()
    locations = cache.get("sys_%s_locations" % map_system.system.pk)
    if not locations:
        locations = {}
    return {
        "system": system,
        "mapsys": map_system,
        "scanwarning": scan_warning,
        "isinterest": interest,
        "stfleets": st_fleets,
        "locations": locations,
        "can_edit": can_edit,
    }
Beispiel #7
0
 def send_alert(self, to_users, subject, message, from_user, sub_group):
     jid_list = []
     from_jid = get_config("JABBER_FROM_JID", None).value
     from_password = get_config("JABBER_FROM_PASSWORD", None).value
     jid_space_char = get_config("JABBER_LOCAL_SPACE_CHAR", None).value
     jabber_domain = get_config("JABBER_LOCAL_DOMAIN", None).value
     local_jabber = get_config("JABBER_LOCAL_ENABLED", None).value == "1"
     full_message = render_to_string(
         "jabber_message.txt", {
             'subject': subject,
             'message': message,
             'sub_group': sub_group.name,
             'from_user': from_user.username,
             'time': datetime.now(pytz.utc)
         })
     for user in to_users:
         if self.is_registered(user, sub_group):
             if local_jabber:
                 jid_list.append(("%s@%s" % (user.username.replace(
                     " ", jid_space_char), jabber_domain)).encode('utf-8'))
             for jid in user.jabber_accounts.all():
                 jid_list.append(jid.jid.encode('utf-8'))
     client = JabberClient(jid=from_jid.encode('utf-8'),
                           password=from_password.encode('utf-8'),
                           to_list=jid_list,
                           message=full_message.encode('utf-8'))
     if client.connect():
         client.process()
Beispiel #8
0
def get_system_context(ms_id):
    map_system = get_object_or_404(MapSystem, pk=ms_id)

    #If map_system represents a k-space system get the relevant KSystem object
    if map_system.system.is_kspace():
        system = map_system.system.ksystem
    else:
        system = map_system.system.wsystem

    scan_threshold = datetime.now(pytz.utc) - timedelta(
        hours=int(get_config("MAP_SCAN_WARNING", None).value))
    interest_offset = int(get_config("MAP_INTEREST_TIME", None).value)
    interest_threshold = (datetime.now(pytz.utc) -
                          timedelta(minutes=interest_offset))

    scan_warning = system.lastscanned < scan_threshold
    if interest_offset > 0:
        interest = (map_system.interesttime
                    and map_system.interesttime > interest_threshold)
    else:
        interest = map_system.interesttime
        # Include any SiteTracker fleets that are active
    st_fleets = map_system.system.stfleets.filter(ended=None).all()
    return {
        'system': system,
        'mapsys': map_system,
        'scanwarning': scan_warning,
        'isinterest': interest,
        'stfleets': st_fleets
    }
Beispiel #9
0
def get_system_context(ms_id):
    map_system = get_object_or_404(MapSystem, pk=ms_id)

    #If map_system represents a k-space system get the relevant KSystem object
    if map_system.system.is_kspace():
        system = map_system.system.ksystem
    else:
        system = map_system.system.wsystem

    scan_threshold = datetime.now(pytz.utc) - timedelta(
        hours=int(get_config("MAP_SCAN_WARNING", None).value)
    )
    interest_offset = int(get_config("MAP_INTEREST_TIME", None).value)
    interest_threshold = (datetime.now(pytz.utc)
                          - timedelta(minutes=interest_offset))

    scan_warning = system.lastscanned < scan_threshold
    if interest_offset > 0:
        interest = (map_system.interesttime and
                    map_system.interesttime > interest_threshold)
    else:
        interest = map_system.interesttime
        # Include any SiteTracker fleets that are active
    st_fleets = map_system.system.stfleets.filter(ended=None).all()
    return {'system': system, 'mapsys': map_system,
            'scanwarning': scan_warning, 'isinterest': interest,
            'stfleets': st_fleets}
 def __init__(self, *args, **kwargs):
     BaseCommand.__init__(self, *args, **kwargs)
     self.local_enabled = False
     # Change this to True to log requests for debug *logs may include passwords*
     self.LOGGING_ENABLED = False
     if get_config("JABBER_LOCAL_ENABLED",None).value == "1":
         self.local_enabled = True
         self.local_user = get_config("JABBER_FROM_JID", False).value.split('@')[0]
         self.local_pass = get_config("JABBER_FROM_PASSWORD", False).value
         self.space_char = get_config("JABBER_LOCAL_SPACE_CHAR", False).value
 def __init__(self, *args, **kwargs):
     BaseCommand.__init__(self, *args, **kwargs)
     self.local_enabled = False
     # Change this to True to log requests for debug *logs may include passwords*
     self.LOGGING_ENABLED = False
     if get_config("JABBER_LOCAL_ENABLED",None).value == "1":
         self.local_enabled = True
         self.local_user = get_config("JABBER_FROM_JID", False).value.split('@')[0]
         self.local_pass = get_config("JABBER_FROM_PASSWORD", False).value
         self.space_char = get_config("JABBER_LOCAL_SPACE_CHAR", False).value
Beispiel #12
0
 def get_settings(self):
     from core.utils import get_config
     from core.models import ConfigEntry
     config_dict = dict()
     for x in ConfigEntry.objects.filter(user=None).all():
         config_dict[x.name] = get_config(x.name, self).value
     return config_dict
Beispiel #13
0
def applicant_register(request, app_type=None):
    email_required = get_config("RECRUIT_REQUIRE_EMAIL", None).value == "1"
    if not app_type:
        app_type = get_object_or_404(AppType, pk=request.POST.get("app_type"))
    if request.method == "POST":
        form = RecruitRegistrationForm(request.POST)
        valid = form.is_valid()
        email = request.POST.get("email", None)
        if email_required and not email:
            form.errors["__all__"] = form.error_class(["An email address is required."])
            valid = False
        if valid:
            newUser = form.save()
            newUser.is_active = False
            if email:
                newUser.email = email
            newUser.save()
            log_user = authenticate(username=newUser.username, password=request.POST.get("password1", ""))
            login(request, log_user)
            return HttpResponseRedirect(request.POST.get("next_page"))
    else:
        form = RecruitRegistrationForm()
    next_page = reverse("Recruitment.views.get_application", args=(app_type.pk,))
    return TemplateResponse(
        request,
        "recruit_register.html",
        {"form": form, "email_required": email_required, "next_page": next_page, "app_type": app_type},
    )
Beispiel #14
0
 def credit_site(self, site_type, system, boss):
     """
     Credits a site.
     """
     # Get the fleet member weighting variable and multiplier
     x = float(get_config("ST_SIZE_WEIGHT", None).value)
     n = self.members.count()
     if x > 1:
         weight_factor = x / float(n + (x - 1))
     else:
         # If the factor is set to anything equal to or less than 1,
         # we will not weight the results by fleet size
         weight_factor = float(1)
     if SystemWeight.objects.filter(system=system).count():
         weight_factor = weight_factor * system.st_weight.weight
     raw_points = SiteWeight.objects.get(
         site_type=site_type, sysclass=system.sysclass).raw_points
     site = SiteRecord(fleet=self,
                       site_type=site_type,
                       system=system,
                       boss=boss,
                       fleetsize=self.members.count(),
                       raw_points=raw_points,
                       weighted_points=raw_points * weight_factor)
     site.save()
     for user in self.members.filter(leavetime=None).all():
         site.members.add(UserSite(site=site, user=user.user,
                                   pending=False))
     return site
Beispiel #15
0
 def system_to_dict(self, system, levelX):
     """
     Takes a MapSystem and X,Y data and returns the dict of information to be passed to
     the map JS as JSON.
     """
     interesttime = int(get_config("MAP_INTEREST_TIME", self.user).value)
     threshold = datetime.datetime.now(pytz.utc) - timedelta(minutes=interesttime)
     if system.interesttime and system.interesttime > threshold:
         interest = True
     else:
         interest = False
     if system.map.systems.filter(interesttime__gt=threshold).count() != 0:
         path = False
         for sys in system.map.systems.filter(interesttime__gt=threshold).all():
             if system in self.get_path_to_map_system(sys):
                 path = True
     else:
         path = False
     activity_estimate = (system.system.podkills + system.system.npckills +
             system.system.shipkills)
     from Map.models import WSystem
     if system.system.is_wspace():
         effect = WSystem.objects.get(pk=system.system.pk).effect
     else:
         effect = None
     if system.parentsystem:
         parentWH = system.parent_wormholes.get()
         if parentWH.collapsed:
             collapsed = True
         else:
             collapsed = False
         result = {'sysID': system.system.pk, 'Name': system.system.name,
                 'LevelX': levelX,'activity': activity_estimate,
                 'LevelY': self.levelY, 'SysClass': system.system.sysclass,
                 'Friendly': system.friendlyname, 'interest': interest,
                 'interestpath': path, 'ParentID': system.parentsystem.pk,
                 'activePilots': system.system.active_pilots.count(),
                 'WhToParent': parentWH.bottom_type.name,
                 'WhFromParent': parentWH.top_type.name,
                 'WhMassStatus': parentWH.mass_status,
                 'WhTimeStatus': parentWH.time_status,
                 'WhToParentBubbled': parentWH.bottom_bubbled,
                 'WhFromParentBubbled': parentWH.top_bubbled,
                 'imageURL': self.get_system_icon(system),
                 'whID': parentWH.pk, 'msID': system.pk,
                 'effect': effect, 'collapsed': collapsed}
     else:
         result = {'sysID': system.system.pk, 'Name': system.system.name,
                 'LevelX': levelX, 'activity': activity_estimate,
                 'LevelY': self.levelY, 'SysClass': system.system.sysclass,
                 'Friendly': system.friendlyname, 'interest': interest,
                 'interestpath': path, 'ParentID': None,
                 'activePilots': system.system.active_pilots.count(),
                 'WhToParent': "", 'WhFromParent': "",
                 'WhMassStatus': None, 'WhTimeStatus': None,
                 'WhToParentBubbled': None, 'WhFromParentBubbled': None,
                 'imageURL': self.get_system_icon(system),
                 'whID': None, 'msID': system.pk,
                 'effect': effect, 'collapsed': False}
     return result
Beispiel #16
0
 def credit_site(self, site_type, system, boss):
     """
     Credits a site.
     """
     # Get the fleet member weighting variable and multiplier
     x = float(get_config("ST_SIZE_WEIGHT", None).value)
     n = self.members.count()
     if x > 1:
         weight_factor = x / float(n + (x - 1))
     else:
         # If the factor is set to anything equal to or less than 1,
         # we will not weight the results by fleet size
         weight_factor = float(1)
     if SystemWeight.objects.filter(system=system).count():
         weight_factor = weight_factor * system.st_weight.weight
     raw_points = SiteWeight.objects.get(site_type=site_type, sysclass=system.sysclass).raw_points
     site = SiteRecord(
         fleet=self,
         site_type=site_type,
         system=system,
         boss=boss,
         fleetsize=self.members.count(),
         raw_points=raw_points,
         weighted_points=raw_points * weight_factor,
     )
     site.save()
     for user in self.members.filter(leavetime=None).all():
         site.members.add(UserSite(site=site, user=user.user, pending=False))
     return site
Beispiel #17
0
 def get_settings(self):
     from core.utils import get_config
     from core.models import ConfigEntry
     config_dict = dict()
     for x in ConfigEntry.objects.filter(user=None).all():
         config_dict[x.name] = get_config(x.name, self).value
     return config_dict
Beispiel #18
0
    def send_alert(self, to_users, subject, message, from_user, sub_group):
        subdomain = get_config("SLACK_SUBDOMAIN", None).value

        if self.exists(sub_group):
            channel = SlackChannel.objects.get(group=sub_group)
            destination = "https://%s.slack.com/services/hooks/incoming-webhook?token=%s" % (
                subdomain, channel.token)
            payload = {
                'payload':
                json.dumps({
                    'channel':
                    channel.channel,
                    'username':
                    "******",
                    'attachments': [{
                        'pretext':
                        'Notifying <!channel> for new ping from <@%s>' %
                        (from_user.username, ),
                        'fallback':
                        "EWS-PING: %s - %s" % (subject, message),
                        'fields': [{
                            'title': subject,
                            'value': message
                        }]
                    }]
                })
            }
            r = requests.post(destination, data=payload)
            return {'status_code': r.status_code, 'text': r.text}
Beispiel #19
0
    def send_alert(self, to_users, subject, message, from_user, sub_group):
        subdomain = get_config("SLACK_SUBDOMAIN", None).value

        if self.exists(sub_group):
            header = '%s - %s' % (from_user.username, subject)
            channel = SlackChannel.objects.get(group=sub_group)
            destination = "https://%s.slack.com/services/hooks/incoming-webhook?token=%s" % (
                subdomain, channel.token)
            payload = {
                'payload':
                json.dumps({
                    'channel':
                    channel.channel,
                    'username':
                    "******",
                    'attachments': [{
                        'fallback':
                        "New alert!",
                        'fields': [{
                            'title': header,
                            'value': message
                        }]
                    }]
                })
            }
            requests.post(destination, data=payload)
Beispiel #20
0
 def delete_old_sigs(self, user):
     delete_threshold = int(get_config("MAP_AUTODELETE_DAYS", user).value)
     for sig in self.system.signatures.all():
         now = datetime.now(pytz.utc)
         if (sig.sigtype and sig.sigtype.shortname == 'WH' and
                 sig.modified_time < (now - timedelta(days=2))):
             sig.delete(user, self)
         elif sig.modified_time < (now - timedelta(days=delete_threshold)):
             sig.delete(user, self)
Beispiel #21
0
def get_signature_list(request, map_id, ms_id):
    """
    Determines the proper escalationThreshold time and renders
    system_signatures.html
    """
    if not request.is_ajax():
        raise PermissionDenied
    system = get_object_or_404(MapSystem, pk=ms_id)
    escalation_downtimes = int(get_config("MAP_ESCALATION_BURN", request.user).value)
    return TemplateResponse(request, "system_signatures.html", {"system": system, "downtimes": escalation_downtimes})
Beispiel #22
0
 def send_alert(self, to_users, subject, message, from_user, sub_group):
     jid_list = []
     from_jid = get_config("JABBER_FROM_JID", None).value
     from_password = get_config("JABBER_FROM_PASSWORD", None).value
     jid_space_char = get_config("JABBER_LOCAL_SPACE_CHAR", None).value
     jabber_domain = get_config("JABBER_LOCAL_DOMAIN", None).value
     local_jabber = get_config("JABBER_LOCAL_ENABLED", None).value == "1"
     full_message = render_to_string("jabber_message.txt", {'subject': subject,
         'message': message, 'sub_group': sub_group.name,
         'from_user': from_user.username, 'time': datetime.now(pytz.utc)})
     for user in to_users:
         if self.is_registered(user, sub_group):
             if local_jabber:
                 jid_list.append(str("%s@%s" % (user.username.replace(" ",
                     jid_space_char), jabber_domain)))
             for jid in user.jabber_accounts.all():
                 jid_list.append(str(jid.jid))
     client = JabberClient(jid=str(from_jid), password=str(from_password), to_list=jid_list, message=str(full_message))
     if client.connect():
         client.process()
Beispiel #23
0
    def get_system_icon(self, system):
        """
        Takes a MapSystem and returns the appropriate icon to display on the map
        as a realative URL.
        """
        pvp_threshold = int(get_config("MAP_PVP_THRESHOLD", self.user).value)
        npc_threshold = int(get_config("MAP_NPC_THRESHOLD", self.user).value)
        staticPrefix = "%s" % (settings.STATIC_URL + "images/")
        if system.system.active_pilots.filter(user=self.user).count():
            return staticPrefix + "mylocation.png"

        if system.stfleets.filter(ended__isnull=True).count() != 0:
            return staticPrefix + "farm.png"

        if system.system.shipkills + system.system.podkills > pvp_threshold:
            return staticPrefix + "pvp.png"

        if system.system.npckills > npc_threshold:
            return staticPrefix + "carebears.png"

        return None
Beispiel #24
0
    def get_system_icon(self, system):
        """
        Takes a MapSystem and returns the appropriate icon to display on the map
        as a realative URL.
        """
        pvp_threshold = int(get_config("MAP_PVP_THRESHOLD", self.user).value)
        npc_threshold = int(get_config("MAP_NPC_THRESHOLD", self.user).value)
        staticPrefix = "%s" % (settings.STATIC_URL + "images/")
        if system.system.active_pilots.filter(user=self.user).count():
            return staticPrefix + "mylocation.png"

        if system.system.stfleets.filter(ended__isnull=True).count() != 0:
            return staticPrefix + "farm.png"

        if system.system.shipkills + system.system.podkills > pvp_threshold:
            return staticPrefix + "pvp.png"

        if system.system.npckills > npc_threshold:
            return staticPrefix + "carebears.png"

        return None
    def send_alert(self, to_users, subject, message, from_user, sub_group):
        subdomain = get_config("SLACK_SUBDOMAIN", None).value

        if self.exists(sub_group):
            header = '%s - %s' % (from_user.username, subject)
            channel = SlackChannel.objects.get(group=sub_group)
            destination = "https://%s.slack.com/services/hooks/incoming-webhook?token=%s" % (subdomain, channel.token)
            payload = {'payload':json.dumps({'channel': channel.channel,
                'username': "******",
                'attachments':[{'fallback': "New alert!",
                    'fields':[{'title': header, 'value': message}]}]})}
            requests.post(destination, data=payload)
Beispiel #26
0
def get_system_context(ms_id, user):
    map_system = get_object_or_404(MapSystem, pk=ms_id)
    if map_system.map.get_permission(user) == 2:
        can_edit = True
    else:
        can_edit = False
    # If map_system represents a k-space system get the relevant KSystem object
    if map_system.system.is_kspace():
        system = map_system.system.ksystem
    else:
        system = map_system.system.wsystem

    scan_threshold = datetime.now(pytz.utc) - timedelta(
        hours=int(get_config("MAP_SCAN_WARNING", None).value))
    interest_offset = int(get_config("MAP_INTEREST_TIME", None).value)
    interest_threshold = (datetime.now(pytz.utc) -
                          timedelta(minutes=interest_offset))

    scan_warning = system.lastscanned < scan_threshold
    if interest_offset > 0:
        interest = (map_system.interesttime
                    and map_system.interesttime > interest_threshold)
    else:
        interest = map_system.interesttime
        # Include any SiteTracker fleets that are active
    st_fleets = map_system.system.stfleets.filter(ended=None).all()
    locations = cache.get('sys_%s_locations' % map_system.system.pk)
    if not locations:
        locations = {}
    has_siblings = map_system.has_siblings()
    return {
        'system': system,
        'mapsys': map_system,
        'scanwarning': scan_warning,
        'isinterest': interest,
        'stfleets': st_fleets,
        'locations': locations,
        'can_edit': can_edit,
        'has_siblings': has_siblings
    }
Beispiel #27
0
def get_system_context(msID):
    mapsys = get_object_or_404(MapSystem, pk=msID)
    currentmap = mapsys.map

    #if mapsys represents a k-space system get the relevent KSystem object
    if mapsys.system.is_kspace():
        system = mapsys.system.ksystem
    #otherwise get the relevant WSystem
    else:
        system = mapsys.system.wsystem

    scanthreshold = datetime.now(pytz.utc) - timedelta(hours=int(get_config("MAP_SCAN_WARNING", None).value))
    interest_offset = int(get_config("MAP_INTEREST_TIME", None).value)
    interestthreshold = datetime.now(pytz.utc) - timedelta(minutes=interest_offset)

    scanwarning = system.lastscanned < scanthreshold
    if  interest_offset > 0:
        interest = mapsys.interesttime and mapsys.interesttime > interestthreshold
    else:
        interest = mapsys.interesttime
    return { 'system' : system, 'mapsys' : mapsys,
             'scanwarning' : scanwarning, 'isinterest' : interest }
Beispiel #28
0
def get_signature_list(request, map_id, ms_id):
    """
    Determines the proper escalationThreshold time and renders
    system_signatures.html
    """
    if not request.is_ajax():
        raise PermissionDenied
    system = get_object_or_404(MapSystem, pk=ms_id)
    escalation_downtimes = int(get_config("MAP_ESCALATION_BURN",
                                          request.user).value)
    return TemplateResponse(request, "system_signatures.html",
                            {'system': system,
                            'downtimes': escalation_downtimes})
Beispiel #29
0
def add_system(request, map_id):
    """
    AJAX view to add a system to a current_map. Requires POST containing:
       topMsID: map_system ID of the parent map_system
       bottomSystem: Name of the new system
       topType: WormholeType name of the parent side
       bottomType: WormholeType name of the new side
       timeStatus: Wormhole time status integer value
       massStatus: Wormhole mass status integer value
       topBubbled: 1 if Parent side bubbled
       bottomBubbled: 1 if new side bubbled
       friendlyName: Friendly name for the new map_system
    """
    if not request.is_ajax():
        raise PermissionDenied
    try:
        # Prepare data
        current_map = Map.objects.get(pk=map_id)
        top_ms = MapSystem.objects.get(pk=request.POST.get('topMsID'))
        bottom_sys = System.objects.get(name=request.POST.get('bottomSystem'))
        top_type = WormholeType.objects.get(name=request.POST.get('topType'))
        bottom_type = WormholeType.objects.get(
            name=request.POST.get('bottomType'))
        time_status = int(request.POST.get('timeStatus'))
        mass_status = int(request.POST.get('massStatus'))
        if request.POST.get('topBubbled', '0') != "0":
            top_bubbled = True
        else:
            top_bubbled = False
        if request.POST.get('bottomBubbled', '0') != "0":
            bottom_bubbled = True
        else:
            bottom_bubbled = False
        # Add System
        bottom_ms = current_map.add_system(request.user, bottom_sys,
                                           request.POST.get('friendlyName'),
                                           top_ms)
        # Add Wormhole
        bottom_ms.connect_to(top_ms, top_type, bottom_type, top_bubbled,
                             bottom_bubbled, time_status, mass_status)

        # delete old signatures
        if int(get_config("MAP_AUTODELETE_SIGS", request.user).value) == 1:
            bottom_ms.delete_old_sigs(request.user)

        current_map.clear_caches()
        return HttpResponse()
    except ObjectDoesNotExist:
        return HttpResponse(status=400)
Beispiel #30
0
 def approve(self):
     """
     Mark the site approved.
     """
     new_fleetsize = self.site.fleetsize + 1
     x = float(get_config("ST_SIZE_WEIGHT", None).value)
     n = new_fleetsize
     if x > 1:
         weight_factor = x / float(n + (x - 1))
     else:
         weight_factor = float(1)
     self.site.fleetsize = new_fleetsize
     self.site.weighted_points = self.site.raw_points * weight_factor
     self.site.save()
     self.pending = False
     self.save()
Beispiel #31
0
 def approve(self):
     """
     Mark the site approved.
     """
     new_fleetsize = self.site.fleetsize + 1
     x = float(get_config("ST_SIZE_WEIGHT", None).value)
     n = new_fleetsize
     if x > 1:
         weight_factor = x / float(n + (x - 1))
     else:
         weight_factor = float(1)
     self.site.fleetsize = new_fleetsize
     self.site.weighted_points = self.site.raw_points * weight_factor
     self.site.save()
     self.pending = False
     self.save()
Beispiel #32
0
    def log_sig(self, user, action, map_system):
        """Log the fact that the signature was scanned."""

        # only include advanced logging if enabled
        include_distance = get_config("MAP_ADVANCED_LOGGING", None).value
        if include_distance == "1":
            map_system.map.add_log(
                user,
                "%s signature %s in %s (%s), %s jumps out from root system." %
                (action, self.sigid, map_system.system.name,
                 map_system.friendlyname, map_system.distance_from_root()))
        else:
            map_system.map.add_log(
                user, "%s signature %s in %s (%s)." %
                (action, self.sigid, map_system.system.name,
                 map_system.friendlyname))
Beispiel #33
0
def general_settings(request):
    """
    Returns and processes the general settings section.
    """
    npc_threshold = get_config("MAP_NPC_THRESHOLD", None)
    pvp_threshold = get_config("MAP_PVP_THRESHOLD", None)
    scan_threshold = get_config("MAP_SCAN_WARNING", None)
    interest_time = get_config("MAP_INTEREST_TIME", None)
    escalation_burn = get_config("MAP_ESCALATION_BURN", None)
    advanced_logging = get_config("MAP_ADVANCED_LOGGING", None)
    autodelete_sigs = get_config("MAP_AUTODELETE_SIGS", None)
    autodelete_days = get_config("MAP_AUTODELETE_DAYS", None)
    if request.method == "POST":
        scan_threshold.value = int(request.POST["scanwarn"])
        interest_time.value = int(request.POST["interesttimeout"])
        pvp_threshold.value = int(request.POST["pvpthreshold"])
        npc_threshold.value = int(request.POST["npcthreshold"])
        escalation_burn.value = int(request.POST["escdowntimes"])
        advanced_logging.value = int(request.POST["advlogging"])
        autodelete_sigs.value = int(request.POST["autodelsigs"])
        autodelete_days.value = int(request.POST["autodeldays"])
        scan_threshold.save()
        interest_time.save()
        pvp_threshold.save()
        npc_threshold.save()
        escalation_burn.save()
        advanced_logging.save()
        autodelete_sigs.save()
        autodelete_days.save()
        return HttpResponse()
    return TemplateResponse(
        request,
        "general_settings.html",
        {
            "npcthreshold": npc_threshold.value,
            "pvpthreshold": pvp_threshold.value,
            "scanwarn": scan_threshold.value,
            "interesttimeout": interest_time.value,
            "escdowntimes": escalation_burn.value,
            "advlogging": advanced_logging.value,
            "autodelsigs": autodelete_sigs.value,
            "autodeldays": autodelete_days.value,
        },
    )
Beispiel #34
0
    def log_sig(self, user, action, map_system):
        """Log the fact that the signature was scanned."""

        # only include advanced logging if enabled
        include_distance = get_config("MAP_ADVANCED_LOGGING", None).value
        if include_distance == "1":
            map_system.map.add_log(
                user,
                "%s signature %s in %s (%s), %s jumps out from root system."
                %(action, self.sigid, map_system.system.name,
                  map_system.friendlyname, map_system.distance_from_root()))
        else:
            map_system.map.add_log(
                user,
                "%s signature %s in %s (%s)."
                %(action, self.sigid, map_system.system.name,
                  map_system.friendlyname))
Beispiel #35
0
def add_system(request, map_id):
    """
    AJAX view to add a system to a current_map. Requires POST containing:
       topMsID: map_system ID of the parent map_system
       bottomSystem: Name of the new system
       topType: WormholeType name of the parent side
       bottomType: WormholeType name of the new side
       timeStatus: Wormhole time status integer value
       massStatus: Wormhole mass status integer value
       topBubbled: 1 if Parent side bubbled
       bottomBubbled: 1 if new side bubbled
       friendlyName: Friendly name for the new map_system
    """
    if not request.is_ajax():
        raise PermissionDenied
    try:
        # Prepare data
        current_map = Map.objects.get(pk=map_id)
        top_ms = MapSystem.objects.get(pk=request.POST.get("topMsID"))
        bottom_sys = System.objects.get(name=request.POST.get("bottomSystem"))
        top_type = WormholeType.objects.get(name=request.POST.get("topType"))
        bottom_type = WormholeType.objects.get(name=request.POST.get("bottomType"))
        time_status = int(request.POST.get("timeStatus"))
        mass_status = int(request.POST.get("massStatus"))
        if request.POST.get("topBubbled", "0") != "0":
            top_bubbled = True
        else:
            top_bubbled = False
        if request.POST.get("bottomBubbled", "0") != "0":
            bottom_bubbled = True
        else:
            bottom_bubbled = False
        # Add System
        bottom_ms = current_map.add_system(request.user, bottom_sys, request.POST.get("friendlyName"), top_ms)
        # Add Wormhole
        bottom_ms.connect_to(top_ms, top_type, bottom_type, top_bubbled, bottom_bubbled, time_status, mass_status)

        # delete old signatures
        if int(get_config("MAP_AUTODELETE_SIGS", request.user).value) == 1:
            bottom_ms.delete_old_sigs(request.user)

        current_map.clear_caches()
        return HttpResponse()
    except ObjectDoesNotExist:
        return HttpResponse(status=400)
Beispiel #36
0
def general_settings(request):
    """
    Returns and processes the general settings section.
    """
    npc_threshold = get_config("MAP_NPC_THRESHOLD", None)
    pvp_threshold = get_config("MAP_PVP_THRESHOLD", None)
    scan_threshold = get_config("MAP_SCAN_WARNING", None)
    interest_time = get_config("MAP_INTEREST_TIME", None)
    escalation_burn = get_config("MAP_ESCALATION_BURN", None)
    advanced_logging = get_config("MAP_ADVANCED_LOGGING", None)
    autodelete_sigs = get_config("MAP_AUTODELETE_SIGS", None)
    autodelete_days = get_config("MAP_AUTODELETE_DAYS", None)
    if request.method == "POST":
        scan_threshold.value = int(request.POST['scanwarn'])
        interest_time.value = int(request.POST['interesttimeout'])
        pvp_threshold.value = int(request.POST['pvpthreshold'])
        npc_threshold.value = int(request.POST['npcthreshold'])
        escalation_burn.value = int(request.POST['escdowntimes'])
        advanced_logging.value = int(request.POST['advlogging'])
        autodelete_sigs.value = int(request.POST['autodelsigs'])
        autodelete_days.value = int(request.POST['autodeldays'])
        scan_threshold.save()
        interest_time.save()
        pvp_threshold.save()
        npc_threshold.save()
        escalation_burn.save()
        advanced_logging.save()
        autodelete_sigs.save()
        autodelete_days.save()
        return HttpResponse()
    return TemplateResponse(
        request, 'general_settings.html', {
            'npcthreshold': npc_threshold.value,
            'pvpthreshold': pvp_threshold.value,
            'scanwarn': scan_threshold.value,
            'interesttimeout': interest_time.value,
            'escdowntimes': escalation_burn.value,
            'advlogging': advanced_logging.value,
            'autodelsigs': autodelete_sigs.value,
            'autodeldays': autodelete_days.value
        })
Beispiel #37
0
    def send_alert(self, to_users, subject, message, from_user, sub_group):
        subdomain = get_config("SLACK_SUBDOMAIN", None).value

        if self.exists(sub_group):
            channel = SlackChannel.objects.get(group=sub_group)
            destination = "https://%s.slack.com/services/hooks/incoming-webhook?token=%s" % (subdomain, channel.token)
            payload = {'payload':json.dumps({'channel': channel.channel,
                'username': "******",
                'attachments':[{
                    'pretext': 'Notifying <!channel> for new ping from <@%s>' % (from_user.username,),
                    'fallback': "EWS-PING: %s - %s" % (subject, message),
                    'fields':[{
                        'title': subject,
                        'value': message
                    }]
                }]
            })}
            r = requests.post(destination, data=payload)
            return {'status_code': r.status_code, 'text': r.text}
Beispiel #38
0
    def __init__(self, dataloader, config):
        self.dataloader = dataloader
        self.reference_dir = config.reference_images
        self.results = config.results_dir
        self.device = 'cpu'
        self.config = get_config('configs/celeba-hq_256.yaml')
        self.noise_dim = self.config['noise_dim']
        self.image_size = self.config['new_size']
        self.checkpoint = config.checkpoint
        self.trainer = HiSD_Trainer(self.config)
        self.state_dict = torch.load(self.checkpoint,
                                     map_location=torch.device('cpu'))
        self.trainer.models.gen.load_state_dict(self.state_dict['gen_test'])
        self.trainer.models.gen.to(self.device)

        self.c_dim = config.c_dim
        self.selected_attrs = config.selected_attrs

        self.E = self.trainer.models.gen.encode
        self.T = self.trainer.models.gen.translate
        self.G = self.trainer.models.gen.decode
        self.M = self.trainer.models.gen.map
        self.F = self.trainer.models.gen.extract

        self.seed = None

        self.transform = transforms.Compose([
            transforms.Resize(self.image_size),
            transforms.ToTensor(),
            transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
        ])

        #Attacks
        self.epsilon = 0.005
        self.k = 10
        self.a = 0.01
        self.loss_fn = nn.MSELoss().to(self.device)
        self.rand = True
Beispiel #39
0
def applicant_login(request, app_type=None):
    email_required = get_config("RECRUIT_REQUIRE_EMAIL", None).value == "1"
    form = RecruitRegistrationForm()
    if not app_type:
        app_type = get_object_or_404(AppType, pk=request.POST.get("app_type"))
    if request.method == "POST":
        log_user = authenticate(username=request.POST.get("username2", ""), password=request.POST.get("password3", ""))
        if log_user is not None:
            login(request, log_user)
            return HttpResponseRedirect(request.POST.get("next_page"))
        else:
            next_page = reverse("Recruitment.views.get_application", args=(app_type.pk,))
            return TemplateResponse(
                request,
                "recruit_register.html",
                {"form": form, "email_required": email_required, "next_page": next_page, "app_type": app_type},
            )
    else:
        next_page = reverse("Recruitment.views.get_application", args=(app_type.pk,))
        return TemplateResponse(
            request,
            "recruit_register.html",
            {"form": form, "email_required": email_required, "next_page": next_page, "app_type": app_type},
        )
Beispiel #40
0
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
"""Event-based IRC Class"""

import sys
import time

from core import Process, log, utils, version

LOG = log.get_logger()
CONFIG = utils.get_config()


def Main():
    """Main IRC loop."""
    networks = CONFIG.get("networks", type="list")
    log.setup_logger()
    LOG.info("Starting %s" % version.version_string())
    LOG.info("Connecting to IRC Networks: %s" % ", ".join(networks))

    procs = []
    for network in networks:
        proc = Process(network)
        proc.start()
        procs.append(proc)
Beispiel #41
0
def _process_user_display_settings(request, user):
    zen_mode = get_config("MAP_ZEN_MODE", user)
    pilot_list = get_config("MAP_PILOT_LIST", user)
    details_combined = get_config("MAP_DETAILS_COMBINED", user)
    render_tags = get_config("MAP_RENDER_WH_TAGS", user)
    highlight_active = get_config("MAP_HIGHLIGHT_ACTIVE", user)
    auto_refresh = get_config("MAP_AUTO_REFRESH", user)
    kspace_mapping = get_config('MAP_KSPACE_MAPPING', user)
    silent_mapping = get_config("MAP_SILENT_MAPPING", user)
    render_collapsed = get_config("MAP_RENDER_COLLAPSED", user)

    # Create seperate configs for the user if they are falling back to defaults
    if not zen_mode.user:
        zen_mode = ConfigEntry(name=zen_mode.name, user=user)
    if not pilot_list.user:
        pilot_list = ConfigEntry(name=pilot_list.name, user=user)
    if not details_combined.user:
        details_combined = ConfigEntry(name=details_combined.name, user=user)
    if not render_tags.user:
        render_tags = ConfigEntry(name=render_tags.name, user=user)
    if not highlight_active.user:
        highlight_active = ConfigEntry(name=highlight_active.name, user=user)
    if not auto_refresh.user:
        auto_refresh = ConfigEntry(name=auto_refresh.name, user=user)
    if not kspace_mapping.user:
        kspace_mapping = ConfigEntry(name=kspace_mapping.name, user=user)
    if not silent_mapping.user:
        silent_mapping = ConfigEntry(name=silent_mapping.name, user=user)
    if not render_collapsed.user:
        render_collapsed = ConfigEntry(name=render_collapsed.name, user=user)
    zen_mode.value = request.POST.get('zen_mode', 0)
    pilot_list.value = request.POST.get('pilot_list', 0)
    details_combined.value = request.POST.get('details_combined', 0)
    render_tags.value = request.POST.get('render_tags', 0)
    highlight_active.value = request.POST.get('highlight_active', 0)
    auto_refresh.value = request.POST.get('auto_refresh', 0)
    kspace_mapping.value = request.POST.get('kspace_mapping', 0)
    silent_mapping.value = request.POST.get('silent_mapping', 0)
    render_collapsed.value = request.POST.get('render_collapsed', 0)
    zen_mode.save()
    pilot_list.save()
    details_combined.save()
    render_tags.save()
    highlight_active.save()
    auto_refresh.save()
    kspace_mapping.save()
    silent_mapping.save()
    render_collapsed.save()

    saved = True

    return TemplateResponse(
        request, 'display_settings.html', {
            'zen_mode': zen_mode.value,
            'pilot_list': pilot_list.value,
            'details_combined': details_combined.value,
            'render_tags': render_tags.value,
            'highlight_active': highlight_active.value,
            'auto_refresh': auto_refresh.value,
            'kspace_mapping': kspace_mapping.value,
            'silent_mapping': silent_mapping.value,
            'render_collapsed': render_collapsed.value,
            'saved': saved,
            'context_user': user,
        })
Beispiel #42
0
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

"""Event-based IRC Class"""


import sys
import time

from core import Process, log, utils, version


LOG = log.get_logger()
CONFIG = utils.get_config()


def Main():
    """Main IRC loop."""
    networks = CONFIG.get("networks", type="list")
    log.setup_logger()
    LOG.info("Starting %s" % version.version_string())
    LOG.info("Connecting to IRC Networks: %s" % ", ".join(networks))

    procs = []
    for network in networks:
        proc = Process(network)
        proc.start()
        procs.append(proc)
Beispiel #43
0
import argparse
import torchvision.utils as vutils
import sys
import torch
import os
from torchvision import transforms
from PIL import Image
import numpy as np
import time

# use cpu by default
# device = 'cuda:0'
device = 'cpu'

# load checkpoint
config = get_config('configs/celeba-hq_256.yaml')
noise_dim = config['noise_dim']
image_size = config['new_size']
checkpoint = 'checkpoint_256_celeba-hq.pt'
trainer = HiSD_Trainer(config)
state_dict = torch.load(checkpoint)
trainer.models.gen.load_state_dict(state_dict['gen_test'])
trainer.models.gen.to(device)

E = trainer.models.gen.encode
T = trainer.models.gen.translate
G = trainer.models.gen.decode
M = trainer.models.gen.map
F = trainer.models.gen.extract

transform = transforms.Compose([
import os, json, logging, tornado.web, twilio.twiml, redis
from sys import argv, exit
from time import sleep

from core.api import MPServerAPI
from core.utils import get_config, num_to_hash

BASE_URL, NUM_SALT, MAX_DAILY_CALLS = get_config(['base_url', 'our_salt', 'max_daily_calls'])
DAILY_CALLS = 1
GLOBAL_BLACKLIST = 2

ONE = 1
TWO = 2
THREE = 3
FOUR = 4

KEY_MAP = {
	'1_LackofSelfConfidenceMenu':[
		'2_SomebodyImpressedYouMenu',
		'10_YouAreACriminalMenu',
		'23_TattooOutofStyleMenu',
		'28_BodyImageMenu'
	],
	'2_SomebodyImpressedYouMenu':[
		'3_InAMovieMenu',
		'9_ButTryingVeryHardEnd',
		'2_SomebodyImpressedYouMenu',
		'6_AtAPartyMenu',
	],
	'3_InAMovieMenu':[
		'3_InAMovieMenu',
Beispiel #45
0
def display_settings(request, user=None):
    """
    Returns and processes the display settings section.
    """
    if not user and not request.user.has_perm("Map.map_admin"):
        raise PermissionDenied
    if user:
        user = request.user
    zen_mode = get_config("MAP_ZEN_MODE", user)
    pilot_list = get_config("MAP_PILOT_LIST", user)
    details_combined = get_config("MAP_DETAILS_COMBINED", user)
    render_tags = get_config("MAP_RENDER_WH_TAGS", user)
    highlight_active = get_config("MAP_HIGHLIGHT_ACTIVE", user)
    auto_refresh = get_config("MAP_AUTO_REFRESH", user)
    scaling_factor = get_config("MAP_SCALING_FACTOR", user)
    kspace_mapping = get_config("MAP_KSPACE_MAPPING", user)
    silent_mapping = get_config("MAP_SILENT_MAPPING", user)
    render_collapsed = get_config("MAP_RENDER_COLLAPSED", user)
    saved = False
    if request.method == "POST":
        if user:
            return _process_user_display_settings(request, user)
        else:
            zen_mode.value = request.POST.get("zen_mode", 0)
            pilot_list.value = request.POST.get("pilot_list", 0)
            details_combined.value = request.POST.get("details_combined", 0)
            render_tags.value = request.POST.get("render_tags", 0)
            scaling_factor.value = request.POST.get("scaling_factor", 1)
            highlight_active.value = request.POST.get("highlight_active", 0)
            auto_refresh.value = request.POST.get("auto_refresh", 0)
            kspace_mapping.value = request.POST.get("kspace_mapping", 0)
            silent_mapping.value = request.POST.get("silent_mapping", 0)
            render_collapsed.value = request.POST.get("render_collapsed", 0)
            zen_mode.save()
            pilot_list.save()
            details_combined.save()
            render_tags.save()
            scaling_factor.save()
            highlight_active.save()
            auto_refresh.save()
            kspace_mapping.save()
            silent_mapping.save()
            render_collapsed.save()
        saved = True

    return TemplateResponse(
        request,
        "display_settings.html",
        {
            "zen_mode": zen_mode.value,
            "pilot_list": pilot_list.value,
            "details_combined": details_combined.value,
            "render_tags": render_tags.value,
            "scaling_factor": scaling_factor.value,
            "highlight_active": highlight_active.value,
            "auto_refresh": auto_refresh.value,
            "kspace_mapping": kspace_mapping.value,
            "silent_mapping": silent_mapping.value,
            "render_collapsed": render_collapsed.value,
            "saved": saved,
            "context_user": user,
        },
    )
Beispiel #46
0
def feedback_panel():
    return {'render': get_config("CORE_FEEDBACK_ENABLED",
        None).value == "1"}
Beispiel #47
0
def _process_user_display_settings(request, user):
    zen_mode = get_config("MAP_ZEN_MODE", user)
    pilot_list = get_config("MAP_PILOT_LIST", user)
    details_combined = get_config("MAP_DETAILS_COMBINED", user)
    render_tags = get_config("MAP_RENDER_WH_TAGS", user)
    highlight_active = get_config("MAP_HIGHLIGHT_ACTIVE", user)
    auto_refresh = get_config("MAP_AUTO_REFRESH", user)
    kspace_mapping = get_config("MAP_KSPACE_MAPPING", user)
    silent_mapping = get_config("MAP_SILENT_MAPPING", user)
    render_collapsed = get_config("MAP_RENDER_COLLAPSED", user)

    # Create seperate configs for the user if they are falling back to defaults
    if not zen_mode.user:
        zen_mode = ConfigEntry(name=zen_mode.name, user=user)
    if not pilot_list.user:
        pilot_list = ConfigEntry(name=pilot_list.name, user=user)
    if not details_combined.user:
        details_combined = ConfigEntry(name=details_combined.name, user=user)
    if not render_tags.user:
        render_tags = ConfigEntry(name=render_tags.name, user=user)
    if not highlight_active.user:
        highlight_active = ConfigEntry(name=highlight_active.name, user=user)
    if not auto_refresh.user:
        auto_refresh = ConfigEntry(name=auto_refresh.name, user=user)
    if not kspace_mapping.user:
        kspace_mapping = ConfigEntry(name=kspace_mapping.name, user=user)
    if not silent_mapping.user:
        silent_mapping = ConfigEntry(name=silent_mapping.name, user=user)
    if not render_collapsed.user:
        render_collapsed = ConfigEntry(name=render_collapsed.name, user=user)
    zen_mode.value = request.POST.get("zen_mode", 0)
    pilot_list.value = request.POST.get("pilot_list", 0)
    details_combined.value = request.POST.get("details_combined", 0)
    render_tags.value = request.POST.get("render_tags", 0)
    highlight_active.value = request.POST.get("highlight_active", 0)
    auto_refresh.value = request.POST.get("auto_refresh", 0)
    kspace_mapping.value = request.POST.get("kspace_mapping", 0)
    silent_mapping.value = request.POST.get("silent_mapping", 0)
    render_collapsed.value = request.POST.get("render_collapsed", 0)
    zen_mode.save()
    pilot_list.save()
    details_combined.save()
    render_tags.save()
    highlight_active.save()
    auto_refresh.save()
    kspace_mapping.save()
    silent_mapping.save()
    render_collapsed.save()

    saved = True

    return TemplateResponse(
        request,
        "display_settings.html",
        {
            "zen_mode": zen_mode.value,
            "pilot_list": pilot_list.value,
            "details_combined": details_combined.value,
            "render_tags": render_tags.value,
            "highlight_active": highlight_active.value,
            "auto_refresh": auto_refresh.value,
            "kspace_mapping": kspace_mapping.value,
            "silent_mapping": silent_mapping.value,
            "render_collapsed": render_collapsed.value,
            "saved": saved,
            "context_user": user,
        },
    )
Beispiel #48
0
    def validate(self):
        """
        Validate a character API key. Return False if invalid, True
        if valid.

        :reutrns: bool -- True if valid, False if invalid
        """
        char_allowed = int(get_config("API_ALLOW_CHARACTER_KEY",
                                      None).value) == 1
        expire_allowed = int(get_config("API_ALLOW_EXPIRING_KEY",
                                        None).value) == 1
        auth = self.get_authenticated_api()
        self.lastvalidated = datetime.now(pytz.utc)
        try:
            result = auth.account.APIKeyInfo()
        except eveapi.AuthenticationError:
            self.valid = False
            self.validation_error = "Access Denied: Key not valid."
            self.save()
            return False
        if result.key.type == u'Character' and not char_allowed:
            self.valid = False
            self.validation_error = ("API Key is a character key which is not "
                                     "allowed by the administrator.")
            self.save()
            return False
        if result.key.expires and not expire_allowed:
            self.valid = False
            self.validation_error = ("API Key has an expiration date which is "
                                     "not allowed by the administrator.")
            self.save()
            return False
        self.access_mask = result.key.accessMask
        corp_list = []
        access_error_list = []
        for character in result.key.characters:
            corp_list.append(character.corporationID)
        access_required = _build_access_req_list(self.user, corp_list)
        for access in access_required:
            if not access.requirement.key_allows(self.access_mask):
                access_error_list.append("Endpoint %s required but "
                                         "not allowed." %
                                         access.requirement.call_name)
        if len(access_error_list):
            self.valid = False
            self.validation_error = ("The API Key does not meet "
                                     "access requirements: \n\n")
            for x in access_error_list:
                self.validation_error = "%s \n %s" % (self.validation_error, x)
            self.save()
            # Still try to get character details for security
            try:
                self.update_characters()
            except Exception:
                pass
            return False
        else:
            self.valid = True
            self.validation_error = ""
            self.save()
            self.update_characters()
            return True
Beispiel #49
0
import torchvision.utils as vutils
import sys
import torch
import os
from torchvision import transforms
from PIL import Image
import numpy as np
import time

# device = 'cuda:0'
device = 'cpu'

# load checkpoint
noise_dim = 32
image_size = 128
config = get_config('configs/celeba-hq.yaml')
checkpoint = 'checkpoint_128_celeba-hq.pt'
trainer = HiSD_Trainer(config)
state_dict = torch.load(checkpoint)
trainer.models.gen.load_state_dict(state_dict['gen_test'])
trainer.models.gen.to(device)

E = trainer.models.gen.encode
T = trainer.models.gen.translate
G = trainer.models.gen.decode
M = trainer.models.gen.map
F = trainer.models.gen.extract

transform = transforms.Compose([
    transforms.Resize(image_size),
    transforms.ToTensor(),
Beispiel #50
0
 def system_to_dict(self, system, levelX):
     """
     Takes a MapSystem and X,Y data and returns the dict of information to be passed to
     the map JS as JSON.
     """
     interesttime = int(get_config("MAP_INTEREST_TIME", self.user).value)
     threshold = datetime.datetime.now(
         pytz.utc) - timedelta(minutes=interesttime)
     if system.interesttime and system.interesttime > threshold:
         interest = True
     else:
         interest = False
     if system.map.systems.filter(interesttime__gt=threshold).count() != 0:
         path = False
         for sys in system.map.systems.filter(
                 interesttime__gt=threshold).all():
             if system in self.get_path_to_map_system(sys):
                 path = True
     else:
         path = False
     activity_estimate = (system.system.podkills + system.system.npckills +
                          system.system.shipkills)
     from Map.models import WSystem
     if system.system.is_wspace():
         effect = WSystem.objects.get(pk=system.system.pk).effect
     else:
         effect = None
     if system.parentsystem:
         parentWH = system.parent_wormholes.get()
         if parentWH.collapsed:
             collapsed = True
         else:
             collapsed = False
         result = {
             'sysID': system.system.pk,
             'Name': system.system.name,
             'LevelX': levelX,
             'activity': activity_estimate,
             'LevelY': self.levelY,
             'SysClass': system.system.sysclass,
             'Friendly': system.friendlyname,
             'interest': interest,
             'interestpath': path,
             'ParentID': system.parentsystem.pk,
             'activePilots': system.system.active_pilots.count(),
             'WhToParent': parentWH.bottom_type.name,
             'WhFromParent': parentWH.top_type.name,
             'WhMassStatus': parentWH.mass_status,
             'WhTimeStatus': parentWH.time_status,
             'WhToParentBubbled': parentWH.bottom_bubbled,
             'WhFromParentBubbled': parentWH.top_bubbled,
             'imageURL': self.get_system_icon(system),
             'whID': parentWH.pk,
             'msID': system.pk,
             'effect': effect,
             'collapsed': collapsed
         }
     else:
         result = {
             'sysID': system.system.pk,
             'Name': system.system.name,
             'LevelX': levelX,
             'activity': activity_estimate,
             'LevelY': self.levelY,
             'SysClass': system.system.sysclass,
             'Friendly': system.friendlyname,
             'interest': interest,
             'interestpath': path,
             'ParentID': None,
             'activePilots': system.system.active_pilots.count(),
             'WhToParent': "",
             'WhFromParent': "",
             'WhMassStatus': None,
             'WhTimeStatus': None,
             'WhToParentBubbled': None,
             'WhFromParentBubbled': None,
             'imageURL': self.get_system_icon(system),
             'whID': None,
             'msID': system.pk,
             'effect': effect,
             'collapsed': False
         }
     return result
Beispiel #51
0
    def validate(self):
        """
        Validate a character API key. Return False if invalid, True
        if valid.

        :reutrns: bool -- True if valid, False if invalid
        """
        char_allowed = int(get_config("API_ALLOW_CHARACTER_KEY",
                None).value) == 1
        expire_allowed = int(get_config("API_ALLOW_EXPIRING_KEY",
                None).value) == 1
        auth = self.get_authenticated_api()
        self.lastvalidated = datetime.now(pytz.utc)
        try:
            result = auth.account.APIKeyInfo()
        except eveapi.AuthenticationError:
            self.valid = False
            self.validation_error = "Access Denied: Key not valid."
            self.save()
            return False
        if result.key.type == u'Character' and not char_allowed:
            self.valid = False
            self.validation_error = ("API Key is a character key which is not "
                        "allowed by the administrator.")
            self.save()
            return False
        if result.key.expires and not expire_allowed:
            self.valid = False
            self.validation_error = ("API Key has an expiration date which is "
                        "not allowed by the administrator.")
            self.save()
            return False
        self.access_mask = result.key.accessMask
        corp_list = []
        access_error_list = []
        for character in result.key.characters:
            corp_list.append(character.corporationID)
        access_required = _build_access_req_list(self.user, corp_list)
        for access in access_required:
            if not access.requirement.key_allows(self.access_mask):
                access_error_list.append("Endpoint %s required but "
                        "not allowed." % access.requirement.call_name)
        if len(access_error_list):
            self.valid = False
            self.validation_error = ("The API Key does not meet "
                    "access requirements: \n\n")
            for x in access_error_list:
                self.validation_error = "%s \n %s" % (
                        self.validation_error, x)
            self.save()
            # Still try to get character details for security
            try:
                self.update_characters()
            except Exception:
                pass
            return False
        else:
            self.valid = True
            self.validation_error = ""
            self.save()
            self.update_characters()
            return True