Renpy python variable text color - python

I started making a novel and learn renpy really recently, and I came across a difficulty that I couldn't find the solution. I put an input for the user to define the name of the protagonist, but when I declare the character, the color that I designated to appear in the text box is not working.
Here a piece of my code:
python:
sn = ""
define luca = Character(" Luca Kaneshiro", color="#ffffff")
define sn = Character("%(sn)s", color="#ffffff")
label start:
call askname
luca "Hey %(sn)s."
sn "Hi, Luca!"
label askname:
$ sn = renpy.input("What's my name?", length=32)
here's how the text in displayed
I was expecting it to be displayed in white color, but instead it was displayed in yellow, the collor that I defined for gui.accent_color. Is there any solution for that? A way to turn the text in the sn variable into a normal text or something like this?

According to Renpy's documentation on Character, you need to attached a who_style arguments, specifically who_color in this case:
define sn = Character("%(sn)s", who_color="#ffffff")
Also, unrelated but renpy doc uses square bracket for string/text interpolation instead, so in case the above doesn't work, try the following:
define sn = Character("[sn]", who_color="#ffffff")

Related

Python + Open AI/GPT3 question: Why is part of my prompt spilling into the responses I receive?

This happens to probably 10% of responses I get. For whatever reason, the last bits of my prompt somehow spill into it, at the start of it. Like there will be a period, or a question mark, or sometimes a few of the last letters from the prompt, that get removed from the prompt, and somehow find their way into BOTH the response that gets printed inside of the Visual Studio Code terminal, AND in the outputted version that gets written to a corresponding Excel spreadsheet.
Any reason why this might happen?
Some example responses:
.
Most apples are colored red.
Also
?
Most rocks are colored gray.
Another example:
for it.
Most oceans are colored blue.
The period, the question mark, " for it" somehow get transposed FROM the end of the prompt, and tacked onto the response. And they even get removed from the prompt that was originally in the Excel spreadsheet to begin with.
Could this be a bug with xlsxwriter? open ai? Some combo of both?
Code here:
import xlsxwriter
import openpyxl
import os
import openai
filename = f'testing-openai-gpt3-requests-v1.xlsx'
wb = openpyxl.load_workbook(filename, read_only=False)
sheet = wb.active
# print("starting number of ideas is:")
# print(sheet.max_row)
for x in range(sheet.max_row):
c = sheet.cell(row = x+1, column = 1)
# print(c.value)
myCurrentText = c.value
myCurrentPrompt = "What is the color of most of the following objects: " + myCurrentBusinessIdea
openai.api_key = [none of your business]
response = openai.Completion.create(
model = "text-davinci-003",
prompt = myCurrentPrompt,
max_tokens = 1000,
)
TheOutputtedSummary = response['choices'][0]['text']
print(TheOutputtedSummary)
sheet.cell(row = x+1, column = 6).value = TheOutputtedSummary
wb.save(str(filename))
print('All finished!')
GPT-3 is a powerful language model capable of generating human-like text based on the input provided. However, it is important to ensure that the input text is clear and well-formatted in order to get the desired output.
One way to avoid issues with incomplete sentences is to ensure that your input text always ends with a full stop or other appropriate punctuation. This can help GPT-3 understand that the input text is complete, and prevent it from generating text that appears to be part of the input.
Here's how I solved the issue on a project I worked on. The project is a website featuring Amazon products, and it includes descriptions of the products based on reviews from purchasers.
It is important to be as clear as possible when generating a prompt for GPT-3, as this can help ensure that the model produces the desired output. Here's an example of a clear and well-formatted prompt:
"I will ask you a question and provide you with a list of objects.
Please tell me the colour of most of the following objects:
[dynamic text]
END OF THE LIST."

AutocompleteInput for all words in string (Bokeh)

I've made an interactive Bokeh plot with an AutocompleteInput widget (link here - the widget is the name input on the left hand side).
The auto completion currently only works with exact matches of the entire string.
Is there a way for it to work with any word in the string, with words being deliminated by spaces?
The code used for the widget is below, and an abridged list that makes up the completions.
name_list = ['Takehiro Tomiyasu', 'Marco Benassi', 'Leandro Barreiro Martins']
name = AutocompleteInput(title='Highlighted player name:', value='Takehiro Tomiyasu', completions=name_list,
restrict=True, case_sensitive=False)
Many thanks.

How can I accurately set the new cursor positions after text replacements have been made

I am trying to adapt a plugin for automated text replacement in a Sublime Text 3 Plugin. What I want it to do is paste in text from the clipboard and make some automatic text substitutions
import sublime
import sublime_plugin
import re
class PasteAndEscapeCommand(sublime_plugin.TextCommand):
def run(self, edit):
# Position of cursor for all selections
before_selections = [sel for sel in self.view.sel()]
# Paste from clipboard
self.view.run_command('paste')
# Postion of cursor for all selections after paste
after_selections = [sel for sel in self.view.sel()]
# Define a new region based on pre and post paste cursor positions
new_selections = list()
delta = 0
for before, after in zip(before_selections, after_selections):
new = sublime.Region(before.begin() + delta, after.end())
delta = after.end() - before.end()
new_selections.append(new)
# Clear any existing selections
self.view.sel().clear()
# Select the saved region
self.view.sel().add_all(new_selections)
# Replace text accordingly
for region in self.view.sel():
# Get the text from the selected region
text = self.view.substr(region)
# Make the required edits on the text
text = text.replace("\\","\\\\")
text = text.replace("_","\\_")
text = text.replace("*","\\*")
# Paste the text back to the saved region
self.view.replace(edit, region, text)
# Clear selections and set cursor position
self.view.sel().clear()
self.view.sel().add_all(after_selections)
This works for the most part except I need to get the new region for the edited text. The cursor will be placed to the location of the end of the pasted text. However since I am making replacements which always make the text larger the final position will be inaccurate.
I know very little about Python for Sublime and like most others this is my first plugin.
How do I set the cursor position to account for the size changes in the text. I know I need to do something with the after_selections list as I am not sure how to create new regions as they were created from selections which are cleared in an earlier step.
I feel that I am getting close with
# Add the updated region to the selection
self.view.sel().subtract(region)
self.view.sel().add(sublime.Region(region.begin()+len(text)))
This, for some yet unknown to me reason, places the cursor at the beginning and end of the replaced text. A guess would be that I am removing the regions one by one but forgetting some "initial" region that also exists.
Note
I am pretty sure the double loop in the code in the question here is redundant. but that is outside the scope of the question.
I think your own answer to your question is a good one and probably the way I would go if I was to do something like this in this manner.
In particular, since the plugin is modifying the text on the fly and making it longer, the first way that immediately presents itself as a solution other than what your own answer is doing would be to track the length change of the text after the replacements so you can adjust the selections accordingly.
Since I can't really provide a better answer to your question than the one you already came up with, here's an alternative solution to this instead:
import sublime
import sublime_plugin
class PasteAndEscapeCommand(sublime_plugin.TextCommand):
def run(self, edit):
org_text = sublime.get_clipboard()
text = org_text.replace("\\","\\\\")
text = text.replace("_","\\_")
text = text.replace("*","\\*")
sublime.set_clipboard(text)
self.view.run_command("paste")
sublime.set_clipboard(org_text)
This modifies the text on the clipboard to be quoted the way you want it to be quoted so that it can just use the built in paste command to perform the paste.
The last part puts the original clipboard text back on the clipboard, which for your purposes may or may not be needed.
So, one approach for this would be to make new regions as the replaced text is created using their respective lengths as starting positions. Then once the loop is complete clear all existing selections and set the new one we created in the replacement loop.
# Replace text accordingly
new_replacedselections = list()
for region in self.view.sel():
# Get the text from the selected region
text = self.view.substr(region)
# Make the required edits on the text
text = text.replace("\\","\\\\") # Double up slashes
text = text.replace("*","\\*") # Escape *
text = text.replace("_","\\_") # Escape _
# Paste the text back to the saved region
self.view.replace(edit, region, text)
# Add the updated region to the collection
new_replacedselections.append(sublime.Region(region.begin()+len(text)))
# Set the selection positions after the new insertions.
self.view.sel().clear()
self.view.sel().add_all(new_replacedselections)

Python to find out, from coordinates of non- habitable areas to location/address

Hello all… my question is regarding how to find out the location of a pair of geographical coordinates. Sorry the questions are fragmented because I did some searches and putting them together still doesn't find the right way.
1st question:
Seems Geopy is the best way to geocoding, if some outputs in non-English words is not a matter. (any help is warmly welcome for solving the non-English output problem)
However some of coordinates I need to search is in non- habitable areas.
An example below:
from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.reverse("81.79875708, -42.1875")
print(location.address)
It returns.
None
When search this coordinates on https://maps.google.com/, it indicates the nearest recognized point “Northeast Greenland National Park”, which is better than “None”.
So how can I get this “nearest recognized point”?
2nd question on using “pygmaps”
aamap = pygmaps.maps(81.79875708, -42.1875, 16)
the output is:
<pygmaps.maps instance at 0x000000000313CC08>
What’s the use of it, and how to turn it into texts?
3rd question using the “Json” way:
response = urllib2.urlopen('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA')
js = json.load(response)
print js['results'][0]['geometry']['location']
Is there a way to reverse? i.e. using coordinates to find out its addresses.
Thanks.
I cannot answer all your questions but, regarding your second question I suppose that you made use of print(aamap) to get the output.
The default behavior when printing an object that doesn't specify a way to be print is to print its class and its memory location. That is the result you obtained.
<pymaps.maps instance at 0x0000000000313CC08>
Test this code to understand :
class NotPrintable(object):
def __init__(self, text):
""" Instanciation method """
self.text = text
class Printable(object):
def __init__(self, text):
""" Instanciation method """
self.text = text
def __repr__(self):
""" Text representation of the object called by print"""
return "A printable object whose the value is : {0}".format(self.text)
if __name__ == "__main__":
print( NotPrintable("StackOverFlowTest") )
print( Printable("StackOverFlowTest") )
The result is :
<__main__.NotPrintable object at 0x7f2e644fe208>
A printable object whose the value is : StackOverFlowTest
The result you get indicate that you are not supposed to print the item to visualize its content. A quick search on "google" lead me to this site : https://code.google.com/p/pygmaps/
It provides example of code using pymaps, and it appear that the good way to visualize the data is :
#create the map object
mymap = pygmaps.maps(37.428, -122.145, 16)
#export the map
mymap.draw('./mymap.html')
That create an HTML page that contain your map.
If interested in, you could take a look at the maps code at https://code.google.com/p/pygmaps/source/browse/trunk/pygmaps.py but it seems that it is the only way to output the object data. If you really have to provide a text output, you'll probably have to code the export by yourself.
Hope it helps!
=====EDIT=====
Concerning the googlemap JSON API, seeing the documentation : https://developers.google.com/maps/documentation/geocoding/
You can find in the first lines information about Reverse geocoding, i.e.
The process of [...] translating a location on the map into a human-readable address, is known as reverse geocoding.
See this particulary : https://developers.google.com/maps/documentation/geocoding/#ReverseGeocoding
here is an example of query for information about the location whose the latitude is "40.71" and the longitude is "-73.96" :
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.71,-73.96&key=API_KEY
Here is the documentation about API_key : https://developers.google.com/console/help/#UsingKeys

python in terminal - how to get current colour?

I have read a couple of URLs about setting colour in terminal. But after a colour change a while later I'd like to reset into previous colour. How can I get current colour ?
(I'd like to avoid third party libraries and use only batteries included ;-))
Especially (from (python) colour printing with decorator in a function ):
import sys
green = '\033[01;32m'
red = '\033[01;31m'
... remember current colours here ...
sys.stdout.write(green+"Hello ")
sys.stderr.write(red+"world!")
You can return default color the same way you colorize your texts:
native = '\033[m'
sys.stdout.write(native)
Thus temporary coloring may be achieved with
print green + 'Hello' + native

Categories