示例#1
0
文件: mailer.py 项目: petryshend/flpy
 def __init__(self, only_with_photos):
     self.only_with_photos = only_with_photos
     self.driver = webdriver.Firefox()
     self.women_send_intro_links = []
     self.men = self.load_men_array_from_json()
     self.men_countries = list(self.men.keys())
     self.username = Credentials.get()["username"]
     self.password = Credentials.get()["password"]
示例#2
0
def final_time():
  logging.info('We are entering the final time.')
  credentials = Credentials(database_directory=FLAGS.internal_directory)
  owners_data = credentials.owner()
  print owners_data

  for (group_id, aws_access_key_id, aws_secret_access_key) in owners_data:
    sns_connection = boto.connect_sns(aws_access_key_id, aws_secret_access_key)
    sqs_connection = boto.connect_sqs(aws_access_key_id, aws_secret_access_key)
    iam_connection = boto.connect_iam(aws_access_key_id, aws_secret_access_key)
    group_manager = GroupManager(sns_connection, sqs_connection, iam_connection,
                                 database_directory=FLAGS.internal_directory)
    group_manager.delete_group(group_id)
示例#3
0
def first_time():
  # Clear internal databases' directory.
  _rm_rf(FLAGS.internal_directory)

  # Make internal databases' directory.
  os.makedirs(FLAGS.internal_directory)

  # Create connections for different AWS services.
  s3_connection = boto.connect_s3(
    aws_access_key_id = FLAGS.aws_access_key_id,
    aws_secret_access_key = FLAGS.aws_secret_access_key)
  sdb_connection = boto.connect_sdb(
    aws_access_key_id = FLAGS.aws_access_key_id,
    aws_secret_access_key = FLAGS.aws_secret_access_key)
  sqs_connection = boto.connect_sqs(
    aws_access_key_id = FLAGS.aws_access_key_id,
    aws_secret_access_key = FLAGS.aws_secret_access_key)
  sns_connection = boto.connect_sns(
    aws_access_key_id = FLAGS.aws_access_key_id,
    aws_secret_access_key = FLAGS.aws_secret_access_key)
  iam_connection = boto.connect_iam(
    aws_access_key_id = FLAGS.aws_access_key_id,
    aws_secret_access_key = FLAGS.aws_secret_access_key)

  # Creates notification service topics and queues.
  group_manager = GroupManager(sns_connection, sqs_connection, iam_connection,
                               database_directory = FLAGS.internal_directory)

  group_id = get_random_uuid()

  # Creates S3 Bucket.
  bucket_name = group_id
  blob_store = BlobStore(s3_connection, bucket_name)
  assert isinstance(blob_store.bucket, boto.s3.bucket.Bucket)

  # Creates SimpleDB domains.
  data_domain_name = bucket_name + '_data'
  lock_domain_name = bucket_name + '_locks'
  metadata_store = MetadataStore(sdb_connection, lock_domain_name,
                                 data_domain_name,
                                 database_directory = FLAGS.internal_directory)

  # Credentials table.
  credentials = Credentials(database_directory = FLAGS.internal_directory)
  if not credentials.set_credentials(group_id, 'us-east-1',
                                     FLAGS.namespace, FLAGS.aws_access_key_id,
                                     FLAGS.aws_secret_access_key, 'OWNER'):
    logging.error('We were unable to set our own owner credentials.')
示例#4
0
def get_connection(client_email, private_key_path):
  """Shortcut method to establish a connection to the Cloud Datastore.

  Use this if you are going to access several datasets
  with the same set of credentials (unlikely):

  >>> import gclouddatastore
  >>> connection = gclouddatastore.get_connection(email, key_path)
  >>> dataset1 = connection.dataset('dataset1')
  >>> dataset2 = connection.dataset('dataset2')

  :type client_email: string
  :param client_email: The e-mail attached to the service account.

  :type private_key_path: string
  :param private_key_path: The path to a private key file (this file was
                           given to you when you created the service
                           account).

  :rtype: :class:`gclouddatastore.connection.Connection`
  :returns: A connection defined with the proper credentials.
  """
  from connection import Connection
  from credentials import Credentials

  credentials = Credentials.get_for_service_account(
      client_email, private_key_path)
  return Connection(credentials=credentials)
示例#5
0
文件: ui.py 项目: rushiagr/proxman
    def onclick_apply_button(self, widget):
        
        dat = self.get_data()
#        print dat
        
        cred = Credentials(dat)
        errors = cred.validate()
        
        if len(errors) is not 0:
            error_text = 'Please check the following errors:\n'
            for i in range(len(errors)):
                error_text += ('    ' + str(i+1) + '. ' + errors[i] + '\n')
            error_window = PopUp(error_text)
            return
        
        if ApplyProxy(cred).status is 'success':
            popup = DestructionPopUp('Proxy applied to the system! :)')
示例#6
0
    def __init__(self, *args):
        self.credentials_dialog = Credentials()
        self.email = ""
        self.password = ""
        self.verify_credentials()

        super(Client, self).__init__(*args)
        uic.loadUi('client.ui', self)

        self.publishers = {
                0: self.send_text,
                1: self.send_quote,
                2: self.send_chat,
                3: self.send_url,
                4: self.send_photo,
                5: self.send_video,
                6: self.send_audio}
        self.setWindowTitle(self.email)
示例#7
0
 def __init__(self, parser):
     self.no_pass = False
     optparse.OptionGroup.__init__(self, parser, "Credentials Options")
     self.add_option("--simple-bind-dn", metavar="DN", action="callback",
                     callback=self._set_simple_bind_dn, type=str,
                     help="DN to use for a simple bind")
     self.add_option("--password", metavar="PASSWORD", action="callback",
                     help="Password", type=str, callback=self._set_password)
     self.add_option("-U", "--username", metavar="USERNAME", 
                     action="callback", type=str,
                     help="Username", callback=self._parse_username)
     self.add_option("-W", "--workgroup", metavar="WORKGROUP", 
                     action="callback", type=str,
                     help="Workgroup", callback=self._parse_workgroup)
     self.add_option("-N", "--no-pass", action="store_true",
                     help="Don't ask for a password")
     self.add_option("-k", "--kerberos", metavar="KERBEROS", 
                     action="callback", type=str,
                     help="Use Kerberos", callback=self._set_kerberos)
     self.creds = Credentials()
示例#8
0
文件: getopt.py 项目: endisd/samba
 def __init__(self, parser):
     CredentialsOptions.__init__(self, parser)
     self.no_pass2 = False
     self.add_option("--simple-bind-dn2", metavar="DN2", action="callback",
                     callback=self._set_simple_bind_dn2, type=str,
                     help="DN to use for a simple bind")
     self.add_option("--password2", metavar="PASSWORD2", action="callback",
                     help="Password", type=str, callback=self._set_password2)
     self.add_option("--username2", metavar="USERNAME2",
                     action="callback", type=str,
                     help="Username for second server", callback=self._parse_username2)
     self.add_option("--workgroup2", metavar="WORKGROUP2",
                     action="callback", type=str,
                     help="Workgroup for second server", callback=self._parse_workgroup2)
     self.add_option("--no-pass2", action="store_true",
                     help="Don't ask for a password for the second server")
     self.add_option("--kerberos2", metavar="KERBEROS2",
                     action="callback", type=str,
                     help="Use Kerberos", callback=self._set_kerberos2)
     self.creds2 = Credentials()
示例#9
0
#IoT Device Registration and Connection Service
import asyncio
import os
import json
import datetime
import random

from azure.iot.device.aio import ProvisioningDeviceClient
from azure.iot.device.aio import IoTHubDeviceClient
from azure.iot.device import MethodResponse
from azure.iot.device import Message
from credentials import Credentials
from iotc import IOTCConnectType, IOTCLogLevel, IOTCEvents
from iotc.aio import IoTCClient
import app_logger
credentials: Credentials = Credentials()


async def register_device():
    provisioning_device_client = ProvisioningDeviceClient.create_from_symmetric_key(
        provisioning_host=credentials.provisioning_host,
        registration_id=credentials.registration_id,
        id_scope=credentials.id_scope,
        symmetric_key=credentials.symmetric_key)

    registration_result = await provisioning_device_client.register()
    print(f'Registration result: {registration_result.status}')
    return registration_result


async def register_device():
示例#10
0
 def setUp(self):
     '''
     setup method that runs before each test cases
     '''
     self.new_user = User("Joseph", "Kahiga", "Kahiga@1234")
     self.new_app = Credentials("Facebook", "Kahiga@1234")
class TestCredentials(unittest.TestCase):
    '''
    creating test cases for credentials class
    '''
    def setUp(self):
        '''
        set up method before test cases
        '''

        self.new_credentials = Credentials("Instagram", "paSwo678")

    def tearDown(self):
        '''
            tearDown method that does clean up after each test case has run.
            '''
        Credentials.cred_list = []

    def test_init(self):

        self.assertEqual(self.new_credentials.accountname, "Instagram")
        self.assertEqual(self.new_credentials.accountpassword, "paSwo678")

    def test_save_credentials(self):
        '''
        checks whether the credentials has been saved to credentials list
        '''
        self.new_credentials.save_credentials()
        self.assertEqual(len(Credentials.cred_list), 1)

    def test_save_multiple_credentials(self):
        '''
            test_save_multiple_credentials to check if we can save multiple credentials
            objects to our credentials_list
            '''
        self.new_credentials.save_credentials()
        test_credentials = Credentials("Twitter", "twe458")  # new credentials
        test_credentials.save_credentials()
        self.assertEqual(len(Credentials.cred_list), 2)

    def test_delete_credentials(self):
        '''
            test_delete_credentials to test if we can remove a credentials from our credentials list
            '''

        self.new_credentials.save_credentials()
        test_credentials = Credentials("Netflix", "fghjk")  # new credentials
        test_credentials.save_credentials()

        self.new_credentials.delete_credentials(
        )  # Deleting a credentials object
        self.assertEqual(len(Credentials.cred_list), 1)

    def test_find_credentials_by_accountname(self):
        '''
        test to check if we can find an account credentials by name and display password
        '''

        self.new_credentials.save_credentials()
        test_credentials = Credentials("Facebook", "user56789")  # new account
        test_credentials.save_credentials()

        found_credentials = Credentials.find_by_accountname("Facebook")

        self.assertEqual(found_credentials.accountname,
                         test_credentials.accountname)

    def test_account_exists(self):
        '''
        test to check if we can return a Boolean  if we cannot find the account.
        '''

        self.new_credentials.save_credentials()
        test_credentials = Credentials("Pinterest", "23dfgdb")  # new account
        test_credentials.save_credentials()

        credentials_exists = Credentials.credentials_exist("Pinterest")

        self.assertTrue(credentials_exists)

    def test_display_all_credentials(self):
        '''
        method that returns a list of all account credentials saved
        '''

        self.assertEqual(Credentials.display_credentials(),
                         Credentials.cred_list)

    def test_copy_password(self):
        '''
        Test to confirm that we are copying the password from a found account
        '''

        self.new_credentials.save_credentials()
        Credentials.copy_password("Instagram")

        self.assertEqual(self.new_credentials.accountpassword,
                         pyperclip.paste())
示例#12
0
def find_credential(app_name):
    '''
    Function that finds a contact by username and return the credential
    '''
    return Credentials.find_by_app_name(app_name)
示例#13
0
def delete_credential(Credentials):
    '''
    a function to delete credential
    '''
    Credentials.delete_credential()
示例#14
0
					continue

				print u'POST\t{0:d}\t{1:s}'.format(sc, s)

			else:
				print u'POST\t{0:s}'.format(s)



			cur = self.con.cursor()
			cur.execute(self.publish, (s, p, sc))
			cur.close()



if __name__ == '__main__':
	from credentials import Credentials
	from sources import Sources

	cred = Credentials()
	con = cred.db()

	s = Sources(con, **cred.strdict('api'))
	g = Generator(con, sources = s, **cred.strdict('api'))

	if cred.cred['api']['new']:
		print 'Reinitializing database.'
		g.reset()

	g.tweet()
示例#15
0
        return [{u'name': flavor.name,
                 u'id': flavor.id,
                 u'ram': flavor.ram,
                 u'disk': flavor.disk,
                 u'vcpus': flavor.vcpus}
                for flavor in self.nc.flavors.findall()]

    def image_list(self):
        return [{u'name': image.name,
                 u'id': image.id} for image in self.nc.images.findall()]


if __name__ == '__main__':
    from credentials import Credentials

    creds = Credentials()
    nc = NovaClient(creds.get_nova_creds())

    pool = 5
    i = 0

    print 'First need check availability flavor:'
    print nc.flavor_list()
    print '\nThen need check availability image:'
    print nc.image_list()

    print '\nCreate pool instance:'
    while i < pool:
        print 'Create instance %s' % i
        nc.create_new_instance(DEF_NAME, DEF_IMAGE_ID,
                               DEF_FLAVOR_ID, SSH_MY_KEY)
示例#16
0
def display_app():
    '''
    Function that displays a list of apps saved
    '''
    return Credentials.display_app()
示例#17
0
def app_existance(app):
    '''
    Function that checks if an app exists and returns a boolean
    '''
    return Credentials.app_exist(app)
示例#18
0
def find_app(app):
    '''
    Function that finds an app
    '''
    return Credentials.find_app(app)
示例#19
0
def create_app(app, app_password):
    '''
    Function to create new app and password
    '''
    new_app = Credentials(app, app_password)
    return new_app
示例#20
0
from gather_keys_oauth2 import OAuth2Server
import fitbit
from credentials import Credentials
import datetime
import io


def daterange(d1, d2):
    return (d1 + datetime.timedelta(days=i) for i in range((d2 - d1).days + 1))


if __name__ == '__main__':

    c = Credentials('config.ini')  # start
    date1 = datetime.date(2016, 5, 10)
    date2 = datetime.date(2016, 6, 30)
    #date2 = datetime.date.today() - datetime.timedelta(days = 1)

    TEMPLATE_TSV = """{date}\t{time}\t{heart_rate}\n"""
    TEMPLATE_CSV = """{date},{time},{heart_rate}\n"""

    if c.hasCredentials():  # credentials
        if not c.hasAuthorization():  # no token
            print 'doing autorization...'
            server = OAuth2Server(c.getClientId(), c.getClientSecret(), c.getURI())
            server.browser_authorize()

            c.setAutorization(server.oauth.token['access_token'], server.oauth.token['refresh_token'],
                              server.oauth.token['expires_at'])

        out_file_name = 'output/heart-rate-' + str(datetime.date.today()) + '.csv'
示例#21
0
def get_connection(dataset_id, client_email=None, private_key_path=None):
  credentials = Credentials.get_for_service_account(
      client_email, private_key_path)
  return Connection(dataset_id, credentials=credentials)
示例#22
0
文件: parse.py 项目: neapel/twitkov
						message[i : i + self.parts].lower(),
						message[i + self.parts] if i < last else None,
						i == 0
					)
					for i in range(last + 1)
				])
				cur.executemany(self.insert, l)

		cur.close()



if __name__ == '__main__':
	from credentials import Credentials

	cred = Credentials()
	con = cred.db()
	p = Parser( con, **cred.strdict('api') )

	if cred.cred['api']['new']:
		print 'Reinitializing database.'
		p.reset()

	try:
		p.analyze( cred.stream() )
	except KeyboardInterrupt:
		pass

	con.close()

示例#23
0
 def test_save_multiple_credentials(self):
     self.newCredentials.save_credentials()
     test_credentials = Credentials("Twitter", "@alexkimutai",
                                    "password12345")
     test_credentials.save_credentials()
     self.assertEqual(len(Credentials.credentials_list), 4)
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--mode", help="""the mode to consider:
     "full" for the whole WxS server (see the "--wxs-server" option),
     "workspace" for a workspace,
     "layer" for a single layer""", choices=['full', 'workspace', 'layer'],
                        required=True)

    parser.add_argument("--item", help="""indicates the item (layer or workspace) name, see the "mode" option.
                                       The option is ignored in "full" mode.""")
    parser.add_argument("--geoserver", help="the GeoServer to use.", required=True)
    parser.add_argument("--dry-run", help="Dry-run mode", action='store_true', default=False)
    parser.add_argument("--disable-ssl-verification", help="Disable certificate verification", action="store_true")

    args = parser.parse_args(sys.argv[1:])
    creds = Credentials(logger=logger)

    if args.disable_ssl_verification:
        bypassSSLVerification()
    # Disable FutureWarning from owslib
    warnings.simplefilter("ignore", category=FutureWarning)

    (user, password) = creds.getFromUrl(args.geoserver)
    gscatalog = Catalog(args.geoserver + "/rest/", username=user, password=password)
    errors = []
    # Whole geoserver catalog
    if args.mode == "full":
        print_banner(args)
        # Layers
        workspaces = gscatalog.get_workspaces()
        for ws in workspaces:
示例#25
0
def generate_password():
    '''
    Function that generates random passwords
    '''
    generate_password = Credentials.gen_password()
    return generate_password
示例#26
0
文件: twitter.py 项目: neapel/twitkov
			opt = { 'count': pagesize, 'page': page }
			if( self.stalk ):
				opt['screen_name'] = self.stalk

			print 'Fetching tweets', page * pagesize, 'to', (page + 1) * pagesize

			try:
				req = Request(url + '?' + urlencode(opt), headers = self.headers) 
				js = loads( '\n'.join( urlopen(req).readlines() ) )
				if len(js) < 5:
					break
				for tweet in js:
					yield tweet['text']
			except:
				break


	def __iter__(self):
		if self.stream == 'sample':
			return self.sample()
		else:
			return self.timeline()



if __name__ == '__main__':
	from credentials import Credentials
	c = Credentials()
	for m in c.stream():
		print m
示例#27
0
def check_existing_email(password):
    """
    Function that check if a email exists with that password and return a Boolean
    """
    return Credentials.credentials_exist(password)
示例#28
0
 def setUp(self):
     self._cred_dict = {
         'lol': 42
     }
     self.loader = Credentials([FakeBackend(self._cred_dict)])
示例#29
0
from PIL import ImageTk, Image

from constants.fileConstants import FileConstants
from credentials import Credentials
from stream import Stream
from twitchapi import authorize, validateOAuth
from windows.mainWindow import MainWindow

if not validateOAuth():
    oAuth = authorize()
else:
    with open("oauth.txt", "r") as f:
        oAuth = f.read().rstrip()

credentials = Credentials(oAuth)
mainWindow = MainWindow(credentials)
Stream.DEFAULT_BOX_ART = ImageTk.PhotoImage(Image.open(FileConstants.PREVIEW_BOX_ART))
Stream.DEFAULT_STREAM_PREVIEW = ImageTk.PhotoImage(Image.open(FileConstants.STREAM_PREVIEW))
mainWindow.window.mainloop()
示例#30
0
def check_existing_credentials(app_name):
    '''
    functions that checks if a credential exist
    '''
    return Credentials.find_by_app_name(app_name)
示例#31
0
 def setUp(self):
     self.db = CDB.CallybotDB(*Credentials().db_info)
示例#32
0
def display_credentials():
    '''
    function that displays all the credentials
    '''
    return Credentials.display_credentials()
示例#33
0
class TestCredentials(unittest.TestCase):
    def setUp(self):
        self.new_credentials = Credentials("twitter", "celinemmbone3",
                                           "CelineColline")

    def test_init(self):
        self.assertEqual(self.new_credentials.account, "twitter")
        self.assertEqual(self.new_credentials.password, "celinemmbone3")
        self.assertEqual(self.new_credentials.user_name, "CelineColline")

    def test_save_credentials(self):
        self.new_credentials.save_credentials()
        # saving the new credentials
        self.assertEqual(len(Credentials.credentials_list), 1)

# setup and class creation up here

    def tearDown(self):
        Credentials.credentials_list = []


# other test cases here
#     def test_save_multiple_credentials(self):

#         self.new_credentials.save_credentials()
#         test_credentials = Credentials(
#             "twitter", "celinemmbone3", "CelineColline")  # new credentials

# More tests above

    def test_delete_credentials(self):
        '''
            test_delete_credentials to test if we can remove a credentials from our credentials list
            '''
        self.new_credentials.save_credentials()
        test_credentials = Credentials("twitter", "celinemmbone3",
                                       "CelineColline")  # new credentials
        test_credentials.save_credentials()

    def test_find_credentials_by_password(self):
        '''
        test to check if we can find a credentials by phone number and display information
      '''

        self.new_credentials.save_credentials()
        test_credentials = Credentials("twitter", "celinemmbone3",
                                       "CelineColline")  # new credentials
        test_credentials.save_credentials()

        # found_credentials = Credentials.find_by_password("gift254")

        # self.assertEqual(found_credentials.credentials,test_credentials.password)

    def test_credentials_exists(self):
        '''
        test to check if we can return a Boolean  if we cannot find the credentials.
        '''

        self.new_credentials.save_credentials()
        test_credentials = Credentials("twitter", "celinemmbone3",
                                       "CelineColline")  # new contact
        test_credentials.save_credentials()

        credentials_exists = Credentials.credentials_exist("celinemmbone3")

        self.assertTrue(credentials_exists)

    def test_display_all_credentials(self):
        '''
        method that returns a list of all credentials saved
        '''

        self.assertEqual(Credentials.display_all_credentials(),
                         Credentials.credentials_list)

    # def test_copy_email(self):
    #     '''
    #     Test to confirm that we are copying the email address from a found credential
    #     '''

    #     self.new_credentials.save_credentials()
    #     Credentials.copy_email("*****@*****.**")

    # self.assertEqual(self.new_credentials.email,pyperclip.paste())

    def test_display_credentials(self):
        '''
        method that returns a list of all credentials saved
        '''

        self.assertEqual(Credentials.display_all_credentials(),
                         Credentials.credentials_list)
    def setUp(self):
        '''
        set up method before test cases
        '''

        self.new_credentials = Credentials("Instagram", "paSwo678")
示例#35
0
 def setUp(self):
     self.new_credentials = Credentials("twitter", "celinemmbone3",
                                        "CelineColline")
示例#36
0
class TestUser(unittest.TestCase):
    '''
    Test class that defines test cases for the user class behaviours.
    '''
    new_user = User("Joseph", "Kahiga", "Kahiga@1234")  # captures user details
    new_app = Credentials(
        "Facebook",
        "Kahiga@1234")  # captures app details from credentials class

    def setUp(self):
        '''
        setup method that runs before each test cases
        '''
        self.new_user = User("Joseph", "Kahiga", "Kahiga@1234")
        self.new_app = Credentials("Facebook", "Kahiga@1234")

    def tearDown(self):
        '''
        teardown method that clean up after each test case has run
        '''
        User.user_details = []
        Credentials.app_details = []

    # test to check correct initialization of user
    def test_init(self):
        '''
        test to check whether user is initialized correctly
        '''
        self.assertEqual(self.new_user.fname, "Kamangu")
        self.assertEqual(self.new_user.sname, "Dam")
        self.assertEqual(self.new_user.password, "KA@1234")

        self.assertEqual(self.new_app.app, "Facebook")
        self.assertEqual(self.new_app.app_password, "Ak@1234")

    # test to check whether our user details have been saved
    def test_save_user(self):
        '''
        test that checks whether our user details have been saved
        '''
        self.new_user.save_user()
        self.assertEqual(len(User.user_details), 1)

    # deleting user
    def test_delete_user(self):
        '''
        test checks whether a user can delete their account
        '''
        self.new_user.save_user()
        test_user = User("Joseph", "Kahiga", "Kahiga@1234")
        test_user.save_user

        self.new_user.delete_account()
        self.assertEqual(len(User.user_details), 0)

    # test checking if user exists
    def test_user_exists(self):
        '''
        checks if user exists by password. returns a boolean if user doesn't exist
        '''
        self.new_user.save_user()
        test_user = User("Kahiga", "Testsecondname", "Kahiga@1234")
        test_user.save_user()

        user_exists = User.user_exist("Joseph")

        self.assertTrue(user_exists)

    # test that finds user by first_name
    def test_find_user_by_fname(self):
        '''
        test to find user by first name
        '''

        self.new_user.save_user()
        test_user = User("Joseph", "Kahiga", "Kahiga@1234")
        test_user.save_user()

        found_user = User.find_by_fname("Joseph")

        self.assertEqual(found_user.fname, test_user.fname)

    # test that displays users
    def display_user(self):
        '''
        Test that displays users
        '''
        self.assertEqual(User.display_user(), User.user_details)
示例#37
0
url = "https://sprint.tobiipro.com"
browser.get(url)

#Set max time for loading page in seconds
delay = 5

#Try to load page. If not done within delay, throw exception
try:
    email_element = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.NAME, 'email')))
    
except TimeoutException:
    print("The webpage {} did not load within {} seconds".format(url, delay))
    

#Import credentials from local file
myCredentials = Credentials()

#Wait until field is ready to be clickable
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.NAME, 'email')))

#Enter credentials into fields
email_element.send_keys(myCredentials.username)
password_element = browser.find_element_by_name('password')
password_element.send_keys(myCredentials.password)

#Click login
submit_button = browser.find_element_by_name('submit')
submit_button.click()

#Verify that the log in was sucessful by checking that the correct page name exist
assert "Tobii Pro Sprint" in browser.title
示例#38
0
 def setUp(self):
     self.newCredentials = Credentials("Instagram", "alex kimutai",
                                       "password12345")
def create_account(account, login, password, user):
    '''
    Function to add an existing account
    '''
    new_credential = Credentials(account, login, password, user)
    return new_credential
示例#40
0
 def test_display_credentials(self):
     self.assertEqual(Credentials.display_credentials(),
                      Credentials.credentials_list)
示例#41
0
class CredentialsOptions(optparse.OptionGroup):
    """Command line options for specifying credentials."""
    def __init__(self, parser):
        self.no_pass = False
        optparse.OptionGroup.__init__(self, parser, "Credentials Options")
        self.add_option("--simple-bind-dn", metavar="DN", action="callback",
                        callback=self._set_simple_bind_dn, type=str,
                        help="DN to use for a simple bind")
        self.add_option("--password", metavar="PASSWORD", action="callback",
                        help="Password", type=str, callback=self._set_password)
        self.add_option("-U", "--username", metavar="USERNAME", 
                        action="callback", type=str,
                        help="Username", callback=self._parse_username)
        self.add_option("-W", "--workgroup", metavar="WORKGROUP", 
                        action="callback", type=str,
                        help="Workgroup", callback=self._parse_workgroup)
        self.add_option("-N", "--no-pass", action="store_true",
                        help="Don't ask for a password")
        self.add_option("-k", "--kerberos", metavar="KERBEROS", 
                        action="callback", type=str,
                        help="Use Kerberos", callback=self._set_kerberos)
        self.creds = Credentials()

    def _parse_username(self, option, opt_str, arg, parser):
        self.creds.parse_string(arg)

    def _parse_workgroup(self, option, opt_str, arg, parser):
        self.creds.set_domain(arg)

    def _set_password(self, option, opt_str, arg, parser):
        self.creds.set_password(arg)

    def _set_kerberos(self, option, opt_str, arg, parser):
        if bool(arg) or arg.lower() == "yes":
            self.creds.set_kerberos_state(MUST_USE_KERBEROS)
        else:
            self.creds.set_kerberos_state(DONT_USE_KERBEROS)

    def _set_simple_bind_dn(self, option, opt_str, arg, parser):
        self.creds.set_bind_dn(arg)

    def get_credentials(self, lp):
        """Obtain the credentials set on the command-line.

        :param lp: Loadparm object to use.
        :return: Credentials object
        """
        self.creds.guess(lp)
        if not self.no_pass:
            self.creds.set_cmdline_callbacks()
        return self.creds
示例#42
0
def aanstuurderObvArgumenten(argumenten):
    ############## 1. parse credential-related flags ##############
    cr = Credentials()
    # print argumenten.__dict__
    if argumenten.worker == "dummy_login" or argumenten.worker == "dummy_logout":
        print "ik wil credentials ophalen voor spek en bonen"
        gebruikersnaam, wachtwoord = cr.dummy()

    else:
        if argumenten.credentials == "keyring":
            print "ik haal de credentials uit de keyring"
            gebruikersnaam, wachtwoord = cr.getset()

        elif argumenten.credentials == "forget":
            print "ik wil vergeten"
            cr.forget()
            exit(0)

        elif argumenten.credentials == "guest_mode":
            print "ik wil me anders voordoen dan ik ben"
            gebruikersnaam, wachtwoord = cr.guest()

    ############## 2. switch on communicator-related flags ##############
    if argumenten.communicator == "curses":
        print "ik wil vloeken"
        if os.name == "posix":
            co = communicator.CursesCommunicator()
        else:
            co = communicator.ColoramaCommunicator()

    elif argumenten.communicator == "android":
        print "ik wou dat ik een robot was"
        co = communicator.AndroidCommunicator()

    elif argumenten.communicator == "colortext":
        print "ik wil vrolijke kleuren"
        co = communicator.ColoramaCommunicator()

    elif argumenten.communicator == "plaintext":
        print "ik wil terug naar de basis"
        co = communicator.PlaintextCommunicator()

    elif argumenten.communicator == "dialog":
        print "ik wil fancy dialogs"
        if os.name == "posix":
            co = communicator.DialogCommunicator()
        else:
            co = communicator.ColoramaCommunicator()

    elif argumenten.communicator == "bubble":
        print "ik wil bellen blazen"
        if os.name == "posix":
            co = communicator.BubbleCommunicator()
        else:
            co = communicator.ColoramaCommunicator()

    elif argumenten.communicator == "summary":
        print "ik wil het mooie in de kleine dingen zien"
        co = communicator.SummaryCommunicator()

    elif argumenten.communicator == "quiet":
        print "ik wil zwijgen"
        co = communicator.QuietCommunicator()

    ############## 3. switch on login-type flags ##############
    if argumenten.worker == "login":
        print "ik wil inloggen"
        mainLoginprocedure(co, gebruikersnaam, wachtwoord)

    elif argumenten.worker == "force_login":
        print "ik moet en zal inloggen"
        mainForceerLoginprocedure(co, gebruikersnaam, wachtwoord)

    elif argumenten.worker == "logout":
        print "ik wil uitloggen"
        mainLoguitprocedure(co, gebruikersnaam, wachtwoord)

    elif argumenten.worker == "dummy_login":
        print "ik wil inloggen voor spek en bonen"
        mainLoginprocedure(co, gebruikersnaam, wachtwoord, dummy=True)

    elif argumenten.worker == "dummy_logout":
        print "ik wil uitloggen voor spek en bonen"
        mainLoguitprocedure(co, gebruikersnaam, wachtwoord, dummy=True)
def find_account(account):
    '''
    Function to find an account
    '''
    return Credentials.find_by_account(account)
示例#44
0
class Client(QtGui.QMainWindow):
    def __init__(self, *args):
        self.credentials_dialog = Credentials()
        self.email = ""
        self.password = ""
        self.verify_credentials()

        super(Client, self).__init__(*args)
        uic.loadUi('client.ui', self)

        self.publishers = {
                0: self.send_text,
                1: self.send_quote,
                2: self.send_chat,
                3: self.send_url,
                4: self.send_photo,
                5: self.send_video,
                6: self.send_audio}
        self.setWindowTitle(self.email)

    @QtCore.pyqtSlot()
    def on_photo_path_button_clicked(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Znajdź plik',
                    '/home')
        self.photo_path.setText(filename)

    @QtCore.pyqtSlot()
    def on_video_path_button_clicked(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Znajdź plik',
                    '/home', 'pliki wideo (*.asf *.asx *.avi *.divx *.dv *.dvx *.m4v *.mov *.mp4 *.mpeg *.mpg *.qt *.wmv *.3g2 *.3gp *.3ivx *.3vx)')
        self.video_path.setText(filename)

    @QtCore.pyqtSlot()
    def on_audio_path_button_clicked(self):
        filename = QtGui.QFileDialog.getOpenFileName(self, 'Znajdź plik',
                    '/home', 'pliki dźwiękowe (*.mp3 *.aiff *.aif)')
        self.audio_path.setText(filename)

    @QtCore.pyqtSlot()
    def on_publish_clicked(self):
        self.statusBar().showMessage(u'wysyłanie treści')
        result = self.publishers[self.tabs.currentIndex()]()
        self.show_status_message(result)

    def verify_credentials(self):
        self.credentials_dialog.exec_()
        self.email = self.credentials_dialog.email.text()
        self.password = self.credentials_dialog.password.text()
        if tumblr.validate_credentials(urlencode({'email': self.email,
                'password': self.password})) != 200:
            self.credentials_dialog.setWindowTitle(u'sprawdź poprawność danych')
            self.verify_credentials()

    def show_status_message(self, status):
        if status >= 200 and status < 300:
            self.statusBar().showMessage(u'treść opublikowana', 10000)
        elif status >= 400 and status < 500:
            self.statusBar().showMessage(u'błędne dane', 10000)
        elif status >= 500 and status < 600:
            self.statusBar().showMessage(u'błąd serwera', 10000)

    def send_text(self):
        params = urlencode({'email': self.email,
            'password': self.password,
            'type': 'regular',
            'title': self.regular_title.text().toLocal8Bit(),
            'body': self.regular_body.toPlainText().toLocal8Bit()})
        return tumblr.post_text(params, len(params)) 

    def send_quote(self):
        params = urlencode({'email': self.email,
            'password': self.password,
            'type': 'quote',
            'quote': self.quote_quote.toPlainText().toLocal8Bit(),
            'source': self.quote_source.toPlainText().toLocal8Bit()})
        return tumblr.post_text(params, len(params)) 

    def send_chat(self):
        params = urlencode({'email': self.email,
            'password': self.password,
            'type': 'conversation',
            'title': self.conversation_title.text().toLocal8Bit(),
            'conversation': self.conversation_conversation.toPlainText().toLocal8Bit()})
        return tumblr.post_text(params, len(params)) 

    def send_url(self):
        params = urlencode({'email': self.email,
            'password': self.password,
            'type': 'link',
            'name': self.link_name.text().toLocal8Bit(),
            'url': self.link_url.text().toLocal8Bit(),
            'description': self.link_description.toPlainText().toLocal8Bit()})
        return tumblr.post_text(params, len(params)) 

    def send_photo(self):
        params = urlencode({'email': self.email,
            'password': self.password,
            'type': 'photo',
            'data': open(self.photo_path.text()).read(),
            'caption': self.photo_caption.toPlainText().toLocal8Bit()})
        return tumblr.post_text(params, len(params)) 

    def send_video(self):
        params = urlencode({'email': self.email,
            'password': self.password,
            'type': 'video',
            'data': open(self.video_path.text()).read(),
            'caption': self.video_caption.toPlainText().toLocal8Bit()})
        return tumblr.post_text(params, len(params))

    def send_audio(self):
        params = urlencode({'email': self.email,
            'password': self.password,
            'type': 'audio',
            'data': open(self.audio_path.text()).read(),
            'caption': self.audio_caption.toPlainText().toLocal8Bit()})
        return tumblr.post_text(params, len(params))
示例#45
0
def create_credential(app_name,username, password):
    '''
    function to create a new credential
    '''
    new_credential = Credentials(app_name,username,password)
    return new_credential
示例#46
0
import tweepy
from credentials import Credentials
from datetime import date
from operator import itemgetter
import io

TEMPLATE_TSV = """{tweet_id}\t{tweet_created}\t{tweet_user}\t{tweet_text}\n"""
TEMPLATE_CSV = """{tweet_id},{tweet_created},{tweet_user},\"{tweet_text}\"\n"""

c = Credentials('config.json')

auth = tweepy.OAuthHandler(c.getConsumerKey(), c.getConsumerSecret())
auth.set_access_token(c.getAccessToken(), c.getAccessTokenSecret())

api = tweepy.API(auth)

l = []
hash_tag = 'xpb'
for tweet in tweepy.Cursor(api.user_timeline, screen_name=c.getScreenName()).items():
    if '#' + hash_tag in tweet.text:
        l.append({'tweet_id': tweet.id,
                  'tweet_created': tweet.created_at,
                  'tweet_user': tweet.user.screen_name.encode('UTF-8'),
                  'tweet_text': tweet.text.encode('UTF-8')
                  })

l = sorted(l, key=itemgetter('tweet_created'))

print(l[0:3])

out_file_name = 'output/tweets-' + hash_tag + '-' + str(date.today()) + '.csv'
示例#47
0
def save_credentials(Credentials):
    '''
    function to save credentials
    '''
    Credentials.save_credentials()
def generate_a_password():
    '''
    Function to generate a password for the user account
    '''
    return Credentials.generate_password()
示例#49
0
class TestCredentials(unittest.TestCase):

    def setUp(self):
        self._cred_dict = {
            'lol': 42
        }
        self.loader = Credentials([FakeBackend(self._cred_dict)])

    def test_require(self):
        creds = self.loader.require(['lol'])

        self.assertTrue(getattr(creds, 'lol', False),
                        'Creds should contain "lol"')
        self.assertEqual(creds.lol, 42)

    def test_require_missing_key(self):
        try:
            self.loader.require(['lol', 'missing'])
        except KeyError:
            pass
        else:
            assert False, "Key was missing KeyError should have been thrown."

    def test_load(self):
        cred = self.loader.load('lol')

        self.assertEqual(cred, 42)

    def test_load_missing_key(self):
        try:
            self.loader.load('missing')
        except KeyError:
            pass
        else:
            assert False, "Key was missing KeyError should have been thrown."

    def test_add_backend(self):
        other_fake_backend = FakeBackend({'lol2': '43'})
        self.loader.add_backend(other_fake_backend)

        self.assertEqual(len(self.loader._backends), 2)

    def test_multiple_backends(self):
        other_fake_backend = FakeBackend({'lol2': 43})
        self.loader.add_backend(other_fake_backend)

        cred = self.loader.load('lol2')
        self.assertEqual(cred, 43)

    def test_key_in_muliple_backends(self):
        other_fake_backend = FakeBackend({'lol': 43})
        self.loader.add_backend(other_fake_backend)

        cred = self.loader.load('lol')
        self.assertEqual(cred, 42)
def display_credential():
    '''
    Function to return all the saved credentials
    '''
    return Credentials.display_credentials()
示例#51
0
文件: getopt.py 项目: endisd/samba
class CredentialsOptionsDouble(CredentialsOptions):
    """Command line options for specifying credentials of two servers."""
    def __init__(self, parser):
        CredentialsOptions.__init__(self, parser)
        self.no_pass2 = False
        self.add_option("--simple-bind-dn2", metavar="DN2", action="callback",
                        callback=self._set_simple_bind_dn2, type=str,
                        help="DN to use for a simple bind")
        self.add_option("--password2", metavar="PASSWORD2", action="callback",
                        help="Password", type=str, callback=self._set_password2)
        self.add_option("--username2", metavar="USERNAME2",
                        action="callback", type=str,
                        help="Username for second server", callback=self._parse_username2)
        self.add_option("--workgroup2", metavar="WORKGROUP2",
                        action="callback", type=str,
                        help="Workgroup for second server", callback=self._parse_workgroup2)
        self.add_option("--no-pass2", action="store_true",
                        help="Don't ask for a password for the second server")
        self.add_option("--kerberos2", metavar="KERBEROS2",
                        action="callback", type=str,
                        help="Use Kerberos", callback=self._set_kerberos2)
        self.creds2 = Credentials()

    def _parse_username2(self, option, opt_str, arg, parser):
        self.creds2.parse_string(arg)

    def _parse_workgroup2(self, option, opt_str, arg, parser):
        self.creds2.set_domain(arg)

    def _set_password2(self, option, opt_str, arg, parser):
        self.creds2.set_password(arg)

    def _set_kerberos2(self, option, opt_str, arg, parser):
        if bool(arg) or arg.lower() == "yes":
            self.creds2.set_kerberos_state(MUST_USE_KERBEROS)
        else:
            self.creds2.set_kerberos_state(DONT_USE_KERBEROS)

    def _set_simple_bind_dn2(self, option, opt_str, arg, parser):
        self.creds2.set_bind_dn(arg)

    def get_credentials2(self, lp):
        """Obtain the credentials set on the command-line.

        :param lp: Loadparm object to use.
        :return: Credentials object
        """
        self.creds2.guess(lp)
        if not self.no_pass2:
            self.creds2.set_cmdline_callbacks()
        return self.creds2