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
 # 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
@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
def get_schema(self, schema: object) -> object:
    """Get the Schema class
    """
    if isinstance(schema, str):
        Schema = getattr(self.request["operation"], schema, None)
    else:
        Schema = schema
    if Schema is None:
        Schema = getattr(self, schema, None)
        if Schema is None:
            raise web.HTTPNotImplemented
    return Schema

I don't even know what to say

By why, 2019-05-23 20:19:52
@define
class DedupConfig:
    columns_to_dedup_by: Optional[List]
    time_range_in_minutes: Optional[int]
    timestamp_column_name: Optional[str]
    leave_deduped_samples_in_time_range: Optional[int] = field(default=1)

    def __attrs_post_init__(self):
        if not self.timestamp_column_name:
            raise ValueError(f"timestamp_column_name parameter must be provided")
        if not self.columns_to_dedup_by:
            raise ValueError(f"columns_to_dedup_by parameter must be provided")
        if not self.time_range_in_minutes:
            raise ValueError(f"time_range_in_minutes parameter must be provided")
By Anonymous, 2022-06-12 22:09:32
# Weird list cleanup
product = "{0}".format(list(product))
product = re.sub(r"\), \(+", "], [", product)
product = re.sub(r"\(+", "[", product)
product = product.replace(")]", "]]").replace(")", "")
product = ast.literal_eval(product)

I don't know why I get this strange fomat for this array of objects... Ok let's do it fast: 1 - Convert array in string 2 - Clean up string 3 - Convert string in array

By Anonymous, 2018-09-05 23:51:16
return [word for word in words if any(all(ch in row for ch in word.lower()) for row in rows)]

Filtering words that can be typed using only one row of the keyboard.

By Mark, 2019-02-27 15:53:46
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
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:10:32
def get_first_index_of_array(array):
    """
    this function is very usefull for get first index of array
    """
    return array[0]


assert get_first_index_of_array([1, 2, 3, 4, 5]) == 1
assert get_first_index_of_array([1, 2, 3, 4, 5]) != 2
assert get_first_index_of_array([1, 2, 3, 4, 5]) != 3
assert get_first_index_of_array([1, 2, 3, 4, 5]) != 4
assert get_first_index_of_array([1, 2, 3, 4, 5]) != 4
By Mohammad Hosseini, 2017-12-13 15:29:01
def open(self, *filename):
	if len(filename) > 1:
		print(("Usage:\nopen() - opens with the initialized "
			"filename\nopen(filename) - opens with given filename"))
		return 1
	if len(filename) == 1:
		self.filename = filename[0]
	if self.filename is None:
		print("No filename given")
		return 1
	self.struct_p = open_struct(self.last_error, self.error_size, \
		self.filename)
	if self.struct_p is None:
		print("Cannot open file: " + self.filename)
		return 1
	self.load_data()
	return 0
By Anonymous, 2017-12-12 03:26:17
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
if student_id:
    assignments = Assignment.objects.filter(week__in=weeks)

    unenrolled_students = Wave.objects.filter(week__in=weeks).values_list('unenrolled_students', flat=True)

    # Construct responses based on assignment type
    Assignment.build_assignments_for_weeks(responses, assignments, students, unenrolled_students)
    max_num_assessments = Assessment.build_assessments_for_weeks(responses)
    Comment.build_comments_for_weeks(responses, weeks, students, unenrolled_students)

elif wave_id:
    assignments = Assignment.objects.filter(week__in=weeks)

    unenrolled_students = Wave.objects.filter(week__in=weeks).values_list('unenrolled_students', flat=True)

    # Construct responses based on assignment type
    Assignment.build_assignments_for_weeks(responses, assignments, students, unenrolled_students)
    max_num_assessments = Assessment.build_assessments_for_weeks(responses)
    Comment.build_comments_for_weeks(responses, weeks, students, unenrolled_students)

else:
    # can't happen
    pass
By Anonymous, 2018-03-23 12:46:10
reduc_ind = list(xrange(1, len(x.get_shape())))
By Anonymous, 2017-08-14 18:37:29
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