def divide(a, b):
    try:
        return a / b
    except:
        x = 17

My smart exception handling before meeting "pass" :))

By mophix, 2017-12-15 18:13:07
product = None
for key in dictionary.keys():
	if product is None:
		product = dictionary[key]
	else:
		product = itertools.product(product, dictionary[key])

product = "{0}".format(list(product))
product = re.sub(r"\), \(+", "], [", product)
product = re.sub(r"\(+", "[", product)
product = product.replace(")]", "]]").replace(")", "")
product = ast.literal_eval(product)

Ok, I have a weird array of objects as output of itertools and I need an array of strings... 1 - Convert the array to string 2 - Clean it up with regex and replace 3 - Convert the string to array 4 - Problem solved

By AnonimaPitoni, 2018-09-06 00:27:34
try:
    raise
except RuntimeError:
    raise

try this in python3

By FranchuFranchu, 2019-03-14 23:10:03
A,B=map(str,input().split())        # let's begin by casting strings to strings!

while(int(A)!=0 and int(B)!=0):

    tamanhoa=0
    tamanhob=0

    for i in range(len(A)):
        tamanhoa+=1                 # wonderful way to determine the length of
                                    # a string!
    for i in range(len(B)):
        tamanhob+=1

    vA = [0]*tamanhoa
    vB = [0]*tamanhob

    if tamanhoa>tamanhob:
        vA = [0]*tamanhoa           # Just to make sure it really gets set!!!
        vB = [0]*tamanhoa

        for i in range(tamanhoa-1,-1,-1):
            vA[i]=int(A[i])         # he even saved an operation by casting
                                    # the char to int at the same time!
        for i in range(tamanhob):
            vB[i+1]=int(B[i])
    elif tamanhoa<tamanhob:
        vA = [0]*tamanhob           # Just to make sure it really gets set!!!
        vB = [0]*tamanhob

        for i in range(tamanhoa):
            vA[i+1]=int(A[i])

        for i in range(tamanhob-1,-1,-1):
            vB[i]=int(B[i])

        tamanhoa=tamanhob

    else:
        for i in range(tamanhoa):
            vA[i]=int(A[i])

        for i in range(tamanhob):
            vB[i]=int(B[i])

    print(vA)
    print(vB)
    
    carry = 0

    for i in range(tamanhoa-1,-1,-1):
        soma = vA[i] + vB[i]
        if soma > 9:
            carry += 1
            if vA[i-1]!= 9:
                vA[i-1] += 1
            else:
                vB[i-1] +=1


    if carry == 0:
        print('No carry operation.')
    elif carry == 1:
        print(carry, 'carry operation.')
    else:
        print(carry, 'carry operations.')

    A,B=map(str,input().split())    # why bother casting strings to int? yay

    if int(A)==0 and int(B)==0:
        break

This wonder was found within answers to a university programming test. Code as-is, comments added by me.

By Anonymous, 2017-12-14 00:09:27
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while (1):

    _, frame = cap.read()

    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

    lower_green = np.array([40, 50, 50])
    upper_green = np.array([80, 102, 200])

    # Threshold the HSV image to get only green colors
    mask = cv2.inRange(hsv, lower_green, upper_green)

    total_pixels = mask.shape[0] * mask.shape[1]
    print "Number of pixels: %", total_pixels

    pixel_counter = 0
    x_counter = 0
    y_counter = 0
    for y in xrange(640):
        for x in xrange(480):
            pixel = mask[x, y]
            if pixel == 255:
                pixel_counter += 1
                x_counter += x
                y_counter += y
    x_center = x_counter / pixel_counter
    y_center = y_counter / pixel_counter
    print x_center, y_center

    cv2.line(frame, (x_center+15, y_center), (x_center+2, y_center), (235, 218, 100), 1)
    cv2.line(frame, (x_center-15, y_center), (x_center-2, y_center), (235, 218, 100), 1)
    cv2.line(frame, (x_center, y_center+15), (x_center, y_center+2), (235, 218, 100), 1)
    cv2.line(frame, (x_center, y_center-15), (x_center, y_center-2), (235, 218, 100), 1)

    cv2.circle(frame, (x_center, y_center), 4, (235, 218, 100), 2)

    cv2.imshow('frame', frame)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cv2.destroyAllWindows()

track the green color

By Vik.victory, 2017-06-23 19:11:14
apps_to_be_deployed = apps_to_be_deployed.strip()
if apps_to_be_deployed.endswith(":"):
    apps_to_be_deployed_length = len(apps_to_be_deployed)
    apps_to_be_deployed_list = list(apps_to_be_deployed)
    apps_to_be_deployed_list[apps_to_be_deployed_length - 1] = ''
    apps_to_be_deployed = "".join(apps_to_be_deployed_list)
By jlo, 2019-09-14 01:16:59
def possibilities():
    alphabets=(n,o,r,t,h,e,a,s,u,w,m,y)
    combinations=list()
    for n in range(9,-1,-1):
            for o in range(9,-1,-1):
                    for r in range(9,-1,-1):
                            for t in range(9,-1,-1):
                                    for h in range(9,-1,-1):
                                            for e in range(9,-1,-1):
                                                    for a in range(9,-1,-1):
                                                            for s in range(9,-1,-1):
                                                                    for u in range(9,-1,-1):
                                                                            for w in range(9,-1,-1):
                                                                                    for m in range(9,-1,-1):
                                                                                            for y in range(9,-1,-1):
                                                                                                    if len(set([n,o,r,t,h,e,a,s,u,w,m,y]))==12:
                                                                                                    north=10000*n + 1000*o +100*r +10*t +h
                                                                                                    east=1000*e +100*a +10*s +t
                                                                                                    south=10000*s + 1000*o +100*u +10*t +h
                                                                                                    west=1000*w + 100*e +10*s +t
                                                                                                    earth= 10000*e + 1000*a + 100*r +10*t +h
                                                                                                    if north +east +south +west == earth:
                                                                                                            combinations.append((north,east,south,west,earth))

    return combinations
By Dusk Code, 2018-04-25 11:47:49
from django.http import JsonResponse, HttpResponse
import requests

def download_custom_award(request):
    try:
        custom_img = requests.get(request.GET.get('award'))
        response = HttpResponse(custom_img.content, content_type='application/PNG')
        filename = "Your_Award.png"
        response['Content-Disposition'] = 'attachment; filename=%s' % (filename)
        return response
    except Exception as e:
        return JsonResponse({'Status': 404, "message": e.message})

This developer was trying to force the browser to download a custom image rather than show it inline, so he coded an open reverse proxy and attempted to release it to a production web app. Also, all exceptions are trapped and shown to the user in plaintext in their browser.

By Anonymous, 2020-05-26 10:38:31
def get_verified_infos(request):
    try:
        # request logic here
        return data
    except Exception:
        logger.error(
            'Request to XXX was unsuccessful, '
            'Will retry till max recursion! Retrying...'
        )
        return get_verified_infos(request)

Used for OpenID authentication

By Anonymous, 2020-11-04 18:28:11
j =0
import random
import hashlib
#geetting inputs
c = input("data  ")
n= int(input("N(the count of last numbers)=  "))
v= input(str(n)+" last char  ")
#list of alphas
l1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z', 'u']
l2 = ["A", 'B', 'C', 'D', 'E', 'F','G' , 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Y', 'Z', 'U']
alphas= 0
#calc the count of alppphas
x=""
for j in c:
    if(j in l1 or j in l2):
        alphas +=1
#positions
h = 2**alphas
hs = []
cc =0
j=0
xf =0
# the stat of main coode
for j in range(h):
    #making a sring with 1 and 0
    while True:
        x=""
        for i in range(len(c)):
            x+=str(random.randint(0,1))
        if(not(x in hs)):
            hs.append(x)
            break
    Xx =""
    cc =0
    #convert that to lower and upper
    for j1 in x:
        if(j1=="0"):
            Xx+=c[cc].lower()
        else:
            Xx+=c[cc].upper()
        cc+=1
    #hash
    m = hashlib.sha256()
    m.update(Xx.encode('utf-8'))
    h = m.hexdigest()
    #if
    if(h[0-n:]==v):
        print("text :"+Xx)
        print("hash :"+h)
        xf = True
        break
    if xf==True:
        break
j =0
#if that not possible to have git push -Desirable-hash by changed lower to upper and upper to lower
if(xf==0):
    while 1:
        j+=1
        d = c+str(j)
        m = hashlib.sha256()
        m.update(d.encode('utf-8'))
        h = m.hexdigest()
        if(h[0-n:]==v):
            print("text :"+d)
            print("hash :"+h)
            break
x = input("press enter to exit")0

this program take a string from you and give you a Desirable-hash by changing lower to upper and changing lower to upper if that possible

By shamsnaamir, 2019-12-13 10:04:28
        if "[trait]" in lines[i]:
            in_trait = True
        elif "[/trait]" in lines[i]:
            in_trait = False
        elif "[object]" in lines[i]:
            in_object = True
        elif "[/object]" in lines[i]:
            in_object = False
        elif "[stage]" in lines[i]:
            in_stage = True
        elif "[/stage]" in lines[i]:
            in_stage = False
        elif "[cfg]" in lines[i]:
            in_cfg = True
        elif "[/cfg]" in lines[i]:
            in_cfg = False
        elif "[goal]" in lines[i]:
            in_goal = True
        elif "[/goal]" in lines[i]:
            in_goal = False
#... 150 more lines of this

Basically, linting a config file with a DOM tree, using Python

By Anonymous, 2019-12-28 23:35:11
# Create vpc peering connection
response = ec2.delete_vpc_peering_connection(peer_connection_id)

a part of AWS Landing Zone solution

By Amazon Solutions, 2019-07-10 12:49:42
def _take_items_from_list_and_put_them_into_string(self, list):
    string = ''
    for element in list:
        string += element + ','
    if len(string) > 0 and string[-1] == ',':
        string = string[0:-1]
    return string
By JK, 2017-12-13 13:54:43

    def dow_to_dict_from_self(self):
        # res = {'name': self.name, 'enabled': self.enabled }
        res = {'sun': 0, 'mon': 0, 'tue': 0, 'wed': 0, 'thr': 0, 'fri': 0,
               'sat': 0,
               'enabled': 0, 'dow': 0, 'name': 'untitled'}

        if (int(self.days_of_week) & 0x01) == 0x01:  # sun
            res['sun'] = 1
        if (int(self.days_of_week) & 0x02) == 0x02:  # mon
            res['mon'] = 1
        if (int(self.days_of_week) & 0x04) == 0x04:  # tue
            res['tue'] = 1
        if (int(self.days_of_week) & 0x08) == 0x08:  # wed
            res['wed'] = 1
        if (int(self.days_of_week) & 0x10) == 0x10:  # thr
            res['thr'] = 1
            res['thu'] = 1  # '%a' returns thu for Thursday
        if (int(self.days_of_week) & 0x20) == 0x20:  # fri
            res['fri'] = 1
        if (int(self.days_of_week) & 0x40) == 0x40:  # sat
            res['sat'] = 1
        if (int(
                self.days_of_week) & 0x40) == 0x80:  # enabled # new enable#
            # flag -- duplicate in db
            res['enabled'] = 1

        res['enabled'] = self.enabled  # remove this
        res['dow'] = self.days_of_week
        res['name'] = self.name

        return res

kept the original comments - they're very helpful

By Anonymous, 2018-07-11 19:40:44
if HOST == 'AdaLovelace' or HOST == 'vbu' or HOST == 'asus':
    urlpatterns += patterns('',
        (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT}),
    )
By Kadet, 2016-02-14 16:37:32