code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function complete self start
begin
assert trie != none msg string No training has been done
set words = split start string
set progress = trie
for word in words
begin
if not call has_child word
begin
return none
end
set progress = call get_child word
end
set prediction = string
set next_trie = call most_likely_child
w... | def complete(self, start):
assert self.trie != None, "No training has been done"
words = start.split(' ')
progress = self.trie
for word in words:
if not progress.has_child(word):
return None
progress = progress.get_child(word)
prediction = ... | Python | nomic_cornstack_python_v1 |
string Insitu_constrained_RF_SSM Boxplot_evaluation_periods date: 18-Sep-2021 author: L.Zhang Contact: leojayak@gmail.com ------------------------------------- Description:
comment libraries
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
comment Set the working path
set file_metrics... | """
Insitu_constrained_RF_SSM Boxplot_evaluation_periods
date: 18-Sep-2021
author: L.Zhang
Contact: leojayak@gmail.com
-------------------------------------
Description:
"""
# libraries
import os
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Set the working path
file_metrics = r'C:\Users... | Python | zaydzuhri_stack_edu_python |
import reader
import params
import matplotlib.pyplot as plt
set x = list
set total = 0
set min_price = 1000
set max_price = 0
for k in parse reader metadata_path
begin
if string price in k
begin
append x k at string price
set total = total + 1
if k at string price > max_price
begin
set max_price = k at string price
en... | import reader
import params
import matplotlib.pyplot as plt
x = []
total = 0
min_price = 1000
max_price = 0
for k in reader.parse(params.metadata_path):
if 'price' in k:
x.append(k['price'])
total += 1
if k['price'] > max_price:
max_price = k['price']
if k['price'] < mi... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function isPalindrome self s
begin
string :type s: str :rtype: bool
set s = join string filter lambda x -> is alpha x or is digit x list s
set s = lower s
for i in range length s // 2
begin
if s at i != s at length s - 1 - i
begin
return false
end
end
return true
end function
end cl... | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = ''.join(filter(lambda x: x.isalpha() or x.isdigit(), list(s)))
s = s.lower()
for i in range(len(s) // 2):
if s[i] != s[len(s) - 1 - i]:
retur... | Python | zaydzuhri_stack_edu_python |
import logging
class MessageDecode
begin
function __init__ self msg
begin
try
begin
set _url = decode msg at 0 at 1 at 0 at 1 at b'url' string utf-8
set _id = decode msg at 0 at 1 at 0 at 0 string utf-8
end
except Exception as e
begin
warning string empty url or id from msg: { msg } , error: { e } exc_info=true
set _ur... | import logging
class MessageDecode:
def __init__(self, msg):
try:
self._url = msg[0][1][0][1][b'url'].decode('utf-8')
self._id = msg[0][1][0][0].decode('utf-8')
except Exception as e:
logging.warning(f'empty url or id from msg: {msg}, error: {e}', exc_info=True)... | Python | zaydzuhri_stack_edu_python |
for linha in arquivo
begin
if cod_p in linha
begin
set linha_lista = split linha string #
print linha_lista at 2
set prod = decimal replace linha_lista at 2 string , string .
print prod + prod
end
end | for linha in arquivo:
if cod_p in linha:
linha_lista = linha.split(" # ")
print(linha_lista[2])
prod = float(linha_lista[2].replace(',', '.'))
print(prod+prod)
| Python | zaydzuhri_stack_edu_python |
function load_database fname
begin
comment Parse into atomic_symbols
set ed = call ElementDatabase fname
comment Get the range of atomic numbers (optimistically)
set max_no = max list comprehension x at string atomic_number for x in data at string data
comment Update the atomic symbols
for i in range max_no
begin
set a... | def load_database(fname):
# Parse into atomic_symbols
ed = ElementDatabase(fname)
# Get the range of atomic numbers (optimistically)
max_no = max([x["atomic_number"] for x in ed.data["data"]])
# Update the atomic symbols
for i in range(max_no):
atomic_symbols[i+1] = ed[i+1]
# Update atomic symbols dic... | Python | nomic_cornstack_python_v1 |
function leapfrog theta r grad epsilon f
begin
comment make half step in r
set rprime = r + 0.5 * epsilon * grad
comment make new step in theta
set thetaprime = theta + epsilon * rprime
comment compute new gradient
set tuple logpprime gradprime = f dist thetaprime
comment make half step in r again
set rprime = rprime +... | def leapfrog(theta, r, grad, epsilon, f):
# make half step in r
rprime = r + 0.5 * epsilon * grad
# make new step in theta
thetaprime = theta + epsilon * rprime
#compute new gradient
logpprime, gradprime = f(thetaprime)
# make half step in r again
rprime = rprime + 0.5 * epsilon * gradpr... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Feb 26 10:40:26 2019 @author: maxya
comment -*- coding: utf-8 -*-
string time-advance- bank with 4 teller, two types of accounts
comment DEPENDENCY - to make random numbers easily
import numpy as np
function simulate numXacts wantreport
begin
comment --INITIALIZE STAT... | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 26 10:40:26 2019
@author: maxya
"""
# -*- coding: utf-8 -*-
''' time-advance- bank with 4 teller, two types of accounts '''
import numpy as np # DEPENDENCY - to make random numbers easily
def simulate(numXacts,wantreport):
#--INITIALIZE STATISTI... | Python | zaydzuhri_stack_edu_python |
comment encoding:utf-8
comment 这个示例可以知道
comment 1. 函数可以作为参数进行传递
comment 通过这种方法可以将函数做更进一步的抽象
comment 2. lambda 的用法,使得调用这类函数更简单
comment 一个通用的排序算法
function sort_list_comm work key
begin
for j in range length work - 1
begin
for i in range length work - 1
begin
if call key work at i > call key work at i + 1
begin
set tuple ... | #encoding:utf-8
# 这个示例可以知道
# 1. 函数可以作为参数进行传递
# 通过这种方法可以将函数做更进一步的抽象
# 2. lambda 的用法,使得调用这类函数更简单
# 一个通用的排序算法
def sort_list_comm(work , key):
for j in range(len(work)-1):
for i in range(len(work)-1):
if key(work[i]) > key(work[i+1]):
work[i],work[i+1] = work[i+1],work[i]
# 普通list排序
work = [2,... | Python | zaydzuhri_stack_edu_python |
function ready_to_dispatch request test_status=false
begin
set ready_to_dispatch = filter ready_to_plate=true plate__isnull=false plate__gel_1008_csv__isnull=true
set plate_ids_ready_to_dispatch = list
set plates_ready_to_dispatch = list
set consignment_summaries = dict
for holding_rack in ready_to_dispatch
begin
ca... | def ready_to_dispatch(request, test_status=False):
ready_to_dispatch = HoldingRack.objects.filter(ready_to_plate=True, plate__isnull=False, plate__gel_1008_csv__isnull=True)
plate_ids_ready_to_dispatch = []
plates_ready_to_dispatch = []
consignment_summaries = {}
for holding_rack in ready_to_dispatch:
HoldingRac... | Python | nomic_cornstack_python_v1 |
function print_table seqids data outputfile separator=string
begin
set tags = keys data
with open outputfile string w as out
begin
write out join separator list string #Sequence ID + list tags + string
for s in seqids
begin
write out s
for t in tags
begin
write out format string {}{} separator get data at t s string
en... | def print_table(seqids, data, outputfile, separator='\t'):
tags = data.keys()
with open(outputfile, 'w') as out:
out.write(separator.join(["#Sequence ID"] + list(tags)) + "\n")
for s in seqids:
out.write(s)
for t in tags:
out.write("{}{}".format(separator... | Python | nomic_cornstack_python_v1 |
comment Package is a directory which consists of modules and sub-packages
comment In other words, package is a set of modules
function display
begin
print string This is display function from module1
end function | #Package is a directory which consists of modules and sub-packages
#In other words, package is a set of modules
def display():
print("This is display function from module1") | Python | zaydzuhri_stack_edu_python |
function test_st_facets00401m15_positive mode save_output output_format
begin
call assert_bindings schema=string sunData/SType/ST_facets/ST_facets00401m/ST_facets00401m15.xsd instance=string sunData/SType/ST_facets/ST_facets00401m/ST_facets00401m15_p.xml class_name=string Root version=string 1.1 mode=mode save_output=s... | def test_st_facets00401m15_positive(mode, save_output, output_format):
assert_bindings(
schema="sunData/SType/ST_facets/ST_facets00401m/ST_facets00401m15.xsd",
instance="sunData/SType/ST_facets/ST_facets00401m/ST_facets00401m15_p.xml",
class_name="Root",
version="1.1",
mode=m... | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template , jsonify
import pymongo
import json
from bson import json_util , ObjectId
set app = call Flask __name__
comment Sets up the mongo connection: local server for db is created and connected to mongo
set conn = string mongodb://localhost:27017
set client = call MongoClient conn
co... | from flask import Flask, render_template, jsonify
import pymongo
import json
from bson import json_util, ObjectId
app = Flask(__name__)
# Sets up the mongo connection: local server for db is created and connected to mongo
conn = "mongodb://localhost:27017"
client = pymongo.MongoClient(conn)
# Assign our database as ... | Python | zaydzuhri_stack_edu_python |
comment while (test > 0):
comment remain = remain + (test % 10)
comment test = int(test / 10)
comment print (test)
print remain | #while (test > 0):
## remain = remain + (test % 10)
# test = int(test / 10)
# print (test)
print (remain)
| Python | zaydzuhri_stack_edu_python |
function terminate self
begin
pass
end function | def terminate(self):
pass | Python | nomic_cornstack_python_v1 |
import urllib2
from clarifai.client import ClarifaiApi
import unicodedata | import urllib2
from clarifai.client import ClarifaiApi
import unicodedata | Python | zaydzuhri_stack_edu_python |
import random as rn
set gram = random integer 1 6
set count = 0
while true
begin
set num = integer input string Enter the number
if num == gram
begin
set count = count + 1
print string You guessed right number in { count } attempt
break
end
else
if num > gram
begin
set count = count + 1
print string Number guessed is g... | import random as rn
gram=rn.randint(1,6)
count = 0
while True:
num=int(input("Enter the number"))
if num==gram:
count+=1
print(f"You guessed right number in {count} attempt")
break
elif num>gram:
count+=1
print("Number guessed is greater")
else:
count+=1
print("Numb... | Python | zaydzuhri_stack_edu_python |
function combine_words word **kwargs
begin
if string prefix in kwargs
begin
return kwargs at string prefix + word
end
else
if string suffix in kwargs
begin
return word + kwargs at string suffix
end
return word
end function | def combine_words(word,**kwargs):
if 'prefix' in kwargs:
return kwargs['prefix']+word
elif 'suffix' in kwargs:
return word+kwargs['suffix']
return word | Python | zaydzuhri_stack_edu_python |
function read_ceilometer_file self calibration_factor=none
begin
set tuple header data_lines = call _read_common_header_part
append header call _read_header_line_4 data_lines at - 3
set metadata = call _handle_metadata header
set data at string range = call _calc_range
set data at string beta_raw = call _read_backscatt... | def read_ceilometer_file(self, calibration_factor: float | None = None) -> None:
header, data_lines = self._read_common_header_part()
header.append(self._read_header_line_4(data_lines[-3]))
self.metadata = self._handle_metadata(header)
self.data["range"] = self._calc_range()
self... | Python | nomic_cornstack_python_v1 |
function get_search_count_vacancy text=none
begin
set data = call get_search_vacancies text
if is instance data dict
begin
return get data string found
end
else
begin
raise exception string Полученные данные не являются словарем
end
end function | def get_search_count_vacancy(text=None):
data = get_search_vacancies(text)
if isinstance(data, dict):
return data.get('found')
else:
raise Exception('Полученные данные не являются словарем') | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
string Remove duplicates in image-replaced event dataframe
set col_names1 = list string client_event_time string new-image string project-id string old-image string source
set df1 = call drop_duplicates keep=string first
set df1 at string old-image = string ' + as type df1 at stri... | import pandas as pd
import numpy as np
'''Remove duplicates in image-replaced event dataframe'''
col_names1 = ['client_event_time','new-image','project-id','old-image','source']
df1 = pd.read_csv('sample1.csv', usecols= col_names1, keep_default_na=False, na_values=[""]).drop_duplicates(keep='first')
df1['old-image'] =... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import os
import re
from math import radians , degrees
import numpy as np
import pandas as pd
import cv2
from pdftabextract import imgproc
from pdftabextract.geom import pt
from pdftabextract.common import read_xml , parse_pages , save_page_grids
from pdftabextract.textboxes import rotate_... | # -*- coding: utf-8 -*-
import os
import re
from math import radians, degrees
import numpy as np
import pandas as pd
import cv2
from pdftabextract import imgproc
from pdftabextract.geom import pt
from pdftabextract.common import read_xml, parse_pages, save_page_grids
from pdftabextract.textboxes import rotate_textbo... | Python | jtatman_500k |
function get_name_DID name proxy=none hostport=none
begin
string Get the DID for a name or subdomain Return the DID string on success Return None if not found
assert proxy or hostport msg string Need proxy or hostport
if proxy is none
begin
set proxy = call connect_hostport hostport
end
set did_schema = dict string typ... | def get_name_DID(name, proxy=None, hostport=None):
"""
Get the DID for a name or subdomain
Return the DID string on success
Return None if not found
"""
assert proxy or hostport, 'Need proxy or hostport'
if proxy is None:
proxy = connect_hostport(hostport)
did_schema = {
... | Python | jtatman_500k |
function run self
begin
comment read in the entries for this step
for line in call xreadlines
begin
set entry = loads line
comment if we are moving beyond this timestep, then wait for
comment more data from the master
if entry at string step > step
begin
call get_master_updates
end
comment now update the skyline using ... | def run(self):
# read in the entries for this step
for line in self.input.xreadlines():
entry = json.loads(line)
# if we are moving beyond this timestep, then wait for
# more data from the master
if entry['step'] > self.step:
self.get_mast... | Python | nomic_cornstack_python_v1 |
function metplus_config
begin
try
begin
if string JLOGFILE in environ
begin
setup setup send_dbn=false jobname=string MTDWrapper jlogfile=environ at string JLOGFILE
end
else
begin
setup setup send_dbn=false jobname=string MTDWrapper
end
call postmsg string mtd_wrapper is starting
comment Read in the configuration objec... | def metplus_config():
try:
if 'JLOGFILE' in os.environ:
produtil.setup.setup(send_dbn=False, jobname='MTDWrapper',
jlogfile=os.environ['JLOGFILE'])
else:
produtil.setup.setup(send_dbn=False, jobname='MTDWrapper')
produtil.log.postmsg('... | Python | nomic_cornstack_python_v1 |
function test_attributes self
begin
set s = call cls string path dict string sortfield string name ; string sortdirection string desc
assert equal field string name
assert equal direction string desc
end function | def test_attributes(self):
s = self.cls("path", {"sortfield": "name", "sortdirection": "desc"})
self.assertEqual(s.field, "name")
self.assertEqual(s.direction, "desc") | Python | nomic_cornstack_python_v1 |
comment Посчитать, сколько раз встречается определенная цифра в числах,
comment которые находятся в списке. Количество введенных чисел и искомая цифра задаются с клавиатуры.
comment Числа выбираются рандомно.
import random
set a = integer input string Введите колличество чисел:
set b = list comprehension random integer... | # Посчитать, сколько раз встречается определенная цифра в числах,
# которые находятся в списке. Количество введенных чисел и искомая цифра задаются с клавиатуры.
# Числа выбираются рандомно.
import random
a=int(input('Введите колличество чисел:'))
b=[random.randint(10,1000) for i in range(a)]
print(b)
c=int(... | Python | zaydzuhri_stack_edu_python |
function check_if_directory_exist_and_create_it self path
begin
set exist = call check_if_directory_exist path
if exist == - 1
begin
call create_directory path
return 1
end
else
begin
return 0
end
end function | def check_if_directory_exist_and_create_it(self, path):
exist = self.check_if_directory_exist(path)
if exist == -1:
self.create_directory(path)
return 1
else:
return 0 | Python | nomic_cornstack_python_v1 |
function softmax self x
begin
set e_x = exp x - max x
return e_x / sum axis=0
end function | def softmax(self, x):
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum(axis=0) | Python | nomic_cornstack_python_v1 |
function _render_window self car_id mode
begin
if viewer at car_id is none
begin
from gym.envs.classic_control import rendering
set viewer at car_id = call Viewer WINDOW_W WINDOW_H
call set_caption string Car { car_id }
set score_label = call Label string 0000 font_size=36 x=20 y=WINDOW_H * 2.5 / 40.0 anchor_x=string l... | def _render_window(self, car_id, mode):
if self.viewer[car_id] is None:
from gym.envs.classic_control import rendering
self.viewer[car_id] = rendering.Viewer(WINDOW_W, WINDOW_H)
self.viewer[car_id].window.set_caption(f"Car {car_id}")
self.score_label = pyglet.tex... | Python | nomic_cornstack_python_v1 |
set MySeq = string ACGTGG
set TransTable = call maketrans string AGCT string TCGA
set revMySeq = MySeq at slice : : - 1
set revcomplMySeq = call translate TransTable
print string Your reverse complement sequence is: revcomplMySeq | MySeq="ACGTGG"
TransTable=str.maketrans("AGCT","TCGA")
revMySeq=MySeq[::-1]
revcomplMySeq=revMySeq.translate(TransTable)
print("Your reverse complement sequence is: ", revcomplMySeq)
| Python | zaydzuhri_stack_edu_python |
function test_netstat_sudo_lnp_centos_7_7 self
begin
assert equal parse netstat centos_7_7_netstat_sudo_lnp quiet=true centos_7_7_netstat_sudo_lnp_json
end function | def test_netstat_sudo_lnp_centos_7_7(self):
self.assertEqual(jc.parsers.netstat.parse(self.centos_7_7_netstat_sudo_lnp, quiet=True), self.centos_7_7_netstat_sudo_lnp_json) | Python | nomic_cornstack_python_v1 |
string @author 王志 @desc 使用多组天线建立坐标系求得物体二维坐标,对物体进行了位置追踪,实现了手写数字和字母。 @data 2021/01/08
comment WalabotAPI works on both Python 2 an 3.
from __future__ import print_function
from sys import platform
from imp import load_source
from os.path import join
from util.plot_util import *
from scipy.optimize import fsolve
from nump... | '''
@author 王志
@desc 使用多组天线建立坐标系求得物体二维坐标,对物体进行了位置追踪,实现了手写数字和字母。
@data 2021/01/08
'''
from __future__ import print_function # WalabotAPI works on both Python 2 an 3.
from sys import platform
from imp import load_source
from os.path import join
from util.plot_util import *
from scipy.optimize import fsolve
from numpy im... | Python | zaydzuhri_stack_edu_python |
function Author
begin
return call Div id=string AuthorBox children=list call Div id=string AuthorImage children=list call Img id=string AImg src=call get_asset_url string profile_dummy.png call Div id=string AuthorData children=list call H1 string Author Information call P string Name: name call P string Origin: place ... | def Author():
return html.Div(id="AuthorBox", children=[
html.Div(id="AuthorImage", children=[
html.Img(id="AImg", src=app.get_asset_url('profile_dummy.png'))
]),
html.Div(id="AuthorData", children=[
html.H1("Author Information"),
html.P("Name: name"),
... | Python | nomic_cornstack_python_v1 |
function axis_aligned_extrema self
begin
set n = degree
if n <= 1
begin
return tuple array list array list
end
set Cj = polynomial_coefficients
set dCj = array range 1 n + 1 at tuple slice : : none * Cj at slice 1 : :
set dims = list
set roots = list
for tuple i pi in enumerate T
begin
set r = call roots pi at s... | def axis_aligned_extrema(self):
n = self.degree
if n <= 1:
return np.array([]), np.array([])
Cj = self.polynomial_coefficients
dCj = np.arange(1, n+1)[:, None] * Cj[1:]
dims = []
roots = []
for i, pi in enumerate(dCj.T):
r = np.roots(pi[::-... | Python | nomic_cornstack_python_v1 |
import math
function is_prime num
begin
if num < 2
begin
return false
end
for i in range 2 integer square root num + 1
begin
if num % i == 0
begin
return false
end
end
return true
end function
function generate_prime_list start end
begin
set prime_list = list
for num in range start end + 1
begin
if call is_prime num
b... | import math
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def generate_prime_list(start, end):
prime_list = []
for num in range(start, end+1):
if is_prime(num):
prime... | Python | jtatman_500k |
function attach_volume self instance_id volume_id device
begin
set response = call attach_volume url verb headers version instance_id volume_id device
if response is not none
begin
set res = call AttachVolumeResponse
call parseString string text res
return res
end
else
begin
return none
end
end function | def attach_volume(self, instance_id, volume_id, device):
response = volume.attach_volume(self.url, self.verb, self.headers,
self.version, instance_id, volume_id, device)
if response is not None :
res = AttachVolumeResponse.AttachVolumeResponse()
... | Python | nomic_cornstack_python_v1 |
from collections import defaultdict
from typing import List
from collections import deque
import string
class Solution
begin
function findLadders self beginWord endWord wordList
begin
comment 先将 wordList 放到哈希表里,便于判断某个单词是否在 wordList 里
set word_set = set wordList
set res = list
if length word_set == 0 or endWord not in ... | from collections import defaultdict
from typing import List
from collections import deque
import string
class Solution:
def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
# 先将 wordList 放到哈希表里,便于判断某个单词是否在 wordList 里
word_set = set(wordList)
res = []... | Python | zaydzuhri_stack_edu_python |
for i in range 1 6
begin
for j in range 5 - i
begin
print string end=string
end
for j in range 2 * i - 1
begin
print string * end=string
end
print
end | for i in range(1, 6):
for j in range(5-i):
print(" ", end="")
for j in range(2*i-1):
print("*", end="")
print() | Python | iamtarun_python_18k_alpaca |
import joche
set x = integer call raw_input string Dime un numero entero
print
comment print "Uso de la Funcion typenum"
comment print joche.typenum(x) | import joche
x=int(raw_input('Dime un numero entero '))
print
#print "Uso de la Funcion typenum"
#print joche.typenum(x)
| Python | zaydzuhri_stack_edu_python |
function count_unique_vowels *strings
begin
set vowels = set literal string a string e string i string o string u
set unique_vowels = set
for string in strings
begin
for char in string
begin
if is alpha char
begin
set char = lower char
if char in vowels
begin
add unique_vowels char
end
end
end
end
return length unique_... | def count_unique_vowels(*strings):
vowels = {'a', 'e', 'i', 'o', 'u'}
unique_vowels = set()
for string in strings:
for char in string:
if char.isalpha():
char = char.lower()
if char in vowels:
unique_vowels.add(char)
return len(un... | Python | jtatman_500k |
comment Unclock gmail use less secure password for APP found here: https://www.abstractapi.com/guides/sending-email-with-python
import sys
import os
from collections import defaultdict
from datetime import datetime
import smtplib
import ssl
from control_data import *
comment Need to send email, accaunt need to be with ... | # Unclock gmail use less secure password for APP found here: https://www.abstractapi.com/guides/sending-email-with-python
import sys
import os
from collections import defaultdict
from datetime import datetime
import smtplib
import ssl
from control_data import *
# Need to send email, accaunt need to be w... | Python | zaydzuhri_stack_edu_python |
function _to_keys l
begin
set d = dict
if string dBm in l
begin
remove l string dBm
end
while l
begin
set k = pop l 0
set v = pop l 0
if string = in v
begin
set v = split v string = at 1
end
set d at k = v
end
return d
end function | def _to_keys(l):
d = {}
if 'dBm' in l:
l.remove('dBm')
while l:
k = l.pop(0)
v = l.pop(0)
if '=' in v:
v = v.split('=')[1]
d[k] = v
return d | Python | nomic_cornstack_python_v1 |
function __check_words self url
begin
set probability = 0
set response = call __get_page_data url
if response is none
begin
return 0.0
end
set content = string content
if content is not none
begin
for tuple word value in items _words_values
begin
if word in content
begin
set probability = probability + value
end
end
re... | def __check_words(self, url):
probability = 0
response = self.__get_page_data(url)
if response is None:
return 0.0
content = str(response.content)
if content is not None:
for word, value in self._words_values.items():
if word in content:
... | Python | nomic_cornstack_python_v1 |
comment _*_ encoding: utf-8 _*_
import unittest
from calculator.calculator import Calculator
class TestCalculator extends TestCase
begin
function setUp self
begin
set calculator = call Calculator
end function
function test_add_given_two_values_should_return_the_correct_value self
begin
set result = add calculator 10 10... | # _*_ encoding: utf-8 _*_
import unittest
from calculator.calculator import Calculator
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calculator = Calculator()
def test_add_given_two_values_should_return_the_correct_value(self):
result = self.calculator.add(10, 10)
... | Python | zaydzuhri_stack_edu_python |
import os
import requests
import hashlib
import uuid
function download_files urls
begin
comment use a set to have unique hashes
set unique_hashes = set
comment download files
for url in urls
begin
set r = get requests url allow_redirects=true
comment calculate hash
set h = hex digest sha256 content
comment check if not... | import os
import requests
import hashlib
import uuid
def download_files(urls):
#use a set to have unique hashes
unique_hashes = set()
#download files
for url in urls:
r = requests.get(url, allow_redirects=True)
##calculate hash
h = hashlib.sha256(r.content).h... | Python | zaydzuhri_stack_edu_python |
function assemble dataset_type data_type dataset_len
begin
comment get all the expected segment numbers
set floored_upper = integer dataset_len / 500 * 500
set upper = 0
if floored_upper < dataset_len
begin
set upper = floored_upper + 500
end
else
begin
set upper = floored_upper
end
comment will contain all the np arra... | def assemble(dataset_type, data_type, dataset_len):
floored_upper = int(dataset_len / 500) * 500 # get all the expected segment numbers
upper = 0
if floored_upper < dataset_len:
upper = floored_upper + 500
else:
upper = floored_upper
combined_dataset = [] # will contain all the np... | Python | nomic_cornstack_python_v1 |
string A very simple example of logistic regression via TensorFlow, used for the Deep Learning workshop. We will use the MNIST dataset of handwritten digits (http://yann.lecun.com/exdb/mnist/) Authors: Juliet Moreiro (@julietsvq) and Pablo Doval (@PabloDoval)
import sys
append path string ../
from utils.init import ini... | '''
A very simple example of logistic regression via TensorFlow, used for the Deep Learning workshop.
We will use the MNIST dataset of handwritten digits (http://yann.lecun.com/exdb/mnist/)
Authors: Juliet Moreiro (@julietsvq) and Pablo Doval (@PabloDoval)
'''
import sys
sys.path.append('../')
from utils.init import... | Python | zaydzuhri_stack_edu_python |
function _stop_socket self
begin
if has attribute self string _sock_filename
begin
try
begin
remove os _sock_filename
end
except OSError
begin
pass
end
end
end function | def _stop_socket(self):
if hasattr(self, "_sock_filename"):
try:
os.remove(self._sock_filename)
except OSError:
pass | Python | nomic_cornstack_python_v1 |
import pytest
from main import main
function test_main_help capsys
begin
with raises SystemExit as exc
begin
call main list string --help
end
set tuple out err = call readouterr
assert args at 0 == 0
assert string usage: greet [-h] in out
assert err == string
end function
function test_main_success capsys
begin
set re... | import pytest
from ..main import main
def test_main_help(capsys):
with pytest.raises(SystemExit) as exc:
main(['--help'])
out, err = capsys.readouterr()
assert exc.value.args[0] == 0
assert 'usage: greet [-h]' in out
assert err == ''
def test_main_success(capsys):
ret = main(['--logl... | Python | zaydzuhri_stack_edu_python |
comment her eleman eşsizdir.
comment elemanlar değiştirilemez.
comment sırasızdır.
set myset = set literal string hale string melisa 3 4
print myset
for sets in myset
begin
print sets
end
print string hale in myset
print string halenur in myset
if string hale in myset
begin
print string olala
end
add myset string selam... | #her eleman eşsizdir.
#elemanlar değiştirilemez.
#sırasızdır.
myset = { "hale", "melisa", 3, 4}
print(myset)
for sets in myset:
print(sets)
print("hale" in myset)
print("halenur" in myset)
if "hale" in myset:
print("olala")
myset.add("selam")
print(myset)
myset.update(["lale", "sümbül"])
... | Python | zaydzuhri_stack_edu_python |
import tracemalloc
import time
import pandas as pd
import matplotlib.pyplot as plt
import sys
import sympy
set b_primes = list
set n_primes = list
start tracemalloc
set n = 1000
for i in range 0 50
begin
set b = call nextprime n
append b_primes b
set n = b
end
set m = 0
while m < 800
begin
set n = call nextprime m
ap... | import tracemalloc
import time
import pandas as pd
import matplotlib.pyplot as plt
import sys
import sympy
b_primes = []
n_primes = []
tracemalloc.start()
n = 1000
for i in range(0, 50):
b = sympy.nextprime(n)
b_primes.append(b)
n = b
m = 0
while m<800:
n = sympy.nextprime(m)
n_primes.append(n)
... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function clumsy self N
begin
set operators = list string * string // string + string -
set to_eval = string
set idx = 0
for i in range N 0 - 1
begin
set to_eval = to_eval + string i
if idx > 3
begin
set idx = 0
end
if i > 1
begin
set to_eval = to_eval + operators at idx
end
set idx = idx + 1
end
r... | class Solution:
def clumsy(self, N: int) -> int:
operators = ["*", "//", "+", "-"]
to_eval = ""
idx = 0
for i in range(N, 0, -1):
to_eval += str(i)
if idx > 3:
idx = 0
if i > 1:
to_eval += operators[idx]
... | Python | zaydzuhri_stack_edu_python |
function find_meta meta
begin
set meta_match = search format string ^__{meta}__ = ['\"]([^'\"]*)['\"] meta=meta META_FILE M
if meta_match
begin
return call group 1
end
raise call RuntimeError format string Unable to find __{meta}__ string. meta=meta
end function | def find_meta(meta):
meta_match = re.search(
r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M
)
if meta_match:
return meta_match.group(1)
raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta)) | Python | nomic_cornstack_python_v1 |
function gcd a_num b_num
begin
string Recursive GCD finder Using Euclid's Algorithm - gcd of a & b = gcd of b & a%b - gcd of a & 0 = a
if b_num == 0
begin
print a_num
end
else
begin
set rem = a_num % b_num
return call gcd b_num rem
end
end function
print call gcd 10 25
comment gcd(10, 3) #1
comment gcd(11, 13) #1
comme... | def gcd(a_num: int, b_num: int) -> int:
"""
Recursive GCD finder
Using Euclid's Algorithm
- gcd of a & b = gcd of b & a%b
- gcd of a & 0 = a
"""
if b_num == 0:
print(a_num)
else:
rem = (a_num % b_num)
return gcd(b_num, rem)
print(gcd(10, 25))
# gcd(10, 3) #1
# ... | Python | zaydzuhri_stack_edu_python |
from scipy.ndimage.filters import convolve
from skimage.transform import resize
import matplotlib.pyplot as plt
from scipy import ndimage
import numpy as np
import imutils
from imutils.video import VideoStream
from imutils.video import FPS
import pickle
import time
import cv2
import os
function rgb_ke_gray rgb
begin
se... | from scipy.ndimage.filters import convolve
from skimage.transform import resize
import matplotlib.pyplot as plt
from scipy import ndimage
import numpy as np
import imutils
from imutils.video import VideoStream
from imutils.video import FPS
import pickle
import time
import cv2
import os
def rgb_ke_gray(rgb... | Python | zaydzuhri_stack_edu_python |
comment leetcode/medium/2615. Sum of Distances
comment 2615-sum-of-distances
comment URL: https://leetcode.com/problems/sum-of-distances/description/
comment NOTE: Description
comment NOTE: Constraints
comment NOTE: Explanation
comment NOTE: Reference
from typing import List
class Solution
begin
function distance self ... | # leetcode/medium/2615. Sum of Distances
# 2615-sum-of-distances
# URL: https://leetcode.com/problems/sum-of-distances/description/
#
# NOTE: Description
# NOTE: Constraints
# NOTE: Explanation
# NOTE: Reference
from typing import List
class Solution:
def distance(self, nums: List[int]) -> List[int]:
inde... | Python | zaydzuhri_stack_edu_python |
function init_perception self
begin
set chat_parser = call NSPQuerier opts
if not has attribute self string perception_modules
begin
set perception_modules = dict
end
set perception_modules at string self = call SelfPerception self
set perception_modules at string vision = call Perception perception_model_dir
end func... | def init_perception(self):
self.chat_parser = NSPQuerier(self.opts)
if not hasattr(self, "perception_modules"):
self.perception_modules = {}
self.perception_modules["self"] = SelfPerception(self)
self.perception_modules["vision"] = Perception(self.opts.perception_model_dir) | Python | nomic_cornstack_python_v1 |
function wont_implement_method base_type name reason=none explanation=none
begin
if reason is not none
begin
if reason not in _WONT_IMPLEMENT_REASONS
begin
raise call AssertionError string reason must be one of { list keys _WONT_IMPLEMENT_REASONS } , got { reason }
end
set reason_data = _WONT_IMPLEMENT_REASONS at reaso... | def wont_implement_method(base_type, name, reason=None, explanation=None):
if reason is not None:
if reason not in _WONT_IMPLEMENT_REASONS:
raise AssertionError(
f"reason must be one of {list(_WONT_IMPLEMENT_REASONS.keys())}, "
f"got {reason!r}")
reason_data = _WONT_IMPLEMENT_REASONS... | Python | nomic_cornstack_python_v1 |
comment LESSON
function getPerson
begin
set name = string Leona
set age = 35
set country = string UK
return tuple name age country
end function
set tuple name age country = call getPerson
print name
print age
print country
comment EXERCISES
function someNumbers
begin
set a = 69
set b = 96
return tuple a b
end function
... | # LESSON
def getPerson():
name = "Leona"
age = 35
country = "UK"
return name, age, country
name, age, country = getPerson()
print(name)
print(age)
print(country)
# EXERCISES
def someNumbers():
a = 69
b = 96
return a, b
a, b = someNumbers()
c = a + b
print(a)
print(b)
pri... | Python | zaydzuhri_stack_edu_python |
from keras.models import Sequential
from keras.utils import to_categorical
from keras.layers import Dense
import keras
from keras import backend as K
import numpy as np
import pandas as pd
import copy
set trainfile = string spam_data/spam_train.csv
set testfile = string spam_data/spam_test.csv
comment open raw data
set... | from keras.models import Sequential
from keras.utils import to_categorical
from keras.layers import Dense
import keras
from keras import backend as K
import numpy as np
import pandas as pd
import copy
trainfile = 'spam_data/spam_train.csv'
testfile = 'spam_data/spam_test.csv'
# open raw data
raw_data = pd.read_csv(... | Python | zaydzuhri_stack_edu_python |
async function queue self ctx page=1
begin
set player = get players id
if not queue
begin
return await call send string :x: Nothing in queue.
end
set items_per_page = 10
set pages = ceil length queue / items_per_page
set start = page - 1 * items_per_page
set end = start + items_per_page
set queue_list = string
for tup... | async def queue(self, ctx, page: int=1):
player = self.bot.lavalink.players.get(ctx.guild.id)
if not player.queue:
return await ctx.send(':x: Nothing in queue.')
items_per_page = 10
pages = math.ceil(len(player.queue) / items_per_page)
start = (page - 1) * items_per_p... | Python | nomic_cornstack_python_v1 |
function _generate_grasps self graspable num_grasps vis=false
begin
comment get surface points
set grasps = list
set tuple surface_points _ = call surface_points grid_basis=false
shuffle random surface_points
set shuffled_surface_points = surface_points at slice : min max_num_surface_points_ length surface_points :
... | def _generate_grasps(self, graspable, num_grasps,
vis=False):
# get surface points
grasps = []
surface_points, _ = graspable.sdf.surface_points(grid_basis=False)
np.random.shuffle(surface_points)
shuffled_surface_points = surface_points[:min(self.max_num_... | Python | nomic_cornstack_python_v1 |
from PyQt5.QtWidgets import *
from PyQt5 import uic , QtWidgets , QtCore
import sys
class createUi extends QMainWindow
begin
function __init__ self parent=none
begin
call __init__
set window = call loadUi string UiForms/createScreen.ui self
set parent = parent
call create_base
end function
function create_base self
beg... | from PyQt5.QtWidgets import *
from PyQt5 import uic, QtWidgets, QtCore
import sys
class createUi(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(createUi, self).__init__()
self.window = uic.loadUi("UiForms/createScreen.ui", self)
self.parent = parent
self.create_ba... | Python | zaydzuhri_stack_edu_python |
function calculate_class_recall self confusion_mat
begin
return call diagonal confusion_mat / sum confusion_mat axis=1
end function | def calculate_class_recall(self, confusion_mat):
return np.diagonal(confusion_mat) / np.sum(confusion_mat, axis=1) | Python | nomic_cornstack_python_v1 |
function get_available_row self board column
begin
for i in range length board - 1 - 1 - 1
begin
if board at i at column == 0
begin
return i
end
end
end function | def get_available_row(self, board, column):
for i in range(len(board) - 1, -1, -1):
if board[i][column] == 0:
return i | Python | nomic_cornstack_python_v1 |
function localizations self
begin
set result = list
set locations = call get_val string templates default=string
for location in split locations string :
begin
set path_location = expand user path location
if is directory path path_location
begin
append result path_location
end
end
return result
end function | def localizations(self):
result = []
locations = self.get_val("templates", default="")
for location in locations.split(":"):
path_location = os.path.expanduser(location)
if os.path.isdir(path_location):
result.append(path_location)
return re... | Python | nomic_cornstack_python_v1 |
function values self episode
begin
set state = states at - 1
return list comprehension get _data call key state action 0.0 for action in range nb_actions
end function | def values(self, episode):
state = episode.states[-1]
return [self._data.get(self.key(state, action), 0.0) for action in range(self.nb_actions)] | Python | nomic_cornstack_python_v1 |
import sys
append path string ./
from utils.filename import calculateFileName
set filename = call calculateFileName argv
set f = open filename string r
set input = read f
comment Part 1
set lengths = list map lambda x -> integer x split input string ,
set index = 0
set skipSize = 0
set myList = list range 256
if length... | import sys
sys.path.append('./')
from utils.filename import calculateFileName
filename = calculateFileName(sys.argv)
f = open(filename, "r")
input = f.read()
# Part 1
lengths = list(map(lambda x: int(x), input.split(',')))
index = 0
skipSize = 0
myList = list(range(256))
if len(sys.argv) > 1:
myList = list(ran... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
set sess = call Session
comment default가 shuffle
set myqueue = call string_input_producer list string q_1.txt string q_2.txt string q_3.txt shuffle=false
set reader = call TextLineReader
comment 실제 데이터는 value에 들어감
set tuple key value = read reader myqueue
comment 값이 없을 때 x(sp):-1, y(dist):999 입력... | import tensorflow as tf
sess = tf.Session()
myqueue = tf.train.string_input_producer(['q_1.txt','q_2.txt','q_3.txt'], shuffle=False) #default가 shuffle
reader = tf.TextLineReader()
key, value = reader.read(myqueue) #실제 데이터는 value에 들어감
record_default=[[-1],[999]] #값이 없을 때 x(sp):-1, y(dist):999 입력
sp, dist = tf.... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
class Solution extends object
begin
function detectCapitalUse self word
begin
if length word == 1
begin
return true
end
if is upper word at 0 and is upper word at 1
begin
if length word > 2
begin
for idx in call xrange 2 length word
begin
if not is upper word at idx
begin
return false
end
e... | #!/usr/bin/env python
class Solution(object):
def detectCapitalUse(self, word):
if len(word) == 1:
return True
if word[0].isupper() and word[1].isupper():
if len(word) > 2:
for idx in xrange(2, len(word)):
if not word[idx].isupper():
return False
return True
else:
return True
e... | Python | zaydzuhri_stack_edu_python |
function prepare_data self from_date to_date stock_names dependencies
begin
set data = drop missing mean call rolling num_days
set columns = list comprehension format feature_template name for name in stock_names
set ready = true
end function | def prepare_data(self, from_date, to_date, stock_names, dependencies):
self.data = dependencies[0].data.rolling(self.num_days).mean().dropna()
self.data.columns = [self.feature_template.format(name) for name in stock_names]
self.ready = True | Python | nomic_cornstack_python_v1 |
comment 654. Maximum Binary Tree
import sys
comment Definition for a binary tree node.
class TreeNode
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
end function
end class
class Solution
begin
function constructMaximumBinaryTree self nums
begin
if length nums
begin
set max = - maxsize... | # 654. Maximum Binary Tree
import sys
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: list[int]) -> TreeNode:
if len(nums):
max = ... | Python | zaydzuhri_stack_edu_python |
function __init__ self name=none address=none
begin
set name = name
set address = address
set dongle = call Adapter call list_adapters at 0
if not powered
begin
set powered = true
end
debug string Adapter powered
debug string Start discovery
call nearby_discovery
set ubit = device call get_dbus_path DEVICE_INTERFACE st... | def __init__(self, name=None, address=None):
self.name = name
self.address = address
self.dongle = adapter.Adapter(adapter.list_adapters()[0])
if not self.dongle.powered:
self.dongle.powered = True
logger.debug('Adapter powered')
logger.debug('Start discovery'... | Python | nomic_cornstack_python_v1 |
import requests
comment getting input
set inputurl = strip input string Input the URL here:
set r = get requests inputurl
set status = status_code
set headers = headers
set content = text
print string The status code is: { status_code }
if status_code is not 200
begin
exit
end
else
begin
for tuple key value in items he... | import requests
#getting input
inputurl = input("Input the URL here: ").strip()
r = requests.get(inputurl)
status = r.status_code
headers = r.headers
content = r.text
print(f'The status code is: {r.status_code}')
if r.status_code is not 200:
exit()
else:
for key, value in headers.items():
print(f'\n {key}: {val... | Python | zaydzuhri_stack_edu_python |
comment Field trial simulation
comment guilherme borchardt - Oct., 2021
comment simulation of inference about differences between averages.
comment assumption: two independent variables that with similar variances and \
comment follow normal distribution.
comment inference statistics: T-Test for equal variance - two ta... | # Field trial simulation
# guilherme borchardt - Oct., 2021
# simulation of inference about differences between averages.
# assumption: two independent variables that with similar variances and \
# follow normal distribution.
# inference statistics: T-Test for equal variance - two tails.
app_name = 'Field Trial Analys... | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ key value
begin
set __self__ string key key
set __self__ string value value
end function | def __init__(__self__, *,
key: pulumi.Input[str],
value: pulumi.Input[str]):
pulumi.set(__self__, "key", key)
pulumi.set(__self__, "value", value) | Python | nomic_cornstack_python_v1 |
function find_best_periods self n_periods=5 return_scores=false
begin
string Find the top several best periods for the model
return call find_best_periods self n_periods return_scores=return_scores
end function | def find_best_periods(self, n_periods=5, return_scores=False):
"""Find the top several best periods for the model"""
return self.optimizer.find_best_periods(self, n_periods,
return_scores=return_scores) | Python | jtatman_500k |
set name = string John Jacob Jingle Heimer Schmidt
set nameUpper = upper name
print nameUpper | name = "John Jacob Jingle Heimer Schmidt"
nameUpper = name.upper()
print(nameUpper)
| Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
class ImageAPI
begin
function gradient self color
begin
set picture = list
for x in range 0 250
begin
set arrayx = list
for y in range 0 250
begin
set arrayy = list
for z in range 0 3
begin
if z == color
begin
set val = x * y * 2 / 5 * 10 ^ 4 * 3
end
else
begin
set ... | import numpy as np
import matplotlib.pyplot as plt
class ImageAPI:
def gradient(self, color):
picture = []
for x in range(0, 250):
arrayx = []
for y in range(0, 250):
arrayy = []
for z in range(0, 3):
if(z == color):
... | Python | zaydzuhri_stack_edu_python |
function runClaws self
begin
set right_trigger = right_trigger
set right_bumper = right_bumper
if call is_diff string relicClaw 0 call clip if expression right_bumper then 0.8 else 0 * 255 - 130 + 0 0 255 - 130
begin
call setPosition call get_val string relicClaw
end
if call is_diff string blockGrabL 0 call clip right_... | def runClaws(self):
right_trigger = self.gamepadA.right_trigger
right_bumper = self.gamepadA.right_bumper
if(self.react.is_diff("relicClaw",0,Range.clip((0.8 if right_bumper else 0)*(255-130)+0,0,255-130))):
self.relicClaw.setPosition(self.react.get_val("relicClaw"))
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2 as cv
set BLACK = tuple 0 0 0
set WHITE = tuple 255 255 255
set RED = tuple 0 0 255
set GREEN = tuple 0 255 0
set BLUE = tuple 255 0 0
set CYAN = tuple 255 255 0
set MAGENTA = tuple 255 0 255
set YELLOW = tuple 0 255 255
set colors = tuple RED GREEN BLUE MAGENTA CYAN YELLOW WHITE
set p0 = ... | import numpy as np
import cv2 as cv
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (0, 0, 255)
GREEN = (0, 255, 0)
BLUE = (255, 0, 0)
CYAN = (255, 255, 0)
MAGENTA = (255, 0, 255)
YELLOW = (0, 255, 255)
colors = (RED, GREEN, BLUE, MAGENTA, CYAN, YELLOW, WHITE)
p0 = p1 = 0, 0
img0 = np.zeros((200, 500, 3), np.uint8... | Python | zaydzuhri_stack_edu_python |
function get_art_name self
begin
return art_name
end function | def get_art_name(self):
return self.art_name | Python | nomic_cornstack_python_v1 |
function _getWeights self
begin
set weights = network at observed at 0
if length observed == 1
begin
return weights
end
for node in observed at slice 1 : :
begin
set weights = call getTableProduct weights network at node observed observed_values
end
return weights
end function | def _getWeights(self):
weights = self.network[self.observed[0]]
if len(self.observed) == 1:
return weights
for node in self.observed[1:]:
weights = getTableProduct(weights,self.network[node], self.observed, self.observed_values)
return weights | Python | nomic_cornstack_python_v1 |
import pickle , sys
import w2v_helpers
from config import MODELS , BOOK_SERIES , DUMPFILE
string Create a "social network" for a list of input characters by finding close relations in vector space. INPUT: a list of character names, and the list of (word embedding models to be used) RESULT: the config.NUM_CONNS closest ... | import pickle,sys
import w2v_helpers
from config import MODELS, BOOK_SERIES, DUMPFILE
"""
Create a "social network" for a list of input characters by finding close relations in vector space.
INPUT: a list of character names, and the list of (word embedding models to be used)
RESULT: the config.NUM_CONNS ... | Python | zaydzuhri_stack_edu_python |
function _statistics_meta_to_id_statistics_metadata meta
begin
return tuple id dict string has_mean has_mean ; string has_sum has_sum ; string name name ; string source source ; string statistic_id statistic_id ; string unit_of_measurement unit_of_measurement
end function
comment type: ignore[typeddict-item]
comment ty... | def _statistics_meta_to_id_statistics_metadata(
meta: StatisticsMeta,
) -> tuple[int, StatisticMetaData]:
return (
meta.id,
{
"has_mean": meta.has_mean, # type: ignore[typeddict-item]
"has_sum": meta.has_sum, # type: ignore[typeddict-item]
"name": meta.name,... | Python | nomic_cornstack_python_v1 |
function print_word_lengths string
begin
comment remove leading and trailing spaces
set string = strip string
comment base case: if the string is empty, return
if not string
begin
return
end
comment find the index of the first non-alphabetic character
set i = 0
while i < length string and not is alpha string at i
begin... | def print_word_lengths(string):
# remove leading and trailing spaces
string = string.strip()
# base case: if the string is empty, return
if not string:
return
# find the index of the first non-alphabetic character
i = 0
while i < len(string) and not string[i].isalpha():
i +... | Python | jtatman_500k |
function meter self
begin
return call disk_io_counters perdisk=false
end function
comment ^ tuple of
comment - read_count: number of reads < used
comment - write_count: number of writes < used
comment - read_bytes: number of bytes read < used
comment - write_bytes: number of bytes written < used
comment - read_time: ti... | def meter(self):
return psutil.disk_io_counters(perdisk=False)
# ^ tuple of
# - read_count: number of reads < used
# - write_count: number of writes < used
# - read_bytes: number of bytes read < used
# - wr... | Python | nomic_cornstack_python_v1 |
comment EXERCISE 3 - GUESS A NUMBER
set actual = 45
set attempt = 0
while true
begin
set attempt = attempt + 1
set guess = integer input string guess the number :
if guess > actual
begin
print string your guess is too high
end
else
if guess < actual
begin
print string your guess is too low
end
else
begin
print string y... | # EXERCISE 3 - GUESS A NUMBER
actual = 45
attempt = 0
while True :
attempt += 1
guess = int(input("guess the number : \n "))
if guess > actual :
print("your guess is too high")
elif guess < actual:
print("your guess is too low")
else :
print(f"you guessed the n... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
import re
set s = string \tafa\t13d\t8773\rfafa\r323
comment replace替换方法,但是每次只能替换一个
comment 删除所有\t,替换为空格,也可以替换为其它字符
set s1 = replace s string \t string
print s1
print string * * 50
comment re.sub正则替换一次可以替换多个
set s = string afa 13d 8773 fafa 323
set s2 = sub string [\t\r] string s
print s2
... | # -*- coding:utf-8 -*-
import re
s = r'\tafa\t13d\t8773\rfafa\r323'
# replace替换方法,但是每次只能替换一个
# 删除所有\t,替换为空格,也可以替换为其它字符
s1 = s.replace(r'\t', '')
print(s1)
print('*' * 50)
# re.sub正则替换一次可以替换多个
s = '\tafa\t13d\t8773\rfafa\r323'
s2 = re.sub(r'[\t\r]', '', s)
print(s2)
print('*' * 50) | Python | zaydzuhri_stack_edu_python |
function legendre_symbol a p
begin
set ls = power a p - 1 / 2 p
return if expression ls == p - 1 then - 1 else ls
end function | def legendre_symbol(a, p):
ls = pow(a, (p - 1) / 2, p)
return -1 if ls == p - 1 else ls | Python | nomic_cornstack_python_v1 |
function text_path self text
begin
call _add_instruction string text_path text
end function | def text_path(self, text):
self._add_instruction("text_path", text) | Python | nomic_cornstack_python_v1 |
string similar as 940. The only point here is we need to find the k which the first index that is 1 not 0. This way we can make sure all other will starts will '1'. dp[i] : till index i, the number of unique good subsequece .
class Solution
begin
function numberOfUniqueGoodSubsequences self binary
begin
set binary = st... | """
similar as 940.
The only point here is we need to find the k which the first index that is 1 not 0.
This way we can make sure all other will starts will '1'.
dp[i] : till index i, the number of unique good subsequece .
"""
class Solution:
def numberOfUniqueGoodSubsequences(self, binary: str) -> int:
bi... | Python | zaydzuhri_stack_edu_python |
function __init__ self source_repo manifest_repo build_names incr_type force branch manifest=DEFAULT_MANIFEST dry_run=true master=false
begin
set cros_source = source_repo
set buildroot = directory
if starts with manifest_repo INTERNAL_GOB_URL
begin
set manifest_dir = join path buildroot string manifest-versions-intern... | def __init__(self, source_repo, manifest_repo, build_names, incr_type, force,
branch, manifest=constants.DEFAULT_MANIFEST, dry_run=True,
master=False):
self.cros_source = source_repo
buildroot = source_repo.directory
if manifest_repo.startswith(site_config.params.INTERNAL_GOB_U... | Python | nomic_cornstack_python_v1 |
comment Enter your code here. Read input from STDIN. Print output to STDOUT
set a = call raw_input | # Enter your code here. Read input from STDIN. Print output to STDOUT
a = raw_input()
| Python | zaydzuhri_stack_edu_python |
string Seed your database with test values
import sqlite3
import pudb
set db = string rpg.db
set connection = call connect db
set c = call cursor
set monsters = list list string red string scary string 2 string 7 string 5 string 4 list string blue string not scary string 4 string 74 string 9 string 0
print string Destr... | """
Seed your database with test values
"""
import sqlite3
import pudb
db = 'rpg.db'
connection = sqlite3.connect(db)
c = connection.cursor()
monsters = [
["red", "scary","2","7","5","4"],
["blue", "not scary","4","74","9","0"]
]
print("Destroying old data")
c.execute("DELETE FROM monster")
# pu.db
for m... | Python | zaydzuhri_stack_edu_python |
function wait_for text finish=none io=none
begin
if finish
begin
set
comment threads, sigh
sleep 0.1
end
if not io
begin
set io = stdout
end
set finish = event
write io text
function _wait
begin
while not call is_set
begin
write io string .
flush io
wait finish timeout=1
end
write io string
end function
start thread ta... | def wait_for(text, finish=None, io=None):
if finish:
finish.set()
time.sleep(0.1) # threads, sigh
if not io:
io = sys.stdout
finish = threading.Event()
io.write(text)
def _wait():
while not finish.is_set():
io.write('.')
io.flush()
... | Python | nomic_cornstack_python_v1 |
async function cancella context userId
begin
if administrator
begin
set userId = await call CleanUserId userId
set nomeUtente = string mentions at 0
print string Rimozione del membro: + nomeUtente
await call remove_user userId
await call say string Rimozione del membro: + nomeUtente + string avvenuta correttamente
end
... | async def cancella(context, userId):
if context.message.author.server_permissions.administrator:
userId = await data_bot.CleanUserId(userId)
nomeUtente = str(context.message.mentions[0])
print('Rimozione del membro: ' + nomeUtente)
await data_bot.remove_user(userId)
awa... | 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.