示例#1
0
 def loadInfo(self, content):
    
     lines = content.splitlines()
     del content
     
     #keeps the last key in use. 
     lastkey = None
     pkg_info = package.package()
     
     for line in lines:
        
         #New package info
         if len(line) == 0 :
             self.pkg_list.append(pkg_info)
             pkg_info = package.package()
         #Multiline info
         #TODO: Update files list
         elif line.startswith(' '):
             key = lastkey
             value = pkg_info.get(key)
             value +=  '\n%s'%line
             pkg_info.set(key, value)
         
         else:
             #get key
             splited_line = line.split(':',1)
             if len(splited_line) > 1:
                 value = splited_line[1].strip()
             else:
                 print "Bad line:_____%s______"%line
           
             key = splited_line[0].strip()
             pkg_info.set(key,value)
             lastkey = key
     del lines
示例#2
0
def publish_cmd(args):
    label = None if args.prerelease == False else "pre"

    project = Project(os.getcwd(), "release", label)

    print "Preparing release {}".format(project.release_tag_name())
    if not args.force:
        helpers.assert_clean()
        helpers.assert_branch(project.release_branch())
        helpers.set_version(project.build_version(), project.label())

    print("Building: {}".format(project.build_product()))
    build.build(project)

    print("Signing product with identity \"{}\"".format(
        project.codesign_identity()))
    sign.sign_everything_in_app(project.build_product(),
                                project.codesign_identity())

    print("Packaging {} to {} as {}".format(project.build_product(),
                                            project.image_path(),
                                            project.image_name()))
    package(project.build_product(), project.image_path(),
            project.image_name())

    print("Generating release notes...")
    generate_release_notes(project)

    print("Committing and tagging \"{}\"".format(project.release_tag_name()))
    if not args.force:  # We didn't set_version, so nothing should have changed
        commit_release(project)
    tag_release(project.release_tag_name(), args.force)

    publish_release(project, args.prerelease, args.draft, args.dry_run)
示例#3
0
def publish_cmd(args):
    label = None if args.prerelease == False else "pre"
    
    project = Project(os.getcwd(), "release", label)

    print "Preparing release {}".format(project.release_tag_name())
    if not args.force:
        helpers.assert_clean()
        helpers.assert_branch(project.release_branch())
        helpers.set_version(project.build_version(), project.label())

    print("Building: {}".format(project.build_product()))
    build.build(project)

    print("Signing product with identity \"{}\"".format(project.codesign_identity()))
    sign.sign_everything_in_app(project.build_product(), project.codesign_identity())

    print("Packaging {} to {} as {}".format(project.build_product(), project.image_path(), project.image_name()))
    package(project.build_product(), project.image_path(), project.image_name())

    print("Generating release notes...")
    generate_release_notes(project)

    print("Committing and tagging \"{}\"".format(project.release_tag_name()))
    if not args.force: # We didn't set_version, so nothing should have changed
        commit_release(project)
    tag_release(project.release_tag_name(), args.force)

    publish_release(project, args.prerelease, args.draft, args.dry_run)
示例#4
0
def business_function(tcpClientSocket, number):

    #业务功能
    bracelet = 10000000
    while bracelet < 10000000 + number:
        bracelet += 1
        data_bracelet = data.bracelet_id(bracelet)

        text = json.dumps(data_bracelet)
        print('发送的业务数据', text)
        iv = Random.new().read(AES.block_size)
        aes = AESUtil.AESUtil('keykeykeykeykey1', iv)  # 初始化密钥 和 iv
        data_aes = iv + aes.encrypt(text)  # 加密
        cmd = 0x70
        t = (int(time.time()))

        send_package = package.package(data_aes, cmd, t)
        # 转成16进制
        data_hex = np.array(bytearray(send_package))
        tcpClientSocket.send(data_hex)  # 发送数据

        def recv_size(the_socket):
            # 先读取4个字节,赋值给l,然后根据l在读取l长度字节
            recv_size = the_socket.recv(4)
            l = int.from_bytes(recv_size, byteorder='big', signed=True)
            sock_data = the_socket.recv(l)
            return sock_data

        #接收数据
        feedback = recv_size(tcpClientSocket)
        msg_id = package.analysis(feedback)[0]  # 获取msg_id
        print('feedbackmsg_id:', msg_id)
        analysis_package = package.analysis(feedback)[1]  # 获取解析数据包
        print('feedback解析数据包:', analysis_package)
        assert str(t) in analysis_package.decode('utf-8')

        recvData = recv_size(tcpClientSocket)
        msg_id = package.analysis(recvData)[0]  #获取msg_id
        print('业务返回的msg_id:', msg_id)
        analysis_package = package.analysis(recvData)[1]  #获取解析数据包
        print('业务解析数据包:', analysis_package)

        #############返回feedback###################
        feedback = [{
            'msg_id': msg_id,  # 消息ID int64 此feedback包是针对该msg_id的回包
        }]
        text = json.dumps(feedback)
        iv = Random.new().read(AES.block_size)
        aes = AESUtil.AESUtil('keykeykeykeykey1', iv)  # 初始化密钥 和 iv
        data_aes = iv + aes.encrypt(text)  # 加密

        # #####返回包头#####
        t = (int(time.time()))
        result_feedback = package.package(data_aes, 0x6F, t)
        # 转成16进制
        data_hex = np.array(bytearray(result_feedback))
        tcpClientSocket.send(data_hex)  # 发送数据
示例#5
0
文件: win32build.py 项目: ieure/pypy
def make_pypy(tag, options):
    pypy = 'pypy%s' % (tag,)
    args = [sys.executable,
         str(builddir.join('translate.py')),
         '--output=' + pypy,
         ] + options
    print "Execute", args
    p = subprocess.Popen(args, cwd=str(builddir))
    p.wait()
    zipfile = 'pypy-%s-win32%s' % (VERSION, tag)
    package.package(pypydir.dirpath(), zipfile, pypy, pypydir)
示例#6
0
def make_pypy(tag, options):
    pypy = 'pypy%s' % (tag, )
    args = [
        sys.executable,
        str(builddir.join('translate.py')),
        '--output=' + pypy,
    ] + options
    print "Execute", args
    p = subprocess.Popen(args, cwd=str(builddir))
    p.wait()
    zipfile = 'pypy-%s-win32%s' % (VERSION, tag)
    package.package(pypydir.dirpath(), zipfile, pypy, pypydir)
示例#7
0
def main():
    config = load_config()
    config["refresh_source"] = False
    config["clean_build"] = False

    global global_config
    global_config = type("Config", (), config)
    verify_package_config(global_config)
    check_arguments()
    complete_parts(global_config)
    build_parts(global_config)
    package(global_config)
示例#8
0
def Equipment_registration(tcpClientSocket, data_register):
    #设备注册0x65
    #data_register = data.register()
    # for letter in data_register:
    text = json.dumps(data_register)
    iv = Random.new().read(AES.block_size)
    #aes = AESUtil.AESUtil('keykeykeykeykey1')  # 初始化密钥 和 iv
    aes = AESUtil.AESUtil('keykeykeykeykey1', iv)  # 初始化密钥 和 iv
    data_aes = iv + aes.encrypt(text)  # 加密]
    cmd = 0x65
    t = (int(time.time()))
    send_package = package.package(data_aes, cmd, t)
    # 转成16进制
    data_hex = np.array(bytearray(send_package))
    tcpClientSocket.send(data_hex)  # 发送数据

    def recv_size(the_socket):
        # 先读取4个字节,赋值给l,然后根据l在读取l长度字节
        recv_size = the_socket.recv(4)
        l = int.from_bytes(recv_size, byteorder='big', signed=True)
        sock_data = the_socket.recv(l)
        return sock_data

    #接收数据
    feedback = recv_size(tcpClientSocket)
    msg_id = package.analysis(feedback)[0]  # 获取msg_id
    print('feedback返回的msg_id:', msg_id)
    analysis_package = package.analysis(feedback)[1]  # 获取解析数据包
    print('feedback解析数据包:', analysis_package.decode('utf-8'))
    assert str(t) in analysis_package.decode('utf-8')
    recvData = recv_size(tcpClientSocket)
    msg_id = package.analysis(recvData)[0]  #获取msg_id
    print('注册返回的msg_id:', msg_id)
    analysis_package = package.analysis(recvData)[1]  #获取解析数据包
    print('注册解析数据包:', analysis_package)

    #############返回feedback###################
    feedback = [{
        'msg_id': msg_id,  # 消息ID int64 此feedback包是针对该msg_id的回包
    }]
    text = json.dumps(feedback)
    iv = Random.new().read(AES.block_size)
    aes = AESUtil.AESUtil('keykeykeykeykey1', iv)  # 初始化密钥 和 iv
    data_aes = iv + aes.encrypt(text)  # 加密

    # #####返回包头#####
    t = (int(time.time()))
    result_feedback = package.package(data_aes, 0x6F, t)
    # 转成16进制
    data_hex = np.array(bytearray(result_feedback))
    tcpClientSocket.send(data_hex)  # 发送数据
def main():
    parser = argparse.ArgumentParser(
        description="SOTorrent - Comment Induced Updates")
    parser.add_argument(
        "--stage",
        "-s",
        help="Stage of Analysis: FULL, STATS, NAIVE, EVAL, PACK",
        type=str,
        nargs="+")
    parser.add_argument("--clean",
                        "-c",
                        help="(Re)Make SQL Tables: True, False",
                        type=str,
                        default="T")
    parser.add_argument(
        "--user",
        "-u",
        help="Allow commenters to also be editors: True, False",
        type=str,
        default="F")

    arg_stage = parser.parse_args().stage[0].upper().strip(
    ) if parser.parse_args().stage else None
    if arg_stage is None:
        print("Please specify a stage")
    elif arg_stage == "FULL":
        arg_clean = True if parser.parse_args().clean.upper().strip(
        )[:1] == "T" else False
        arg_filter_user = True if parser.parse_args().user.upper().strip(
        )[:1] == "F" else False
        full(arg_clean, arg_filter_user, False)
    elif arg_stage == "STATS":
        stats()
    elif arg_stage == "NAIVE":
        arg_clean = True if parser.parse_args().clean.upper().strip(
        )[:1] == "T" else False
        arg_filter_user = True if parser.parse_args().user.upper().strip(
        )[:1] == "F" else False
        full(arg_clean, arg_filter_user, True)
    elif arg_stage == "EVAL":
        evaluate()
    elif arg_stage == "PACK":
        try:
            csv = parser.parse_args().stage[1]
            conn = sqlite3.connect("sotorrent.sqlite3")
            package(conn, csv)
            conn.close()
        except IndexError:
            print("Please provide a CSV to pack into JSON")
示例#10
0
    def create_RREP_pck(self,pck_RREQ):
        pck_RREP = package(Network_layer._id_pck,'RREP',"i am a RREP",self.host.get_mac(),pck_RREQ.get_originator())
        
        logging.info(f' I am host[{self.host.get_mac()}] and received a RREQ pack from host[{pck_RREQ.get_originator()}]')
        logging.info(f' Host[{self.host.get_mac()}] is sending a RREP to host[{pck_RREQ.get_originator()}]')
        
        print(f'\033[36m --- HOST[{self.host.get_mac()}] is sending a RREP to HOST[{pck_RREQ.get_originator()}] ---\033[37m')
        Network_layer._id_pck += 1
        
        # get the way back
        way_back = pck_RREQ.get_path()
        for way in way_back:
            # save the way that pck has being through
            pck_RREP.add_path(way)
        
        # saving route
        self.table.save_route(way_back, pck_RREQ.get_originator())
        way_back.reverse()

        # The next jump is who sent to me
        next = way_back.pop(1)
        pck_RREP.add_next(next.get_mac())
        
        #than send to link layer
        self.host.link.sending_request(pck_RREP) 
示例#11
0
def heart_beat(tcpClientSocket, heartbeat):
    #心跳包
    #data_1 = data.heartbeat()
    # 心跳包0x64

    # for letter in data_register:
    text = json.dumps(heartbeat)
    iv = Random.new().read(AES.block_size)
    aes = AESUtil.AESUtil('keykeykeykeykey1', iv)  # 初始化密钥 和 iv
    data_aes = iv + aes.encrypt(text)  # 加密
    cmd = 0x64
    t = (int(time.time()))
    send_package = package.package(data_aes, cmd, t)
    # 转成16进制
    data_hex = np.array(bytearray(send_package))
    tcpClientSocket.send(data_hex)  # 发送数据

    def recv_size(the_socket):
        # 先读取4个字节,赋值给l,然后根据l在读取l长度字节
        recv_size = the_socket.recv(4)
        l = int.from_bytes(recv_size, byteorder='big', signed=True)
        sock_data = the_socket.recv(l)
        return sock_data

    #接收数据
    # feedback = recv_size(tcpClientSocket)
    recvData = recv_size(tcpClientSocket)
    msg_id = package.analysis(recvData)[0]  #获取msg_id
    print('心跳返回的msg_id:', msg_id)
    analysis_package = package.analysis(recvData)[1]  #获取解析数据包
    print('心跳解析数据包:', analysis_package)


# print('关闭 socket!')
示例#12
0
 def __init__(self, depends=[]):
   rave3ver = NODE_REPOSITORY["RAVE"].getversion()
   rave3uri = NODE_REPOSITORY["RAVE"].geturi()
   rave3branch = NODE_REPOSITORY["RAVE"].getbranch()
   rave3fetcher = gitfetcher(rave3uri, rave3ver, rave3branch)
   self._rave3package=package("RAVE", rave3ver, rave3fetcher, depends)
   self._currentpackage=self._rave3package
   super(rave_package, self).__init__("RAVE", "UNDEFINED")
示例#13
0
def force_download():
    """
    address where you can tell server to force download package
    """
    if request.method == 'POST':
        form_package = request.form.get('package')
        if not form_package:
            return render_add_template("You have to fill package name.",
                                       "danger")

        try:
            data = simple_package(form_package, True)
        except exceptions.NotFound:
            return render_add_template("Package not found.", "danger")

        versions = data.get('versions')

        form_version = str(request.form.get('version'))
        highest_dig = -1
        package_version = None
        name_dig_list = []

        for version in versions:
            name = str(version.name)
            if name.endswith(".whl"):
                continue

            name_digonly = re.sub("[^0123456789\.]", "", name)
            name_dig_pretty = name_digonly.replace("..", "")
            name_dig_list.append(name_dig_pretty)

            if form_version:
                if form_version == name_dig_pretty:
                    package_version = version
            else:
                if name_dig_pretty > highest_dig:
                    highest_dig = name_dig_pretty
                    package_version = version

        if not package_version:
            return render_add_template(
                "Given version not found.", "danger",
                "Available versions:\n{}".format(name_dig_list), "info")

        code = package(
            "source", data.get('source_letter'), data.get('package_name'),
            package_version.name,
            urlparse.parse_qs(package_version.external_link).get('remote')[0],
            return_code=True)

        if code == 200:
            return render_add_template(
                "Package already exists. ({})".format(name), "info")
        if code == 201:
            return render_add_template(
                "You have successfully added new package ({})".format(name),
                "success")
    return render_add_template()
示例#14
0
    def rmpackage(self):
        
        current_pkg = package.package()
        if self.deb.endswith('deb'):
            current_pkg.setBinary(True)
        elif self.deb.endswith('dsc'):
            current_pkg.setBinary(False)
        else:
            print "Error: Unknown file format"
            sys.exit(7)
        if not os.path.exists(os.path.join(os.sep, self.apt_conf, 'apt_%s.conf'%self.dist)):
	    print "Error: No se encuentra el fichero de configuraci�n de apt"
	    sys.exit(9)
        print "File: %s"%os.path.join(os.sep, self.repo, self.deb)
        current_pkg.importInfo(os.path.join(os.sep, self.repo, self.deb))
        
        architecture = self.arch
        if current_pkg.isBinary():
	    architecture = 'binary-%s'%self.arch
        else:
            architecture = 'source'            

        index_location = os.path.join(os.sep, self.repo, 'dists', self.dist, self.section, architecture)
        self.branch = index_location
        self.lockBranch()
        plist = packagesList.packagesList()
        print 'Index location: %s'%index_location
        file_content,index_file = self.getIndexContent(index_location)
        plist.loadInfo(file_content)
        #The package is searched by it's path in the pool
        result = plist.searchByName(self.deb, current_pkg.isBinary())
        if result:
            print "Localizando.............OK\nPath: %s"%self.deb
            plist.removePackage(result)
	    path = os.path.join(os.sep, self.repo, 'dists', self.dist, self.section, architecture)
            print 'Index file: ' + os.path.join(os.sep, self.repo, 'dists', self.dist, self.section, architecture, index_file)
            plist.newFiles(path, current_pkg.isBinary())
	    dirs = os.walk(path)
	    dirs = dirs.next()[-1]
	    for f in dirs:
	    	if not f.startswith('.'):
			try:
			     print "cambiando permisos a %s"%(path + os.sep + f)
                             os.chmod(path + os.sep + f, 0664)
                             print "cambiando grupo a %s"%(path + os.sep + f)
                             os.chown(path + os.sep + f, os.getuid(), self.gid)
			except:
			     print 'Error cambiando permisos a %s'%(os.sep.join([path,f]))
            print "File removed from index....%s"%os.path.join(os.sep, self.repo, self.deb)
            done = True
            self.unLockBranch()
        else:
            print "No se ha localizado el paquete....%s"%self.deb
            self.unLockBranch()
            sys.exit(2)
            done = False
            
        return done
示例#15
0
    def add_package(self):
        
	#Creating package instance
        current = package.package()      
        file_name = self.deb.split(os.sep)[-1]
        #Source files support
        if file_name.endswith('.dsc'):
            current.setBinary(False)
        #TODO:filter wrong input
        if os.path.exists(self.deb):
            if current.importInfo(self.deb):
                sys.exit(2)
        else:
            print "The file %s doesn't exists"%self.deb
            sys.exit(2)
        
        if not os.path.exists(self.apt_file):
            print "No se encuentra el fichero de configuraci�n apt_codename.conf"
            sys.exit(9)

        current_section = current.get('Section')
        current_arch = current.get('Architecture').strip()
        #Get supported sections and architectures from apt config file
        (dist_sections, dist_architectures) = self.getAptInfo()
    
        #Check if both section and architectures exist in the repository
        current_section = current_section.split('/')
        if self.section:
	    pass
	elif not self.section and len(current_section) > 1 and current_section[0] in dist_sections:
            self.section = current_section[0].strip()
        #If no section is especified or it doesn't exists set main section as default.
        else:
            self.section = 'main'
        print "section\t\t\t%s"%self.section
        #Check if architecture exists
        #TODO: Add in all  architectures.
        dist_architectures.append('all')
        default = 'i386'
        print 'current_arch: %s'%current_arch
        if current.isBinary() and current_arch in dist_architectures:
            if current_arch == 'all':
                current_arch = default
            self.arch = 'binary-%s'%current_arch
        elif not current.isBinary() and current_arch in ['all','any']:
            self.arch = 'source'
        else:
            print '\nUnknown architecture: %s'%current_arch
            sys.exit(3)
        print 'Architecture: %s'%self.arch
        self.branch = os.path.join(os.sep,self.repo, 'dists', self.dist, self.section, self.arch)
        self.lockBranch()
        self.updateIndexFiles(current, file_name)
        self.updatePool(current)
        #self.gen_Release()
        self.unLockBranch()
        sys.exit(0)
 def createpack(self,probability,slot):
     n = random.random()
     #check if the station will create a package
     if n<probability :
         newpack = package.package(slot)
         #if the package was created check if the buffer is full
         if len(self.buffer) == self.buffersize :
             del(newpack)
         #if there is space on the buffer append the package
         else:
             self.buffer.append(newpack)
示例#17
0
    def getMediaList(self, folderName='', cacheType=CACHE_TYPE_MEMORY):

        if folderName == '':
            folderName = 'myfiles'

        opener = urllib2.build_opener(
            urllib2.HTTPCookieProcessor(self.cookiejar), MyHTTPErrorProcessor)
        opener.addheaders = [('User-Agent', self.user_agent),
                             ('X-Requested-With', 'XMLHttpRequest')]

        sessionValue = self.authorization.getToken('session_token')
        if (sessionValue == ''):
            xbmcgui.Dialog().ok(self.addon.getLocalizedString(30000),
                                self.addon.getLocalizedString(30049),
                                self.addon.getLocalizedString(30050),
                                'sessionValue')
            self.crashreport.sendError('getMediaList:sessionValue', 'not set')
            xbmc.log(
                self.addon.getAddonInfo('name') + ': ' +
                self.addon.getLocalizedString(30050) + 'sessionValue',
                xbmc.LOGERROR)
            return

        if folderName == 'FOLLOWING':
            url = 'https://www.mediafire.com/api/1.4/device/get_foreign_resources.php?r=sfrv&session_token=' + sessionValue + '&response_format=json'

            request = urllib2.Request(url)
            self.cookiejar.add_cookie_header(request)

            # try login
            try:
                response = opener.open(request)

            except urllib2.URLError, e:
                xbmc.log(
                    self.addon.getAddonInfo('name') + ': ' + str(e),
                    xbmc.LOGERROR)
                return
            response_data = response.read()
            response.close()

            mediaFiles = []
            # parsing page for files
            for r in re.finditer('\"folders\"\:\[\{.*?\}\]', response_data,
                                 re.DOTALL):
                entry = r.group()
                for q in re.finditer(
                        '\"name\"\:\"([^\"]+)\"\,.*?\"folderkey\"\:\"([^\"]+)\"',
                        entry, re.DOTALL):
                    subfolderName, subfolderID = q.groups()

                    media = package.package(
                        0, folder.folder(subfolderID, subfolderName))
                    mediaFiles.append(media)
示例#18
0
def full(clean, filter_user, naive):
    conn = sqlite3.connect("sotorrent.sqlite3")
    print("Connection made")
    if clean:
        setup_sqlite(conn)
    start = time.time()
    df_questions, df_answers, df_comments, df_edits = get_data(conn)
    end = time.time()
    print("Data loading took {0:2f} seconds".format(end - start))

    pipeline = Processor(conn, df_questions, df_answers, df_comments, df_edits,
                         filter_user, naive)
    start = time.time()
    pipeline.process()
    end = time.time()
    print("Took {0:2f} seconds to process".format(end - start))

    # Generate the statistics
    stats()

    # Package the results into JSON
    package(conn, "results.csv")
    print("Finished packaging pairs into JSON")
    conn.close()
	def package_parse(self, pack):
		ack = False
		if pack.startswith(redundancy.ack_prefix):
			ack = True
			pack = pack[len(redundancy.ack_prefix):]
		prefix = None
		for index in redundancy.messages:
			if pack.startswith(redundancy.messages[index]):
				prefix = index
				pack = pack[len(redundancy.messages[index]):]
				break
		if prefix == None: return 1 # Fatal error

		pkg = package.package(ack, prefix, pack)
		self.buffer_list.push_right(pkg)
		return 0
示例#20
0
    def getMediaList(self, folderName='', cacheType=CACHE_TYPE_MEMORY):

        if folderName == '':
            folderName = 'myfiles'



        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookiejar), MyHTTPErrorProcessor)
        opener.addheaders = [('User-Agent', self.user_agent),('X-Requested-With' ,'XMLHttpRequest')]



        sessionValue = self.authorization.getToken('session_token')
        if (sessionValue == ''):
            xbmcgui.Dialog().ok(self.addon.getLocalizedString(30000), self.addon.getLocalizedString(30049), self.addon.getLocalizedString(30050),'sessionValue')
            self.crashreport.sendError('getMediaList:sessionValue','not set')
            xbmc.log(self.addon.getAddonInfo('name') + ': ' + self.addon.getLocalizedString(30050)+ 'sessionValue', xbmc.LOGERROR)
            return

        if folderName == 'FOLLOWING':
            url = 'https://www.mediafire.com/api/1.4/device/get_foreign_resources.php?r=sfrv&session_token='+sessionValue+'&response_format=json'

            request = urllib2.Request(url)
            self.cookiejar.add_cookie_header(request)

            # try login
            try:
                response = opener.open(request)

            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return
            response_data = response.read()
            response.close()


            mediaFiles = []
            # parsing page for files
            for r in re.finditer('\"folders\"\:\[\{.*?\}\]' ,response_data, re.DOTALL):
                    entry = r.group()
                    for q in re.finditer('\"name\"\:\"([^\"]+)\"\,.*?\"folderkey\"\:\"([^\"]+)\"' ,entry, re.DOTALL):
                        subfolderName,subfolderID = q.groups()

                        media = package.package(0,folder.folder(subfolderID,subfolderName))
                        mediaFiles.append(media)
示例#21
0
    def send_pck(self,message,destination):
        if len(message) > 0 :	#check if message is valid
            # print for debugging
            print('* '*20)
            print("* Creating a package in network_layer *")
            print('* '*20, '\n')

            #new package with the message
            pck = package(Network_layer._id_pck,'DATA',message,self.host.get_mac(),destination)
            logging.info(f' Created a DATA package from host[{self.host.get_mac()}] to host[{destination}]')
            
            pck.package_info() # prints the package information
            Network_layer._id_pck += 1 # update the id

            # checks if the destination is my neighbor
            nb = self.host.get_neighbors()
            var = False
            for obj in nb:
                if destination == obj.get_mac():
                    var = True
                    break    

            # destination is a host's neighbor
            if var:
                logging.info(f' Host{destination} is my neighbor, so I can send')
                self.host.link.sending_request(pck)

            # if is not my neighbor, then check if I have a way to him
            if self.table.get_route() != {}:
                print("\033[36m\t\tL3: I HAVE A ROUTE TABLE, BUT I DO NOT KNOW IF I HAVE DESTINY ON IT \033[37m")
                # set the next jump
                next_jp = self.table.next_jump(destination, self.host)
                
                if next_jp:
                    logging.info(f' I(host{self.host.get_mac()}) can get into the destination')
                    logging.info(f' And the next jump is to host[{next_jp}]')
                    pck.add_path(self.host)
                    pck.add_next(next_jp)
                    self.host.link.sending_request(pck)
            
            # if the host can't get into the destination, then it make a RREQ
            else :
                print(f"\033[36m +++++++++ L3: HOST{self.host.get_mac()} HAS NO ROUTE TO {destination}\033[37m")
                logging.info(f' I am host[{self.host.get_mac()}] and do not have a route for {destination} yet')
                self.create_RREQ_pck(pck)
示例#22
0
    def create_RREQ_pck(self,pck):
        self.pending_pck.append(pck) # save the package to send later
        
        pck_RREQ = package(Network_layer._id_pck,'RREQ',"I am a RREQ",self.host.get_mac(),pck.get_destination())
        Network_layer._id_pck += 1
        # if the host makes this type of pck, is saves to a list, so it won't send again
        self.received_pck.append(pck_RREQ.get_id())
        
        # print for debugging
        print(f'\t\t\033[36m HOST[{self.host.get_mac()}] IS CREATING A RREQ TO {pck.get_destination()}\033[37m\n')
        print(f'\t\t\033[36m HOST[{self.host.get_mac()}] IS ADDING ITSELF TO THE PATH\033[37m\n')
        
        # log print
        logging.info(f' Host[{self.host.get_mac()}] created a RREQ pack to host[{pck.get_destination()}]')
        logging.info(f' I am adding myself to the path')

        pck_RREQ.add_path(self.host) # adding itself on the path
        self.host.link.sending_request(pck_RREQ) # send a request to master
示例#23
0
文件: fisel_encr.py 项目: plow/fisel
import hashdeep
import obfuscate
import package

hashdeep_out_file = "file_hashes.out"

hashdeep.hashdeep(hashdeep_out_file)
obfuscate.obfuscate(hashdeep_out_file)
package.package()

示例#24
0
文件: client.py 项目: Uzivija/Network
                elif y[0] == "t":
                    packet_response.set_time(y[1])
                elif y[0] == "d1":
                    packet_response.add_data(y[1])
                    print(y[1])
                elif y[0] == "e":
                    packet_response.set_end(y[1])
    packet_response.set_s("ACK")
    packet_response.set_t()
    response = packet_response.return_packet_sort
    UDPClientSocket.sendto(response.encode(), serverAddressPort)

UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)  # gniazdo

while True:
    packet = package()
    packet_response = package()
    print("Wybierz operacje:\n"
          "modulo\n"
          "dodawanie\n"
          "odejmowanie\n"
          "losowanie\n"
          "sortowanie rosnace\n"
          "sortowanie malejace\n\n"
          "Aby zakończyć wpisz exit")
    msgFromClient = input("\n")

    if msgFromClient == "modulo":
        print("Modulo")
        liczba1 = input("Podaj pierwsza liczbe: ")
        liczba2 = input("Podaj druga liczbe: ")
示例#25
0
from package import package

with open('cipher.txt', 'r+') as chars:
    package(chars.read(), flag='to_cipher')
示例#26
0
import socket
import time
import random
import sys
from package import package


listeningAddress = ("", 20001)
UDPSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)  # gniazdo
UDPSocket.bind(listeningAddress)

p1 = package()
print(time.ctime())
session_id = random.randint(1000, 100000)
while True:

    # odebranie komunikatu
    bytesAddressPair = UDPSocket.recvfrom(1024)
    message = bytesAddressPair[0].decode()
    address = bytesAddressPair[1][0]

    # identyfikator sesji
    p1.set_i(session_id)

    # wyswietlenie komunikatu
    print(time.ctime())
    print("Message from client:", message)

    # odczytanie operacji komunikatu
    c_message = message.split("#")
    for x in c_message:
示例#27
0
import datetime
from datetime import time
import calculator

#Variables
hashtable = hashtable()
addressList = []
distanceList = []

#Read in package data from csv
with open('data/packages.csv') as packageFile:
    reader = csv.reader(packageFile, delimiter=',')

    for row in reader:
        timestamp = time(hour=0, minute=0, second=0, microsecond=0)
        temp = package(row[0], row[1], row[2], row[3], row[4], row[5], row[6],
                       row[7], timestamp)
        hashtable.insert(int(temp.id) - 1, temp)

#Read in distance data from csv
with open('data/distances_table.csv') as distanceFile:
    reader = csv.reader(distanceFile, delimiter=',')
    for row in reader:
        distanceList.append(row)

#Read in address data from csv
with open('data/addresses.csv') as addressFile:
    reader = csv.reader(addressFile, delimiter=',')
    for row in reader:
        list1 = [row[0]]
        list1.append(row[2])
        addressList.append(list1)
示例#28
0
from package import package

chars = """ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*():"'<>?[],.?/-_=+ """
print(len(chars))
package(chars, flag='to_uncipher')
示例#29
0
        response_data = response.read()
        response.close()

        mediaFiles = []


        if folderName == 'FRIENDS':
            for r in re.finditer('\"thumbnail\"\:\"([^\"]+)\".*?\"userId\"\:\"([^\"]+)\"\,\"authName\"\:([^\,]+)\,\"authLastName\"\:([^\,]+)\,\"authFirstName\"\:([^\,]+)\,' ,response_data, re.DOTALL):
                thumb,userID,userName,userFirst,userLast = r.groups()
                thumbURL = re.sub('"', '', re.sub('\\\/', '/', thumb))
                userName = re.sub('"', '', userName)
                userFirst = re.sub('"', '', userFirst)
                userLast = re.sub('"', '', userLast)

                if userName != 'null':
                    media = package.package(0,folder.folder('u='+userID+'f=0',userName, thumbURL))
                else:
                    media = package.package(0,folder.folder('u='+userID+'f=0',userFirst + ' - '+userLast, thumbURL))

                mediaFiles.append(media)

            return mediaFiles
        elif folderName == 'FEED':
            for r in re.finditer('\{\"id\"\:.*?\d\"\}' ,response_data, re.DOTALL):
                entry = r.group()

                for q in re.finditer('\"hiveId\"\:\"([^\"]+)\".*?\"thumb\"\:\"([^\"]+)\".*\"title\"\:\"([^\"]+)\".*\"type\"\:\"video\"' ,entry, re.DOTALL):
                    fileID,thumbnail,fileName = q.groups()
                    thumbnail = re.sub('\\\\', '', thumbnail)
                    fileName = urllib.quote(fileName)
                    media = package.package(file.file(fileID, fileName, fileName, self.VIDEO, '', thumbnail),folder.folder('',''))
示例#30
0
For each list:
    0: In deck
    1: In player
    2: In Greedy_AI
    3: In waste
'''
card_map = [ [ 0 for y in range( 4 ) ] for x in range( 52 ) ]
for i in range(len(card_map)):
    card_map[i][0] = 1

modify_card_map(card_map, handPL, 1)
modify_card_map(card_map, handAI, 2)


gameinfo = package.package(card_map=card_map, handPL=handPL, handAI=handAI, scorePL=scorePL, scoreAI=scoreAI, pastwin)

'''
Start game
'''
while True:
    gameinfo = Round(gameinfo)
    if len(deck) == 0:
        if len(handPL) == 0:
            rocker = 'PL'
            handAI,scorePL,scoreAI,waste = Endgame(handAI,scorePL,scoreAI,rocker,waste)
            break
        elif len(handAI) == 0:
            rocker = 'AI'
            handPL,scorePL,scoreAI,waste = Endgame(handPL,scorePL,scoreAI,rocker,waste)
            break
示例#31
0
    elif instanceName != '':

            oc = box.box(PLUGIN_URL,addon,instanceName, user_agent)

    try:
            oc
    except NameError:
            xbmcgui.Dialog().ok(addon.getLocalizedString(30000), addon.getLocalizedString(30049), addon.getLocalizedString(30050), 'oc')
            log(aaddon.getLocalizedString(30050)+ 'oc', True)
            xbmcplugin.endOfDirectory(plugin_handle)


    mediaFile = file.file(filename, title, '', 0, '','')
    mediaFolder = folder.folder(directory,directory)
    url = oc.getPlaybackCall(cacheType,package.package(mediaFile,mediaFolder ))

    item = xbmcgui.ListItem(path=url)
    item.setInfo( type="Video", infoLabels={ "Title": title , "Plot" : title } )
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
#play a video given its exact-title
elif mode == 'streamurl':

    url = plugin_queries['url']

    try:
        title = plugin_queries['title']
    except:
        title = ''

示例#32
0
from extra_functions import *
from node_installer import node_installer
from experimental import experimental

##
# All modules that should be installed for the baltrad node
# Note, it is essential that the order is correct here since
# they will be installed in this order. There is no dependency
# checking for this.
#
# So, if for example HDF5 is dependent on ZLIB. ZLIB must be installed prior to
# HDF5. But since HDF5 is dependent on ZLIB, HDF5 must get the depends set to ZLIB
# so that HDF5 is rebuilt each time ZLIB is rebuilt.
##
MODULES = [
    prepareinstaller(package("PREPARE", "1.0", nodir(), remembered=False)),
    shinstaller(package("ZLIB", "1.2.11", nodir()), ":"),
    cmmi(
        package("HDF5",
                "1.10.1",
                untar(urlfetcher("hdf5-1.10.1.tar.gz"), "hdf5-1.10.1", True),
                depends=["ZLIB"]),
        "--prefix=\"$TPREFIX\" --with-pthread=yes --enable-threadsafe --enable-unsupported",
        False,
        True,  # unsupported for MT + HL library
        foptionalarg=hdf5_optional_zlib_arg),
    netcdfinstaller(
        package("NETCDF",
                "4.5.0",
                untar(urlfetcher("netcdf-c-4.5.0.tar.gz"), "netcdf-c-4.5.0",
                      True),
示例#33
0
                if mode == 'audio':
                    playbackType = int(
                        addon.getSetting('free_playback_type_audio'))
                else:
                    playbackType = int(
                        addon.getSetting('free_playback_type_video'))
            except:
                if mode == 'audio':
                    playbackType = 0
                else:
                    playbackType = 1

    mediaFile = file.file(filename, title, '', 0, '', '')
    mediaFolder = folder.folder(directory, directory)
    mediaURLs = service.getPlaybackCall(
        playbackType, package.package(mediaFile, mediaFolder))

    playbackURL = ''

    # BEGIN JoKeRzBoX
    # - Get list of possible resolutions (quality), pre-ordered from best to lower res, from a String constant
    # - Create associative array (a.k.a. hash list) availableQualities with each available resolution (key) and media URL (value)
    # - Simple algorithm to go through possible resolutions and find the best available one based on user's choice
    # FIX: list of qualities shown to user are now ordered from highest to low resolution
    if mode == 'audio':
        possibleQualities = addon.getLocalizedString(30058)
    else:
        possibleQualities = addon.getLocalizedString(30057)
    listPossibleQualities = possibleQualities.split("|")
    availableQualities = {}
    for mediaURL in mediaURLs:
示例#34
0
        mediaFiles = []

        if folderName == 'FRIENDS':
            for r in re.finditer(
                    '\"thumbnail\"\:\"([^\"]+)\".*?\"userId\"\:\"([^\"]+)\"\,\"authName\"\:([^\,]+)\,\"authLastName\"\:([^\,]+)\,\"authFirstName\"\:([^\,]+)\,',
                    response_data, re.DOTALL):
                thumb, userID, userName, userFirst, userLast = r.groups()
                thumbURL = re.sub('"', '', re.sub('\\\/', '/', thumb))
                userName = re.sub('"', '', userName)
                userFirst = re.sub('"', '', userFirst)
                userLast = re.sub('"', '', userLast)

                if userName != 'null':
                    media = package.package(
                        0,
                        folder.folder('u=' + userID + 'f=0', userName,
                                      thumbURL))
                else:
                    media = package.package(
                        0,
                        folder.folder('u=' + userID + 'f=0',
                                      userFirst + ' - ' + userLast, thumbURL))

                mediaFiles.append(media)

            return mediaFiles
        elif folderName == 'FEED':
            for r in re.finditer('\{\"id\"\:.*?\d\"\}', response_data,
                                 re.DOTALL):
                entry = r.group()
示例#35
0
                return
            response_data = response.read()
            response.close()

            mediaFiles = []
            # parsing page for files
            for r in re.finditer(
                    '\{\"folderkey\"\:.*?\"dropbox_enabled\"\:\"[^\"]+\"\}',
                    response_data, re.DOTALL):
                entry = r.group()
                for q in re.finditer(
                        '\"folderkey\"\:\"([^\"]+)\"\,\"name\"\:\"([^\"]+)\"',
                        entry, re.DOTALL):
                    subfolderID, subfolderName = q.groups()

                    media = package.package(
                        0, folder.folder(subfolderID, subfolderName))
                    mediaFiles.append(media)

            url = 'https://www.mediafire.com/api/folder/get_content.php?r=mvbn&content_type=files&filter=all&order_by=name&order_direction=asc&chunk=1&version=1.2&folder_key=' + folderName + '&session_token=' + sessionValue + '&response_format=json'

            request = urllib2.Request(url)
            self.cookiejar.add_cookie_header(request)

            # try login
            try:
                response = opener.open(request)

            except urllib2.URLError, e:
                xbmc.log(
                    self.addon.getAddonInfo('name') + ': ' + str(e),
                    xbmc.LOGERROR)
示例#36
0
        # parsing page for files
        for r in re.finditer('\{\"audio\"\:.*?\"userRole\"\:0\}',
                             response_data, re.DOTALL):
            entry = r.group()
            for q in re.finditer('\"(download)\"\:\"([^\"]+)\",', entry,
                                 re.DOTALL):
                downloadID, downloadURL = q.groups()
            for q in re.finditer('\"(title)\"\:\"([^\"]+)\",', entry,
                                 re.DOTALL):
                titleID, title = q.groups()

            downloadURL = re.sub('\\\\', '', downloadURL)
            downloadURL = re.sub('\%20', '+', downloadURL)

            media = package.package(
                file.file(title, title, title, self.AUDIO, '', ''),
                folder.folder('', ''))
            media.setMediaURL(mediaurl.mediaurl(downloadURL, '', '', ''))
            mediaFiles.append(media)

        for r in re.finditer(
                'data\-downloadurl\=\"video\/[^\:]+\:([^\:]+)\:\/index\.php\?rm\=box_v2_download_file\&amp\;file_id\=([^\&]+)\&amp\;print_download_url\=1\"',
                response_data, re.DOTALL):
            fileName, fileID = r.groups()

            media = package.package(
                file.file(fileID, fileName, fileName, self.VIDEO, '', ''),
                folder.folder('', ''))
            mediaFiles.append(media)
        for r in re.finditer(
                'data\-downloadurl\=\"audio\/[^\:]+\:([^\:]+)\:\/index\.php\?rm\=box_v2_download_file\&amp\;file_id\=([^\&]+)\&amp\;print_download_url\=1\"',
示例#37
0
        oc = box.box(PLUGIN_URL, addon, instanceName, user_agent)

    try:
        oc
    except NameError:
        xbmcgui.Dialog().ok(addon.getLocalizedString(30000),
                            self.addon.getLocalizedString(30049),
                            self.addon.getLocalizedString(30050), 'oc')
        log(aaddon.getLocalizedString(30050) + 'oc', True)
        xbmcplugin.endOfDirectory(plugin_handle)

    mediaFile = file.file(filename, title, '', 0, '', '')
    mediaFolder = folder.folder(directory, directory)
    url = oc.getPlaybackCall(cacheType,
                             package.package(mediaFile, mediaFolder))

    item = xbmcgui.ListItem(path=url)
    item.setInfo(type="Video", infoLabels={"Title": title, "Plot": title})
    xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
#play a video given its exact-title
elif mode == 'streamurl':

    url = plugin_queries['url']

    try:
        title = plugin_queries['title']
    except:
        title = ''

    instanceName = ''
示例#38
0
                playbackType = 0
        else:
            try:
                if mode == 'audio':
                    playbackType = int(addon.getSetting('free_playback_type_audio'))
                else:
                    playbackType = int(addon.getSetting('free_playback_type_video'))
            except:
                if mode == 'audio':
                    playbackType = 0
                else:
                    playbackType = 1

    mediaFile = file.file(filename, title, '', 0, '','')
    mediaFolder = folder.folder(directory,directory)
    mediaURLs = service.getPlaybackCall(playbackType,package.package(mediaFile,mediaFolder ))

    playbackURL = ''

    # BEGIN JoKeRzBoX
    # - Get list of possible resolutions (quality), pre-ordered from best to lower res, from a String constant
    # - Create associative array (a.k.a. hash list) availableQualities with each available resolution (key) and media URL (value)
    # - Simple algorithm to go through possible resolutions and find the best available one based on user's choice
    # FIX: list of qualities shown to user are now ordered from highest to low resolution
    if mode == 'audio':
        possibleQualities = addon.getLocalizedString(30058)
    else:
        possibleQualities = addon.getLocalizedString(30057)
    listPossibleQualities = possibleQualities.split("|")
    availableQualities = {}
    for mediaURL in mediaURLs:
示例#39
0
def package_app(app_path, image_path, image_name):
    package.package(app_path, image_path, image_name)
示例#40
0
            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return
            response_data = response.read()
            response.close()


            mediaFiles = []
            # parsing page for files
            for r in re.finditer('\{\"folderkey\"\:.*?\"dropbox_enabled\"\:\"[^\"]+\"\}' ,response_data, re.DOTALL):
                    entry = r.group()
                    for q in re.finditer('\"folderkey\"\:\"([^\"]+)\"\,\"name\"\:\"([^\"]+)\"' ,entry, re.DOTALL):
                        subfolderID,subfolderName = q.groups()

                        media = package.package(0,folder.folder(subfolderID,subfolderName))
                        mediaFiles.append(media)

            url = 'https://www.mediafire.com/api/folder/get_content.php?r=mvbn&content_type=files&filter=all&order_by=name&order_direction=asc&chunk=1&version=1.2&folder_key='+folderName+'&session_token='+sessionValue+'&response_format=json'

            request = urllib2.Request(url)
            self.cookiejar.add_cookie_header(request)

            # try login
            try:
                response = opener.open(request)

            except urllib2.URLError, e:
                xbmc.log(self.addon.getAddonInfo('name') + ': ' + str(e), xbmc.LOGERROR)
                return
            response_data = response.read()
示例#41
0
文件: build.py 项目: BucOder/gitx
def package_app(app_path, image_path, image_name):
    package.package(app_path, image_path, image_name)
示例#42
0
文件: box.py 项目: ddurdle/KODI-Box
                    for q in re.finditer('\"name\"\:\"([^\"]+)\",' ,entry, re.DOTALL):
                        fileName= q.group(1)
                        break
#                    for q in re.finditer('\"url_for_page_link\"\:\"([^\"]+)\",' ,entry, re.DOTALL):
                    for q in re.finditer('\"url_for_page_link\"\:\"([^\"]+)\",' ,entry, re.DOTALL):
                        downloadURL = q.group(1)
                        #downloadURL = re.sub('\\', '', downloadURL)
                        #downloadURL = re.sub('\%20', '+', downloadURL)
                        break
                    for q in re.finditer('\"id\"\:([^\,]+),' ,entry, re.DOTALL):
                        fileID = q.group(1)
                        break

                    if contentType == 'audio':
                        media = package.package(file.file(fileID, fileName, fileName, self.AUDIO, '', ''),folder.folder('',''))
                    elif contentType == 'video':
                        media = package.package(file.file('f_'+str(fileID), fileName, fileName, self.VIDEO, '', ''),folder.folder('',''))
                    #media.setMediaURL(mediaurl.mediaurl(downloadURL, '','',''))
                    mediaFiles.append(media)

        for r in re.finditer('data\-downloadurl\=\"video\/[^\:]+\:([^\:]+)\:\/index\.php\?rm\=box_v2_download_file\&amp\;file_id\=([^\&]+)\&amp\;print_download_url\=1\"' ,response_data, re.DOTALL):
                fileName,fileID = r.groups()

                media = package.package(file.file(fileID, fileName, fileName, self.VIDEO, '', ''),folder.folder('',''))
                mediaFiles.append(media)
        for r in re.finditer('data\-downloadurl\=\"audio\/[^\:]+\:([^\:]+)\:\/index\.php\?rm\=box_v2_download_file\&amp\;file_id\=([^\&]+)\&amp\;print_download_url\=1\"' ,response_data, re.DOTALL):
                fileName,fileID = r.groups()

                media = package.package(file.file(fileID, fileName, fileName, self.AUDIO, '', ''),folder.folder('',''))
                mediaFiles.append(media)