Exemple #1
0
def main():
    securities = [
        Security(30, "$", RiskLevel.LOW, Trend.UP, 0, "Ukraine", "I"),
        Equity(20, "$", RiskLevel.MEDIUM, Trend.DOWN, 0, "Russia", "I",
               "Roshen", 0.5),
        Debt(10, "$", RiskLevel.HIGH, Trend.UP, 0, "Belarus", "I"),
        Derivative(0, "$", RiskLevel.DANGER, Trend.UP, 0, "Moldova", "I",
                   "house"),
        Security(0, "$", RiskLevel.LOW, Trend.DOWN, 10, "Ukraine", "I")
    ]
    manager = SecuritiesManager(*securities)

    filteredList = manager.filterByPrice(0)
    for s in filteredList:
        print(s)
    print()

    sortedList = SecuritiesManager.sortByPriceAscending(securities)
    for s in sortedList:
        print(s)
    print()

    sortedFilteredList = SecuritiesManager.sortByDurationDescending(
        filteredList)
    for s in sortedFilteredList:
        print(s)
def main():
    #setup
    my_ib = MyIb()
    Security.set_trading_exchange_information(
        exchange_info.trading_exchange_timezone, 
        exchange_info.exchange_opening_time, 
        exchange_info.exchange_normal_close_time, 
        exchange_info.exchange_early_close_time, exchange_info.trading_holidays)
    
    #create security object
    my_security = Security(my_ib, symbol='GOOG', secType='STK',
        exchange='SMART')
    
    #Register callbacks
    my_ib.conn.register(error_handler, 'Error')
    my_ib.conn.register(my_security.save_historical_data, 'HistoricalData')
    
    my_ib.connect_to_ib_servers()
    
    #get SMA
    sma = my_security.get_historical_sma(length=150, barSizeSetting='1 day',
        ohlc='CLOSE', whatToShow='MIDPOINT', endDateTime='now')
    print("My SMA: {}".format(sma))
    
    print(sma)

    my_ib.conn.disconnect()
Exemple #3
0
 def showSalePane(self, event):
     name = self.login.nameText.GetValue()
     user = Security(name, self.login.passText.GetValue())
     connect = DatabaseConn()
     connect.cur().execute("UPDATE security SET state = 'off'")
     data = connect.cur().execute(
         "select name,password,status from security")
     if user.checkpass(data):
         if (user.getStatus() == 'admin'):
             connect.cur().execute(
                 "UPDATE security SET state = 'on'  WHERE name = '{name}'".
                 format(name=name))
             connect.commit()
             self.login.nameText.SetValue("")
             self.login.passText.SetValue("")
             self.window.Show(True)
             self.Hide()
             self.Layout()
         else:
             connect.cur().execute(
                 "UPDATE security SET state = 'on'  WHERE name = '{name}'".
                 format(name=name))
             connect.commit()
             self.login.nameText.SetValue("")
             self.login.passText.SetValue("")
             self.sales.Show()
             self.Hide()
             self.Layout()
     else:
         self.login.status.SetLabel("Incorrect Username or Password")
     connect.close()
Exemple #4
0
def main():
    #setup
    my_ib = MyIb()
    Security.set_trading_exchange_information(
        exchange_info.trading_exchange_timezone,
        exchange_info.exchange_opening_time,
        exchange_info.exchange_normal_close_time,
        exchange_info.exchange_early_close_time,
        exchange_info.trading_holidays)

    #create security object
    my_security = Security(my_ib,
                           symbol='GOOG',
                           secType='STK',
                           exchange='SMART')

    #Register callbacks
    my_ib.conn.register(error_handler, 'Error')
    my_ib.conn.register(my_security.save_historical_data, 'HistoricalData')

    my_ib.connect_to_ib_servers()

    #get SMA
    sma = my_security.get_historical_sma(length=150,
                                         barSizeSetting='1 day',
                                         ohlc='CLOSE',
                                         whatToShow='MIDPOINT',
                                         endDateTime='now')
    print("My SMA: {}".format(sma))

    print(sma)

    my_ib.conn.disconnect()
Exemple #5
0
    def __init__(self, *args):
        import string

        apply(self._pre_init, args)
        Security.__init__(self)
        self._wf.flush()
        self._post_init()
Exemple #6
0
 def printme(self):
     Security.printme(self)
     try:
         print('K=%f, T=%s, t=%s, life=%d' %
               (self.strikeprice, self.expirydate.strftime('%Y-%m-%d'),
                self.listeddate.strftime('%Y-%m-%d'), self.lifedays))
     except:
         print('--------------------error here--------------------')
 def __init__(self, enabled: bool, expirationSeconds: int,
              blockAfterFailures: int):
     self.database = {}
     self.enabled = enabled
     self.expirationSeconds = expirationSeconds
     self.blockAfterFailures = blockAfterFailures
     self.logs = Logs(self.__class__.__name__)
     self.security = Security()
Exemple #8
0
    def __init__(self, _next_partition_name, _public_key=None, _debug=True):

        self.debug = _debug
        self.next_partition_name = _next_partition_name
        self.public_key = _public_key
        self.security = Security()
        self.uuid_project = ''
        self.version = 0
        self.date_expiration = ''
        self.type = ''
        self.new = {}
Exemple #9
0
    def __init__(self, objectName):
        self.level = 'INFO'
        if "LOG_LEVEL" in environ:
            self.level = environ["LOG_LEVEL"]

        self.format = 'TEXT'
        if "LOG_FORMAT" in environ:
            self.format = environ["LOG_FORMAT"]

        self.objectName = objectName
        self.security = Security()
Exemple #10
0
 def __init__(self, *args):
     self._pre_init(*args)
     Security.__init__(self)
     self._wf.flush()
     line = self._rf.readline()
     challenge = int(line.strip())
     response = self._encode_challenge(challenge)
     line = repr(int(response))
     if line[-1] in 'Ll': line = line[:-1]
     self._wf.write(line + '\n')
     self._wf.flush()
     self._post_init()
 def __init__(self, *args):
     self._pre_init(*args)
     Security.__init__(self)
     self._wf.flush()
     line = self._rf.readline()
     challenge = int(line.strip())
     response = self._encode_challenge(challenge)
     line = repr(int(response))
     if line[-1] in 'Ll': line = line[:-1]
     self._wf.write(line + '\n')
     self._wf.flush()
     self._post_init()
Exemple #12
0
 def __init__(self, *args):
     import string
     apply(self._pre_init, args)
     Security.__init__(self)
     self._wf.flush()
     line = self._rf.readline()
     challenge = string.atoi(string.strip(line))
     response = self._encode_challenge(challenge)
     line = repr(long(response))
     if line[-1] in 'Ll': line = line[:-1]
     self._wf.write(line + '\n')
     self._wf.flush()
     self._post_init()
Exemple #13
0
 def __init__(self, *args):
     import string
     apply(self._pre_init, args)
     Security.__init__(self)
     self._wf.flush()
     line = self._rf.readline()
     challenge = string.atoi(string.strip(line))
     response = self._encode_challenge(challenge)
     line = repr(long(response))
     if line[-1] in 'Ll': line = line[:-1]
     self._wf.write(line + '\n')
     self._wf.flush()
     self._post_init()
    def update_securities(self, force_full_output=False, max_tries=6):
        priority = ['ALWAYS', 'FILL']
        if len(self._watchlist.keys()) > 500:
            logger.warning(
                "Too many securities for API Request. Truncating to 500 oldest-updated reports"
            )
            updated = []
            for symbol in self._watchlist.keys():
                if os.path.exists(
                        os.path.join(Security.STOCK_DIR, f'{symbol}.json')):
                    with open(
                            os.path.join(Security.STOCK_DIR,
                                         f'{symbol}.json')) as f:
                        updated.append({
                            "symbol":
                            symbol,
                            "updated_at":
                            json.load(f)[-1]['date'],
                            'priority':
                            self._watchlist[symbol]['update_priority']
                        })
                else:
                    updated.append({
                        "symbol":
                        symbol,
                        "updated_at":
                        '1970-01-01',
                        'priority':
                        self._watchlist[symbol]['update_priority']
                    })
            updated = sorted(updated,
                             key=lambda x:
                             (priority.index(x['priority']), x['updated_at']))
            securities = [u['symbol'] for u in updated][:500]

        logger.info(f"Collected securities list: {', '.join(securities)}")
        for symbol in securities:
            s = Security(symbol)
            failed = 0
            request = 0
            while request == 0 and failed < max_tries:
                if failed != 0:
                    logger.warning(
                        f"Failed {failed} out of {max_tries} times for {symbol}"
                    )
                request = s.update(force_full_output)
                failed += 1
                if request == 0:
                    logger.info("Waiting 12 seconds...")
                    time.sleep(12)
Exemple #15
0
    def __init__(self, _uuid_project, _id_device, _version, _host_broker, \
                    _callback_on_receive_update, _private_key=None, _public_key=None, _delivery_type='Push', _debug=True):
        self.host_broker = _host_broker
        self.debug = _debug
        self.delivery_type = _delivery_type
        self.id_device = _id_device
        self.private_key = _private_key
        self.public_key = _public_key
        self.security = Security()
        self.message_incoming = bytes()
        self.do_decrypt = False
        self.aes_random_key = ''

        _id_on_broker = "FotaSuit-" + _uuid_project + "-" + self.id_device
        self.mqtt_client = MQTTClient(_id_on_broker, self.host_broker)
        self.mqtt_client.DEBUG = self.debug
        self.mqtt_client.set_callback(self.publish_received)

        self.update_file_size = 0
        self.update_file_index = 0
        self.update_file_handle = 0
        self.memory = Memory(self.debug)
        _next_partition = self.memory.get_next_partition_name()

        self.callback_on_receive_update = _callback_on_receive_update

        if not (self.delivery_type == 'Push' or self.delivery_type == 'Pull'):
            raise ValueError("'type' variable not supported. Try 'Pull' or 'Push'.")

        while not self.connect_on_broker(True):
            self.print_debug("trying connection with broker...")
            time.sleep(3)

        self.manifest = Manifest(_next_partition, _public_key)
        self.manifest.load(_uuid_project, _version)

        files = os.listdir()
        if '_updated.iota' in files: #have an update ?

            # notify the upgrade
            _version = str(self.manifest.version)
            _msg = '{"idDevice":"'+self.id_device+'", "uuidProject":"'+_uuid_project+'"'
            _msg += ', "version":'+_version+', "date": ""}'

            #TODO: insert other informations in message like date
            self.publish_on_topic(_version, "updated", _msg)
            os.remove('_updated.iota')
            
        self.subscribe_task = "manifest" # waiting for manifest file
        self.print_debug("initialized.")
Exemple #16
0
def getIndicador():
    """
        Endpoint that is to get data  to render reports on platform
    """
    authOk = True
    response = exception_response

    # Allow skipping authentication checks only if in debug mode
    if app.debug:
        sec = Security()
        authOk = sec.validate_access(request.authorization)
    else:
        print('\n Authentication checks skipped')

    if authOk:
        #return True
        try:
            response = []
            reportfilter = request.json

            print("\n *************************")

            obj = MeuDesconto()
            ret_audiencia = obj.getIndicadores()
            resp = make_response(jsonify(ret_audiencia), 200)

            new_resp = json.loads(resp.data)
            response.append(new_resp)

            response = make_response(json.dumps(response))
            response.headers[
                'Content-Type'] = 'application/json; charset=utf-8'

        except Exception as e:
            now = datetime.now()
            try:
                f = open("Logchamadas.log", "a")
                f.write("\n{0} - Erro: {1} - Parametros : {2}".format(
                    now.strftime("%d/%m/%Y %H:%M:%S"), str(e),
                    str(reportfilter)))
                f.close()
            except:
                pass
            exception_response['Razao'] = str(e)
            return make_response(jsonify(exception_response), 400)
    else:
        print("\n UNAUTHORIZED ACCESS")
        raise ValueError

    return response
Exemple #17
0
def update_page(cell, content):
    """ update method """
    cipher = Security('ec2cli')
    server, user, passwd, parent_id, page_id, title, response, region, product = config(
        cell)
    confluence = Confluence(url=server,
                            username=user,
                            password=cipher.decrypt(passwd))

    confluence.update_page(parent_id=parent_id,
                           page_id=page_id,
                           title=title,
                           body=content)

    return response
Exemple #18
0
 def post(cls):
     username = request.form['username']
     password = request.form['password']
     user = Security.authenticate(username, password)
     if user:
         login_user(user)
         jsonUser = cls.__getUser(user)
         if user.Role == 'Stud':
             if jsonUser['grade'] == 1:
                 return make_response(
                     render_template('StudentView.html',
                                     userInfo={'user': user.FName}))
             if jsonUser['grade'] == 4:
                 return make_response(
                     render_template('StudentViewGrade4.html',
                                     userInfo={'user': user.FName}))
         elif user.Role == "Prof":
             if jsonUser['grade'] == 1:
                 return make_response(
                     render_template('TeacherViewGrade1.html',
                                     userInfo={'user': user.FName}))
             if jsonUser['grade'] == 4:
                 return make_response(
                     render_template('professor4.html',
                                     userInfo={'user': user.FName}))
         elif user.Role == "Admin":
             return make_response(
                 render_template('AdminView.html',
                                 userInfo=jsonify({'user': jsonUser})))
     return make_response(render_template('login.html'))
Exemple #19
0
def handler(event, context):
    # Get info on the cms' resources from the constants file
    with open("constants.json", "r") as resources_file:
        resources = json.loads(resources_file.read())
    
    # Extract the request body
    request_body = event["body"]
    
    # Check that a request is included
    if "request" in request_body:
        request = request_body["request"]
    else:
        Error.send_error("noRequest")
    
    # Check that the request is supported
    if not supported_request(request):
        Error.send_error("unsupportedRequest", data={"request": request})
    
    if "token" in event:
        user_token = remove_prefix(event["token"])
    else:
        user_token = None
    
    """ Authenticate the request unless it is login, as login requires no
        authentication
    """
    if request != "loginUser":
        # Check that a token is provided with the request
        if user_token == None:
            Error.send_error("noToken")
        
        # Check that the user has the necessary permissions to make the request
        user_info = Security.authenticate_and_authorize(
            user_token, request, resources["TOKEN_TABLE"],
            resources["USER_TABLE"], resources["ROLE_TABLE"]
        )

        print user_info
        
        # Strip dynamo type identifiers from user info
        user_info = strip_dynamo_types(user_info)
        
        # Check if authentication or authorization returned an error
        if "error" in user_info:
            Error.send_error(authorized["error"], data=authorized["data"])
    else:
        user_info = None
    
    # Process the request
    if not user_info == None:
        response = process_request(request_body, resources, request,
                                   user_info=user_info, token=user_token)
    else:
        response = process_request(request_body, resources, request)
    
    # Check if response returned an error
    if "error" in response:
        Error.send_error(response["error"], data=response["data"])
    
    return strip_dynamo_types(response)
Exemple #20
0
    def __init__(self, login_name, password=None):
        super(XmlRpcLogin,self).__init__()

        self.set_app_server("xmlrpc")

        # If the tag <force_lowercase_login> is set to "true"
        # in the TACTIC config file,
        # then force the login string argument to be lowercase.
        # This tag is false by default.        
        self.login_name = login_name
        if Config.get_value("security","force_lowercase_login") == "true":
            self.login_name = self.login_name.lower()
        
        self.password = password

        # clear the main container
        #Container.clear()

        Environment.set_env_object( self )

        # set up the security object
        security = Security()
        Environment.set_security(security)

        self._do_login()
Exemple #21
0
    def tsla(self):
        tsla = Security('TSLA')
        price = tsla.get_price()
        self.prices.put(price)
        volume = tsla.security.get_volume()
        # if volume != self.volume:
        #     print(volume)
        #     self.volume = volume
        # else:
        #     return

        # do things necessary for avg and stddev calc
        # self.price_sum = self.prices.sum()
        # self.price_sum_sq = self.prices.sum_sq()
        # self.count = len(self.prices)

        avg = self.prices.average()
        var = self.prices.variance()

        if price < avg * (1 - self.boundary):
            # low price, want to buy
            while portfolio.buy(tsla, 1):
                pass
            self.holding = True
        elif price > avg * (1 + self.boundary):
            # high price, want to sell_all
            portfolio.sell_all(tsla)
            self.holding = False
        print(
            f'Price: {price:.2f}\tAvg: {avg:.2f}\tvar: {var:.2f} <{time.asctime()}',
            end='\r')
 def rsi_bollinger_report(self):
     df = pd.DataFrame()
     for w in self.list():
         df_signals = Security(w).signals_rsi_bollinger()
         if df_signals is None:
             continue
         row = {
             'security':
             w,
             'last_date_overbought':
             df_signals[df_signals['signal'] ==
                        'OVER-BOUGHT']['date'].max(),
             'last_date_underbought':
             df_signals[df_signals['signal'] ==
                        'UNDER-BOUGHT']['date'].max(),
             'current_sma_price':
             df_signals[df_signals['date'].max() ==
                        df_signals['date']]['sma_price_20dy'].tolist()[0],
             'current_price':
             df_signals[df_signals['date'].max() == df_signals['date']]
             ['close'].tolist()[0],
             'last_updated':
             df_signals['date'].max()
         }
         df_new = pd.DataFrame.from_dict([row])
         df = pd.concat([df, df_new])
     return df.reset_index(drop=True)
Exemple #23
0
    def __init__(self, ticket, site=None):
        super(XmlRpcInit,self).__init__()


        if not site:
            # if not explicitly set, keep the current site
           site = Site.get_site() 

        self.set_app_server("xmlrpc")

        self.ticket = ticket


        # clear the main container
        #Container.clear()

        Environment.set_env_object( self )

        # set up the security object
        security = Security()
        Environment.set_security(security)


        if site:
            Site.set_site(site)

        self._do_login()
Exemple #24
0
def add_security(*args):
    try:
        name, ticker, country, ir_website, currency = args
    except ValueError:
        print(f"{SYNTAX_INPUT_ERROR} Example: {Security.example_input()}")
        return

    db.insert_security(Security(" ".join(name.split("-")), ticker, country, ir_website, currency))
Exemple #25
0
def dzh2DivRec(dzh_rec):
    """convert function"""

    stamp2date = datetime.datetime.fromtimestamp
    sec = Security(dzh_rec[0])
    return [DivRec(sec,
                     stamp2date(rec[0]).date(),
                     rec[1], rec[4], rec[2], rec[3]
            ) for rec in dzh_rec[1]]
Exemple #26
0
class XMLProcessorNotifier(smtpInterface):
    # adding encryption switch.  emailed sensitive data must be encrypted.
    def __init__(self, docName, docs=[], encrypt=False):
        # turn on encryption switch
        if encrypt:
            self.encrypt = encrypt
            self.security = Security()
        
        self.mailSystem = smtpInterface(settings)
        if docName <> '':
            folderName = os.path.split(docName)[0]
            self.mailSystem.setRecipients(inputConfiguration.SMTPRECIPIENTS[folderName])
            self.docName = docName
        else:
            if len(docs) > 0:
                # first file dictates where this is going, mostly files will be in the output location.
                try:
                    folderName = os.path.split(docs[0])[0]
                    self.mailSystem.setRecipients(inputConfiguration.SMTPRECIPIENTS[folderName])
                except KeyError:
                    raise
            

    def sendDocumentAttachment(self, Subject='Your Message Subject', Message='Message Body goes here.', attachment=None):
        self.mailSystem.setMessageSubject(Subject)
        self.mailSystem.setMessage(Message)
        self.mailSystem.formatMessage()
        for f in attachment:
            if self.encrypt:
                attachment = 'encryptdAttachment.enc'
                # FIXME encrypt the file before attaching.
                self.security.encryptFile(f, attachment)
                
            else:
                attachment = f
            
            print 'file: %s' % f
            self.mailSystem.setAttachmentText(attachment)
        try:
            self.sendMessage()
        except Exception, detail:
            if settings.DEBUG:
                print "problem sending notification", str(detail)
            return
 def __init__(self, line):
     elts = map(elt_parser, line.rstrip().split("\t"))
     self.raw = raw = self.Raw(*elts)
     self.security = Security(raw.StockID, account2market(raw.Account),
                              raw.StockName)
     self.fee = sum(
         (float(getattr(raw, 'Fee' + str(i))) for i in (1, 2, 3, 4)))
     self.quantity = float(raw.Quantity)
     self.date = dt.datetime.strptime(raw.Date[0:8], "%Y%m%d").date()
     self.amount = float(self.raw.Amount)
Exemple #28
0
    def __init__(self, project_code=None, login_code=None, site=None):
        self.set_app_server("batch")

        if not site:
            # if not explicitly set, keep the current site
           site = Site.get_site() 


        plugin_dir = Environment.get_plugin_dir()
        if plugin_dir not in sys.path:
            sys.path.insert(0, plugin_dir)

        super(Batch,self).__init__()

        self.login_code = login_code

        # clear the main container
        Container.create()

        if site:
            Site.set_site(site)

        # set this as the environment
        if not project_code:
            self.context = self.get_default_context()
        else:
            self.context = project_code

        Environment.set_env_object( self )

        # set up the security object
        security = Security()
        Environment.set_security(security)

        self._do_login()
        site_dir = Environment.get_site_dir()
        if site_dir not in sys.path:
            sys.path.insert(0, site_dir)

        # set the project
        from pyasm.biz import Project

        if self.context == "batch":
            Project.set_project("admin")
        else:
            Project.set_project(self.context)

        self.initialize_python_path()


        # start workflow engine
        #from pyasm.command import Workflow
        #Workflow().init()

        DbContainer.commit_thread_sql()
Exemple #29
0
class Logs:
    def __init__(self, objectName):
        self.level = 'INFO'
        if "LOG_LEVEL" in environ:
            self.level = environ["LOG_LEVEL"]

        self.format = 'TEXT'
        if "LOG_FORMAT" in environ:
            self.format = environ["LOG_FORMAT"]

        self.objectName = objectName
        self.security = Security()

    def __print__(self, level, extraFields):
        fields = {
            'date': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            'level': level,
            'objectName': self.objectName,
            'ip': self.security.getUserIP(),
            'referrer': self.security.getUserReferrer()
        }

        # Include extra fields custom by the user
        fields.update(extraFields)

        if self.format == 'JSON':
            print(json.dumps(fields))
        else:
            print(' - '.join(map(str, fields.values())))

    def error(self, extraFields):
        if self.level in ['INFO', 'WARNING', 'ERROR']:
            self.__print__('ERROR', extraFields)

    def warning(self, extraFields):
        if self.level in ['INFO', 'WARNING']:
            self.__print__('WARNING', extraFields)

    def info(self, extraFields):
        if self.level in ['INFO']:
            self.__print__('INFO', extraFields)
    def login(self):
        security = Security()
        security.decrypt_cred()
        # credentials = self.getCredential()
        scopes = [
            'https://www.googleapis.com/auth/spreadsheets',
            'https://www.googleapis.com/auth/drive.file'
        ]
        global SERVICE_ACCOUNT

        if SERVICE_ACCOUNT:
            logging.info(
                f"SERVICE_ACCOUNT.auth.expired {SERVICE_ACCOUNT.auth.expired}")
            if SERVICE_ACCOUNT.auth.expired:
                SERVICE_ACCOUNT = gspread.service_account('./credentials.json',
                                                          scopes=scopes)
                logging.info('Service Account successfully refreshed')
            return SERVICE_ACCOUNT
        else:
            SERVICE_ACCOUNT = gspread.service_account('./credentials.json',
                                                      scopes=scopes)
            return SERVICE_ACCOUNT
Exemple #31
0
    def __init__(self, ticket=None):

        super(TacticInit,self).__init__()

        self.ticket = ticket

        # create the main container
        Container.create()

        Environment.set_env_object( self )

        # set up the security object
        security = Security()
        Environment.set_security(security)
Exemple #32
0
 def __init__(self,
              pricePerUnit=0,
              currency="$",
              riskLevel=RiskLevel.LOW,
              trend=Trend.UP,
              duration=0,
              emitent="NoEmitent",
              owner="NoOwner",
              asset="NoAsset",
              security=Security()):
     super(Debt, self).__init__(pricePerUnit, currency, riskLevel, trend,
                                duration, emitent, owner)
     self.asset = asset
     self.security = Security
Exemple #33
0
    def __init__(my, ticket):
        super(XmlRpcInit, my).__init__()

        my.set_app_server("xmlrpc")

        my.ticket = ticket

        # clear the main container
        #Container.clear()

        Environment.set_env_object(my)

        # set up the security object
        security = Security()
        Environment.set_security(security)

        my._do_login()
Exemple #34
0
 def onConnect(self, request):
     """
     Called whenever a new client connects to our websocket.
     Is used for authenticating newly connected clients.
     """
     # check if the user sent valid authentication attributes
     authenticated = Security.auth_status(
         request.headers,
         Config.get_user(),
         Config.get_password()
     )
     if not authenticated:
         # deny connection
         raise HttpException(401, "Invalid authentication data.")
     else:
         print("Authenticated: {0}".format(request.peer))
         self.factory.add_client(self)
Exemple #35
0
    def __init__(my, project_code=None, login_code=None, site=None):
        my.set_app_server("batch")

        plugin_dir = Environment.get_plugin_dir()
        if plugin_dir not in sys.path:
            sys.path.insert(0, plugin_dir)

        super(Batch, my).__init__()

        my.login_code = login_code

        # clear the main container
        Container.create()

        if site:
            Site.set_site(site)

        # set this as the environment
        if not project_code:
            my.context = my.get_default_context()
        else:
            my.context = project_code

        Environment.set_env_object(my)

        # set up the security object
        security = Security()
        Environment.set_security(security)

        my._do_login()
        site_dir = Environment.get_site_dir()
        if site_dir not in sys.path:
            sys.path.insert(0, site_dir)

        # set the project
        from pyasm.biz import Project

        if my.context == "batch":
            Project.set_project("admin")
        else:
            Project.set_project(my.context)

        my.initialize_python_path()

        DbContainer.commit_thread_sql()
Exemple #36
0
 def __init__(self, docName, docs=[], encrypt=False):
     # turn on encryption switch
     if encrypt:
         self.encrypt = encrypt
         self.security = Security()
     
     self.mailSystem = smtpInterface(settings)
     if docName <> '':
         folderName = os.path.split(docName)[0]
         self.mailSystem.setRecipients(inputConfiguration.SMTPRECIPIENTS[folderName])
         self.docName = docName
     else:
         if len(docs) > 0:
             # first file dictates where this is going, mostly files will be in the output location.
             try:
                 folderName = os.path.split(docs[0])[0]
                 self.mailSystem.setRecipients(inputConfiguration.SMTPRECIPIENTS[folderName])
             except KeyError:
                 raise
 def makeTrade(self, security, amount):
     if amount is 0:
         print("Entered trading amount of 0")
         return
     print("Trading " + str(amount) + " of " + security.securityName + " at price of " + str(security.price))
     foundFlag = False
     if self.positions:
         for p in self.positions:
             if p.security.securityName == security.securityName:
                 foundFlag = True
                 newAveragePrice = self.calculateNewPositionAveragePrice(p.security, p.amount, security, amount)
                 p.amount += amount
                 p.security.price = newAveragePrice
                 if p.amount is 0:
                     self.positions.remove(p)
     if foundFlag == False:
         newSecurity = Security(security.securityName, security.securityType, security.price)
         self.positions.append(Position(newSecurity, amount))
     self.cash -= (security.price * amount)
     self.calculatePortfolioValue()
     self.calculateTotalValue()
 def __init__(self, *args):
     Server.__init__(self, *args)
     Security.__init__(self)
Exemple #39
0
"""RPC Client module."""
Exemple #40
0
 def __init__(self, *args):
     apply(Server.__init__, (self,) + args)
     Security.__init__(self)
Exemple #41
0
 def printme(self):
     Security.printme(self)
     try:
         print('K=%f, T=%s, t=%s, life=%d' %(self.strikeprice, self.expirydate.strftime('%Y-%m-%d'), self.listeddate.strftime('%Y-%m-%d'),self.lifedays))
     except:
         print('--------------------error here--------------------')
Exemple #42
0
"""RPC Server module."""
		ob_operations = Operations()
		print "Computing: Fibonacci"
		ob_operations.computeFibonacci(10)
		print "computing: Power of 2"
		ob_operations.computePower(128)
	except IOError:
		print "Exception: Too Many Files Open"
	except MemoryError:
		print "Exception: Memory Usage"
	except:
		print "Exception: ", sys.exc_info()[0]

	print "\nLoading Exploit Program\n"

	try:
		ob_security = Security()

		parser = argparse.ArgumentParser()
		parser.add_argument('--file', '-f')
		args = parser.parse_args()

		if args.file:
			if ob_security.filepath(args.file):
				print "check: file path: pass"
				if ob_security.fileSize(args.file):
					print "check: file size: pass"
					if ob_security.code(args.file):
						print "check: source code: pass"
						print "\nExploit Code Execution & Output"
						if ob_security.execute(args.file):
							print "\ncheck: code execute: pass"
from security import Security


class MockML(object):
    def check_model(self, model):
        pass

    def check_input_params(self, model, input_params):
        pass

    def check_model_params(self, model, model_params):
        pass

    def check_components(self, model, components):
        pass

    def check_interm_params(self, model, interm_params, hidden_params):
        pass

ml = MockML()

s = Security(ml, 'foo', 'logger', 'out')
inp = {'error_control': 'False'}
print(s.team_arguments(inp))