Exemplo n.º 1
0
def lookupBarang(katakunci, id, max):
    requtil = Utility()
    if max is None:
        max = 40;
    pasiens = []
    if katakunci is not None and '' != katakunci and id is None:
        print 'katakunci'
        print max
        pasiens = models.Barang.objects.filter(
            Q(nama__icontains=katakunci) | Q(merk__icontains=katakunci) | Q(kode__icontains=katakunci))[
                  :max]
    elif id is not None:
        print 'id'
        pasiens = models.Barang.objects.filter(id__exact=id)
        print 'query from id'
        #lookup specific id, to set id value
    else:
        print 'other'
        print id
        print katakunci
        pasiens = models.Barang.objects.all()[:max]
    jpasiens = [];
    for pasien in pasiens:
        jpasien = requtil.modelToDicts([pasien])
        jpasiens.append(jpasien)
    return jpasiens;
Exemplo n.º 2
0
def lookupBdi(katakunci, inventory_id, id, max):
    requtil = Utility()
    if max is None:
        max = 40;
    pasiens = []
    if katakunci is not None and '' != katakunci and id is None:
        print 'katakunci'
        print max
        pasiens = models.BarangDiInventory.objects.filter(
            Q(barang__nama__icontains=katakunci) | Q(barang__merk__icontains=katakunci) |
            Q(barang__kode__icontains=katakunci, inventori__id__exact=inventory_id))[
                  :max]
    elif id is not None:
        print 'id'
        pasiens = models.BarangDiInventory.objects.filter(barang__id__exact=id)
        print 'query from id'
        #lookup specific id, to set id value
    else:
        print 'other'
        print id
        print katakunci
        pasiens = models.BarangDiInventory.objects.filter(inventory__id__exact=inventory_id)[:max]
    jpasiens = [];
    for bdi in pasiens:
        jpasien = requtil.modelToDicts([bdi.barang])
        jpasiens.append(jpasien)
    return jpasiens;
Exemplo n.º 3
0
  def close_file(self, left_hemi_file, right_hemi_file, left_curvature_output_file, right_curvature_output_file):
    '''
    '''
    m = numpy.ctypeslib.as_array(self.__matrix.get_obj())
    m = m.reshape(self.__shape)
    
    
    #here
    lh_vertices, lh_faces = nibabel.freesurfer.read_geometry( left_hemi_file )
    rh_vertices, rh_faces = nibabel.freesurfer.read_geometry( right_hemi_file )
    
    sum_vector = numpy.sum( m, axis=0 )

    import sys, os
    sys.path.append(os.path.join( os.path.dirname( __file__ ),'../'))
    from utility import Utility

    # write curvature files
    Utility.write_freesurfer_curvature( left_curvature_output_file, sum_vector[0:len( lh_vertices )] )
    Utility.write_freesurfer_curvature( right_curvature_output_file, sum_vector[len( lh_vertices ):] )  # here we start with the offset
    # end here
    print 'crv written!!! FTW!'
    
    numpy.save( self.__matrix_file, m)
    
    print 'stored matrix'
Exemplo n.º 4
0
	def addTask(projectId, taskId, taskType):
		tasks = Settings.getTasks(projectId, taskType)
		if taskId in tasks:
			return
		tasks.append( taskId )
		path = "%s/%s.%s.json"%(PROJECTS_PATH, projectId, taskType)
		Utility.saveJson( path, tasks )
Exemplo n.º 5
0
def index(request):
    util = Utility(post=request.POST, get=request.GET)
    c = util.nvlGet('c');
    if c is not None:
        if 'formtutorial' == c:
            return render_to_response('inventory/form_tutorial.html')
        if 'local' == c:
            t = loader.get_template('portal_ivtamd.html')
            djProd = '''http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/'''
            djProdExt = '''.js'''
            djDev = '''/static/dojolib/'''
            djDevExt = '''.js'''
            d = {"dj": djDev, 'djExt': djProdExt}
            return HttpResponse(t.render(Context(d)))
        if 'home' == c:
            return render_to_response('inventory/web.html')
        if 'pabean' == c:
            return render_to_response('inventory/dokumen_css.html')
    else:
        #t = loader.get_template('portal_ivt.html')
        t = loader.get_template('portal_ivtamd.html')
        #        t = loader.get_template('portal_inventory.html') // the old system
        #djProd = '''http://ajax.googleapis.com/ajax/libs/dojo/1.6/'''
        djProd = '''http://ajax.googleapis.com/ajax/libs/dojo/1.7.2/'''
        djProdExt = '''.js'''
        djDev = '''/static/dojolib/'''
        djDevExt = '''.js'''
        d = {"dj": djProd, 'djExt': djProdExt}
        return HttpResponse(t.render(Context(d)))
Exemplo n.º 6
0
	def removeTask(projectId, taskId, taskType):
		tasks = Settings.getTasks(projectId, taskType)
		if taskId in tasks:
			tasks.remove( taskId)
		path = "%s/%s.%s.json"%(PROJECTS_PATH, projectId, taskType)
		if not Utility.isLocked( path ):
			Utility.saveJson( path, tasks )
Exemplo n.º 7
0
	def addPredictionTask(projectId, taskId):
		print 'addPredictionTask....'
		path = "%s/%s.%s.json"%(PROJECTS_PATH, projectId, PREDICT_TASK_TYPE)
		Utility.lock(path)
		Settings.reconcilePredictionTasks( projectId )
		Settings.addTask(projectId, taskId, PREDICT_TASK_TYPE)
		Utility.unlock(path)
Exemplo n.º 8
0
    def parse_Jobberman(self, response):
        i = CareerItem()
        utility = Utility()

        i['url'] = response.url
        logging.info(response.url)
        try:
        	i['title'] = response.xpath('//div[@class="job-quick-sum"]/h1/text()').extract()[0]
        except IndexError:
        	i['title'] = response.xpath('//div[@class="job-quick-sum"]/h1/text()').extract()
        
        try:
        	description = response.xpath('//div[@class="job-details-main"]/p[2]/text()').extract()[0]
        except IndexError:
        	description = response.xpath('//div[@class="job-details-main"]/p[2]/text()').extract()
        
        i['description'] = utility.limit_length_of_string(description)#(description[:150] + '...') if len(description) > 150 else description
        i['category'] = utility.stringReplace(self.category, '/', ',')
        i['location'] = self.location #str(self.location).replace('/', ',')

        # try:
        # 	i['location'] = response.xpath('//div[@class="job-details-sidebar"]/p[7]/a/text()').extract()[0]
        # except IndexError:
        # 	i['location'] = response.xpath('//div[@class="job-details-sidebar"]/p[7]/a/text()').extract()

        # try:
        # 	i['category'] = str(response.xpath('//div[@class="job-details-sidebar"]/p[9]/a/text()').extract()[0]).replace('/', ',')
        # except IndexError:
        # 	i['category'] = str(response.xpath('//div[@class="job-details-sidebar"]/p[9]/a/text()').extract()).replace('/', ',')Onye

        i['sponsor'] = 'jobberman.com'
        #log.msg(i)
        yield i
    def _parse_dir(self):

        dir_name = Utility.get_dir_name(self.current_path)
        file_name = Utility.get_base_name(self.current_path)

        # get files with extension stored in ext
        file_list = []
        for ext in self.extension_list:
            file_list += glob.glob1(dir_name, ext)

        # sort list
        file_list = [f for f in file_list]
        file_list.sort()

        # current file index list
        current_index = file_list.index(file_name)

        # find the next file path
        if current_index + 1 < len(file_list):
            self._next_path = \
                dir_name + '/' + file_list[current_index + 1]
        else:
            self._next_path = None

        # find the previous file path
        if current_index > 0:
            self._previous_path = \
                dir_name + '/' + file_list[current_index - 1]
        else:
            self._previous_path = None

        return file_list
Exemplo n.º 10
0
def simpanItemMutasi(reqData):
    requtil = Utility(reqData=reqData);
    id = requtil.nvlGet('id', 0)
    idBrg = requtil.nvlGet('barang_id', 0)
    pbl = None
    if id == 0:
        pbl = initMutasi(reqData)
    else:
        pbls = models.Mutasi.objects.filter(id__exact=id)
        if len(pbls):
            pbl = pbls[0]
            #prepare barang
    brg = None
    brgs = models.Barang.objects.filter(id__exact=idBrg)
    if len(brgs):
        brg = brgs[0]
    else:
        raise StandardError('Barang ini tidak ditemukan')
    ipbl = models.ItemMutasi()
    ipbl.barang = brg
    ipbl.mutasi = pbl
    ipbl.harga = brg.harga
    ipbl.jumlah = requtil.nvlGet('barang_qty', 0)
    ipbl.save()
    return ipbl
    def load(self, filename, initial_page=0):

        image_extensions = ['.bmp', '.jpg', '.jpeg', '.gif', '.png', '.pbm',
                            '.pgm', '.ppm', '.tiff', '.xbm', '.xpm', '.webp']

        loader = LoaderFactory.create_loader(
            Utility.get_file_extension(filename), set(image_extensions))

        loader.progress.connect(self.load_progressbar_value)

        try:
            loader.load(filename)
        except NoDataFindException as excp:
            # Caso nao exista nenhuma imagem, carregamos a imagem indicando
            # erro
            from page import Page
            print excp.message
            q_file = QtCore.QFile(":/icons/notCover.png")
            q_file.open(QtCore.QIODevice.ReadOnly)
            loader.data.append(Page(q_file.readAll(), 'exit_red_1.png', 0))

        self.comic = Comic(Utility.get_base_name(filename),
                           Utility.get_dir_name(filename), initial_page)

        self.comic.pages = loader.data
        self.current_directory = Utility.get_dir_name(filename)
        self.path_file_filter.parse(filename)
Exemplo n.º 12
0
 def stop_loop():
     now = time.time()
     if now < deadline and (io_loop._callbacks or io_loop._timeouts):
         io_loop.add_timeout(now + 1, stop_loop)
     else:
         io_loop.stop()
         Utility.print_msg ('\033[93m'+ 'shutdown' + '\033[0m', True, 'done')
Exemplo n.º 13
0
    def build_alert(self, alert_id, alert_message, location=None):
        """Build the actual alert and returns it, formatted.

        DEPRECATION NOTICE:  The 'alert_id' field has been introduced for
        better readability.  It's currently set to be the same as 'id'.
        At some point in the future, the 'id' field will be removed.

        Args:
            alert_id (int): The ID of the alert you want to build
            alert_message (str): The message to be embedded in the alert.

        Returns:
            tuple: Position 0 contains the string 'sitch_alert'.  Position 1
                contains the alert and metadata.
        """
        if location is None:
            print("AlertManager: No geo for alarm: %s" % str(alert_message))
            location = {"type": "Point", "coordinates": [0, 0]}
        elif Utility.validate_geojson(location) is False:
            print("AlertManager: Invalid geojson %s for: %s" % (location,
                                                                alert_message))
            location = {"type": "Point", "coordinates": [0, 0]}
        lat = location["coordinates"][1]
        lon = location["coordinates"][0]
        gmaps_url = Utility.create_gmaps_link(lat, lon)
        message = Utility.generate_base_event()
        message["alert_id"] = alert_id
        message["id"] = alert_id
        message["alert_type"] = self.get_alert_type(alert_id)
        message["event_type"] = "sitch_alert"
        message["details"] = ("%s  %s" % (alert_message, gmaps_url))
        message["location"] = location
        retval = ("sitch_alert", message)
        return retval
Exemplo n.º 14
0
def main_handler():
    response.content_type = 'application/json'
    return {
        'status': 'OK',
        'detail': 'Nothing to show on this page, try http://%s:%s/login'
                      % (Utility.ins().hostname(), Utility.ins().port())
    }
Exemplo n.º 15
0
def getSupplierSider(reqData):
    requtil = Utility(reqData=reqData)
    pas = models.Supplier.objects.filter(id__exact=requtil.nvlGet('id'))
    if pas[0] is not None:
        id = pas[0].id
        jpas = requtil.modelToDicts([pas[0]])
    html = render_to_string('inventory/form_supplier_sider.html', jpas)
    return html
Exemplo n.º 16
0
def initKonversi(reqData):
    requtil = Utility(reqData=reqData);
    _apu = appUtil()
    #prepare inventory
    pbl = models.Konversi()
    pbl.nomor = ('00000000000000%s' % (_apu.getIncrement(5)))[-6:]
    pbl.inventory = getInvById(requtil.nvlGet('inventory_id'))
    pbl.save()
    return pbl
Exemplo n.º 17
0
 def reportTrainingStats(self, elapsedTime, batchIndex, valLoss, trainCost, mode=0):
     DB.storeTrainingStats( self.id, valLoss, trainCost, mode=mode)
     msg = '(%0.1f)     %i     %f%%'%\
     (
        elapsedTime,
        batchIndex,
        valLoss
     )
     status = '[%f]'%(trainCost)
     Utility.report_status( msg, status )
Exemplo n.º 18
0
def initPengeluaranPabean(reqData):
    requtil = Utility(reqData=reqData);
    _apu = appUtil()
    #prepare inventory
    pbl = models.DokumenPabean()
    pbl = requtil.bindRequestModel(pbl)
    pbl.nomor = ('00000000000000%s' % (_apu.getIncrement(7)))[-6:]
    pbl.inventory = models.Inventory.objects.get(id__exact=requtil.nvlGet('inventory_id'))
    pbl.save()
    return pbl
Exemplo n.º 19
0
def initMutasi(reqData):
    requtil = Utility(reqData=reqData);
    _apu = appUtil()
    #prepare inventory
    pbl = models.Mutasi()
    pbl.nomor = ('00000000000000%s' % (_apu.getIncrement(4)))[-6:]
    pbl.asal = getInvById(requtil.nvlGet('inventory_asal_id'))
    pbl.tujuan = getInvById(requtil.nvlGet('inventory_tujuan_id'))
    pbl.save()
    return pbl
Exemplo n.º 20
0
def getBarangSider(reqData):
    requtil = Utility(reqData=reqData)
    pas = models.Barang.objects.filter(id__exact=requtil.nvlGet('id'))
    if pas[0] is not None:
        id = pas[0].id
        jpas = requtil.modelToDicts([pas[0]])
        urlss = "000000%s.jpg" % (id)
        jpas['url'] = urlss[-10:]
    html = render_to_string('inventory/form_barang_sider.html', jpas)
    return html
Exemplo n.º 21
0
def prepareFormInventory(reqData):
    requtil = Utility(reqData=reqData)
    jresp = dict({'html': render_to_string('inventory/form_inventory.html', {})})
    data = {}
    if 'id' in reqData:
        id = requtil.nvlGet('id')
        if id > 0:
            pas = models.Inventory.objects.get(id__exact=requtil.nvlGet('id'))
            data = requtil.modelToDict(pas)
            jresp.update({'data': data})
    return jresp
Exemplo n.º 22
0
 def getProjectEditData(self, projectId ):
     print 'project.getProjectEditData ', projectId
     project = DB.getProject( projectId )
     project = None if project is None else project.toJson()
     data = {}
     data['project'] = project
     data['images'] = Utility.getImages( Paths.TrainGrayscale )
     data['validation_images'] = Utility.getImages( Paths.ValidGrayscale )
     data['projectnames'] = DB.getProjectNames()
     data = json.dumps( data )
     return Utility.compress( data )
Exemplo n.º 23
0
def prepareFormBarang(reqData):
    requtil = Utility(reqData=reqData)
    jresp = dict({'html': render_to_string('inventory/form_mutasi.html', {})})
    data = {}
    if 'id' in reqData:
        id = requtil.nvlGet('id')
        if id > 0:
            brg = models.Barang.objects.get(id__exact=requtil.nvlGet('id'))
            data = requtil.modelToDicts([brg])
            jresp.update({'data': data});
    return jresp
Exemplo n.º 24
0
def prepareFormSupplier(reqData):
    requtil = Utility(reqData=reqData)
    jresp = dict({'html': render_to_string('inventory/form_supplier.html', {})})
    data = {}
    if 'id' in reqData:
        id = requtil.nvlGet('id')
        if id > 0:
            sup = models.Supplier.objects.get(id__exact=requtil.nvlGet('id'))
            data = requtil.modelToDicts([sup])
            jresp.update({'data': data});
    return jresp
Exemplo n.º 25
0
def prepareFormRencanaPembelian(reqData):
    requtil = Utility(reqData=reqData)
    jresp = dict({'html': render_to_string('inventory/form_rencana_pembelian.html', {})})
    data = {}
    if 'id' in reqData:
        id = requtil.nvlGet('id')
        if id > 0:
            cust = models.Customer.objects.get(id__exact=requtil.nvlGet('id'))
            data = requtil.modelToDicts([cust])
            jresp.update({'data': data});
    return jresp
Exemplo n.º 26
0
def saveUpdateSupplier(reqData):
    requtil = Utility(reqData=reqData)
    sup = models.Supplier()
    sup = requtil.bindRequestModel(sup)
    if requtil.nvlGet('id', None) is None:
        #barang baru di inventory
        #init barang di inventory object
        #init barang object

        sup.save()
    else: sup.save()
    return requtil.modelToDicts([sup])
Exemplo n.º 27
0
 def report(self, name, dims):
         msg = '%s'%(name)
         status = '['
         p_dim = None
         for dim in dims:
                 if p_dim == None:
                         status = '%s%s'%(status, dim)
                 else:
                         status = '%s x %s'%(status, dim)
                 p_dim  = dim
         status = '%s]'%status
         Utility.report_status( msg, status)
Exemplo n.º 28
0
def saveUpdatePartner(reqData):
    requtil = Utility(reqData=reqData)
    cust = models.Partner()
    #init barang object
    cust = requtil.bindRequestModel(cust)
    if requtil.nvlGet('id', None) is None:
        #barang baru di inventory
        #init barang di inventory object

        cust.save()
    else: cust.save()
    return requtil.modelToDicts([cust])
Exemplo n.º 29
0
def mapBarang(item_id, barang_id):
    util = Utility()
    items = models.ItemBcdtMap.objects.filter(id__exact=item_id)
    brgs = models.Barang.objects.filter(id__exact=barang_id)
    for item in items:
        for brg in brgs:
            item.barang = brg;
            item.save()
            break
        break
    hsl = util.modelToDicts([item.barang, item], prefiks=['barang_', None])
    print hsl
    return hsl
Exemplo n.º 30
0
def getMaping(id):
    util = Utility()
    items = models.ItemBcdtMap.objects.filter(bcdt__id__exact=id)
    jitems = [];
    for item in items:
        if item.barang is not None:
            jitem = util.modelToDicts([item.barang, item],
                replaces=['id:barang_id', 'nama:barang_nama', 'merk:barang_merk'])
        else:
            jitem = util.modelToDicts([item.barang, item])
        jitems.append(jitem)

    return jitems
Exemplo n.º 31
0
    def Compile(self: Any) -> None:
        """Compile the Officer Challenge XAssets."""

        challenges: List[Dict[str, Any]] = []

        challenges = OfficerChallenges.Table(self, challenges)

        Utility.WriteFile(self, f"{self.eXAssets}/officerChallenges.json",
                          challenges)

        log.info(f"Compiled {len(challenges):,} Officer Challenges")
Exemplo n.º 32
0
 def get_enduser_friendly_partition_description(self):
     flat_string = ""
     index = 0
     for short_device_node in self.redo_dict['parts'].keys():
         base_device_node, partition_number = Utility.split_device_string(
             short_device_node)
         flat_string += "(" + str(
             partition_number) + ": " + self.flatten_partition_string(
                 short_device_node) + ") "
         index += 1
     return flat_string
Exemplo n.º 33
0
    def bytes(self):
        e = self.elems()
        if self.dir == "fprop":
            e *= 4
        else:
            e *= 5

        if self.sub > 0:
            return 0
        else:
            return e * Utility.typeToBytes(self.type)
Exemplo n.º 34
0
    def Compile(self: Any) -> None:
        """Compile the Vehicle Track XAssets."""

        tracks: List[Dict[str, Any]] = []

        tracks = VehicleTracks.IDs(self, tracks)
        tracks = VehicleTracks.Table(self, tracks)

        Utility.WriteFile(self, f"{self.eXAssets}/vehicleTracks.json", tracks)

        log.info(f"Compiled {len(tracks):,} Vehicle Tracks")
Exemplo n.º 35
0
    def Compile(self: Any) -> None:
        """Compile the Charm XAssets."""

        charms: List[Dict[str, Any]] = []

        charms = Charms.IDs(self, charms)
        charms = Charms.Table(self, charms)

        Utility.WriteFile(self, f"{self.eXAssets}/charms.json", charms)

        log.info(f"Compiled {len(charms):,} Charms")
Exemplo n.º 36
0
    def Compile(self: Any) -> None:
        """Compile the Miscellaneous Challenges XAssets."""

        challenges: List[Dict[str, Any]] = []

        challenges = MiscellaneousChallenges.Table(self, challenges)

        Utility.WriteFile(self, f"{self.eXAssets}/miscChallenges.json",
                          challenges)

        log.info(f"Compiled {len(challenges):,} Miscellaneous Challenges")
Exemplo n.º 37
0
    def Compile(self: Any) -> None:
        """Compile the Tomogunchi Turbo Challenges XAssets."""

        challenges: List[Dict[str, Any]] = []

        challenges = TurboChallenges.Table(self, challenges)

        Utility.WriteFile(self, f"{self.eXAssets}/turboChallenges.json",
                          challenges)

        log.info(f"Compiled {len(challenges):,} Tomogunchi Turbo Challenges")
Exemplo n.º 38
0
    def Compile(self: Any) -> None:
        """Compile the Weapon Unlock Challenge XAssets."""

        challenges: List[Dict[str, Any]] = []

        challenges = WeaponUnlockChallenges.Table(self, challenges)

        Utility.WriteFile(self, f"{self.eXAssets}/weaponUnlockChallenges.json",
                          challenges)

        log.info(f"Compiled {len(challenges):,} Weapon Unlock Challenges")
Exemplo n.º 39
0
 def make_vec(self,content:str):
     vec=[]
     words = Ut.file2List(TfConfig.words_path)
     seg_list = jieba.analyse.extract_tags(content, withWeight=True)
     for word in words:
         v = 0
         for x, w in seg_list:
             if x == word:
                 v = w
         vec.append(v)
     return vec
Exemplo n.º 40
0
    def Compile(self: Any) -> None:
        """Compile the Gesture XAssets."""

        gestures: List[Dict[str, Any]] = []

        gestures = Gestures.IDs(self, gestures)
        gestures = Gestures.Table(self, gestures)

        Utility.WriteFile(self, f"{self.eXAssets}/gestures.json", gestures)

        log.info(f"Compiled {len(gestures):,} Gestures")
Exemplo n.º 41
0
    def Compile(self: Any) -> None:
        """Compile the Weekly Multiplayer Challenges XAssets."""

        challenges: List[Dict[str, Any]] = []

        challenges = WeeklyChallengesMP.Table(self, challenges)

        Utility.WriteFile(self, f"{self.eXAssets}/weeklyChallengesMP.json",
                          challenges)

        log.info(f"Compiled {len(challenges):,} Weekly Multiplayer Challenges")
Exemplo n.º 42
0
 def get_enduser_friendly_partition_description(self):
     flat_string = ""
     index = 0
     for long_device_node in self.image_format_dict_dict.keys():
         base_device_node, partition_number = Utility.split_device_string(
             long_device_node)
         flat_string += "(" + str(
             partition_number) + ": " + self.flatten_partition_string(
                 long_device_node) + ") "
         index += 1
     return flat_string
Exemplo n.º 43
0
    def Table(self: Any, types: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
        """Compile the mp/gametypestable.csv XAsset."""

        table: List[Dict[str, Any]] = Utility.ReadCSV(
            self, f"{self.iXAssets}/mp/gametypestable.csv", GameTypesTable)

        if table is None:
            return types

        for entry in table:
            types.append({
                "altId":
                entry.get("ref"),
                "name":
                self.localize.get(entry.get("name")),
                "description":
                self.localize.get(entry.get("desc")),
                "hints": {
                    "global":
                    None if (val := entry.get("objectiveHintAttackers")) !=
                    entry.get("objectiveHintDefenders") else
                    self.localize.get(val),
                    "offense":
                    None if (val := entry.get("objectiveHintAttackers"))
                    == entry.get("objectiveHintDefenders") else
                    self.localize.get(val),
                    "defense":
                    None if entry.get("objectiveHintAttackers")
                    == (val := entry.get("objectiveHintDefenders")) else
                    self.localize.get(val),
                },
                "category":
                self.ModernWarfare.GetGameTypeCategory(entry.get("category")),
                "teamBased":
                bool(entry.get("teamBased")),
                "roundBased":
                bool(entry.get("isRoundBased")),
                "teamChoice":
                bool(entry.get("teamChoice")),
                "classChoice":
                bool(entry.get("classChoice")),
                "scaleXP":
                entry.get("xpScalar"),
                "scaleWeaponXP":
                entry.get("weaponXPScalar"),
                "icons": {
                    "core": entry.get("image"),
                    "hardcore": entry.get("hardcoreImage"),
                    "realism": entry.get("realismImage"),
                    "cdl": entry.get("CDLImage"),
                },
                "hidden":
                bool(entry.get("hideInUI")),
            })
Exemplo n.º 44
0
    def Compile(self: Any) -> None:
        """Compile the Vehicle Horn XAssets."""

        horns: List[Dict[str, Any]] = []

        horns = VehicleHorns.IDs(self, horns)
        horns = VehicleHorns.Table(self, horns)

        Utility.WriteFile(self, f"{self.eXAssets}/vehicleHorns.json", horns)

        log.info(f"Compiled {len(horns):,} Vehicle Horns")
Exemplo n.º 45
0
    def _inspect(self):
        self.result = { key: [] for key in [r['RegionName'] for r in self.regions['Regions']] }


        for region in self.regions['Regions']:
            rds = boto3.client(self.aws_resource, region['RegionName'])
            rds_response = rds.describe_db_instances()
            for instance in rds_response['DBInstances']:

                if instance['InstanceCreateTime'].replace(tzinfo=None) >= self.A_WHILE:
                    continue

                arn = 'arn:aws:rds:{0}:{1}:db:{2}'.format(region['RegionName'],
                                                          Utility.aws_account_id(),
                                                          instance['DBInstanceIdentifier'])

                details = { 'name': instance['DBInstanceIdentifier'],
                            'region': region['RegionName'],
                            'launched': instance['InstanceCreateTime'].strftime('%Y-%m-%d'),
                            'class': instance['DBInstanceClass'],
                            'owner': 'None',
                            'project': 'None' }
                tags = { }
                tag_response = rds.list_tags_for_resource(ResourceName=arn)
                for tag in tag_response['TagList']:
                    display_name = tag['Key'].lower()
                    if display_name in self.ABBREVIATIONS:
                        display_name = self.ABBREVIATIONS[display_name]
                    tags[display_name] = tag['Value']

                if 'owner' in tags:
                    details['owner'] = tags['owner']
                if 'project' in tags:
                    details['project'] = tags['project']

                tags = { key: tags[key] for key in self.TAGS_OF_INTEREST if key in tags }
                details['other_tags'] = ', '.join(
                    ['{0}={1}'.format(k, Utility.format_for_display(v)) for (k,v) in sorted(tags.items())])
                if not details['other_tags']:
                    details['other_tags'] = 'None'
                self.result[region['RegionName']].append(details)
Exemplo n.º 46
0
    def __init__(self):
        self.modules = list()  #Command Modules
        self.cmds = {}  #Commands
        self.cmdescs = {}  #command Descriptions
        self.bot = Bot(None)
        self.pref = "//"
        self.link = "https://discordapp.com/oauth2/authorize?client_id=354353934074380298&scope=bot&permissions=271674432"
        self.owner = None  #Owner Info
        self.servers = {}

        #Adding Commands
        if Owner(self).open():
            self.modules.append(Owner(self))
            self.cmdescs.update(Owner(self).settings().descs)
            for a in Owner(self).lis:
                self.cmds[a] = Command(a, self.modules[0].lis[a])
        if Roles(self).open():
            self.modules.append(Roles(self))
            self.cmdescs.update(Roles(self).settings().descs)
            for a in Roles(self).lis:
                self.cmds[a] = Command(a, self.modules[1].lis[a])
        if Filter(self).open():
            self.modules.append(Filter(self))
            self.cmdescs.update(Filter(self).settings().descs)
            for a in Filter(self).lis:
                self.cmds[a] = Command(a, self.modules[2].lis[a])
        if Utility(self).open():
            self.modules.append(Utility(self))
            self.cmdescs.update(Utility(self).settings().descs)
            for a in Utility(self).lis:
                self.cmds[a] = Command(a, self.modules[3].lis[a])
        if Chat(self).open():
            self.modules.append(Chat(self))
            self.cmdescs.update(Chat(self).settings().descs)
            for a in Chat(self).lis:
                self.cmds[a] = Command(a, self.modules[4].lis[a])
        if Entertainment(self).open():
            self.modules.append(Entertainment(self))
            self.cmdescs.update(Entertainment(self).settings().descs)
            for a in Entertainment(self).lis:
                self.cmds[a] = Command(a, self.modules[5].lis[a])
Exemplo n.º 47
0
    def _do_nfs_mount_command(self, settings):
        destination_path = settings['destination_path']
        try:
            if not os.path.exists(destination_path) and not os.path.isdir(destination_path):
                os.mkdir(destination_path, 0o755)

            is_unmounted, message = Utility.umount_warn_on_busy(destination_path)
            if not is_unmounted:
                GLib.idle_add(self.please_wait_popup.destroy)
                GLib.idle_add(self.callback, False, message)
                return

            if settings['server'] != "":
                server = settings['server']
            else:
                GLib.idle_add(self.please_wait_popup.destroy)
                GLib.idle_add(self.callback, False, "Must specify server.")
                return

            if settings['remote_path'] != "":
                exported_dir = settings['remote_path']
            else:
                GLib.idle_add(self.please_wait_popup.destroy)
                GLib.idle_add(self.callback, False, "Must specify exported directory.")
                return

            mount_cmd_list = ["mount.nfs", server + ":" + exported_dir, settings['destination_path']]
            mount_process, mount_flat_command_string, mount_failed_message = Utility.interruptable_run("Mounting network shared folder with NFS: ", mount_cmd_list, use_c_locale=False, is_shutdown_fn=self.is_stop_requested)
            if mount_process.returncode != 0:
                check_password_msg = _("Please ensure the server and exported path are correct, and try again.")
                GLib.idle_add(self.please_wait_popup.destroy)
                GLib.idle_add(self.callback, False, mount_failed_message + "\n\n" + check_password_msg)
                return
            else:
                GLib.idle_add(self.please_wait_popup.destroy)
                GLib.idle_add(self.callback, True, "", destination_path)
        except Exception as e:
            tb = traceback.format_exc()
            print(tb)
            GLib.idle_add(self.please_wait_popup.destroy)
            GLib.idle_add(self.callback, False, "Error mounting NFS folder: " + tb)
Exemplo n.º 48
0
def getMinutesAverage(code=None):
    """
        Takes: carrier code (str)
        Query variables: month (str), content-type (str), delay (str), airport-code1 (str), airportcode2 (str)
        Returns:  ?
    """

    ## Load args ##
    month = request.args.get("month")
    contentType = request.args.get("content-type")
    delayType = request.args.get("delay")
    airportCode1 = request.args.get("airport-code1")
    airportCode2 = request.args.get("airport-code2")

    if (contentType == "None" or contentType is None):
        contentType = "application/json"
    queryString = "?airport-code1=" + str(
        airportCode1) + "&content-type=" + str(contentType) + "&month=" + str(
            month)
    ###############

    ## Logic     ##
    carrier = Carrier.query.filter_by(code=code).first()
    airport1 = Airport.query.filter_by(code=airportCode1).first()
    airport2 = Airport.query.filter_by(code=airportCode2).first()
    if (carrier is None or airport1 is None or airport2 is None):
        flask.abort(404, "404(Carrier or Airport not found)")

    dict = Utility.getMean(airport1, airport2, carrier, month)
    if (dict == "None"):
        return flask.abort(500, "empty dictionary return for mean")
    standardDeviationDictionary = Utility.getStandardDeviation(
        airport1, airport2, carrier, month, dict)

    finalDictionary = {
        "mean": dict,
        "standard-deviation": standardDeviationDictionary,
        "carrier-uri": "/carriers/" + code + queryString
    }

    return json.dumps(finalDictionary)
Exemplo n.º 49
0
    def license_valid(self, user_email, app_code, license_text):
        try:
            f = Fernet(self.secret_key)
            license_decryped = f.decrypt(license_text)

            license_components = license_decryped.decode().split('|')
            license_user_email, license_app_code, license_valid, license_salt = map(
                lambda s: s.split(":")[1], license_components)

            user_email_matches = user_email == license_user_email
            app_id_matches = app_code == license_app_code
            license_validity_left = (Utility.parseDateYMD(license_valid) - \
                                     Utility.parseDateYMD(str(datetime.now()).split(" ")[0])).days

            if user_email_matches and app_id_matches and license_validity_left > 0:
                return {"valid": True, "day_left": license_validity_left}
            else:
                return {"invalid": False, "day_left": 0}

        except InvalidToken as i:
            raise InvalidToken
Exemplo n.º 50
0
    def GetStore(self: Any) -> Optional[Dict[str, Any]]:
        """
        Fetch the latest Store data for Modern Warfare and Warzone from
        the Tracker Network API.
        """

        data: Optional[Any] = Utility.GET(
            self, "https://api.tracker.gg/api/v1/modern-warfare/store")

        if data is None:
            return None

        store: Dict[str, Any] = data.get("data")
        updateDate: str = Utility.ISOtoHumanDate(self,
                                                 store.get("lastUpdated"))
        updateTime: str = Utility.ISOtoHumanTime(self,
                                                 store.get("lastUpdated"))

        log.info(f"Fetched the Store for {updateDate} at {updateTime} UTC")

        return store
Exemplo n.º 51
0
 def write_lai_report(cls, report, report_file_name):
     mcc, mnc, lac = util.mcc_mnc_lac_from_filename(report_file_name)
     columns = ["cgi", "nearest", "distance"]
     with open(report_file_name, 'w') as outfile:
         producer = csv.DictWriter(outfile, fieldnames=columns)
         producer.writeheader()
         for cgi, relations in report.items():
             producer.writerow({
                 'cgi': cgi,
                 'nearest': relations['nearest'],
                 'distance': relations['distance']
             })
Exemplo n.º 52
0
    def Compile(self: Any) -> None:
        """Compile the Accessory XAssets."""

        accessories: List[Dict[str, Any]] = []

        accessories = Accessories.IDs(self, accessories)
        accessories = Accessories.Table(self, accessories)

        Utility.WriteFile(self, f"{self.eXAssets}/accessories.json",
                          accessories)

        log.info(f"Compiled {len(accessories):,} Accessories")
 def testDirectCreationIsSuccess(self):
     """Test if directory exists"""
     log.info(self.testDirectCreationIsSuccess.__name__)
     for directory in Utility.gen(self.directory_names):
         excode = os.path.isdir(directory)
         if (excode):
             Utility.Logtst.debug_log(
                 log, 'Directory {} exist: Yes'.format(directory))
         else:
             Utility.Logtst.debug_log(
                 log, 'Directory {} exist: No'.format(directory))
             raise EOFError('No such directory {}'.format(directory))
Exemplo n.º 54
0
    def get_model_paths(self):
        path = self.get_path()
        j_path = '%s_best.json' % (path)
        w_path = '%s_best_weights.h5' % (path)

        # first, attempt the best model, otherwise default to the latest
        if not os.path.exists(j_path) and not os.path.exists(w_path):
            path = Utility.get_dir(self.path)
            j_path = '%s/%s_%s.json' % (Paths.Models, self.id, self.type)
            w_path = '%s/%s_%s_weights.h5' % (Paths.Models, self.id, self.type)

        return j_path.lower(), w_path.lower()
Exemplo n.º 55
0
    def parse_input(file):
        formulas = []
        for line in Utility.read_linestxt(file):
            formula = Formula()
            compounds, result = line.split("=>")

            result_element = Chemist.string_to_element(result)
            formula.set_result(result_element)
            for element_line in compounds.split(","):
                formula.add_compound(Chemist.string_to_element(element_line))
            formulas.append(formula)
        return formulas
Exemplo n.º 56
0
def person_search():
    _first_name, _father_name, _dob = request.json["name"], request.json["father_name"], \
                                   Utility.get_date(request.json["dob"])
    _first_name = _first_name.lower()
    _father_name = _father_name.lower()

    user_found: People = db.session.query(People).filter_by(
        dob=_dob, father_name=_father_name, first_name=_first_name).first()
    if user_found is not None:
        return person_schema.jsonify(user_found)
    else:
        return jsonify(Resources.data["error_detail_not_found"])
Exemplo n.º 57
0
def view_activity(start_date, end_date):
    token = request.environ['HTTP_AUTHORIZATION']
    _user_id = Utility.get_payload_from_jwt(token)["id"]
     
    base_report_path = './data/report'
    user_folder = str(_user_id)
    report_file_namea = '{}_{}.xlsx'.format(start_date, end_date)
    report_path = os.path.join(base_report_path, user_folder, report_file_namea)
    report_absolute_location = os.path.abspath(report_path)
    Utility.make_directory(base_report_path, user_folder)

    if os.path.exists(report_absolute_location):
        os.remove(report_absolute_location)
    
    parsed_start_date = get_date(start_date)
    parsed_end_date   = get_date(end_date) + timedelta(days=1)
    result = db.session.query(Activity).filter(Activity.when >= parsed_start_date, Activity.when < parsed_end_date , Activity.user_id==_user_id).all()

    upsert_activities(result, start_date, end_date, report_absolute_location)

    return send_file(report_path, attachment_filename=report_file_namea)
 def localization_error_regression(pred_batch, truth_batch, debug=False):
     '''euclidian error when modeling the output representation is a matrix (image)\
        both pred and truth are batches, typically a batch of 32
     '''
     error = []
     for pred, truth in zip(pred_batch, truth_batch):
         if debug:
             print(pred, truth)
         pred_x, pred_y = pred[0], pred[1]
         true_x, true_y = truth[0], truth[1]
         error.append(Utility.distance((pred_x, pred_y), (true_x, true_y)))
     return error
 def getTableHeader(self, fileList):
     utility = Utility()
     filePaths = self.getFilePaths(fileList, "csv",
                                   ResourceLocation.DatabaseLocation.value)
     utility.writeLogs(ResourceLocation.LogFileLocation.value,
                       ("\n").join(filePaths), LogMessage.Files.value, "a",
                       False)
     tableHeaders = []
     for filePath in filePaths:
         fileHeader = ((FileUtil(filePath, "r")).getFileContent())[0]
         tableHeaders.append(fileHeader)
     return tableHeaders
Exemplo n.º 60
0
    def flatten_partition_string(self, short_device_node):
        flat_string = ""
        base_device_node, partition_number = Utility.split_device_string(
            short_device_node)
        type = self.foxclone_dict['partitions'][short_device_node]['type']
        if type == "extended":
            flat_string = type
            return flat_string
        else:
            fs = self.foxclone_dict['partitions'][short_device_node]['fs']
            if fs is None:
                flat_string += "unknown"
            elif fs != "":
                flat_string += self.foxclone_dict['partitions'][
                    short_device_node]['fs'] + " "

            num_bytes = self._compute_partition_size_byte_estimate(
                short_device_node)
            flat_string += " " + str(
                Utility.human_readable_filesize(num_bytes))
            return flat_string