How to Convert an Integer to a String in C

If you need to convert an Integer to a String in C, then you can do one of the following: Option 1 – Use sprintf() int sprintf(char *str, const char *format, [arg1, arg2, ... ]); You can do something like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <stdio.h> int main(void) { int number; char text[20]; printf("Enter a number: "); scanf("%d", &number); sprintf(text, "%d", number); printf("\nYou have entered: %s", text); return 0; } Option 2 – Use itoa() char* itoa(int num, char * buffer, int base)

How to append to an Array in Elasticsearch using elasticsearch-py

If you are using the Official ElasticSearch Python library (Docs), and you want to create an index: 1 2 3 4 5 6 7 doc = { "something": "123a", "somethingelse": "456b", "timestamp": datetime.now(), "history": [] } es.index(index="someindex", doc_type="somedoctype", id="someid", body=doc) You can append items to the history each time, instead of overriding them, like this: 1 2 3 4 5 6 7 8 9 10 es.update(index="someindex", doc_type="somedoctype", id="someid", body={ "script" : { "source": "ctx.

How to Copy Text to the Clipboard in Python

If you need to Copy Text to the Clipboard using your Python application code, then you can do the following: Option 1 – Using pyperclip First install the pyperclip package, using pip: 1 pip install pyperclip Now you can run the following code: 1 2 3 4 5 6 7 8 import pyperclip as pc a1 = "This text will now be in your clipboard" pc.copy(a1) a2 = pc.paste() print(a2) print(type(a2)) Option 2 – Using pyperclip3 This version is similar to the first option above, except it copies all the data into bytes.

How to Read a PDF file in Python

If you need to read a PDF (Portable Document Format) file in your Python code, then you can do the following: Option 1 – Using PyPDF2 1 2 3 4 5 from PyPDF2 import PDFFileReader temp = open('your_document.pdf', 'rb') PDF_read = PDFFileReader(temp) first_page = PDF_read.getPage(0) print(first_page.extractText()) Option 2 – Using PDFplumber 1 2 3 4 import PDFplumber with PDFplumber.open("your_document.PDF") as temp: first_page = temp.pages[0] print(first_page.extract_text()) Option 3 – Using textract 1 2 import textract PDF_read = textract.

How to Convert HEX to RBG in Python

If you need to convert HEX (Hexadecimal) to RGB (Red-Green-Blue) in your Python code, then you can do the following: Option 1 – Using the PIL library 1 2 3 from PIL import ImageColor hex = input('Enter HEX value: ') ImageColor.getcolor(hex, "RGB") Option 2 – Using a custom solution 1 2 hex = input('Enter HEX value: ').lstrip('#') print('RGB value =', tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)))

How to Refer to a Null Object in Python

If you need to refer to a Null Object in your Python code, then you can do the following. It is important to note that Python does not have a Null type, instead Python refers to not set objects or variables as None. We can use the is keyword to check if an object or variable has the type of None. 1 2 3 4 5 object_name = None print(object_name is None) object_name = ' some_value' print(object_name is None)

How to Convert Bytearray to String in Python

If you need to convert a Bytearray to a String in Python, then you can do the following: Option 1 – Using bytes() 1 2 3 b = bytearray("test", encoding="utf-8") str1 = bytes(b) print(str1) Option 2 – Using bytearray.decode() 1 2 3 b = bytearray("test", encoding="utf-8") str1 = b.decode() print(str1)

How to get the Hostname in Python

If you need to get the Hostname in your Python application, then you can do the following: Option 1 – Using gethostname() 1 2 import socket print(socket.gethostname()) Option 2 – Using the platform module 1 2 import platform print (platform.node()) Option 3 – Using os.uname() 1 2 3 import os hname = os.uname() print(hname)

How to get the IP Address in Python

If you need to get the IP Address in your Python application, then you can do the following: Option 1 – Using socket.gethostname() 1 2 import socket print(socket.gethostbyname(socket.gethostname())) Option 2 – Using socket.getsockname() 1 2 3 4 import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) print(s.getsockname()[0]) Option 3 – Using the netifaces module 1 2 3 4 from netifaces import interfaces, ifaddresses, AF_INET for ifaceName in interfaces(): addresses = [i['addr'] for i in ifaddresses(ifaceName).

How to use SSH in your Python application

If you need to make an SSH connection and issues commands over SSH using your Python application, then you can do the following: Option 1 – Using the paramiko library 1 2 3 ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute) Option 2 – Using the subprocess module 1 subprocess.check_output(['ssh', 'my_server', 'echo /*/']) Option 3 – Using the subprocess module 1 subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.

How to Pause a Program in Python

If you need to pause the execution of your Python program, then you can do the following: Option 1 – Using time.sleep() 1 2 3 4 import time time_duration = 3.5 time.sleep(time_duration) Option 2 – Using input() 1 2 name = input("Please enter your name: ") print("Name:", name) Option 3 – Using os.system("pause") 1 2 3 import os os.system("pause")

How to Convert String to Double in Python

If you need to convert a String to a Double in your Python code: Option 1 – Convert String to Double using float() 1 2 3 string = '1234.5678' myfloat = float(string) print(myfloat) Option 2 – Convert String to Double using decimal.Decimal() 1 2 3 4 5 from decimal import Decimal string = '1234.5678' myfloat = Decimal(string) print(myfloat)

How to a Run Bash Command in Python

If you need to run a bash command in your Python code, then you can do the following: Option 1 – Using run() from subprocess Module 1 2 3 4 from subprocess import PIPE comp_process = subprocess.run("ls",stdout=PIPE, stderr=PIPE) print(comp_process.stdout) Option 2 – Using Popen() from subprocess Module 1 2 3 4 5 6 from subprocess import PIPE process = subprocess.Popen("ls",stdout=PIPE, stderr=PIPE) output, error = process.communicate() print(output) process.kill

How to Force Redeployment of AWS API Gateway using AWS CloudFormation

If you have an AWS API Gateway resource, and need it to force a redeployment using CloudFormation, then you can use the TIMESTAMP trick. Example AWS CloudFormation Extract template.yaml extract: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 APIGatewayStage: Type: AWS::ApiGateway::Stage Properties: StageName: !Sub ${EnvironmentTagName} RestApiId: !Ref APIGateway DeploymentId: !Ref APIGatewayDeployment__TIMESTAMP__ TracingEnabled: true MethodSettings: - DataTraceEnabled: true HttpMethod: "*" LoggingLevel: INFO ResourcePath: "/*" MetricsEnabled: true APIGatewayDeployment__TIMESTAMP__: Type: AWS::ApiGateway::Deployment Properties: RestApiId: !

How to Deploy React App to S3 and CloudFront

If you would like to deploy a React App to AWS S3 and AWS CloudFront, then you can follow this guide. The following solution creates a React App and deploys it to S3 and CloudFront using the client’s CLI. It also chains commands so that a React build, S3 sync and CloudFront invalidation can occur with a single command. Code available at GitHub https://github.com/ao/deploy-react-to-s3-cloudfront Target Architecture Guided Deployment Solution Create a directory for the application:

How to Read a File in Python

If you need to read a file in Python, then you can use the open() built-in function to help you. Let’s say that you have a file called somefile.txt with the following contents: 1 2 Hello, this is a test file With some contents How to Open a File and Read it in Python We can read the contents of this file as follows: 1 2 f = open("somefile.txt", "r") print(f.

How to Drop Columns in Pandas Only If Exists

If you have a Pandas DataFrame, and want to only drop columns if they exist, then you can do the following: Add parameter errors to DataFrame.drop: errors : {‘ignore’, ‘raise’}, default ‘raise’ If ‘ignore’, suppress error and only existing labels are dropped. 1 df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore') An example of how to Ignore Errors with .drop() 1 2 3 4 5 6 df = pd.DataFrame({'row_num':[1,2], 'w':[3,4]}) df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore') print (df) w 0 3 1 4

[Solved] An error occurred while calling o86.getDynamicFrame. Exception thrown in awaitResult:

If you are running a GlueJob in AWS and get the following error: An error occurred while calling o86.getDynamicFrame. Exception thrown in awaitResult: Then you need to view the CloudWatch logs to help you pinpoint where the problem is occuring. How to solve the Exception thrown in awaitResult It’s highly likely that the issue is in an expired IAM Role. When a Role is created in IAM, the default maximum session duration is set to 1 hour.