Exemplo n.º 1
1
    def _reboot_buildout(self):
        # rerun bootstrap to recreate bin/buildout with
        # the virtualenf python as the interpreter
        buildout_dir = self.buildout["buildout"]["directory"]
        bootstrap_path = buildout_dir + "/bootstrap.py"
        cmd_list = [self.python_cmd]
        if os.path.exists(bootstrap_path):
            cmd_list.append(bootstrap_path)
            # cmd_list.extend(self.buildout_args)
        else:
            cmd_list.append(self.buildout_path)
            cmd_list.extend(self.buildout_args)
            cmd_list.append("bootstrap")
        subprocess.call(cmd_list)

        # rerun buildout if it isn't running under the
        # virtualenv interpreter
        self.logger.info(sys.executable)
        if sys.executable != self.python_cmd:
            cmd_list = [self.buildout_path]
            cmd_list.extend(self.buildout_args)
            self.logger.info("Rebooting buildout")
            subprocess.call(cmd_list)

            sys.exit()

        pass
Exemplo n.º 2
0
    def update_map(self):
        """Update map images (Tilemill)
        """
        print "\n- Aggiorna cartine Tilemill"

        projectFileName = os.path.join(self.TILEMILLDIR, "project.mml")
        inFile = open(projectFileName)
        data = json.load(inFile)
        inFile.close()
        #print_layers_statuses(data)

        #create map img background
        imgFile = os.path.join("html", "img", "tilemill", "sfondo_errori.png")
        self.export_tilemill_img("sfondo_errori", imgFile)

        #create map img with all errors
        print "Total"
        self.enable_all_layers(data)
        self.save_tilemill_project(projectFileName, data)
        self.export_tilemill_img("tags_sbagliati", imgFile)
        #add a label over tilemill img
        call("convert %s -quality 100 -fill white -undercolor '#00000080' -gravity NorthWest -pointsize 24 -annotate +0+3 ' Tutti ' %s" % (imgFile, imgFile), shell=True)

        #create map img of each check
        for check in self.checks.values():
            if check.type != "tags":
                continue
            print check.name
            self.toggle_layers(check.name, data)
            self.save_tilemill_project(projectFileName, data)
            imgFile = os.path.join("html", "img", "tilemill", "%s.png" % check.name)
            self.export_tilemill_img("tags_sbagliati", imgFile)
            #add a label with the check name over tilemill image
            call("convert %s -quality 100 -fill white -undercolor '#00000080' -gravity NorthWest -pointsize 24 -annotate +0+3 ' %s ' %s" % (imgFile, check.title, imgFile), shell=True)
Exemplo n.º 3
0
def loop():
	time.sleep(1)
	
	print 'Check if server has stuff, and if so send to Arduino.'
	# When the Server **sends** data:
	# Write to the Arduino's Serial port.
	# Currently, timeout = 1
	data = get_from_server()
	if len(data) > 0:
		print "Got data: %s" % data
		try:
			print 'sending to arduino light?'
			shelf_num = int(data)
			light_shelf(shelf_num)
			time.sleep(5)
			print 'done sleeping'
		except:
			print 'oops not a number!'

	# When the Arduino **sends** data:
	# POST to the Server.
	print 'listening to arduino'
	tags_data = get_tags_from_arduino()
	print tags_data
	# Parse tags
	if tags_data is not None:
		tag_scan_pairs = []
		print tags_data
		for tag in tags_data.split('|'):
			if len(tag) == 0:
				continue
			tmp = tag.split(':')
			print tmp
			call(['afplay','beep-2.wav'])
			tag_to_server(int(tmp[0]), int(tmp[1]))
Exemplo n.º 4
0
def make_directories():
    input_base = os.path.dirname(input_root)
    command = ("find {} -type d | sed -n 's|{}||p' | "
               "parallel --gnu -j 4 mkdir -p {}/{{}}").format(input_root,
                                                              input_base,
                                                              output_root)
    subprocess.call(command, shell=True)
Exemplo n.º 5
0
 def stress(self, stress_options):
     stress = common.get_stress_bin(self.get_cassandra_dir())
     args = [ stress ] + stress_options
     try:
         subprocess.call(args)
     except KeyboardInterrupt:
         pass
Exemplo n.º 6
0
def dispatch_to_slurm(commands):
    scripts = {}

    for job_name, command in commands.iteritems():
        script = submit(command, job_name=job_name, time="0",
                        memory="{}G".format(maxmem), backend="slurm",
                        shell_script="#!/usr/bin/env bash")
        script += " --partition={}".format(partition)
        script += " --ntasks=1"
        script += " --cpus-per-task={}".format(maxcpu)
        script += " --mail-type=END,FAIL"
        script += " --mail-user={}".format(email)
        scripts[job_name] = script

    scheduled_jobs = set(queued_or_running_jobs())

    for job_name, script in scripts.iteritems():
        if job_name not in scheduled_jobs:
            if verbose:
                print("{}".format(script), file=sys.stdout)

            if not dry_run:
                subprocess.call(script, shell=True)
        else:
            print("{} already running, skipping".format(job_name),
                  file=sys.stderr)
Exemplo n.º 7
0
def bootstrap_file(task, semaphore):
    ct = threading.current_thread()
    semaphore.acquire()
    print("Running \"%s\"" % " ".join(task["command"]))
    with open(task["output"], "w") as log_fp:
        subp.call(task["command"], stdout=log_fp, stderr=subp.STDOUT)
    semaphore.release()
Exemplo n.º 8
0
def StartTCPServer():
	userAddress = ""
	firstConn = 1
	TCP_IP = '0.0.0.0'
	TCP_PORT = 1337
	while(1):
		print("Starting TCP Server on {0}:{1}".format(TCP_IP,TCP_PORT))
		print("Configuring connection")
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
		s.bind((TCP_IP,TCP_PORT))
		print("Waiting for connection")
		try:
			s.listen(1)
			conn,addr = s.accept()
			if firstConn == 1:
				userAddress = str(addr[0])
				firstConn = 0
			print("Connected to: " + str(addr[0]) +":"+ str(addr[1]))
			while 1:
				if userAddress == str(addr[0]):
					data = conn.recv(BUFFER_SIZE)
					if not data: break
					data = data.decode()
					print("Data received: "+data)
					if data[:3] == Client.INIT_HEY:
						print("Initiallizing connection")
						conn.send((Server.INIT_OK+"\n").encode())
						print("Connection initiallized")
					elif data[:3] == Client.KTHXBYE:
						conn.send(Server.CLOSE.encode())
						clean()
					elif data[:3] == Client.CUSTOM_MOVE:
						data = str(data)
						formattedData = data.split(",")
						direction = formattedData[1]
						left = formattedData[2]
						right = formattedData[3]
						response = "URRAY"
						response = customSpeed(direction,left,right)
						print(direction+","+left+","+right)
						conn.send((str(response)+"\n").encode())
					elif data[:3] == Client.SHUTDOWN:
						conn.send("Shutdown Received")
						call(["shutdown", "now"])
					elif data[:3] == Client.REBOOT:
						conn.send("Rebbot received")
						call(["reboot"])
					else:
						print("Command not understood: "+data)
				else:
					print("Somebody else was trying to connect!!")
			conn.send(Server.CLOSE.encode())
		except KeyboardInterrupt:
			print("Rage Quit")
		except:
			print("Error happened:",sys.exc_info())
		finally:
			s.close()
			clean()
Exemplo n.º 9
0
    def OnButton1Click(self):
        self.labelVariable.set( self.entryVariable.get()+" pocket" )
        #execfile("pocket_V1.py")
	#pocket_V1.main() # do whatever is in test1.py
        subprocess.call("./pocket_V1.py", shell=True)
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)
Exemplo n.º 10
0
def setup():
  import subprocess

  line_break()
  print("Installing python2.7...")
  subprocess.call(['brew', 'install', 'python'])

  line_break()
  print("Installing pip...")
  subprocess.call(['easy_install-2.7', 'pip'])
  # if you got permissions issues and bad install, use this
  # subprocess.call(['sudo', 'easy_install-2.7', 'pip'])

  line_break()
  print("Installing Fabric...")
  subprocess.call(['pip', 'install', 'fabric'])

  line_break()
  print("Installing YAML...")
  subprocess.call(['pip', 'install', 'PyYAML'])

  line_break()
  print("Installing terminal-notifier...")
  subprocess.call(['gem', 'install', 'terminal-notifier'])

  line_break()
  print("DONE!  You're good to go!")
Exemplo n.º 11
0
 def execute(self, ssh_options, args):
   master = self._get_master()
   if not master:
     sys.exit(1)
   subprocess.call("ssh %s root@%s '%s'" % (xstr(ssh_options),
                                            master.public_ip,
                                            " ".join(args)), shell=True)
Exemplo n.º 12
0
def share(filename):
    # TODO: Move this connection handling into a function in Kano Utils
    import subprocess

    if not is_internet():
        subprocess.call(['sudo', 'kano-settings', '4'])

    if not is_internet():
        return 'You have no internet'

    success, _ = login_using_token()
    if not success:
        os.system('kano-login 3')
        success, _ = login_using_token()
        if not success:
            return 'Cannot login'

    data = json.loads(request.data)
    filename, filepath = _save(data)
    success, msg = upload_share(filepath, filename, APP_NAME)

    if not success:
        return msg

    increment_app_state_variable_with_dialog(APP_NAME, 'shared', 1)

    return ''
Exemplo n.º 13
0
 def login(self, ssh_options):
   master = self._get_master()
   if not master:
     sys.exit(1)
   subprocess.call('ssh %s ubuntu@%s' % \
                   (xstr(ssh_options), master.public_ip),
                   shell=True)
Exemplo n.º 14
0
 def push(self, ssh_options, file):
   master = self._get_master()
   if not master:
     sys.exit(1)
   subprocess.call('scp %s -r %s ubuntu@%s:' % (xstr(ssh_options),
                                              file, master.public_ip),
                                              shell=True)
Exemplo n.º 15
0
 def create_profile_F(self):
     """Function to create the SSHTunnel Firefox profile
     All firefox instances must be closed
     (or they can be left open, but the function will killall firefox)        
     """
    
     
     subprocess.call(["killall", "firefox"]) #all firefox instance must be killed
     subprocess.check_call(["firefox","-CreateProfile","SSHTunnel"]) #Create a new Profile named SSHTunnel
   
     
     #Navigate to the profile folder:
     os.chdir('/home/'+ str(LOGNAME) +'/.mozilla/firefox/')
     list_of_items = os.listdir(os.getcwd())
     for folder in list_of_items:
         if 'SSHTunnel' in folder:
             os.chdir(folder)
             break
     else:
         raise Exception("Create new profile for firefox failed")
                     
     
     write_prefs_js()       
     
     self.launch_firefox_instance()
Exemplo n.º 16
0
    def do_lrun(self, argv):
        """Execute client-side shell command

        SYNOPSIS:
            lrun command [arg1 [arg2 [...] ] ]

        DESCRIPTION:
                Execute a shell command in your own operating system.
                This command works like the `exec` command in unix
                shells.
             
                NOTE: This core command shouldn't be confused with the
                `run` plugin, which does the same thing in the
                remotely exploited system.
             
        EXAMPLES:
            > lrun ls -la /
            > lrun htop
        """
        if len(argv) == 1:
            return self.interpret("help lrun")

        cmd = " ".join(argv[1:])

        if argv[1] != "exit":
            tmpfile = Path()
            postcmd = " ; pwd >'%s' 2>&1" % tmpfile
            subprocess.call(cmd + postcmd, shell=True)
            try:
                os.chdir(tmpfile.read())
            finally:
                del tmpfile
Exemplo n.º 17
0
def main():
    active = []

    for streamer in streamers:
        x = twitch.searchStreams(streamer)
        if x:
            for stream in x:
                if stream['channel']['name'] == streamer:
                    active.append(stream)

    count = 0
    for result in active:
        print("{0} -{1}: {2}".format(count,
                                     result['channel']['name'],
                                     result['channel']['url']))
        count = count + 1

    choice = -99
    if count > 0:
        choice = input("Please select a stream (-99 to exit): ")

    if int(choice) != -99:
        url = active[int(choice)]['channel']['url']
        command = "livestreamer --player mpv {0} high".format(url)
        subprocess.call(shlex.split(command))
    else:
        print("No active streams.\n")
Exemplo n.º 18
0
def hype(jobguid):
  workdir = 'workdirs/{}'.format(jobguid)


  spin0 = os.path.abspath('hype_static/fake_spin0.yoda'.format(workdir))
  spin2 = os.path.abspath('{}/inputs/fake_spin2.yoda'.format(workdir))
  
  env = jinja2.Environment(undefined=jinja2.StrictUndefined)

  hypetmplt = 'hype_static/Higgs_spin0_vs_2_diphoton_hepdata.tmplt'
 

  log.info("trying to render template")
  with open(hypetmplt) as hypeRunTemplate:
    basename = os.path.basename(hypetmplt)
    filledtemplate = '{}/{}'.format(workdir,basename.rsplit('.',1)[0]+'.hype')

    template = env.from_string(hypeRunTemplate.read())

    with open(filledtemplate,'w+') as output:
        log.info("writing template to {}".format(filledtemplate))
        output.write(template.render({'SPIN_0_YODA':spin0,'SPIN_2_YODA':spin2}))


  logfile = '{}/hype.logfile'.format(workdir)
  log.info("trying to run hype and print to logfile {}".format(logfile))
  with open(logfile,'w') as logfile:
    subprocess.call(['hype/bin/hype',os.path.abspath(filledtemplate)], stdout = logfile)

  log.info('hype done')

  return jobguid
Exemplo n.º 19
0
def main():
    f1 = TFile("/afs/cern.ch/user/m/muell149/workb/HLTONLINE/CMSSW_7_0_0_pre1/src/DQMOffline/Trigger/test/700pre1DQM.root")
    f2 = TFile("/afs/cern.ch/user/m/muell149/workb/HLTONLINE/CMSSW_7_0_0_pre1/src/DQMOffline/Trigger/test/700pre2DQM.root")
    r1="700pre1"
    r2="700pre2"
    savePlotDir="DQM_plots/"+r1+"_"+r2+"/"
    cmd = "mkdir "+savePlotDir
    subprocess.call(cmd,shell=True)
    
    path1="DQMData/Run 1/HLT/Run summary/GeneralHLTOffline"
    f1.cd(path1)
    dir = f1.Get(path1)
    nextkey = dir.GetListOfKeys()
      
    for key in nextkey:
        h1 = key.ReadObj()
        #print "h1 before=",type(h1)
        if isinstance(h1,TH1F):
            print h1.GetName()
            if h1 is not None:
                hist_name = h1.GetName()
                path = "DQMData/Run 1/HLT/Run summary/GeneralHLTOffline/"+hist_name
                h2 = f2.Get(path)
                if h2 is not None:
                    #print "h2=",h2.GetName()
                    #print type(h1), type(h2)
                    #break
                    plot(h1,h2,r1,r2,savePlotDir)
Exemplo n.º 20
0
def gen_moc():
  workDir = os.getcwd() + "/Gui"
  print workDir
  dirList = os.listdir(workDir)

  for files in 	dirList:
    if files.endswith(".h"):
      print files
      outp = "moc_" + files[:-2] + ".cpp"
      print outp
      affected = "./Gui/" + files
      call(["moc", affected, "-o", outp])
      #os.rename(outp, "./Gui/" + outp)
      l = -1
      f = open(outp)
      lines = f.readlines()
      f.close()
      for line in lines:
        if line[0] == '#':
            break;
        l = l + 1

      if l >= 0:
        f = open(outp, 'w');
        lines[l] = '\n#include "EdPrec.h"\n'
        f.writelines(lines)
        f.close()
      
      shutil.move(outp, "./Gui/" + outp)
Exemplo n.º 21
0
def dump_a_session(dbobj, str_session_id):
    """
    Using mongodump to export images in a session from hardcoded database 
    on slideatlas
    """
    sessionid = ObjectId("4ed62213114d971078000000")

    # Create a meta collection connecting to temp db

    conn = dbobj.connection
    db = conn["bev1"]
    sessionobj = db["sessions"].find_one({"_id" : ObjectId(str_session_id)})

#    for aviewid in sessionobj["views"]:
#        viewobj = db["views"].find_one({"_id" : aviewid["ref"]})
#        imgobj = db["images"].find_one({"_id" : viewobj["img"]})
#        print "Processing ", imgobj["filename"]
#        db["claw"].insert(imgobj)
#        params = [ "mongodump", "-h", "slide-atlas.org", "-u", "claw", "-p", "claw123", "-d", "bev1", "-c", str(imgobj["_id"]) ]
#        print params
#        call(params)
    params = [ "mongodump", "-h", "slide-atlas.org", "-u", "claw", "-p", "claw123", "-d", "bev1", "-c", "claw"]
    call(params)

    print "done"
Exemplo n.º 22
0
def render(filtered, args):
    print("> Regenerating haproxy configuration...")
    with file_or_stdout(args['--output']) as outf:
        outf.write(_generate_conf(filtered, args['<jinja2_template>']))

    if args['--run-cmd']:
        subprocess.call(args['--run-cmd'], shell=True)
def help_boot_avd():
    try:
        emulator = get_identifier()

        # Wait for the adb to answer
        args = [settings.ADB_BINARY,
                "-s",
                emulator,
                "wait-for-device"]
        logger.info("help_boot_avd: wait-for-device")
        subprocess.call(args)

        # Make sure adb running as root
        logger.info("help_boot_avd: root")
        adb_command(['root'])

        # Make sure adb running as root
        logger.info("help_boot_avd: remount")
        adb_command(['remount'])

        # Make sure the system verity feature is disabled (Obviously, modified the system partition)
        logger.info("help_boot_avd: disable-verity")
        adb_command(['disable-verity'])

        # Make SELinux permissive - in case SuperSu/Xposed didn't patch things right
        logger.info("help_boot_avd: setenforce")
        adb_command(['setenforce', '0'], shell=True)

        logger.info("help_boot_avd: finished!")
        return True
    except:
        PrintException("help_boot_avd")
        return False
Exemplo n.º 24
0
def open_file(fname):
    if sys.platform.startswith('darwin'):
        subprocess.call(('open', fname))
    elif os.name == 'nt':
        os.startfile(fname)
    elif os.name == 'posix':
        subprocess.call(('xdg-open', fname))
Exemplo n.º 25
0
    def configure_linter(self, language):
        """Fill out the template and move the linter into Packages."""

        try:
            if language is None:
                return

            if not self.fill_template(self.temp_dir, self.name, self.fullname, language):
                return

            git = util.which('git')

            if git:
                subprocess.call((git, 'init', self.temp_dest))

            shutil.move(self.temp_dest, self.dest)

            util.open_directory(self.dest)
            self.wait_for_open(self.dest)

        except Exception as ex:
            sublime.error_message('An error occurred while configuring the plugin: {}'.format(str(ex)))

        finally:
            if self.temp_dir and os.path.exists(self.temp_dir):
                shutil.rmtree(self.temp_dir)
Exemplo n.º 26
0
    def test_s_option(self):
        usersite = site.USER_SITE
        self.assertIn(usersite, sys.path)

        rc = subprocess.call([sys.executable, '-c',
            'import sys; sys.exit(%r in sys.path)' % usersite])
        self.assertEqual(rc, 1)

        rc = subprocess.call([sys.executable, '-s', '-c',
            'import sys; sys.exit(%r in sys.path)' % usersite])
        self.assertEqual(rc, 0)

        env = os.environ.copy()
        env["PYTHONNOUSERSITE"] = "1"
        rc = subprocess.call([sys.executable, '-c',
            'import sys; sys.exit(%r in sys.path)' % usersite],
            env=env)
        self.assertEqual(rc, 0)

        env = os.environ.copy()
        env["PYTHONUSERBASE"] = "/tmp"
        rc = subprocess.call([sys.executable, '-c',
            'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'],
            env=env)
        self.assertEqual(rc, 1)
Exemplo n.º 27
0
def cloneFromGit():
    global clone_dir,git_path
    try:
        subprocess.call('/usr/bin/git clone '+git_path+' '+clone_dir,shell=True)
    except Exception as e:
        print e
        sys.exit(1)
Exemplo n.º 28
0
	def __init__(self):
		#try loading the config file
		# if it doesn't exist, create one
		try:
			self.configFile = expanduser("~") + "/.puut/puut.conf"
			#load configuration
			self.config = {}
			exec(open(self.configFile).read(),self.config)
		except IOError:
			self.setupPuut()
			call(["notify-send", "Puut: Setup config", "Setup your user data at '~/.puut/puut.conf'"])
			sys.exit(1)

		#testing if server & credentials are correct
		r = requests.get(self.config["serverAddress"] + "/info", auth=(self.config["user"],self.config["password"]))
		if not (r.text=="PUUT"):
			call(["notify-send", "Puut: Server error", "Contacting the server was unsuccessful, are credentials and server correct?\nResponse was: "+ r.text])
			sys.exit(1)		
		
		#setting up keyhooks
		for self.idx, self.val in enumerate(self.config["keys"]):
			keybinder.bind(self.val, self.hotkeyFired, self.idx) 

		#setup GTK Status icon
		self.statusicon = gtk.StatusIcon()
		self.statusicon.set_from_file("icon.png") 
		self.statusicon.connect("popup-menu", self.right_click_event)
		self.statusicon.set_tooltip("StatusIcon Example")
Exemplo n.º 29
0
def get_task(task_id, src_id):
    print task_id
    print src_id
    task = filter(lambda t: t['dst'][:5] == task_id[:5], tasks)
    new_task = filter(lambda t: t['src'][:5] == src_id[:5], task)
    if len(new_task) == 0:
	print "cannot find the ip " + task_id + " from the database"
        print "calling king service from server"
	print subprocess.call(["../king/bin/king", src_id, task_id], stdout=open('log.txt','a'))
	re_tasks = []
	with open('out.txt') as ff:
    		lines = ff.readlines()
    		for line in lines:
    			words = line.split(' ')
			re_task = {'src': words[1],
				'dst': words[4],
				'rtt': words[7],
				'bandwidth': words[11]}
			re_tasks.append(re_task)
	print re_tasks
	_task = filter(lambda t: t['dst'][:5] == task_id[:5], re_tasks)
    	inject_task = filter(lambda t: t['src'][:5] == src_id[:5], _task)
	print inject_task
	if len(inject_task) == 0:
		abort(404)
	print inject_task
	new_task = inject_task
    print new_task
    return jsonify( { 'task': make_public_task(new_task[0]) } )
Exemplo n.º 30
0
def generate_image(now):
    """
    Generate the GEMPAK file!
    """
    cmd = "csh mwplot.csh %s" % (
                                        now.strftime("%Y %m %d %H %M"),)
    subprocess.call(cmd, shell=True)
Exemplo n.º 31
0
 def test_3_word_count(self):
     if subprocess.call("python test_word_count.py") < 0:
         assert (), "test_word_count has failed."
Exemplo n.º 32
0
 def on_adapter_name_changed(self, entry):
     subprocess.call(["bt-adapter", "--set", "Alias", entry.get_text()])
     self.update_status()
def start_camera():
    subprocess.call([
        'lxterminal', '-e',
        'python3 day-and-night-timelapse-full-v2.3.py cam_configfile.yaml'
    ])
def preview():
    subprocess.call(
        ['lxterminal', '-e', 'python3 cam_preview.py cam_configfile.yaml'])
def view_configfile():
    subprocess.call(['lxterminal', '-e', 'mousepad cam_configfile.yaml'])
Exemplo n.º 36
0
def main():
    """Go Main Go"""
    nt = network.Table("AWOS")
    qdict = loadqc()
    pgconn = get_dbconn('iem', user='******')
    icursor = pgconn.cursor()

    # We run at 12z
    now12z = datetime.datetime.utcnow()
    now12z = now12z.replace(hour=12, minute=0, second=0, microsecond=0,
                            tzinfo=pytz.utc)
    today6z = now12z.replace(hour=6)
    today0z = now12z.replace(hour=0)
    yesterday6z = today6z - datetime.timedelta(days=1)
    yesterday12z = now12z - datetime.timedelta(days=1)

    fmt = "%-6s:%-19s: %3s / %3s / %5s / %4s / %2s\n"

    shef_fn = "/tmp/awos_rtp.shef"
    out = open(shef_fn, 'w')
    out.write(("\n"
               "\n"
               "\n"
               ".BR DMX %s Z DH06/TAIRVX/DH12/TAIRVP/PPDRVZ/SFDRVZ/SDIRVZ\n"
               ": IOWA AWOS RTP FIRST GUESS PROCESSED BY THE IEM\n"
               ":   06Z to 06Z HIGH TEMPERATURE FOR %s\n"
               ":   00Z TO 12Z TODAY LOW TEMPERATURE\n"
               ":   12Z YESTERDAY TO 12Z TODAY RAINFALL\n"
               ":   ...BASED ON REPORTED OBS...\n"
               ) % (now12z.strftime("%m%d"),
                    yesterday6z.strftime("%d %b %Y").upper()))

    # 6z to 6z high temperature
    highs = {}
    sql = """SELECT id,
        round(max(tmpf)::numeric,0) as max_tmpf,
        count(tmpf) as obs FROM current_log c, stations t
        WHERE t.iemid = c.iemid and t.network = 'AWOS' and valid >= %s
        and valid < %s
        and tmpf > -99 GROUP by id """
    args = (yesterday6z, today6z)
    icursor.execute(sql, args)
    for row in icursor:
        if qdict.get(row[0], {}).get('tmpf'):
            continue
        highs[row[0]] = row[1]

    # 12z to 12z precip
    pcpn = {}
    sql = """
        select id, sum(precip) from
        (select id, extract(hour from valid) as hour,
        max(phour) as precip from current_log c, stations t
        WHERE t.network = 'AWOS' and t.iemid = c.iemid
        and valid  >= %s and valid < %s
        GROUP by id, hour) as foo
        GROUP by id
    """
    args = (yesterday12z, now12z)
    icursor.execute(sql, args)
    for row in icursor:
        if qdict.get(row[0], {}).get('precip'):
            continue
        pcpn[row[0]] = "%5.2f" % (row[1],)

    # 0z to 12z low temperature
    lows = {}
    sql = """
        SELECT id, round(min(tmpf)::numeric,0) as min_tmpf,
        count(tmpf) as obs FROM
        current_log c JOIN stations t on (t.iemid = c.iemid)
        WHERE t.network = 'AWOS' and valid >= %s
        and valid < %s  and tmpf > -99 GROUP by id
    """
    args = (today0z, now12z)
    icursor.execute(sql, args)
    for row in icursor:
        if qdict.get(row[0], {}).get('tmpf'):
            continue
        lows[row[0]] = row[1]

    ids = nt.sts.keys()
    ids.sort()
    for myid in ids:
        out.write(fmt % (myid, nt.sts[myid]["name"], highs.get(myid, 'M'),
                         lows.get(myid, 'M'), pcpn.get(myid, 'M'), "M", "M"))

    out.write(".END\n")
    out.close()

    cmd = ("/home/ldm/bin/pqinsert -p 'plot ac %s0000 awos_rtp.shef "
           "awos_rtp.shef shef' %s") % (now12z.strftime("%Y%m%d"), shef_fn)
    subprocess.call(cmd, shell=True)
    os.unlink(shef_fn)
Exemplo n.º 37
0
def unzip_if_necessary(filepath):
    if filepath.endswith(".zip"):
        path_to_unzipped_file = filepath.rstrip(".zip")
        if not isfile(path_to_unzipped_file):
            call(["unzip", filepath, path_to_unzipped_file])
        return path_to_unzipped_file
Exemplo n.º 38
0
#!/usr/bin/env python
if __name__ == '__main__':
    from setuptools import setup
    from setuptools.extension import Extension
    from Cython.Build import cythonize
    import subprocess as sp

    # this should create the file rbf/_version.py
    sp.call(['python', 'make_version.py'])
    version_info = {}
    with open('rbf/_version.py', 'r') as fb:
        exec(fb.read(), version_info)

    ext = []
    ext += [Extension(name='rbf.poly', sources=['rbf/poly.pyx'])]
    ext += [Extension(name='rbf.sputils', sources=['rbf/sputils.pyx'])]
    ext += [Extension(name='rbf.pde.halton', sources=['rbf/pde/halton.pyx'])]
    ext += [
        Extension(name='rbf.pde.geometry', sources=['rbf/pde/geometry.pyx'])
    ]
    ext += [
        Extension(name='rbf.pde.sampling', sources=['rbf/pde/sampling.pyx'])
    ]
    setup(
        name='RBF',
        version=version_info['__version__'],
        description='Package containing the tools necessary for radial basis '
        'function (RBF) applications',
        author='Trever Hines',
        author_email='*****@*****.**',
        url='www.github.com/treverhines/RBF',
Exemplo n.º 39
0
def havealienmanager(alientype):
    if alientype in alien_manager_states:
        return alien_manager_states[alientype]
    res = 0 == subprocess.call(['Alien-' + alientype, '--have-manager'])
    alien_manager_states[alientype] = res
    return res
Exemplo n.º 40
0
def run_pylint(commands):
    with directory('test/'):
        result = subprocess.call(commands)
    return result
Exemplo n.º 41
0
    def create_ubuntu(self, recovery, version, iso, sender=None, conn=None):
        """Creates Ubuntu compatible recovery media"""

        self._reset_timeout()
        self._check_polkit_privilege(sender, conn,
                                     'com.dell.recoverymedia.create')
        logging.debug("create_ubuntu: recovery %s, version %s, iso %s" %
                      (recovery, version, iso))

        #create temporary workspace
        tmpdir = tempfile.mkdtemp()
        atexit.register(walk_cleanup, tmpdir)

        #mount the recovery partition
        mntdir = self.request_mount(recovery, "r", sender, conn)

        #validate that ubuntu is on the partition
        if not os.path.exists(os.path.join(mntdir, '.disk', 'info')) and \
           not os.path.exists(os.path.join(mntdir, '.disk', 'info.recovery')):
            logging.warning(
                "create_ubuntu: recovery partition missing .disk/info and .disk/info.recovery"
            )
            if os.path.exists(os.path.join(mntdir, 'bootmgr')):
                raise CreateFailed(
                    "This tool can not create a recovery image from a Windows recovery partition."
                )
            raise CreateFailed(
                "Recovery partition is missing critical ubuntu files.")

        #test for an updated dell recovery deb to put in
        try:
            self._test_for_new_dell_recovery(mntdir, tmpdir)
        except:
            raise CreateFailed(
                "Error injecting updated Dell Recovery into image.")

        #check for a nested ISO image
        if os.path.exists(os.path.join(mntdir, 'ubuntu.iso')):
            pattern = re.compile('^ubuntu.iso|^.disk')
            w_size = black_tree("size", pattern, mntdir)
            self.start_sizable_progress_thread(_('Preparing nested image'),
                                               tmpdir, w_size)
            black_tree("copy", pattern, mntdir, tmpdir)
            self.stop_progress_thread()
            mntdir = self.request_mount(os.path.join(mntdir, 'ubuntu.iso'),
                                        "r", sender, conn)

        #Generate BTO XML File
        self.xml_obj.replace_node_contents('date', str(datetime.date.today()))
        self.xml_obj.replace_node_contents('iso', version)
        self.xml_obj.replace_node_contents('generator', check_version())
        self.xml_obj.write_xml(os.path.join(tmpdir, 'bto.xml'))

        #Arg list
        xorrisoargs = [
            'xorriso', '-as', 'mkisofs', '-R', '-r', '-J', '-joliet-long',
            '-l', '-cache-inodes', '-iso-level', '3', '-A', 'Dell Recovery',
            '-p', 'Dell', '-publisher', 'Dell', '-o', iso, '-m', '*.exe', '-m',
            '*.sys', '-m', 'syslinux', '-m', 'syslinux.cfg', '-m',
            os.path.join(mntdir, 'bto.xml'), '-m',
            os.path.join(mntdir, 'isolinux'), '-m',
            os.path.join(mntdir, 'bto_version')
        ]

        #include bootloader as eltorito if we have it
        if os.path.exists(os.path.join(mntdir, 'boot', 'efi.img')):
            xorrisoargs.append('-e')
            xorrisoargs.append('boot/efi.img')
            xorrisoargs.append('-no-emul-boot')
            xorrisoargs.append('-append_partition')
            xorrisoargs.append('2')
            xorrisoargs.append('0xef')
            xorrisoargs.append(os.path.join(mntdir, 'boot', 'efi.img'))
            xorrisoargs.append('-partition_cyl_align')
            xorrisoargs.append('all')

        #disable 32 bit bootloader if it was there.
        grub_path = os.path.join(mntdir, 'boot', 'grub', 'i386-pc')
        if os.path.exists(grub_path):
            xorrisoargs.append('-m')
            xorrisoargs.append(grub_path)
        grub_path = os.path.join(tmpdir, 'boot', 'grub', 'i386-pc')
        os.makedirs(grub_path)
        for name in ['boot.img', 'core.img']:
            with open(os.path.join(grub_path, name), 'w'):
                pass

        #include EFI binaries
        if os.path.exists(os.path.join(mntdir, 'efi.factory')) and \
           not os.path.exists(os.path.join(mntdir, 'efi')):
            xorrisoargs.append('-m')
            xorrisoargs.append('efi.factory')
            shutil.copytree(os.path.join(mntdir, 'efi.factory'),
                            os.path.join(tmpdir, 'efi'))

        #if no bootstrap in RP, we'll put it in the initrd
        bootstrap_initrd = not os.path.exists(
            os.path.join(mntdir, 'scripts', 'bootstrap.sh'))

        #Renerate UUID
        os.mkdir(os.path.join(tmpdir, '.disk'))
        os.mkdir(os.path.join(tmpdir, 'casper'))
        self.start_pulsable_progress_thread(
            _('Regenerating UUID / Rebuilding initramfs'))
        (old_initrd,
         old_uuid) = create_new_uuid(os.path.join(mntdir, 'casper'),
                                     os.path.join(mntdir, '.disk'),
                                     os.path.join(tmpdir, 'casper'),
                                     os.path.join(tmpdir, '.disk'),
                                     new_compression="auto",
                                     include_bootstrap=bootstrap_initrd)
        self.stop_progress_thread()
        xorrisoargs.append('-m')
        xorrisoargs.append(os.path.join('.disk', old_uuid))
        xorrisoargs.append('-m')
        xorrisoargs.append(os.path.join('casper', old_initrd))

        #Restore .disk/info
        info_path = os.path.join(mntdir, '.disk', 'info.recovery')
        if os.path.exists(info_path):
            xorrisoargs.append('-m')
            xorrisoargs.append(info_path)
            shutil.copy(info_path, os.path.join(tmpdir, '.disk', 'info'))

        #if we have any any ISO/USB bootable bootloader on the image, copy in a theme
        grub_theme = False
        for topdir in [mntdir, tmpdir]:
            if os.path.exists(
                    os.path.join(topdir, 'boot', 'grub', 'x86_64-efi')):
                grub_theme = True
        if grub_theme:
            if not os.path.exists(os.path.join(tmpdir, 'boot', 'grub')):
                os.makedirs(os.path.join(tmpdir, 'boot', 'grub'))
            #conffiles
            shutil.copy('/usr/share/dell/grub/theme/grub.cfg',
                        os.path.join(tmpdir, 'boot', 'grub', 'grub.cfg'))
            xorrisoargs.append('-m')
            xorrisoargs.append(os.path.join(mntdir, 'boot/grub/grub.cfg'))
            directory = os.path.join(mntdir, 'boot', 'grub', 'x86-64_efi')
            if os.path.exists(directory):
                if not os.path.exists(
                        os.path.join(tmpdir, 'boot', 'grub', 'x86_64-efi')):
                    os.makedirs(
                        os.path.join(tmpdir, 'boot', 'grub', 'x86_64-efi'))
                shutil.copy(
                    '/usr/share/dell/grub/theme/%s/grub.cfg' % 'x86_64-efi',
                    os.path.join(tmpdir, 'boot', 'grub', 'x86_64-efi',
                                 'grub.cfg'))
                xorrisoargs.append('-m')
                xorrisoargs.append(
                    os.path.join(mntdir,
                                 'boot/grub/%s/grub.cfg' % 'x86_64-efi'))
            #theme
            if not os.path.exists(os.path.join(mntdir, 'boot', 'grub',
                                               'dell')):
                shutil.copytree('/usr/share/dell/grub/theme/dell',
                                os.path.join(tmpdir, 'boot', 'grub', 'dell'))
            #fonts
            if not os.path.exists(
                    os.path.join(mntdir, 'boot', 'grub',
                                 'dejavu-sans-12.pf2')):
                ret = subprocess.call([
                    'grub-mkfont',
                    '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf',
                    '-s=12',
                    '--output=%s' %
                    os.path.join(tmpdir, 'boot', 'grub', 'dejavu-sans-12.pf2')
                ])
                if ret is not 0:
                    raise CreateFailed("Creating GRUB fonts failed.")

            if not os.path.exists(
                    os.path.join(mntdir, 'boot', 'grub',
                                 'dejavu-sans-bold-14.pf2')):
                ret = subprocess.call([
                    'grub-mkfont',
                    '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf',
                    '-s=14',
                    '--output=%s' % os.path.join(tmpdir, 'boot', 'grub',
                                                 'dejavu-sans-bold-14.pf2')
                ])
                if ret is not 0:
                    raise CreateFailed("Creating GRUB fonts failed.")

        #if we previously backed up a grub.cfg or common.cfg
        for path in ['factory/grub.cfg', 'factory/common.cfg']:
            if os.path.exists(os.path.join(mntdir, path + '.old')):
                xorrisoargs.append('-m')
                xorrisoargs.append(os.path.join(mntdir, path) + '*')
                if not os.path.exists(os.path.join(tmpdir, 'factory')):
                    os.makedirs(os.path.join(tmpdir, 'factory'))
                shutil.copy(os.path.join(mntdir, path + '.old'),
                            os.path.join(tmpdir, path))

        #regenerate md5sum file
        if os.path.exists(os.path.join(mntdir, 'md5sum.txt')):
            xorrisoargs.append('-m')
            xorrisoargs.append(os.path.join(mntdir, 'md5sum.txt'))
            regenerate_md5sum(tmpdir, mntdir)
        #Directories to install
        xorrisoargs.append(tmpdir + '/')
        xorrisoargs.append(mntdir + '/')

        #ISO Creation
        seg1 = subprocess.Popen(xorrisoargs,
                                stderr=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                universal_newlines=True)
        pipe = seg1.stderr

        fcntl.fcntl(pipe.fileno(), fcntl.F_SETFL,
                    fcntl.fcntl(pipe.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK)

        retval = seg1.poll()
        logging.debug(" create_ubuntu: xorriso debug")
        while (retval is None):
            readx = select.select([pipe.fileno()], [], [])[0]
            if readx:
                output = pipe.read()
                if output.strip():
                    logging.debug(output.strip())
                    split = output.split()
                    if (len(split) > 4):
                        progress = split[4]
                        if (progress[-1:] == '%'):
                            self.report_progress(_('Building ISO'),
                                                 progress[:-1])
            retval = seg1.poll()
        if retval is not 0:
            logging.error(
                " create_ubuntu: xorriso exited with a nonstandard return value."
            )
            logging.error("  cmd: %s" % xorrisoargs)
            logging.error("  stderror: %s" % pipe.readlines())
            logging.error("  error: %s" % output.strip())
            raise CreateFailed("ISO Building exited unexpectedly:\n%s" %
                               output.strip())
Exemplo n.º 42
0
if __name__ == '__main__':
    if len(sys.argv) < 3:
        print "Usage: Alien --<mode> AlienType:alienpkg [...]\n"
        print "Valid options for <mode> are:"
        print "    --get-version"
        print "    --getinstallversion"
        print "    --greater-than"
        print "    --met|--within-range|--interval"
        print "    --have-manager"
        print "    --get-manager-rule"
        print "    --install\n"
        print "Valid options for AlienType are:"
        print "    CPAN"
        print "    LuaRocks"
        print "    PIP"
        print "    RubyGems\n"
        print "Example:"
        print "    Alien --install CPAN:XML::Parser"
        print "    Alien --install PIP:burn"
        exit(1)
    mode = sys.argv[1]
    prog = sys.argv[2]
    try:
        alientype, alienpkg = split(prog)
    except ValueError:
        print "Error: missing program name"
        exit(1)
    args = ['Alien-' + alientype, mode, alienpkg] + sys.argv[3:]
    exit(subprocess.call(args))

Exemplo n.º 43
0
def on_message(client, userdata, msg):

    if(msg.topic=="acho/tv/power"):
	call(["curl", arduino+"/arduino/command/power"])
	client.publish("acho/tts", "Apagando la television")
        print "topic power recibido"
Exemplo n.º 44
0
def ebehydro(fpath,
             cent='0_5',
             etaos=0.12,
             gpu_id=0,
             system='pbpb2760',
             oneshot=False):
    ''' Run event_by_event hydro, with initial condition 
    from smearing on the particle list'''

    fout = fpath
    if not os.path.exists(fout):
        os.mkdir(fout)

    cfg.NX = 200
    cfg.NY = 200
    cfg.NZ = 121
    cfg.DT = 0.02
    cfg.DX = 0.16
    cfg.DY = 0.16
    cfg.DZ = 0.20

    cfg.ntskip = 20
    cfg.nxskip = 2
    cfg.nyskip = 2
    cfg.nzskip = 2

    cfg.eos_type = 'lattice_pce150'
    cfg.TAU0 = 0.6
    cfg.fPathOut = fout

    #cfg.TFRZ = 0.137
    cfg.TFRZ = 0.100

    cfg.ETAOS_XMIN = 0.154

    cfg.ETAOS_YMIN = 0.15
    cfg.ETAOS_RIGHT_SLOP = 0.0
    cfg.ETAOS_LEFT_SLOP = 0.0

    cfg.save_to_hdf5 = True

    # for auau
    if system == 'auau200':
        cfg.Eta_gw = 1.3
        cfg.Eta_flat = 1.5
        comments = 'au+au IP-Glasma'
        collision = AuAu200()
        scale_factor = 57.0
    # for pbpb
    else:
        cfg.Eta_gw = 1.8
        cfg.Eta_flat = 2.0
        comments = 'pb+pb IP-Glasma'
        if system == 'pbpb2760':
            collision = PbPb2760()
            scale_factor = 128.0
        elif system == 'pbpb5020':
            collision = PbPb5020()
            scale_factor = 151.0

    grid_max = cfg.NX / 2 * cfg.DX

    fini = os.path.join(fout, 'trento_ini/')

    if os.path.exists(fini):
        call(['rm', '-r', fini])

    collision.create_ini(cent,
                         fini,
                         num_of_events=1,
                         grid_max=grid_max,
                         grid_step=cfg.DX,
                         one_shot_ini=oneshot)
    if oneshot:
        s = np.loadtxt(os.path.join(fini, 'one_shot_ini.dat'))
    else:
        s = np.loadtxt(os.path.join(fini, '0.dat'))
    smax = s.max()
    s_scale = s * scale_factor
    t0 = time()

    visc = CLVisc(cfg, gpu_id=gpu_id)

    ed = from_sd_to_ed(s_scale, visc.ideal.eos)

    ev = np.zeros((cfg.NX * cfg.NY * cfg.NZ, 4), cfg.real)

    # repeat the ed(x,y) NZ times
    ev[:, 0] = np.repeat((ed.T).flatten(), cfg.NZ)

    eta_max = cfg.NZ // 2 * cfg.DZ
    eta = np.linspace(-eta_max, eta_max, cfg.NZ)

    heta = np.ones(cfg.NZ)

    fall_off = np.abs(eta) > cfg.Eta_flat
    eta_fall = np.abs(eta[fall_off])
    heta[fall_off] = np.exp(-(eta_fall - cfg.Eta_flat)**2 /
                            (2.0 * cfg.Eta_gw**2))

    # apply the heta longitudinal distribution
    ev[:, 0] *= np.tile(heta, cfg.NX * cfg.NY)

    visc.ideal.load_ini(ev)

    visc.evolve(max_loops=4000,
                save_hypersf=True,
                save_bulk=True,
                save_vorticity=False)

    write_config(cfg, comments)
    t1 = time()
    print('finished. Total time: {dtime}'.format(dtime=t1 - t0))

    cwd = os.getcwd()
    os.chdir('../sampler/mcspec/')
    viscous_on = 'true'
    after_reso = 'true'
    nsampling = '2000'
    call(['python', 'sampler.py', fout, viscous_on, after_reso, nsampling])
    os.chdir(cwd)

    #from create_table import create_table_for_jet
    #create_table_for_jet(fout, visc.ideal.eos)
    os.chdir('../CLSmoothSpec/build')
    #os.system('cmake -D VISCOUS_ON=ON ..')
    #os.system('make')
    call(['./spec', fpath])
    os.chdir(cwd)
    after_reso = '0'
    call(['python', '../spec/main.py', fpath, after_reso])
Exemplo n.º 45
0
#! /usr/local/bin/python3
import datetime
import subprocess
import sys

# Do experiments many time
time = datetime.datetime.today()
time_fmt = '%Y%m%d-%H%M%S'
path = time.strftime(time_fmt)
# reuilt files are in 'path/'
result_file = path + '-result'
subprocess.call(['mkdir', path])
argvs = sys.argv
if len(argvs) <= 1:
    count = 2
else:
    count = int(argvs[1])
for i in range(count):
    #for fnode_num in range(10, 101, 10):
    for p_a in range(1, 11):
        subprocess.call(['ns', 'detect.tcl', str(p_a/100), result_file])

# Process the results
rf = open(result_file, 'r')
pd_file = open('p_A-maj_vs_pd', 'w')
pf_file = open('p_A-maj_vs_pf', 'w')
pd = dict()
pf = dict()
for line in rf:
    results = line.split()
    var = float(results[0])
Exemplo n.º 46
0
def scp(dirname):
    subprocess.call('scp -r %s jdouglass@ncp-geome:~/backblaze_mount' %
                    dirname,
                    shell=True)
    os.makedirs(lock_dir)

# noinspection PyBroadException
try:
    os.stat(config['startdir'])
except:
    os.makedirs(config['startdir'])

locks = list()
for n, c in zip(job_names, job_commands):
    # if the submission script crashes before all jobs are submitted, the lockfile system ensures that only
    # not-yet-submitted jobs will be submitted the next time this script runs
    next_lockfile = os.path.join(lock_dir, n+'.LOCK')
    locks.append(next_lockfile)
    if not os.path.isfile(os.path.join(script_dir, n)):
        if lock(next_lockfile):
            next_job = create_job(n, c)

            if (socket.gethostname() == 'discovery7.hpcc.dartmouth.edu') or (socket.gethostname() == 'ndoli.hpcc.dartmouth.edu'):
                submit_command = 'echo "[SUBMITTING JOB: ' + next_job + ']"; mksub'
            else:
                submit_command = 'echo "[RUNNING JOB: ' + next_job + ']"; sh'

            call(submit_command + " " + next_job, shell=True)

# all jobs have been submitted; release all locks
for l in locks:
    release(l)
if not lock_dir_exists:  # remove lock directory if it was created here
    os.rmdir(lock_dir)
Exemplo n.º 48
0
	json_data = open('citycode.json')
	data = json.load(json_data)
	for d in data:
		if d['city']==cityNameText:
			code = d['code']
	if(code==''):
		print "No such city found, please check with citycode.json or the usage\nUsage python main.py $city-Name \nCity-Name should be hyphen(-) seperated if it is of more than one word, first word capitalised cased"
	else:
		# link.py
		os.chdir('..\hotels')
		proc = subprocess.Popen('scrapy crawl link -o reviews.json',stdin=subprocess.PIPE,shell=True)
		proc.stdin.write(cityName+'_'+code)
		proc.stdin.close()
		retcode = proc.wait()
		# copy
		subprocess.call('copy sentiment.py ..\stanford-corenlp-full-2014-10-31', shell=True)
		subprocess.call('copy reviews.json ..\stanford-corenlp-full-2014-10-31', shell=True)
		subprocess.call('del reviews.json', shell=True)
		subprocess.call('md ..\\'+cityName, shell=True)

		# go to stanford
		os.chdir('..\stanford-corenlp-full-2014-10-31')
		proc4 = subprocess.Popen('python sentiment.py', shell=True)
		retcode4 = proc4.wait()
		# copy reviews
		subprocess.call('del sentiment.py',shell=True)
		subprocess.call('copy rate.csv ..\\'+cityName, shell=True)
		subprocess.call('copy rate.txt ..\\'+cityName, shell=True)
		subprocess.call('copy reviews.json ..\\'+cityName, shell=True)
		subprocess.call('del rate.csv',shell=True)
		subprocess.call('del rate.txt',shell=True)
Exemplo n.º 49
0
import sys

LOCALES_TO_SKIP = []


def available_locales(l10n_path):
    for xliff_path in glob.glob(l10n_path + "/*/firefox-ios.xliff"):
        parts = xliff_path.split(os.sep)
        yield parts[-2]


if __name__ == "__main__":
    project_path = sys.argv[1]
    l10n_path = sys.argv[2]

    for locale in available_locales(l10n_path):
        if locale in LOCALES_TO_SKIP:
            continue
        command = [
            "xcodebuild", "-exportLocalizations", "-localizationPath",
            "/tmp/xliff", "-project", project_path, "-exportLanguage", locale
        ]

        print "Exporting '%s' to '/tmp/xliff/%s.xliff'" % (locale, locale)
        subprocess.call(command)

        src_path = "/tmp/xliff/%s.xliff" % locale
        dst_path = "%s/%s/firefox-ios.xliff" % (l10n_path, locale)
        print "Copying '%s' to '%s'" % (src_path, dst_path)
        shutil.copy(src_path, dst_path)
Exemplo n.º 50
0
# "VPLMedia/bunny/Tutorial.pyscene"
from pathlib import Path
import subprocess
import os

cwd = os.path.dirname(os.path.realpath(__file__)) + '\\'
print("Current Path is " + cwd)

for frame in range(1, 121):
    targetFile = "rotation_animation" + str(frame) + ".py"
    script = '.\\Scripts\\BunnyAnimation\\' + targetFile
    args = [
        cwd + '\\Bin\\x64\\Release\\Mogwai.exe',
        '--script',
        cwd + script,
        '--verbosity',
        '5',
    ]
    subprocess.call(args)
def stop_camera():
    subprocess.call([
        'lxterminal', '-e',
        'kill $(ps aux | grep "day-and-night-timelapse-full-v2.3.py cam_configfile.yaml")'
    ])
Exemplo n.º 52
0
 def test_4_uninstall(self):
     if subprocess.call("python spark_install.py -U -sv " + sparkversion +
                        " -hv " + hadoopversion) < 0:
         assert (), "Uninstall process failed."
Exemplo n.º 53
0
    (40, 80),
    (80, 160),
    (160, 320),
]

ns = []
sigrid_eval = []
sigrid_weights = []
esmf_eval = []
esmf_weights = []
for srcDims in src_celldims:
    # generate the grids
    dstDims = (srcDims[0] // 2, srcDims[1] // 2)
    call(['python', 'generate_field.py', \
     '--src_nj', '{}'.format(srcDims[0] + 1), \
     '--src_ni', '{}'.format(srcDims[1] + 1), \
     '--dst_nj', '{}'.format(dstDims[0] + 1), \
     '--dst_ni', '{}'.format(dstDims[1] + 1), \
     ])

    srcN = srcDims[0] * srcDims[1]
    dstN = dstDims[0] * dstDims[1]
    ns.append(srcN * dstN)
    print('number of src * dst cells is {}'.format(srcN * dstN))

    # run esmf
    err = open('log.err', 'w')
    out = open('log.txt', 'w')
    call(['python', 'esmf_conserve.py'], stdout=out, stderr=err)
    out.close()
    esmf_eval.append(getEvaluationTime('log.txt'))
    esmf_weights.append(getWeightsTime('log.txt'))
Exemplo n.º 54
0
	return result2
	
def deviceFound():
	result=subprocess.check_output("adb devices",shell=True)
	return result

modeCheck="adb shell su"
cmd1="adb shell ls /storage/emulated/0/"
cmdcam="adb shell am start -a android.media.action.IMAGE_CAPTURE"
cmd2="adb shell rm -rf /storage/emulated/0/DCIM"
cmd3="adb reboot"
cmd4="adb shell input keyevent 27"
cmd5="adb wait-for-device"

result0=subprocess.check_output(modeCheck,shell=True) 
subprocess.call("exit",shell=True)

if result0=="su command not found":
	print("clearing is not p[ossible ,pls make it test version")
else:
	print("device found and performing test")
	result5=deviceFound()
	if "device" in result5:
		print("the device is connected")
		result1=subprocess.check_output(cmd1,shell=True)
		if "DCIM" in result1:
			print("DCIM already found deleting files")
			result2=delDcim()
			if "DCIM" in result2: 
				print("file not deleted")
			else:
Exemplo n.º 55
0
 def export(self):
     export = [
         'python2', self.eptofmu_file, '-i', self.idd_file, '-w',
         self.epw_file, '-a', '2', self.idf_file
     ]
     subprocess.call(export)
Exemplo n.º 56
0
def delDcim():
	subprocess.call(cmd2,shell=True)
	result2=subprocess.check_output(cmd1,shell=True)
	return result2
Exemplo n.º 57
0
def reconfigure(target, package):
    """executes a dpkg-reconfigure into installed system to each
    package which provided by args."""
    subprocess.call(['log-output', '-t', 'ubiquity', 'chroot', target,
                     'dpkg-reconfigure', '-fnoninteractive', package],
                    preexec_fn=reconfigure_preexec, close_fds=True)
Exemplo n.º 58
0
def fetch_all_translations():
    if subprocess.call([TX, 'pull', '-f', '-a']):
        print('Error while fetching translations', file=sys.stderr)
        exit(1)
Exemplo n.º 59
0
##******************************************************************************
# Kill VRSG processes for selected HOTAS stations

# TODO: add this step once you know what the commands are

##******************************************************************************
# Find all directories for selected HOTAS stations and copy files from
# appropriate backup release folder into all the HOTAS plugins folders

# Create list of directories inside of backup release folder
backup_folder = all_versions[version][1]
backup_release_folders = list()
for item in os.listdir(backup_folder):
    item_path = os.path.join(backup_folder, item)
    if not os.path.isfile(item_path):
        backup_release_folders.append(item)

# Find all FOLDERS in VRSG directory that have 'Plugins', 'H00X', and 'OTW',
# 'sensor1', or 'sensor2' in their directory names, and perform robocopy from
# backup folder into correct VRSG folder
VRSG_folder = 'C:\\vrsg'
for HOTAS in HOTAS_list:
    for release_folder in backup_release_folders:
        for item in os.listdir(VRSG_folder):
            item_path = os.path.join(VRSG_folder, item)
            if (HOTAS in item) and (release_folder in item) and ('Plugins' in item) and (not os.path.isfile(item_path)):
                subprocess.call('robocopy ' + os.path.join(backup_folder, release_folder) + ' ' + item_path + ' /MIR /COPY:DAT /DCOPY:T /NFL /NDL /NJS /NJH /NS /NC', shell=True)

elapsed_time = time.time() - start_time
print '\n\tDone. (Elapsed time: {0:.3f} sec)\n'.format(elapsed_time)
	def teardown_pwm(self, pin):
		call("gpio -g mode " + str(pin) + " in", shell=True)
		self._logger.debug("reset former pwm_pin " + str(pin) + " pin_mode back to INPUT." )