我们从Python开源项目中,提取了以下24个代码示例,用于说明如何使用textwrap.shorten()。
def display(self): """Display the found awesome content on result window""" self.result_window.erase() for idx, val in enumerate(self.matched_blocks[self.top:self.top + self.max_lines]): if val['type'] == 'category': if idx == self.current: self.result_window.addstr(idx, 0, shorten(val['line'], self.width, placeholder='...'), curses.color_pair(2)) else: self.result_window.addstr(idx, 0, shorten(val['line'], self.width, placeholder='...'), curses.color_pair(1)) elif val['type'] == 'awesome': if idx == self.current: self.result_window.addstr(idx, 2, shorten(val['line'], self.width - 3, placeholder='...'), curses.color_pair(2)) else: self.result_window.addstr(idx, 2, shorten(val['line'], self.width - 3, placeholder='...')) self.result_window.refresh()
def style_tweet(tweet, porcelain=False): conf = click.get_current_context().obj["conf"] limit = conf.character_limit if porcelain: return "{nick}\t{url}\t{tweet}".format( nick=tweet.source.nick, url=tweet.source.url, tweet=str(tweet)) else: if sys.stdout.isatty() and not tweet.text.isprintable(): return None styled_text = format_mentions(tweet.text) len_styling = len(styled_text) - len(click.unstyle(styled_text)) final_text = textwrap.shorten(styled_text, limit + len_styling) if limit else styled_text timestamp = tweet.absolute_datetime if conf.use_abs_time else tweet.relative_datetime return "? {nick} ({time}):\n{tweet}".format( nick=click.style(tweet.source.nick, bold=True), tweet=final_text, time=click.style(timestamp, dim=True))
def directory_name(release): ''' Returns the proper directory name for a Release. ''' artist = textwrap.shorten(release.album_artist, width=50, placeholder='_') album = textwrap.shorten(release.title, width=40, placeholder='_') year = release.year if release.bitrate == 'V0 (VBR)': format_info = 'V0' elif release.bitrate == '320': format_info = '320' else: format_info = release.format if release.medium != 'CD': format_info = release.medium + ' ' + format_info path = ALBUM_TEMPLATE.substitute(**locals()) if release.catalog_number: path += ' {' + release.catalog_number + '}' path = path.replace('/', '_').replace('\\', '_') path = sanitize_path(path) return path
def __repr__(self): message_snippet = textwrap.shorten(self.message, width=30) return f'<Question {self.uid} {message_snippet!r}>'
def shorten(line): indent = re.match(r"^\s*", line).group() return indent + textwrap.shorten(line, 60)
def escape_latex_verbatim(code): code = re.sub(r"\\end\s*{\s*verbatim\s*}", "", code) return "\n".join((shorten(line) for line in code.splitlines()))
def gen_subcommand_help(self): ''' Generates s ''' commands = sorted(self.subcommands.items(), key=lambda i: i[0]) return '\n'.join( '%s %s' % ( subcommand.ljust(15), textwrap.shorten(description, width=61), ) for subcommand, (description, action, opts) in commands )
def __post(self, data): with aiohttp.Timeout(self.timeout, loop=self.loop): try: response = await self.__session.post(str(self.__url), data=data, headers=self.__headers) except aiohttp.ClientError as e: log.debug('Caught during POST request: %r', e) raise ConnectionError(str(self.url)) else: if response.status == CSRF_ERROR_CODE: # Send request again with CSRF header self.__headers[CSRF_HEADER] = response.headers[CSRF_HEADER] log.debug('Setting CSRF header: %s = %s', CSRF_HEADER, response.headers[CSRF_HEADER]) await response.release() return await self.__post(data) elif response.status == AUTH_ERROR_CODE: await response.release() log.debug('Authentication failed') raise AuthError(str(self.url)) else: try: answer = await response.json() except aiohttp.ClientResponseError as e: text = textwrap.shorten(await response.text(), 50, placeholder='...') raise RPCError('Server sent malformed JSON: {}'.format(text)) else: return answer
def check_shorten(self, text, width, expect, **kwargs): result = shorten(text, width, **kwargs) self.check(result, expect)
def test_width_too_small_for_placeholder(self): shorten("x" * 20, width=8, placeholder="(......)") with self.assertRaises(ValueError): shorten("x" * 20, width=8, placeholder="(.......)")
def brodcast_dificulties(request, message, subject): msg = TalkMessages() msg.text = message msg.user = request.user msg.subject = subject simple_notify = textwrap.shorten(strip_tags(msg.text), width = 30, placeholder = "...") for p in subject.professor.all(): talks = Conversation.objects.filter((Q(user_one = request.user) & Q(user_two__email = p.email)) | (Q(user_two = request.user) & Q(user_one__email = p.email))) if talks.count() > 0: msg.talk = talks[0] else: msg.talk = Conversation.objects.create(user_one = request.user, user_two = p) msg.save() notification = { "type": "chat", "subtype": subject.slug, "space": "subject", "user_icon": request.user.image_url, "notify_title": str(request.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (msg.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": msg}, request), "container": "chat-" + str(request.user.id), "last_date": _("Last message in %s")%(formats.date_format(msg.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % p.id).send({'text': notification}) sendChatPushNotification(p, msg) ChatVisualizations.objects.create(viewed = False, message = msg, user = p)
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image",'') users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.ytvideo.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def sendChatPushNotification(user, message): device = FCMDevice.objects.filter(user = user, active = True).first() if not device is None: serializer = ChatSerializer(message) json_r = json.dumps(serializer.data) json_r = json.loads(json_r) info = {} info["data"] = {} info["data"]["messages"] = [] info["data"]["message_sent"] = json_r info["message"] = "" info["type"] = "" info["title"] = "" info["success"] = True info["number"] = 1 info['extra'] = 0 response = json.dumps(info) title = str(message.user).join(_(" sent a message")) simple_notify = textwrap.shorten(strip_tags(message.text), width = 30, placeholder = "...") if message.image: simple_notify += " ".join(_("[Photo]")) device.send_message(data = {"response": response, "title": title, "body": simple_notify, "user_from": message.user.email, "user_name": str(message.user), "user_img": message.user.image_url, "type": 'chat'})
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image",'') users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.goal.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def trait_code(self): """Create the trait code for the given schema""" kwargs = {} if self.description: kwargs['help'] = textwrap.shorten(self.description, 70) # TODO: handle multiple matches with an AllOf() for TraitExtractor in self.trait_extractors: trait_extractor = TraitExtractor(self) if trait_extractor.check(): return trait_extractor.trait_code(**kwargs) else: raise ValueError("No recognized trait code for schema with " "keys {0}".format(tuple(self.schema.keys())))
def rip(self, ctx, member_or_text: str): """RIP\nCreates a tombstone for either a member or some text. Mention a member to get the avatar + name""" if ctx.message.mentions: user_name = ctx.message.mentions[0].name.replace(" ", "%20") rip_member = ctx.message.mentions[0] ava_url = rip_member.avatar_url url = "https://ripme.xyz/{}" msg = url.format(user_name) tomb = Image.open(os.path.join(asset_pos, "tombstone.png")) base_img = Image.new("RGBA", (tomb.width, tomb.height), color="White") with aiohttp.ClientSession() as session: async with session.get(ava_url) as resp: ava = await resp.content.read() ava_img = Image.open(io.BytesIO(ava)) ava_img_greyscale = ImageOps.autocontrast(ava_img.convert("L").filter(ImageFilter.CONTOUR)).filter( ImageFilter.SMOOTH).resize((200, 200)) base_img.paste(ava_img_greyscale, (140, 380, 340, 580)) final = ImageChops.multiply(base_img, tomb) f = ImageFont.truetype(os.path.join(asset_pos, "Symbola.ttf"), size=35) d = ImageDraw.Draw(final) w, h = d.textsize(rip_member.name, font=f) d.multiline_text(((60 + ((350 - w) / 2)), 315), rip_member.name, fill="Black", font=f, align="center") final.save(os.path.join(asset_pos, "rip.png")) await self.bot.send_file(ctx.message.channel, os.path.join(asset_pos, "rip.png"), content=msg) else: content = ctx.message.content.partition(" ") user_name = content[2].replace(" ", "_") url = "https://ripme.xyz/{}" msg = url.format(user_name) base_img = Image.new("RGB", (520, 640), color="White") tomb = Image.open(os.path.join(asset_pos, "tombstone.png")) base_img.paste(tomb) f = ImageFont.truetype(os.path.join(asset_pos, "Symbola.ttf"), size=35) d = ImageDraw.Draw(base_img) text = textwrap.shorten(content[2], width=25, placeholder="") w, h = d.textsize(text, font=f) d.text(((60 + ((350 - w) / 2)), 315), text, fill="Black", font=f, align="center") d.text((160, 450), "2016 - 2016", fill="Black", font=f) base_img.save(os.path.join(asset_pos, "rip.jpeg")) await self.bot.send_file(ctx.message.channel, os.path.join(asset_pos, "rip.jpeg"), content=msg)
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.pdf_file.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.link.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.webconference.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.bulletin.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.webpage.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro
def form_valid(self, form): message = form.cleaned_data.get('comment') image = form.cleaned_data.get("image") users = (self.request.POST.get('users[]','')).split(",") user = self.request.user subject = self.filelink.topic.subject if (users[0] is not ''): for u in users: to_user = User.objects.get(email=u) talk, create = Conversation.objects.get_or_create(user_one=user,user_two=to_user) created = TalkMessages.objects.create(text=message,talk=talk,user=user,subject=subject,image=image) simple_notify = textwrap.shorten(strip_tags(message), width = 30, placeholder = "...") if image is not '': simple_notify += " ".join(_("[Photo]")) notification = { "type": "chat", "subtype": "subject", "space": subject.slug, "user_icon": created.user.image_url, "notify_title": str(created.user), "simple_notify": simple_notify, "view_url": reverse("chat:view_message", args = (created.id, ), kwargs = {}), "complete": render_to_string("chat/_message.html", {"talk_msg": created}, self.request), "container": "chat-" + str(created.user.id), "last_date": _("Last message in %s")%(formats.date_format(created.create_date, "SHORT_DATETIME_FORMAT")) } notification = json.dumps(notification) Group("user-%s" % to_user.id).send({'text': notification}) ChatVisualizations.objects.create(viewed = False, message = created, user = to_user) success = str(_('The message was successfull sent!')) return JsonResponse({"message":success}) erro = HttpResponse(str(_("No user selected!"))) erro.status_code = 404 return erro