id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
12,763
import sys MAX = 0 arr = list(map(int, input().split())) def DFS(x): global MAX if len(arr) == 2: MAX = max(MAX, x) return for i in range(1, len(arr)-1): save = arr[i] arr.pop(i) DFS(x + arr[i-1] * arr[i]) arr.insert(i, save)
null
12,765
import sys N, M = map(int, input().split()) arr = sorted(list(map(int, input().split()))) choose = [ 0 for _ in range(10) ] used = [ 0 for _ in range(10) ] def dfs(idx, cnt): global N, M if cnt == M: for idx in range(cnt): print(arr[choose[idx]], end=' ') print() return ...
null
12,767
import sys N, M = map(int, input().split()) choose = [ 0 for _ in range(10) ] used = [ 0 for _ in range(10) ] def dfs(cnt): global N, M if cnt == M: for idx in range(cnt): print(choose[idx], end=' ') print() return for i in range(1, N + 1): if used[i]: ...
null
12,768
import sys sys.setrecursionlimit(10**4) def input(): return sys.stdin.readline().rstrip()
null
12,769
import sys n, h, d = map(int, input().split()) visit = [[False] * n for _ in range(n)] umbs = [] answer = INF if answer == INF: print(-1) else: print(answer) def dfs(cur): global answer, n y, x, health, durability, cnt = cur dist = abs(end[0] - y) + abs(end[1] - x) if dist <= health + durabilit...
null
12,771
import sys N, M = map(int, input().split()) arr = sorted(list(map(int, input().split()))) choose = [ 0 for _ in range(10) ] used = [ 0 for _ in range(10) ] def dfs(idx, cnt): global N, M if cnt == M: for idx in range(cnt): print(arr[choose[idx]], end=' ') print() return ...
null
12,773
import sys ans = 0 nx = [0, 0, 1, -1] ny = [1, -1, 0, 0] visited = [[0 for i in range(31)] for j in range(31)] N = arr[0] dir = arr[1:] visited[14][14] = 1 def DFS(x,y,ct,now): global ans if ct == N: ans += now return for i in range(4): dx = x + nx[i] dy = y + ny[i] ...
null
12,774
import sys def input(): return sys.stdin.readline().strip()
null
12,775
import sys N, M = map(int, input().split()) arr = sorted(list(map(int, input().split()))) choose = [ 0 for _ in range(10) ] def dfs(cnt): global N, M if cnt == M: for idx in range(cnt): print(arr[choose[idx]], end=' ') print() return for i in range(0,N): choose...
null
12,777
import sys N = int(input()) arr = [] visited = [0] * (N+1) def DFS(): if len(arr) == N: print(*arr) return for i in range(1, N+1): if visited[i] == 0: visited[i] = 1 arr.append(i) DFS() arr.pop() visited[i] = 0
null
12,779
import sys N, M = map(int, input().split()) choose = [ 0 for _ in range(10) ] def dfs(idx, cnt): global N, M if cnt == M: for idx in range(cnt): print(choose[idx], end=' ') print() return for i in range(idx, N + 1): choose[cnt] = i dfs(i, cnt + 1)
null
12,781
import sys N, M = map(int, input().split()) choose = [ 0 for _ in range(10) ] def dfs(idx, cnt): global N, M if cnt == M: for idx in range(cnt): print(choose[idx], end=' ') print() return for i in range(1, N + 1): choose[cnt] = i dfs(i + 1, cnt + 1)
null
12,783
import sys N, M = map(int, input().split()) arr = sorted(list(map(int, input().split()))) choose = [ 0 for _ in range(10) ] def dfs(cnt): global N, M if cnt == M: for idx in range(cnt): print(arr[choose[idx]], end=' ') print() return pre = -1 for i in range(0, N): ...
null
12,785
import sys from collections import deque arr = deque(list(map(int, input().split()))) oper = list(map(int, input().split())) MIN = 1e9+1 MAX = -1e9-1 def DFS(ans): global MIN, MAX if not arr: MIN = min(MIN, ans) MAX = max(MAX, ans) return for i in range(4): if oper[i] > 0: ...
null
12,787
import sys from collections import deque result = [] for i in range(10): result.append(i) if len(result) > N: print(result[N]) else: print(-1) def bfs(N): queue = deque() for i in range(1, 10): queue.append((i, str(i))) while queue: if len(result) == N + 1: break ...
null
12,789
import sys N, S = map(int, input().split()) arr = list(map(int, input().split())) poc = [] ans = 0 def backTracking(idx): global ans if len(poc) >= N: if sum(poc) == S: ans += 1 return else: if sum(poc) == S and poc: ans += 1 for i in range(idx,N): ...
null
12,791
import sys N, M = map(int, input().split()) Map = [ [ 0 for _ in range(M + 1) ] for __ in range(N + 1) ] answer = 0 def dfs(cnt): global answer if cnt == N * M: answer += 1 return y = cnt // M + 1 x = cnt % M + 1 dfs(cnt + 1) if Map[y - 1][x] == 0 or Map[y][x - 1] == ...
null
12,793
import sys N, M = map(int, input().split()) arr = sorted(list(map(int, input().split()))) choose = [ 0 for _ in range(10) ] used = [ 0 for _ in range(10) ] def dfs(cnt): global N, M if cnt == M: for idx in range(cnt): print(arr[choose[idx]], end=' ') print() return f...
null
12,795
import sys N, M = map(int, input().split()) arr = sorted(list(map(int, input().split()))) choose = [ 0 for _ in range(10) ] def dfs(idx, cnt): global N, M if cnt == M: for idx in range(cnt): print(arr[choose[idx]], end=' ') print() return pre = -1 for i in range(id...
null
12,797
import sys N, M = map(int, input().split()) arr = sorted(list(map(int, input().split()))) choose = [ 0 for _ in range(10) ] used = [ 0 for _ in range(10) ] def dfs(cnt): global N, M if cnt == M: for idx in range(cnt): print(arr[choose[idx]], end=' ') print() return p...
null
12,799
import sys for _ in range(F): a, b = map(int, sys.stdin.readline().split()) relation[a][b] = True relation[b][a] = True def dfs(start, relation, friends): global flag, visit, answer if flag: # 친구 관계 성립되면 더이상 할 필요 X return if len(friends) == K: # 만족하는 친구관계가 K개 일때 flag = True ...
null
12,803
import math import sys def input(): return sys.stdin.readline().rstrip()
null
12,809
import sys dp = [0] * 101 def recursion(x): if x == 1 or x == 2 or x == 3: return 1 if dp[x] == 0: dp[x] = recursion(x-2) + recursion(x-3) return dp[x]
null
12,816
import sys sys.setrecursionlimit(1000000) def input(): return sys.stdin.readline().rstrip()
null
12,817
import sys def dfs(cur): flag = True visited[cur] = True for nei in graph[cur]: if visited[nei]: if label[cur] == label[nei]: #만약 neighbor node와 label이 같다면? return False # Bipartite graph가 아니다! else: label[nei] = 3 - label[cur] # 현재 node와 다른 label 저장 ...
null
12,819
import sys from collections import deque dx = [-1,1,0,0] dy = [0,0,-1,1] def bfs(x, y): queue = deque() queue.append((x, y)) visited[x][y] = True while queue: x,y = queue.popleft() for i in range(4): nx = x + dx[i] ny = y + dy[i] if not (0<=nx<N and 0...
null
12,822
import sys M, N = map(int, input().split()) banner = [list(map(int, input().split())) for _ in range(M)] dirx = (1, 0, -1, 0, 1, 1, -1, -1) diry = (0, 1, 0, -1, 1, -1, 1, -1) def find_string(row, col): stack = [(row, col)] banner[row][col] = 0 while stack: x, y = stack.pop() for dx, dy in z...
null
12,824
import sys from collections import deque m, n = map(int,input().split()) board = [list(map(int,input().split())) for _ in range(m)] start = list(map(int,input().split())) start[0]-=1 start[1]-=1 end = list(map(int,input().split())) end[0]-=1 end[1]-=1 def move(dir): def bfs(): y, x, dir = start visit = [[[Fals...
null
12,826
import sys from collections import deque def checkMap(): for z in range(H): for i in range(N): for j in range(M): if arr[z][i][j] == 0: return False return True M, N, H = map(int, input().split()) arr = [] nx = [-1,0,1,0,0,0] ny = [0,-1,0,1,0,0] nz = [0,0,...
null
12,828
from collections import deque import sys q = deque() fire_q = deque() def bfs(q, cnt): global r, c next_q = deque() while q: y, x = q.popleft() if board[y][x] == 2: continue for i in range(4): ny, nx = y + dy[i], x + dx[i] if ny<0 or ny>=r+2 or nx<0 or nx>=c+2...
null
12,829
import sys from collections import deque from itertools import combinations m = map(int, input().split()) arr = [list(map(int, input().split())) for _ in range(n)] empty, virus = get_pos() ons(empty, 3) m - (len(empty) + len(virus)) def get_pos(): empty, virus = [], [] for i in range(n): for j in rang...
null
12,830
import sys from collections import deque from itertools import combinations arr = [list(map(int, input().split())) for _ in range(n)] def set_wall(comb): for y, x in comb: arr[y][x] = 1
null
12,831
import sys from collections import deque from itertools import combinations arr = [list(map(int, input().split())) for _ in range(n)] def collapse_wall(comb): for y, x in comb: arr[y][x] = 0
null
12,832
import sys from collections import deque from itertools import combinations direction = [(0, 1), (-1, 0), (0, -1), (1, 0)] m = map(int, input().split()) arr = [list(map(int, input().split())) for _ in range(n)] m - (len(empty) + len(virus)) def bfs(virus): queue = deque(virus) visited = [[False] * m for _ in r...
null
12,834
import sys arr = [[] for i in range(N+1)] visited = [0] * (N+1) for i in range(M): u,v = map(int, input().split()) arr[u].append(v) arr[v].append(u) for i in range(1,N+1): if visited[i] == 0: DFS(i) ans += 1 def DFS(now): visited[now] = 1 for i in arr[now]: if visited[i]...
null
12,836
from collections import deque import sys def answer(G, r): is_giga_find = False longest = 0 body = 0 visited = [False for _ in range(len(G))] q = deque() q.append((0, r)) visited[r] = True while q: dist, node = q.popleft() if dist > longest: longest = dist ...
null
12,838
import sys ans = [] if ans: print(ans[0]) else: print(-1) def DFS(x,ct): if x == B: ans.append(ct) return if x * 10 + 1 <= B: DFS(x * 10 + 1,ct+1) if x * 2 <= B: DFS(x*2,ct+1)
null
12,840
from collections import deque import sys def bfs(board): end = (0,7) que = deque() que.append((7,0,0)) visit = [[[False] * 8 for _ in range(8)] for _ in range(9)] visit[0][7][0] = True dy = [0,0,0,-1,1,-1,1,-1,1] dx = [0,-1,1,0,0,-1,1,1,-1] result = 0 while que: y,x,time = q...
null
12,842
import sys N = int(input()) arr = [list(input()) for _ in range(N)] def dfs(idx): global N visited = [ True for _ in range(N) ] visited[idx] = False stack = [ (idx, 0) ] total = 0 while stack: curent_x, p_cnt = stack.pop() for either_x in range(N): if arr[curent_x][e...
null
12,843
import sys sys.setrecursionlimit(10000) def input(): return sys.stdin.readline().rstrip()
null
12,844
import sys nx = [-1,-1,-1,0,1,1,1,0] ny = [-1,0,1,1,1,0,-1,-1] while True: w, h = map(int, input().split()) if w == 0 and h == 0: break arr = [] ct = 0 for i in range(h): arr.append(list(map(int, input().split()))) for i in range(h): for j in range(w): if arr[...
null
12,846
from collections import deque import sys n, m = map(int, input().split()) G = [] def answer(row, col): global m, n shortest = 10000001 q = deque() direction = [(1, 0), (0, 1), (-1, 0), (0, -1)] visited = [[[0] * 2 for _ in range(m)] for _ in range(n)] q.append((row, col, 1)) visited[row][...
null
12,848
import sys from collections import deque L, W = map(int, input().split()) arr = [] nx = [-1, 0, 1, 0] ny = [0, -1, 0, 1] for i in range(L): arr.append(input()) for i in range(L): for j in range(W): if arr[i][j] == 'L': visited = [[0 for i in range(W)] for j in range(L)] ct = BFS(...
null
12,849
import os import sys import subprocess import argparse from bs4 import BeautifulSoup as bs import requests def load_arg(): parser = argparse.ArgumentParser() arg = parser.add_argument arg('--pr_number', type=int, help="Pull Request Number") arg('--check_solution', action='store_true') parser.set_de...
null
12,850
import os import sys import subprocess import argparse from bs4 import BeautifulSoup as bs import requests def check_alreay_exist_solution(path): if os.path.exists(path): raise Exception("Alread Exists Solution") print("It is a new Solution!!")
null
12,851
import os import sys import subprocess import argparse from bs4 import BeautifulSoup as bs import requests def run(command): ret = subprocess.check_output(command, shell=True).decode('utf8') return ret def get_pr_file(pr_number): run(f"git fetch origin +refs/pull/{pr_number}/merge") files = run(f"git -...
null
12,852
import os import sys import subprocess import argparse from bs4 import BeautifulSoup as bs import requests def run(command): ret = subprocess.check_output(command, shell=True).decode('utf8') return ret def detect_tab(path): with open(path, 'r') as f: solution = f.readlines() f.close() fo...
null
12,853
import os import subprocess as sp def getCount(folder): lines = list() with open(f'./{folder}/list.md', 'r') as f: lines = f.readlines() f.close() total = 0 cnt = 0 for line in lines: S = line.split(",")[0] total += 1 if S != '': cnt += 1 ret...
null
12,854
import os import subprocess as sp seq = [ "header.md", "codingtest_info.md", "workbook_header.md", "workbook.md", "workbook_footer.md", "contributors.md", "updatelog.md", "TODO.md", "footer.md" ] def assemble(): with open('./README.md', 'w') as f: f.close() for md in seq: os.system(f"cat ./mar...
null
12,855
import os import subprocess as sp def make_contributors(): os.system('python3 ./scripts/make_contributor.py')
null
12,856
import datetime import random import json import urllib.request as request from utils import Date, Communication class Communication: def get_json(url): def get_database(cls): def get_picked_problem(cls): def get_today_problem(cls): def make_table(data: dict, save_file: str) -> None: database ...
null
12,857
import datetime import random import json import urllib.request as request from utils import Date, Communication def get_today_date(): year, month, day = Date.get_today_date() timeformat = f"{year:04d}/{month:02d}/{day:02d}" return timeformat class Communication: __URL = { "database": "https://...
null
12,858
from API import SolvedAPI import json def urlProblem(number, name): FORMAT = f"<a href=\"https://www.acmicpc.net/problem/{number}\" target=\"_blank\">{name}</a>" return FORMAT
null
12,859
from API import SolvedAPI import json def urlSolution(link): if link == "": return "" FORMAT = f"<a href=\"{link}\">바로가기</a>" return FORMAT
null
12,860
from API import SolvedAPI import json def urlLevel(level): url = f"https://static.solved.ac/tier_small/{level}.svg" ret = f"<img height=\"25px\" width=\"25px\" src=\"{url}\"/>" return ret
null
12,861
from urllib import request import ssl import json import atexit import time import datetime import pytz from utils import Communication ALPHA = [ 'B', 'S', 'G', 'P', 'D', 'R' ] return f"{ALPHA[level // 5]}{5 - level % 5} def changeLevel(level): ALPHA = [ 'B', 'S', 'G', 'P', 'D', 'R' ] level -= 1 re...
null
12,862
import os import time import datetime import pytz def getProblem(Dir): ret = list() with open(f"{Dir}/list.md", 'r') as f: ret = f.readlines() f.close() return ret
null
12,863
import os import time import datetime import pytz def Assemble(*args): problems = set() for i in args: for problem in i: problemID = problem.split(',')[-2] problems.add(problemID) return problems
null
12,864
import os import time print("""# Status 간단하게 파이썬으로 진행사항 및 문제 수를 알아보기 위해 만들어 보았습니다. [메인으로 돌아가기](https://github.com/tony9402/baekjoon) """) print(f"총 문제 수 : {len(TotalProblem)} ") print(f"총 추천 문제 수 : {len(Recommend_List)} ({len(Recommend_List) / len(TotalProblem) * 100. :.2f}%) ") print(f"알고리즘 Tag 개수 : {len(Folders)} ...
null
12,865
import os import time import datetime import pytz def getTier(Str): if len(Str) == 2: # Ex p2, P2... return Str.upper() else: # Gold5... return Str[0].upper() + Str[-1]
null
12,866
import os import time import datetime import pytz def getRecommend(*args): ret = list() # Not Set, Get Problem Info (ProblemID, Problem Name, Tier) for i in args: for problem in i: info = problem.split(",") rec = info[0].strip() if not rec == '': ret....
null
12,867
import os import time import datetime import pytz def calPercentageOfRec(*args): total = 0 hasSolution = 0 for i in args: for problem in i: info = problem.split(",") rec = info[0].strip() link = info[-1].strip() if rec == '': contin...
null
12,868
import json def read_json(path): with open(path, 'r') as f: data = json.load(f) f.close() return data
null
12,869
import json def write_codeowners(data, path = "CODEOWNERS"): LangtoExt = { "*": "*", "c": "c", "cpp": "cpp", "python": "py", "java": "java", "swift": "swift", "rust": "rs", "kotlin": "kt", "javascript": "js", "go": "go" } f = o...
null
12,870
from API import SolvedAPI from make_table import Table import json import argparse import os table = None def updateProblems(): print("update start") table.run() print("update end")
null
12,871
from API import SolvedAPI from make_table import Table import json import argparse import os solution_list = dict() def getFolder(path, EXCEPT=list()): def updateSolution(): rootFolder = "./solution" tagFolder = getFolder(rootFolder) # in ./solution for tag in tagFolder: solution_list[tag] = se...
null
12,872
from API import SolvedAPI from make_table import Table import json import argparse import os config = dict() solution_list = dict() solutionRPATH = "./../solution" rootFolder = "./" tagFolder = config.get('tags') for tag in tagFolder: currentPath = f"{rootFolder}/{tag}" ...
null
12,873
from API import SolvedAPI from make_table import Table import json import argparse import os def updateStatus(): os.system('python3 ./scripts/arrange.py > status.md')
null
12,874
from API import SolvedAPI from make_table import Table import json import argparse import os table = None def updateLevel(): table.run(force = True)
null
12,875
import torch import numpy as np import os import cv2 from os.path import join import pickle def check_modelpath(paths): if isinstance(paths, str): assert os.path.exists(paths), paths return paths elif isinstance(paths, list): for path in paths: if os.path.exists(path): ...
null
12,876
import os import numpy as np import cv2 The provided code snippet includes necessary dependencies for implementing the `bbox_from_keypoints` function. Write a Python function `def bbox_from_keypoints(keypoints, rescale=1.2, detection_thresh=0.05, MIN_PIXEL=5)` to solve the following problem: Get center and scale for b...
Get center and scale for bounding box from openpose detections.
12,877
import os import numpy as np import math import cv2 import torch from ..basetopdown import BaseTopDownModelCache from .hrnet import HRNet The provided code snippet includes necessary dependencies for implementing the `get_max_preds` function. Write a Python function `def get_max_preds(batch_heatmaps)` to solve the fol...
get predictions from score maps heatmaps: numpy.ndarray([batch_size, num_joints, height, width])
12,878
import os import numpy as np import math import cv2 import torch from ..basetopdown import BaseTopDownModelCache from .hrnet import HRNet COCO17_IN_BODY25 = [0,16,15,18,17,5,2,6,3,7,4,12,9,13,10,14,11] def coco17tobody25(points2d): kpts = np.zeros((points2d.shape[0], 25, 3)) kpts[:, COCO17_IN_BODY25, :2] = poi...
null
12,879
import os import numpy as np import torch from functools import partial import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from .layers import drop_path, to_2tuple, trunc_normal_ from ..basetopdown import BaseTopDownModelCache from ..topdown_keypoints import BaseKeypoints ...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/...
12,880
import os import numpy as np import torch from functools import partial import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from .layers import drop_path, to_2tuple, trunc_normal_ from ..basetopdown import BaseTopDownModelCache from ..topdown_keypoints import BaseKeypoints ...
Calculate absolute positional embeddings. If needed, resize embeddings and remove cls_token dimension for the original embeddings. Args: abs_pos (Tensor): absolute positional embeddings with (1, num_position, C). has_cls_token (bool): If true, has 1 embedding in abs_pos for cls token. hw (Tuple): size of input image to...
12,881
import torch import math import collections.abc from itertools import repeat import warnings import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `drop_path` function. Write a Python function `def drop_path(x, drop_prob: float = 0., training: bool = False, scale_by_keep:...
Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks). This is the same as the DropConnect impl I created for EfficientNet, etc networks, however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper... See discussion: https://github.com/...
12,882
import torch import math import collections.abc from itertools import repeat import warnings import torch.nn as nn def _ntuple(n): def parse(x): if isinstance(x, collections.abc.Iterable) and not isinstance(x, str): return tuple(x) return tuple(repeat(x, n)) return parse
null
12,883
import torch import math import collections.abc from itertools import repeat import warnings import torch.nn as nn def _trunc_normal_(tensor, mean, std, a, b): # Cut & paste from PyTorch official master until it's in a few official releases - RW # Method based on https://people.sc.fsu.edu/~jburkardt/presentatio...
r"""Fills the input Tensor with values drawn from a truncated normal distribution. The values are effectively drawn from the normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values outside :math:`[a, b]` redrawn until they are within the bounds. The method used for generating the random values wo...
12,884
import os import os.path as osp import torch import torch.nn as nn from torchvision.models.resnet import BasicBlock, Bottleneck from torchvision.models.resnet import model_urls from ..basetopdown import get_preds_from_heatmaps def make_conv_layers(feat_dims, kernel=3, stride=1, padding=1, bnrelu_final=True): layer...
null
12,885
import os import os.path as osp import torch import torch.nn as nn from torchvision.models.resnet import BasicBlock, Bottleneck from torchvision.models.resnet import model_urls from ..basetopdown import get_preds_from_heatmaps def make_deconv_layers(feat_dims, bnrelu_final=True): layers = [] for i in range(len...
null
12,886
import math import numpy as np The provided code snippet includes necessary dependencies for implementing the `get_max_preds` function. Write a Python function `def get_max_preds(batch_heatmaps)` to solve the following problem: get predictions from score maps heatmaps: numpy.ndarray([batch_size, num_joints, height, wi...
get predictions from score maps heatmaps: numpy.ndarray([batch_size, num_joints, height, width])
12,887
import math import numpy as np def coco17tobody25(points2d): kpts = np.zeros((points2d.shape[0], 25, 3)) kpts[:, COCO17_IN_BODY25, :2] = points2d[:, :, :2] kpts[:, COCO17_IN_BODY25, 2:3] = points2d[:, :, 2:3] kpts[:, 8, :2] = kpts[:, [9, 12], :2].mean(axis=1) kpts[:, 8, 2] = kpts[:, [9, 12], 2].min(...
null
12,888
import torch import torch.nn as nn import torchvision.models.resnet as resnet import numpy as np import math class Bottleneck(nn.Module): """ Redefinition of Bottleneck residual block Adapted from the official PyTorch implementation """ expansion = 4 def __init__(self, inplanes, planes, stride=1...
Constructs an HMR model with ResNet50 backbone. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
12,889
''' Date: 2021-10-25 11:51:37 am Author: dihuangdh Descriptions: ----- LastEditTime: 2021-10-25 1:50:40 pm LastEditors: dihuangdh ''' import torch from torchvision.transforms import Normalize import numpy as np import cv2 from .models import hmr class constants: FOCAL_LENGTH = 5000. IMG_RES = 224 # Mean an...
Read image, do preprocessing and possibly crop it according to the bounding box. If there are bounding box annotations, use them to crop the image. If no bounding box is specified but openpose detections are available, use them to get the bounding box.
12,890
def solve_translation(X, x, K): A = np.zeros((2*X.shape[0], 3)) b = np.zeros((2*X.shape[0], 1)) fx, fy = K[0, 0], K[1, 1] cx, cy = K[0, 2], K[1, 2] for nj in range(X.shape[0]): A[2*nj, 0] = 1 A[2*nj + 1, 1] = 1 A[2*nj, 2] = -(x[nj, 0] - cx)/fx A[2*nj+1, 2] = -(x[nj,...
null
12,891
''' Date: 2021-10-25 11:51:37 am Author: dihuangdh Descriptions: ----- LastEditTime: 2021-10-25 1:50:40 pm LastEditors: dihuangdh ''' import torch from torchvision.transforms import Normalize import numpy as np import cv2 from .models import hmr def estimate_translation_np(S, joints_2d, joints_conf, K): """Find ca...
null
12,892
import os from os.path import join import numpy as np import cv2 import torch import torch.nn as nn import pickle import math The provided code snippet includes necessary dependencies for implementing the `get_warp_matrix` function. Write a Python function `def get_warp_matrix(theta, size_input, size_dst, size_target)...
Calculate the transformation matrix under the constraint of unbiased. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). Args: theta (float): Rotation angle in degrees. size_input (np.ndarray): Size of input image [w, h]. size_dst (np.ndarra...
12,893
import os from os.path import join import numpy as np import cv2 import torch import torch.nn as nn import pickle import math def generate_patch_image_cv(cvimg, c_x, c_y, bb_width, bb_height, patch_width, patch_height, do_flip, scale, rot): trans, inv_trans = gen_trans_from_patch_cv(c_x, c_y, bb_width, bb_height, p...
null
12,894
import os from os.path import join import numpy as np import cv2 import torch import torch.nn as nn import pickle import math def xyxy2ccwh(bbox): w = bbox[:, 2] - bbox[:, 0] h = bbox[:, 3] - bbox[:, 1] cx = (bbox[:, 2] + bbox[:, 0])/2 cy = (bbox[:, 3] + bbox[:, 1])/2 return np.stack([cx, cy, w, h]...
null
12,895
import os from os.path import join import numpy as np import cv2 import torch import torch.nn as nn import pickle import math def get_max_preds(batch_heatmaps): ''' get predictions from score maps heatmaps: numpy.ndarray([batch_size, num_joints, height, width]) ''' assert isinstance(batch_heatmaps, ...
null
12,896
import os from os.path import join import numpy as np import cv2 import torch import torch.nn as nn import pickle import math def gdown_models(ckpt, url): print('Try to download model from {} to {}'.format(url, ckpt)) os.makedirs(os.path.dirname(ckpt), exist_ok=True) cmd = 'gdown "{}" -O {}'.format(url, ck...
null
12,897
def get_backbone_info(backbone): info = { 'resnet18': {'n_output_channels': 512, 'downsample_rate': 4}, 'resnet34': {'n_output_channels': 512, 'downsample_rate': 4}, 'resnet50': {'n_output_channels': 2048, 'downsample_rate': 4}, 'resnet50_adf_dropout': {'n_output_channels': 2048, '...
null
12,898
from torch import nn The provided code snippet includes necessary dependencies for implementing the `_make_divisible` function. Write a Python function `def _make_divisible(v, divisor, min_value=None)` to solve the following problem: This function is taken from the original tf repo. It ensures that all layers have a c...
This function is taken from the original tf repo. It ensures that all layers have a channel number that is divisible by 8 It can be seen here: https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py :param v: :param divisor: :param min_value: :return:
12,899
from torch import nn model_urls = { 'mobilenet_v2': 'https://download.pytorch.org/models/mobilenet_v2-b0353104.pth', } class MobileNetV2(nn.Module): def __init__(self, num_classes=1000, width_mult=1.0, inverted_residual_setting=None, round_near...
Constructs a MobileNetV2 architecture from `"MobileNetV2: Inverted Residuals and Linear Bottlenecks" <https://arxiv.org/abs/1801.04381>`_. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr
12,900
import os import torch import torch.nn as nn import torch.nn.functional as F from yacs.config import CfgNode as CN The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1)` to solve the following problem: 3x...
3x3 convolution with padding
12,901
import os import torch import torch.nn as nn import torch.nn.functional as F from yacs.config import CfgNode as CN def get_pose_net(cfg, is_train): model = PoseHighResolutionNet(cfg) if is_train and cfg['MODEL']['INIT_WEIGHTS']: model.init_weights(cfg['MODEL']['PRETRAINED']) return model def get_cfg...
null
12,902
import os import torch import torch.nn as nn import torch.nn.functional as F from yacs.config import CfgNode as CN def get_pose_net(cfg, is_train): def get_cfg_defaults(pretrained, width=32, downsample=False, use_conv=False): def hrnet_w48( pretrained=True, pretrained_ckpt='data/pretrained_models/pose_...
null
12,903
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1)` to solve the following problem: 3x3 convolution with padding Here is the function: def con...
3x3 convolution with padding
12,904
import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `conv1x1` function. Write a Python function `def conv1x1(in_planes, out_planes, stride=1)` to solve the following problem: 1x1 convolution Here is the function: def conv1x1(in_planes, out_planes, stride=...
1x1 convolution
12,905
import torch import torch.nn as nn class BasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, base_width=64, dilation=1, norm_layer=None): super(BasicBlock, self).__init__() if norm_layer is None: norm_layer =...
r"""ResNet-18 model from `"Deep Residual Learning for Image Recognition" <https://arxiv.org/pdf/1512.03385.pdf>`_ Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr