common_id
stringlengths 5
5
| image
stringlengths 18
18
| code
stringlengths 55
1.44k
|
---|---|---|
10149 | Test/png/10149.png | def get_pid_list():
pids = [int(x) for x in os.listdir('/proc') if x.isdigit()]
return pids
|
10653 | Test/png/10653.png | def remove_tag(self, tag):
self.tags = list(set(self.tags or []) - set([tag]))
|
10415 | Test/png/10415.png | def hash(self, id):
h = md5(id).hexdigest()
return os.path.join(self.path, h+self.type)
|
11026 | Test/png/11026.png | # Write a python function to find the maximum volume of a cuboid with given sum of sides.
def max_volume(s):
maxvalue = 0
i = 1
for i in range(s - 1):
j = 1
for j in range(s):
k = s - i - j
maxvalue = max(maxvalue, i * j * k)
return maxvalue
|
10289 | Test/png/10289.png | def _rename(self, name, callback):
self._coroutine_queue.put(self._conversation.rename(name))
callback()
|
10520 | Test/png/10520.png | def get_geoip(ip):
reader = geolite2.reader()
ip_data = reader.get(ip) or {}
return ip_data.get('country', {}).get('iso_code')
|
10782 | Test/png/10782.png | # Write a function to check whether it follows the sequence given in the patterns array.
def is_samepatterns(colors, patterns):
if len(colors) != len(patterns):
return False
sdict = {}
pset = set()
sset = set()
for i in range(len(patterns)):
pset.add(patterns[i])
sset.add(colors[i])
if patterns[i] not in sdict.keys():
sdict[patterns[i]] = []
keys = sdict[patterns[i]]
keys.append(colors[i])
sdict[patterns[i]] = keys
if len(pset) != len(sset):
return False
for values in sdict.values():
for i in range(len(values) - 1):
if values[i] != values[i + 1]:
return False
return True
|
10829 | Test/png/10829.png | # Write a function to find the triplet with sum of the given array
def check_triplet(A, n, sum, count):
if count == 3 and sum == 0:
return True
if count == 3 or n == 0 or sum < 0:
return False
return check_triplet(A, n - 1, sum - A[n - 1], count + 1) or check_triplet(
A, n - 1, sum, count
)
|
10655 | Test/png/10655.png | def _transform_triple_numpy(x):
return np.array([x.head, x.relation, x.tail], dtype=np.int64)
|
10549 | Test/png/10549.png | def get_group_name(id_group):
group = Group.query.get(id_group)
if group is not None:
return group.name
|
11214 | Test/png/11214.png | # Write a function to calculate the permutation coefficient of given p(n, k).
def permutation_coefficient(n, k):
P = [[0 for i in range(k + 1)] for j in range(n + 1)]
for i in range(n + 1):
for j in range(min(i, k) + 1):
if j == 0:
P[i][j] = 1
else:
P[i][j] = P[i - 1][j] + (j * P[i - 1][j - 1])
if j < k:
P[i][j + 1] = 0
return P[n][k]
|
10536 | Test/png/10536.png | def accept(self):
with db.session.begin_nested():
self.state = MembershipState.ACTIVE
db.session.merge(self)
|
10186 | Test/png/10186.png | def clean(s):
lines = [l.rstrip() for l in s.split('\n')]
return '\n'.join(lines)
|
10484 | Test/png/10484.png | def to_pointer(cls, instance):
return OctavePtr(instance._ref, instance._name, instance._address)
|
11117 | Test/png/11117.png | # Write a function to find the minimum product from the pairs of tuples within a given list.
def min_product_tuple(list1):
result_min = min([abs(x * y) for x, y in list1])
return result_min
|
11201 | Test/png/11201.png | # Write a function to calculate a grid of hexagon coordinates where function returns a list of lists containing 6 tuples of x, y point coordinates.
import math
def calculate_polygons(startx, starty, endx, endy, radius):
sl = (2 * radius) * math.tan(math.pi / 6)
p = sl * 0.5
b = sl * math.cos(math.radians(30))
w = b * 2
h = 2 * sl
startx = startx - w
starty = starty - h
endx = endx + w
endy = endy + h
origx = startx
origy = starty
xoffset = b
yoffset = 3 * p
polygons = []
row = 1
counter = 0
while starty < endy:
if row % 2 == 0:
startx = origx + xoffset
else:
startx = origx
while startx < endx:
p1x = startx
p1y = starty + p
p2x = startx
p2y = starty + (3 * p)
p3x = startx + b
p3y = starty + h
p4x = startx + w
p4y = starty + (3 * p)
p5x = startx + w
p5y = starty + p
p6x = startx + b
p6y = starty
poly = [
(p1x, p1y),
(p2x, p2y),
(p3x, p3y),
(p4x, p4y),
(p5x, p5y),
(p6x, p6y),
(p1x, p1y),
]
polygons.append(poly)
counter += 1
startx += w
starty += yoffset
row += 1
return polygons
|
10833 | Test/png/10833.png | # Write a function to find the maximum difference between the number of 0s and number of 1s in any sub-string of the given binary string.
def find_length(string, n):
current_sum = 0
max_sum = 0
for i in range(n):
current_sum += 1 if string[i] == "0" else -1
if current_sum < 0:
current_sum = 0
max_sum = max(current_sum, max_sum)
return max_sum if max_sum else 0
|
10820 | Test/png/10820.png | # Write a python function to find the perimeter of a cylinder.
def perimeter(diameter, height):
return 2 * (diameter + height)
|
10749 | Test/png/10749.png | # Write a function to filter even numbers using lambda function.
def filter_evennumbers(nums):
even_nums = list(filter(lambda x: x % 2 == 0, nums))
return even_nums
|
10999 | Test/png/10999.png | # Write a function to find out the number of ways of painting the fence such that at most 2 adjacent posts have the same color for the given fence with n posts and k colors.
def count_no_of_ways(n, k):
dp = [0] * (n + 1)
total = k
mod = 1000000007
dp[1] = k
dp[2] = k * k
for i in range(3, n + 1):
dp[i] = ((k - 1) * (dp[i - 1] + dp[i - 2])) % mod
return dp[n]
|
11045 | Test/png/11045.png | # Write a function that matches a word at the end of a string, with optional punctuation.
import re
def text_match_word(text):
patterns = "\w+\S*$"
if re.search(patterns, text):
return "Found a match!"
else:
return "Not matched!"
|
11035 | Test/png/11035.png | # Write a function to print check if the triangle is isosceles or not.
def check_isosceles(x, y, z):
if x == y or y == z or z == x:
return True
else:
return False
|
10341 | Test/png/10341.png | def err(txt):
print("%s# %s%s%s" % (PR_ERR_CC, get_time_stamp(), txt, PR_NC))
sys.stdout.flush()
|
10832 | Test/png/10832.png | # Write a function to get the angle of a complex number.
import cmath
def angle_complex(a, b):
cn = complex(a, b)
angle = cmath.phase(a + b)
return angle
|
11279 | Test/png/11279.png | # Write a function to find maximum possible sum of disjoint pairs for the given array of integers and a number k.
def max_sum_pair_diff_lessthan_K(arr, N, K):
arr.sort()
dp = [0] * N
dp[0] = 0
for i in range(1, N):
dp[i] = dp[i - 1]
if arr[i] - arr[i - 1] < K:
if i >= 2:
dp[i] = max(dp[i], dp[i - 2] + arr[i] + arr[i - 1])
else:
dp[i] = max(dp[i], arr[i] + arr[i - 1])
return dp[N - 1]
|
10600 | Test/png/10600.png | def readtxt(filepath):
with open(filepath, 'rt') as f:
lines = f.readlines()
return ''.join(lines)
|
10214 | Test/png/10214.png | def incr(self, key, to_add=1):
if key not in self.value:
self.value[key] = CountMetric()
self.value[key].incr(to_add)
|
10956 | Test/png/10956.png | # Write a function to calculate the harmonic sum of n-1.
def harmonic_sum(n):
if n < 2:
return 1
else:
return 1 / n + (harmonic_sum(n - 1))
|
10809 | Test/png/10809.png | # Write a function to find the kth element in the given array.
def kth_element(arr, n, k):
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] == arr[j + 1], arr[j]
return arr[k - 1]
|
10500 | Test/png/10500.png | def job(ctx, project, job): # pylint:disable=redefined-outer-name
ctx.obj = ctx.obj or {}
ctx.obj['project'] = project
ctx.obj['job'] = job
|
10978 | Test/png/10978.png | # Write a python function to find the sum of even numbers at even positions.
def sum_even_and_even_index(arr, n):
i = 0
sum = 0
for i in range(0, n, 2):
if arr[i] % 2 == 0:
sum += arr[i]
return sum
|
11001 | Test/png/11001.png | # Write a function to find the third side of a right angled triangle.
import math
def otherside_rightangle(w, h):
s = math.sqrt((w * w) + (h * h))
return s
|
10411 | Test/png/10411.png | def stop(self):
with self.lock:
for dummy in self.threads:
self.queue.put(None)
|
10954 | Test/png/10954.png | # Write a function for computing square roots using the babylonian method.
def babylonian_squareroot(number):
if number == 0:
return 0
g = number / 2.0
g2 = g + 1
while g != g2:
n = number / g
g2 = g
g = (g + n) / 2
return g
|
10647 | Test/png/10647.png | def set_sleep(self, value=False):
return (yield from self.handle_set(self.API.get('sleep'), int(value)))
|
10692 | Test/png/10692.png | def paste(tid=None, review=False):
submit(pastebin=True, tid=tid, review=False)
|
10319 | Test/png/10319.png | def get(self, ring, angle):
pixel = self.angleToPixel(angle, ring)
return self._get_base(pixel)
|
10205 | Test/png/10205.png | def keybd_event(bVk: int, bScan: int, dwFlags: int, dwExtraInfo: int) -> None:
ctypes.windll.user32.keybd_event(bVk, bScan, dwFlags, dwExtraInfo)
|
11063 | Test/png/11063.png | # Write a python function to count the number of rectangles in a circle of radius r.
def count_Rectangles(radius):
rectangles = 0
diameter = 2 * radius
diameterSquare = diameter * diameter
for a in range(1, 2 * radius):
for b in range(1, 2 * radius):
diagnalLengthSquare = a * a + b * b
if diagnalLengthSquare <= diameterSquare:
rectangles += 1
return rectangles
|
10957 | Test/png/10957.png | # Write a function to find the intersection of two arrays using lambda function.
def intersection_array(array_nums1, array_nums2):
result = list(filter(lambda x: x in array_nums1, array_nums2))
return result
|
10304 | Test/png/10304.png | def store(self, key: object, value: object):
self._user_data.update({key: value})
|
10686 | Test/png/10686.png | def _rindex(mylist: Sequence[T], x: T) -> int:
return len(mylist) - mylist[::-1].index(x) - 1
|
11047 | Test/png/11047.png | # Write a python function to find the maximum occuring divisor in an interval.
def find_Divisor(x, y):
if x == y:
return y
return 2
|
10902 | Test/png/10902.png | # Write a python function to convert octal number to decimal number.
def octal_To_Decimal(n):
num = n
dec_value = 0
base = 1
temp = num
while temp:
last_digit = temp % 10
temp = int(temp / 10)
dec_value += last_digit * base
base = base * 8
return dec_value
|
11284 | Test/png/11284.png | # Write a python function to check whether an array is subarray of another or not.
def is_Sub_Array(A, B, n, m):
i = 0
j = 0
while i < n and j < m:
if A[i] == B[j]:
i += 1
j += 1
if j == m:
return True
else:
i = i - j + 1
j = 0
return False
|
10183 | Test/png/10183.png | def getTotaln(self):
n = sum([field.n for field in self.fields])
return n
|
11257 | Test/png/11257.png | # Write a python function to find the sum of fifth power of first n odd natural numbers.
def odd_Num_Sum(n):
j = 0
sm = 0
for i in range(1, n + 1):
j = 2 * i - 1
sm = sm + (j * j * j * j * j)
return sm
|
10701 | Test/png/10701.png | def strip_codes(s: Any) -> str:
return codepat.sub('', str(s) if (s or (s == 0)) else '')
|
10831 | Test/png/10831.png | # Write a function to sum all amicable numbers from 1 to a specified number.
def amicable_numbers_sum(limit):
if not isinstance(limit, int):
return "Input is not an integer!"
if limit < 1:
return "Input must be bigger than 0!"
amicables = set()
for num in range(2, limit + 1):
if num in amicables:
continue
sum_fact = sum([fact for fact in range(1, num) if num % fact == 0])
sum_fact2 = sum([fact for fact in range(1, sum_fact) if sum_fact % fact == 0])
if num == sum_fact2 and num != sum_fact:
amicables.add(num)
amicables.add(sum_fact2)
return sum(amicables)
|
10161 | Test/png/10161.png | def object_info(**kw):
infodict = dict(izip_longest(info_fields, [None]))
infodict.update(kw)
return infodict
|
10121 | Test/png/10121.png | def info(self):
return (self.identity, self.url, self.pub_url, self.location)
|
11137 | Test/png/11137.png | # Write a function to extract the elementwise and tuples from the given two tuples.
def and_tuples(test_tup1, test_tup2):
res = tuple(ele1 & ele2 for ele1, ele2 in zip(test_tup1, test_tup2))
return res
|
11190 | Test/png/11190.png | # Write a function to find sequences of one upper case letter followed by lower case letters in the given string by using regex.
import re
def match(text):
pattern = "[A-Z]+[a-z]+$"
if re.search(pattern, text):
return "Yes"
else:
return "No"
|
10968 | Test/png/10968.png | # Write a function to find the nth newman–shanks–williams prime number.
def newman_prime(n):
if n == 0 or n == 1:
return 1
return 2 * newman_prime(n - 1) + newman_prime(n - 2)
|
10523 | Test/png/10523.png | def self_edge_filter(_: BELGraph, source: BaseEntity, target: BaseEntity, __: str) -> bool:
return source == target
|
11188 | Test/png/11188.png | # Write a python function to find the maximum occurring character in a given string.
def get_max_occuring_char(str1):
ASCII_SIZE = 256
ctr = [0] * ASCII_SIZE
max = -1
ch = ""
for i in str1:
ctr[ord(i)] += 1
for i in str1:
if max < ctr[ord(i)]:
max = ctr[ord(i)]
ch = i
return ch
|
10585 | Test/png/10585.png | def mac(csp, var, value, assignment, removals):
"Maintain arc consistency."
return AC3(csp, [(X, var) for X in csp.neighbors[var]], removals)
|
10869 | Test/png/10869.png | # Write a function to remove all elements from a given list present in another list.
def remove_elements(list1, list2):
result = [x for x in list1 if x not in list2]
return result
|
10539 | Test/png/10539.png | def _tile(self, n):
pos = self._trans(self.pos[n])
return Tile(pos, pos).pad(self.support_pad)
|
10852 | Test/png/10852.png | # Write a python function to find the sum of absolute differences in all pairs of the given array.
def sum_Pairs(arr, n):
sum = 0
for i in range(n - 1, -1, -1):
sum += i * arr[i] - (n - 1 - i) * arr[i]
return sum
|
11202 | Test/png/11202.png | # Write a function to convert the given binary tuple to integer.
def binary_to_integer(test_tup):
res = int("".join(str(ele) for ele in test_tup), 2)
return str(res)
|
11241 | Test/png/11241.png | # Write a function to remove particular data type elements from the given tuple.
def remove_datatype(test_tuple, data_type):
res = []
for ele in test_tuple:
if not isinstance(ele, data_type):
res.append(ele)
return res
|
10502 | Test/png/10502.png | def bookmark(ctx, username): # pylint:disable=redefined-outer-name
ctx.obj = ctx.obj or {}
ctx.obj['username'] = username
|
10885 | Test/png/10885.png | # Write a python function to find two distinct numbers such that their lcm lies within the given range.
def answer(L, R):
if 2 * L <= R:
return (L, 2 * L)
else:
return -1
|
10807 | Test/png/10807.png | # Write a function to convert the given decimal number to its binary equivalent.
def decimal_to_binary(n):
return bin(n).replace("0b", "")
|
10770 | Test/png/10770.png | # Write a python function to find smallest number in a list.
def smallest_num(xs):
return min(xs)
|
11274 | Test/png/11274.png | # Write a function to get the sum of a non-negative integer.
def sum_digits(n):
if n == 0:
return 0
else:
return n % 10 + sum_digits(int(n / 10))
|
10825 | Test/png/10825.png | # Write a function to convert all possible convertible elements in the list to float.
def list_to_float(test_list):
res = []
for tup in test_list:
temp = []
for ele in tup:
if ele.isalpha():
temp.append(ele)
else:
temp.append(float(ele))
res.append((temp[0], temp[1]))
return str(res)
|
11008 | Test/png/11008.png | # Write a function to find the count of all binary sequences of length 2n such that sum of first n bits is same as sum of last n bits.
def count_binary_seq(n):
nCr = 1
res = 1
for r in range(1, n + 1):
nCr = (nCr * (n + 1 - r)) / r
res += nCr * nCr
return res
|
10748 | Test/png/10748.png | # Write a function to find frequency of the elements in a given list of lists using collections module.
from collections import Counter
from itertools import chain
def freq_element(nums):
result = Counter(chain.from_iterable(nums))
return result
|
10237 | Test/png/10237.png | def MLOAD(self, address):
self._allocate(address, 32)
value = self._load(address, 32)
return value
|
10313 | Test/png/10313.png | def login(self, username, password=None, token=None):
self.session.basic_auth(username, password)
|
10906 | Test/png/10906.png | # Write a function to find the largest triangle that can be inscribed in an ellipse.
import math
def largest_triangle(a, b):
if a < 0 or b < 0:
return -1
area = (3 * math.sqrt(3) * pow(a, 2)) / (4 * b)
return area
|
10654 | Test/png/10654.png | def initialize_indices():
Host.init()
Range.init()
Service.init()
User.init()
Credential.init()
Log.init()
|
10356 | Test/png/10356.png | def make_aware(dt):
return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)
|
10880 | Test/png/10880.png | # Write a function to find the occurence of characters 'std' in the given string 1. list item 1. list item 1. list item 2. list item 2. list item 2. list item
def count_occurance(s):
count = 0
for i in range(len(s)):
if s[i] == "s" and s[i + 1] == "t" and s[i + 2] == "d":
count = count + 1
return count
|
10277 | Test/png/10277.png | def calc_base64(s):
s = compat.to_bytes(s)
s = compat.base64_encodebytes(s).strip() # return bytestring
return compat.to_native(s)
|
10872 | Test/png/10872.png | # Write a python function to check whether the sum of divisors are same or not.
import math
def divSum(n):
sum = 1
i = 2
while i * i <= n:
if n % i == 0:
sum = sum + i + math.floor(n / i)
i += 1
return sum
def areEquivalent(num1, num2):
return divSum(num1) == divSum(num2)
|
11140 | Test/png/11140.png | # Write a function to find the median of a trapezium.
def median_trapezium(base1, base2, height):
median = 0.5 * (base1 + base2)
return median
|
10228 | Test/png/10228.png | def sys_rt_sigaction(self, signum, act, oldact):
return self.sys_sigaction(signum, act, oldact)
|
11147 | Test/png/11147.png | # Write a function to convert a list of multiple integers into a single integer.
def multiple_to_single(L):
x = int("".join(map(str, L)))
return x
|
11062 | Test/png/11062.png | # Write a function to find t-nth term of arithemetic progression.
def tn_ap(a, n, d):
tn = a + (n - 1) * d
return tn
|
10522 | Test/png/10522.png | def main(output):
from hbp_knowledge import get_graph
graph = get_graph()
text = to_html(graph)
print(text, file=output)
|
10836 | Test/png/10836.png | # Write a function to shortlist words that are longer than n from a given list of words.
def long_words(n, str):
word_len = []
txt = str.split(" ")
for x in txt:
if len(x) > n:
word_len.append(x)
return word_len
|
10199 | Test/png/10199.png | def isfile(path):
try:
st = os.stat(path)
except os.error:
return False
return stat.S_ISREG(st.st_mode)
|
10663 | Test/png/10663.png | def _file_path(self, uid):
file_name = '%s.doentry' % (uid)
return os.path.join(self.dayone_journal_path, file_name)
|
10167 | Test/png/10167.png | def get_domain(url):
if 'http' not in url.lower():
url = 'http://{}'.format(url)
return urllib.parse.urlparse(url).hostname
|
11171 | Test/png/11171.png | # Write a function to find the maximum product subarray of the given array.
def max_subarray_product(arr):
n = len(arr)
max_ending_here = 1
min_ending_here = 1
max_so_far = 0
flag = 0
for i in range(0, n):
if arr[i] > 0:
max_ending_here = max_ending_here * arr[i]
min_ending_here = min(min_ending_here * arr[i], 1)
flag = 1
elif arr[i] == 0:
max_ending_here = 1
min_ending_here = 1
else:
temp = max_ending_here
max_ending_here = max(min_ending_here * arr[i], 1)
min_ending_here = temp * arr[i]
if max_so_far < max_ending_here:
max_so_far = max_ending_here
if flag == 0 and max_so_far == 0:
return 0
return max_so_far
|
11094 | Test/png/11094.png | # Write a function to find out the minimum no of swaps required for bracket balancing in the given string.
def swap_count(s):
chars = s
count_left = 0
count_right = 0
swap = 0
imbalance = 0
for i in range(len(chars)):
if chars[i] == "[":
count_left += 1
if imbalance > 0:
swap += imbalance
imbalance -= 1
elif chars[i] == "]":
count_right += 1
imbalance = count_right - count_left
return swap
|
10566 | Test/png/10566.png | def handle_endtag(self, tag):
if tag in self.mathml_elements:
self.fed.append("</{0}>".format(tag))
|
10403 | Test/png/10403.png | def up(self):
self.swap(self.get_ordering_queryset().filter(
order__lt=self.order).order_by('-order'))
|
10279 | Test/png/10279.png | def append(self, object):
the_id = object.id
self._check(the_id)
self._dict[the_id] = len(self)
list.append(self, object)
|
10242 | Test/png/10242.png | def computeGaussKernel(x):
xnorm = np.power(euclidean_distances(x, x), 2)
return np.exp(-xnorm / (2.0))
|
10581 | Test/png/10581.png | def leave1out(learner, dataset):
"Leave one out cross-validation over the dataset."
return cross_validation(learner, dataset, k=len(dataset.examples))
|
10561 | Test/png/10561.png | def join(prev, sep, *args, **kw):
yield sep.join(prev, *args, **kw)
|
10135 | Test/png/10135.png | def initialize(self, argv=None):
super(BaseParallelApplication, self).initialize(argv)
self.to_work_dir()
self.reinit_logging()
|
10976 | Test/png/10976.png | # Write a function to find the n'th star number.
def find_star_num(n):
return 6 * n * (n - 1) + 1
|
10629 | Test/png/10629.png | def set_aad_cache(token, cache):
set_config_value('aad_token', jsonpickle.encode(token))
set_config_value('aad_cache', jsonpickle.encode(cache))
|
10721 | Test/png/10721.png | # Write a function to count the most common words in a dictionary.
from collections import Counter
def count_common(words):
word_counts = Counter(words)
top_four = word_counts.most_common(4)
return top_four
|
10535 | Test/png/10535.png | def delete(cls, group, user):
with db.session.begin_nested():
cls.query.filter_by(group=group, user_id=user.get_id()).delete()
|