code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function sg_compare_varEx_table ds varEx percentages
begin
comment Table Header
set header = list string \%
for i in range Nc
begin
append header i + 1
end
comment Table Rows
for k in keys varEx
begin
set rows = list header
for p in percentages
begin
set row = list integer p * 100
set res = varEx at k at p
for x in res... | def sg_compare_varEx_table(ds, varEx, percentages):
# Table Header
header = ['\%']
for i in range(Nc):
header.append(i+1)
# Table Rows
for k in varEx.keys():
rows = [header]
for p in percentages:
row = [int(p*100)]
res = varEx[k][p]
fo... | Python | nomic_cornstack_python_v1 |
function destination_address self destination_address
begin
if destination_address and destination_address < 0 or destination_address > 255
begin
raise call ValueError format string Invalid Address Value (0-255): {!r} destination_address
end
set _destination_address = destination_address
end function | def destination_address(self,
destination_address: int):
if destination_address and (destination_address < 0 or destination_address > 255):
raise ValueError('Invalid Address Value (0-255): {!r}'.format(destination_address))
self._destination_address = destinat... | Python | nomic_cornstack_python_v1 |
function _get_chunk token
begin
if token is none
begin
return string
end
function token_filter tok
begin
string True for various modifiers of tok and compound tokens, which include tok
return tok is token or ends with dep_ string mod or dep_ == string compound
end function
set tree = call _get_tree root=token depth=2 ... | def _get_chunk(token: spacy.tokens.Token) -> str:
if token is None:
return ""
def token_filter(tok):
"""True for various modifiers of tok and compound tokens, which include tok"""
return tok is token or \
tok.dep_.endswith("mod") or \
... | Python | nomic_cornstack_python_v1 |
function new_port
begin
from Crypto import Random
set n = sum map ord call get_random_bytes 10 % 9999 - custom at string base_port
return custom at string base_port + n
end function | def new_port():
from Crypto import Random
n = sum(map(ord, Random.get_random_bytes(10))) % (
9999 - config.custom['base_port'])
return config.custom['base_port'] + n | Python | nomic_cornstack_python_v1 |
function create_webserver_user
begin
call require string environment provided_by=environments
comment deploy_user already exists
if webserver_user != deploy_user
begin
call sudo string useradd --system %(webserver_user)s % env
end
end function | def create_webserver_user():
require('environment', provided_by=env.environments)
if env.webserver_user != env.deploy_user: # deploy_user already exists
sudo('useradd --system %(webserver_user)s' % env) | Python | nomic_cornstack_python_v1 |
comment Largest Contiguous Sum
comment Given an array of positive and negative integers, write a function to
comment find the contiguous sequence (in other words, a non-empty subarray of
comment adjacent elements) with the largest sum. Return the sum.
comment Sample input: [2, 3, -8, -1, 2, 4, -2, 3]
comment Expected o... | # Largest Contiguous Sum
# Given an array of positive and negative integers, write a function to
# find the contiguous sequence (in other words, a non-empty subarray of
# adjacent elements) with the largest sum. Return the sum.
# Sample input: [2, 3, -8, -1, 2, 4, -2, 3]
# Expected output: 7, from summing up the sequ... | Python | zaydzuhri_stack_edu_python |
function test_task_results_other_user self
begin
set cat = dict string id string 0 ; string title string cat-title ; string supported_os string all ; string ui_data dict string color string #123 ; string image_url string https://s3.amazonaws.com/kinapp-static/brand_img/gift_card.png ; string header_image_url string htt... | def test_task_results_other_user(self):
cat = {'id': '0',
'title': 'cat-title',
'supported_os': 'all',
'ui_data': {'color': "#123",
'image_url': 'https://s3.amazonaws.com/kinapp-static/brand_img/gift_card.png',
'header_image_url': '... | Python | nomic_cornstack_python_v1 |
function encode_body self body
begin
if is instance body bytes
begin
return body
end
return encode body string utf-8
end function | def encode_body(self, body):
if isinstance(body, bytes): return body
return body.encode("utf-8") | Python | nomic_cornstack_python_v1 |
function remove_duplicates ls key=lambda el -> el
begin
set seen = set
comment always returns True
set add_to_seen = lambda elem -> not add seen elem
return list comprehension elem for elem in ls if call key elem not in seen and call add_to_seen call key elem
end function | def remove_duplicates(ls, key=lambda el: el):
seen = set()
add_to_seen = lambda elem: not seen.add(elem) # always returns True
return [elem for elem in ls
if key(elem) not in seen and add_to_seen(key(elem))] | Python | nomic_cornstack_python_v1 |
function get_G_elements mu nu
begin
set sum = 0.0
for lambd in range 2
begin
for sigma in range 2
begin
set sum = sum + call get_G_elements_terms mu nu sigma lambd
end
end
return sum
end function | def get_G_elements(mu, nu):
sum = 0.
for lambd in range(2):
for sigma in range(2):
sum += get_G_elements_terms(mu, nu, sigma, lambd)
return sum | Python | nomic_cornstack_python_v1 |
function singledispatch func
begin
set registry = dict
set dispatch_cache = call WeakKeyDictionary
set cache_token = none
function dispatch cls
begin
string generic_func.dispatch(cls) -> <function implementation> Runs the dispatch algorithm to return the best available implementation for the given *cls* registered on ... | def singledispatch(func):
registry = {}
dispatch_cache = WeakKeyDictionary()
cache_token = None
def dispatch(cls):
"""generic_func.dispatch(cls) -> <function implementation>
Runs the dispatch algorithm to return the best available implementation
for the given *cls* registered o... | Python | nomic_cornstack_python_v1 |
comment Using Numpy, Scipy and Opencv libraries for python
import os , sys , argparse
import numpy as np
import imutils , cv2 , math
from skimage.filters import threshold_adaptive
from geopy.distance import vincenty
comment defining global variables
set debug = true
set THRESHOLD_THETA = 0.2
set THRESHOLD_RHO = 30
set ... | #Using Numpy, Scipy and Opencv libraries for python
import os, sys, argparse
import numpy as np
import imutils, cv2, math
from skimage.filters import threshold_adaptive
from geopy.distance import vincenty
#defining global variables
debug=True
THRESHOLD_THETA = 0.2
THRESHOLD_RHO = 30
RIGHT_HAND_BOUNDARY_CONSTANT = 1... | Python | zaydzuhri_stack_edu_python |
function parse_python_file filename
begin
with open filename as file
begin
set root = parse ast read file
end
return root
end function | def parse_python_file(filename: str):
with open(filename) as file:
root = ast.parse(file.read())
return root | Python | nomic_cornstack_python_v1 |
function import_comments
begin
set conn = call connection
set cur = call cursor
execute cur string SELECT id, number FROM proceedings where status = 'Open'
end function | def import_comments():
conn = db.connection()
cur = conn.cursor()
cur.execute("SELECT id, number FROM proceedings where status = 'Open'")
| Python | nomic_cornstack_python_v1 |
function update self
begin
if not payload
begin
raise call PayloadException string Invalid or Missing Payload
end
if not secret_ref
begin
raise call LookupError string Secret is not yet stored.
end
if type payload is bytes
begin
set headers = dict string content-type string application/octet-stream
end
else
if type pay... | def update(self):
if not self.payload:
raise exceptions.PayloadException("Invalid or Missing Payload")
if not self.secret_ref:
raise LookupError("Secret is not yet stored.")
if type(self.payload) is bytes:
headers = {'content-type': "application/octet-stream... | Python | nomic_cornstack_python_v1 |
function set_init_orientation self gamma theta psi
begin
set dcm at 0 = call euler2dcm gamma theta psi
end function | def set_init_orientation(self, gamma, theta, psi):
self.dcm[0] = euler2dcm(gamma, theta, psi) | Python | nomic_cornstack_python_v1 |
import glob
import numpy as np
import matplotlib.pyplot as plt
from scipy import misc
import os
from tqdm import tqdm
set atri_dir = string attribute_resized/
set mask_dir = string segmentation_resized/
set output_dir = string semantic_map/
comment [ISIC_00000, ISIC_000001, ISIC_000003, ...]
set file_name_arr = list
f... | import glob
import numpy as np
import matplotlib.pyplot as plt
from scipy import misc
import os
from tqdm import tqdm
atri_dir = 'attribute_resized/'
mask_dir = 'segmentation_resized/'
output_dir = 'semantic_map/'
file_name_arr = [] # [ISIC_00000, ISIC_000001, ISIC_000003, ...]
for file in glob.glob(atri_dir+'*.png')... | Python | zaydzuhri_stack_edu_python |
class Queue
begin
function __init__ self
begin
set li1 = list
set li2 = list
end function
function enqueue self data
begin
append li1 data
end function
function dequeue self
begin
if length li1 == 0
begin
return - 1
end
set i = length li1 - 1
while i > 0
begin
append li2 pop li1
set i = i - 1
end
pop li1
set i = leng... | class Queue:
def __init__(self):
self.li1 = []
self.li2 = []
def enqueue(self,data):
self.li1.append(data)
def dequeue(self):
if len(self.li1) == 0:
return -1
i = len(self.li1) - 1
while i > 0:
self.li2.append(self.li1.pop())
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import sys
import time
from functools import lru_cache
from itertools import permutations
from random import randint , random , shuffle
from neh import NEH
import numpy as np
import commonFunction
import random
set debug = false
class Flowshop extends object
be... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import time
from functools import lru_cache
from itertools import permutations
from random import randint, random, shuffle
from neh import NEH
import numpy as np
import commonFunction
import random
debug=False
class Flowshop(object):
"""
A class for ini... | Python | zaydzuhri_stack_edu_python |
import random
import time
import csv
import requests
from googlesearch import search
function extract_between text match last
begin
set found = find text match
if found != - 1
begin
set end = find text last length match + found + 1
return text at slice found + length match : end :
end
return none
end function
function... | import random
import time
import csv
import requests
from googlesearch import search
def extract_between(text, match, last):
found = text.find(match)
if found != -1:
end = text.find(last, len(match) + found + 1)
return text[found + len(match): end]
return None
def extract_latitude_longit... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment !/usr/bin/env python
import sys
from regex import Regex , UNICODE
import codecs
call reload sys
call setdefaultencoding string utf-8
class Generizer extends object
begin
function __init__ self
begin
set __author__ = string Revo
set __date__ = string 2017-12-28
comment self.__date__... | # -*- coding: utf-8 -*-
#!/usr/bin/env python
import sys
from regex import Regex, UNICODE
import codecs
reload(sys)
sys.setdefaultencoding('utf-8')
class Generizer(object):
def __init__(self):
self.__author__ = "Revo"
self.__date__ = "2017-12-28"
#self.__date__ = "2017-10-24"
# em... | Python | zaydzuhri_stack_edu_python |
function concat_aligned items time_major=none
begin
if length items == 0
begin
return list
end
else
if length items == 1
begin
comment we assume the input is aligned. In any case, it doesn't help
comment performance to force align it since that incurs a needless copy.
return items at 0
end
else
if is instance items at... | def concat_aligned(
items: List[np.ndarray], time_major: Optional[bool] = None
) -> np.ndarray:
if len(items) == 0:
return []
elif len(items) == 1:
# we assume the input is aligned. In any case, it doesn't help
# performance to force align it since that incurs a needless copy.
... | Python | nomic_cornstack_python_v1 |
string ResNet in PyTorch. Reference: [1] He, Kaiming, et al. "Deep residual learning for image recognition." Proceedings of the IEEE conference on computer vision and pattern recognition. 2016.
import torch
import torch.nn as nn
import torch.nn.functional as F
set _bn_mom = 0.99
class BasicBlock extends Module
begin
se... | """ResNet in PyTorch.
Reference:
[1] He, Kaiming, et al.
"Deep residual learning for image recognition."
Proceedings of the IEEE conference on computer vision and pattern recognition. 2016.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
_bn_mom = 0.99
class BasicBlock(nn.Module):
... | Python | zaydzuhri_stack_edu_python |
comment заполнить список 100 нулями, кроме первого и последнего элементов, которые должны быть равны 1:
comment первый вариант:
set list0 = list 0 * 100
set list0 at 0 = 1
set list0 at - 1 = 1
print list0
comment второй вариант:
print list 1 + list 0 * 98 + list 1
comment сформировать возрастающий список из чётных чисе... | # заполнить список 100 нулями, кроме первого и последнего элементов, которые должны быть равны 1:
# первый вариант:
list0 = [0] * 100
list0[0] = list0[-1] = 1
print(list0)
# второй вариант:
print([1]+[0]*98+[1])
# сформировать возрастающий список из чётных чисел (количество элементов 45):
list1 = [i for i in range(2, ... | Python | zaydzuhri_stack_edu_python |
async function test_light_state_change hass aioclient_mock mock_deconz_websocket
begin
set data = dict string lights dict string 0 dict string colorcapabilities 31 ; string ctmax 500 ; string ctmin 153 ; string etag string 055485a82553e654f156d41c9301b7cf ; string hascolor true ; string lastannounced none ; string last... | async def test_light_state_change(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, mock_deconz_websocket
) -> None:
data = {
"lights": {
"0": {
"colorcapabilities": 31,
"ctmax": 500,
"ctmin": 153,
"etag": "055485a82553... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
from django.http import HttpResponse
from django.utils import simplejson
import feedparser
from django.views.decorators.cache import cache_page
decorator call cache_page 60 * 60 * 2 cache=string default
function read request
begin
string Parse RSS feed given inside 'url' get param. It returns a JS... | # coding: utf-8
from django.http import HttpResponse
from django.utils import simplejson
import feedparser
from django.views.decorators.cache import cache_page
@cache_page(60 * 60 * 2, cache="default")
def read(request):
"""Parse RSS feed given inside 'url' get param. It returns a JSON array with the title and l... | Python | zaydzuhri_stack_edu_python |
function _cmd_sigs self
begin
set expression = call read_string conn
try
begin
set sigs = call get_signatures expression
end
except any
begin
with send_lock
begin
call write_bytes conn _SERR
end
call _debug_write string error in eval
call _debug_write call format_exc
end
try else
begin
with send_lock
begin
call write_b... | def _cmd_sigs(self):
expression = read_string(self.conn)
try:
sigs = self.get_signatures(expression)
except:
with self.send_lock:
write_bytes(self.conn, ReplBackend._SERR)
_debug_write('error in eval')
_debug_write(traceback.format_... | Python | nomic_cornstack_python_v1 |
function test_tree_binary_tree_traversals self
begin
set n2 = call BinaryNode 2
set n6 = call BinaryNode 6
set n20 = call BinaryNode 20
set n4 = call BinaryNode 4 n2 n6
set n10 = call BinaryNode 10 none n20
set n8 = call BinaryNode 8 n4 n10
set in_order_sequence = list
call in_order_traversal n8 in_order_sequence
asse... | def test_tree_binary_tree_traversals(self):
n2 = tb.BinaryNode(2)
n6 = tb.BinaryNode(6)
n20 = tb.BinaryNode(20)
n4 = tb.BinaryNode(4, n2, n6)
n10 = tb.BinaryNode(10, None, n20)
n8 = tb.BinaryNode(8, n4, n10)
in_order_sequence = []
tb.in_order_traversal(n8,... | Python | nomic_cornstack_python_v1 |
comment code
function find_longest_pallindrome inp_str
begin
set str_len = length inp_str
set track_arr = list comprehension list comprehension 0 for x in range str_len for y in range str_len
set max_len = 1
set start_i = 0
import pdb
call set_trace
comment Fixing positions in track_arr for single chars
for i in range ... | #code
def find_longest_pallindrome(inp_str):
str_len = len(inp_str)
track_arr = [[0 for x in range(str_len)] for y in range(str_len)]
max_len = 1
start_i = 0
import pdb; pdb.set_trace()
# Fixing positions in track_arr for single chars
for i in range(str_len):
track_arr[i][i] = 1
... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode.cn id=480 lang=python3
comment [480] 滑动窗口中位数
comment https://leetcode-cn.com/problems/sliding-window-median/description/
comment algorithms
comment Hard (40.02%)
comment Likes: 152
comment Dislikes: 0
comment Total Accepted: 8.6K
comment Total Submissions: 21.5K
comment Testcase Example: '[1,3,... | #
# @lc app=leetcode.cn id=480 lang=python3
#
# [480] 滑动窗口中位数
#
# https://leetcode-cn.com/problems/sliding-window-median/description/
#
# algorithms
# Hard (40.02%)
# Likes: 152
# Dislikes: 0
# Total Accepted: 8.6K
# Total Submissions: 21.5K
# Testcase Example: '[1,3,-1,-3,5,3,6,7]\n3'
#
# 中位数是有序序列最中间的那个数。如果序列的大... | Python | zaydzuhri_stack_edu_python |
import numpy as np
class Integrator
begin
string Base integrator class. The implemented integrators should be able to solve the differential equation dy -- = f(t, y) dt efficiently. :param dt: step length :type dt: float :param f: f(t, y) is a function of t and y :type f: func
function __init__ self dt f
begin
set dt =... | import numpy as np
class Integrator:
"""Base integrator class. The implemented integrators should
be able to solve the differential equation
dy
-- = f(t, y)
dt
efficiently.
:param dt: step length
:type dt: float
:param f: f(t, y) is a function of t and y
:type f: func
""... | Python | zaydzuhri_stack_edu_python |
function style_format script style
begin
return format script s=start m=mid e=end
end function | def style_format(script, style):
return script.format(s=style.start, m=style.mid, e=style.end) | Python | nomic_cornstack_python_v1 |
function _setup_working_dir self working_dir
begin
debug string setting up working dir in %s % working_dir
comment create the working directory
make directory self working_dir
set files = call iteritems
comment give all our files names, and symlink or unarchive them
for tuple name path in files
begin
set dest = join pa... | def _setup_working_dir(self, working_dir):
log.debug('setting up working dir in %s' % working_dir)
# create the working directory
self.mkdir(working_dir)
files = self._working_dir_mgr.name_to_path('file').iteritems()
# give all our files names, and symlink or unarchive t... | Python | nomic_cornstack_python_v1 |
string * * * * * * * * * * * * * * *
class Pattern6
begin
function printPattern self n
begin
for i in range n 0 - 1
begin
for x in range n - i
begin
print string end=string
end
for j in range i
begin
print string * end=string
end
print
end
end function
end class
set ob = call Pattern6
set rows = integer input string H... | """
* * * * *
* * * *
* * *
* *
*
"""
class Pattern6:
def printPattern(self,n):
for i in range(n,0,-1):
for x in range(n-i):
print(" ",end="")
for j in range(i):
print("* ",end="")
print()
ob = Pattern6()
rows = int(input("How ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Jun 29 16:41:18 2021 @author: silva
import os
set environ at string TF_CPP_MIN_LOG_LEVEL = string 2
import tensorflow as tf
from tensorflow import keras
import csv
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from IPython.dis... | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 29 16:41:18 2021
@author: silva
"""
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import tensorflow as tf
from tensorflow import keras
import csv
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from IPython.display import c... | Python | zaydzuhri_stack_edu_python |
function onSubData self data
begin
comment split msg to get topic and message
set tuple _topic _msg = split data string
print format string Data on Topic={} with Message={} _topic _msg end=string flush=true
end function | def onSubData(self, data):
# split msg to get topic and message
_topic, _msg = data.split(" ")
print('\rData on Topic={} with Message={}'.format(_topic, _msg), end='', flush=True) | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
class Image_Stitching
begin
function __init__ self
begin
set ratio = 0.85
set min_match = 10
set sift = call SIFT_create
set smoothing_window_size = 100
end function
comment 获取单应性矩阵
function registration self img1 img2
begin
comment 分别获取两张图的关键点kp1,kp2以及是描述子des1,des1
set tuple kp1 des1 = ca... | import numpy as np
import cv2
class Image_Stitching():
def __init__(self):
self.ratio = 0.85
self.min_match = 10
self.sift = cv2.xfeatures2d.SIFT_create()
self.smoothing_window_size = 100
# 获取单应性矩阵
def registration(self, img1, img2):
# 分别获取两张图的关键点kp1... | Python | zaydzuhri_stack_edu_python |
comment 다음의 결과와 같이 반목문을 이용해 단어의 순서를 거꾸로 해 반환하는 함수를 작성하고
comment 그 함수를 이용해 회문(앞뒤 어느 쪽에서도 같은 단어, 말) 여부를 판단하는 코드를 작성하십시오
comment 입력
comment eye
comment 출력
comment eye
comment 입력하신 단어는 회문(Palindrome)입니다.
comment 문자열로 입력받는다
set a = input
comment n-1
set num = length a
set result = string
for i in a
begin
set result = resul... | # 다음의 결과와 같이 반목문을 이용해 단어의 순서를 거꾸로 해 반환하는 함수를 작성하고
# 그 함수를 이용해 회문(앞뒤 어느 쪽에서도 같은 단어, 말) 여부를 판단하는 코드를 작성하십시오
# 입력
# eye
# 출력
# eye
#
# 입력하신 단어는 회문(Palindrome)입니다.
a=input() #문자열로 입력받는다
num=len(a) #n-1
result=""
for i in a :
result=result+i
print(result)
if a==result :
print("입력하신 단어는 회문(Palindrome)입니다.") | Python | zaydzuhri_stack_edu_python |
import sys
set input = readline
from operator import itemgetter
function main
begin
set tuple a b t = map int split strip input
set span = b - a
print b + t - b + span - 1 // span * span
end function
if __name__ == string __main__
begin
call main
end | import sys
input = sys.stdin.readline
from operator import itemgetter
def main():
a, b, t = map(int, input().strip().split())
span = b - a
print(b + ((t - b + span - 1) // span) * span)
if __name__ == '__main__':
main()
| Python | zaydzuhri_stack_edu_python |
comment 1 Problem Statement Link : https://www.codechef.com/COOK112B/problems/DIET
comment Solution :
for _ in range integer input
begin
set tuple n k = map int split input
set li = list map int split input
set remaining_gram = 0
set status = false
set total = 0
set count = 0
for i in li
begin
set total = remaining_gra... | # 1 Problem Statement Link : https://www.codechef.com/COOK112B/problems/DIET
# Solution :
for _ in range(int(input())):
n, k = map(int, input().split())
li = list(map(int, input().split()))
remaining_gram = 0
status = False
total = 0
count = 0
for i in li:
total = remaining_gram + i
if total >= k:
count ... | Python | zaydzuhri_stack_edu_python |
function randomAssign self evidence
begin
comment TODO: Define this method, in conjunction with the other three methods to implement the Gibbs sampling algorithm
pass
end function | def randomAssign(self, evidence):
pass # TODO: Define this method, in conjunction with the other three methods to implement the Gibbs sampling algorithm | Python | nomic_cornstack_python_v1 |
string CS5250 Assignment 4, Scheduling policies simulator Sample skeleton program Original Author: Minh Ho Edited by: Joshua Siao Re-implementation of FCFS and implementation of RR, SRTF and SJF scheduling schemes. Input file: input.txt Output files: FCFS.txt RR.txt SRTF.txt SJF.txt Apr 10th Revision 1: Update FCFS imp... | '''
CS5250 Assignment 4, Scheduling policies simulator
Sample skeleton program
Original Author: Minh Ho
Edited by: Joshua Siao
Re-implementation of FCFS and implementation of RR, SRTF and SJF scheduling schemes.
Input file:
input.txt
Output files:
FCFS.txt
RR.txt
SRTF.txt
SJF.txt
Apr 10th Revision ... | Python | zaydzuhri_stack_edu_python |
function call self inputs
begin
return call resize_with_crop_or_pad inputs _shape_internal padding_mode=_padding_mode
end function | def call(self, inputs):
return array_ops.resize_with_crop_or_pad(inputs, self._shape_internal,
padding_mode=self._padding_mode) | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
import sys
import csv
class Point
begin
function __init__ self x y realFlag
begin
set x = x
set y = y
set realFlag = realFlag
set guessFlag = none
end function
function __repr__ self
begin
return string (x, y) = ( + string x + string , + string y + string ) , realFlag:... | import numpy as np
import matplotlib.pyplot as plt
import sys
import csv
class Point:
def __init__(self, x, y, realFlag):
self.x = x
self.y = y
self.realFlag = realFlag
self.guessFlag = None
def __repr__(self):
return "(x, y) = (" + str(self.x) + ", " + s... | Python | zaydzuhri_stack_edu_python |
import argparse
set a = open string data.txt
set X = split read line a
set X = list comprehension decimal x for x in X
set Y = split read line a
set Y = list comprehension decimal y for y in Y
print X
print Y
close a
set parser = call ArgumentParser
call add_argument string x metavar=string x type=float nargs=string + ... | import argparse
a = open('data.txt')
X = a.readline().split()
X = [float(x) for x in X]
Y = a.readline().split()
Y = [float(y) for y in Y]
print(X)
print(Y)
a.close()
parser = argparse.ArgumentParser()
parser.add_argument('x', metavar='x', type=float, nargs='+',
help='input number')
i = 0
K = [... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
from SourceLib import SourceRcon
if __name__ == string __main__
begin
import argparse
set parser = call ArgumentParser description=string Start a server
call add_argument string -s help=string Server IP dest=string ip required=true
call add_argument string -sp ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from SourceLib import SourceRcon
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='Start a server')
parser.add_argument('-s', help='Server IP', dest='ip', required=True)
parser.add_argument('-sp', help='Server port... | Python | zaydzuhri_stack_edu_python |
comment Valo Mara
comment vmara2
comment Monday 3:00PM
comment Drawing concentric shapes
function drawSquare turtle size
begin
call forward turtle size
call turnRight turtle
call forward turtle size
call turnRight turtle
call forward turtle size
call turnRight turtle
call forward turtle size
end function
function drawC... | #Valo Mara
#vmara2
#Monday 3:00PM
#Drawing concentric shapes
def drawSquare(turtle,size):
forward(turtle,size)
turnRight(turtle)
forward(turtle,size)
turnRight(turtle)
forward(turtle,size)
turnRight(turtle)
forward(turtle,size)
def drawConcentricSquare(turtle):
numSquare = 1
while (numSquare < 20... | Python | zaydzuhri_stack_edu_python |
function paragraphs value autoescape=none
begin
if autoescape
begin
set esc = conditional_escape
end
else
begin
set esc = lambda x -> x
end
set paras = split re string [\r\n]+ value
set paras = list comprehension string <p>%s</p> % call esc strip p for p in paras
return call mark_safe join string paras
end function | def paragraphs(value, autoescape=None):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
paras = re.split(r'[\r\n]+', value)
paras = ['<p>%s</p>' % esc(p.strip()) for p in paras]
return mark_safe('\n'.join(paras)) | Python | nomic_cornstack_python_v1 |
import requests
from lxml import html
import os
function main
begin
string Solution to "I hate mathematics". Requires that you set an environment variable PHPSESSID.
set BASE_URL = string https://ringzer0team.com/challenges/32/
set cookie = dict string PHPSESSID call getenv string PHPSESSID
set response = get requests ... | import requests
from lxml import html
import os
def main():
'''
Solution to "I hate mathematics".
Requires that you set an environment variable PHPSESSID.
'''
BASE_URL = "https://ringzer0team.com/challenges/32/"
cookie = {
"PHPSESSID": os.getenv("PHPSESSID"),
}
response = requ... | Python | zaydzuhri_stack_edu_python |
function parse_cellline_page self response
begin
set table_html = get call xpath string //table
set df = call read_html io=table_html at 0
set record = call to_dict
comment add link
update record dict string link url
yield record
end function | def parse_cellline_page(self, response):
table_html = response.xpath('//table').get()
df = pd.read_html(io=table_html)[0]
record = df.dropna().set_index(0)[1].to_dict()
record.update({'link': response.url}) # add link
yield record | Python | nomic_cornstack_python_v1 |
function printElfAndOatSymbols self symbols title
begin
set rows = list
if symbols
begin
for symbol in symbols
begin
append rows list name call liefConstToString type hexadecimal value hexadecimal size call liefConstToString visibility if expression is_function then string Yes else string No if expression is_static th... | def printElfAndOatSymbols(self, symbols, title):
rows = []
if symbols:
for symbol in symbols:
rows.append([
symbol.name,
self.liefConstToString(symbol.type),
hex(symbol.value),
hex(symbol.size),
... | Python | nomic_cornstack_python_v1 |
function createFunctionTerm self
begin
return call Transition_createFunctionTerm self
end function | def createFunctionTerm(self):
return _libsbml.Transition_createFunctionTerm(self) | Python | nomic_cornstack_python_v1 |
comment Exercicio 3
set sexo = upper string input string Informe seu sexo: [M]asculino / [F]eminino:
if sexo at 0 == string M
begin
print string Sexo masculino!
end
else
if sexo at 0 == string F
begin
print string Sexo Feminino!
end
else
begin
print string Sexo Invalido!
end | #Exercicio 3
sexo = str(input('Informe seu sexo: [M]asculino / [F]eminino: ')).upper()
if sexo[0] == 'M':
print('Sexo masculino!')
elif sexo[0] == 'F':
print('Sexo Feminino!')
else:
print('Sexo Invalido! ')
| Python | zaydzuhri_stack_edu_python |
function view_period self period_guess=0.25 operation=string mean_z nslice=10 e_or_m=none
begin
set pos = period_guess
set check = list string mean_x string min_x string max_x string mean_y string min_y string max_y string mean_z string min_z string max_z
if operation not in check
begin
return print format string opera... | def view_period(self,period_guess=0.25,operation='mean_z',nslice=10,e_or_m=None,):
pos = period_guess
check = ['mean_x','min_x','max_x','mean_y','min_y','max_y','mean_z','min_z','max_z']
if operation not in check:
return print("operation expects any of {!r}, got {}".format(check,oper... | Python | nomic_cornstack_python_v1 |
comment ============================================================================#
comment FIT AND TEST CLASSIFICATION ALGORITHM
comment ============================================================================#
string Runs the full classification loop. Inputs include training and testing set directory paths, as ... | #============================================================================#
# FIT AND TEST CLASSIFICATION ALGORITHM
#============================================================================#
'''
Runs the full classification loop. Inputs include training and testing set
directory paths, as well as training and t... | Python | zaydzuhri_stack_edu_python |
function dataproduct self identity dataproduct_id
begin
set metadata = dict
set permissions = call dataproduct_permissions dataproduct_id identity or dict
set session = call session
comment find Group or Data layer object
set OWSLayer = model string ows_layer
set query = filter by query session OWSLayer name=dataprod... | def dataproduct(self, identity, dataproduct_id):
metadata = {}
permissions = self.permission.dataproduct_permissions(
dataproduct_id, identity
) or {}
session = self.config_models.session()
# find Group or Data layer object
OWSLayer = self.config_models.mod... | Python | nomic_cornstack_python_v1 |
function find_relevant_points red_x red_y green_x green_y
begin
call get_distinct_coordinates green_x green_y
call get_distinct_coordinates red_x red_y
return tuple red_x red_y green_x green_y
end function | def find_relevant_points(red_x, red_y, green_x, green_y):
get_distinct_coordinates(green_x, green_y)
get_distinct_coordinates(red_x, red_y)
return red_x, red_y, green_x, green_y | Python | nomic_cornstack_python_v1 |
function distributeCandies candies
begin
set newList = set candies
return min length candies / 2 length newList
end function | def distributeCandies(candies):
newList = set(candies)
return min(len(candies)/2,len(newList))
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import RPi.GPIO as GPIO
import blinky as b
import time as t
call setmode BCM
setup GPIO 16 IN
setup GPIO 21 IN
setup GPIO 25 IN
setup GPIO 12 IN
setup GPIO 20 IN
while true
begin
if input 25 == false
begin
call red
end
else
if input 12 == false
begin
call yellow
end
else
if input 16 == fal... | #!/usr/bin/env python3
import RPi.GPIO as GPIO
import blinky as b
import time as t
GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.IN)
GPIO.setup(21, GPIO.IN)
GPIO.setup(25, GPIO.IN)
GPIO.setup(12, GPIO.IN)
GPIO.setup(20, GPIO.IN)
while True:
if GPIO.input(25) == False:
b.red()
elif GPIO.input(12) == False... | Python | zaydzuhri_stack_edu_python |
from collections import deque
import random
from cards import Card
set __all__ = list string Deck
class Deck extends object
begin
string Represents a playing card deck optionally with jokers. Each member is an instance of :class:`cardsource.cards.Card`. A ``Deck`` is an iterable object that supports a number of standar... | from collections import deque
import random
from .cards import Card
__all__ = ['Deck']
class Deck(object):
"""
Represents a playing card deck optionally with jokers. Each member is
an instance of :class:`cardsource.cards.Card`.
A ``Deck`` is an iterable object that supports a number of standard
... | Python | zaydzuhri_stack_edu_python |
function get_vb_distribution_active_replica self servers=list buckets=list
begin
set servers = call get_kv_nodes servers
set tuple active replica = call collect_vbucket_num_stats servers buckets
set tuple active_result replica_result = call compare_analyze_active_replica_vb_nums active replica
return tuple active_resu... | def get_vb_distribution_active_replica(self, servers=[], buckets=[]):
servers = self.get_kv_nodes(servers)
active, replica = self.data_collector.collect_vbucket_num_stats(servers, buckets)
active_result, replica_result = self.data_analyzer.compare_analyze_active_replica_vb_nums(active, replica)
... | Python | nomic_cornstack_python_v1 |
function get_maximum_time self
begin
comment Implemented from template for osid.Metadata.get_minimum_cardinal
from osid_errors import IllegalState
if _kwargs at string syntax not in list string TIME
begin
raise call IllegalState
end
else
begin
return _kwargs at string maximum_time
end
end function | def get_maximum_time(self):
# Implemented from template for osid.Metadata.get_minimum_cardinal
from .osid_errors import IllegalState
if self._kwargs['syntax'] not in ['TIME']:
raise IllegalState()
else:
return self._kwargs['maximum_time'] | Python | nomic_cornstack_python_v1 |
function initDB dburi=string sqlite:// echo=false clear=false
begin
set engine = call create_engine dburi
set echo = echo
call connect engine
if clear
begin
call drop_all
end
call create_all
return metadata
end function | def initDB(dburi='sqlite://', echo=False, clear=False):
engine = sqla.create_engine(dburi)
engine.echo=echo
metadata.connect(engine)
if clear:
metadata.drop_all()
metadata.create_all()
return metadata | Python | nomic_cornstack_python_v1 |
set x = input string ?
set a = integer x
set x = input string ?
set b = integer x
print a * b | x = input("?")
a = int(x)
x = input("?")
b = int(x)
print (a *b)
| Python | zaydzuhri_stack_edu_python |
function transition s direction
begin
comment sum up every element at same index of two lists
set new_pos = list comprehension sum x for x in zip s direction
if call hit_wall new_pos
begin
return s
end
else
begin
return new_pos
end
end function | def transition(s, direction):
new_pos = [sum(x) for x in zip(s, direction)] # sum up every element at same index of two lists
if hit_wall(new_pos):
return s
else:
return new_pos | Python | nomic_cornstack_python_v1 |
class DesignHashSet
begin
function __init__ self
begin
set table = bytearray 10 ^ 6
end function
function add self key
begin
set table at key = 1
end function
function remove self key
begin
set table at key = 0
end function
function contains self key
begin
return table at key == 1
end function
end class | class DesignHashSet:
def __init__(self):
self.table = bytearray(10 ** 6)
def add(self, key: int):
self.table[key] = 1
def remove(self, key: int):
self.table[key] = 0
def contains(self, key):
return self.table[key] == 1
| Python | zaydzuhri_stack_edu_python |
function groupAnagrams self strs
begin
set dict_result = default dictionary list
for s in strs
begin
append dict_result at join string sorted s s
end
return values dict_result
end function | def groupAnagrams(self, strs):
dict_result = collections.defaultdict(list)
for s in strs:
dict_result[''.join(sorted(s))].append(s)
return dict_result.values()
| Python | zaydzuhri_stack_edu_python |
comment Parser.py
from Lexer import Lexer
from Partiture import make_midi
import ply.yacc as yacc
import sys
from ColorsPL import bcolors
from Composer import Composer
class Parser
begin
set tokens = tokens
function __init__ self
begin
set parser = none
set lexer = none
comment start values for notes
set cNote = 60
com... | # Parser.py
from Lexer import Lexer
from Partiture import make_midi
import ply.yacc as yacc
import sys
from ColorsPL import bcolors
from Composer import Composer
class Parser:
tokens = Lexer.tokens
def __init__(self):
self.parser = None
self.lexer = None
self.cNote = 60 # start valu... | Python | zaydzuhri_stack_edu_python |
comment 1 Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
set path = string diabetes.csv
set dataset = read csv path
set X = values
set y = ... | #1 Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn import metrics
path = "diabetes.csv"
dataset = pd.read_csv(path)
X = dataset.iloc[:, :8].valu... | Python | zaydzuhri_stack_edu_python |
import urllib.request
url retrieve string http://example.com/file.jpg string local.jpg
comment Code executed. | import urllib.request
urllib.request.urlretrieve('http://example.com/file.jpg', 'local.jpg')
# Code executed.
| Python | flytech_python_25k |
import requests
from bs4 import BeautifulSoup
set m = string https://www.thespike.gg
set url = string https://www.thespike.gg/events/
set req = get requests url
set soup = call BeautifulSoup content string html.parser
set f = find all soup string ul dict string class string events-overview-lists
set a = list
for i in ... | import requests
from bs4 import BeautifulSoup
m = "https://www.thespike.gg"
url = "https://www.thespike.gg/events/"
req = requests.get(url)
soup = BeautifulSoup(req.content,"html.parser")
f = soup.find_all("ul",{"class":"events-overview-lists"})
a = []
for i in f:
l = i.find("a")
a.append(l.get("href"))
m... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import argparse as ap
import os
from googlesearch import lucky , search
from os import mkdir , chdir
string This script is meant to download albums from Spotify easily, after creating its directory. It will : - Create a directory for the album and move into it. - Perform a google search to... | #!/usr/bin/env python3
import argparse as ap
import os
from googlesearch import lucky, search
from os import mkdir, chdir
""" This script is meant to download albums from Spotify easily, after creating its directory.
It will :
- Create a directory for the album and move into it.
- Perform a google search to... | Python | zaydzuhri_stack_edu_python |
function configure_with_sound_control self
begin
for q in questions
begin
comment reconfiguring the question to a sound control object
set q at string question = call sc q at string question
comment making sure that the on_wrong option is not set to None befor setting it be a sound control object
if not get q string on... | def configure_with_sound_control(self):
for q in self.questions:
q["question"] = sc(q["question"]) #reconfiguring the question to a sound control object
if not q.get("on_wrong") == None: #making sure that the on_wrong option is not set to None befor setting it be a sound control object
q["on_wrong"] = sc(q[... | Python | nomic_cornstack_python_v1 |
function forward_exponential_habets alpha N D DRR PSD_Y PSD_V
begin
set E = exp - 2 * alpha * N * D
set kappa = min 1 - E / DRR * E 1
set psd_X = call maximum PSD_Y - PSD_V 0
set tuple K N = shape
set PSD_R = call empty tuple K N
for n in range D N
begin
set PSD_R at tuple slice : : n = 1 - kappa * E * PSD_R at tupl... | def forward_exponential_habets(alpha, N, D, DRR, PSD_Y, PSD_V):
E = np.exp(-2*alpha*N*D)
kappa = min( (1 - E) / (DRR * E ), 1)
psd_X = np.maximum(PSD_Y - PSD_V, 0)
K, N = PSD_Y.shape
PSD_R = np.empty((K,N))
for n in range(D,N):
PSD_R[:,n] = ( (1-kappa) * E * PSD_R[:,n-D] ) + ( kappa * ... | Python | nomic_cornstack_python_v1 |
function restore_run self run_id
begin
call restore_run run_id
end function | def restore_run(self, run_id):
self._tracking_client.restore_run(run_id) | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
string DESCRIPTION: A working solution for Python challenge problem #8, which starts at: http://www.pythonchallenge.com/pc/def/integrity.html The page has a linked image which takes you to a password protected area. The interesting part of the source seems to be: <!-- un: 'BZh91AY&SYA¯ ... | #! /usr/bin/env python
"""
DESCRIPTION:
A working solution for Python challenge problem #8, which starts at:
http://www.pythonchallenge.com/pc/def/integrity.html
The page has a linked image which takes you to a password protected
area. The interesting part of the source seems to be:
<!--
un: 'BZ... | Python | zaydzuhri_stack_edu_python |
function timeout self
begin
return get pulumi self string timeout
end function | def timeout(self) -> Optional[str]:
return pulumi.get(self, "timeout") | Python | nomic_cornstack_python_v1 |
import pickle
from os.path import join
set pkl_dir = string ./my_pick_and_place
set demos_file = string demos_0.pkl
with open join pkl_dir demos_file string rb as f
begin
set data = load pickle f
print string data data
for tuple k v in items data
begin
print k
try
begin
print shape
end
except any
begin
print k
end
end
... | import pickle
from os.path import join
pkl_dir = "./my_pick_and_place"
demos_file = "demos_0.pkl"
with open(join(pkl_dir, demos_file), 'rb') as f:
data = pickle.load(f)
print("data", data)
for k,v in data.items():
print(k)
try:
print(v.shape)
except:
print(k... | Python | zaydzuhri_stack_edu_python |
import time
function timer t
begin
while t
begin
set tuple mins secs = divide mod t 60
set timer = format string {:02d}:{:02d} mins secs
print timer end=string
sleep 1
set t = t - 1
end
print string time is up
end function
set t = integer input string input time in secs:
call timer t | import time
def timer(t):
while t :
mins, secs= divmod(t,60)
timer= '{:02d}:{:02d}'.format(mins, secs)
print(timer, end="\r")
time.sleep(1)
t-=1
print('time is up ')
t = int(input('input time in secs: '))
timer(t)
| Python | zaydzuhri_stack_edu_python |
function push self
begin
set dict_to_push = dict
for field in field_list
begin
set dict_to_push at call get_field_name = lower string get field
end
call push _hash dict_to_push
end function | def push(self):
dict_to_push = {}
for field in self.field_list:
dict_to_push[field.get_field_name()] = str(field.get()).lower()
self._db.push(self._hash, dict_to_push) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import os
import time
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import cnn_learn.alexnet_learn.alexnet_inference as inference
import cnn_learn.alexnet_learn.alexnet_train as mnist_train
comment 每10秒加载一次最新的模型,并在测试数据上测试最新模型的正确率
set ... | # -*- coding: utf-8 -*-
import os
import time
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import cnn_learn.alexnet_learn.alexnet_inference as inference
import cnn_learn.alexnet_learn.alexnet_train as mnist_train
# 每10秒加载一次最新的模型,并在测试数据上测试最新模型的正确率
E... | Python | zaydzuhri_stack_edu_python |
set n = input string Escreva algo:
print string { n } é do tipo { type n }
print string { n } é numérico? { call isnumeric }
print string { n } é letra? { is alpha n }
print string { n } é alfanumérico? { is alphanumeric n }
print string { n } é decimal? { call isdecimal }
print string { n } só tem espaços? { is space ... | n = input('Escreva algo: ')
print(f'{n} é do tipo {type(n)}')
print(f'{n} é numérico? {n.isnumeric()}')
print(f'{n} é letra? {n.isalpha()}')
print(f'{n} é alfanumérico? {n.isalnum()}')
print(f'{n} é decimal? {n.isdecimal()}')
print(f'{n} só tem espaços? {n.isspace()}')
print(f'{n} está em maiúsculas? {n.isupper()}')
p... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment in team with:
comment Jakub Arnold 2894e3d5-bd76-11e7-a937-00505601122b
comment Petra Doubravová 7ac09119-b96f-11e7-a937-00505601122b
import numpy as np
import mountain_car_evaluator
function selectAction state
begin
set rand = call rand
if rand <= epsilon
begin
return random integ... | #!/usr/bin/env python3
# in team with:
#Jakub Arnold 2894e3d5-bd76-11e7-a937-00505601122b
#Petra Doubravová 7ac09119-b96f-11e7-a937-00505601122b
import numpy as np
import mountain_car_evaluator
def selectAction(state):
rand = np.random.rand()
if(rand <= epsilon):
return np.random.randint(0... | Python | zaydzuhri_stack_edu_python |
function get_quantity self
begin
return quantity
end function | def get_quantity(self):
return self.quantity | Python | nomic_cornstack_python_v1 |
function resource self
begin
return get pulumi self string resource
end function | def resource(self) -> Optional[pulumi.Input['_core.v1.TypedLocalObjectReferencePatchArgs']]:
return pulumi.get(self, "resource") | Python | nomic_cornstack_python_v1 |
function MakeParentDirectoriesWorldReadable path
begin
comment No need to do anything special on Windows.
if call IsWindows
begin
return
end
while path != directory name path path
begin
set current_permissions = call S_IMODE call stat path at ST_MODE
end
end function | def MakeParentDirectoriesWorldReadable(path):
# No need to do anything special on Windows.
if IsWindows():
return
while path != os.path.dirname(path):
current_permissions = stat.S_IMODE(os.stat(path)[stat.ST_MODE]) | Python | nomic_cornstack_python_v1 |
import re
function abbreviate input
begin
set result = string
set input = sub string [,] string input
set input = sub string [-] string input
set input = split input string : at 0
for word in split input string
begin
set first_letter = upper word at 0
set result = result + first_letter
set word = word at slice 1 : ... | import re
def abbreviate(input):
result = ''
input = re.sub('[,]', '', input)
input = re.sub('[-]', ' ', input)
input = input.split(':')[0]
for word in input.split(' '):
first_letter = word[0].upper()
result += first_letter
word = word[1:]
for letter in word:
... | Python | zaydzuhri_stack_edu_python |
import math
set n = integer input string 1st :
set m = integer input string 2nd :
for i in range n m
begin
if i > 1
begin
for num in range 2 i
begin
if i % num == 0
begin
break
end
end
for else
begin
print i
end
end
end | import math
n=int(input('1st : '))
m=int(input("2nd : "))
for i in range(n,m):
if i>1:
for num in range(2,i):
if(i % num)==0:
break
else:
print(i) | Python | zaydzuhri_stack_edu_python |
for i in range m + 1
begin
for j in range n + 1
begin
if i == 0 or j == 0
begin
continue
end
if s at i - 1 == t at j - 1
begin
set dp at i at j = max dp at i - 1 at j 1 + dp at i - 1 at j - 1
end
else
begin
set dp at i at j = max dp at i at j - 1 dp at i - 1 at j
end
end
end
print dp at m at n | for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0:
continue
if s[i-1] == t[j-1]:
dp[i][j] = max(dp[i-1][j], 1 + dp[i-1][j-1])
else:
dp[i][j] = max(dp[i][j-1], dp[i-1][j])
print(dp[m][n])
| Python | zaydzuhri_stack_edu_python |
string Largest BST Subtree Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it. Note: A subtree must include all of its descendants. Example: Input: [10,5,15,1,8,null,7] 10 / \ 5 15 / \ \ 1 8 7 Output: 3 Explanation: The Large... | """
Largest BST Subtree
Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.
Note:
A subtree must include all of its descendants.
Example:
Input: [10,5,15,1,8,null,7]
10
/ \
5 15
/ \ \
1 8 7
Output: 3... | Python | zaydzuhri_stack_edu_python |
function create_package_proxy self record package_id package_node_id legacy_relationship_type=PROXY_RELATIONSHIP_TYPE
begin
with call session as s
begin
comment Safe to use session with `create_package_proxy_tx()`:
return call create_package_proxy_tx tx=s record=record package_id=package_id package_node_id=package_node... | def create_package_proxy(
self,
record: Union[Record, RecordId],
package_id: int,
package_node_id: str,
legacy_relationship_type: str = labels.PROXY_RELATIONSHIP_TYPE,
) -> PackageProxy:
with self.session() as s:
# Safe to use session with `create_package_... | Python | nomic_cornstack_python_v1 |
function add_netnode_plugin_name plugin_name
begin
string Add the given plugin name to the list of plugin names registered in the current IDB. Note that this implicitly uses the open IDB via the idc iterface.
set current_names = set call get_netnode_plugin_names
if plugin_name in current_names
begin
return
end
add curr... | def add_netnode_plugin_name(plugin_name):
"""
Add the given plugin name to the list of plugin names registered in
the current IDB.
Note that this implicitly uses the open IDB via the idc iterface.
"""
current_names = set(get_netnode_plugin_names())
if plugin_name in current_names:
... | Python | jtatman_500k |
function _construct_axes_from_arguments self args kwargs require_all=false sentinel=none
begin
string Construct and returns axes if supplied in args/kwargs. If require_all, raise if all axis arguments are not supplied return a tuple of (axes, kwargs). sentinel specifies the default parameter when an axis is not supplie... | def _construct_axes_from_arguments(
self, args, kwargs, require_all=False, sentinel=None):
"""Construct and returns axes if supplied in args/kwargs.
If require_all, raise if all axis arguments are not supplied
return a tuple of (axes, kwargs).
sentinel specifies the default... | Python | jtatman_500k |
function replace_links soup resource_dir replace_data
begin
set resource_tags = find all name=list keys TAGS_ATTR
call change_tags resource_tags replace_data resource_dir
return call prettify
end function | def replace_links(
soup: BeautifulSoup,
resource_dir: str,
replace_data: dict,
) -> str:
resource_tags = soup.findAll(name=list(TAGS_ATTR.keys()))
change_tags(resource_tags, replace_data, resource_dir)
return soup.prettify() | Python | nomic_cornstack_python_v1 |
function tokenize self filename new_filename=false
begin
for tuple idx string in enumerate call get_text_list
begin
set table = __tables at idx
for column in find all string column
begin
if get column string name == string text
begin
set output = check output string echo ' + text + string ' | greeb shell=true
set text_... | def tokenize(self, filename, new_filename=False):
for idx, string in enumerate(self.get_text_list()):
table = self.__tables[idx]
for column in table.findall('column'):
if column.get('name') == 'text':
output = subprocess.check_output("echo '" + column... | Python | nomic_cornstack_python_v1 |
set info = dict string first_name string wang ; string last_name string xiaoming ; string age 18 ; string city string beijing
print info at string first_name
print info at string last_name
print info at string age
print info at string city | info = {
'first_name': 'wang',
'last_name': 'xiaoming',
'age': 18,
'city': 'beijing',
}
print(info['first_name'])
print(info['last_name'])
print(info['age'])
print(info['city']) | Python | zaydzuhri_stack_edu_python |
function plot_voxel_surface cls mview vox value col line_thick
begin
call _plot_voxel_surface call _get_tls_geo mview vox value col line_thick
end function | def plot_voxel_surface(cls, mview, vox, value, col, line_thick):
gxapi_cy.WrapMVU._plot_voxel_surface(GXContext._get_tls_geo(), mview, vox, value, col, line_thick) | Python | nomic_cornstack_python_v1 |
function user_interest_path customer_id user_interest_id
begin
return format string customers/{customer_id}/userInterests/{user_interest_id} customer_id=customer_id user_interest_id=user_interest_id
end function | def user_interest_path(customer_id: str, user_interest_id: str,) -> str:
return "customers/{customer_id}/userInterests/{user_interest_id}".format(
customer_id=customer_id, user_interest_id=user_interest_id,
) | Python | nomic_cornstack_python_v1 |
comment !/home/rjslater/anaconda3/bin/python
if __name__ == string __main__
begin
with open string /proc/cpuinfo string r as cpuInfoFile
begin
set cpuInfo = read lines cpuInfoFile
set coreSpeeds = list
for line in cpuInfo
begin
if string MHz in line
begin
append coreSpeeds round integer decimal strip line at slice fin... | #!/home/rjslater/anaconda3/bin/python
if __name__ == '__main__':
with open('/proc/cpuinfo', 'r') as cpuInfoFile:
cpuInfo = cpuInfoFile.readlines()
coreSpeeds = []
for line in cpuInfo:
if 'MHz' in line:
coreSpeeds.append(round(int(float(line[line.find(':') + 1:].... | Python | zaydzuhri_stack_edu_python |
function join_url base_url url
begin
if base_url
begin
return url join base_url url
end
return url
end function | def join_url(base_url, url):
if base_url:
return urlparse.urljoin(base_url, url)
return url | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.