示例#1
0
def create():
    if request.method == 'POST':
        content = request.get_json(silent=True)
        fullName = cgi.escape(content['username'])
        className = cgi.escape(content['classname'])

        hashids = Hashids(salt=settings.HASHID_SALT,min_length=6)
        increment()
        count = get_count()
        hashid = hashids.encode(count)

        courseId = DEFAULT_COURSE_PREFIX + hashid
        userId = request.cookies.get('remote_userid') if 'remote_userid' in request.cookies else generate_user_id()
        userColor = request.cookies.get('remote_usercolor') if 'remote_usercolor' in request.cookies else generate_color()

        host = app.config.get('host')
        resp = make_response(hashid)

        # Add course to database
        key = courseId
        course = Course.get_or_insert(key, courseId=courseId, teacherName=fullName)
        course.put()

        # Add teacher to course

        # Create OpenTok session
        opentok_sdk = OpenTok(OPENTOK_API_KEY, OPENTOK_API_SECRET)
        # use tokbox server to route media streams;
        # if you want to use p2p - change media_mode to MediaModes.relayed
        opentok_session = opentok_sdk.create_session(media_mode = MediaModes.routed)
        opentok_token = opentok_sdk.generate_token(opentok_session.session_id)
        
        key = courseId + userId
        user = Student.get_or_insert(key, 
            courseId = courseId,
            studentId = userId,
            fullName = fullName,
            color = userColor,
            role = 'TEACHER',
            opentokSessionId = opentok_session.session_id,
            opentokToken = opentok_token
        )
        user.put()

        # Set user cookies (teacher role)
        auth = json.loads(request.cookies.get('remote_auth')) if 'remote_auth' in request.cookies else {}
        auth[hashid] = {
            'role': 'Instructor',
            'opentok_api_key': OPENTOK_API_KEY,
            'opentok_session_id': user.opentokSessionId,
            'opentok_token': user.opentokToken
        }
        resp.set_cookie('remote_userfullname', fullName)
        resp.set_cookie('remote_auth', json.dumps(auth))
        resp.set_cookie('remote_userid', userId)
        resp.set_cookie('remote_usercolor', userColor)
        #resp.set_cookie('remote_userinitials', userInitials)

        return resp
    return redirect('/main#/create')
示例#2
0
def hello():
    if counter.getCount("counter") == 5:
        counter.reset("counter")
        return "y"
    else:
        counter.increment("counter")
        return "n"
示例#3
0
 def add(jid):
   counter.increment('total')
   shard = counter.get_count('total') % config.CRON_NUM
   google_user = GoogleUser(key_name=jid, shard=shard, last_update=int(time.time()))
   google_user.jid = jid
   Db.set_datastore(google_user)
   return google_user
示例#4
0
    def post(self):
        upload_files = self.get_uploads('file')  # 'file' is file upload field in the form
	if not upload_files:
		self.redirect('/failed/nofile/')
		return
        blob_info = upload_files[0]
	key = blob_info.key()
	if blob_info.size > 1048576:
		blob_info.delete()
	        self.redirect('/failed/sizeerror/%s' % blob_info.filename)
		return
	blob_reader = blobstore.BlobReader(key)
	magic = blob_reader.read(50)
	if magic[0:3] != "MPQ" or not "StarCraft II replay" in magic:
		blob_info.delete()
	        self.redirect('/failed/typeerror/%s' % blob_info.filename)
		return


	replayid = counter_as_string('principal')
	increment('principal')

	m = md5()
	m.update(blob_reader.read(blob_info.size))
	replaymd5 = m.hexdigest()
	
	replay = Replay(replayid=replayid, replaymd5 = replaymd5, blobinfo = str(key), ip=self.request.remote_addr)
	replay.put()

        self.redirect('/success/%s' % replayid)
示例#5
0
    def post(self):
        upload_files = self.get_uploads(
            'file')  # 'file' is file upload field in the form
        if not upload_files:
            self.redirect('/failed/nofile/')
            return
        blob_info = upload_files[0]
        key = blob_info.key()
        if blob_info.size > 1048576:
            blob_info.delete()
            self.redirect('/failed/sizeerror/%s' % blob_info.filename)
            return
        blob_reader = blobstore.BlobReader(key)
        magic = blob_reader.read(50)
        if magic[0:3] != "MPQ" or not "StarCraft II replay" in magic:
            blob_info.delete()
            self.redirect('/failed/typeerror/%s' % blob_info.filename)
            return

        replayid = counter_as_string('principal')
        increment('principal')

        m = md5()
        m.update(blob_reader.read(blob_info.size))
        replaymd5 = m.hexdigest()

        replay = Replay(replayid=replayid,
                        replaymd5=replaymd5,
                        blobinfo=str(key),
                        ip=self.request.remote_addr)
        replay.put()

        self.redirect('/success/%s' % replayid)
def main():
    print("Parent: Count is {}".format(counter.get_count()))
    counter.increment()

    print("Child 1: Count is {}".format(child1.get_count()))

    print("Child 2: Count is {}".format(child2.get_count()))
示例#7
0
 def add(jid):
     counter.increment('total')
     shard = counter.get_count('total') % config.CRON_NUM
     google_user = GoogleUser(key_name=jid,
                              shard=shard,
                              last_update=int(time.time()))
     google_user.jid = jid
     Db.set_datastore(google_user)
     return google_user
示例#8
0
    def get(self, resource, extension):
        query = Replay.all()
        query.filter('replayid =', resource)

        results = query.fetch(1)

        if results:
            result = results[0]
            blob_info = blobstore.BlobInfo.get(result.blobinfo)
            increment(resource)
            self.send_blob(blob_info)
            return
示例#9
0
	def get(self, resource, extension):
		query = Replay.all()
		query.filter('replayid =', resource)

		results = query.fetch(1)

		if results:
			result = results[0]
			blob_info = blobstore.BlobInfo.get(result.blobinfo)
			increment(resource)
			self.send_blob(blob_info)
			return
示例#10
0
 def test1(self):
   name = "foo"
   assert counter.get_count(name) == 0
 
   counter.increment(name)
   assert counter.get_count(name) == 1
 
   counter.increment(name, 3)
   assert counter.get_count(name) == 4
 
   counter.set_value(name, 2)
   assert counter.get_count(name) == 2
示例#11
0
    def get_context(self, counter_name):

        """
        Increment and return the specified counter's value
        """

        # increment the specified counter
        counter.increment(counter_name)
        # get the counter value
        hit_count = counter.get_count(counter_name)
        # return the counter value as JSON object
        return {'count': hit_count}
示例#12
0
    def set_or_create(self, model, id, parent_key=None):
        u = current_user(required=True)
        if model == "users":
            if not (id == "me" or id == "" or id == u):
                raise AppError(
                    "Id must be the current " +
                    "user_id or me. User {} tried to modify user {}.".format(
                        u, id))
            id = u
            cls = users
        else:
            cls = type(model.lower(), (ScopedExpando, ), {})
        data = parse_body(self)
        key = parse_id(id, model, data.get("Id"))
        clean_data(data)
        validate(cls.__name__, data)
        already_exists = False
        if key:
            old_model = key.get()
            if old_model:
                if model != "users" and not old_model.can_write(u):
                    raise AppError("You do not have sufficient privileges.")
                already_exists = True

        # TODO: might want to add this post creation since you already have the key
        if parent_key:
            data[parent_key.kind()] = parent_key.urlsafe()

        m = reflective_create(cls, data)
        if key:
            m.key = key
        if model != "users":
            if len(m.owners) == 0:
                m.owners.append(u)
        m.put()
        # increment count
        if not already_exists and store_metadata:
            increment(model)
        # update indexes
        search.put(m)
        redirect = self.request.get("redirect")
        if redirect:
            self.redirect(redirect)
            # Raising break error to avoid header and body writes from @as_json decorator since we override as a redirect
            raise BreakError()
        return m.to_dict()
示例#13
0
文件: __init__.py 项目: d2m/tailbone
  def set_or_create(self, model, id, parent_key=None):
    u = current_user(required=True)
    if model == "users":
      if not (id == "me" or id == "" or id == u):
        raise AppError("Id must be the current " +
                       "user_id or me. User {} tried to modify user {}.".format(u, id))
      id = u
      cls = users
    else:
      cls = type(model.lower(), (ScopedExpando,), {})
    data = parse_body(self)
    key = parse_id(id, model, data.get("Id"))
    clean_data(data)
    validate(cls.__name__, data)
    already_exists = False
    if key:
      old_model = key.get()
      if old_model:
        if model != "users" and not old_model.can_write(u):
          raise AppError("You do not have sufficient privileges.")
        already_exists = True

    # TODO: might want to add this post creation since you already have the key
    if parent_key:
      data[parent_key.kind()] = parent_key.urlsafe()

    m = reflective_create(cls, data)
    if key:
      m.key = key
    if model != "users":
      if len(m.owners) == 0:
        m.owners.append(u)
    m.put()
    # increment count
    if not already_exists and store_metadata:
      increment(model)
    # update indexes
    search.put(m)
    redirect = self.request.get("redirect")
    if redirect:
      self.redirect(redirect)
      # Raising break error to avoid header and body writes from @as_json decorator since we override as a redirect
      raise BreakError()
    return m.to_dict()
 def get(self):
     value = int(self.request.get('id'))
     cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
     voteNumber = 0;
     if cookie:
         if "LastVote" in cookie:
             if int(cookie["LastVote"].value) != 0:
                 voteNumber = int(cookie["LastVote"].value);
                 stringOfCounter = 'IdeaWIVG_' + str(value);
                 stringOfCounterD = 'IdeaWIVG_' + str(voteNumber) + 'D';
                 counter.increment(stringOfCounter)
                 counter.increment(stringOfCounterD)
             else:
                 stringOfCounter = 'IdeaWIVG_' + str(value);
                 counter.increment(stringOfCounter)
         else:
             stringOfCounter = 'IdeaWIVG_' + str(value);
             counter.increment(stringOfCounter)
     NameOfVoted = "";
     if (value ==1):
         NameOfVoted  = "My Eyes"
     elif (value ==2):
         NameOfVoted  = "Furball Fury"
     elif (value ==3):
         NameOfVoted  = "Lux"
     elif (value ==4):
         NameOfVoted  = "Air Rocky"
     elif (value ==5):
         NameOfVoted  =  "Afterlife Empire"
     template = JINJA_ENVIRONMENT.get_template('WIVGVote.jinja')
     template_values = {
         "voteName": NameOfVoted,
         "voteValue": value,
         "Amount1":counter.get_count('IdeaWIVG_1')-counter.get_count('IdeaWIVG_1D'),
         "Amount2":counter.get_count('IdeaWIVG_2')-counter.get_count('IdeaWIVG_2D'),
         "Amount3":counter.get_count('IdeaWIVG_3')-counter.get_count('IdeaWIVG_3D'),
         "Amount4":counter.get_count('IdeaWIVG_4')-counter.get_count('IdeaWIVG_4D'),
         "Amount5":counter.get_count('IdeaWIVG_5')-counter.get_count('IdeaWIVG_5D'),
     }
     self.response.out.write(template.render(template_values))
import counter

counter.increment()


def get_count():
    try:
        return counter.get_count()
    except NameError:
        return 0
示例#16
0
    def post(self):
        user = users.get_current_user()
        if user:
            submission =  Idea_VideoGameW1.get(Idea_VideoGameW1_key(user.user_id()))
            if (submission==None):
                counter.increment('IdeaWIVG1')
                submission = Idea_VideoGameW1(key=Idea_VideoGameW1_key(user.user_id()))
                submission.put()
                quickGet = Idea_QuickGet(key=Idea_QuickGet_key(counter.get_count('IdeaWIVG1')))
                quickGet.link = submission
                quickGet.put()
            submission.name=self.request.get('name')
            submission.tagline=self.request.get('tagline')
            submission.genres=self.request.get('genres')
            submission.describe=self.request.get('describe')
            submission.original=self.request.get('original')
            submission.look=self.request.get('look')
            submission.namePerson=self.request.get('namePerson')
            submission.who=self.request.get('who')
            submission.email=self.request.get('email')
            submission.additionalInfo=self.request.get('additionalInfo')
           
            
            submission.residenceStatus=self.request.get('residenceStatus')
            submission.legal1=False;
            submission.legal2=False;
            submission.legal3=False;
            submission.legal4=False;
            submission.review = False;
            submission.comment = False;
            submission.visible = False;
            
            a = ''
            b = ''
            c = ''
            d = ''
            e = ''
            f = ''
            y = ''
            z = True
            
            
            
            if self.request.get('legal1'):
                submission.legal1 = True;
                a = 'checked'
            if self.request.get('legal2'):
                b = 'checked'
                submission.legal2 = True;
            if self.request.get('legal3'):
                c = 'checked'
                submission.legal3 = True;
            if self.request.get('review'):
                d = 'checked'
                submission.review = True;
            if self.request.get('comment'):
                e = 'checked'
                submission.comment = True;
            if self.request.get('showIt'):
                f = 'checked'
                submission.visible = True
            if self.request.get('legal4'):
                y = 'checked'
                submission.visible = True

            
            

            
            
            submission.put()
            template = JINJA_ENVIRONMENT.get_template('ideaWIVG.jinja')
           

            template_values = {
            "name": submission.name,
            "namePerson":submission.namePerson,
            "tagline": submission.tagline,
            "genres": submission.genres,
            "describe": submission.describe,
            "original": submission.original,
            "look": submission.look,
            "who": submission.who,
            "email": submission.email,
            "additionalInfo": submission.additionalInfo,
            "residenceStatus": submission.residenceStatus,
            "legal1": a,
            "legal2": b,
            "legal3": c,
            "review": d,
            "legal4": y,
            "comment": e,
            "showIt": f,
            "justSaved":z,

            }
            self.response.out.write(template.render(template_values))
示例#17
0
def run():
    while True:
        r = requests.get(url)
        if r.text == "y":
            counter.increment("ycounter")
示例#18
0
 def get(self):
     user = users.get_current_user()
     if user:
         submission =  Idea_VideoGameW1.get(Idea_VideoGameW1_key(user.user_id()))
         template = JINJA_ENVIRONMENT.get_template('ideaWIVG.jinja')
         if (submission==None):
             counter.increment('IdeaWIVG1')
             
             submission = Idea_VideoGameW1(key=Idea_VideoGameW1_key(user.user_id()))
             submission.put()
             quickGet = Idea_QuickGet(key=Idea_QuickGet_key(counter.get_count('IdeaWIVG1')))
             quickGet.link = submission
             quickGet.put()
        
         a = ''
         b = ''
         c = ''
         d = ''
         e = ''
         f = ''
         z = False
         y = False
         if submission.legal1:
             a='checked'
         if submission.legal2:
             b='checked'
         if submission.legal3:
             c='checked'
         if submission.review:
             d='checked'
         if submission.comment:
             e='checked'
         if submission.visible:
             f='checked'
         if submission.visible:
             y='checked'
         template_values = {
         "name": submission.name,
         "namePerson":submission.namePerson,
         "tagline": submission.tagline,
         "genres": submission.genres,
         "describe": submission.describe,
         "original": submission.original,
         "look": submission.look,
         "who": submission.who,
         "email": submission.email,
         "additionalInfo": submission.additionalInfo,
         "residenceStatus": submission.residenceStatus,
         "legal1": a,
         "legal2": b,
         "legal3": c,
         "review": d,
         "legal4": y,
         "comment": e,
         "showIt": f,
         "justSaved":z,
         
         }
         
         
         self.response.out.write(template.render(template_values))
     
     else:
         url = '/submitIdea'
         self.response.out.write('''<meta http-equiv="refresh" content="0; url=%s" />''' % users.create_login_url(url));
示例#19
0
文件: app.py 项目: haldun/optimyser2
 def get(self):
   selected = self.get_selected()
   if selected is None:
     return
   counter.increment('%s:%s:conversion' % (self.experiment.key().name(), selected))
   self.write('1')
示例#20
0
def increment(mood):
    if mood:
        counter.increment("smile_count")
    else:
        counter.increment("cry_count")
示例#21
0
def generate_user_id():
    hashids = Hashids(salt=settings.HASHID_SALT, min_length=6)
    increment()
    count = get_count()
    hashid = hashids.encode(count)
    return hashid
示例#22
0
      private=True
    channelinstance=Channel(name=channel,private=private)
    channelinstance.put()
    logging.info('New channel %s' % (channel))
                                           
  # 3. tarkista onko url jo olemassa channel-tasolla
  channelurlquery=ChannelUrl.query(ChannelUrl.url==urlinstance.key, ChannelUrl.channel==channelinstance.key)
  channelurlinstance=channelurlquery.get()
  if not channelurlinstance:
    l=list(string.ascii_uppercase)
    l.append('Z')

    DEFAULT_COUNTER_NAME=chr(now.isocalendar()[0]-2010+65)+l[(now.isocalendar()[1]-1)/2]
    #logging.debug('DEFAULT_COUNTER_NAME: %s' % (DEFAULT_COUNTER_NAME))

    counter.increment(DEFAULT_COUNTER_NAME)
    key_name=DEFAULT_COUNTER_NAME+str(counter.get_count(DEFAULT_COUNTER_NAME))
    #logging.debug('key_name %s' % (key_name))

    channelurlinstance=ChannelUrl(id=key_name,channel=channelinstance.key,url=urlinstance.key)
    channelurlinstance.put()
    #logging.debug('New channelurl %s/%s' % (channel,url))
  else:
    #logging.info('OLDIE! %s %s' % (channelurlinstance.channel.name,channelurlinstance.url.url))
    logging.info('Old channelurl %s %s' % (channel,url))
    old_url=True
    old_post=Post.query(Post.channelurl==channelurlinstance.key).order(Post.date).get()
    try:
      old_date=old_post.date.strftime("%d.%m.%y %H:%M")
    except:
      try:
示例#23
0
 def increment_count():
   return counter.increment('Patient')
    def process_task(self, target, command, args):

        if 'algorithm' in self._shared_settings and self._shared_settings[
                'algorithm']:
            algorithm = self._shared_settings['algorithm']
        else:
            algorithm = 'naive'

        logging.info("SUBSTART\t%s\t%s\t%s\t%s\t%s" %
                     (datetime.utcnow(), self._shared_settings['targets_in'],
                      target[0], command, algorithm))

        MAX_THREADS = 15
        sslVersionDict = {
            'sslv2': SSLV2,
            'sslv3': SSLV3,
            'tlsv1': TLSV1,
            'tlsv1_1': TLSV1_1,
            'tlsv1_2': TLSV1_2
        }

        result_dicts = {
            'preferredCipherSuite': {},
            'acceptedCipherSuites': {},
            'rejectedCipherSuites': {},
            'errors': {}
        }

        try:
            sslVersion = sslVersionDict[command]
        except KeyError:
            raise Exception("PluginOpenSSLCipherSuites: Unknown command.")

        # Get the list of available cipher suites for the given ssl version
        sslClient = SslClient(sslVersion=sslVersion)
        sslClient.set_cipher_list('ALL:COMPLEMENTOFALL')
        cipher_list = sslClient.get_cipher_list()

        NB_THREADS = min(len(cipher_list),
                         MAX_THREADS)  # One thread per cipher

        # Create a thread pool
        thread_pool = ThreadPool()
        # First add the "pref" job to only execute it once
        # Scan for the preferred cipher suite
        if algorithm != 'connopt':
            thread_pool.add_job((self._pref_ciphersuite, (target, sslVersion)))

        log_round_counter = 0

        while (len(result_dicts['acceptedCipherSuites']) +
               len(result_dicts['rejectedCipherSuites']) +
               len(result_dicts['errors']) < len(cipher_list)):

            log_round_counter += 1

            new_jobs = self._calculate_jobs(sslVersion, cipher_list,
                                            result_dicts, algorithm, target[2])
            for job in new_jobs:
                thread_pool.add_job(
                    (self._test_ciphersuite, (target, sslVersion, job)))

            # logging.debug("Adding following jobs:\n%s" % pprint.pformat(new_jobs))
            # logging.debug("%s: round=%d, new_jobs=%d, algorithm=%s" % (sslVersion,
            #                                                           log_round_counter,
            #                                                           len(new_jobs),
            #                                                           algorithm))

            # Start processing the jobs
            thread_pool.start(NB_THREADS)

            # Store the results as they come
            for completed_job in thread_pool.get_result():
                (job, results) = completed_job
                for result in results:
                    (result_type, ssl_cipher, keysize, dh_infos, msg) = result
                    (result_dicts[result_type])[ssl_cipher] = (msg, keysize,
                                                               dh_infos)

            # Store thread pool errors
            for failed_job in thread_pool.get_error():
                (job, exception) = failed_job
                # job[1][2] is a list of cipher suites now
                ssl_ciphers = job[1][2]
                error_msg = str(
                    exception.__class__.__name__) + ' - ' + str(exception)
                for ssl_cipher in ssl_ciphers:
                    result_dicts['errors'][ssl_cipher] = (error_msg, None,
                                                          None)

            thread_pool.join()
            # Reset thread pool
            thread_pool = ThreadPool()

            # logging.debug("ciphers total %d results a: %d, r: %d, e: %d after %d connections" % (
            #    len(cipher_list),
            #    len(result_dicts['acceptedCipherSuites']),
            #    len(result_dicts['rejectedCipherSuites']),
            #    len(result_dicts['errors']),
            #    self.log_connection_counter))

        timedelta = datetime.now() - self.log_starttime
        logging.info("RESULT\t%s\t%s\t%s" % (target[0], command, ",".join(
            stats.get_pattern_for_result_dict(sslVersion, result_dicts))))
        logging.info("SUBEND\t%s\t%s\t%s\t%s\t%s\t%s\t%s" %
                     (datetime.utcnow(), self._shared_settings['targets_in'],
                      target[0], command, algorithm, timedelta.total_seconds(),
                      self.log_connection_counter))

        increment(self.log_connection_counter)

        # Generate results
        return PluginBase.PluginResult(
            self._generate_text_output(result_dicts, command),
            self._generate_xml_output(result_dicts, command))
示例#25
0
 def increment_count():
   return counter.increment('Visit')