code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function binarySearch s target
begin
set tuple start end = tuple 0 length s - 1
while start + 1 < end
begin
set mid = integer start + end - start / 2
comment print(mid)
if s at mid == target
begin
return mid
end
else
if s at mid < target
begin
set start = mid
end
else
begin
set end = mid
end
end
return if expression ab... | def binarySearch(s, target):
start, end = 0, len(s)-1
while(start + 1 < end):
mid = int(start + (end - start)/2)
# print(mid)
if s[mid] == target:
return mid
elif s[mid] < target:
start = mid
else:
end = mid
return start if abs(s[... | Python | zaydzuhri_stack_edu_python |
function square x
begin
set x = x * x
return x
end function
set num = list
set num = list filter square range 1 11
set sum = 0
for i in num
begin
set sum = sum + i
end
print string sum of squares from 1-10= sum | def square(x):
x*=x
return x
num=[]
num=list(filter(square,range(1,11)))
sum=0
for i in num:
sum+=i
print("sum of squares from 1-10=",sum)
| Python | zaydzuhri_stack_edu_python |
if operation == 1
begin
set sum = number_1 + number_2
print sum
end
else
if operation == 2
begin
set sub = number_1 - number_2
print sub
end
else
if operation == 3
begin
set mul = number_1 * number_2
print mul
end
else
if operation == 4
begin
set div = number_1 / number_2
print div
end | if operation == 1:
sum = number_1 + number_2
print(sum)
elif operation == 2:
sub = number_1 - number_2
print(sub)
elif operation == 3:
mul = number_1 * number_2
print(mul)
elif operation == 4:
div = number_1 / number_2
print(div)
| Python | zaydzuhri_stack_edu_python |
comment 元组 不可变
set t = tuple string 你好 string 我好 string 大家好
print t at 1
print t at slice 1 : :
print t at slice : 2 :
comment 不可变
comment t[1] = '呵呵' | # 元组 不可变
t = ('你好', '我好', '大家好')
print(t[1])
print(t[1:])
print(t[:2])
# 不可变
# t[1] = '呵呵' | Python | zaydzuhri_stack_edu_python |
function main
begin
call main
comment Connect to the sparkify key space.
set tuple cluster session = call connect_keyspace string sparkify
call process_csv session
call shutdown
call shutdown
end function | def main():
gfcsv.main()
#Connect to the sparkify key space.
cluster,session=connect_keyspace('sparkify')
process_csv(session)
session.shutdown()
cluster.shutdown() | Python | nomic_cornstack_python_v1 |
string "EX 4
comment 1:
print string 1:
import random
function alea n
begin
return random integer 1 n
end function
while true
begin
print call alea 5
end | """"EX 4"""
#1:
print("1:")
import random
def alea(n):
return random.randint(1,n)
while True:
print(alea(5))
| Python | zaydzuhri_stack_edu_python |
function test_handle_synapse_http_error__logged_in self
begin
set syn = call Synapse skip_checks=true
set credentials = call Mock
for status_code in tuple 401 403 404
begin
set response = call Mock status_code=status_code headers=dict
with raises SynapseHTTPError as cm_ex
begin
call _handle_synapse_http_error response
... | def test_handle_synapse_http_error__logged_in(self):
syn = Synapse(skip_checks=True)
syn.credentials = Mock()
for status_code in (401, 403, 404):
response = Mock(status_code=status_code, headers={})
with pytest.raises(SynapseHTTPError) as cm_ex:
syn._hand... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import time , sys , serial
comment configure the serial connections (the parameters differs on the device you are connecting to)
set ser = call Serial port=string /dev/tty.usbserial baudrate=2400 parity=PARITY_NONE stopbits=STOPBITS_ONE bytesize=EIGHTBITS timeo... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import time,sys,serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/tty.usbserial',
baudrate=2400,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
... | Python | zaydzuhri_stack_edu_python |
function _from_catalog self
begin
if version < 90300
begin
return
end
for trig in call fetch
begin
set enabled = enable_modes at enabled
set by_oid at oid = trig
set self at call key = trig
end
end function | def _from_catalog(self):
if self.dbconn.version < 90300:
return
for trig in self.fetch():
trig.enabled = self.enable_modes[trig.enabled]
self.by_oid[trig.oid] = self[trig.key()] = trig | Python | nomic_cornstack_python_v1 |
from os import system
from json import dump , load
from datetime import datetime
function print_menu
begin
call system string cls
print string Aplikasi Tiket Bioskop Sederhana [1]. Lihat Semua Tiket [2]. Tambah Tiket Baru [3]. Cari Tiket [4]. Hapus Tiket [5]. Update Tiket [6]. Tentang Aplikasi [Q]. Keluar
end function
... | from os import system
from json import dump, load
from datetime import datetime
def print_menu():
system("cls")
print("""
Aplikasi Tiket Bioskop Sederhana
[1]. Lihat Semua Tiket
[2]. Tambah Tiket Baru
[3]. Cari Tiket
[4]. Hapus Tiket
[5]. Update Tiket
[6]. Tentang Aplikasi
[Q]. Keluar
""")
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment coding: utf-8
import time
import os
call system string clear
sleep 2
set J1 = call raw_input string J1 Introduce: piedra, papel o tijera:
set J2 = call raw_input string J2 Introduce: piedra, papel o tijera:
print
print | #!/usr/bin/python
# coding: utf-8
import time
import os
os.system ('clear')
time.sleep (2)
J1 = raw_input("J1 Introduce: piedra, papel o tijera: ")
J2 = raw_input("J2 Introduce: piedra, papel o tijera: ")
print
print | Python | zaydzuhri_stack_edu_python |
function read self l
begin
while l > length buf
begin
set buf = buf + call recv 4096
end
set obuf = buf
set buf = obuf at slice l : :
return obuf at slice : l :
end function | def read(self, l):
while l > len(self.buf):
self.buf += self.conn.recv(4096)
obuf = self.buf
self.buf = obuf[l:]
return obuf[:l] | Python | nomic_cornstack_python_v1 |
if 5 == 5
begin
print string hey
end
else
if 5 != 6
begin
print string hey colin
end
string hello this is a comment
set name = input string enter your name:
print name
comment def myfunc():
comment global x
comment x = 300
comment myfunc()
comment print(x) | if (5 == 5):
print('hey')
elif (5 != 6):
print('hey colin')
'''hello this is a comment'''
name = input("enter your name: ")
print(name)
# def myfunc():
# global x
# x = 300
# myfunc()
# print(x) | Python | zaydzuhri_stack_edu_python |
function clear_map self
begin
delete string all
call draw_map
set car = call build_car car_pos 12
end function | def clear_map(self):
self.canvas.delete("all")
self.draw_map()
self.car = self.build_car(self.car_pos, 12) | Python | nomic_cornstack_python_v1 |
function solution n
begin
set battery = 0
while n > 1
begin
comment 짝수이면
if n % 2 == 0
begin
set n = n // 2
end
else
begin
set n = n - 1
set battery = battery + 1
set n = n // 2
end
end
return battery + 1
end function
set n = 5
print call solution n | def solution(n):
battery = 0
while(n > 1):
if(n % 2 == 0): # 짝수이면
n = n//2
else:
n -= 1
battery += 1
n = n//2
return battery+1
n = 5
print(solution(n)) | Python | zaydzuhri_stack_edu_python |
comment latihan 1
comment huruf = 'abcdefghijklmnopqrstu'
comment y = input('masukan kata: ').lower()
comment list_huruf = [i for i in huruf]
comment rumus = list_huruf[2:]+list_huruf[:2]
comment # print(rumus)
comment output = ''
comment for i in y :
comment if i == ' ':
comment output += ' '
comment elif i in huruf:
... | #latihan 1
# huruf = 'abcdefghijklmnopqrstu'
# y = input('masukan kata: ').lower()
# list_huruf = [i for i in huruf]
# rumus = list_huruf[2:]+list_huruf[:2]
# # print(rumus)
# output = ''
# for i in y :
# if i == ' ':
# output += ' '
# elif i in huruf:
# output += rumus[list_huru... | Python | zaydzuhri_stack_edu_python |
function getPrecipitation self rutaNC
begin
set dataset = call Dataset rutaNC
comment print("leyendo el netcdf\n imprimiendo el metadato")
print file_format
print keys dimensions
comment print(dataset.dimensions['T'])
comment print(dataset.variables.keys())
comment print(dataset.variables['precipitation'])
comment prin... | def getPrecipitation(self, rutaNC):
dataset = Dataset(rutaNC)
# print("leyendo el netcdf\n imprimiendo el metadato")
print(dataset.file_format)
print(dataset.dimensions.keys())
# print(dataset.dimensions['T'])
# print(dataset.variables.keys())
# print(dataset.vari... | Python | nomic_cornstack_python_v1 |
from heapq import heappop , heappush
from bisect import bisect_left
function solve t n_list lr_list_list
begin
set res = list
for tuple n lr_list in zip n_list lr_list_list
begin
set h = list
set l_values_s = list sorted list comprehension lr at 0 for lr in lr_list
set right_dict = dictionary
for tuple l r in lr_list... | from heapq import heappop, heappush
from bisect import bisect_left
def solve(t, n_list, lr_list_list):
res = []
for n, lr_list in zip(n_list, lr_list_list):
h = []
l_values_s = list(sorted([lr[0] for lr in lr_list]))
right_dict = dict()
for l, r in lr_list:
if l n... | Python | zaydzuhri_stack_edu_python |
function __setstate__ self state
begin
if call issparse state at string transition_matrix
begin
set state at string transition_matrix = call toarray
end
comment Recalculate the cumulative probabilities
set state at string cumulative_probabilities = cumulative sum np state at string transition_matrix axis=1
set __dict__... | def __setstate__(self, state):
if sparse.issparse(state['transition_matrix']):
state['transition_matrix'] = state['transition_matrix'].toarray()
# Recalculate the cumulative probabilities
state['cumulative_probabilities'] = np.cumsum(state['transition_matrix'], axis=1)
sel... | Python | nomic_cornstack_python_v1 |
import sys
function deldup x
begin
set r = x at 0
end function | import sys
def deldup(x):
r = x[0] | Python | zaydzuhri_stack_edu_python |
import tkinter
import win32gui
import win32con
import re
from controlpanel import AppControlPanel
set UPDATE_INTERVAL = 5000
class App
begin
function __init__ self
begin
set root = call Tk string now playing
call string wm string attributes string . string -topmost string 1
call overrideredirect true
call geometry stri... | import tkinter
import win32gui
import win32con
import re
from controlpanel import AppControlPanel
UPDATE_INTERVAL = 5000
class App():
def __init__(self):
self.root = tkinter.Tk('now playing')
self.root.call('wm', 'attributes', '.', '-topmost', '1')
self.root.overrideredirect(True)
... | Python | zaydzuhri_stack_edu_python |
function test_routing_url_rewriting_policy_path api_client
begin
set response = get call api_client string /
assert status_code == 200
set echoed_request = call create response
assert path == string /
end function | def test_routing_url_rewriting_policy_path(api_client):
response = api_client().get("/")
assert response.status_code == 200
echoed_request = EchoedRequest.create(response)
assert echoed_request.path == "/" | Python | nomic_cornstack_python_v1 |
function start_Exec self ast_exec
begin
set violation_found = false
if call get_type == string Exec
begin
set violation_found = true
end
if violation_found
begin
call add_violation string CAST_Python_Rule.avoidUsingExec ast_exec
end
end function | def start_Exec(self, ast_exec):
violation_found = False
if ast_exec.get_type() == "Exec":
violation_found = True
if violation_found :
self.get_current_symbol().add_violation('CAST_Python_Rule.avoidUsingExec', ast_exec) | Python | nomic_cornstack_python_v1 |
function world_map
begin
comment AJAX CALL FOR USER STATE VISIT
comment get current user from session
set user_id = session at string user_id
end function | def world_map():
# AJAX CALL FOR USER STATE VISIT
# get current user from session
user_id = session["user_id"] | Python | nomic_cornstack_python_v1 |
function init_hidden self hidden_dim
begin
comment num_layers * num_directions, batch, hidden_dim
set bidirectional_mult = if expression bidirectional then 2 else 1
comment hidden state and cell state
if gpu_enabled
begin
return tuple cuda call Variable zeros 1 * bidirectional_mult batch_size hidden_dim cuda call Varia... | def init_hidden(self, hidden_dim):
# num_layers * num_directions, batch, hidden_dim
bidirectional_mult = 2 if self.bidirectional else 1
# hidden state and cell state
if self.gpu_enabled:
return (autograd.Variable(torch.zeros(1 * bidirectional_mult, self.batch_size, hidden_dim... | Python | nomic_cornstack_python_v1 |
string Slicing time series Slicing is particularly useful for time series, since it's a common thing to want to filter for data within a date range. Add the date column to the index, then use .loc[] to perform the subsetting. The important thing to remember is to keep your dates in ISO 8601 format, that is, yyyy-mm-dd.... | '''
Slicing time series
Slicing is particularly useful for time series, since it's a common thing to want to filter for data within a date range. Add the date column to the index, then use .loc[] to perform the subsetting. The important thing to remember is to keep your dates in ISO 8601 format, that is, yyyy-mm-dd.
R... | Python | zaydzuhri_stack_edu_python |
function refine_peaks self xs ys
begin
set im = im
comment force size ODD
set size = if expression lsize % 2 == 1 then lsize else lsize + 1
set size = size + 2
set r = size + 1 / 2
comment get "nearby" mask
set tuple i j = ogrid at tuple slice - r + 1 : r : slice - r + 1 : r :
set dist = square root i ^ 2 + j ^ 2
set... | def refine_peaks (self, xs, ys):
im = self.im
# force size ODD
size = self.lsize if self.lsize % 2 == 1 else self.lsize + 1
size += 2
r = (size + 1) / 2
# get "nearby" mask
i, j = np.ogrid[-r+1:r, -r+1:r]
dist = np.sqrt (i**2 + j**2)
mask = dist < ... | Python | nomic_cornstack_python_v1 |
function _fluorescence_to_concentration fluorescence standards_col standards output_folder=string . r_minimum=R_MINIMUM inner=true
begin
set standards = call Series standards index=index
set means = mean group by fluorescence at standards_col standards
comment Don't use the very first or very last concentrations for re... | def _fluorescence_to_concentration(fluorescence, standards_col, standards,
output_folder='.', r_minimum=R_MINIMUM,
inner=True):
standards = pd.Series(standards, index=fluorescence.index)
means = fluorescence[standards_col].groupby(standards)... | Python | nomic_cornstack_python_v1 |
function alternative_colors N corners
begin
set r1 = array list 1 0 0
set r2 = array list 0 1 0
set r3 = array list 0 0 1
set r = array list r1 r2 r3
set colors = zeros tuple N 3
set colors at 0 = array list 0 0 0
set points = zeros tuple N 2
for i in range 1 N - 1
begin
set j = random integer 3
set colors at i + 1 = c... | def alternative_colors(N, corners):
r1 = np.array([1, 0, 0])
r2 = np.array([0, 1, 0])
r3 = np.array([0, 0, 1])
r = np.array([r1, r2, r3])
colors = np.zeros((N, 3))
colors[0] = np.array([0, 0, 0])
points = np.zeros((N, 2))
for i in range(1, N - 1):
j = np.random.randint(3)
... | Python | nomic_cornstack_python_v1 |
function self_link self
begin
return get pulumi self string self_link
end function | def self_link(self) -> pulumi.Output[str]:
return pulumi.get(self, "self_link") | Python | nomic_cornstack_python_v1 |
function multiline_print lists
begin
set combined_list = list
set combined_list = combined_list + lists at 0
comment We prepend newline characters to strings at the start of lines to avoid
comment the ugly space intendations that tf.print's behavior of separating
comment everything with a space would otherwise cause.
... | def multiline_print(lists):
combined_list = []
combined_list += lists[0]
# We prepend newline characters to strings at the start of lines to avoid
# the ugly space intendations that tf.print's behavior of separating
# everything with a space would otherwise cause.
for item in lists[1:]:
if isinstance(... | Python | nomic_cornstack_python_v1 |
function plot_best_scores all_scores thresholds epochs model_name output_dir if_save=false
begin
comment find the best score per epoch
set best_scores = max all_scores axis=1
print best_scores
figure figsize=tuple 10 8
plot epochs best_scores string o--k label=model_name
x label string Epochs fontsize=20
y label string... | def plot_best_scores(all_scores: np.ndarray, thresholds: np.ndarray, epochs: np.ndarray, model_name: str, output_dir: str, if_save: bool=False) -> None:
# find the best score per epoch
best_scores = np.max(all_scores, axis=1)
print(best_scores)
plt.figure(figsize=(10, 8))
plt.plot(epochs, best_score... | Python | nomic_cornstack_python_v1 |
function error_correct_scratch_size self
begin
return encode_scratch_size
end function | def error_correct_scratch_size(self) -> int:
return self.encode_scratch_size | Python | nomic_cornstack_python_v1 |
import wx
from wx.lib.pubsub import pub
import csv
import shutil
from tempfile import NamedTemporaryFile
import numpy as np
import random
import cv2
import os
class ViewerPanel extends Panel
begin
string
comment ----------------------------------------------------------------------
function __init__ self parent
begin
... | import wx
from wx.lib.pubsub import pub
import csv
import shutil
from tempfile import NamedTemporaryFile
import numpy as np
import random
import cv2
import os
########################################################################
class ViewerPanel(wx.Panel):
""""""
#-----------------------------------------... | Python | zaydzuhri_stack_edu_python |
import dhash
from PIL import Image
function compute_hashes files
begin
comment compute hash for the images
set hashes = list
for tuple index file in enumerate files
begin
try
begin
set image = open file
set tuple row col = call dhash_row_col image
set img_hash = call format_hex row col
append hashes img_hash
end
excep... | import dhash
from PIL import Image
def compute_hashes(files):
# compute hash for the images
hashes = []
for index, file in enumerate(files):
try:
image = Image.open(file)
row, col = dhash.dhash_row_col(image)
img_hash = dhash.format_hex(row, col)
has... | Python | zaydzuhri_stack_edu_python |
function send_org_invitation org_mem
begin
set user = user
set url = format string {domain}{url}?c={org_uid} domain=FEEDVAY_DOMAIN url=reverse string console_org_home org_uid=org_uid
comment Create message body
set message_body = content
comment Create database entry
set email_msg = call create username=username email_... | def send_org_invitation(org_mem):
user = org_mem.registered_user.user
url = "{domain}{url}?c={org_uid}".format(
domain = settings.FEEDVAY_DOMAIN,
url = reverse('console_org_home'),
org_uid = org_mem.organization.org_uid
)
# Create message body
... | Python | nomic_cornstack_python_v1 |
function get_pixel_format self
begin
return call PixelFormat pixelFormat
end function | def get_pixel_format(self) -> PixelFormat:
return PixelFormat(self._frame.pixelFormat) | Python | nomic_cornstack_python_v1 |
function get_name ticker_symbol page=none
begin
if page is none
begin
set page = call scrape_page BASE_URL + ticker_symbol
end
set sentiment = call xpath FULL_NAME_XPATH
if not sentiment
begin
return none
end
else
begin
return replace sentiment at 0 string string
end
end function | def get_name(ticker_symbol, page=None):
if page is None:
page = scrape_page(BASE_URL + ticker_symbol)
sentiment = page.xpath(FULL_NAME_XPATH)
if not sentiment:
return None
else:
return sentiment[0].replace("\n", "") | Python | nomic_cornstack_python_v1 |
function update_signal_processing_parameters self **kwargs
begin
for tuple key value in items kwargs
begin
if key in __dict__
begin
set __dict__ at key = value
end
end
end function | def update_signal_processing_parameters(self, **kwargs):
for key, value in kwargs.items():
if key in self.__dict__:
self.__dict__[key] = value | Python | nomic_cornstack_python_v1 |
set name = string input string enter the name
print
set i = string input string Print Yes to start
if i == string Yes
begin
print string Let's start
set answ = input string 1.Who is father of our nation?
if answ == string gandhi
begin
print string Good keep going
end
else
begin
print string No wrong answer
end
set ans ... | name=str(input("enter the name"))
print()
i=str(input("Print Yes to start"))
if(i=='Yes'):
print("Let's start")
answ=input("1.Who is father of our nation?")
if(answ=='gandhi'):
print("Good keep going")
else:
print("No wrong answer")
ans=input("2.What is our national game?")
if(ans=='... | Python | zaydzuhri_stack_edu_python |
function Keldysh_Rate Uion Z E
begin
set ans = square root 6.0 * pi / 4.0
set ans = ans * Uion * square root E / Uion ^ 1.5
set ans = ans * exp - 4.0 / 3.0 * square root 2.0 * Uion ^ 1.5 / E
return ans
end function | def Keldysh_Rate(Uion,Z,E):
ans = np.sqrt(6.0*np.pi)/4.0
ans *= Uion * np.sqrt(E/(Uion**1.5))
ans *= np.exp(-(4.0/3.0)*np.sqrt(2.0)*(Uion**1.5)/E)
return ans | Python | nomic_cornstack_python_v1 |
function get_helm_application_namespaces self context app_name
begin
return call get_helm_application_namespaces app_name
end function | def get_helm_application_namespaces(self, context, app_name):
return self._helm.get_helm_application_namespaces(app_name) | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment ---------------------------------------------------------------------
string Neural Machine Translation - Encoder Decoder model Chainer implementation of an encoder-decoder sequence to sequence model using bi-directional LSTM encoder
comment ------------------------------------------------... | # coding: utf-8
# ---------------------------------------------------------------------
'''
Neural Machine Translation - Encoder Decoder model
Chainer implementation of an encoder-decoder sequence to sequence
model using bi-directional LSTM encoder
'''
# ---------------------------------------------------------... | Python | zaydzuhri_stack_edu_python |
function fibonacci n
begin
if n < 0
begin
return - 1
end
else
if n == 0
begin
return 0
end
else
if n == 1
begin
return 1
end
else
begin
return call fibonacci n - 1 + call fibonacci n - 2
end
end function | def fibonacci(n):
if n < 0:
return -1
elif n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
| Python | jtatman_500k |
string python中的常用模块
import sys
import time
import urllib.request
comment 判断字节
print call getsizeof 28
print time
print call localtime time
print read url open string http://www.baidu.com | '''python中的常用模块'''
import sys
import time
import urllib.request
print((sys.getsizeof(28))) #判断字节
print(time.time())
print(time.localtime(time.time()))
print(urllib.request.urlopen('http://www.baidu.com').read()) | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import nltk as nltk
comment from nltk import RegexpTokenizer
comment from nltk import TweetTokenizer
from nltk import tokenize
import os
import numpy as np
import re
import string
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.stem import Word... | import pandas as pd
import nltk as nltk
#from nltk import RegexpTokenizer
#from nltk import TweetTokenizer
from nltk import tokenize
import os
import numpy as np
import re
import string
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
from nltk.stem import WordNetLemmatize... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3.8
from flask import Flask , request
set app = call Flask __name__
set config at string DEBUG = true
decorator call route string / methods=list string GET string POST
function adder_page
begin
set errors = string
if method == string POST
begin
set d = none
set e = none
set f = none
set g = non... | #!/usr/bin/python3.8
from flask import Flask, request
app = Flask(__name__)
app.config["DEBUG"] = True
@app.route("/", methods=["GET", "POST"])
def adder_page():
errors = ""
if request.method == "POST":
d = None
e = None
f = None
g = None
b = None
h = None
... | Python | zaydzuhri_stack_edu_python |
function generate_product_state psi_i L
begin
if L == 0
begin
return none
end
set psi = array list 1.0
for i in range L
begin
set psi = call kron psi psi_i
end
return psi
end function | def generate_product_state(psi_i, L):
if L == 0:
return None
psi = np.array([1.0])
for i in range(L):
psi = np.kron(psi, psi_i)
return psi | Python | nomic_cornstack_python_v1 |
function _account_info remote resp
begin
set oauth_logged_in_with_remote = remote
set resource = call get_resource remote resp
set valid_roles = get config string OAUTHCLIENT_CERN_OPENID_ALLOWED_ROLES OAUTHCLIENT_CERN_OPENID_ALLOWED_ROLES
set cern_roles = get resource string cern_roles
if cern_roles is none or not call... | def _account_info(remote, resp):
g.oauth_logged_in_with_remote = remote
resource = get_resource(remote, resp)
valid_roles = current_app.config.get(
"OAUTHCLIENT_CERN_OPENID_ALLOWED_ROLES",
OAUTHCLIENT_CERN_OPENID_ALLOWED_ROLES,
)
cern_roles = resource.get("cern_roles")
if cern_r... | Python | nomic_cornstack_python_v1 |
function print_function
begin
print format string Hello World, this is {0} with HNGi7 ID {1} using {2} and email {3} for stage 2 task full_name id language email
end function
call print_function | def print_function():
print("Hello World, this is {0} with HNGi7 ID {1} using {2} and email {3} for stage 2 task".format(full_name,id,language,email))
print_function() | Python | zaydzuhri_stack_edu_python |
if integer n >= 1
begin
for i in range 1 integer n + 1
begin
set factorial = factorial * i
end
end
print factorial | if int(n) >= 1:
for i in range (1,int(n)+1):
factorial = factorial * i
print(factorial) | Python | zaydzuhri_stack_edu_python |
function func
begin
set r = integer call raw_input
set ans = list 0 * 17
for i in range 4
begin
set a = map int split call raw_input string
if i == r - 1
begin
for x in a
begin
set ans at x = 1
end
end
end
return ans
end function
set T = integer call raw_input
for t in range T
begin
set a = call func
set b = call func
... | def func():
r = int(raw_input())
ans = [0] * 17
for i in range(4):
a = map(int, raw_input().split(' '))
if i == r-1:
for x in a:
ans[x] = 1
return ans
T = int(raw_input())
for t in range(T):
a = func()
b = func()
cnt = 0
ans = 0
for i in range(1, 17):
if a[i] == 1 and b[i] == 1:
cnt += ... | Python | zaydzuhri_stack_edu_python |
comment Implementation of the npde class which is a basic building block of the linked list
class Node
begin
function __init__ self init_data index
begin
set _data = init_data
set _next = none
set _index = index
end function
decorator property
function index self
begin
return _index
end function
decorator setter
functi... | # Implementation of the npde class which is a basic building block of the linked list
class Node:
def __init__(self, init_data, index):
self._data = init_data
self._next = None
self._index = index
@property
def index(self):
return self._index
@index.setter
def inde... | Python | zaydzuhri_stack_edu_python |
comment Deleting Tuple
set a = tuple 10 20 - 50 21.3 string GeekyShows
print a
print
comment Not Possible to delete one element like below line
comment del a[1] # Show TypeError
comment We can delete entire tuple
comment del a
comment print(a) # after deleting entire tuple a become undefined
comment It is not possible ... | # Deleting Tuple
a = (10, 20, -50, 21.3, 'GeekyShows')
print(a)
print()
# Not Possible to delete one element like below line
#del a[1] # Show TypeError
# We can delete entire tuple
#del a
#print(a) # after deleting entire tuple a become undefined
# It is not possible to delete one element but we can concate or ... | Python | zaydzuhri_stack_edu_python |
function showAllRecords self
begin
set olvResults = call getAllRecords
call setRows
end function | def showAllRecords(self):
self.olvResults = self.controller.getAllRecords()
self.setRows() | Python | nomic_cornstack_python_v1 |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import preprocessing
import pickle
set data = read csv string car.data
print head data
comment precprocesssing to convert non numeric data numeric retuns numpy array
set le = call Lab... | import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn import preprocessing
import pickle
data = pd.read_csv("car.data")
print(data.head())
#precprocesssing to convert non numeric data numeric retuns numpy array
le = preprocessi... | Python | zaydzuhri_stack_edu_python |
function isFromReferencedFile self
begin
pass
end function | def isFromReferencedFile(self):
pass | Python | nomic_cornstack_python_v1 |
while num <= 20
begin
print num
set num = num + 1
end | while num <= 20:
print(num)
num += 1 | Python | zaydzuhri_stack_edu_python |
import numpy as np
function net *args
begin
comment print(args)
comment print(type(args))
set weight = list list 1 2
set bias = 0
set lst1 = list
set lst2 = list
set lst3 = list
for i in args
begin
append lst1 list i at 0
append lst2 list i at 1
end
comment print(lst1)
for i in range length lst1
begin
set temp = lis... | import numpy as np
def net(*args):
#print(args)
#print(type(args))
weight = [[1,2]]
bias= 0
lst1 = []
lst2 = []
lst3 = []
for i in args:
lst1.append([i[0]])
lst2.append([i[1]])
#print(lst1)
for i in range(len(lst1)):
temp =[]
if i==0:
... | Python | zaydzuhri_stack_edu_python |
import os
import cv2
import numpy as np
from glob import glob
from joblib import dump , load
from collections import Counter
from sklearn.cluster import KMeans
from utils.visualize import visualize_histograms , visualize_keypoints
function load_images
begin
set dataset = dict string train_img dict ; string test_img di... | import os
import cv2
import numpy as np
from glob import glob
from joblib import dump, load
from collections import Counter
from sklearn.cluster import KMeans
from utils.visualize import visualize_histograms, visualize_keypoints
def load_images():
dataset = {'train_img': {}, 'test_img': {}}
classes = os.lis... | Python | zaydzuhri_stack_edu_python |
function validation_format rdd_file_in_textfile
begin
set word_tokenize_rdd = map lambda x -> tuple x at 0 call tokenize_words x at 1
set words_rdd = map lambda x -> tuple x at 0 x at 1
set clean_word_rdd = filter lambda x -> length x at 1 > 1 and x at 1 not in value
set rdd_docid_word = call sortByKey
return rdd_docid... | def validation_format(rdd_file_in_textfile):
word_tokenize_rdd = rdd_file_in_textfile.map(lambda x: (x[0], tokenize_words(x[1])))
words_rdd = word_tokenize_rdd.flatMapValues(lambda x: x).map(lambda x: (x[0], x[1]))
clean_word_rdd = words_rdd.map(lambda x: (x[0], cleanup_word(x[1]))).filter(lambda x: len(x[1... | Python | nomic_cornstack_python_v1 |
function find_if_robot_in_circle instr
begin
set dirs = list tuple 0 1 tuple 1 0 tuple 0 - 1 tuple - 1 0
set cd = 0
set tuple x y = tuple 0 0
for ad in instr
begin
if ad == string G
begin
set x = x + dirs at cd at 0
set y = y + dirs at cd at 1
end
else
if ad == string R
begin
set cd = cd + 1 % 4
end
else
if ad == strin... | def find_if_robot_in_circle(instr):
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
cd = 0
x, y = 0, 0
for ad in instr:
if ad == "G":
x += dirs[cd][0]
y += dirs[cd][1]
elif ad == "R":
cd = (cd + 1) % 4
elif ad == "L":
cd = (cd + 3) % 4
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Thu May 30 15:30:34 2019 @author: NITS
import pandas as pd
import numpy as np
set dataset = read csv string Auto_mpg.txt delimiter=string \s+ header=none
comment dataset1 = pd.read_csv("Auto_mpg.txt",delim_whitespace=True)
set columns = list string mpg string cylinders st... | # -*- coding: utf-8 -*-
"""
Created on Thu May 30 15:30:34 2019
@author: NITS
"""
import pandas as pd
import numpy as np
dataset = pd.read_csv("Auto_mpg.txt",delimiter = "\s+",header = None)
#dataset1 = pd.read_csv("Auto_mpg.txt",delim_whitespace=True)
dataset.columns = ["mpg", "cylinders", "displacement","horsepowe... | Python | zaydzuhri_stack_edu_python |
function _fill_spc self spc_id spc_name model nid_to_pid_map
begin
set spc_names = list spc_name
call create_alternate_vtk_grid spc_name color=PURPLE_FLOAT line_width=5 opacity=1.0 point_size=5 representation=string point is_visible=false
comment node_ids = model.get_SPCx_node_ids(spc_id)
set node_ids_c1 = call get_SPC... | def _fill_spc(self, spc_id, spc_name, model, nid_to_pid_map):
spc_names = [spc_name]
self.gui.create_alternate_vtk_grid(
spc_name, color=PURPLE_FLOAT, line_width=5, opacity=1.,
point_size=5, representation='point', is_visible=False)
# node_ids = model.get_SPCx_node_ids(s... | Python | nomic_cornstack_python_v1 |
class TrieNode
begin
function __init__ self
begin
set children = dict
set leaf = false
end function
end class
class Trie
begin
function __init__ self
begin
set root = call TrieNode
print string Create Trie
end function
function insert self word
begin
set curr = root
for tuple i ch in enumerate word
begin
if not ch in ... | class TrieNode:
def __init__(self):
self.children = {}
self.leaf = False
class Trie:
def __init__(self):
self.root = TrieNode()
print("Create Trie")
def insert(self, word):
curr = self.root
for i, ch in enumerate(word):
if not ch in curr.children... | Python | zaydzuhri_stack_edu_python |
function login_prompt request
begin
set template = string checkout/login_prompt.html
set context = dict string page_header string Checkout Options
return call render request template context
end function | def login_prompt(request):
template = 'checkout/login_prompt.html'
context = {
'page_header': 'Checkout Options',
}
return render(request, template, context) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
set query = string Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics.
function count_alphabet input_str
begin
return list comprehension length right strip word string ,. for word in split strip input_str string
end fu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
query = "Now I need a drink, alcoholic of course, after the heavy lectures involving quantum mechanics."
def count_alphabet(input_str):
return [len(word.rstrip(',.')) for word in input_str.strip().split(' ')]
| Python | zaydzuhri_stack_edu_python |
function __exit__ self type value traceback
begin
call free
end function | def __exit__(self, type, value, traceback):
self.free() | Python | nomic_cornstack_python_v1 |
function read self relpath rsc=none mode=string r useFilepath=none
begin
string Reads the contents for a given relative filepath. This will call the load function and do a full read on the file contents. :param relpath | <str> rsc | <str> || None mode | <str> | 'r' or 'rb' :return <str>
set f = load self relpath rsc mo... | def read(self, relpath, rsc=None, mode='r', useFilepath=None):
"""
Reads the contents for a given relative filepath. This will call
the load function and do a full read on the file contents.
:param relpath | <str>
rsc | <str> || None
... | Python | jtatman_500k |
function get_num_piezas self pieza
begin
set num_piezas = 0
for i in range filas
begin
for j in range columnas
begin
if call get_color == pieza
begin
set num_piezas = num_piezas + 1
end
end
end
return num_piezas
end function | def get_num_piezas(self, pieza):
num_piezas=0
for i in range(self.filas):
for j in range(self.columnas):
if self.board[i][j].get_color() == pieza:
num_piezas+=1
return num_piezas | Python | nomic_cornstack_python_v1 |
import numpy
import urllib
import scipy.optimize
import random
import math
comment MSE
from sklearn.metrics import mean_squared_error
function parseData fname
begin
for l in url open fname
begin
yield eval l
end
end function | import numpy
import urllib
import scipy.optimize
import random
import math
#MSE
from sklearn.metrics import mean_squared_error
def parseData(fname):
for l in urllib.urlopen(fname):
yield eval(l)
| Python | zaydzuhri_stack_edu_python |
class Solution
begin
function change self amount coins
begin
set size_a = amount
set size_c = length coins
set dp = list comprehension list comprehension 0 for i in range size_a + 1 for j in range size_c + 1
for i in range size_c + 1
begin
set dp at i at 0 = 1
end
for i in range 1 size_c + 1
begin
for j in range 1 size... | class Solution:
def change(self, amount: int, coins: List[int]) -> int:
size_a = amount
size_c = len(coins)
dp = [[0 for i in range(size_a+1)] for j in range(size_c+1)]
for i in range(size_c+1):
dp[i][0] = 1
for i in range(1, size_c+1):
for j in ran... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment In[1]:
from roadsimulator.simulator import Simulator
comment In[2]:
import os
import numpy as np
from tqdm import tqdm
from scipy.misc import imread
comment In[3]:
set simulator = call Simulator
comment Simulator class
comment In[4]:
from roadsimulator.colors import White , DarkShadow
from... | # coding: utf-8
# In[1]:
from roadsimulator.simulator import Simulator
# In[2]:
import os
import numpy as np
from tqdm import tqdm
from scipy.misc import imread
# In[3]:
simulator = Simulator()
#Simulator class
# In[4]:
from roadsimulator.colors import White, DarkShadow
from roadsimulator.layers.layers ... | Python | zaydzuhri_stack_edu_python |
function intersects self x
begin
set r1 = call Rect x
if isEmpty or isInfinite or isEmpty or isInfinite
begin
return false
end
set r = call Rect self
if isEmpty
begin
return false
end
return true
end function | def intersects(self, x):
r1 = Rect(x)
if self.isEmpty or self.isInfinite or r1.isEmpty or r1.isInfinite:
return False
r = Rect(self)
if r.intersect(r1).isEmpty:
return False
return True | Python | nomic_cornstack_python_v1 |
function gateways self
begin
return get pulumi self string gateways
end function | def gateways(self) -> Optional[Sequence[str]]:
return pulumi.get(self, "gateways") | Python | nomic_cornstack_python_v1 |
function bmc_equiv circ1 circ2 horizon assume=none
begin
comment Create distinguishing predicate.
set expr = call uatom 1 val=0
for o1 in outputs
begin
set o2 = string { o1 } ##copy
set size = size
set expr = expr ? call uatom size o1 != call uatom size o2
end
call with_output string distinguished
set monitor = aig
ass... | def bmc_equiv(circ1, circ2, horizon, assume=None) -> Iterator[bool]:
# Create distinguishing predicate.
expr = BV.uatom(1, val=0)
for o1 in circ1.outputs:
o2 = f'{o1}##copy'
size = circ1.omap[o1].size
expr |= BV.uatom(size, o1) != BV.uatom(size, o2)
expr.with_output('distinguishe... | Python | nomic_cornstack_python_v1 |
from math_two import calc
set flag = true
print string введите действие: + -сложение, - -вычитание, / -деление, * -умножние, ^ -возведение в степень, module -модуль, random -случайное число, fact -факториал, arccos -arccos, quit -выход из программы
while flag
begin
set com = input
if com == string /
begin
call fun_dele... | from math_two import calc
flag = True
print("введите действие:"
"\n + -сложение,"
"\n - -вычитание,"
"\n / -деление,"
"\n * -умножние,"
"\n ^ -возведение в степень,"
"\n module -модуль,"
"\n random -случайное число,"
"\n fact -факториал,"
"\n arccos -ar... | Python | zaydzuhri_stack_edu_python |
import argparse
import os
import re
import glob
import sys
import itertools
function chop_loaded_log_message line
begin
try
begin
set tuple fromClass fromFile = split strip strip strip split line string [ at 1 string ] string Loaded string from
if string file in fromFile
begin
set fromFile = fromFile at slice 6 : :
e... | import argparse
import os
import re
import glob
import sys
import itertools
def chop_loaded_log_message(line):
try:
fromClass,fromFile = line.split('[')[1].strip(']').strip("Loaded").strip().split("from")
if 'file' in fromFile:
fromFile = fromFile[6:]
return (fromFile.strip(']... | Python | zaydzuhri_stack_edu_python |
function __polynomial_hash self s base=31 max_size=168
begin
set digest = 0
set max_size = 168
for c in s
begin
set digest = base * digest + ordinal c
end
set digest = digest ? 2 ^ max_size - 1
return right strip hexadecimal digest string L
end function | def __polynomial_hash(self, s, base = 31, max_size=168):
digest = 0
max_size = 168
for c in s: digest = base * digest + ord(c)
digest &= 2 ** max_size - 1
return hex(digest).rstrip('L') | Python | nomic_cornstack_python_v1 |
import numpy as np
import tensorflow as tf
class BackpropagationModel
begin
function __init__ self sequenceLength numClasses dimension numHiddenNodes
begin
set x = call placeholder float32 list none sequenceLength * dimension
set yhat = call placeholder float32 list none numClasses
comment Initialize weights
set W1 = c... | import numpy as np
import tensorflow as tf
class BackpropagationModel:
def __init__(self, sequenceLength, numClasses, dimension, numHiddenNodes):
self.x = tf.placeholder(tf.float32, [None, sequenceLength * dimension])
self.yhat = tf.placeholder(tf.float32, [None, numClasses])
# Initialize ... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
import sqlite3
import pymysql
from tkinter.filedialog import askopenfilename
set root = call Tk
set filename = string
call bind string <Escape> lambda e -> call quit
call attributes string -fullscreen true
call configure background=string black
function draw_Schema
begin
set DBtype = get Database... | from tkinter import *
import sqlite3
import pymysql
from tkinter.filedialog import askopenfilename
root = Tk()
filename=""
root.bind('<Escape>', lambda e: root.quit())
root.attributes('-fullscreen', True)
root.configure(background='black')
def draw_Schema():
DBtype = Database_kind.get()
print(DBtype)
if ... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import scipy.sparse
import json
from math import sqrt
from math import isnan
from scipy.stats import pearsonr
set data = read csv string data/n_data.csv
set placeInfo = read csv string data/t_data.csv
with open string data/district_wise_places.json as r
begin
set district_places =... | import numpy as np
import pandas as pd
import scipy.sparse
import json
from math import sqrt
from math import isnan
from scipy.stats import pearsonr
data = pd.read_csv('data/n_data.csv')
placeInfo = pd.read_csv('data/t_data.csv')
with open("data/district_wise_places.json") as r:
district_places = json.loads(r.rea... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import sys
from heapq import *
comment Config. management
function enc_conf H R
begin
return join string | tuple H R at 0 R at 1 R at 2 R at 3
end function
function final_enc c
begin
return ends with c string ||||
end function
function dec_conf S
begin
set tuple H RA RB RC RD = split S str... | #!/usr/bin/env python3
import sys
from heapq import *
# Config. management
def enc_conf(H,R):
return '|'.join((H,R[0],R[1],R[2],R[3]))
def final_enc(c):
return c.endswith('||||')
def dec_conf(S):
H,RA,RB,RC,RD = S.split('|')
return (H,[RA,RB,RC,RD])
def conf_succ(c):
H,R = dec_conf(c)
# mo... | Python | zaydzuhri_stack_edu_python |
function world2pix self lon lat energy combine=false
begin
set lon = value
set lat = value
set tuple x y _ = call wcs_world2pix lon lat 0 0
set z = call world2pix energy
set shape = shape
set x = x * ones shape
set y = y * ones shape
set z = z * ones shape
if combine == true
begin
set x = flat
set y = flat
set z = flat... | def world2pix(self, lon, lat, energy, combine=False):
lon = lon.to('deg').value
lat = lat.to('deg').value
x, y, _ = self.wcs.wcs_world2pix(lon, lat, 0, 0)
z = self.energy_axis.world2pix(energy)
shape = (x * y * z).shape
x = x * np.ones(shape)
y = y * np.ones(sha... | Python | nomic_cornstack_python_v1 |
function debug self
begin
if filename is none
begin
call savefile
end
set proc = communicate popen list exe_path filename string D stdout=PIPE at 0
set output = decode proc string utf-8
if string parse error in output
begin
comment delete quadraples file it's of no use
call list string rm string out.txt
call configure ... | def debug(self):
if self.filename is None:
self.savefile()
proc = subprocess.Popen([self.exe_path, self.filename, "D"], stdout=subprocess.PIPE).communicate()[0]
output = proc.decode("utf-8")
if 'parse error' in output:
subprocess.call(["rm", "out.txt"]) # delete... | Python | nomic_cornstack_python_v1 |
function sample self
begin
set x = state
set dx = theta * mu - x + sigma * call rand *x.shape
set state = x + dx
return state
end function | def sample(self):
x = self.state
dx = self.theta * (self.mu - x) + self.sigma * np.random.rand(*x.shape)
self.state = x + dx
return self.state | Python | nomic_cornstack_python_v1 |
function fibonacci_sequence n
begin
if n == 0
begin
return list
end
else
if n == 1
begin
return list 0
end
else
if n == 2
begin
return list 0 1
end
else
begin
set fib_numbers = list 0 1
for i in range 2 n
begin
append fib_numbers fib_numbers at i - 2 + fib_numbers at i - 1
end
return fib_numbers
end
end function | def fibonacci_sequence(n):
if n == 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib_numbers = [0, 1]
for i in range(2, n):
fib_numbers.append(fib_numbers[i-2] + fib_numbers[i-1])
return fib_numbers
| Python | flytech_python_25k |
comment !/usr/bin/env python3
string Create a function diamond that returns a two dimensional integer array where the 1s form a diamond shape. Rest of the numbers are 0. The function should get a parameter that tells the length of a side of the diamond. Do this using the eye and concatenate functions of NumPy and array... | #!/usr/bin/env python3
'''
Create a function diamond that returns a two dimensional integer array where the 1s form a diamond shape.
Rest of the numbers are 0. The function should get a parameter that tells the length of a side of the diamond.
Do this using the eye and concatenate functions of NumPy and array slicing... | Python | zaydzuhri_stack_edu_python |
function load_index self version_string
begin
string Load the completion index for a given CLI version. :type version_string: str :param version_string: The AWS CLI version, e.g "1.9.2". :raises: :class:`IndexLoadError <exceptions.IndexLoadError>`
set filename = call _filename_for_version version_string
try
begin
set c... | def load_index(self, version_string):
"""Load the completion index for a given CLI version.
:type version_string: str
:param version_string: The AWS CLI version, e.g "1.9.2".
:raises: :class:`IndexLoadError <exceptions.IndexLoadError>`
"""
filename = self._filename_for_... | Python | jtatman_500k |
function eval self text
begin
if trace_client
begin
set request = tuple none EVAL_CODE text
write stderr string %s: < %s % tuple host call short_repr request
end
set value = eval text globals context
if trace_client
begin
set reply = tuple none NORMAL_RETURN value
write stderr string %s: > %s % tuple host call short_re... | def eval(self, text):
if self.trace_client:
request = None, EVAL_CODE, text
sys.stderr.write('%s: < %s\n' % (self.host, short_repr(request)))
value = eval(text, globals(), self.context)
if self.trace_client:
reply = None, NORMAL_RETURN, value
sys.s... | Python | nomic_cornstack_python_v1 |
function parseXML xml_file
begin
set job_ids = list string 7517210 string 7442066 string 00010001
set tree = none
set tree = call ElementTree file=xml_file
end function | def parseXML(xml_file):
job_ids = ['7517210','7442066','00010001']
tree = None
tree = et.ElementTree(file=xml_file) | Python | nomic_cornstack_python_v1 |
string 백준 15552 알람 시계 Prob https://www.acmicpc.net/problem/2884 End Day : 2020. 1. 1
import sys
set N = integer input
for _ in range N
begin
set tuple A B = map int split read line stdin
print A + B
end
string 5 1 1 12 34 5 500 40 60 1000 1000 >> 2 46 505 100 2000 | """
백준 15552 알람 시계
Prob https://www.acmicpc.net/problem/2884
End Day : 2020. 1. 1
"""
import sys
N = int(input())
for _ in range(N):
A, B = map(int, sys.stdin.readline().split())
print(A+B)
"""
5
1 1
12 34
5 500
40 60
1000 1000
>>
2
46
505
100
2000
""" | Python | zaydzuhri_stack_edu_python |
class kDTree
begin
function __init__ self n points
begin
set count = 0
set origin = points
set points = sorted points
set pointNum = list none * n
set l = list none * n
set r = list none * n
call make1DTree 0 n
end function
function make1DTree self l r
begin
if not l < r
begin
return none
end
set mid = l + r // 2
set a... | class kDTree():
def __init__(self,n,points):
self.count=0
self.origin=points
self.points=sorted(points)
self.pointNum=[None]*n
self.l=[None]*n
self.r=[None]*n
self.make1DTree(0,n)
def make1DTree(self,l,r):
if not l<r:
retur... | Python | zaydzuhri_stack_edu_python |
import unittest
from UnitTesting.shorthand import *
import numpy as np
from FDM.source.matrices import *
from scipy.sparse import csr_matrix , identity , lil_matrix
class TestMatrices extends TestCase
begin
function testDxx self
begin
set desiredMatrix = call lil_matrix array list list - 2.0 1.0 0.0 0.0 0.0 0.0 0.0 0.0... | import unittest
from UnitTesting.shorthand import *
import numpy as np
from FDM.source.matrices import *
from scipy.sparse import csr_matrix, identity, lil_matrix
class TestMatrices(unittest.TestCase):
def testDxx(self):
desiredMatrix = lil_matrix(np.array([
[-2., 1., 0., 0., 0., 0., 0., 0., 0.],
... | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ pod_affinity_term weight
begin
set __self__ string pod_affinity_term pod_affinity_term
set __self__ string weight weight
end function | def __init__(__self__, *,
pod_affinity_term: 'outputs.SearchHeadClusterSpecAffinityPodAffinityPreferredDuringSchedulingIgnoredDuringExecutionPodAffinityTerm',
weight: int):
pulumi.set(__self__, "pod_affinity_term", pod_affinity_term)
pulumi.set(__self__, "weight", weigh... | Python | nomic_cornstack_python_v1 |
import requests
import json
class MatchHistory
begin
comment match history uses puuid to search in Riot API
function __init__ self puuid region api_key
begin
set puuid = puuid
if region == string na1
begin
set region = string americas
end
else
if region == string euw1
begin
set region = string europe
end
else
begin
set... | import requests
import json
class MatchHistory:
# match history uses puuid to search in Riot API
def __init__(self, puuid, region, api_key):
self.puuid = puuid
if region == "na1":
self.region = "americas"
elif region == "euw1":
self.region = "europe"
el... | Python | zaydzuhri_stack_edu_python |
function display_message
begin
string Print a message that tells everyone what you are learning about in this chapter
print string I am learning about functions in ch8.
end function
call display_message | def display_message():
"""
Print a message that tells everyone what you are learning about in this chapter
"""
print("I am learning about functions in ch8.")
display_message()
| Python | zaydzuhri_stack_edu_python |
function build_poly x degree
begin
set num_samples = shape at 0
set tx = ones num_samples
for i in range 1 degree + 1
begin
set tx = c_ at tuple tx call power x i
end
return tx
end function | def build_poly(x, degree):
num_samples = x.shape[0]
tx = np.ones(num_samples)
for i in range(1, (degree+1)):
tx = np.c_[tx, np.power(x, i)]
return tx | Python | nomic_cornstack_python_v1 |
import math
set l = string harshsrah
set x = integer length l / 2
for i in range 0 x
begin
if l at i == l at 2 * x - i
begin
set flag = string true
end
else
begin
set flag = string false
end
end
if flag == string true
begin
print string palindrom
end
else
begin
print string no
end | import math
l="harshsrah"
x=int(len(l)/2)
for i in range (0,x):
if l[i] == l[(2*x-i)]:
flag="true"
else:
flag="false"
if flag=="true":
print("palindrom")
else:
print("no")
| Python | zaydzuhri_stack_edu_python |
function palindrome string
begin
return if expression string == string at slice : : - 1 then 0 else 1
end function
for i in range A B + 1
begin
if call palindrome string i == 0
begin
set ans = ans + 1
end
end
print ans | def palindrome(string): return 0 if string==string[::-1] else 1
for i in range(A, B+1):
if palindrome(str(i)) == 0 :
ans += 1
print(ans) | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.