示例#1
0
 def get_or_create(cls,user=None):
     if not user:
         user = users.get_current_user()
     if not user:
         raise Exception('not logged in - cannot get or create TickUser')
     existing = cls.all().filter('all_users = ',user).get()
     if not existing:
         invitations = None
         if not users.is_current_user_admin():
             invitations = Invitation.all().filter('email_address =',user.email().lower()).fetch(1000)
         if users.is_current_user_admin() or invitations:
             existing = cls(
                 tick_name       = user.nickname(),
                 email_address   = user.email(),
                 all_users       = [user],
                 all_user_ids    = [user.user_id()],
                 )
             existing.put()
             # add inviters as followers
             if invitations:
                 from follow import Follow
                 for invite in invitations:
                     Follow.add_follower(existing,invite.inviter)
             # add default lists
             from ticklist import TickList
             from setlist import SetList
             TickList.create_list('Suggestions for Tick','public')
             getting_started = SetList.all(keys_only=True).filter('name =','getting started with tick').get()
             if getting_started:
                 TickList.create_from_setlist('Getting Started',getting_started.id())
             TickUserStat.generate_stats(existing) # TODO: create a new stats infrastructure
         else:
             raise NotInvitedError('not invited')
     return existing
示例#2
0
    def post(self):
        self.response.headers['Content-Type'] = 'text/html'
        if self.request.get('button') == 'Follow':

            id = self.request.get('id')
            following_user_key = ndb.Key('MyUser', id)
            following_user = following_user_key.get()
            his_follower = Follow.query(Follow.user == following_user)

            user = users.get_current_user()
            my_user_key = ndb.Key('MyUser', user.user_id())
            my_user = my_user_key.get()
            my_following = Follow.query(Follow.user == my_user)

            for i in his_follower:
                for j in i.followers:
                    if j.user_id != my_user.user_id:
                        i.followers.append(my_user)
                        i.put()
            for i in my_following:
                for j in i.following:
                    if j.user_id != following_user:
                        i.following.append(following_user)
                        i.put()

            self.redirect('/')

        if self.request.get('button') == 'Unfollow':

            id = self.request.get('id')
            following_user_key = ndb.Key('MyUser', id)
            following_user = following_user_key.get()
            his_follower = Follow.query(Follow.user == following_user)

            user = users.get_current_user()
            my_user_key = ndb.Key('MyUser', user.user_id())
            my_user = my_user_key.get()
            my_following = Follow.query(Follow.user == my_user)

            for i in his_follower:
                for j in i.followers:
                    if j.email_address == my_user.email_address:
                        i.followers.remove(j)
                i.put()
            for i in my_following:
                for j in i.following:
                    if j.email_address == following_user.email_address:
                        i.following.remove(j)
                i.put()

            self.redirect('/')
        if self.request.get('button') == 'Return to main page':
            self.redirect('/')
示例#3
0
文件: bill.py 项目: shenyk/possum
 def send_in_the_kitchen(self):
     """We send the first category available to the kitchen.
     """
     if self.category_to_follow:
         follow = Follow(category=self.category_to_follow)
         follow.save()
         todolist = []
         heure = follow.date.strftime("%H:%M")
         # heure = datetime.datetime.now().strftime("%H:%M")
         todolist.append("[%s] Table %s (%s couv.)" % (heure, self.table,
                                                       self.couverts))
         todolist.append(">>> envoye %s" % follow.category.nom)
         todolist.append(" ")
         nb_products_sent = self.produits.filter(sent=True).count()
         # liste des produits qui doivent etre envoyés en cuisine
         products = []
         for product in self.produits.iterator():
             if product.est_un_menu():
                 # on veut les produits du menu
                 for sub in product.contient.iterator():
                     if not sub.sent and sub.made_with == follow.category:
                         sub.sent = True
                         products.append(sub)
                         follow.produits.add(sub)
                         sub.save()
             else:
                 if not product.sent \
                    and product.made_with == follow.category:
                     product.sent = True
                     products.append(product)
                     follow.produits.add(product)
                     product.save()
         if nb_products_sent == 0:
             # on crée le ticket avec la liste des produits et
             # des suites
             products = self.get_first_todolist_for_kitchen()
             if products:
                 todolist += products
         else:
             products.sort()
             for product in products:
                 todolist.append(product)
         for printer in Printer.objects.filter(kitchen=True):
             result = printer.regroup_list_and_print(todolist,
                                                     "kitchen-%s-%s" % (
                                                     self.id, 
                                                     follow.category.id))
             if not result:
                 return False
         follow.save()
         self.following.add(follow)
         self.something_for_the_kitchen()
         return True
示例#4
0
def checkLog(logFile):
    log = Follow(logFile)  #1.log
    while 1:
        time.sleep(1)
        #print log
        log_re = re.compile(
            '^(?P<client_ip>.*?) (?P<host>.*?) (?P<user>.*?) \[(?P<date>.*?)\] "(?P<method>[\w]+) (?P<uri>.*?) (?P<protocol>HTTP/1.1)" (?P<status>200) (?P<body_size>\d+) "(?P<http_referer>.*?)" "(?P<http_user_agent>.*?)" "(?P<http_accept_language>.*?)" "(?P<request_time>.*?)" "(?P<upstream_response_time>.*?)" "(?P<upstream_addr>.*?)" "(?P<upstream_status>.*?)"'
        )

        line = log.readline()
        print line
        if line:
            log_m = log_re.match(line)
            print log_m.groupdict()
示例#5
0
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'

        user = users.get_current_user()  #boolean
        id = self.request.get('id')
        myuser_key = ndb.Key('MyUser', id)
        myuser = myuser_key.get()

        my_follow = Follow.query()

        my_post = MyPost.query(
            MyPost.creator == myuser).order(-MyPost.creation_time)

        list_comment = ListComment.query()

        template_values = {
            'user': user,
            'my_post': my_post,
            'my_follow': my_follow,
            'myuser': myuser,
            'id': id,
            'list_comment': list_comment,
        }

        template = JINJA_ENVIRONMENT.get_template('myprofil.html')
        self.response.write(template.render(template_values))
示例#6
0
 def fanout(self):
     from follow import Follow, FollowIndex    
     follower_ids_set = set(self.actor.all_user_ids) # the owner should be able to see this activity
     follower_ids_set.update(set(self.extra_recipients)) # the extra recipients should be able to see it too
     if not hasattr(self.target,'sharing') or self.target.sharing == 'public':
         # if the target is public, so should all his/her followers
         follower_keys = Follow.all(keys_only=True).ancestor(self.actor).fetch(1000)
         for key in follower_keys:
             index_num = 0
             for ind in FollowIndex.all().ancestor(key).fetch(1000):
                 follower_ids_set.update(set(ind.view_permissions))
         if not self.other or not hasattr(self.other,'sharing') or self.other.sharing == 'public':
             # both target and other are public, the activity should be public too
             follower_ids_set.add('public')
     # create an activity index for each 5000 users that can see the activity
     max_list_size = datastore._MAX_INDEXED_PROPERTIES - 1        
     index_num = 1
     act_ind_ents = []
     follower_ids = list(follower_ids_set)
     while (index_num-1)*max_list_size < len(follower_ids):
         date_key = ActivityIndex.gen_date_key(self.creation_date,self.actor.key().id())
         new_act_ind = ActivityIndex(
             parent=self,
             date_key=date_key,
             edit_permissions=[],
             view_permissions=follower_ids[(index_num-1)*max_list_size:index_num*max_list_size])
         act_ind_ents.append(new_act_ind)
         index_num += 1
     db.put(act_ind_ents)
示例#7
0
    def follow(self, user, incident):
        follow = Follow(user, incident)
        self.database.insert_follow(follow)
        self.create_notification(
            incident, user.forename + ' ' + user.surname +
            ' is now following ' + incident.title)

        self.database.commit()
示例#8
0
    def removeLinkedPoint(self, unlinkPointRoot, linkType, user):
        if user:
            theRoot = self.key.parent().get()
            newPoint = Point(parent=theRoot.key)  # All versions ancestors of the caseRoot
            newPoint.authorName = user.name
            newPoint.authorURL = user.url
            newPoint.supportingPointsLastChange = list(self.supportingPointsLastChange)
            newPoint.supportingPointsRoots = list(self.supportingPointsRoots)
            newPoint.counterPointsRoots = list(self.counterPointsRoots)
            newPoint.counterPointsLastChange = list(self.counterPointsLastChange)
            newPoint.childPointsRoots = list(self.childPointsRoots)
            newPoint.childPointsLastChange = list(self.childPointsLastChange)
            
            newPoint.sources = list(self.sources)

            try:
                newPoint.removeLink(unlinkPointRoot, linkType)
            except Exception as e:
                logging.info(
                    'Could not remove supporting point from list: ' + str(e))
            newPoint.title = self.title
            newPoint.nodetype = self.nodetype            
            newPoint.content = self.content
            newPoint.summaryText = self.summaryText
            newPoint.version = self.version + 1
            newPoint.upVotes = self.upVotes
            newPoint.downVotes = self.downVotes
            newPoint.voteTotal = self.voteTotal  
            newPoint.ribbonTotal = self.ribbonTotal
            newPoint.imageURL = self.imageURL
            newPoint.imageDescription = self.imageDescription
            newPoint.imageAuthor = self.imageAuthor
            newPoint.url = self.url
            self.current = False
            newPoint.current = True
            self.put()
            newPoint.put()
            theRoot.current = newPoint.key
            theRoot.put()
            
            Follow.createFollow(user.key, theRoot.key, "edited")
            Point.addNotificationTask(theRoot.key, user.key, "unlinked a %s point from" % linkType)
            
            return newPoint
        else:
            return None
示例#9
0
def ticker(portfolio, logfile, fmt):
    portfolio = report.read_portfolio_4(portfolio)
    lines = Follow(logfile)
    rows = parse_stock_data(lines)
    rows = filter_symbols(rows, portfolio)
    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['name', 'price', 'shares'])
    for rowdata in rows:
        formatter.row(rowdata.values())
示例#10
0
def main():
    # Set up the authentication!
    auth = OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
    api = API(auth)
    ratelimit = api.rate_limit_status()
    # Create a user and public stream
    u = UserStreamListener()
    userstream = Stream(auth, u)

    p = PublicStreamListener()
    publicstream = Stream(auth, p)

    # Show my followers
    f = Follow(auth)
    print f.my_followers()

    print "Streaming started..."
    publicstream.filter(track=TRACKING_TERMS)
示例#11
0
 def base_view_permissions(self):
     # TODO: in future, this will create a list including: the owner, friends, and 'public' if required
     output = list(self.owner.all_user_ids) #[TickUser.self.__class__.owner.get_value_for_datastore(self)]
     if self.sharing == 'public':
         from follow import Follow
         [output.extend(tick_user.all_user_ids) for tick_user in Follow.get_followers(self.owner)]
         output.append('public')
     elif self.sharing == 'specific':
         output.extend(self.specified_permissions)
     return output
示例#12
0
 def get_or_create(cls, user=None):
     if not user:
         user = users.get_current_user()
     if not user:
         raise Exception('not logged in - cannot get or create TickUser')
     existing = cls.all().filter('all_users = ', user).get()
     if not existing:
         invitations = None
         if not users.is_current_user_admin():
             invitations = Invitation.all().filter(
                 'email_address =',
                 user.email().lower()).fetch(1000)
         if users.is_current_user_admin() or invitations:
             existing = cls(
                 tick_name=user.nickname(),
                 email_address=user.email(),
                 all_users=[user],
                 all_user_ids=[user.user_id()],
             )
             existing.put()
             # add inviters as followers
             if invitations:
                 from follow import Follow
                 for invite in invitations:
                     Follow.add_follower(existing, invite.inviter)
             # add default lists
             from ticklist import TickList
             from setlist import SetList
             TickList.create_list('Suggestions for Tick', 'public')
             getting_started = SetList.all(keys_only=True).filter(
                 'name =', 'getting started with tick').get()
             if getting_started:
                 TickList.create_from_setlist('Getting Started',
                                              getting_started.id())
             TickUserStat.generate_stats(
                 existing)  # TODO: create a new stats infrastructure
         else:
             raise NotInvitedError('not invited')
     return existing
示例#13
0
 def create(title, nodetype, content, summaryText, user, backlink=None, linktype="",
            imageURL=None, imageAuthor=None, imageDescription=None, 
            sourceURLs=None, sourceNames=None):
     newUrl = makeURL(title)
     pointRoot = PointRoot()
     pointRoot.url = newUrl
     pointRoot.nodetype = nodetype
     pointRoot.numCopies = 0
     pointRoot.editorsPick = False
     pointRoot.viewCount = 1
     if backlink:
         if linktype == 'supporting':
             pointRoot.pointsSupportedByMe = [backlink]
         elif linktype == 'counter':
             pointRoot.pointsCounteredByMe = [backlink]
         elif linktype == 'child':
             pointRoot.myParentPoints = [backlink]
             
     createdPoint, createdPointRoot = Point.transactionalCreate(
                         pointRoot, title, nodetype, content, summaryText, user,
                         imageURL, imageAuthor, imageDescription, 
                         sourceURLs, sourceNames )
     Follow.createFollow(user.key, createdPointRoot.key, "created")
     return createdPoint, createdPointRoot
示例#14
0
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'

        user = users.get_current_user()  #boolean
        id = self.request.get('id')
        myuser_key = ndb.Key('MyUser', id)
        myuser = myuser_key.get()

        my_follow = Follow.query(Follow.user == myuser)

        template_values = {
            'user': user,
            'my_follow': my_follow,
            'myuser': myuser,
            'id': id,
        }

        template = JINJA_ENVIRONMENT.get_template('myfollower.html')
        self.response.write(template.render(template_values))
示例#15
0
 def fanout(self):
     from follow import Follow, FollowIndex
     follower_ids_set = set(
         self.actor.all_user_ids
     )  # the owner should be able to see this activity
     follower_ids_set.update(
         set(self.extra_recipients
             ))  # the extra recipients should be able to see it too
     if not hasattr(self.target,
                    'sharing') or self.target.sharing == 'public':
         # if the target is public, so should all his/her followers
         follower_keys = Follow.all(keys_only=True).ancestor(
             self.actor).fetch(1000)
         for key in follower_keys:
             index_num = 0
             for ind in FollowIndex.all().ancestor(key).fetch(1000):
                 follower_ids_set.update(set(ind.view_permissions))
         if not self.other or not hasattr(
                 self.other, 'sharing') or self.other.sharing == 'public':
             # both target and other are public, the activity should be public too
             follower_ids_set.add('public')
     # create an activity index for each 5000 users that can see the activity
     max_list_size = datastore._MAX_INDEXED_PROPERTIES - 1
     index_num = 1
     act_ind_ents = []
     follower_ids = list(follower_ids_set)
     while (index_num - 1) * max_list_size < len(follower_ids):
         date_key = ActivityIndex.gen_date_key(self.creation_date,
                                               self.actor.key().id())
         new_act_ind = ActivityIndex(
             parent=self,
             date_key=date_key,
             edit_permissions=[],
             view_permissions=follower_ids[(index_num - 1) *
                                           max_list_size:index_num *
                                           max_list_size])
         act_ind_ents.append(new_act_ind)
         index_num += 1
     db.put(act_ind_ents)
示例#16
0
文件: bill.py 项目: thetreerat/possum
 def print_ticket_kitchen(self):
     """Prepare and send ticket to printers in kitchen."""
     output = True
     if self.category_to_follow:
         follow = Follow(category=self.category_to_follow)
         follow.save()
         todolist = []
         # header
         time = follow.date.strftime("%H:%M")
         todolist.append("[%s] Table %s (%s couv.)" %
                         (time, self.table, self.couverts))
         todolist.append(">>> faire: %s" % follow.category.nom)
         todolist.append(" ")
         # list of products to prepare (without Menu)
         products = self.get_products_for_category(follow.category)
         todolist += self.prepare_products(products)
         follow.produits = products
         follow.save()
         self.following.add(follow)
         # save send status
         for product in products:
             product.sent = True
             product.save()
         self.update_kitchen()
         # if another category following, we send it too to inform kitchen
         if self.category_to_follow:
             todolist.append(" ")
             category = self.category_to_follow
             todolist.append("Ensuite, pour info: %s" % category)
             products = self.get_products_for_category(category)
             todolist += self.prepare_products(products)
         # we print for each printers in kitchen
         name = "kitchen-%s-%s" % (self.id, follow.category_id)
         for printer in Printer.objects.filter(kitchen=True):
             if not printer.print_list(todolist, name, kitchen=True):
                 output = False
     return output
示例#17
0
文件: bill.py 项目: anoopl/possum
 def print_ticket_kitchen(self):
     """Prepare and send ticket to printers in kitchen."""
     output = True
     if self.category_to_follow:
         follow = Follow(category=self.category_to_follow)
         follow.save()
         todolist = []
         # header
         time = follow.date.strftime("%H:%M")
         todolist.append("[%s] Table %s (%s couv.)" % (time, self.table,
                                                       self.couverts))
         todolist.append(">>> faire: %s" % follow.category.nom)
         todolist.append(" ")
         # list of products to prepare (without Menu)
         products = self.get_products_for_category(follow.category)
         todolist += self.prepare_products(products)
         follow.produits = products
         follow.save()
         self.following.add(follow)
         # save send status
         for product in products:
             product.sent = True
             product.save()
         self.update_kitchen()
         # if another category following, we send it too to inform kitchen
         if self.category_to_follow:
             todolist.append(" ")
             category = self.category_to_follow
             todolist.append("Ensuite, pour info: %s" % category)
             products = self.get_products_for_category(category)
             todolist += self.prepare_products(products)
         # we print for each printers in kitchen
         name = "kitchen-%s-%s" % (self.id, follow.category_id)
         for printer in Printer.objects.filter(kitchen=True):
             if not printer.print_list(todolist, name):
                 output = False
     return output
示例#18
0
def log_num_follow():
    num = Follow.raw_sql('select count(1) from follow').fetchone()[0]
    log_history_new(Follow, LOG_HISTORY_CID_FOLLOW, num)
示例#19
0
 def setUp(self):
     api = create_api()
     self.follow = Follow(api)
示例#20
0
class Root(object):

    _cp_config = {
        'tools.sessions.on': True,
        'tools.auth.on': True,
        'tools.sessions.locking': 'explicit' #this and the acquire_lock and the release_lock statements in the login and logout functions are necessary so that multiple ajax requests can be processed in parallel in a single session
    }

#    stream = Stream()

#    images = Images()    

    follow = Follow()

    following = Following()

    followers = Followers()

    myposts = MyPosts()
    
    post = Post()

    feed = Feed()

    auth = Authenticate()

    register = Register()

    singlepost = SinglePost()

    love = Love()
    
    repost = Repost()
    
#    @cherrypy.expose
#    def default(self,*args):
#        return static.serve_file("/home/ec2-user/server/google_verification_file.html");        

    @cherrypy.expose
    def index(self):

        gtag_string = open("gtag.js").read()

        disclaimer_string = open("disclaimer.html").read()
        
        if is_session_authenticated():
            raise cherrypy.HTTPRedirect("/feed/");

        desktop_menu_string = open("desktop_unauthenticated_menu.html").read()
        mobile_menu_string = open("mobile_unauthenticated_menu.html").read()
        
        secrets_file=open("/home/ec2-user/secrets.txt")

        passwords=secrets_file.read().rstrip('\n')

        db_password = passwords.split('\n')[0]
        
        dbname = "nplat"

        is_mobile = False

        if "User-Agent" in cherrypy.request.headers and ("Android" in cherrypy.request.headers['User-Agent'] or "iPhone" in cherrypy.request.headers['User-Agent'] or "iPad" in cherrypy.request.headers['User-Agent']):
            is_mobile = True
            
        conn = MySQLdb.connect(host='nplat-instance.cphov5mfizlt.us-west-2.rds.amazonaws.com', user='******', passwd=db_password, port=3306)
            
        curs = conn.cursor()
        
        curs.execute("use "+dbname+";")
    
        curs.execute("select username,name,registration_time from user_info;")
    
        userinfo_fetchall = curs.fetchall()

        colnames = [desc[0] for desc in curs.description]

        body_string = "<center>\n"
        
        for userinfo in userinfo_fetchall:
            userinfo_dict=dict(zip(colnames, userinfo))        
            body_string += "<a href=\""+userinfo_dict["username"]+"\">"+userinfo_dict["username"] + " (" + userinfo_dict["name"] + ")</a><br>\n" 

        body_string += "<br>\n"
                
        curs.execute("select t1.*,(select unique_id from posts where unique_id=t1.parent_unique_id limit 1),(select text from posts where unique_id=t1.parent_unique_id limit 1),(select video_unique_id from posts where unique_id=t1.parent_unique_id limit 1),(select image_unique_id from posts where unique_id=t1.parent_unique_id limit 1),(select time from posts where unique_id=t1.parent_unique_id limit 1),(select username from posts where unique_id=t1.parent_unique_id limit 1),(select count(*) from loves where post_unique_id=t1.unique_id),(select count(*) from posts where parent_unique_id=t1.unique_id),(select count(*) from loves where post_unique_id=t1.parent_unique_id),(select count(*) from posts where parent_unique_id=t1.parent_unique_id) FROM posts as t1 order by t1.time desc;")

        colnames = [desc[0] for desc in curs.description]

        posts=curs.fetchall()

        conn.close()
            
        body_string = "<center>\n"

        for post in posts:
            post_dict = dict(zip(colnames, post))

#                datetime_string_fmt = '%Y-%m-%d %H:%M:%S.%f'
            datetime_string_fmt = '%Y-%m-%d'                

            body_string += "<div class=\"post\">\n"

            if post_dict["parent_unique_id"]:

                body_string += "<p style=\"float:left;text-align:left;position:relative;top:-20px;width:75%;\"><b>"+post_dict["(select username from posts where unique_id=t1.parent_unique_id limit 1)"] + "</b> (reposted by <b>"+post_dict["username"]+"</b>)</p>"
                body_string += "<p style=\"float:left;text-align:right;position:relative;top:-20px;width:25%;\">"+post_dict["(select time from posts where unique_id=t1.parent_unique_id limit 1)"].strftime(datetime_string_fmt)+"</p>"

                body_string += "<i>" + post_dict["(select text from posts where unique_id=t1.parent_unique_id limit 1)"] + "</i><br><br>\n"

                if post_dict["(select video_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"] != None:
                    if is_mobile:
                        body_string += "<video width=\"90%\" height=\"240\" controls>  <source src=\"https://video.n-plat.com/?filename=video"+str(post_dict["(select video_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"])+".mp4\" type=\"video/mp4\"></video><br>\n"
                    else:    
                        body_string += "<video width=\"320\" height=\"240\" controls>  <source src=\"https://video.n-plat.com/?filename=video"+str(post_dict["(select video_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"])+".mp4\" type=\"video/mp4\"></video><br>\n"


                if post_dict["(select image_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"] != None:
                    if is_mobile:
                        body_string += "<img style=\"max-width: 90%; max-height: 300\" src=\"https://image.n-plat.com/?filename=image"+str(post_dict["(select image_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"])+".jpeg\"></img><br>\n"
                    else:
                        body_string += "<img style=\"max-width: 300; max-height: 300\" src=\"https://image.n-plat.com/?filename=image"+str(post_dict["(select image_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"])+".jpeg\"></img><br>\n"
                            
                body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:left;\"><img class=\"heart\" height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=heart_outline.png\"/>"+str(post_dict["(select count(*) from loves where post_unique_id=t1.parent_unique_id)"])+"</p>"
                body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:center;\"><img class=\"repost\" height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=repost.png\"/>"+str(post_dict["(select count(*) from posts where parent_unique_id=t1.parent_unique_id)"])+"</p>"                
                body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:right;\"><a href=\"https://n-plat.com/singlepost/?id="+str(+post_dict["parent_unique_id"])+"\"><img height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=share.png\"/></a></p>"
            else:
                
                body_string += "<p style=\"float:left;text-align:left;position:relative;top:-20px;width:75%;\"><b>"+post_dict["username"] + "</b></p>"
                body_string += "<p style=\"float:left;text-align:right;position:relative;top:-20px;width:25%;\">"+post_dict["time"].strftime(datetime_string_fmt)+"</p>"

                body_string += "<i>" + post_dict["text"] + "</i><br><br>\n"

                if post_dict["video_unique_id"] != None:
                    if is_mobile:
                        body_string += "<video width=\"90%\" height=\"240\" controls>  <source src=\"https://video.n-plat.com/?filename=video"+str(post_dict["video_unique_id"])+".mp4\" type=\"video/mp4\"></video><br>\n"
                    else:    
                        body_string += "<video width=\"320\" height=\"240\" controls>  <source src=\"https://video.n-plat.com/?filename=video"+str(post_dict["video_unique_id"])+".mp4\" type=\"video/mp4\"></video><br>\n"


                if post_dict["image_unique_id"] != None:
                    if is_mobile:
                        body_string += "<img style=\"max-width: 90%; max-height: 300\" src=\"https://image.n-plat.com/?filename=image"+str(post_dict["image_unique_id"])+".jpeg\"></img><br>\n"
                    else:
                        body_string += "<img style=\"max-width: 300; max-height: 300\" src=\"https://image.n-plat.com/?filename=image"+str(post_dict["image_unique_id"])+".jpeg\"></img><br>\n"

                            
                body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:left;\"><img class=\"heart\" height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=heart_outline.png\"/>"+str(post_dict["(select count(*) from loves where post_unique_id=t1.unique_id)"])+"</p>"
                body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:center;\"><img class=\"repost\" height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=repost.png\"/>"+str(post_dict["(select count(*) from posts where parent_unique_id=t1.unique_id)"])+"</p>"                
                body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:right;\"><a href=\"https://n-plat.com/singlepost/?id="+str(+post_dict["unique_id"])+"\"><img height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=share.png\"/></a></p>"

            body_string += "</div>"

        body_string += "</center>\n"

        desktop_html_string = open("desktop.html").read()
            
        desktop_html_string = desktop_html_string.format(
            a=gtag_string,
            b="",
            c=desktop_menu_string,
            d=body_string,
            e=disclaimer_string)

        mobile_html_string = open("mobile.html").read()
            
        mobile_html_string=mobile_html_string.format(
            a=gtag_string,
            b="",
            c=mobile_menu_string,
            d=body_string,
            e=disclaimer_string)
        
        if is_mobile:
            html_string = mobile_html_string
        else:
            html_string = desktop_html_string

        return html_string

    @cherrypy.expose
    def default(self, user):

        gtag_string = open("gtag.js").read()

        disclaimer_string = open("disclaimer.html").read()
        
        if is_session_authenticated():
            desktop_menu_string = open("desktop_authenticated_menu.html").read()
            mobile_menu_string = open("mobile_authenticated_menu.html").read()
        else:
            desktop_menu_string = open("desktop_unauthenticated_menu.html").read()
            mobile_menu_string = open("mobile_unauthenticated_menu.html").read()
        
        is_mobile = False

        if "User-Agent" in cherrypy.request.headers and ("Android" in cherrypy.request.headers['User-Agent'] or "iPhone" in cherrypy.request.headers['User-Agent'] or "iPad" in cherrypy.request.headers['User-Agent']):
            is_mobile = True

        valid_username = True    
            
        for c in user:
            if c != 'a' and c != 'b' and c != 'c' and c != 'd' and c != 'e' and c != 'f' and c != 'g' and c != 'h' and c != 'i' and c != 'j' and c != 'k' and c != 'l' and c != 'm' and c != 'n' and c != 'o' and c != 'p' and c != 'q' and c != 'r' and c != 's' and c != 't' and c != 'u' and c != 'v' and c != 'w' and c != 'x' and c != 'y' and c != 'z' and c != 'A' and c != 'B' and c != 'C' and c != 'D' and c != 'E' and c != 'F' and c != 'G' and c != 'H' and c != 'I' and c != 'J' and c != 'K' and c != 'L' and c != 'M' and c != 'N' and c != 'O' and c != 'P' and c != 'Q' and c != 'R' and c != 'S' and c != 'T' and c != 'U' and c != 'V' and c != 'W' and c != 'X' and c != 'Y' and c != 'Z' and c != '0' and c != '1' and c != '2' and c != '3' and c != '4' and c != '5' and c != '6' and c != '7' and c != '8' and c != '9' and c != '_' and c != '-' and c != '.':
                valid_username = False

        if not valid_username:
            body_string = "<center>Invalid username</center>"
        else:    
            secrets_file=open("/home/ec2-user/secrets.txt")

            passwords=secrets_file.read().rstrip('\n')
            
            db_password = passwords.split('\n')[0]
            
            dbname = "nplat"
            
            conn = MySQLdb.connect(host='nplat-instance.cphov5mfizlt.us-west-2.rds.amazonaws.com', user='******', passwd=db_password, port=3306)
            
            curs = conn.cursor()
    
            curs.execute("use "+dbname+";")
       
            curs.execute("select * from user_info where username=\""+user+"\";")

            userinfo_fetchall = curs.fetchall()
        
            if len(userinfo_fetchall):
                assert(len(userinfo_fetchall) == 1)
                colnames = [desc[0] for desc in curs.description]
                name_string = "<center>\n"
                for userinfo in userinfo_fetchall:
                    userinfo_dict=dict(zip(colnames, userinfo))        
                    name_string += "<h2>" + userinfo_dict["name"] + "</h2>\n<br>\n" 
                name_string += "</center>\n"

                curs.execute("select t1.*,(select unique_id from posts where unique_id=t1.parent_unique_id limit 1),(select text from posts where unique_id=t1.parent_unique_id limit 1),(select video_unique_id from posts where unique_id=t1.parent_unique_id limit 1),(select image_unique_id from posts where unique_id=t1.parent_unique_id limit 1),(select time from posts where unique_id=t1.parent_unique_id limit 1),(select username from posts where unique_id=t1.parent_unique_id limit 1),(select count(*) from loves where post_unique_id=t1.unique_id),(select count(*) from posts where parent_unique_id=t1.unique_id),(select count(*) from loves where post_unique_id=t1.parent_unique_id),(select count(*) from posts where parent_unique_id=t1.parent_unique_id) FROM posts as t1 WHERE t1.username=\""+user+"\" ORDER by t1.time desc;")

                colnames = [desc[0] for desc in curs.description]

                posts=curs.fetchall()

                if len(posts) != 0:
                    body_string = "<center>\n"
                    for post in posts:
                        post_dict = dict(zip(colnames, post))

                        datetime_string_fmt = '%Y-%m-%d'                

                        body_string += "<div class=\"post\">\n"

                        if post_dict["parent_unique_id"]:

                            body_string += "<p style=\"float:left;text-align:left;position:relative;top:-20px;width:75%;\"><b>"+post_dict["(select username from posts where unique_id=t1.parent_unique_id limit 1)"] + "</b> (reposted by <b>"+post_dict["username"]+"</b>)</p>"
                            body_string += "<p style=\"float:left;text-align:right;position:relative;top:-20px;width:25%;\">"+post_dict["(select time from posts where unique_id=t1.parent_unique_id limit 1)"].strftime(datetime_string_fmt)+"</p>"

                            body_string += "<i>" + post_dict["(select text from posts where unique_id=t1.parent_unique_id limit 1)"] + "</i><br><br>\n"

                            if post_dict["(select video_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"] != None:
                                if is_mobile:
                                    body_string += "<video width=\"90%\" height=\"240\" controls>  <source src=\"https://video.n-plat.com/?filename=video"+str(post_dict["(select video_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"])+".mp4\" type=\"video/mp4\"></video><br>\n"
                                else:    
                                    body_string += "<video width=\"320\" height=\"240\" controls>  <source src=\"https://video.n-plat.com/?filename=video"+str(post_dict["(select video_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"])+".mp4\" type=\"video/mp4\"></video><br>\n"

                            if post_dict["(select image_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"] != None:
                                if is_mobile:
                                    body_string += "<img style=\"max-width: 90%; max-height: 300\" src=\"https://image.n-plat.com/?filename=image"+str(post_dict["(select image_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"])+".jpeg\"></img><br>\n"
                                else:
                                    body_string += "<img style=\"max-width: 300; max-height: 300\" src=\"https://image.n-plat.com/?filename=image"+str(post_dict["(select image_unique_id from posts where unique_id=t1.parent_unique_id limit 1)"])+".jpeg\"></img><br>\n"
                            
                            body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:left;\"><img class=\"heart\" height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=heart_outline.png\"/>"+str(post_dict["(select count(*) from loves where post_unique_id=t1.parent_unique_id)"])+"</p>"
                            body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:center;\"><img class=\"repost\" height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=repost.png\"/>"+str(post_dict["(select count(*) from posts where parent_unique_id=t1.parent_unique_id)"])+"</p>"                
                            body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:right;\"><a href=\"https://n-plat.com/singlepost/?id="+str(+post_dict["parent_unique_id"])+"\"><img height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=share.png\"/></a></p>"
                        else:
                
                            body_string += "<p style=\"float:left;text-align:left;position:relative;top:-20px;width:75%;\"><b>"+post_dict["username"] + "</b></p>"
                            body_string += "<p style=\"float:left;text-align:right;position:relative;top:-20px;width:25%;\">"+post_dict["time"].strftime(datetime_string_fmt)+"</p>"

                            body_string += "<i>" + post_dict["text"] + "</i><br><br>\n"

                            if post_dict["video_unique_id"] != None:
                                if is_mobile:
                                    body_string += "<video width=\"90%\" height=\"240\" controls>  <source src=\"https://video.n-plat.com/?filename=video"+str(post_dict["video_unique_id"])+".mp4\" type=\"video/mp4\"></video><br>\n"
                                else:    
                                    body_string += "<video width=\"320\" height=\"240\" controls>  <source src=\"https://video.n-plat.com/?filename=video"+str(post_dict["video_unique_id"])+".mp4\" type=\"video/mp4\"></video><br>\n"


                            if post_dict["image_unique_id"] != None:
                                if is_mobile:
                                    body_string += "<img style=\"max-width: 90%; max-height: 300\" src=\"https://image.n-plat.com/?filename=image"+str(post_dict["image_unique_id"])+".jpeg\"></img><br>\n"
                                else:
                                    body_string += "<img style=\"max-width: 300; max-height: 300\" src=\"https://image.n-plat.com/?filename=image"+str(post_dict["image_unique_id"])+".jpeg\"></img><br>\n"
                            
                            body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:left;\"><img class=\"heart\" height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=heart_outline.png\"/>"+str(post_dict["(select count(*) from loves where post_unique_id=t1.unique_id)"])+"</p>"
                            body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:center;\"><img class=\"repost\" height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=repost.png\"/>"+str(post_dict["(select count(*) from posts where parent_unique_id=t1.unique_id)"])+"</p>"                
                            body_string += "<p style=\"float:left;position:relative;bottom:-20px;width:33.3333333333333333333333%;text-align:right;\"><a href=\"https://n-plat.com/singlepost/?id="+str(+post_dict["unique_id"])+"\"><img height=\"20\" width=\"20\" src=\"https://image.n-plat.com/?filename=share.png\"/></a></p>"

                        body_string += "</div>"

                        body_string += """

<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script type="text/javascript"> 
$('img.heart').click(function(event) {
   event.preventDefault();
   request_json_object = {"post_id" : event.target.parentNode.parentNode.lastChild.firstChild.href.split('=')[1]}
   $.ajax({
      url: '/love/',
      type: 'POST',
      contentType: 'application/json',
      data: JSON.stringify(request_json_object),
//      data: '',
      success: function(data){
         response_json_object = JSON.parse(data)
         if (json_object["success"]) {

         }
         else {

         }
      },
      error : function (data) {

      }
   });
});
$('img.repost').click(function(event) {
   event.preventDefault();
   request_json_object = {"post_id" : event.target.parentNode.parentNode.lastChild.firstChild.href.split('=')[1]}
   $.ajax({
      url: '/repost/',
      type: 'POST',
      contentType: 'application/json',
      data: JSON.stringify(request_json_object),
      success: function(data){
         response_json_object = JSON.parse(data)
         if (json_object["success"]) {

         }
         else {

         }
      },
      error : function (data) {

      }
   });
});
</script>

"""
        

                        
                else:
                    body_string="<center><i>"+user+" has not posted anything yet</i></center>"

            else:
                body_string = "<center>Username not found</center>"
                
        desktop_html_string = open("desktop.html").read()
                
        desktop_html_string = desktop_html_string.format(
            a=gtag_string,
            b="",
            c=desktop_menu_string,
            d=body_string,
            e=disclaimer_string)

        mobile_html_string = open("mobile.html").read()
            
        mobile_html_string = mobile_html_string.format(
            a=gtag_string,
            b="",
            c=mobile_menu_string,
            d=body_string,
            e=disclaimer_string)
            
        if is_mobile:
            html_string = mobile_html_string
        else:
            html_string = desktop_html_string 
            
        return html_string
示例#21
0
 def test_integration1_true_close(self):
     player = Player()
     monster = Monster()
     follow = Follow()
     self.assertTrue(follow.closeEnough(monster.position, player.position))
示例#22
0
def default_follow_xiyoumc(username):
    Follow('xiyoumc', username)
示例#23
0
def filter_symbols(rows, names):
    rows = (row for row in rows if row['name'] in names)
    yield rows


def parse_stock_data(lines):
    rows = csv.reader(lines)
    rows = select_colomns(rows, [0, 1, 4])
    rows = convert_types(rows, [str, str, str])
    rows = make_dict(rows, ['name', 'price', 'shares'])
    return rows


def ticker(portfolio, logfile, fmt):
    portfolio = report.read_portfolio_4(portfolio)
    lines = Follow(logfile)
    rows = parse_stock_data(lines)
    rows = filter_symbols(rows, portfolio)
    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['name', 'price', 'shares'])
    for rowdata in rows:
        formatter.row(rowdata.values())


if __name__ == "__main__":
    portfolio = report.read_portfolio_4('Data/portfolio.csv')
    lines = Follow('Data/stocklog.csv')
    rows = parse_stock_data(lines)
    rows = filter_symbols(rows, portfolio)
    for row in rows:
        print(row)
示例#24
0
    def get(self):
        self.response.headers['Content-Type'] = 'text/html'

        url = ''
        url_string = ''

        user = users.get_current_user() #boolean

        if user:
            url = users.create_logout_url(self.request.uri)
            url_string = 'logout'
            myuser_key = ndb.Key('MyUser', user.user_id()) #generate a key for MyUser type
            myuser = myuser_key.get()
            my_follow = Follow.query(Follow.user == myuser)
            if myuser == None: # if we find the key or not here not
                myuser = MyUser(id=user.user_id(), email_address = user.email(), user_id = user.user_id())
                myfollow = Follow(user=myuser)
                myuser.put() #commit myuser in datastore
                myfollow.put()

            key = ndb.Key('ListUser', 'default')
            list_user = key.get()
            if list_user == None:
                list_user = ListUser(id='default')
                list_user.put()

            my_following_post = MyPost.query()
            my_post = MyPost.query(MyPost.creator == myuser)
            list_comment = ListComment.query()

            list_post = ListPost.query(ListPost.user == myuser)
            if list_post.count() == 0:
                my_list_post = ListPost(user=myuser)
                for i in my_following_post:
                    for j in my_follow:
                        for k in j.following:
                            if i.creator == k:
                                my_list_post.list_post.append(i)
                for i in my_post:
                    my_list_post.list_post.append(i)
                my_list_post.list_post = sorted(my_list_post.list_post, key=lambda post: post.creation_time, reverse=True)
                if len(my_list_post.list_post) > 50:
                    my_list_post.list_post = my_list_post.list_post[0:50]
                my_list_post.put()
            else:
                for i in list_post:
                    i.key.delete()
                my_list_post = ListPost(user=myuser)
                for i in my_following_post:
                    for j in my_follow:
                        for k in j.following:
                            if i.creator == k:
                                my_list_post.list_post.append(i)
                for i in my_post:
                    my_list_post.list_post.append(i)
                my_list_post.list_post = sorted(my_list_post.list_post, key=lambda post: post.creation_time, reverse=True)
                if len(my_list_post.list_post) > 50:
                    my_list_post.list_post = my_list_post.list_post[0:50]
                my_list_post.put()


            template_values = {
                'url' : url,
                'url_string' : url_string,
                'user' : user,
                'upload_url' : blobstore.create_upload_url('/upload'),
                'list_user' : list_user,
                'my_following_post': my_following_post,
                'my_follow': my_follow,
                'list_post': list_post,
                'list_comment': list_comment,
            }


        else:
            url = users.create_login_url(self.request.uri)
            url_string = 'login'

            template_values = {
                'url' : url,
                'url_string' : url_string,
            }

        template = JINJA_ENVIRONMENT.get_template('main.html')
        self.response.write(template.render(template_values))
示例#25
0
#!/usr/bin/env python
from follow import Follow

if __name__ == '__main__':
    follow = Follow([
        #x   ,   y,   z, yaw, sleep
        [-0.3, -1.4, 0.7, 0, 3]
    ])
    follow.run()
示例#26
0
文件: main.py 项目: usoppu/floflow
    if key_not_exists(instaname, config):
        sys.exit('[ERROR]: ' + instaname + ' is not exists.')
    account = Account(config[instaname])

session = InstaPy(username=account.get_username(),
                  password=account.get_password(),
                  headless_browser=False,
                  multi_logs=True,
                  disable_image_load=True)

with smart_run(session):
    session.set_relationship_bounds(enabled=True)

    session.set_quota_supervisor(
        enabled=True,
        sleep_after=["likes_h", "follows_h", "unfollows_h", "server_calls_h"],
        sleepyhead=True,
        stochastic_flow=True,
        notify_me=True,
        peak_likes_hourly=57,
        peak_likes_daily=700,
        peak_follows_hourly=48,
        peak_follows_daily=None,
        peak_unfollows_hourly=35,
        peak_unfollows_daily=402,
        peak_server_calls_hourly=random.randint(150, 200),
        peak_server_calls_daily=4200)

    Follow(config[instaname], session)
    Unfollow(config[instaname], session)
示例#27
0
def buzz_site_new(user_id, site_id):
    followed = Follow.where('to_id=%s', user_id).col_list(col='from_id')
    for to_id in followed:
        buzz_new(user_id, to_id, CID_BUZZ_SITE_NEW, site_id)
示例#28
0
def main():
    print("welcome to this simple monster fighting game")
    print("monsters will find your position and come towards you")
    print("when they are close enough, attack\n ")

    gamePlaying = True
    numAlive = 3
    player = Player()
    mon1 = Monster()
    mon1.position = [10,10,10]
    mon2 = Monster()
    mon2.position = [20,20,20]
    mon3 = Monster()
    mon3.position = [5,5,5]
    movement = [-5,-5,-5]
    physics = Physics()
    follow = Follow()
    i = 0
   # monsters = [mon1, mon2, mon3]

    while gamePlaying:
        print("\n*****************************************")
        print('you are at [0,0,0]')
        print('you have',player.numAttacks, 'attacks left')
        print('the monsters are at ')


        #print pos
        if mon1.checkAlive():
            print(*mon1.position, sep = ", ")
        if mon2.checkAlive():
            print(*mon2.position, sep=", ")
        if mon3.checkAlive():
            print(*mon3.position, sep=", ")
        print("\n... monsters moving ... \n")
        i +=1

        # attacking
        choice = input("attack? Y/N: ")
        if choice == 'Y':
            player.numAttacks -= 1
            which = input("which monster: ")
            print("\n*****************************************\n")
            if which == "1":
                if follow.closeEnough(mon1.position, player.position) and mon1.checkAlive():
                    mon1.damage()
                    print("you killed a monster!")
                    numAlive -= 1
                else:
                    print("you can't attack that one too bad")
            if which == "2":
                if follow.closeEnough(mon2.position, player.position) and mon2.checkAlive():
                    mon2.damage()
                    print("you killed a monster!")
                    numAlive -= 1
                else:
                    print("you can't attack that one too bad")
            if which == "3":
                if follow.closeEnough(mon3.position, player.position) and mon3.checkAlive():
                    mon3.damage()
                    print("you killed a monster!")
                    numAlive -= 1
                else:
                    print("you can't attack that one too bad")
        elif choice == 'N':
            print("no attack used")
        else:
            print("wasted turn on invalid entry smh")

        #updating pos
        if not follow.closeEnough(mon1.position, player.position):
            mon1.position = physics.update_position(movement, mon1.position, 1)
        if not follow.closeEnough(mon2.position, player.position):
            mon2.position = physics.update_position(movement, mon2.position, 1)
        if not follow.closeEnough(mon3.position, player.position):
            mon3.position = physics.update_position(movement, mon3.position, 1)

        if numAlive == 0 or player.numAttacks == 0:
            gamePlaying = False

    if numAlive == 0:
        print("\n*****************************************")
        print("congrats you killed them all!")
    else:
        print("\n*****************************************")
        print("ran out of attacks - there are", numAlive, "monsters left")
        print("better luck next time")
示例#29
0
 def test_integration1_false_close(self):
     player = Player()
     monster = Monster()
     monster.position = [20, 20, 20]
     follow = Follow()
     self.assertFalse(follow.closeEnough(monster.position, player.position))
示例#30
0
文件: user.py 项目: bbcyyb/missouri
 def follow(self, user):
     if not self.is_following(user):
         follow = Follow(follower=self, followed=user)
         db.session.add(follow)
         db.session.commit()
示例#31
0
    def update( self, newTitle=None, newContent=None, newSummaryText=None, 
                pointsToLink=None, user=None, imageURL=None, imageAuthor=None,
                imageDescription=None, sourcesToAdd=None, sourceKeysToRemove=None):
        if user:
            theRoot = self.key.parent().get()
            newPoint = Point(parent=self.key.parent())  # All versions ancestors of the PointRoot

            newPoint.title = self.title if newTitle is None else newTitle
            newPoint.nodetype = self.nodetype
            
            newPoint.content = self.content if newContent is None else newContent

            if newSummaryText:
                newPoint.summaryText = newSummaryText if (len(
                    newSummaryText) != 250) else newSummaryText + '...'
            else:
                newPoint.summaryText = self.summaryText

            newPoint.authorName = user.name            
            newPoint.authorURL = user.url
            newPoint.supportingPointsRoots = list(self.supportingPointsRoots)
            newPoint.supportingPointsLastChange = list(self.supportingPointsLastChange)
            newPoint.counterPointsRoots = list(self.counterPointsRoots)
            newPoint.counterPointsLastChange = list(self.counterPointsLastChange)
            newPoint.childPointsRoots = list(self.childPointsRoots)
            newPoint.childPointsLastChange = list(self.childPointsLastChange)
                    
            newPoint.sources = self.sources
            keysToRemove = convertListToKeys(sourceKeysToRemove)
            if keysToRemove:
                for keyToRemove in keysToRemove:
                    for oldKey in newPoint.sources:
                        if oldKey == keyToRemove:
                            newPoint.sources.remove(oldKey)

            newPoint.version = self.version + 1
            newPoint.upVotes = self.upVotes
            newPoint.downVotes = self.downVotes
            newPoint.voteTotal = self.voteTotal
            newPoint.imageURL = self.imageURL if imageURL is None else imageURL
            newPoint.imageDescription = self.imageDescription if imageDescription is None else imageDescription
            newPoint.imageAuthor = self.imageAuthor if imageAuthor is None else imageAuthor
            if newPoint.title != self.title:
                newPoint.url = theRoot.updateURL(newPoint.title)
            else:
                newPoint.url = self.url
            newPoint.current = True

            self.current = False

            newPoint, theRoot = self.transactionalUpdate(newPoint, theRoot, sourcesToAdd, user, pointsToLink)
                    
            Follow.createFollow(user.key, theRoot.key, "edited")
            Point.addNotificationTask(theRoot.key, user.key, "edited")

            # THIS NEEDS TO CHECK WHETHER IT IS NECESSARY TO UPDATE THE INDEX
            newPoint.addToSearchIndexNew()

            return newPoint
        else:
            return None
示例#32
0
def buzz_site_new(user_id, site_id):
    followed = Follow.where('to_id=%s', user_id).col_list(col='from_id')
    for to_id in followed:
        buzz_new(user_id, to_id, CID_BUZZ_SITE_NEW , site_id)
示例#33
0
def log_num_follow():
    num = Follow.raw_sql('select count(1) from follow').fetchone()[0]
    log_history_new(Follow, LOG_HISTORY_CID_FOLLOW, num)