def newThread(self, topic): # create new thread object and add it to the list thread = Thread(len(self.threads), topic, 0) self.threads.append(thread) # create generic RankNode to represent thread in the linked list, and # add it to the mapping dict node = RankNode(thread.id, None, None) self.nodes[thread.id] = node # if there is no head, then list is empty. insert node as first element if self.head is None: self.head = node self.tail = node self.insertion = node # if inesrtion is none, all other nodes have negative score. # insert node as first element and update insertion point to node elif self.insertion is None: node.next = self.head self.head = node self.insertion = node # other positive nodes exist. insert node behind insertion point and # update insertion point to node else: self.insertion.insertAfter(node) # if inserting after the last element, update tail to node if (self.insertion == self.tail): self.tail = node self.insertion = node
def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs): if author_id != self.uid: self.markAsDelivered(author_id, thread_id) self.markAsRead(author_id) thread: Thread = Thread(thread_id, thread_type, self.lookupThread(thread_id).name) message: Message = Message(message_object.text, author_id, self.lookupUser(author_id).first_name, thread) client: Client = Client(self) try: log.info( f'\n{message.author_name} in thread {thread.thread_name} said:\n{indent(message.text)}' ) for handler in self.handlers: if (handler.couldHandle(message)): try: log.info(f'Using: {handler.name()}') handler.handle(message, client) except RuntimeError as e: client.sendText(thread, f'Error: {e}') break except: client.sendText(thread, 'X_X') raise
def index(): chatwith_form = ChatWithForm() if chatwith_form.validate_on_submit(): user = User.query.filter_by( username=chatwith_form.username.data).first() if user is None: flash("User does not exist") else: # minor bug: chatting with yourself shows messages of 1st thread created threads_user = db.session.query(users).filter_by( user_id=user.id).all() threads_current_user = db.session.query(users).filter_by( user_id=current_user.id).all() for thread_user in threads_user: for thread_current_user in threads_current_user: if thread_user.thread_id == thread_current_user.thread_id: return redirect( url_for('chat', thread_id=thread_user.thread_id)) thread = Thread(name=user.username) thread.users.append(user) thread.users.append(current_user) db.session.add(thread) db.session.commit() return redirect(url_for('chat', thread_id=thread.id)) return render_template('index.html', title='Chat', chatwith_form=chatwith_form, thread=None)
def new_thread(request): """ create a new thead """ if request.method == 'POST': thread = Thread( creator=request.user, site=Site.objects.get_current(), ) post = Post(thread=thread, creator=request.user, posted_from=get_client_ip(request)) thread_form = forms.ThreadForm(request.POST, instance=thread) post_form = forms.PostForm(request.POST, instance=post) if thread_form.is_valid() and post_form.is_valid(): thread = thread_form.save() post.thread = thread post_form = forms.PostForm(request.POST, instance=post) post_form.save() request.posting_users.add_to_set(request.user.id) return HttpResponseRedirect(reverse('list-threads')) else: thread_form = forms.ThreadForm() post_form = forms.PostForm() return render_to_response("board/new_thread.html", { 'thread_form': thread_form, 'post_form': post_form, }, context_instance=RequestContext(request))
def archive(thread_url): """ Get values from the url to create a Thread object. Passes the thread to parse_html to be download. """ match = None # check for valid urls in extractors for cls in Extractor.__subclasses__(): extractor = None if re.match(cls.VALID_URL, thread_url): match = re.match(cls.VALID_URL, thread_url) extractor = cls() if not (match): print("Improper URL:", thread_url) return 1 board = match.group('board') thread_id = match.group('thread') thread = Thread(thread_id, board, thread_url) params.path_to_download = 'threads/{}/{}'.format(thread.board, thread.tid) if not os.path.exists(params.path_to_download): os.makedirs(params.path_to_download) if params.verbose: print("Downloading thread:", thread.tid) extractor.extract(thread, params)
def find_thread(self,threads,key): rec_cnt = 0 t_ret = Thread() for t in threads: rec_cnt += 1 if t.key == key: t_ret = t.thread break return t_ret,rec_cnt
def save(self, author): self.thread = Thread(title=self.cleaned_data['title'], forum=self.cleaned_data['forum']) self.thread.save() self.post = Post(thread=self.thread, content=self.cleaned_data['content'], author=author) self.post.save() return self.thread
def add_thread(user_id): """Page to add a thread. """ # if this user id combo exists thread = Thread.query.filter(Thread.user1_id == user_id, Thread.user2_id == g.user.id).all() thread2 = Thread.query.filter(Thread.user2_id == user_id, Thread.user1_id == g.user.id).all() if thread: return redirect(f'threads/{thread[0].id}') if thread2: return redirect(f'threads/{thread2[0].id}') # else: if (user_id < g.user.id): new_thread = Thread(user1_id=user_id, user2_id=g.user.id) else: new_thread = Thread(user1_id=g.user.id, user2_id=user_id) db.session.add(new_thread) db.session.commit() return redirect(f'threads/{new_thread.id}')
def create_thread_submit(request, forumid): forum = Forum.get_by_id(int(forumid)) thread = Thread(forum=forum, user=request._user, content="Default", title="Default") data = ThreadForm(request.POST, instance=thread) if data.is_valid(): entity = data.save(commit=False) entity.put() forum.increment_thread_count() forum.set_last_thread(entity) return HttpResponseRedirect('/forum/{0}'.format(forum.key().id())) return render_to_response('home/create_thread.html', {'thread_form': data})
def form(fid): if FormLink.objects(fid=fid): if request.method == 'POST': form_data = FormData() formlink = FormLink.objects(fid=fid).first().to_dbref() form_data.thread = Thread(formlink=formlink).save() form_data.load = semiflatten(request.form) form_data.headers = dict(request.headers.items()) form_data.ip = request.remote_addr form_data.save() return redirect(url_for('forms.data', fid=fid)) return render_template('forms/test_form.html', fid=url_for('forms.form', fid=fid)) else: return 'no form found'
def onListening(self): default_group_id = int(os.environ['FB_DEFAULT_GROUP']) default_group = Thread(default_group_id, fbchat.models.ThreadType.GROUP, self.lookupThread(default_group_id)) self.handlers = [ WakeWordHandler(HelpHandler()), WakeWordHandler(EchoHandler()), WakeWordHandler(TellHandler(default_group)), WakeWordHandler(ImageHandler()), WakeWordHandler(PointsHandler()), # Must be last WakeWordHandler. WakeWordHandler(SorryDaveHandler()), Xkcd37Handler() ] fbchat.Client.onListening(self)
def post(self): user = users.get_current_user() if not user: self.redirect("/welcome") else: teleUser = TeleUser.get_by_id(user.user_id()) if not teleUser: teleUser = TeleUser.fromGSI(user=user) teleUser.put() thread_id = random.randint(1000000000, 9999999999) thread = Thread(thread_id=thread_id) drawingDataUrl = self.request.get("drawing") img_data = drawingDataUrl.split('data:image/png;base64,')[1] img = Image.open(BytesIO(base64.b64decode(img_data))) output = StringIO() img.save(output, format=img.format) drawing = output.getvalue() new_drawing = Drawing(content=drawing) allDrawings = Drawing.query().fetch() drawings = [] for drawin in allDrawings: if drawin.content == new_drawing.content: drawings.append(drawin) if drawings: new_drawing = drawings[0] threads = Thread.query().fetch() for threadD in threads: if new_drawing.key in threadD.drawings: thread = threads[0] new_edit = Edit.query().filter( Edit.addition == new_drawing.key).fetch()[0] else: content_key = new_drawing.put() thread.drawings.append(content_key) thread_key = thread.put() new_edit = Edit(user=teleUser.key, thread=thread_key, addition=content_key) new_edit.put() confirmation_newThread_template = the_jinja_env.get_template( "confirmation-newthread.html") self.response.write( confirmation_newThread_template.render({ "user_info": user, "thread": thread, "new_edit": new_edit }))
def build_thread(self,form,user): print 'after validate' # print 'Logged in as %s' % user u = UserDT() u.first_name = user u.last_name = "b" u.email = user + "@here.com" p = Post() p.title = "thread description" p.body = form.content.data p.creator = u print ' post - post build ' pe = PostArrayEl() pe.key="1" pe.post=p t = Thread() t.title = form.name.data t.creator = u t.posts.append(pe) print ' thread - post build ' t.postcnt=1 return t
def post(self, thread_name): '''Add a comment to thread.''' args, author_name = parse_and_decode() text = bleach.clean(args['text'], strip=True) # Get thread (add if needed) try: thread = (db.session.query(Thread) .filter(Thread.name == thread_name).one()) except NoResultFound: thread = Thread(name=thread_name) db.session.add(thread) db.session.commit() author_id = get_author_add_if_needed(author_name) now = arrow.utcnow() comment = Comment(author_id=author_id, text=text, thread_id=thread.id, created=now, modified=now) db.session.add(comment) db.session.commit() return get_thread_comments(thread)
def save(self, request): event = Event() start_date = self.cleaned_data['start_date'] start_time = self.cleaned_data['start_time'] end_time = self.cleaned_data['end_time'] event.start_time = datetime.combine(start_date, start_time) event.end_time = datetime.combine(start_date, end_time) event.event_name = self.cleaned_data['event_name'] event.event_location = self.cleaned_data['event_location'] event.event_organizer = self.cleaned_data['event_organizer'] event.event_description = self.cleaned_data['event_description'] event.event_website = self.cleaned_data['event_website'] event.save() acl = ACLUserEvent() acl.user = request.user acl.event = event acl.save() discussiondefs = (( 'PR', _(u'Discussion of the upcoming %s'), _(u'Discuss the upcoming event %s before it actually happens.')), ('LI', _(u'Live discussion of %s'), _(u'Discuss the ongoing event %s live.')), ('PO', _(u'Post-hoc discussion of %s'), _(u'Discuss %s after the facts.'))) for s in discussiondefs: thread = Thread() thread.time = datetime.now() thread.user = request.user thread.event = event thread.thread_type = s[0] thread.title = s[1] % (event.event_name) thread.description = s[2] % (event.event_name) thread.save()
def __init__(self, socket=None, parent=None): super().__init__(parent) self.__socket = socket # Socket to listen to self.__workerThread = Thread.Thread(self)
def unknownThread(): try: recv_data = json.loads(request.get_data('data', parse_form_data=True)) print(recv_data) if recv_data['action'] == "create": try: if request.user_logged: if (request.user.username != recv_data['data']['username']) and (not checkPermission(request.user.group, 'FAKE_USERNAME')): toastsList = [{'code': 400, 'message': 'Not matching with currently logged-in user.', 'identifier': 'message.fakeUsername'}] return {'code': 400, 'data': {}, 'toast': toastsList} except: pass print(recv_data['action']) def rand_str(n): return ''.join([random.choice( string.ascii_lowercase + string.ascii_uppercase + string.digits) for i in range(n)]) newThreadId = rand_str(random.randint(6, 30)) print(newThreadId) session = DBSession() existingThreads = session.query(Thread).filter( Thread.thread == newThreadId).all() print(existingThreads) if not existingThreads: print(recv_data['data']) recv_data['data'].update( {'time': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}) recv_data['data'].update({'floor': 1}) if (not recv_data['data']['title']) and (not recv_data['data']['content']): session.close() toastsList = [ {'code': 400, 'message': 'Nothing is provided', 'identifier': 'message.emptyPost'}] return {'code': 400, 'data': {}, 'toast': toastsList} if not recv_data['data']['title']: recv_data['data'].update({'title': 'Untitled'}) if not recv_data['data']['username']: recv_data['data'].update({'username': request.remote_addr}) if not recv_data['data']['content']: recv_data['data'].update( {'content': 'No description provided.'}) if not recv_data['data']['is_public']: recv_data['data'].update( {'is_public': False}) newThreadMetadata = Thread(thread=newThreadId, is_closed=False, is_deleted=False, is_public=recv_data['data']['is_public'], title=recv_data['data']['title']) newThread = Post(thread=newThreadId, username=recv_data['data']['username'], time=recv_data['data']['time'], floor=recv_data['data']['floor'], is_deleted=False, content=recv_data['data']['content']) session.add(newThread) session.add(newThreadMetadata) session.commit() session.close() return {'code': 200, 'data': {'thread': newThreadId}} else: toastsList = [ {'code': 500, 'message': 'Internal Server Error', 'identifier': 'message.ise'}] return {'code': 500, 'data': {}, 'toast': toastsList} elif recv_data['action'] == "query": session = DBSession() for query_entry in recv_data['data']: if not query_entry['count']: query_entry.update({"count": 100}) if query_entry['type'] == "by_thread_id": resultList = [] if request.user_logged: if checkPermission(request.user_group, "GET_DELETED"): resultList = session.query(Thread).filter(Thread.thread.like(query_entry['thread_id'])).all() else: resultList = session.query(Thread).filter(Thread.thread.like(query_entry['thread_id']), Thread.is_deleted == False).all() else: resultList = session.query(Thread).filter(Thread.thread.like(query_entry['thread_id']), Thread.is_deleted == False).all() entryList = [] for i in resultList: entryList.append(json.loads(i.to_json())) session.close() return {'code': 200, 'data': entryList} except Exception as err: print(err) toastsList = [ {'code': 500, 'message': 'Internal Server Error', 'identifier': 'message.ise'}] return {'code': 500, 'data': {}, 'toast': toastsList}
def create_thread(session, title): new_thread = Thread(title) session.add(new_thread) session.flush() return new_thread
def ask(request): """ Request handler when someone posts a question 1. Add question content to the database 2. Select random active answerer 3. Put the question in the answerer's update stack 4. Send push notification to the answerer's device to retrieve updates """ if request.method == 'POST': json_data = json.loads(request.body) try: question_content = json_data['content'] asker_device_id = json_data['device_id'] max_new_threads = json_data['max_new_threads'] except KeyError: print "Error: A posted question did not have a JSON object with the required properties" else: # then add question to database question = Question(asker_device_id=asker_device_id, content=question_content) question.save() # We are going to start one or more threads with random devices, put the critical information about the thread in this array # and send it back to the device new_thread_ids = []; responder_ids = []; # then select a random device to send the question to all_devices = Device.objects.all() asker_device = all_devices.filter(device_id=asker_device_id)[0]; print "Found asker device" print asker_device print max_new_threads reasonable_number_of_tries = 0 while len(new_thread_ids) < max_new_threads: random_device = random.choice(all_devices) if len(all_devices) > 1 else None print "Chosing random device" print random_device # ensure that we've a valid answerer device if random_device is None: return while len(all_devices) > 1 and random_device.device_id == asker_device_id or random_device.device_id in responder_ids : if reasonable_number_of_tries < 5: random_device = random.choice(all_devices) reasonable_number_of_tries = reasonable_number_of_tries + 1 else: break if reasonable_number_of_tries >= 5: break print "Chose another random device" print random_device responder_ids.append(random_device.device_id) print "But I am" print asker_device_id # find a unique thread id # Start the thread between the asker device and the random device response_thread = Thread(question_id=question.id, asker_device=asker_device, answerer_device=random_device) response_thread.save() new_thread_ids.append(response_thread.id) print "response thread with id: " + str(response_thread.id) # add question to answerer_device update stack QuestionUpdates.add_update(random_device, question) ThreadUpdates.add_update(random_device, response_thread) new_threads = [] for i in range(0, len(new_thread_ids)): new_threads.append({'thread_id':new_thread_ids[i], 'responder_device_id':responder_ids[i]}) return HttpResponse(json.dumps({ 'question_id' : question.id, 'threads' : new_threads }), content_type="application/json")
def post(self): user = users.get_current_user() if not user: self.redirect("/welcome") else: teleUser = TeleUser.get_by_id(user.user_id()) if not teleUser: teleUser = TeleUser.fromGSI(user=user) teleUser.put() edit_type = self.request.get("request_type") print self.request.get("thread_id") thread_id = int(self.request.get("thread_id")) thread_entity_list = Thread.query().filter(Thread.thread_id==thread_id).fetch() if thread_entity_list: thread = thread_entity_list[0] else: thread = Thread(thread_id=thread_id) print thread edit_entity_list = Edit.query().filter(Edit.thread==thread.key).fetch() edit_entity_list.sort(key=lambda x: x.addition.get().date,reverse=True) lastEdit = edit_entity_list[0] if lastEdit.user == teleUser.key: self.redirect("/edit?key="+str(thread.key.id())) if edit_type=="caption": if lastEdit.key.kind() == "Caption": self.redirect("/home?request=failed") return caption = self.request.get("caption") new_caption = Caption(content=caption) content_key = new_caption.put() thread.captions.append(content_key) elif edit_type=="drawing": if lastEdit.key.kind() == "Caption": self.redirect("/home?request=failed") return drawingDataUrl = self.request.get("drawing") img_data = drawingDataUrl.split('data:image/png;base64,')[1] img = Image.open(BytesIO(base64.b64decode(img_data))) output = StringIO() img.save(output, format=img.format) drawing = output.getvalue() new_drawing = Drawing(content=drawing) content_key = new_drawing.put() thread.drawings.append(content_key) else: self.response.write("oof!") return thread_key = thread.put() edit_entity_list = Edit.query().filter(Edit.thread==thread_key).fetch() edit_entity_list.sort(key=lambda x: x.addition.get().date,reverse=True) new_edit = Edit(user=teleUser.key,thread=thread_key,addition=content_key) new_edit.put() for edit in edit_entity_list: print edit.thread.id(),":",edit.thread.get().thread_id,":",edit.addition.kind() last_edit = edit_entity_list[0] confirmation_template = the_jinja_env.get_template("confirmation.html") self.response.write(confirmation_template.render({ "user_info":user, "thread":thread, "last_edit":last_edit, "new_edit":new_edit }))
def initialize(self): # Start off by initializing bluetooth socket self.initBluetoothSocket() # Initialize ResponseReceiver and DeviceContext for possible connections self.__responseReceiver = ResponseReceiver.ResponseReceiver() self.__deviceContext = DeviceContext.DeviceContext() # Ready CommandThread and ServiceLoader thread self.__commandThread = Thread.Thread(self) self.__serviceLoaderThread = Thread.Thread(self) # Initialize ModelAdapter and hand it over to the device model self.__modelAdapter = ModelAdapter.ModelAdapter() self.__model = ModelFilter.ModelFilter(adapter=self.__modelAdapter, parent=self) # Set ListView's model self.__listView.setModel(self.__model) # Initialize CommandModel that'll inhabit all scanned available commands self.__commandModel = CommandModel.CommandModel(self) # Add deviceWidget object as an observer of some attributes of self.__deviceWidget self.__deviceContext.attach(self.__deviceWidget, EVCStatus.AUTHORIZATION.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.CHARGE_POINT.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.FIRMWARE_UPDATE.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.CHARGE_SESSION.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.CURRENT_CHARGE_SESSION.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.CACHED_CHARGE_SESSION.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.DELAY_CHARGE_REMAINING_TIME.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.MASTER_CARD.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.USER_CARD.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.METRICS.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.MIN_CURRENT.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.MAX_CURRENT.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.POWER_OPT_MAX.value) self.__deviceContext.attach(self.__deviceWidget, EVCStatus.POWER_OPT_MIN.value) self.__deviceContext.attach(self.__deviceWidget, EVCSetting.TIMEZONE.value) self.__deviceContext.attach(self.__deviceWidget, EVCSetting.LOCKABLE_CABLE.value) self.__deviceContext.attach(self.__deviceWidget, EVCSetting.AVAILABLE_CURRENT.value) self.__deviceContext.attach(self.__deviceWidget, EVCSetting.POWER_OPTIMIZER.value) self.__deviceContext.attach(self.__deviceWidget, EVCSetting.PLUG_AND_CHARGE.value) self.__deviceContext.attach(self.__deviceWidget, EVCSetting.ETHERNET.value) self.__deviceContext.attach(self.__deviceWidget, EVCSetting.CELLULAR.value) self.__deviceContext.attach(self.__deviceWidget, EVCProgram.ECO_CHARGE.value) self.__deviceContext.attach(self.__deviceWidget, EVCProgram.DELAY_CHARGE.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.CONTRACTOR_WELDED.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.CONTRACTOR_RESPONSE.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.INTERLOCK_LOCK.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.INTERLOCK_UNLOCK.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.PP.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.CP_DIODE.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.OVER_VOLTAGE_P1.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.OVER_VOLTAGE_P2.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.OVER_VOLTAGE_P3.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.UNDER_VOLTAGE_P1.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.UNDER_VOLTAGE_P2.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.UNDER_VOLTAGE_P3.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.OVER_CURRENT_P1.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.OVER_CURRENT_P2.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.OVER_CURRENT_P3.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.RESIDUAL_CURRENT.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.PROTECTIVE_EARTH.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.RFID.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.INTERLOCK_PERMANENT.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.OCP_PERMANENT.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.LOAD_BALANCE_MODULE_1.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.LOAD_BALANCE_MODULE_2.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.LOAD_BALANCE_MODULE_3.value) self.__deviceContext.attach(self.__deviceWidget, EVCError.HMI_EXTERNAL.value) self.__deviceContext.attach(self.__deviceWidget, EVCOptions.DELAY_CHARGE_TIME.value) self.__deviceContext.attach(self.__deviceWidget, EVCOptions.ECO_CHARGE_START_TIME.value) self.__deviceContext.attach(self.__deviceWidget, EVCOptions.ECO_CHARGE_STOP_TIME.value)