Changing cursor type from python - python

I am making a text based video game with python, and I need a way to change the cursor type from inside python. Here is my code:
from os import system,getenv
from json import loads,dumps
import uuid
apd = getenv("LOCALAPPDATA")
pf = loads(open(rf"{apd}\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json").read())
pf['profiles']['list'].append({"guid":str(uuid.uuid4()),'name':"Game","commandline": "C:\\Windows\\System32\\cmd.exe","cursorShape": "vintage","font": {"face": "Consolas"},})
open(rf"{apd}\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json",'w').write(dumps(pf))
system('wt -F -d {{PATH TO FILE}} -p "Game" --title Game python game.py')

I'm not sure it's a great idea to place a dependency on Windows Terminal, but if you do go that route, the right way to do this is via the JSON fragment extension feature.
Don't risk modifying the user's Windows Terminal settings file directly via Python. Users will be quite (rightly) upset if you muck up their settings if something goes wrong.
JSON fragment extensions give you the ability to create a separate settings fragment that only applies to your application/profile.
For example, create a fragment:
{
"profiles": [
{
"name": "My Game",
"commandline": "python.exe /path/to/game.py",
"cursorShape": "vintage",
"font": {"face": "Consolas"}
}
]
}
Place this file in either:
C:\ProgramData\Microsoft\Windows Terminal\Fragments\{app-name}\{file-name}.json: For all users on the system
C:\Users\<user>\AppData\Local\Microsoft\Windows Terminal\Fragments\{app-name}\{file-name}.json: For only the current user

Related

Add Python Script as a file to AWS SSM Document (YAML)

I'm trying to write a script for a SystemsManager Automation document and would like to keep the Python code in a seperate file so it's easy to invoke on my local machine. For complex scripts they can also be tested using a tool such as unittest.
Example YAML syntax from my SSM Automation:
mainSteps:
- name: RunTestScript
action: aws:executeScript
inputs:
Runtime: python3.8
Handler: handler
InputPayload:
Action: "Create" # This is just a random payload for now I'm only testing
Script: |-
"${script}" # My script should be injected here :)
Note: Yes, I've written the script directly in YAML and it works fine. But I'd like to achieve something similar to:
locals {
script = file("${path.module}/automations/test.py")
}
resource "aws_ssm_document" "aws_test_script" {
name = "test-script"
document_format = "YAML"
document_type = "Automation"
content = templatefile("${path.module}/automations/test.yaml", {
ssm_automation_assume_role = aws_iam_role.ssm_automation.arn
script = local.script
})
}
My console shows that yes the file is being read correctly.
Terraform plan...:
+ "def handler(event, context):
+ print(event)
+ import boto3
+ iam = boto3.client('iam')
+ response = iam.get_role(
+ RoleName='test-role'
+ )
+ print(response)"
Notice how the indentation is broken? My .py file has the correct indentation.
I suspect one of the terraform functions or YAML operators I'm using it breaking the indentation - which is very important for a language such as Python.
If I go ahead and Terraform apply I receive:
Error: Error updating SSM document: InvalidDocumentContent: YAML not well-formed. at Line: 30, Column: 1
I tried changing the last line in my YAML to be Script: "${script}" and I can Terraform Plan and Apply fine, but the Python script is on a single line and fails when executing the automation in AWS.
I've also tried using indent(4, local.script) without success.
Keen to hear/see what ideas and solutions you may have.
Thanks
I noticed my plan output had "'s around the code. So I tried a multiline string in Python """ and it continued to fail. Bearing in mind I assumed SSM was smart enough to strip quotes if it doesn't want them.
Anyway, the mistake was adding quotes around the template variable:
# Mistake
Script: |-
"${script}" # My script should be injected here :)
Solution
Script: |-
${script}
After that I decided okay now that it works, can I remove the indent() method I'm using and I got the YAML not well-formed error back.
So using:
locals {
script = indent(8, file("${path.module}/automations/test.py"))
}
resource "aws_ssm_document" "test_script" {
name = "test-script"
document_format = "YAML"
document_type = "Automation"
content = templatefile("${path.module}/automations/test.yaml", {
ssm_automation_assume_role = aws_iam_role.ssm_automation.arn
script = local.script
})
}
Works great with:
mainSteps:
- name: RunDMSRolesScript
action: aws:executeScript
inputs:
Runtime: python3.8
Handler: handler
InputPayload:
Action: "create"
Script: |-
${script}
If it helps anyone, this is what my SSM Script looks like in the AWS UI when it runs without errors. Formatted correctly and AWS seems to append " around it but turned into "\" when I provided quotes in my YAML template which would've broken the script as it's now a string literal.
"def handler(event, context):
print(event)
import boto3
iam = boto3.client('iam')
response = iam.get_role(
RoleName='test-role'
)
print(response)"
That's one way to lose 3 hours!

Not working 'activate terminal node' and 'add_existing_component' in python(pycaita)

Here's some simple code for pycatia [PYCATIA site download],
but it seems to be seen not working in my computer.
it looks like File load is totally sucessful.
but all product/cgr is not activated,
becaused of "Do not activate default shapes on open" option in my catia.
Though 'activate_terminal_node' code is commanded, it doen't work properly.
and please let me know how to use 'add_components_from_files' method
thanks in advance
from pycatia import catia
from pycatia.enumeration.enumeration_types import cat_work_mode_type
from pycatia.product_structure_interfaces.product import Product
caa = catia()
documents = caa.documents
documents.open(r'D:\CATIA\test.CATProduct')
document = caa.active_document
product = document.product()
product.apply_work_mode(cat_work_mode_type.index("DESIGN_MODE"))
Product.activate_terminal_node(product.get_products())

Google Vision Api in python stopped working - beginner coder alarm

I was interested in coding a long time. So this year I got a job where I was supposed to scrape text from old event programs. The pictures where terrible quality and results with normal OCR where horrible. I checked the google vision api and tested it manually and the results where great, so I used this opportunity to learn about coding.( I did some python before but the lack of usefulness always drove me away).
I wrote this program, I know its walking on crouches but it worked and did exactly what I wanted for 3 months now. I dont use it regularly but today when I wanted to use it again, it didnt work any more it just jumps to the end of the program, and finishes without making the api requests, at least so it seems to me.
I am really mostly finished with my work and this request doesnt make sense in terms of efficiency but I am just curious why the program I created suddenly stopped working.
If somebody can hint me in the right direction I would highly appreciate it, also if somebody wants to use the program, if it works for them sure let it work instead of yourself :D
I am not sure but I am using linux mint and maybe it stopped working because of some updates of python or vision-api or something.
# coding=utf-8
from google.cloud import vision
import os
import io
import sys
reload(sys)
sys.setdefaultencoding('utf8')
directory = "/home/weareone/Documents/programming/test/here"
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/home/weareone/Documents/programming/test/key.json"
def workinghard(page):
client = vision.ImageAnnotatorClient()
#file_name = os.path.join( os.path.dirname(__file__), page) # Loads the image into memory
#page_er = os.path.abspath(os.path.join(os.path.dirname(page))) <--- my improvisation
with io.open( page, 'rb') as image_file: # after io.open.(file_name <---exchanged with "page")
content = image_file.read()
request = {
"image": {
"content": content
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
response = client.annotate_image(request)
storage = response.full_text_annotation.text
return storage
def listdirs(folder):
return [
d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
if os.path.isdir(d)
]
directories = listdirs(directory)
for year in directories:
logtxt = open(year + ".txt", "w+" )
for root, dirs, files in os.walk(year):
files.sort()
for file23 in files:
if file23.endswith('.jpg'):
pathparent = os.path.join(year,file23)
logtxt.write(workinghard(pathparent))
logtxt.write("-------------------------------------------------------------------------")
print(pathparent)
logtxt.close()
print("DONE")
Thank you very much dear internet
EDIT: I solved it by changing this line the statement apaprently equaled to FALSE.
if file23.endswith('.JPG'):

How to use variables from backend in .scss files

I have a site built with Django, Python and Wagtail.
What I want is to be able to add some styles in the backend and then use it in my frontent's .scss files.
For example I want to be able to set a primary color to #fff via backend and then use it in my .scss file as:
$g-color-primary: primary_color_from_backend;
$g-font-size-default: primary_font_size_from_backend;
I do not have any idea how I can do that and if it's possible at all?
Thanks for the help.
Unfortunately, it is not possible. You can instead define different classes in the CSS file, then use them in your HTML template dependent on the Django template variables there.
This would require to write out the sass color variables content (with scss syntax) in a physical .scss file, which depends on your development environment. And then import it into other .scss file to get compiled and output through a frontend build process tool like Gulp, Webpack.
For example, Webpack's sass-loader plugin provides option to prepend sass code at Frontend build/compile time.
https://github.com/webpack-contrib/sass-loader
module.exports = {
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [
'style-loader',
'css-loader',
{
loader: 'sass-loader',
options: {
prependData: '$env: ' + process.env.NODE_ENV + ';',
},
},
],
},
],
},
};

how can i pass xml format data from flex to python

i want to pass xml format data into python from flex.i know how to pass from flex but my question is how can i get the passed data in python and then the data should be inserted into mysql.and aslo i want to retrieve the mysql data to the python(cgi),the python should convert all the data into xml format,and pass all the data to the flex..
Thank's in advance.....
See http://www.artima.com/weblogs/viewpost.jsp?thread=208528 for more details, here is a breif overview of what I think you are looking for.
The SimpleXMLRPCServer library allows you to easily create a server. Here's about the simplest server you can create, which provides two services to manipulate strings:
import sys
from random import shuffle
from SimpleXMLRPCServer import SimpleXMLRPCServer
class MyFuncs:
def reverse(self, str) :
x = list(str);
x.reverse();
return ''.join(x);
def scramble(self, str):
x = list(str);
shuffle(x);
return ''.join(x);
server = SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(MyFuncs())
server.serve_forever()
Once you make a connection to the server, that server acts like a local object. You call the server's methods just like they're ordinary methods of that object.
This is about as clean an RPC implementation as you can hope for (and other Python RPC libraries exist; for example, CORBA clients). But it's all text based; not very satisfying when trying to create polished applications with nice GUIs. What we'd like is the best of all worlds -- Python (or your favorite language) doing the heavy lifting under the covers, and Flex creating the user experience.
To use the library, download it and unpack it somewhere. The package includes all the source code and the compiled as3-rpclib.swc library -- the .swc extension indicates an archive file, and pieces of this library can be pulled out and incorporated into your final .swf. To include the library in your project, you must tell Flexbuilder (you can get a free trial or just use the free command-line tools, and add on the Apollo portion) where the library is located by going to Project|Properties and selecting "Apollo Build Path," then choosing the "Library path" tab and pressing the "Add SWC..." button. Next, you add the namespace ak33m to your project as seen in the code below, and you're ready to create an XMLRPCObject.
Note: the only reason I used Apollo here was that I was thinking in terms of desktop applications with nice UIs. You can just as easily make it a Flex app.
Here's the entire Apollo application as a single MXML file, which I'll explain in detail:
<?xml version="1.0" encoding="utf-8"?>
<mx:ApolloApplication xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:ak33m="http://ak33m.com/mxml" layout="absolute">
<mx:Form>
<mx:FormHeading label="String Modifier"/>
<mx:FormItem label="Input String">
<mx:TextInput id="instring" change="manipulate()"/>
</mx:FormItem>
<mx:FormItem label="Reversed">
<mx:Text id="reversed"/>
</mx:FormItem>
<mx:FormItem label="Scrambled">
<mx:Text id="scrambled"/>
</mx:FormItem>
</mx:Form>
<ak33m:XMLRPCObject id="server" endpoint="http://localhost:8000"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.AsyncToken;
import mx.controls.Alert;
import mx.collections.ItemResponder;
private function manipulate() : void {
server.reverse(instring.text).addResponder(new ItemResponder(reverseResult, onFault));
server.scramble(instring.text).addResponder(new ItemResponder(scrambleResult, onFault));
}
private function reverseResult(event : ResultEvent, token : AsyncToken = null) : void {
reversed.text = event.result.toString();
}
private function scrambleResult(event : ResultEvent, token : AsyncToken = null) : void {
scrambled.text = event.result.toString();
}
private function onFault (event : FaultEvent, token : AsyncToken = null) : void {
Alert.show(event.fault.faultString, event.fault.faultCode);
}
]]>
</mx:Script>
</mx:ApolloApplication>

Categories

Resources