code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
set cars = list string bmv string audi string toyota string changcheng
sort cars reverse=true
print cars | cars = ['bmv','audi','toyota','changcheng']
cars.sort(reverse=True)
print(cars) | Python | zaydzuhri_stack_edu_python |
function print_one_plus_one
begin
set digit_value = 1 + 1
print digit_value
end function | def print_one_plus_one():
digit_value = 1 + 1
print(digit_value) | Python | zaydzuhri_stack_edu_python |
function test
begin
set t = integer input
for _ in range 0 t
begin
set n = integer input
set res = call func n
print res
end
end function
function func n
begin
if n == 1
begin
return 1
end
else
begin
set res = call func n - 1
set multi = 1
set k = 0
for j in range 1 n
begin
set k = k + j
end
set k = k + 1
for i in rang... | def test():
t = int(input())
for _ in range(0, t):
n = int(input())
res=func(n)
print(res)
def func(n):
if n==1:
return 1
else:
res=func(n-1)
multi=1
k=0
for j in range(1,n):
k=k+j
k=k+1
for i in range(0,n):
... | Python | zaydzuhri_stack_edu_python |
function serialize self value state
begin
comment type: Any
comment type: _ProcessorState
comment type: (...) -> ET.Element
string Serialize the value and returns it.
set xml_value = call _hooks_apply_before_serialize _hooks state value
return call serialize xml_value state
end function | def serialize(
self,
value, # type: Any
state # type: _ProcessorState
):
# type: (...) -> ET.Element
"""Serialize the value and returns it."""
xml_value = _hooks_apply_before_serialize(self._hooks, state, value)
return self._processor.serialize(x... | Python | jtatman_500k |
function get_random_ids request num lesson_number=- 1 lesson_numbers=list
begin
if num < 1
begin
set num = 1
end
comment import pdb;pdb.set_trace()
if is instance lesson_numbers list
begin
if lesson_numbers == list string 0
begin
set cards = filter lesson_number=string
end
else
begin
set cards = filter lesson_number__i... | def get_random_ids(request, num, lesson_number=-1, lesson_numbers=[]):
if num < 1:
num = 1
# import pdb;pdb.set_trace()
if isinstance(lesson_numbers, list):
if lesson_numbers == ['0',]:
cards = SimpleCard.objects.filter(lesson_number='')
else:
cards = SimpleCa... | Python | nomic_cornstack_python_v1 |
string You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b] indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given pairs any number of times. Return the lexicographically smallest string that s can be changed to aft... | '''
You are given a string s, and an array of pairs of indices in the string pairs where pairs[i] = [a, b]
indicates 2 indices(0-indexed) of the string.
You can swap the characters at any pair of indices in the given pairs any number of times.
Return the lexicographically smallest string that s can be changed to afte... | Python | zaydzuhri_stack_edu_python |
comment %load q03_plot_innings_runs_histogram/build.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plot
set ipl_df = read csv string data/ipl_dataset.csv index_col=none
comment Solution
function plot_innings_runs_histogram
begin
set ball_count = ipl_df at list string match_code string delivery
se... | # %load q03_plot_innings_runs_histogram/build.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plot
ipl_df = pd.read_csv('data/ipl_dataset.csv', index_col=None)
# Solution
def plot_innings_runs_histogram():
ball_count=ipl_df[['match_code','delivery']]
a=ipl_df['inning']==1
b=ipl_df['... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function solve self A
begin
set B = list
set C = list
while A
begin
set tmp = pop A 0
while B
begin
set val = pop B
if val <= tmp
begin
while C
begin
set val2 = pop C
if val2 > val
begin
return 0
end
else
begin
append C val2
break
end
end
append C val
end
else
begin
append B val
break
end
end
app... | class Solution:
def solve(self, A):
B = []
C = []
while A:
tmp = A.pop(0)
while B:
val = B.pop()
if val <= tmp:
while C:
val2 = C.pop()
if val2 > val:
... | Python | zaydzuhri_stack_edu_python |
import datetime
class Car
begin
function __init__ self model year
begin
set model = model at slice : 50 :
set year = max 1900 min year year
end function
function start_engine self
begin
print string Engine started
end function
end class
set my_car = call Car string Ford Mustang GT 2020
comment Output: Ford Mustang GT... | import datetime
class Car:
def __init__(self, model, year):
self.model = model[:50]
self.year = max(1900, min(year, datetime.datetime.now().year))
def start_engine(self):
print("Engine started")
my_car = Car("Ford Mustang GT", 2020)
print(my_car.model) # Output: Ford Mustang GT
prin... | Python | jtatman_500k |
function __reconstruct_path self came_from current_node
begin
if came_from at string position is none
begin
return list
end
else
begin
set previous_node = came_from at string position
return call __reconstruct_path came_from previous_node + list current_node - previous_node
end
end function | def __reconstruct_path(self, came_from, current_node):
if came_from[str(current_node.position)] is None:
return []
else:
previous_node = came_from[str(current_node.position)]
return self.__reconstruct_path(came_from, previous_node) + \
[(current_no... | Python | nomic_cornstack_python_v1 |
function set_password name password
begin
string Set the password for a named user. The password must be a properly defined hash. The password hash can be generated with this command: ``python -c "import crypt; print crypt.crypt('password', ciphersalt)"`` .. note:: When constructing the ``ciphersalt`` string, you must ... | def set_password(name, password):
'''
Set the password for a named user. The password must be a properly defined
hash. The password hash can be generated with this command:
``python -c "import crypt; print crypt.crypt('password', ciphersalt)"``
.. note::
When constructing the ``ciphersalt`... | Python | jtatman_500k |
function _construct_conditional_from_prefix self prefix_tree timestamps
begin
comment we don't need a deep copy because we are not using
comment the prefix tree anymore
set conditional_tree = prefix_tree
for node in call items_ordered
begin
if not call _get_recurrence node at 0 sorted timestamps at node at 0
begin
comm... | def _construct_conditional_from_prefix(self, prefix_tree, timestamps):
# we don't need a deep copy because we are not using
# the prefix tree anymore
conditional_tree = prefix_tree
for node in conditional_tree.items_ordered():
if not self._get_recurrence(node[0], sorted(time... | Python | nomic_cornstack_python_v1 |
function get_epo_id href
begin
set beginIndex = find href string contextId= + length string contextId=
set epoId = href at slice beginIndex : :
set endIndex = 0
set nextCharacter = epoId at endIndex
while is digit nextCharacter
begin
set endIndex = endIndex + 1
set nextCharacter = epoId at endIndex
end
set epoId = ep... | def get_epo_id(href):
beginIndex = href.find("contextId=") + len("contextId=")
epoId = href[beginIndex:]
endIndex = 0
nextCharacter = epoId[endIndex]
while nextCharacter.isdigit():
endIndex += 1
nextCharacter = epoId[endIndex]
epoId = epoId[:endIndex]
return epoId | Python | nomic_cornstack_python_v1 |
function bind self field_name parent
begin
comment In order to enforce a consistent style, we error if a redundant
comment 'source' argument has been used. For example:
comment my_field = serializer.CharField(source='my_field')
assert source != field_name msg string It is redundant to specify `source='%s'` on field '%s... | def bind(self, field_name, parent):
# In order to enforce a consistent style, we error if a redundant
# 'source' argument has been used. For example:
# my_field = serializer.CharField(source='my_field')
assert self.source != field_name, (
"It is redundant to specify `source=... | Python | nomic_cornstack_python_v1 |
function run target_dir=VOC2007_TF_DATADIR source_dir=VOC2007_SRC_DIR
begin
if not exists gfile target_dir
begin
make directories target_dir
end
set train_filename = call _get_output_filename target_dir string train
set val_filename = call _get_output_filename target_dir string val
set trainval_filename = call _get_out... | def run(target_dir=VOC2007_TF_DATADIR, source_dir=VOC2007_SRC_DIR):
if not tf.gfile.Exists(target_dir):
tf.gfile.MakeDirs(target_dir)
train_filename = _get_output_filename(target_dir, 'train')
val_filename = _get_output_filename(target_dir, 'val')
trainval_filename = _get_output_filename(target... | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
return string Client(id=%r addr:%s name:%s level:%d state:%d) % tuple id string addr name security_level state
end function | def __str__(self):
return "Client(id=%r addr:%s name:%s level:%d state:%d)" % (
self.id, str(self.addr), self.name, self.security_level, self.state) | Python | nomic_cornstack_python_v1 |
class Node
begin
function __init__ self data=none next=none prev=none
begin
set data = data
set next = next
set prev = prev
end function
end class
class Queue
begin
function __init__ self
begin
set head = none
set tail = none
set count = 0
end function
function enqueue self data
begin
set node = call Node data
if head ... | class Node:
def __init__(self, data=None, next=None, prev=None):
self.data = data
self.next = next
self.prev = prev
class Queue:
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def enqueue(self, data) :
node = Node(data)
... | Python | zaydzuhri_stack_edu_python |
comment 封装、继承、多态
class Turtle
begin
set color = string green
set weight = 10
set legs = 4
set shell = true
set mouth = string 大嘴
comment ethods
function climb self
begin
print string 我在很努力的向前爬....
end function
function run self
begin
print string 我正在飞快的向前跑...
end function
function bite self
begin
print string 咬死你呀,咬死你呀... | #封装、继承、多态
class Turtle:
color='green'
weight=10
legs=4
shell=True
mouth='大嘴'
#ethods
def climb(self):
print('我在很努力的向前爬....')
def run(self):
print('我正在飞快的向前跑...')
def bite(self):
print('咬死你呀,咬死你呀')
def eat(self):
print('有的词,真满足...')
def slee... | Python | zaydzuhri_stack_edu_python |
function strip_cstring data
begin
if b'\x00' in data
begin
return decode data at slice : index data b'\x00' : string ascii
end
else
begin
return decode data string ascii
end
end function | def strip_cstring(data: bytes) -> str:
if b'\0' in data:
return data[:data.index(b'\0')].decode('ascii')
else:
return data.decode('ascii') | Python | nomic_cornstack_python_v1 |
import math
from custom_types import Partial , Hz
function get_filter_order fs transition_width passband_ripple stopband_attenuation
begin
string https://dsp.stackexchange.com/questions/31066/how-many-taps-does-an-fir-filter-need
return 2 / 3 * call log10 1 / 10 * passband_ripple * stopband_attenuation * fs / transitio... | import math
from custom_types import Partial, Hz
def get_filter_order(fs: Partial,
transition_width: Partial,
passband_ripple: float,
stopband_attenuation: float):
"""
https://dsp.stackexchange.com/questions/31066/how-many-taps-does-an-fir-filter... | Python | zaydzuhri_stack_edu_python |
string วิเคาระห์ปริมาณน้ำฝน
import csv
import matplotlib.pyplot as plt
import numpy as np
function plot_all
begin
string ดึงข้อมูลน้ำฝนและแสดงผลเป็นกราฟ
set url = open string 2524-2558.csv
set reader = reader url
set x = array range 2524 2559
set y = list comprehension integer i at 1 for i in reader
set result = call a... | """วิเคาระห์ปริมาณน้ำฝน"""
import csv
import matplotlib.pyplot as plt
import numpy as np
def plot_all():
"""ดึงข้อมูลน้ำฝนและแสดงผลเป็นกราฟ"""
url = open(r'2524-2558.csv')
reader = csv.reader(url)
x = np.arange(2524, 2559)
y = [int(i[1]) for i in reader]
result = np.average(y)
plt.bar(x, y... | Python | zaydzuhri_stack_edu_python |
string Multiple robots moving in parallel @author Juha Reinikainen @date 10.2.2021
import os
import pygame as pg
from threading import Semaphore , Thread
import concurrent.futures
from time import sleep
class House
begin
string # wall " " free space R robot
function __init__ self
begin
set fn = join path split path abs... | """
Multiple robots moving in parallel
@author Juha Reinikainen
@date 10.2.2021
"""
import os
import pygame as pg
from threading import Semaphore, Thread
import concurrent.futures
from time import sleep
class House:
"""
# wall
" " free space
R robot
"""
def __init__(self):
fn = os.path... | Python | zaydzuhri_stack_edu_python |
async function dequeue self *jobs
begin
assert jobs msg string At least one job required
set params = list string DEQUEUE
extend params generator expression get attribute job string id job for job in jobs
set response = await call execute_command *params
return response
end function | async def dequeue(self, *jobs):
assert jobs, 'At least one job required'
params = ['DEQUEUE']
params.extend(getattr(job, 'id', job) for job in jobs)
response = await self.execute_command(*params)
return response | Python | nomic_cornstack_python_v1 |
function zeroones input_arr
begin
set count = 0
set length = length input_arr
for i in input_arr
begin
if i == 0
begin
set count = count + 1
end
end
for j in range 0 count
begin
set input_arr at j = 0
end
for n in range count length
begin
set input_arr at n = 1
end
return input_arr
end function
if __name__ == string __... | def zeroones(input_arr):
count=0
length=len(input_arr)
for i in input_arr:
if i==0:
count+=1
for j in range(0,count):
input_arr[j]=0
for n in range(count,length):
input_arr[n]=1
return input_arr
if __name__ == '__main__':
input_arr=[0,1,0,1,0,0... | Python | zaydzuhri_stack_edu_python |
import math
function derivative x
begin
return 30 * x ^ 5 - 36 * 5 * x ^ 4 - 165 * 2 * x ^ 3 - 180 * x ^ 2
end function
function function x
begin
return 5 * x ^ 6 - 36 * x ^ 5 - 165 * x ^ 4 / 2 - 60 * x ^ 3 + 36
end function
function qubic_interpolation s0 step eps delta f f_der
begin
set y_der_0 = call f_der s0
set k ... | import math
def derivative(x):
return 30 * x ** 5 - 36 * 5 * x ** 4 - 165 * 2 * x ** 3 - 180 * x ** 2
def function(x):
return 5 * x ** 6 - 36 * x ** 5 - 165 * x ** 4 / 2 - 60 * x ** 3 + 36
def qubic_interpolation(s0, step, eps, delta, f, f_der):
y_der_0 = f_der(s0)
k = 0
n = 0
direction = -... | Python | zaydzuhri_stack_edu_python |
from crypto_currency.blockchain import BlockChain
function get_accounts
begin
set blocks = call get_blockchain
set name_list = set
for block in blocks
begin
set transaction = block at string transaction
if length transaction == 3
begin
add name_list get transaction string recipient
end
end
return name_list
end function... | from crypto_currency.blockchain import BlockChain
def get_accounts():
blocks = BlockChain.get_blockchain()
name_list = set()
for block in blocks:
transaction = block['transaction']
if len(transaction) == 3:
name_list.add(transaction.get('recipient'))
return name_list... | Python | zaydzuhri_stack_edu_python |
function add_row self
begin
if length _grid == 0 or length _grid at 0 == 1
begin
append _grid list none
end
else
if length _grid at 0 > 1
begin
set row = list comprehension none for _ in range length _grid at 0
append _grid row
end
return true
end function | def add_row(self):
if len(self._grid) == 0 or len(self._grid[0]) == 1:
self._grid.append([None])
elif len(self._grid[0]) > 1:
row = [None for _ in range(len(self._grid[0]))]
self._grid.append(row)
return True | Python | nomic_cornstack_python_v1 |
import speech_recognition as sr
import subprocess
import time
import os
from gtts import gTTS
from datetime import date , datetime
import webbrowser
import math
function convert_timezone
begin
string format time time string %X %x %Z
set environ at string TZ = string US/Pacific
call tzset
string format time time string ... | import speech_recognition as sr
import subprocess
import time
import os
from gtts import gTTS
from datetime import date, datetime
import webbrowser
import math
def convert_timezone():
time.strftime('%X %x %Z')
os.environ['TZ'] = 'US/Pacific'
time.tzset()
time.strftime('%X %x %Z')
def dotprint():
print (" \n... | Python | zaydzuhri_stack_edu_python |
function sizeof_fmt num suffix=string B
begin
for unit in list string string Ki string Mi string Gi string Ti string Pi string Ei string Zi
begin
if absolute num < 1024.0
begin
return string %3.1f%s%s % tuple num unit suffix
end
set num = num / 1024.0
end
return string %.1f%s%s % tuple num string Yi suffix
end functio... | def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix) | Python | nomic_cornstack_python_v1 |
from flask import Blueprint , flash , render_template , request , url_for , redirect
from models import Destination , Comment , User
from forms import CommentForm , DestinationForm
from import db
from flask import session
from werkzeug.utils import secure_filename
import os
from flask_login import login_required , cur... | from flask import (
Blueprint, flash, render_template, request, url_for, redirect
)
from .models import Destination,Comment,User
from .forms import CommentForm, DestinationForm
from . import db
from flask import session
from werkzeug.utils import secure_filename
import os
from flask_login import login_required, c... | Python | zaydzuhri_stack_edu_python |
comment Listen sind mutable (veränderbar)
comment Immutable: tuple - mit runden Klammern (nicht veränderbar) | # Listen sind mutable (veränderbar)
# Immutable: tuple - mit runden Klammern (nicht veränderbar)
| Python | zaydzuhri_stack_edu_python |
function __filter_to_bc_matrix self filter_mat n
begin
set k = shape at 1
comment When an (n,n) image is convoled with a (k,k) filter, the reesulting matrix
comment has dimension (n - k + 1) assuming a stride of 1. And the total number of
comment pixels in the input image is n ** 2 (assuming the image is square)
set tu... | def __filter_to_bc_matrix(self, filter_mat, n):
k = filter_mat.shape[1]
# When an (n,n) image is convoled with a (k,k) filter, the reesulting matrix
# has dimension (n - k + 1) assuming a stride of 1. And the total number of
# pixels in the input image is n ** 2 (assuming the image is... | Python | nomic_cornstack_python_v1 |
function _get_viewer_mail self
begin
comment Parses each individual component
set Name = get form string name
set Mail = get form string email string
set Message = get form string message
set body = format string Message from someone who viewed your web page: Name: {0} Contact: {1} Message: {2} End of message Name Mail... | def _get_viewer_mail(self):
Name = request.form.get("name") # Parses each individual component
Mail = request.form.get("email", "")
Message = request.form.get("message")
body = """
Message from someone who viewed your web page:
Name: {0}
Contact: {1}
Message: {2}
End of message
""". forma... | Python | nomic_cornstack_python_v1 |
function scan
begin
if ends with DefaultRepository sep
begin
set l = length DefaultRepository
end
else
begin
set l = length DefaultRepository + 1
end
set all_jpg = list comprehension i at slice l : : for i in glob glob join path DefaultRepository string * string *.jpg
debug string Scanned directory %s and found %i im... | def scan():
if config.DefaultRepository.endswith(os.sep):
l = len(config.DefaultRepository)
else:
l = len(config.DefaultRepository) + 1
all_jpg = [i[l:] for i in glob.glob(os.path.join(config.DefaultRepository, "*", "*.jpg"))]
logger.debug("Scanned directory %s and found %i images" % (co... | Python | nomic_cornstack_python_v1 |
function _check_if_pyc fname
begin
from imp import find_module
from os.path import realpath , dirname , basename , splitext
comment Normalize the file-path for the find_module()
set filepath = real path fname
set dirpath = directory name filepath
set module_name = call splitext base name filepath at 0
comment Validate ... | def _check_if_pyc(fname):
from imp import find_module
from os.path import realpath, dirname, basename, splitext
# Normalize the file-path for the find_module()
filepath = realpath(fname)
dirpath = dirname(filepath)
module_name = splitext(basename(filepath))[0]
# Validate and fetch
try:... | Python | nomic_cornstack_python_v1 |
import numpy as np
from scipy import linalg
set A = array list list 5 list 6
set B = array list list 4 1 list 2 2
print T
print A
print B
comment inverse
print call inv B
print B * A
comment [5*4 + 6*1]
print dot A
comment [5*2 + 6*2]
print call det B
print dot A
comment Solve a linear matrix equation, or system of lin... | import numpy as np
from scipy import linalg
A = np.array([[5], [6]])
B = np.array([[4, 1], [2, 2]])
print(A.T)
print(A)
print(B)
print(linalg.inv(B)) #inverse
print(B * A)
print(B.dot(A)) # [5*4 + 6*1]
# [5*2 + 6*2]
print(linalg.det(B))
print(linalg.inv(B).dot(A))
print(linalg.solve(B, A)) #Solve a l... | Python | zaydzuhri_stack_edu_python |
function replacebindvars cls query bindvars
begin
set log = call getLogger string TrigConfFrontier.py
from builtins import int
for tuple var val in list items bindvars
begin
if find query string :%s % var < 0
begin
raise call NameError string variable '%s' is not a bound variable in this query: %s % tuple var query
end... | def replacebindvars(cls, query, bindvars):
log = logging.getLogger( "TrigConfFrontier.py" )
from builtins import int
for var,val in list(bindvars.items()):
if query.find(":%s" % var)<0:
raise NameError("variable '%s' is not a bound variable in this query: %s" % (var, ... | Python | nomic_cornstack_python_v1 |
function New *args **kargs
begin
set obj = call __New_orig__
import itkTemplate
call New obj *args keyword kargs
return obj
end function | def New(*args, **kargs):
obj = itkPolyLineParametricPath3.__New_orig__()
import itkTemplate
itkTemplate.New(obj, *args, **kargs)
return obj | Python | nomic_cornstack_python_v1 |
function curvedScrew outline spine LODr LODp normalsDown=false rScale=none
begin
set verts = list
set faces = list
set order = if expression normalsDown then - 1 else 1
if rScale is none
begin
set rScale = lambda _ -> 1
end
set samples = call samples LODr
set zSamples = list comprehension z for v in samples
comment a... | def curvedScrew(outline, spine, LODr, LODp, normalsDown=False, rScale=None):
verts = []
faces = []
order = -1 if normalsDown else 1
if rScale is None:
rScale = lambda _: 1
samples = outline.samples(LODr)
zSamples = [v.z for v in samples]
zSamplesSortedIds = [i[0] for i in sorted... | Python | nomic_cornstack_python_v1 |
comment spiderjobs
comment coding=utf-8
class SpiderJobs extends object
begin
comment classmemebervariables
comment classmembermethods
function __init__ self
begin
set ListOfJobs = list
set CurrentJob = 0
end function
function AddOneJob self type requesturl headers values
begin
set no = length ListOfJobs
set job = cal... | #spiderjobs
#coding=utf-8
class SpiderJobs(object):
#classmemebervariables
#classmembermethods
def __init__(self):
self.ListOfJobs = []
self.CurrentJob = 0
def AddOneJob(self,type,requesturl,headers,values):
no = len(self.ListOfJobs)
j... | Python | zaydzuhri_stack_edu_python |
function insert self address socket name conn_type parent_sock=none admin=false
begin
append db dict string address address ; string socket socket ; string name name ; string type conn_type ; string last_action time ; string parent_sock parent_sock ; string password admin
end function | def insert(self, address, socket, name, \
conn_type, parent_sock = None, admin = False):
self.db.append({"address":address, "socket":socket, "name":name,\
"type":conn_type, "last_action": time.time(), "parent_sock": parent_sock,\
"password": admin}) | Python | nomic_cornstack_python_v1 |
from collections import Counter
import scipy.sparse as sp
from collections import defaultdict
import numpy as np
class Preprocessor extends object
begin
function __init__ self chunks vectorizer valid_songs=list
begin
set chunks = chunks
set vectorizer = vectorizer
set user_song_dict = default dictionary Counter
set val... | from collections import Counter
import scipy.sparse as sp
from collections import defaultdict
import numpy as np
class Preprocessor(object):
def __init__(self, chunks, vectorizer, valid_songs=[]):
self.chunks = chunks
self.vectorizer = vectorizer
self.user_song_dict = defaultdict(Counter)
... | Python | zaydzuhri_stack_edu_python |
function on_searchEdit_textChanged self txt
begin
call setEnabled boolean txt
end function | def on_searchEdit_textChanged(self, txt):
self.searchButton.setEnabled(bool(txt)) | Python | nomic_cornstack_python_v1 |
function speakers_device_idx
begin
import pyaudio
set p = call PyAudio
set device_idx = list
print string [96mList of Speakers:[0m
for i in range call get_device_count
begin
if string TF-PS1234B Stereo in call get_device_info_by_index i at string name
begin
print string call get_device_info_by_index i at string nam... | def speakers_device_idx():
import pyaudio
p = pyaudio.PyAudio()
device_idx = []
print('\033[96mList of Speakers:\033[0m')
for i in range(p.get_device_count()):
if "TF-PS1234B Stereo" in p.get_device_info_by_index(i)['name']:
print("\t", p.get_device_info_by_index(i)['name'])
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
from scipy.stats import multinomial , dirichlet
class MultinomialExpectationMaximizer
begin
function __init__ self K rtol=0.001 max_iter=100 restarts=10
begin
set _K = K
set _rtol = rtol
set _max_iter = max_iter
set _restarts = restarts
end function
function compute_log_likelihood... | import numpy as np
import pandas as pd
from scipy.stats import multinomial, dirichlet
class MultinomialExpectationMaximizer:
def __init__(self, K, rtol=1e-3, max_iter=100, restarts=10):
self._K = K
self._rtol = rtol
self._max_iter = max_iter
self._restarts = restarts
def compu... | Python | zaydzuhri_stack_edu_python |
from lxml import html
import sys , requests , os , wget
function main
begin
set url = argv at 1
set folder = base name path url
set page = get requests url
set tree = call fromstring content
set imgs = call xpath string //a[@target="_blank"][@class="fileThumb"]/@href
set num = 0
if string # in folder
begin
set folder =... | from lxml import html
import sys, requests, os, wget
def main():
url = sys.argv[1]
folder = os.path.basename(url)
page = requests.get(url)
tree = html.fromstring(page.content)
imgs = tree.xpath('//a[@target="_blank"][@class="fileThumb"]/@href')
num = 0
if "#" in folder:
folder = fo... | Python | zaydzuhri_stack_edu_python |
function _chain_to_another_future self base_future
begin
if base_future in _chained_futures_log
begin
raise call CircularFuturesChainException format string Circular Futures chain detected. Future {} is already in the resolved chain {} base_future set _chained_futures_log
end
else
begin
add _chained_futures_log base_fu... | def _chain_to_another_future(self, base_future):
if base_future in self._chained_futures_log:
raise CircularFuturesChainException(
'Circular Futures chain detected. Future {} is already in the resolved chain {}'.format(
base_future, set(self._chained_futures_log)... | Python | nomic_cornstack_python_v1 |
function main
begin
set t = integer input
for i in range t
begin
set x = call raw_input
set N = integer split x string at 0
set K = integer split x string at 1
set x = call raw_input
set lis = list
set a = split x string
for j in range N
begin
append lis integer a at j
end
set temp = sorted lis key=abs
set prod = 1
re... | def main():
t = int(input())
for i in range(t):
x = raw_input()
N = int(x.split(" ")[0])
K = int(x.split(" ")[1])
x = raw_input()
lis = []
a = x.split(" ")
for j in range(N):
lis.append(int(a[j]))
temp = sorted(lis,key=abs)
prod = 1
temp.reverse()
for j in range(K):
prod *= temp[j] | Python | zaydzuhri_stack_edu_python |
function latest_records resource layout list_id limit list_fields orderby
begin
comment orderby = resource.table[orderby]
set tuple datalist numrows ids = call datalist fields=list_fields start=none limit=limit list_id=list_id orderby=orderby layout=layout
if numrows == 0
begin
comment Empty table or just no match?
fro... | def latest_records(resource, layout, list_id, limit, list_fields, orderby):
#orderby = resource.table[orderby]
datalist, numrows, ids = resource.datalist(fields=list_fields,
start=None,
limit=limit,
... | Python | nomic_cornstack_python_v1 |
for i in range n
begin
if t at i == a at i == t at - 1 == a at 0
begin
set frag = 1
end
if 0 < i < n - 1 and t at i - 1 == t at i and a at i == a at i + 1
begin
set ans = ans * min t at i a at i % mod
end
end
print ans * frag | for i in range(n):
if t[i] == a[i] == t[-1] == a[0]:
frag = 1
if 0 < i < n - 1 and t[i - 1] == t[i] and a[i] == a[i + 1]:
ans = ans * min(t[i], a[i]) % mod
print(ans * frag)
| Python | zaydzuhri_stack_edu_python |
function avg_word_length word_list
begin
set sum = 0
set no_of_words = 0
set averg = 0
for i in word_list
begin
set sum = sum + length i
set no_of_words = no_of_words + 1
end
set averg = sum / no_of_words
end function | def avg_word_length(word_list):
sum = 0
no_of_words = 0
averg = 0
for i in word_list:
sum += len(i)
no_of_words += 1
averg = sum / no_of_words | Python | zaydzuhri_stack_edu_python |
function close self
begin
close _socket
end function | def close(self) -> None:
self._socket.close() | Python | nomic_cornstack_python_v1 |
function clear_globals
begin
global logger_name log_level
set logger_name = none
set log_level = none
end function | def clear_globals():
global logger_name, log_level
logger_name = None
log_level = None | Python | nomic_cornstack_python_v1 |
import math
from random import randrange
from collections import defaultdict
class Point
begin
function __init__ self x y
begin
set x = decimal x
set y = decimal y
set isec = false
end function
function __repr__ self
begin
if isec
begin
return call repr tuple string i x y
end
return call repr tuple x y
end function
fun... | import math
from random import randrange
from collections import defaultdict
class Point:
def __init__(self, x,y):
self.x = float(x)
self.y = float(y)
self.isec = False
def __repr__(self):
if self.isec:
return repr(("i",self.x,self.y))
return repr((self.x,sel... | Python | zaydzuhri_stack_edu_python |
function _validate_table self table
begin
set table = call as_float_array table
assert length shape == 1 msg string The table must be a 1D array!
return table
end function | def _validate_table(self, table):
table = as_float_array(table)
assert len(table.shape) == 1, 'The table must be a 1D array!'
return table | Python | nomic_cornstack_python_v1 |
function process_input input_dict UUID=none build=true
begin
comment Set calculation UUID
if UUID is not none
begin
set input_dict at string calc_key = UUID
end
else
begin
set input_dict at string calc_key = get input_dict string calc_key string uuid 4
end
comment Set default input/output units
call interpret input_dic... | def process_input(input_dict, UUID=None, build=True):
# Set calculation UUID
if UUID is not None:
input_dict['calc_key'] = UUID
else:
input_dict['calc_key'] = input_dict.get('calc_key', str(uuid.uuid4()))
# Set default input/output units
iprPy.input.subset('units').interp... | Python | nomic_cornstack_python_v1 |
class Menu
begin
function __init__ self
begin
set user = none
end function
function showMenu self
begin
print string Menu
print string 1. offer ride
print string 2. search ride
print string 3. post request
print string 4. delete request
print string 5. take request
print string 6. book member
print string 7. cancel boo... | class Menu():
def __init__(self):
self.user = None
def showMenu(self):
print('Menu')
print('1. offer ride')
print('2. search ride')
print('3. post request')
print('4. delete request')
print('5. take request')
print('6. book member')
print('... | Python | zaydzuhri_stack_edu_python |
function as_dict self
begin
set ret = dict
for field in call get_fields
begin
if is instance field WPrimitive
begin
set ret at name = call value
end
else
begin
set ret at name = call as_dict
end
end
return ret
end function | def as_dict(self):
ret = {}
for field in self.get_fields():
if isinstance(field, WPrimitive):
ret[field.name] = field.instance.value()
else:
ret[field.name] = field.as_dict()
return ret | Python | nomic_cornstack_python_v1 |
async function branch_arches group assembly ga_only=false
begin
info string Fetching group config for %s group
set group_config = await call load_group_config group=group assembly=assembly
comment Check if arches_override has been specified. This is used in group.yaml
comment when we temporarily want to build for CPU a... | async def branch_arches(group: str, assembly: str, ga_only: bool = False) -> list:
logger.info('Fetching group config for %s', group)
group_config = await load_group_config(group=group, assembly=assembly)
# Check if arches_override has been specified. This is used in group.yaml
# when we temporarily w... | Python | nomic_cornstack_python_v1 |
function test_divisor_checksum
begin
set spreadsheet = list list 5 9 2 8 list 9 4 7 3 list 3 8 6 5
assert call divisor_checksum_of_rows spreadsheet == 9
end function | def test_divisor_checksum() -> None:
spreadsheet = [
[5, 9, 2, 8],
[9, 4, 7, 3],
[3, 8, 6, 5]
]
assert sc.divisor_checksum_of_rows(spreadsheet) == 9 | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
function pmt
begin
import math
set f = open string pmt_sorted.txt string r
set num = 0
set total = 0
set result = list comprehension list comprehension - 1 for col in range 360 for row in range 180
for line in f
begin
set total = total + 1
set tuple pid z phi = split line
set z = decimal z
... | #!/usr/bin/env python
def pmt():
import math
f = open('pmt_sorted.txt','r')
num=0
total=0
result=[[-1 for col in range(360)] for row in range(180)]
for line in f:
total=total+1
(pid,z,phi) = line.split()
z=float(z)
phi=float(phi)
z=math.acos(z/19500) ... | Python | zaydzuhri_stack_edu_python |
comment import board
comment import pieces
import random
import chess
import bot
import dumbbot
import Tkinter as tk
from PIL import Image , ImageTk
class BoardGuiTk extends Frame
begin
set pieces = dict
set selected = none
set selected_piece = - 1
set hilighted = list
set icons = dict
set color1 = string white
set ... | #import board
#import pieces
import random
import chess
import bot
import dumbbot
import Tkinter as tk
from PIL import Image, ImageTk
class BoardGuiTk(tk.Frame):
pieces = {}
selected = None
selected_piece = -1
hilighted = []
icons = {}
color1 = "white"
color2 = "grey"
rows = 8
co... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import __init__
from utils.activation import sigmoid
function layer_size X Y
begin
string Returns layer sizes Arguments: X : input dataset of shape (input size, number of examples) Y : labels of shape(output size, number of examples)
set n_x = shape at 0
comment default is set to 4
set n_h = 4
set n_... | import numpy as np
import __init__
from utils.activation import sigmoid
def layer_size(X, Y):
'''
Returns layer sizes
Arguments:
X : input dataset of shape (input size, number of examples)
Y : labels of shape(output size, number of examples)
'''
n_x = X.shape[0]
n_h = 4 #defa... | Python | zaydzuhri_stack_edu_python |
import re
comment ilopoihsh sunarthshs pou tha kaleite meso ths sub kai tha epistrefei to antistoixo string kathe fora analoga me to teriasma pou exei ginei
function myfunction m
begin
if call group 0 == string &
begin
return string &
end
else
if call group 0 == string >
begin
return string >
end
else
if call gr... | import re
def myfunction(m): #ilopoihsh sunarthshs pou tha kaleite meso ths sub kai tha epistrefei to antistoixo string kathe fora analoga me to teriasma pou exei ginei
if (m.group(0)=='&'):
return '&'
elif (m.group(0)=='>'):
return '>'
elif (m.group(0)=='<'):
return '<'
... | Python | zaydzuhri_stack_edu_python |
comment 1 부터 n 까지의 합을 구하는 재귀 호출
comment 입력: n
comment 출력: 1 부터 n 까지의 합
function recursion_sum n
begin
set sum = n
if n == 1
begin
return 1
end
return sum + call recursion_sum n - 1
end function
print call recursion_sum 10 | # 1 부터 n 까지의 합을 구하는 재귀 호출
# 입력: n
# 출력: 1 부터 n 까지의 합
def recursion_sum(n):
sum = n
if n == 1:
return 1
return sum + recursion_sum(n - 1)
print(recursion_sum(10)) | Python | zaydzuhri_stack_edu_python |
comment Application TODO : Ajouter une tâche / Supprimer une tâche / Evaluer la charge de travail
set TacheTab = list
set AjouterTache = string 1
set SupprimerTache = string 2
set ListerTache = string 3
set i = 0
set n = 0
set Tache = 0
while true
begin
set SaisieUser = input string Que voulez-vous faire ? Ajouter : 1... | #Application TODO : Ajouter une tâche / Supprimer une tâche / Evaluer la charge de travail
TacheTab = []
AjouterTache = "1"
SupprimerTache = "2"
ListerTache = "3"
i = 0
n = 0
Tache = 0
while True:
SaisieUser = input("Que voulez-vous faire ? Ajouter : 1, Supprimer : 2, Lister : 3 une(des) tâche(s) : ")
print(Sa... | Python | zaydzuhri_stack_edu_python |
function load_dict file_name=none
begin
set file = open file_name string r
set data = load json file
close file
return data
end function
comment df = pd.read_csv(filepath_or_buffer=file_name)
comment print(df)
comment return df.to_dict() | def load_dict(file_name=None):
file = open(file_name, "r")
data = json.load(file)
file.close()
return data
# df = pd.read_csv(filepath_or_buffer=file_name)
# print(df)
# return df.to_dict() | Python | nomic_cornstack_python_v1 |
from couchdbkit import BadValueError
from couchdbkit.ext.django.schema import Document , StringProperty , IntegerProperty , StringListProperty , Property , DocumentSchema , SchemaListProperty , ListProperty , BooleanProperty
from django.conf import settings
from datetime import datetime , date
import sqlalchemy
import ... | from couchdbkit import BadValueError
from couchdbkit.ext.django.schema import (Document, StringProperty, IntegerProperty, StringListProperty, Property,
DocumentSchema, SchemaListProperty, ListProperty, BooleanProperty)
from django.conf import settings
from datetime import datet... | Python | zaydzuhri_stack_edu_python |
function reset_data self
begin
set num_clicks = 0
set num_of_tries = 0
set num_of_match = 0
set score = 100
set pic = list
set image_id = list
comment list of the clicked tile_id
set click_tiles = list
set new_list = call shuffle_list
end function | def reset_data(self):
self.num_clicks = 0
self.num_of_tries = 0
self.num_of_match = 0
self.score = 100
self.pic = []
self.image_id = []
self.click_tiles = [] # list of the clicked tile_id
self.new_list = self.shuffle_list() | Python | nomic_cornstack_python_v1 |
function writes notebook fmt version=NO_CONVERT **kwargs
begin
string Write a notebook to a string
set metadata = deep copy metadata
call rearrange_jupytext_metadata metadata
set fmt = copy fmt
set fmt = call long_form_one_format fmt metadata
set ext = fmt at string extension
set format_name = get fmt string format_nam... | def writes(notebook, fmt, version=nbformat.NO_CONVERT, **kwargs):
"""Write a notebook to a string"""
metadata = deepcopy(notebook.metadata)
rearrange_jupytext_metadata(metadata)
fmt = copy(fmt)
fmt = long_form_one_format(fmt, metadata)
ext = fmt['extension']
format_name = fmt.get('format_nam... | Python | jtatman_500k |
function create_dictionary my_list
begin
set res = dictionary comprehension num : num * 2 for num in my_list
return res
end function
comment run the code
set my_list = list 3 5 7
set res = call create_dictionary my_list
print string The dictionary is + string res | def create_dictionary(my_list):
res = {num: num * 2 for num in my_list}
return res
# run the code
my_list = [3, 5, 7]
res = create_dictionary(my_list)
print('The dictionary is ' + str(res)) | Python | jtatman_500k |
function sync self
begin
string synchronize self from Ariane server according its id (prioritary) or name :return:
debug string Subnet.sync
set params = none
if id is not none
begin
set params = dict string id id
end
else
if name is not none
begin
set params = dict string name name
end
if params is not none
begin
set a... | def sync(self):
"""
synchronize self from Ariane server according its id (prioritary) or name
:return:
"""
LOGGER.debug("Subnet.sync")
params = None
if self.id is not None:
params = {'id': self.id}
elif self.name is not None:
params... | Python | jtatman_500k |
function get_file_chunks self
begin
set raw_content = call get_file_content
if raw_content == ERR
begin
return ERR
end
set file_chunks = call split_file raw_content
end function | def get_file_chunks(self):
raw_content = self.get_file_content()
if raw_content == ERR:
return ERR
self.file_chunks = self.split_file(raw_content) | Python | nomic_cornstack_python_v1 |
function calculateSum n
begin
if n <= 0
begin
return 0
end
else
begin
return n + call calculateSum n - 1
end
end function
set result = call calculateSum 5
print result | def calculateSum(n):
if n <= 0:
return 0
else:
return n + calculateSum(n-1)
result = calculateSum(5)
print(result)
| Python | flytech_python_25k |
function revert_output_preprocessing self output
begin
return exp output
end function | def revert_output_preprocessing(self, output):
return np.exp(output) | Python | nomic_cornstack_python_v1 |
string Created on 16 Aug 2013 @author: hicksj
import unittest
from reports.averagesreport import BowlerInReport , BatsmanInReport , AveragesReportGenerator
from xml.etree import ElementTree
import string
import datetime
from operator import itemgetter
class Test extends TestCase
begin
function getTestXml self leagueCou... | '''
Created on 16 Aug 2013
@author: hicksj
'''
import unittest
from reports.averagesreport import BowlerInReport, BatsmanInReport,\
AveragesReportGenerator
from xml.etree import ElementTree
import string
import datetime
from operator import itemgetter
class Test(unittest.TestCase):
def getTest... | Python | zaydzuhri_stack_edu_python |
function remove_interactions_from self interactions
begin
for tuple u v in interactions
begin
call remove_interaction u v
end
end function | def remove_interactions_from(self, interactions: Iterable):
for u, v in interactions:
self.remove_interaction(u, v) | Python | nomic_cornstack_python_v1 |
comment Filename: mookwl_P2Q6
comment Name: Marcus Mook Wei Lun
comment Description: Sorts 3 integers from largest to smallest
comment Prompt user to enter 3 integers
set a = integer input string Enter 1st integer:
set b = integer input string Enter 2nd integer:
set c = integer input string Enter 3rd integer:
comment D... | # Filename: mookwl_P2Q6
# Name: Marcus Mook Wei Lun
# Description: Sorts 3 integers from largest to smallest
# Prompt user to enter 3 integers
a = int(input("Enter 1st integer:"))
b = int(input("Enter 2nd integer:"))
c = int(input("Enter 3rd integer:"))
# Display result
if a>b>c :
print(a, b, c)
elif a>c>b :
p... | Python | zaydzuhri_stack_edu_python |
comment !/user / bin / python
set tuple a b c = tuple 1 20.2 string Python Programming
print a
print b
print c | #!/user / bin / python
a, b, c = 1, 20.2, "Python Programming"
print(a)
print(b)
print(c) | Python | zaydzuhri_stack_edu_python |
function get_origins self
begin
set origins = list
for stream in self
begin
set origins = origins + list origin
if get attribute self string _warnings true
begin
if origin != origin
begin
warn string Different streams in the Dataset correpond to different events. This may be intentional. Feel free to disable this warn... | def get_origins(self):
origins = []
for stream in self:
origins += [stream.origin]
if getattr(self, '_warnings', True):
if stream.origin!=self[0].origin:
warnings.warn(
"Different streams in the Dataset correpond to "
... | Python | nomic_cornstack_python_v1 |
function set_up self
begin
set tuple _stacks remote_stack_full_paths = call get_stacks _template_file parameter_overrides=_parameter_overrides global_parameter_overrides=_global_parameter_overrides
if remote_stack_full_paths
begin
warning string Below nested stacks(s) specify non-local URL(s), which are unsupported: %s... | def set_up(self) -> None:
self._stacks, remote_stack_full_paths = SamLocalStackProvider.get_stacks(
self._template_file,
parameter_overrides=self._parameter_overrides,
global_parameter_overrides=self._global_parameter_overrides,
)
if remote_stack_full_paths:
... | Python | nomic_cornstack_python_v1 |
comment 实现深入浅出强化学习:原理入门中Page 35的迷宫构建
comment 首先,导入库文件(包括gym模块和gym中的渲染模块)
import gym
import time
import random , copy
from gym.envs.classic_control import rendering
set tuple UP DOWN LEFT RIGHT = tuple 0 1 2 3
comment 我们生成一个类,该类继承 gym.Env. 同时,可以添加元数据,改变渲染环境时的参数
class MazeEnv extends Env
begin
comment 如果你不想改参数,下面可以不用写
se... | # 实现深入浅出强化学习:原理入门中Page 35的迷宫构建
# 首先,导入库文件(包括gym模块和gym中的渲染模块)
import gym
import time
import random, copy
from gym.envs.classic_control import rendering
UP, DOWN, LEFT, RIGHT = 0, 1, 2, 3
# 我们生成一个类,该类继承 gym.Env. 同时,可以添加元数据,改变渲染环境时的参数
class MazeEnv(gym.Env):
# 如果你不想改参数,下面可以不用写
metadata = {
'render.mod... | Python | zaydzuhri_stack_edu_python |
import heapq
import math
function locationFinding V E orientation cur_x cur_y heading map_cor
begin
set map_heading = heading + orientation
if map_heading > 360
begin
set map_heading = map_heading % 360
end
set distpq = list
for i in range 1 V + 1
begin
call heappush distpq tuple square root map_cor at i at 0 - cur_x ... | import heapq
import math
def locationFinding(V, E, orientation, cur_x, cur_y, heading, map_cor):
map_heading = heading + orientation
if map_heading > 360:
map_heading = map_heading%360
distpq = []
for i in range(1, V+1):
heapq.heappush(distpq, (math.sqrt((map_cor[i][0] - cur_x) ** 2 + ... | Python | zaydzuhri_stack_edu_python |
function protected
begin
set user : User = call current_user
set urlparse = url parse icon
if length scheme > 0
begin
set icon = icon
end
else
begin
set icon = url_root + string static/ + icon
end
set user_obj = dict string id id ; string username username ; string nickname nickname ; string twitter_screenname twitter_... | def protected():
user: User = flask_praetorian.current_user()
urlparse = urllib.parse.urlparse(user.icon)
if len(urlparse.scheme) > 0:
icon = user.icon
else:
icon = request.url_root+"static/"+user.icon
user_obj = {
"id": user.id,
"username": user.username,
"ni... | Python | nomic_cornstack_python_v1 |
function center_of_mass nuc_labels nuc_coords units=string bohr
begin
if length nuc_labels != length nuc_coords
begin
raise call ValueError string 'nuc_labels' and 'nuc_coords' do not match.
end
set masses = list map isotopic_mass nuc_labels
set coords = call coordinates_in_bohr nuc_coords units=units
return sum genera... | def center_of_mass(nuc_labels, nuc_coords, units="bohr"):
if len(nuc_labels) != len(nuc_coords):
raise ValueError("'nuc_labels' and 'nuc_coords' do not match.")
masses = list(map(_constants.isotopic_mass, nuc_labels))
coords = coordinates_in_bohr(nuc_coords, units=units)
return sum(m * r for m, ... | Python | nomic_cornstack_python_v1 |
from django.test import TestCase
from tasks.models import Task
from tasks.serializers import TaskDetailSerializer
from django.contrib.auth.models import User
from datetime import datetime , timedelta , timezone
from django.utils.timezone import utc
import logging
set logger = call getLogger string serializers
class Tas... | from django.test import TestCase
from tasks.models import Task
from tasks.serializers import TaskDetailSerializer
from django.contrib.auth.models import User
from datetime import datetime, timedelta, timezone
from django.utils.timezone import utc
import logging
logger = logging.getLogger("serializers")
class TaskSer... | Python | zaydzuhri_stack_edu_python |
function getInterfaces self node
begin
if handle
begin
set cmd = string py "\n".join(["name=%s,mac=%s,ip=%s,enabled=%s" + string % (i.name, i.MAC(), i.IP(), i.isUp())
set cmd = cmd + string for i in %s.intfs.values()]) % node
try
begin
set response = execute self cmd=cmd prompt=string mininet> timeout=10
end
except EOF... | def getInterfaces( self, node ):
if self.handle:
cmd = 'py "\\n".join(["name=%s,mac=%s,ip=%s,enabled=%s"' +\
' % (i.name, i.MAC(), i.IP(), i.isUp())'
cmd += ' for i in %s.intfs.values()])' % node
try:
response = self.execute(
... | Python | nomic_cornstack_python_v1 |
string O(NM), N<=1000, M<=100 역시 문자열처리 문제. 집중해서 문자열 인덱스, 정렬 처리를 신경쓰면 별로 어렵지 않은 문제였다.
function solution files
begin
set newFiles = list
for file in files
begin
set tuple i j = tuple - 1 - 1
for tuple idx c in enumerate file
begin
if is digit c and i == - 1
begin
set i = idx
end
if idx == length file - 1
begin
set j = i... | """
O(NM), N<=1000, M<=100
역시 문자열처리 문제. 집중해서 문자열 인덱스, 정렬 처리를 신경쓰면 별로 어렵지 않은 문제였다.
"""
def solution(files):
newFiles = []
for file in files:
i, j = -1, -1
for idx, c in enumerate(file):
if c.isdigit() and i == -1:
i = idx
if idx == len(file) - 1:
... | Python | zaydzuhri_stack_edu_python |
function LocalExists self
begin
return call is_dir
end function | def LocalExists(self) -> bool:
return pathlib.Path(self.local_path).is_dir() | Python | nomic_cornstack_python_v1 |
function find_max_element_idx arr
begin
string This function takes in an array 'arr' and returns the index of the maximum element in the array. Args: arr: A list of integers. Returns: max_idx: An integer representing the index of the maximum element in the array.
comment Assume the first element as the maximum
set max_... | def find_max_element_idx(arr):
"""
This function takes in an array 'arr' and returns the index of the maximum element in the array.
Args:
arr: A list of integers.
Returns:
max_idx: An integer representing the index of the maximum element in the array.
"""
max_num = arr[0] # Assume th... | Python | greatdarklord_python_dataset |
function notngc self
begin
return boolean _notngc
end function | def notngc(self) -> bool:
return bool(self._notngc) | Python | nomic_cornstack_python_v1 |
import pandas as pd
from collections import Counter
from datetime import datetime
from nltk.tokenize import TweetTokenizer
import csv
comment ----------------------------build_df(filepath)------------------------------------
comment build a dataframe containing columns "word" and "occurence" from a vocabulary.
comment ... | import pandas as pd
from collections import Counter
from datetime import datetime
from nltk.tokenize import TweetTokenizer
import csv
#----------------------------build_df(filepath)------------------------------------
#build a dataframe containing columns "word" and "occurence" from a vocabulary.
# filepath : the path... | Python | zaydzuhri_stack_edu_python |
from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import urllib
from urllib.request import urlopen
from lxml import html
import nltk
comment This code searches the html of a specific instagram page and relays the information.
function post_scan
begin
string url = "https://www.instagram.co... | from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import urllib
from urllib.request import urlopen
from lxml import html
import nltk
# This code searches the html of a specific instagram page and relays the information.
def post_scan():
"""url = "https://www.instagram.com/p... | Python | zaydzuhri_stack_edu_python |
function play_pass s n
begin
set n = n % 26
set resultList = list
for i in range length s
begin
if ordinal string A <= ordinal s at i <= ordinal string Z
begin
set letterByte = ordinal s at i + n
if letterByte > ordinal string Z
begin
set letterByte = letterByte - 26
end
if i % 2 == 1
begin
append resultList lower cha... | def play_pass(s, n):
n = n % 26
resultList = []
for i in range(len(s)):
if ord('A') <= ord(s[i]) <= ord('Z'):
letterByte = ord(s[i]) + n
if letterByte > ord('Z'):
letterByte -= 26
if i % 2 == 1:
resultList.append(chr(letterByte).low... | Python | zaydzuhri_stack_edu_python |
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import MySQLdb
set app = call Flask __name__
set config at string SQLALCHEMY_DATABASE_URI = string mysql://north:starwars@127.0.0.1/north_bay
set db = call SQLAlchemy app
class Person extends Model
begin
set __tablename__ = string people
set id = call ... | from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
import MySQLdb
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://north:starwars@127.0.0.1/north_bay'
db = SQLAlchemy(app)
class Person(db.Model):
__tablename__ = 'people'
id = db.Column(db.Integer, primary_key=True)
... | Python | zaydzuhri_stack_edu_python |
string Library intended for finding differences in har files The idea is that one would import this module in the Python REPL and use it to get information about requests that fail in one har file, but succeed in another. This allows me to fix requests that fail in the mock server. This is designed to fit my needs and ... | """
Library intended for finding differences in har files
The idea is that one would import this module in the Python REPL and use
it to get information about requests that fail in one har file, but
succeed in another. This allows me to fix requests that fail in the
mock server.
This is designed to fit my needs and ... | Python | zaydzuhri_stack_edu_python |
function is_in_square self row col number
begin
set square_nb_col = integer col / 3
set square_nb_row = integer row / 3
set sub_grid = call get_square square_nb_col square_nb_row
return any sub_grid == number
end function | def is_in_square(self, row, col, number):
square_nb_col = int(col/3)
square_nb_row = int(row/3)
sub_grid = self.get_square(square_nb_col, square_nb_row)
return np.any(sub_grid == number) | Python | nomic_cornstack_python_v1 |
function test_valid_filters self
begin
call reset_bluetooth android_devices
set settings = list dict string mode value
set params = list product valid_filter_suite settings
set failed = call run_generated_testcases _magic params tag=string valid_filters
if failed
begin
return false
end
return true
end function | def test_valid_filters(self):
reset_bluetooth(self.android_devices)
settings = [
{'mode':
AdvertiseSettingsAdvertiseMode.ADVERTISE_MODE_LOW_LATENCY.value}
]
params = list(it.product(self.valid_filter_suite, settings))
failed = self.run_generated_testcases... | Python | nomic_cornstack_python_v1 |
from __future__ import annotations
from adt_impl.linkedlist_deque import Node
from adt_impl.deque_interface import DequeInterface
class DoubleNode extends Node
begin
function __init__ self data next prev
begin
call __init__ data next
set prev = prev
if next is not none
begin
set prev = self
end
if prev is not none
begi... | from __future__ import annotations
from adt_impl.linkedlist_deque import Node
from adt_impl.deque_interface import DequeInterface
class DoubleNode(Node):
def __init__(self, data: object, next: DoubleNode, prev: DoubleNode):
super().__init__(data, next)
self.prev = prev
if self.next is not... | Python | zaydzuhri_stack_edu_python |
function version self version
begin
set _version = version
end function | def version(self, version):
self._version = version | 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.