Beispiel #1
0
def generate_movie(movie_name,
                   movie_dir,
                   movie_width,
                   movie_height,
                   movie_fps,
                   movie_frames='*.png',
                   movie_clean_frames=True):
    """
    function used by client code to generate a movie according to
    specified parameters; at this time multiprocessing
    version is used only for Linux OS
    """
    movie_clean_frames = nvl(movie_clean_frames, True)
    if _platform.find("linux") >= 0:
        return __generate_multiprocessing_movie__(movie_name, movie_dir,
                                                  movie_width, movie_height,
                                                  movie_fps, movie_frames,
                                                  movie_clean_frames)
    elif _platform == "darwin":
        # OS X
        raise Exception('Not implemented yet !')
    else:
        # windows family
        movie_specification = MovieSpecification(movie_name, movie_dir,
                                                 movie_width, movie_height,
                                                 movie_fps, None, None,
                                                 movie_frames)
        return __generate_movie__(movie_specification)
Beispiel #2
0
    def __init__(self, wizard, parent):
        super(Initial, self).__init__(wizard, parent)

        for radio in self.load_connection.get_group():
            if radio.name == 'start_new' and platform.find('win') >= 0:
                radio.hide()
            else:
                radio.connect('activate', self._on_radio__activiate)
Beispiel #3
0
    def __init__(self, wizard, parent):
        super(Initial, self).__init__(wizard, parent)

        for radio in self.load_connection.get_group():
            if radio.name == 'start_new' and platform.find('win') >= 0:
                radio.hide()
            else:
                radio.connect('activate', self._on_radio__activiate)
Beispiel #4
0
 def copyPDF(self, src):
     cwd = os.getcwd()
     cwd = cwd[0:cwd.find("/BeisChayim")] + "/BeisChayim"
     pic = src[src.rfind("/"):]
     target = cwd + "/" + pdfDir + "/" + pic
     if platform.find('win') > -1:
         cwd = cwd[0:cwd.find("\\BeisChayim")] + "\\BeisChayim"
         target = cwd + "\\" + picDir + "\\" + pic
     print("Copying: " + src + " to: " + cwd + "\\" + picDir + "\\" + pic)
     copyfile(src, target)
Beispiel #5
0
    def __init__(self, var, data):
        self.var = var
        if self.var == 1:
            self.buildData()
        if self.var == 2:
            self.data = data

        self.filename = "/BCConfig"
        if platform.find('win') > -1:
            self.filename = "\\BCConfig"
Beispiel #6
0
    def replaceOldData(self, fileString):
        cwd = os.getcwd()
        cwd = cwd[0:cwd.find("/BeisChayim")] + "/BeisChayim"

        db01 = cwd + "/" + jsDir + "/db01.js"
        if platform.find('win') > -1:
            db01 = cwd + "\\" + jsDir + "\db01.js"

        fd = open(db01, "w+")
        fd.write(fileString)
        fd.close()
Beispiel #7
0
def open_browser():
    chrome_options = ChOptions()
    chrome_options.add_argument('--headless')
    if platform.find('win') >= 0:
        chrome_driver = os.path.join(os.getcwd(), "chromedriver.exe")
    else:
        chrome_driver = os.path.join(os.getcwd(), "chromedriver")
        os.chmod(chrome_driver, 0o755)
    drv = webdriver.Chrome(chrome_options=chrome_options,
                           executable_path=chrome_driver)
    return drv
Beispiel #8
0
    def writeNewConfig(self, s):
        cwd = os.getcwd()
        cwd = cwd[0:cwd.find("/BeisChayim")] + "/BeisChayim"
        if platform.find('win') > -1:
            cwd = cwd[0:cwd.find("\\BeisChayim")] + "\\BeisChayim"
        #print("writing config to: " + installDir + self.filename)
        configFile = cwd + configDir + self.filename

        #fd = open(cwd + "\\" + installDir + self.filename, "w+")
        fd = open(configFile, "w+")
        fd.write(s)
        fd.close()
Beispiel #9
0
def fingerprint_file(path, maxlength=MAX_AUDIO_LENGTH):
    """Fingerprint a file by calling the fpcalc application."""
    if platform.find("win") != -1:
        fpcalc = 'fpcalc\\fpcalc.exe'
    elif platform.find("linux") != -1:
        fpcalc = 'fpcalc/fpcalc' #use unix binary for linux
    command = [fpcalc, "-length", str(maxlength), path]
    try:
        with open(os.devnull, 'wb') as devnull:
            proc = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=devnull)
            output, _ = proc.communicate()
    except OSError as exc:
        if exc.errno == errno.ENOENT:
            raise NoBackendError("fpcalc not found")
        else:
            raise FingerprintGenerationError("fpcalc invocation failed: %s" % str(exc))
    except UnicodeEncodeError:
        raise FingerprintGenerationError("argument encoding failed")
    retcode = proc.poll()
    if retcode:
        print("fpcalc exited with status %i" % retcode)

    duration = fp = None
    for line in output.splitlines():
        try:
            parts = line.split(b'=', 1)
        except ValueError:
            raise FingerprintGenerationError("malformed fpcalc output")
        if parts[0] == b'DURATION':
            try:
                duration = float(parts[1])
            except ValueError:
                raise FingerprintGenerationError("fpcalc duration not numeric")
        elif parts[0] == b'FINGERPRINT':
            fp = parts[1]

    if duration is None or fp is None:
        print("Skipping {0}...".format(path))
        return None
    return duration, fp
Beispiel #10
0
    def writeStagingData(self, fileString):
        cwd = os.getcwd()
        cwd = cwd[0:cwd.find("/BeisChayim")] + "/BeisChayim"
        filename = cwd + "/" + dataStaging + "/db01.js"
        if platform.find('win') > -1:
            cwd = cwd[0:cwd.find("\\BeisChayim")] + "\\BeisChayim"
            filename = cwd + "\\" + dataStaging + "\\db01.js"

        fd = open(filename, "w+")
        fd.write(fileString)
        fd.close()
        # in case user closes and reopens the file!
        self.replaceOldData(fileString)
Beispiel #11
0
    def buildData(self):
        lineCount = 0
        cwd = os.getcwd()
        cwd = cwd[0:cwd.find("/BeisChayim")] + "/BeisChayim"
        if platform.find('win') > -1:
            cwd = cwd[0:cwd.find("\\BeisChayim")] + "\\BeisChayim"

        JString = '{ "ENTRIES": ['
        # print(cwd)
        # print(jsDir)
        db01 = cwd + "/" + jsDir + "/db01.js"
        if platform.find('win') > -1:
            db01 = cwd + "\\" + jsDir + "\db01.js"

        with open(db01, "r") as JSONfile:
            for line in JSONfile:
                if lineCount > 0:
                    JString += line.replace("'",
                                            "").replace("+",
                                                        "").replace(";", "")
                lineCount += 1

        self.data = json.loads(JString)
Beispiel #12
0
    def setUp(self):
        path = os.path.join(os.path.dirname(__file__))
        filename = 'chromedriver.exe' if platform.find(
            'win') > -1 else 'chromedriver'
        driver_path = os.path.join(path, filename)
        print('Chrome driver location: %s' % driver_path)
        '''Для запуска виртульного дисплея раскомментите строки'''
        #self.display = Display(visible=0, size=(2500, 2000))
        #self.display.start()

        self.driver = webdriver.Chrome(driver_path)
        self.verificationErrors = []
        self.base_url = "https://www.yandex.ru/"
        self.driver.get(self.base_url)
Beispiel #13
0
    def download_drivder(self):
        url_prefix = 'https://chromedriver.storage.googleapis.com/'
        url = '/chromedriver_linux64.zip'
        if ~platform.find('darwin'):
            url = '/chromedriver_mac64.zip'
        if self.is_win():
            url = '/chromedriver_win32.zip'

        path = storage('driver.zip')

        with open(path, 'wb') as driver:
            driver.write(get(url_prefix + self.driver_version + url).content)
            driver.close()
        with ZipFile(path) as file:
            file.extractall(dirname(self._driver_path()))
Beispiel #14
0
    def getConfig(self):
        cwd = os.getcwd()
        cwd = cwd[0:cwd.find("/BeisChayim")] + "/BeisChayim"

        if platform.find('win') > -1:
            cwd = cwd[0:cwd.find("\\BeisChayim")] + "\\BeisChayim"
        configFile = cwd + configDir + self.filename
        #print(configFile)
        #print("##################################")
        configData = dict()
        #with open(cwd + "\\" + configDir + self.filename) as fl:
        with open(configFile) as fl:
            for line in fl:
                varString = line[line.rfind("{") + 1:line.find("}")]
                varData = varString.split(",")
                for x in varData:
                    x = x.replace('\"', '')
                    y = x.split(":")
                    configData[y[0]] = y[1]
        return configData
Beispiel #15
0
def generate_movie(movie_name, movie_dir,
                   movie_width, movie_height,
                   movie_fps, movie_frames='*.png',
                   movie_clean_frames=True):
    """
    function used by client code to generate a movie according to
    specified parameters; at this time multiprocessing
    version is used only for Linux OS
    """
    movie_clean_frames = nvl(movie_clean_frames, True)
    if _platform.find("linux") >= 0:
        return __generate_multiprocessing_movie__(movie_name, movie_dir,
                                              movie_width, movie_height,
                                              movie_fps, movie_frames,
                                              movie_clean_frames)
    elif _platform == "darwin":
        # OS X
        raise Exception('Not implemented yet !')
    else:
        # windows family
        movie_specification = MovieSpecification(movie_name, movie_dir,
                            movie_width, movie_height, movie_fps, None,
                            None, movie_frames)
        return __generate_movie__(movie_specification)
Beispiel #16
0
 def __init__(self):
     if platform.find("linux")> -1:
         self.dsp = ossOpen('/dev/dsp','w')
Beispiel #17
0
 def is_win():
     return ~platform.find('win32')
Beispiel #18
0
def isLinux():
	if platform.find('linux') != -1:
		return True
	return False
Beispiel #19
0
    def read_data_samples(self):
        # Read file_list.txt file to get all meta
        with codecs.open(self.file_list, 'r', 'utf8') as markup_file:
            # read all data
            progresser = tqdm(iterable=range(0, self.dataset_size),
                              desc='AVDB meta parsing',
                              total=self.dataset_size,
                              unit='images')

            prev_idx = None
            data_samples = []
            num_persons = 0
            class_num = 0
            label_per_clip = []
            valence_per_clip = []
            arousal_per_clip = []
            if platform.find('linux') >= 0:
                is_linux = True
            if platform.find('win') >= 0:
                is_linux = False
            else:
                raise Exception("Unexpected operation system")
            for i in progresser:
                if is_linux:
                    datas = markup_file.readline().replace(
                        '\\', ' / ').strip().split()
                else:
                    datas = markup_file.readline().strip().split()
                im_path = os.path.join(self.dataset_root, datas[0])
                wav_path = None
                valence = float(datas[1])
                arousal = float(datas[2])
                text_labels = ''

                if len(datas) == 140:
                    label = int(datas[3])
                    if 'Ryerson' in im_path:
                        if label == 1:
                            continue
                        text_labels = [
                            'neutral', 'calm', 'happy', 'sad', 'angry',
                            'fearful', 'disgust', 'surprised'
                        ][label - 1]
                        wav_path = os.path.dirname(
                            im_path.replace('Video', 'Audio')).replace(
                                '.mp4', '.wav').replace('/01', '/03')
                    elif 'OMGEmotionChallenge' in im_path:
                        wav_path = os.path.dirname(
                            im_path.replace('frames', 'wave')) + '.wav'
                        text_labels = [
                            'anger', 'disgust', 'fear', 'happy', 'neutral',
                            'sad', 'surprise'
                        ][label]
                    landmarks = [[
                        float(datas[2 * k + 4]),
                        float(datas[2 * k + 5])
                    ] for k in range(68)]
                    idx = os.path.dirname(datas[0])
                else:
                    label = int((valence + 10) * (arousal + 10))
                    landmarks = [[
                        float(datas[2 * k + 3]),
                        float(datas[2 * k + 4])
                    ] for k in range(68)]
                    idx = os.path.dirname(datas[0])

                class_num = max(class_num, int(label))

                if prev_idx is None:
                    prev_idx = idx
                if prev_idx != idx:
                    if self.ungroup:
                        for ds in data_samples:
                            self.data.append(ds)
                    else:
                        self.data.append(
                            DataGroup(folder_rel_path=os.path.dirname(
                                data_samples[0].img_rel_path),
                                      wav_rel_path=wav_path,
                                      data_samples=data_samples,
                                      idx=len(self.data)))
                        self.data[-1].labels = int(np.median(label_per_clip))
                        self.data[-1].valence = np.mean(valence_per_clip)
                        self.data[-1].arousal = np.mean(arousal_per_clip)
                        self.data[-1].text_labels = data_samples[0].text_labels
                        label_per_clip, valence_per_clip, arousal_per_clip = [], [], []
                    data_samples = []
                    prev_idx = idx
                    num_persons += 1

                if self.max_num_samples == 0 or len(
                        data_samples) < self.max_num_samples:
                    data_samples.append(
                        DataSample(img_rel_path=im_path,
                                   wav_rel_path=wav_path,
                                   labels=label,
                                   valence=valence,
                                   arousal=arousal,
                                   landmarks=landmarks))
                    data_samples[-1].idx = idx
                    data_samples[-1].text_labels = text_labels
                    if self.load_image:
                        data_samples[-1].image = cv2.imread(im_path)
                    label_per_clip.append(label)
                    valence_per_clip.append(valence)
                    arousal_per_clip.append(arousal)

                if self.max_num_clips > 0 and num_persons == self.max_num_clips:
                    break

            if len(data_samples) > 0:
                if self.ungroup:
                    for ds in data_samples:
                        self.data.append(ds)
                else:
                    self.data.append(
                        DataGroup(folder_rel_path=os.path.dirname(
                            data_samples[0].img_rel_path),
                                  wav_rel_path=wav_path,
                                  data_samples=data_samples,
                                  idx=len(self.data)))
                    self.data[-1].labels = int(np.median(label_per_clip))
                    self.data[-1].valence = np.mean(valence_per_clip)
                    self.data[-1].arousal = np.mean(arousal_per_clip)
                    self.data[-1].text_labels = data_samples[0].text_labels
                num_persons += 1

            self.class_num = class_num
            self.data.sort(key=lambda x: x.idx)

            if self.normalize:
                if self.ungroup:
                    max_valence = max(
                        [abs(sample.valence) for sample in self.data])
                    max_arousal = max(
                        [abs(sample.arousal) for sample in self.data])
                    for sample in self.data:
                        sample.valence /= max_valence
                        sample.arousal /= max_arousal
                else:
                    max_valence = max([
                        abs(sample.valence) for clip in self.data
                        for sample in clip.data_samples
                    ])
                    max_arousal = max([
                        abs(sample.arousal) for clip in self.data
                        for sample in clip.data_samples
                    ])
                    for clip in self.data:
                        clip.valence /= max_valence
                        clip.arousal /= max_arousal
                        for sample in clip.data_samples:
                            sample.valence /= max_valence
                            sample.arousal /= max_arousal
Beispiel #20
0
def main():

    global options

    # parse the command line

    thisScriptName = os.path.basename(__file__)
    usage = "usage: " + thisScriptName + " [options]"
    homeDir = os.environ['HOME']

    parser = OptionParser(usage)

    parser.add_option('--debug',
                      dest='debug',
                      default=True,
                      action="store_true",
                      help='Set debugging on')
    parser.add_option('--verbose',
                      dest='verbose',
                      default=False,
                      action="store_true",
                      help='Set verbose debugging on')
    parser.add_option(
        '--docker_image',
        dest='docker_image',
        default='nsflrose/lrose-cidd',
        help='Set the docker image to run. Should be in DockerHub.')
    parser.add_option(
        '--params',
        dest='params',
        default='',
        help=
        "Set params file name. For example: 'CIDD.pecan'. In this case the URL would be 'http://front.eol.ucar.edu/displayParams/CIDD.pecan'. i.e. the param file name will be appended to the URL. If the --params option is not used, then the params_url will be used instead."
    )
    parser.add_option(
        '--params_url',
        dest='params_url',
        default='http://front.eol.ucar.edu/displayParams/CIDD.pecan',
        help=
        'Set the full URL for CIDD params file. This activates if the --params option is not used.'
    )
    parser.add_option(
        '--params_local',
        dest='params_local',
        default='',
        help=
        "Set path of local params file. This will be provided to CIDD running in the container."
    )

    (options, args) = parser.parse_args()

    # check OS - is this a mac?

    global isOsx
    isOsx = False
    if (platform.find("darwin") == 0):
        isOsx = True

    # set DISPLAY string

    if (isOsx):

        # APPLE OSX

        ipAddr = "localhost"
        ifconfig = subprocess.check_output(['ifconfig']).decode('ascii')

        for line in ifconfig.split("\n"):
            if ((line.find("127.0.0.1") < 0) and line.find("inet ") >= 0):
                ipaddr = line.split()[1]
        print("ipAddr: ", ipAddr, file=sys.stderr)

        displayNum = ":0"
        ps = subprocess.check_output(['ps', '-e']).decode('ascii')
        for line in ps.split("\n"):
            if ((line.find("xinit") < 0) and (line.find("Xquartz") >= 0)
                    and (line.find("listen") >= 0)):
                displayNum = line.split()[4]

        displayStr = "-e DISPLAY=" + ipaddr + displayNum

    else:

        # LINUX

        displayStr = "-e DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix"

    # debug

    if (options.debug):
        print("Running %s:" % thisScriptName, file=sys.stderr)
        print("  docker image: ", options.docker_image, file=sys.stderr)
        print("  CIDD params URL: ", options.params_url, file=sys.stderr)
        if (isOsx):
            print("  OS: this is a mac", file=sys.stderr)
        else:
            print("  OS: this is NOT a mac", file=sys.stderr)
        print("  displayStr: ", displayStr, file=sys.stderr)

    # for local params make copy into /tmp

    paramsLocal = False
    localName = os.path.basename(options.params_local)
    tmpDir = "/tmp/cidd_params"
    if (len(options.params_local) > 0):
        paramsLocal = True
        try:
            os.makedirs(tmpDir)
        except:
            if (options.verbose):
                print("Info exists: ", tmpDir, file=sys.stderr)
        shellCmd("rsync -av " + options.params_local + " " + tmpDir)

    # set up call for running docker

    cmd = "docker run -v $HOME/.Xauthority:/root/.Xauthority "
    cmd += "-v /tmp/cidd_images:/root/images "
    if (paramsLocal):
        cmd += "-v /tmp/cidd_params:/root/params "
    cmd += displayStr + " "
    cmd += options.docker_image + " "
    cmd += "/usr/local/cidd/bin/CIDD -font fixed -p "
    if (paramsLocal):
        cmd += "/root/params/" + localName
    elif (len(options.params) > 0):
        cmd += "http://front.eol.ucar.edu/displayParams/" + options.params
    else:
        cmd += options.params_url
    if (options.verbose):
        cmd += " -v 2"

    # run the command

    shellCmd(cmd)

    # exit

    sys.exit(0)
Beispiel #21
0
#!/usr/bin/env python3
# Coded by : A_Asaker

import os
from sys import platform

#Get The Platform To Determine Either Using Curses Library Or Not
#pf=platform -not Power Factor- :D
pf = 'windows' if platform.find(
    'win') != -1 and platform != 'darwin' else 'unix'

players = ['X', 'O']
n = 3
role = 0
end = 0
score = {'X': 0, 'O': 0}
tie = 0

#Use Curses Library In Case Of Linux Or Mac
if pf == 'unix':
    import curses
    stdscr = curses.initscr()
    curses.start_color()
    curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK)
    curses.cbreak()
    curses.echo()
    stdscr.keypad(1)


#Edited Print Function To Support Cross-Platform Usage
def print_crs(string, attr=None, x=None, y=None):
Beispiel #22
0
def main():
    world = World()
    world.load_game(filename='default_game.yaml')
    p = world.player
    show_status_on_screen = True

    if platform.find('linux') != -1:
        cls_command = 'clear'
    elif platform.find('win') != -1:
        cls_command = 'cls'
    elif platform.find('darwin') != -1:
        cls_command = 'clear'
    else:
        print('Unknown OS. cls will not work!')
        cls_command = False  # type: ignore

    def cls() -> None:
        if cls_command: system(cls_command)

    commands = {
        'quit commands': ['q', 'quit', 'exit'],
        'help commands': ['h', 'help'],
        'move commands': ['m', 'mo', 'move'],
        'character commands': ['c', 'char', 'character'],
        'inventory commands': ['i', 'inv', 'inventory'],
        'look commands': ['l', 'look'],
        'equip commands': ['eq', 'equip'],
        'unequip commands': ['un', 'unequip'],
        'pickup commands': ['pi', 'pickup'],
        'drop commands': ['dr', 'drop'],
        'toggle status': ['st'],
    }

    cls()
    while True:
        if show_status_on_screen:
            #cls()
            p.look()
            p.show_inventory()
            p.show_wearing()

        command_line = input(': ')
        if len(command_line) > 0:
            command = command_line.lower().split()[0]
            if command in commands['quit commands']:
                break
            elif command in commands['help commands']:
                cls()
                for c in commands:
                    print(f'{c}: {commands[c]}')
            elif command in commands['move commands']:
                cls()
                p.move_dialog()
            elif command in commands['character commands']:
                cls()
                if not show_status_on_screen: p.show_wearing()
            elif command in commands['inventory commands']:
                cls()
                if not show_status_on_screen: p.show_inventory()
            elif command in commands['look commands']:
                cls()
                if not show_status_on_screen: p.look()
            elif command in commands['equip commands']:
                cls()
                p.equip_dialog()
            elif command in commands['unequip commands']:
                cls()
                p.unequip_dialog()
            elif command in commands['pickup commands']:
                cls()
                p.pickup_dialog()
            elif command in commands['drop commands']:
                cls()
                p.drop_dialog()
            elif command in commands['toggle status']:
                cls()
                if show_status_on_screen:
                    show_status_on_screen = False
                else:
                    show_status_on_screen = True
            else:
                cls()
                print('')
                print('Unknown command')
                print('')
    def __init__(self, config, stage_type, ar_globals):
        """The constructor"""

        self._prefix = 'VFSImage Backend: '

        ### Init PGSQL Backend
        BackendPGSQL.__init__(self, config, 'archive', ar_globals, self._prefix)
        # Avoid any chance to call uneeded methods
        self.process_archive = None
        self.parse_recipients = None

        self.config = config
        self.type = stage_type

        if self.type != 'storage':
            raise StorageTypeNotSupported, self.type

        self.LOG = ar_globals['LOG']
        self.user = ar_globals['runas']

        if platform.find('linux') == -1:
            raise VFSError, 'This backend only works on Linux'

        error = None
        try:
            self.imagebase= config.get(self.type, 'imagebase')
            self.mountpoint = config.get(self.type, 'mountpoint')
            self.label = config.get(self.type, 'label')
            self.archiverdir = config.get(self.type, 'archiverdir')
            self.imagesize = config.getint(self.type, 'imagesize')
        except:
            t, val, tb = exc_info()
            del t, tb
            error = str(val)

        if error is not None:
            self.LOG(E_ERR, self._prefix + 'Bad config file: %s' % error)
            raise BadConfig

        self.image = self.imagebase + '.img'
        try:
            self.compression = config.get(self.type, 'compression')
        except:
            self.compression = None

        error = None
        if self.compression is not None:
            try:
                compressor, ratio = self.compression.split(':')
                ratio = int(ratio)
                if ratio < 0 or ratio > 9:
                    error = 'Invalid compression ratio'
                elif not compressors.has_key(compressor.lower()):
                    error = 'Compression type not supported'
                self.compression = (compressor, ratio)
            except:
                error = 'Unparsable compression entry in config file'

        if error is not None:
            self.LOG(E_ERR, self._prefix + 'Invalid compression option: %s' % error)
            raise BadConfig, 'Invalid compression option'

        if not access(self.mountpoint, F_OK | R_OK | W_OK):
            self.LOG(E_ERR, self._prefix + 'Mount point is not accessible: %s' % self.mountpoint)
            raise VFSError, 'Mount point is not accessible'

        if self.isMounted():
            self.LOG(E_ERR, self._prefix + 'Image already mounted')
            if not self.umount():
                raise VFSError, 'Cannot umount image'

        isPresent = True
        try:
            stat(self.image)
        except:
            isPresent = False

        if isPresent and not self.initImage():
            raise VFSError, 'Cannot init Image'
        else:
            self.LOG(E_ALWAYS, self._prefix + 'Image init postponed')


        self.LOG(E_ALWAYS, self._prefix + '(%s) at %s' % (self.type, self.image))
def getOsType():

    global osType, osVersion

    # Mac OSX?

    if (platform == "darwin"):
        osType = "OSX"
        osVersion = 10
        return

    # not linux?

    if (platform.find("linux") < 0):
        osType = "unknown"
        osVersion = 0
        return

    # Centos 6?

    if (os.path.isfile("/etc/redhat-release")):
        rhrelease_file = open("/etc/redhat-release", "rt")
        lines = rhrelease_file.readlines()
        rhrelease_file.close()
        for line in lines:
            if (line.find("CentOS release 6") == 0):
                osType = "centos"
                osVersion = 6
                return

    # get os info from /etc/os-release file

    _file = open(options.osFile, "rt")
    lines = _file.readlines()
    _file.close()

    osType = "unknown"
    for line in lines:

        line.strip()

        if (line.find("NAME") == 0):
            nameline = line.lower()
            if (nameline.find("centos") >= 0):
                osType = "centos"
            elif (nameline.find("fedora") >= 0):
                osType = "fedora"
            elif (nameline.find("debian") >= 0):
                osType = "debian"
            elif (nameline.find("ubuntu") >= 0):
                osType = "ubuntu"
            elif (nameline.find("suse") >= 0):
                osType = "suse"
            elif (nameline.find("oracle") >= 0):
                osType = "oracle"

        if (line.find("VERSION_ID") == 0):
            lineParts = line.split('=')
            print("  lineParts: ", lineParts, file=sys.stderr)
            if (lineParts[1].find('"') >= 0):
                subParts = lineParts[1].split('"')
                print("  subParts: ", subParts, file=sys.stderr)
                osVersion = float(subParts[1])
            else:
                osVersion = float(lineParts[1])

            return
Beispiel #25
0
import os

src_dir = f"src{os.sep}libmem-py"
libs = []
readme = ""

with open("README.md", "r") as f:
    readme = f.read()
    f.close()

if platform == "win32":
    libs.append("user32")
    libs.append("psapi")
elif platform.startswith("linux"):
    libs.append("dl")
elif platform.find("bsd") != -1:
    libs.append("dl")
    libs.append("kvm")
    libs.append("procstat")
    libs.append("elf")

libmem = Extension(
    name="libmem",
    include_dirs=[src_dir],
    sources=[f"{src_dir}{os.sep}libmem-py.c", f"{src_dir}{os.sep}libmem.c"],
    libraries=libs)

setup(name="libmem",
      version="0.1.3",
      description="Process and Memory Hacking Library",
      long_description=readme,
def main():

    global options

    # get current dir

    thisDir = os.getcwd()

    # parse the command line

    thisScriptName = os.path.basename(__file__)
    usage = "usage: " + thisScriptName + " [options]"
    homeDir = os.environ['HOME']

    parser = OptionParser(usage)

    parser.add_option('--debug',
                      dest='debug',
                      default=True,
                      action="store_true",
                      help='Set debugging on')
    parser.add_option('--verbose',
                      dest='verbose',
                      default=False,
                      action="store_true",
                      help='Set verbose debugging on')
    parser.add_option(
        '--dir',
        dest='dir',
        default=thisDir,
        help=
        'Directory containing the DORADE data. Default is the current directory.'
    )
    parser.add_option(
        '--docker_image',
        dest='docker_image',
        default='nsflrose/lrose-solo3',
        help=
        'Set the docker image to run. Should be in DockerHub. Default is "nsflrose/lrose-solo3"'
    )

    (options, args) = parser.parse_args()

    # check OS - is this a mac?

    global isOsx
    isOsx = False
    if (platform.find("darwin") == 0):
        isOsx = True

    # set DISPLAY string

    if (isOsx):

        # APPLE OSX

        ipAddr = "localhost"
        ifconfig = subprocess.check_output(['ifconfig']).decode()
        print("ifconfig: ", ifconfig, file=sys.stderr)
        for line in ifconfig.split("\n"):
            if ((line.find("127.0.0.1") < 0) and line.find("inet ") >= 0):
                ipaddr = line.split()[1]
        print("ipAddr: ", ipAddr, file=sys.stderr)

        displayNum = ":0"
        ps = subprocess.check_output(['ps', '-e']).decode()
        for line in ps.split("\n"):
            if ((line.find("xinit") < 0) and (line.find("Xquartz") >= 0)
                    and (line.find("listen") >= 0)):
                displayNum = line.split()[4]

        displayStr = "-e DISPLAY=" + ipaddr + displayNum

    else:

        # LINUX

        displayStr = "-e DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix"

    # debug

    dataDir = options.dir
    if (dataDir.find('.') >= 0):
        dataDir = thisDir

    if (options.debug):
        print("Running %s:" % thisScriptName, file=sys.stderr)
        print("  docker image: ", options.docker_image, file=sys.stderr)
        if (isOsx):
            print("  OS: this is a mac", file=sys.stderr)
        else:
            print("  OS: this is NOT a mac", file=sys.stderr)
        print("  displayStr: ", displayStr, file=sys.stderr)
        print("  dataDir: ", dataDir, file=sys.stderr)

    # get the sweep files in a list

    sweepList = " "
    allFiles = os.listdir(dataDir)
    for file in allFiles:
        if (file.find("swp.") == 0):
            sweepList = sweepList + " ./" + file
    print("  sweepList: ", sweepList, file=sys.stderr)

    # set up call for running docker

    cmd = "docker run -v $HOME/.Xauthority:/root/.Xauthority "
    cmd += "-v " + dataDir + ":/data "
    cmd += displayStr + " "
    cmd += options.docker_image + " "
    bashcmd = "cd /data; /usr/local/bin/solo3 -f " + sweepList
    cmd += 'bash -c \"' + bashcmd + '\"'

    # run the command

    shellCmd(cmd)

    # exit

    sys.exit(0)
Beispiel #27
0
 def close(self):
     if platform.find("linux") > -1:
         self.dsp.close()
Beispiel #28
0
def isLinux():
    if platform.find('linux') != -1:
        return True
    return False