code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_items self
begin
set size = list max_len + canvas_shape
set stack_elements = zeros size dtype=bool
set length = length items
for j in range length
begin
set stack_elements at tuple j slice : : slice : : slice : : = items at j
end
return stack_elements
end function | def get_items(self):
size = [self.max_len] + self.canvas_shape
stack_elements = np.zeros(size, dtype=bool)
length = len(self.items)
for j in range(length):
stack_elements[j, :, :, :] = self.items[j]
return stack_elements | Python | nomic_cornstack_python_v1 |
async function export_psbt psbt
begin
comment don't display a QR code larger than CHUNK_SIZE bytes
set CHUNK_SIZE = 200
set chunked = list comprehension psbt at slice i : i + CHUNK_SIZE : for i in range 0 length psbt CHUNK_SIZE
comment get chunk of bytes, convert to base64 bytes and decode to string
set i = 0
while tr... | async def export_psbt(psbt):
CHUNK_SIZE = 200 # don't display a QR code larger than CHUNK_SIZE bytes
chunked = [
# get chunk of bytes, convert to base64 bytes and decode to string
psbt[i: i + CHUNK_SIZE]
for i in range(0, len(psbt), CHUNK_SIZE)
]
i = 0
while True:
ms... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string ******************************** @Time :2019/9/10 17:35 @Author :gaoliang @Email :337901080@qq.com @File :handle_mysql.py @Software :PyCharm ********************************
import random
import pymysql
from scripts.handle_config import do_config
class HandleMysql
begin
string 处理mys... | # -*- coding: utf-8 -*-
"""
********************************
@Time :2019/9/10 17:35
@Author :gaoliang
@Email :337901080@qq.com
@File :handle_mysql.py
@Software :PyCharm
********************************
"""
import random
import pymysql
from scripts.handle_config import do_config
class Han... | Python | zaydzuhri_stack_edu_python |
function get_filters city month day
begin
print string Hello! Let's explore major US bikeshare data!
print string
comment Get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
sleep 1
while true
begin
print string Which city bikeshare data would you like to explor... | def get_filters(city, month, day):
print ('Hello! Let\'s explore major US bikeshare data!')
print ('')
#Get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
t.sleep(1)
while True:
print ("Which city bikeshare data would you like to exp... | Python | nomic_cornstack_python_v1 |
function get_title_map self world_movies world
begin
set title_gen = call titles_generator world_movies world
for movie in title_gen
begin
append title_map at lower strip movie at string Title movie
end
end function | def get_title_map(self, world_movies, world):
title_gen = self.titles_generator(world_movies, world)
for movie in title_gen:
self.title_map[movie['Title'].strip().lower()].append(movie) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import numpy as np
from sys import *
from distances import get_distance_matrix
import matplotlib as plt
import matplotlib.pyplot as plt
import math
function lee_fichero fichero
begin
set matriz = list
set fichero = open fichero string r
set lineas = read lines fichero
set matriz = list co... | # -*- coding: utf-8 -*-
import numpy as np
from sys import *
from distances import get_distance_matrix
import matplotlib as plt
import matplotlib.pyplot as plt
import math
def lee_fichero(fichero):
matriz = []
fichero = open(fichero,"r")
lineas = fichero.readlines()
matriz = [linea.split(... | Python | zaydzuhri_stack_edu_python |
import math , collections
class StupidBackoffLanguageModel
begin
function __init__ self corpus
begin
string Initialize your data structures in the constructor.
set unigramCounts = dict
set bigramCounts = dict
train self corpus
end function
function train self corpus
begin
string Takes a corpus and trains your languag... | import math, collections
class StupidBackoffLanguageModel:
def __init__(self, corpus):
"""Initialize your data structures in the constructor."""
self.unigramCounts = {}
self.bigramCounts = {}
self.train(corpus)
def train(self, corpus):
""" Takes a corpus and trains your language model.
Compute any cou... | Python | zaydzuhri_stack_edu_python |
string This module provides functions to handle input and output files. Functions: read_datasets
import pandas as pd
import numpy as np
import json
import sys
append path string ../
from scr import recommendation
function read_datasets
begin
string Read csv input files into data frames :return: df: (pandas dataframe) M... | """This module provides functions to handle input and output files.
Functions:
read_datasets
"""
import pandas as pd
import numpy as np
import json
import sys
sys.path.append("../")
from scr import recommendation
def read_datasets():
"""Read csv input files into data frames
:return:
df: (panda... | Python | zaydzuhri_stack_edu_python |
string 相册信息请求器 暴露的接口 :->load_album_data(inthread:bool=False,tp:ThreadPool=None) 加载相册信息(进行多次请求(阻塞)(可否异步?)) 可定义异步魔法方法处理 :->download_images(in_thread:bool=False,tp:ThreadPool=None) 将下载任务添加到线程池 :->adownload_image()->list[Awaitable] 异步请求器(不知道有没有用) 生成图片的异步列表 :->is_fit_tags(*tags:str) 是否符合提供标签 可以更多,不能更少
from concurrent.future... | """
相册信息请求器
暴露的接口
:->load_album_data(inthread:bool=False,tp:ThreadPool=None)
加载相册信息(进行多次请求(阻塞)(可否异步?))
可定义异步魔法方法处理
:->download_images(in_thread:bool=False,tp:ThreadPool=None)
将下载任务添加到线程池
:->adownload_image()->list[Awaitable]
异步请求器(不知道有没有用)
生成图片的异步列表
:->is_fit_tags(*tags:str)
是否符合提供标签
可以更多,不... | Python | zaydzuhri_stack_edu_python |
from numpy import *
comment OR :- a = onse(5.dtype= int)
set a = ones 5
set n = length a
for i in range n
begin
print a at i
end | from numpy import*
a = ones(5) # OR :- a = onse(5.dtype= int)
n = len(a)
for i in range(n):
print(a[i]) | Python | zaydzuhri_stack_edu_python |
function findContactByPhone self phone
begin
return list comprehension ctct for ctct in contactDatabase if phone == phone
end function | def findContactByPhone(self, phone):
return [ctct for ctct in self.contactDatabase if ctct.phone == phone] | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import os
from string import Template
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
set CHROME_OPTIONS = options
call add_argument string --headless
set binary_location = string /Applications/Google Chrome.app/Contents/Mac... | #!/usr/bin/env python
import os
from string import Template
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
CHROME_OPTIONS = Options()
CHROME_OPTIONS.add_argument('--headless')
CHROME_OPTIONS.binary_location = '/Applications/Google Chrome.app/Contents/... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Aug 12 20:21:29 2020 @author: lenovo list
string list
set fruits = list string banana string apple string guava
print fruits
print type fruits
comment <class 'list'>
print length fruits
string append list allows duplicate values
append fruits string mango
print string... | # -*- coding: utf-8 -*-
"""
Created on Wed Aug 12 20:21:29 2020
@author: lenovo
list
"""
'''
list
'''
fruits=['banana','apple','guava']
print(fruits)
print(type(fruits))
#<class 'list'>
print(len(fruits))
'''
append
list allows duplicate values
'''
fruits.append('mango')
print('after append ',fruits)
fruits.append(... | Python | zaydzuhri_stack_edu_python |
function poll self timeout_ms=0 max_records=none
begin
set messages = poll consumer timeout_ms=timeout_ms max_records=max_records
set result = list
for tuple _ msg in items messages
begin
for item in msg
begin
append result item
end
end
return result
end function | def poll(self, timeout_ms=0, max_records=None):
messages = self.consumer.poll(timeout_ms=timeout_ms, max_records=max_records)
result = []
for _, msg in messages.items():
for item in msg:
result.append(item)
return result | Python | nomic_cornstack_python_v1 |
function mode x
begin
set tuple vals counts = unique x return_counts=true
if has attribute vals string __len__
begin
return vals at argument maximum counts
end
else
begin
return vals
end
end function | def mode(x: Sequence):
vals, counts = np.unique(x, return_counts=True)
if hasattr(vals, "__len__"):
return vals[np.argmax(counts)]
else:
return vals | Python | nomic_cornstack_python_v1 |
import pprint
from datetime import datetime
set s = string This is my first python's coversion program
print string
print s
print string
print title s
print string
comment how to use datetime module with string format specifiers
function convert2ampm time24
begin
return string format time string parse time time24 strin... | import pprint
from datetime import datetime
s = "This is my first python's coversion program"
print("")
print(s)
print("")
print(s.title())
print("")
# how to use datetime module with string format specifiers
def convert2ampm(time24: str) -> str:
return datetime.strptime(time24, '%H:%M').strftime('%I:%M%p')
c... | Python | zaydzuhri_stack_edu_python |
function add_journal request journal_id=none
begin
set user_collections = call get_user_collections id
if journal_id is none
begin
set journal = call Journal
end
else
begin
set journal = call get_object_or_404 Journal id=journal_id
end
set form_hash = none
set JournalTitleFormSet = call inlineformset_factory Journal Jo... | def add_journal(request, journal_id=None):
user_collections = models.get_user_collections(request.user.id)
if journal_id is None:
journal = models.Journal()
else:
journal = get_object_or_404(models.Journal, id=journal_id)
form_hash = None
JournalTitleFormSet = inlineformset_facto... | Python | nomic_cornstack_python_v1 |
from math import ceil
function new_avg arr newavg
begin
set result = ceil newavg * length arr + 1 - sum arr
if result > 0
begin
return result
end
else
begin
raise ValueError
end
end function | from math import ceil
def new_avg(arr, newavg):
result = ceil(newavg * (len(arr) + 1) - sum(arr))
if result > 0:
return result
else:
raise ValueError | Python | zaydzuhri_stack_edu_python |
function contents_type self
begin
return get pulumi self string contents_type
end function | def contents_type(self) -> pulumi.Input[str]:
return pulumi.get(self, "contents_type") | Python | nomic_cornstack_python_v1 |
import StatTesting as stat
from StatTesting import pd
comment import pandas as pd
comment pd.set_option('display.unicode.ambiguous_as_wide', True)
comment pd.set_option('display.unicode.east_asian_width', True)
comment pd.set_option('display.width', 180)
set analysis_data = call read_excel string 時間序列分析資料.xlsx
drop ana... | import StatTesting as stat
from StatTesting import pd
# import pandas as pd
# pd.set_option('display.unicode.ambiguous_as_wide', True)
# pd.set_option('display.unicode.east_asian_width', True)
# pd.set_option('display.width', 180)
analysis_data = pd.read_excel("時間序列分析資料.xlsx")
analysis_data.drop("Unnamed: 0",axis=1... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense , Dropout , TimeDistributed , Conv1D , GRU , BatchNormalization , Activation , LSTM , Reshape
import matplotlib.pyplot as plt
import numpy as np
import os
from sklearn.metrics import classification_report
comment Deactivate the G... | import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout, TimeDistributed, Conv1D, GRU, BatchNormalization, Activation, LSTM, Reshape
import matplotlib.pyplot as plt
import numpy as np
import os
from sklearn.metrics import classification_report
# Deactivate the GPU
# os.envi... | Python | zaydzuhri_stack_edu_python |
comment Kyle O'Donnell
comment CISC 481
comment HW 4 - Q-Learning
import random
comment Class for a square on the board, contains useful information on rewards, Q-values, and type of square
class Square
begin
function __init__ self loc s_type reward
begin
set loc = loc
set s_type = s_type
set north = 0
set south = 0
se... | # Kyle O'Donnell
# CISC 481
# HW 4 - Q-Learning
import random
# Class for a square on the board, contains useful information on rewards, Q-values, and type of square
class Square:
def __init__(self, loc, s_type, reward):
self.loc = loc
self.s_type = s_type
self.north = 0
... | Python | zaydzuhri_stack_edu_python |
function _composite_files self files_by_position frame_start frame_end filename_template output_dir
begin
debug string Preparing files for compisiting.
comment Prepare paths to images by frames into list where are stored
comment in order of compositing.
set images_by_frame = dict
for frame_idx in range frame_start fra... | def _composite_files(
self, files_by_position, frame_start, frame_end,
filename_template, output_dir
):
self.log.debug("Preparing files for compisiting.")
# Prepare paths to images by frames into list where are stored
# in order of compositing.
images_by_frame = {}
... | Python | nomic_cornstack_python_v1 |
class Node
begin
function __init__ self data
begin
set data = data
set next = none
end function
end class
class Linked_list
begin
function __init__ self
begin
set head = none
end function
function append self data
begin
set new_node = call Node data
set curr_node = head
if curr_node is none
begin
set head = new_node
en... | class Node:
def __init__(self,data):
self.data=data
self.next=None
class Linked_list:
def __init__(self):
self.head=None
def append(self,data):
new_node=Node(data)
curr_node=self.head
if curr_node is None:
self.head=new_node
else:
... | Python | zaydzuhri_stack_edu_python |
function _configureOrbits self orbits t0 orbit_type time_scale magnitude slope
begin
set orbits_ = copy orbits
if shape == tuple 6
begin
set num_orbits = 1
end
else
begin
set num_orbits = shape at 0
end
if orbit_type == string cartesian
begin
set orbit_type = list comprehension 1 for i in range num_orbits
end
else
if o... | def _configureOrbits(self, orbits, t0, orbit_type, time_scale, magnitude, slope):
orbits_ = orbits.copy()
if orbits_.shape == (6,):
num_orbits = 1
else:
num_orbits = orbits_.shape[0]
if orbit_type == "cartesian":
orbit_type = [1 for i in range(num_orb... | Python | nomic_cornstack_python_v1 |
comment LeNet lab solution from Udacity Self Driving Card ND
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import random
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
function load_mnist_and_pad_with_zeros
begin
set mnist = call read_data_sets ... | # LeNet lab solution from Udacity Self Driving Card ND
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import random
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
def load_mnist_and_pad_with_zeros():
mnist = input_data.read_data_sets('MNIST_dat... | Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
comment class TreeNode:
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Solution
begin
function maxPathSum self root
begin
set ans = - decimal string inf
search root
return ans
end function
function search self node
... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxPathSum(self, root: TreeNode) -> int:
self.ans = -float('inf')
self.search(root)
return self.ans
def s... | Python | zaydzuhri_stack_edu_python |
function __frontend_limit_rules_descriptor self api_info
begin
string Builds a frontend limit rules descriptor from API info. Args: api_info: An _ApiInfo object. Returns: A list of dictionaries with frontend limit rules information.
if not rules
begin
return none
end
set rules = list
for rule in rules
begin
set descri... | def __frontend_limit_rules_descriptor(self, api_info):
"""Builds a frontend limit rules descriptor from API info.
Args:
api_info: An _ApiInfo object.
Returns:
A list of dictionaries with frontend limit rules information.
"""
if not api_info.frontend_limits.rules:
return None
... | Python | jtatman_500k |
function game_over self
begin
remove datos at string baraja datos at string baraja at 0
while true
begin
for event in get event
begin
if type == QUIT
begin
set exit = false
call send encode string desconectado
close player
exit
end
if type == MOUSEBUTTONDOWN
begin
if call colliderect rect
begin
call inicializar
end
end... | def game_over(self):
self.datos['baraja'].remove(self.datos['baraja'][0])
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.exit = False
self.player.send("desconectado".encode())
self.pl... | Python | nomic_cornstack_python_v1 |
function test_avg_database_time self
begin
set time = call timeit string post("http://127.0.0.1:5000/database?format=json&merge=0", data='{"RUR": 1.0, "EUR": 2.0, "USD": 3.0}') number=1000 globals=globals
print time / 1000 end=string flush=true
end function | def test_avg_database_time(self):
time = timeit(
'''post("http://127.0.0.1:5000/database?format=json&merge=0",\
data='{"RUR": 1.0, "EUR": 2.0, "USD": 3.0}')''',
number=1000,
globals=globals())
print(time/1000, end=' ', flush=True) | Python | nomic_cornstack_python_v1 |
import requests
function get_max_intel
begin
string Получение информации о герое с максимальным интеллектом
comment список для теста
comment names = ['Hulk', 'Captain America', 'Thanos', 'Loki']
comment при тестировании закомментить строки 8-11
set name = input string Введите имена героев через запятую:
set names = lis... | import requests
def get_max_intel():
"""Получение информации о герое с максимальным интеллектом"""
#список для теста
# names = ['Hulk', 'Captain America', 'Thanos', 'Loki']
#при тестировании закомментить строки 8-11
name = input('Введите имена героев через запятую: ')
names = []
names.ext... | Python | zaydzuhri_stack_edu_python |
function fingerprint_func self
begin
set fingerprint = call fingerprint_file path
set line = fingerprint
set line = string line
set line_word = string
set after_word = string ')
set before_word = string , '
set num = 1
call lines_func
call duration_func
end function | def fingerprint_func(self):
fingerprint = acoustid.fingerprint_file(self.path)
self.line = fingerprint
self.line = str(self.line)
self.line_word = ""
self.after_word = "')"
self.before_word = ", '"
self.num = 1
self.lines_func()
self.duration_func() | Python | nomic_cornstack_python_v1 |
async function role_rin self ctx target_role remove_role
begin
await call super_massrole ctx list comprehension member for member in members remove_role string No one in ` { target_role } ` has this role. false
end function | async def role_rin(
self, ctx: commands.Context, target_role: FuzzyRole, *, remove_role: StrictRole
):
await self.super_massrole(
ctx,
[member for member in target_role.members],
remove_role,
f"No one in `{target_role}` has this role.",
Fal... | Python | nomic_cornstack_python_v1 |
import numpy as np
import sys
function diff f x h
begin
return f dist x + h - f dist x / decimal h
end function
set x = eval argv at 1
set h = eval argv at 2
set approx_deriv = diff sin x h
set exact_deriv = cos x
print string The approximated value is: { approx_deriv }
print string The exact value is: { exact_deriv }
... | import numpy as np
import sys
def diff(f, x, h):
return (f(x + h) - f(x)) / float(h)
x = eval(sys.argv[1])
h = eval(sys.argv[2])
approx_deriv = diff(np.sin, x, h)
exact_deriv = np.cos(x)
print(f"The approximated value is: {approx_deriv}")
print(f"The exact value is: {exact_deriv}")
print(f"The error is: {exact... | Python | zaydzuhri_stack_edu_python |
import random
comment Set the range of integers
set min_num = 1
set max_num = 1000000
comment Set the length of the array
set array_length = 100000
comment Generate the random array
set random_array = list comprehension random integer min_num max_num for _ in range array_length | import random
# Set the range of integers
min_num = 1
max_num = 1000000
# Set the length of the array
array_length = 100000
# Generate the random array
random_array = [random.randint(min_num, max_num) for _ in range(array_length)]
| Python | jtatman_500k |
function company_id self
begin
return get pulumi self string company_id
end function | def company_id(self) -> Any:
return pulumi.get(self, "company_id") | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
from collections import OrderedDict
from scene import Scene , command
from buildmode import BuildMode
import constants
import utils
import re
import fnmatch
import pprint
from functools import reduce
import operator
comment temporary debug
import traceback
class EditMode extends Scene
begin
functi... | # coding: utf-8
from collections import OrderedDict
from scene import Scene, command
from buildmode import BuildMode
import constants
import utils
import re
import fnmatch
import pprint
from functools import reduce
import operator
#temporary debug
import traceback
class EditMode(Scene):
def __init__(self, project_pat... | Python | zaydzuhri_stack_edu_python |
function get_edge self from_vertex to_vertex
begin
if tuple from_vertex to_vertex in __edges
begin
return __edges at tuple from_vertex to_vertex
end
else
if tuple to_vertex from_vertex in __edges
begin
return __edges at tuple to_vertex from_vertex
end
else
begin
return none
end
end function | def get_edge(self, from_vertex, to_vertex):
if (from_vertex, to_vertex) in self.__edges:
return self.__edges[(from_vertex, to_vertex)]
elif (to_vertex, from_vertex) in self.__edges:
return self.__edges[(to_vertex, from_vertex)]
else:
return None | Python | nomic_cornstack_python_v1 |
from geom import Point , LineSegment , Center , Edge , Corner , interpolate
from module import Module
from import settings
from scipy.spatial import Voronoi , Delaunay
from random import randrange
class ModGraph extends Module
begin
function __init__ self
begin
set map = none
set heights = none
end function
function p... | from ..geom import (Point, LineSegment, Center, Edge, Corner,
interpolate)
from .module import Module
from .. import settings
from scipy.spatial import Voronoi, Delaunay
from random import randrange
class ModGraph(Module):
def __init__(self):
self.map = None
self.heigh... | Python | zaydzuhri_stack_edu_python |
function pc_noutput_items_var self
begin
return call ldpc_decoder_sptr_pc_noutput_items_var self
end function | def pc_noutput_items_var(self):
return _ccsds_swig.ldpc_decoder_sptr_pc_noutput_items_var(self) | Python | nomic_cornstack_python_v1 |
function tolist n
begin
return list comprehension integer i for i in list string n
end function
function toint l
begin
set n = length l
set s = 0
for tuple p i in enumerate l
begin
set s = s + i * 10 ^ n - p - 1
end
return s
end function
function decrement n start
begin
set n at slice : start + 1 : = call tolist call... | def tolist(n):
return [int(i) for i in list(str(n))]
def toint(l):
n = len(l)
s = 0
for p, i in enumerate(l):
s += i * 10 ** (n-p - 1)
return s
def decrement(n, start):
n[:start + 1] = tolist(toint(n[:start + 1]) - 1)
for i in range(start+1, len(n)):
n[i] = 9
def largest_... | Python | zaydzuhri_stack_edu_python |
from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
comment read data
set iris = call load_iris
set logreg = logistic regression
print target
set scores = cross val score logreg data target cv=5
print string Cross-Validation scor... | from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
# read data
iris = load_iris()
logreg = LogisticRegression()
print(iris.target)
scores = cross_val_score(logreg, iris.data, iris.target, cv=5)
print(f"Cross-Validation scores:... | Python | zaydzuhri_stack_edu_python |
string Bubble Sort Implementation in Python
comment Swap function
function swap arr t
begin
set tuple arr at t arr at t + 1 = tuple arr at t + 1 arr at t
end function
function BubbleSort array
begin
comment This loop so that each element is traversed from index 0 to n-2
for i in range 0 length array - 1
begin
comment I... | """
Bubble Sort Implementation in Python
"""
# Swap function
def swap(arr,t):
arr[t],arr[t+1]=arr[t+1],arr[t]
def BubbleSort(array):
for i in range(0,len(array)-1): # This loop so that each element is traversed from index 0 to n-2
for j in range(len(array)-1-i): # Inner loop is from 0 to Unsorted... | Python | zaydzuhri_stack_edu_python |
import math as m
set t = integer input
for _ in range t
begin
set tuple n k = map int split input
set lst = list map int split input
sort lst
set lst1 = lst at slice : k :
set n = count lst max lst1
set r = count lst1 max lst1
print integer call factorial n / call factorial n - r * call factorial r
end | import math as m
t = int(input())
for _ in range(t):
n, k = map(int, input().split())
lst = list(map(int, input().split()))
lst.sort()
lst1 = lst[:k]
n = lst.count(max(lst1))
r = lst1.count(max(lst1))
print(int(m.factorial(n) / (m.factorial(n - r) * m.factorial(r))))
| Python | zaydzuhri_stack_edu_python |
function set_alpha_z self corrs
begin
if sum Hxy == 0 or vz is none
begin
raise exception string Please compute ground homography and z-vanishing point before setting alpha_z.
end
set b = call normalize2D corrs at 0 at 1
set t = call normalize2D corrs at 1 at 1
set z = corrs at 0 at 0 at 2
set delta_z = corrs at 1 at 0... | def set_alpha_z(self, corrs):
if np.sum(self.Hxy) == 0 or self.vz is None:
raise Exception("Please compute ground homography and z-vanishing point before setting alpha_z.")
b = self.normalize2D(corrs[0][1])
t = self.normalize2D(corrs[1][1])
z = corrs[0][0][2]
delta_z ... | Python | nomic_cornstack_python_v1 |
function delete self
begin
try
begin
set r = post url data=dict string ACTION string DELETE
call raise_for_status
end
except RequestException as ex
begin
raise call from_except ex url string TAP string 1.0
end
set _url = none
end function | def delete(self):
try:
r = requests.post(self.url, data = {"ACTION": "DELETE"})
r.raise_for_status()
except requests.exceptions.RequestException as ex:
raise DALServiceError.from_except(ex, self.url, "TAP", "1.0")
self._url = None | Python | nomic_cornstack_python_v1 |
from pymongo import MongoClient
import datetime
set client = call MongoClient string localhost 27017
set db = mongotest
set collection = test_colleciton
set post = dict string author string Mike ; string text string My first blog post! ; string tags list string mongodb string python string pymongo ; string date call ut... | from pymongo import MongoClient
import datetime
client = MongoClient('localhost', 27017)
db = client.mongotest
collection = db.test_colleciton
post = {"author": "Mike",
"text": "My first blog post!",
"tags": ["mongodb", "python", "pymongo"],
"date": datetime.datetime.utcnow()}
result1 = colle... | Python | zaydzuhri_stack_edu_python |
function ionic_fractions self fractions
begin
if fractions is none or all call isnan fractions
begin
set _ionic_fractions = call full atomic_number + 1 nan dtype=float64
return
end
try
begin
if min fractions < 0
begin
raise call ParticleError string Cannot have negative ionic fractions.
end
if length fractions != atomi... | def ionic_fractions(self, fractions):
if fractions is None or np.all(np.isnan(fractions)):
self._ionic_fractions = np.full(
self.atomic_number + 1, np.nan, dtype=np.float64
)
return
try:
if np.min(fractions) < 0:
raise Part... | Python | nomic_cornstack_python_v1 |
function __create_graph self
begin
comment create the nodes
for h in range height
begin
set row : List at JuncNode = list
for w in range width
begin
set jnodes : List at Node = list comprehension call add_node for _ in range 4
set jn = call JuncNode jnodes tuple h w
append row jn
end
append __juncs row
end
comment crea... | def __create_graph(self):
# create the nodes
for h in range(self.height):
row: List[JuncNode] = list()
for w in range(self.width):
jnodes: List[Node] = [self.add_node() for _ in range(4)]
jn = JuncNode(jnodes, (h, w))
row.append(jn)... | Python | nomic_cornstack_python_v1 |
comment write a python script to merge two python dictionaries
set dict1 = dict string a 10 ; string b 8
set dict2 = dict string d 6 ; string c 4
update dict2 dict1
print dict2 | # write a python script to merge two python dictionaries
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
dict2.update(dict1)
print(dict2) | Python | zaydzuhri_stack_edu_python |
comment encoding=utf-8
import sys
import jieba
import jieba.posseg as pseg
set test_sent = string 李小福是创新办主任也是云计算方面的专家; 什么是八一双鹿 例如我输入一个带“韩玉赏鉴”的标题,在自定义词库中也增加了此词为N类 「台中」正確應該不會被切開。mac上可分出「石墨烯」;此時又可以分出來凱特琳了。
call load_userdict string userdict.txt
set words = call cut test_sent cut_all=false
print join string / words | # encoding=utf-8
import sys
import jieba
import jieba.posseg as pseg
test_sent = (
"李小福是创新办主任也是云计算方面的专家; 什么是八一双鹿\n"
"例如我输入一个带“韩玉赏鉴”的标题,在自定义词库中也增加了此词为N类\n"
"「台中」正確應該不會被切開。mac上可分出「石墨烯」;此時又可以分出來凱特琳了。"
)
jieba.load_userdict("userdict.txt")
words = jieba.cut(test_sent, cut_all=False)
print('/'.join(word... | Python | zaydzuhri_stack_edu_python |
import math
function sqrt number
begin
if number == 0 or number == 1
begin
return number
end
if number < 0
begin
return nan
end
set i = 1
set result = 1
while result <= number
begin
set i = i + 1
set result = i * i
end
return i - 1
string Calculate the floored square root of a number Args: number(int): Number to find t... | import math
def sqrt(number):
if(number==0 or number==1):
return number
if number < 0:
return math.nan
i =1
result = 1
while(result<=number):
i+=1
result = i*i
return i-1
"""
Calculate the floored square root of a number
Args:
... | Python | zaydzuhri_stack_edu_python |
function model
begin
return model
end function | def model() -> Model:
return Model() | Python | nomic_cornstack_python_v1 |
for i in range n1
begin
remove l l at length l - 1
end
print *l | for i in range(n1):
l.remove(l[len(l)-1])
print(*l)
| Python | zaydzuhri_stack_edu_python |
function generate_tools_of_run self run
begin
set profile_run_dir = _run_to_profile_run_dir at run
if is directory gfile profile_run_dir
begin
try
begin
set filenames = list directory profile_run_dir
end
except NotFoundError as e
begin
warning string Cannot read asset directory: %s, NotFoundError %s profile_run_dir e
s... | def generate_tools_of_run(self, run):
profile_run_dir = self._run_to_profile_run_dir[run]
if tf.io.gfile.isdir(profile_run_dir):
try:
filenames = tf.io.gfile.listdir(profile_run_dir)
except tf.errors.NotFoundError as e:
logger.warning('Cannot read asset directory: %s, NotFoundError %... | Python | nomic_cornstack_python_v1 |
function epsilon_greedy q s eps=0.5
begin
if random < eps
begin
return call draw
end
else
begin
return call greedy q s
end
end function | def epsilon_greedy(q, s, eps = 0.5):
if random.random()<eps:
return uniform_dist(q.actions).draw()
else:
return greedy(q,s) | Python | nomic_cornstack_python_v1 |
function instrument_keywords instrument caom=false
begin
comment Retrieve one dataset to get header keywords
if not caom
begin
set filter_to_add = dict string program string 01440
end
else
begin
set filter_to_add = dict string proposal_id string 01440
end
set sample = call instrument_inventory instrument return_data=tr... | def instrument_keywords(instrument, caom=False):
# Retrieve one dataset to get header keywords
if not caom:
filter_to_add = {'program': '01440'}
else:
filter_to_add = {'proposal_id': '01440'}
sample = instrument_inventory(instrument, return_data=True, caom=caom,
... | Python | nomic_cornstack_python_v1 |
function string_reverser input_string
begin
string In this first exercise, the goal is to write a function that takes a string as input and then returns the reversed string. For example, if the input is the string "water", then the output should be "retaw". While you're working on the function and trying to figure out ... | def string_reverser(input_string):
"""
In this first exercise, the goal is to write a function that takes a string as input and then returns the reversed string.
For example, if the input is the string "water", then the output should be "retaw".
While you're working on the function and trying to figur... | Python | zaydzuhri_stack_edu_python |
for i in range 0 t + 1
begin
set distance_travelled = 0.5 * integer a * integer i ^ 2
print string Duration: i string Distance: string * * integer integer distance_travelled / integer 10
end
if v <= 60
begin
print string The person did not go over the speed limit. His/her maximum speed was v string m/s.
end
else
begin
... | for i in range(0, t+1):
distance_travelled = 0.5 * int(a) * (int(i)**2)
print("Duration:", i, " Distance: ", ("*" * int(int(distance_travelled)/int(10))))
if v <= 60:
print("The person did not go over the speed limit. His/her maximum speed was", v, "m/s.")
else:
print("The person went over the speed li... | Python | zaydzuhri_stack_edu_python |
function HandleToken self token last_non_space_token
begin
call HandleToken token last_non_space_token
if call IsType IDENTIFIER
begin
if string == string goog.require
begin
set class_token = search token STRING_TEXT
append __goog_require_tokens class_token
end
else
if string == string goog.provide
begin
set class_toke... | def HandleToken(self, token, last_non_space_token):
super(JavaScriptStateTracker, self).HandleToken(token,
last_non_space_token)
if token.IsType(Type.IDENTIFIER):
if token.string == 'goog.require':
class_token = tokenutil.Search(token, Type.STRI... | Python | nomic_cornstack_python_v1 |
string Jogo do Turtle File ------- Turtle.py ------- Lucas Feng <lucasfeng@usp.br>
import turtle
import time
import random
from turtle_map import get_map
function init_window
begin
string Inicia a janela onde o jogo é executado Returns ------- Retorna o objeto da janela "wn"
set window = call Screen
title window string... | """Jogo do Turtle
File
-------
Turtle.py
-------
Lucas Feng <lucasfeng@usp.br>
"""
import turtle
import time
import random
from turtle_map import get_map
def init_window():
"""Inicia a janela onde o jogo é executado
Returns
-------
Retorna o objeto da janela "wn"
"""
window = turtle.Scre... | Python | zaydzuhri_stack_edu_python |
comment yield from 可以对调用函数main和子生成器gen之间建立双向通道
comment 还可以解决子生成器stopInternation异常并返回值,
comment 但同时当前yield from传值到a时会暂停到下一个yield,如果没有则会在当前函数上产生stopInternation异常
function gen
begin
while true
begin
set a = yield
if a > 5
begin
break
end
end
return a
end function
function g2 gen
begin
comment 注意传值后,会运行到下一个yield,如果没有则会出异常
... | # yield from 可以对调用函数main和子生成器gen之间建立双向通道
#还可以解决子生成器stopInternation异常并返回值,
# 但同时当前yield from传值到a时会暂停到下一个yield,如果没有则会在当前函数上产生stopInternation异常
def gen():
while True:
a = yield
if a > 5:
break
return a
def g2(gen):
#注意传值后,会运行到下一个yield,如果没有则会出异常
a = yield from gen
print(a)
... | Python | zaydzuhri_stack_edu_python |
function _dualx_overrides self
begin
comment NOTE: We set the scale using private API to bypass application of
comment set_default_locators_and_formatters: only_if_default=True is critical
comment to prevent overriding user settings! We also bypass autoscale_view
comment because we set limits manually, and bypass child... | def _dualx_overrides(self):
# NOTE: We set the scale using private API to bypass application of
# set_default_locators_and_formatters: only_if_default=True is critical
# to prevent overriding user settings! We also bypass autoscale_view
# because we set limits manually, and bypass child.... | Python | nomic_cornstack_python_v1 |
string Meter Gauge GUI Downloaded from https://github.com/NickWaterton/iperf3-GUI
import tkinter as tk
from tkinter import font as tkf
import math , time
comment class to show a gauge or panel meter
class Meter extends Canvas
begin
function __init__ self master *args **kwargs
begin
comment super(Meter,self).__init__(ma... | '''
Meter Gauge GUI
Downloaded from https://github.com/NickWaterton/iperf3-GUI
'''
import tkinter as tk
from tkinter import font as tkf
import math, time
# class to show a gauge or panel meter
class Meter(tk.Canvas):
def __init__(self,master,*args,**kwargs):
#super(Meter,self).__init__(master,*args,**kw... | Python | zaydzuhri_stack_edu_python |
function get_lock_file_mtime self
begin
return call getmtime _lock_path
end function | def get_lock_file_mtime(self):
return os.path.getmtime(self._lock_path) | Python | nomic_cornstack_python_v1 |
function writeout_thermo_dict output_dict calctype output_file=string thermo_output.txt
begin
comment Define units
set units = dict string T string K ; string P string Pa ; string Psat string Pa ; string rhol string mol/m^3 ; string rhov string mol/m^3 ; string delta string Pa^(1/2)
comment Make comment line
set commen... | def writeout_thermo_dict(output_dict,calctype,output_file="thermo_output.txt"):
# Define units
units = {"T":"K","P":"Pa","Psat":"Pa","rhol":"mol/m^3","rhov":"mol/m^3","delta":"Pa^(1/2)"}
# Make comment line
comment = "# This data was generated in DESPASITO using the thermodynamic calculation: "+calcty... | Python | nomic_cornstack_python_v1 |
function have_double_impl math_name
begin
return call math_suffix math_name double in libc_math_funcs
end function | def have_double_impl(math_name):
return math_suffix(math_name, double) in libc_math_funcs | Python | nomic_cornstack_python_v1 |
comment Lists
set thislist = list string Harry string Rahul string Krish
print thislist
comment Indexing
print thislist at 0
print thislist at - 1
comment for printing 1 by 1
for x in thislist
begin
print x
end
comment Checking Items
if string Harry in thislist
begin
print string yes
end
comment List length
print lengt... | #Lists
thislist = ["Harry","Rahul","Krish"]
print(thislist)
print(thislist[0]) # Indexing
print(thislist[-1])
#for printing 1 by 1
for x in thislist:
print(x)
#Checking Items
if "Harry" in thislist:
print("yes")
#List length
print(len(thislist))
#adding items #append
thislist.append("Singla")
pri... | Python | zaydzuhri_stack_edu_python |
function find_background_dumb vals
begin
set iter_spot = 1
comment taking the moving average until one end is below 175 watts
comment This minimum cutoff seems to be quite variable, probably long-term, constant loads
while iter_spot < 8
begin
set before_background_val = mean vals at slice 60 * iter_spot - 1 : 60 * iter... | def find_background_dumb(vals):
iter_spot = 1
# taking the moving average until one end is below 175 watts
# This minimum cutoff seems to be quite variable, probably long-term, constant loads
while iter_spot < 8:
before_background_val = vals[60*(iter_spot-1):60*(iter_spot)].mean()
std_be... | Python | nomic_cornstack_python_v1 |
function plot_best generation pop fitness plot_n=1
begin
if not is directory string img
begin
return
end
set tuple pop fitness = call sort_by_fitness pop fitness
set fig = figure frameon=false
call set_size_inches 5 5
set ax = call Axes fig list 0.0 0.0 1.0 1.0
call set_xlim - 0.05 1.05
call set_ylim - 0.05 1.05
call s... | def plot_best(generation, pop, fitness, plot_n=1):
if not isdir("img"):
return
pop, fitness = sort_by_fitness(pop, fitness)
fig = plt.figure(frameon=False)
fig.set_size_inches(5, 5)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_xlim(-0.05, 1.05)
ax.set_ylim(-0.05, 1.05)
ax.set_axis... | Python | nomic_cornstack_python_v1 |
import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
set FONT_NAME = string /home/pi/programming/serial/VCR.ttf
class OledDisplay
begin
function __init__ self
begin
set _display = call _init_display
set _font_28 = call truetype FONT_NAME 28
set _font_16 = call truetype FONT_... | import Adafruit_SSD1306
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
FONT_NAME = "/home/pi/programming/serial/VCR.ttf"
class OledDisplay:
def __init__(self):
self._display = self._init_display()
self._font_28 = ImageFont.truetype(FONT_NAME, 28)
self._font_16 ... | Python | zaydzuhri_stack_edu_python |
comment LEXUS NGUYEN
comment For this assignment, I did not collaborate with anyone else.
function sums list1 list2
begin
set answer = list
for i in list1
begin
for e in list2
begin
append answer i + e
end
end
if length answer == length list1 * length list2
begin
return answer
end
end function
function pairs string
be... | # LEXUS NGUYEN
# For this assignment, I did not collaborate with anyone else.
def sums(list1, list2):
answer = [ ]
for i in list1:
for e in list2:
answer.append(i+e)
if len(answer) == (len(list1) * len(list2)):
return answer
def pairs(string):
answer = [ ]
... | Python | zaydzuhri_stack_edu_python |
comment testgps.py\
from gps import *
import os , time
set session = call gps host=string localhost port=string 2947
poll session
call stream
while 1
begin
call system string clear
poll session
comment a = altitude, d = date/time, m=mode,
comment o=postion/fix, s=status, y=satellites
print
print string GPS reading
prin... | # testgps.py\
from gps import *
import os, time
session = gps.gps(host="localhost", port="2947")
session.poll()
session.stream()
while 1:
os.system("clear")
session.poll()
# a = altitude, d = date/time, m=mode,
# o=postion/fix, s=status, y=satellites
print
print ("GPS reading")
print ("------------... | Python | zaydzuhri_stack_edu_python |
function getNeighborCount x y Matrix
begin
set count = 0
if x > 0
begin
if Matrix at y at x - 1 == 1
begin
set count = count + 1
end
if y > 0
begin
if Matrix at y - 1 at x - 1 == 1
begin
set count = count + 1
end
end
if y < h - 1
begin
if Matrix at y + 1 at x - 1 == 1
begin
set count = count + 1
end
end
end
if x < w - ... | def getNeighborCount(x, y, Matrix):
count = 0
if x > 0:
if Matrix[y][x-1] == 1:
count+=1
if y > 0:
if Matrix[y - 1][x - 1] == 1:
count+=1
if y < h - 1:
if Matrix[y + 1][x - 1] == 1:
count+=1
if x < w - 1:
if ... | Python | zaydzuhri_stack_edu_python |
import webapp2
class MainHandler extends RequestHandler
begin
function get self
begin
write out string <html> <head> <title>Awesome Blog!</title> </head> <body> <form method="post"> <input type="text" name="nome"> <input type="submit"> </form> </body> </html>
end function
function post self
begin
set nome = get request... | import webapp2
class MainHandler(webapp2.RequestHandler):
def get(self):
self.response.out.write(
"""
<html>
<head>
<title>Awesome Blog!</title>
</head>
<body>
<form method="post">
<input type="text" name="nome">
<input type="submit">
</form>
</body>
</html>
"""
)
... | Python | zaydzuhri_stack_edu_python |
if prft < 0
begin
print string извините, контора убыточная
end
if prft > 0
begin
print string прибыльная контора, рентвбельность vvp / cost
set men = integer input string введите количество сотрудников >>>
print string рентвбельность на человека vvp - cost / men
19
end | if prft < 0:
print("извините, контора убыточная")
if prft > 0:
print("прибыльная контора, рентвбельность", vvp / cost)
men = int(input("введите количество сотрудников >>>"))
print("рентвбельность на человека", (vvp - cost) / men)
19
| Python | zaydzuhri_stack_edu_python |
function sample_from_posterior self A
begin
string Run Bayesian inference - sample from the posterior distribution.
call sample_from_proposal A
call set_latent_state_sequence A
call update_log_prior A
call update_log_likelihood
set candidate_log_joint_probability = log_prior + log_likelihood
set delta_log_joint_probabi... | def sample_from_posterior(self, A: pd.DataFrame) -> None:
""" Run Bayesian inference - sample from the posterior distribution."""
self.sample_from_proposal(A)
self.set_latent_state_sequence(A)
self.update_log_prior(A)
self.update_log_likelihood()
candidate_log_joint_prob... | Python | jtatman_500k |
comment Replace the line below
set total = 0
for num in num_list
begin
set total = total + num
end
print total | # Replace the line below
total = 0
for num in num_list:
total += num
print(total) | Python | iamtarun_python_18k_alpaca |
function response_condition self
begin
return get pulumi self string response_condition
end function | def response_condition(self) -> Optional[str]:
return pulumi.get(self, "response_condition") | Python | nomic_cornstack_python_v1 |
comment 計算三天的天氣狀況
import pandas as pd
set weatherList = list string Sunny string Cloudy string Rainy
set humidityList = list string VeryDry string Dry string Wet string VeryWet
comment 初始條件
set weatherProbabilities = dict string Sunny 0.63 ; string Cloudy 0.17 ; string Rainy 0.2
print string 天氣初始條件: weatherProbabilitie... | # 計算三天的天氣狀況
import pandas as pd
weatherList = ['Sunny', 'Cloudy', 'Rainy']
humidityList = ['VeryDry', 'Dry', 'Wet', 'VeryWet']
#初始條件
weatherProbabilities = {'Sunny' : 0.63, 'Cloudy' : 0.17, 'Rainy' : 0.20}
print('天氣初始條件:\n',weatherProbabilities)
humidities = {1 : 'VeryDry', 2 : 'Dry', 3 : 'Wet'}
print('濕度:\n',humi... | Python | zaydzuhri_stack_edu_python |
function name self
begin
return _name
end function | def name(self) -> str:
return self._name | Python | nomic_cornstack_python_v1 |
function predict self X return_latent=false
begin
set phi_X = call phi X W add_bias=true
set F = phi_X @ T
set P = call logistic F
set Y = P * R / 1 - P
if return_latent
begin
set K = phi_X @ T
return tuple Y F K
end
return Y
end function | def predict(self, X, return_latent=False):
phi_X = self.phi(X, self.W, add_bias=True)
F = phi_X @ self.beta.T
P = logistic(F)
Y = (P*self.R) / (1-P)
if return_latent:
K = phi_X @ phi_X.T
return Y, F, K
return Y | Python | nomic_cornstack_python_v1 |
class Worker
begin
function __init__ self name surname position wage bonus _income=none
begin
set name = name
set surname = surname
set position = position
set _income = dict string wage wage ; string bonus bonus
end function
end class
class Position extends Worker
begin
function get_full_name self
begin
print string {... | class Worker:
def __init__(self, name, surname, position, wage, bonus, _income=None):
self.name = name
self.surname = surname
self.position = position
self._income = {'wage': wage, 'bonus': bonus}
class Position(Worker):
def get_full_name(self):
print(f'{self.name} {se... | Python | zaydzuhri_stack_edu_python |
function initialise_with_state self ringmaster_status
begin
call set_test_status ringmaster_status
call load_status
call _open_files
call _initialise_presenter
call _initialise_terminal_reader
end function | def initialise_with_state(self, ringmaster_status):
self.ringmaster.set_test_status(ringmaster_status)
self.ringmaster.load_status()
self.ringmaster._open_files()
self.ringmaster._initialise_presenter()
self.ringmaster._initialise_terminal_reader() | Python | nomic_cornstack_python_v1 |
function solution citations
begin
set answer = 0
sort citations
for tuple idx i in enumerate citations
begin
set temp = citations at - idx + 1
if temp >= idx + 1
begin
set answer = idx + 1
end
end
return answer
end function | def solution(citations):
answer = 0
citations.sort()
for idx, i in enumerate(citations):
temp = citations[-(idx + 1)]
if temp >= idx + 1:
answer = idx + 1
return answer | Python | zaydzuhri_stack_edu_python |
function __init__ self side
begin
set side = side
end function | def __init__(self,side):
self.side = side | Python | nomic_cornstack_python_v1 |
function is_equal num1 num2
begin
return num1 == num2
end function | def is_equal(num1, num2):
return num1 == num2 | Python | jtatman_500k |
function insert self *args
begin
return call UintVector_insert self *args
end function | def insert(self, *args):
return _fife.UintVector_insert(self, *args) | Python | nomic_cornstack_python_v1 |
function popenAndCall self command
begin
function runInThread command nothing
begin
set _process = popen split command stdin=PIPE stdout=PIPE stderr=PIPE shell=false
comment Fix the pipes to be nonblocking
call fcntl call fileno F_SETFL O_NONBLOCK
call fcntl call fileno F_SETFL O_NONBLOCK
wait _process
if _callback
beg... | def popenAndCall(self, command):
def runInThread(command, nothing):
self._process = subprocess.Popen(command.split()
,stdin=subprocess.PIPE
,stdout=subprocess.PIPE
,stderr=subprocess.PIPE
,shell=False)
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
comment from serial import Serial
import sys
from math import log
set fig = figure
set ax1 = call add_subplot 1 1 1
set fichero = argv at 1
comment s = Serial(port="/dev/ttyUSB... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
# from serial import Serial
import sys
from math import log
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
fichero = sys.argv[1]
# s = Serial(port="/dev/ttyUSB0", baudrate=115200)
def g... | Python | zaydzuhri_stack_edu_python |
function get_labels self
begin
raise call NotImplementedError
end function | def get_labels(self):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function service_binding_success_hr
begin
with open join path TEST_DATA_DIRECTORY string create_service_binding_success_response_hr.md as f
begin
set expected_hr_output = read f
end
return expected_hr_output
end function | def service_binding_success_hr():
with open(
os.path.join(
TEST_DATA_DIRECTORY, "create_service_binding_success_response_hr.md"
)
) as f:
expected_hr_output = f.read()
return expected_hr_output | Python | nomic_cornstack_python_v1 |
function __init__ self initial_spec=none
begin
call __init__ _lexer
set previous = none
set _initial = initial_spec
end function | def __init__(self, initial_spec=None):
super(SpecParser, self).__init__(_lexer)
self.previous = None
self._initial = initial_spec | Python | nomic_cornstack_python_v1 |
function swap arr i j
begin
set temp = arr at i
set arr at i = arr at j
set arr at j = temp
end function
function printArr arr
begin
for i in range length arr
begin
print arr at i
end
end function
function getStrArr arr
begin
set s = string
for i in range length arr
begin
set s = s + string arr at i
if i < length arr ... | def swap(arr,i,j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def printArr(arr):
for i in range(len(arr)):
print(arr[i])
def getStrArr(arr):
s = ""
for i in range(len(arr)):
s+= str(arr[i])
if(i<len(arr)-1):
s+=" "
return s
T = int(input())
i=0
arr_bi... | Python | zaydzuhri_stack_edu_python |
from interfaz import Interfaz
from control import Control
import pygame
function obtener cliente interfaz control
begin
set vm1 = call get_value
set vm2 = call get_value
set voltajes = list vm1 vm2
set vr1 = call get_value
set vr2 = call get_value
set razones = list vr1 vr2
set vc1 = call get_value
set vc2 = call get_v... | from interfaz import Interfaz
from control import Control
import pygame
def obtener(cliente, interfaz: Interfaz, control: Control):
vm1 = cliente.valvulas['valvula1'].get_value()
vm2 = cliente.valvulas['valvula2'].get_value()
voltajes = [vm1, vm2]
vr1 = cliente.razones['razon1'].get_value()
vr2 =... | Python | zaydzuhri_stack_edu_python |
function key_sequence_to_path sequence
begin
return call rootPath + join string . sequence
end function | def key_sequence_to_path(sequence: List[str]):
return Path.rootPath() + ".".join(sequence) | Python | nomic_cornstack_python_v1 |
function diameter_dist adjacency1 adjacency2
begin
set diameter1 = call diameter adjacency1
set diameter2 = call diameter adjacency2
return absolute diameter1 - diameter2 / diameter1
end function | def diameter_dist(adjacency1,adjacency2):
diameter1 = diameter(adjacency1)
diameter2 = diameter(adjacency2)
return np.abs((diameter1-diameter2)/diameter1) | Python | nomic_cornstack_python_v1 |
function convert_to_normal_tensor tensor orig_device
begin
if is_cuda and orig_device == string cpu
begin
set tensor = cpu tensor
end
return tensor
end function | def convert_to_normal_tensor(tensor: torch.Tensor, orig_device: str) -> torch.Tensor:
if tensor.is_cuda and orig_device == "cpu":
tensor = tensor.cpu()
return tensor | Python | nomic_cornstack_python_v1 |
function _process_communities_data data segment cursor seg_start=- 1
begin
set all_users = list comprehension x for x in data if x at 1
if seg_start == - 1
begin
set seg_start = segment - 0.05
end
set current_users_seg = all_users at slice integer seg_start * length all_users : integer segment * length all_users :
pri... | def _process_communities_data(data, segment, cursor, seg_start=-1):
all_users = [x for x in data if x[1]]
if seg_start == -1:
seg_start = segment - 0.05
current_users_seg = all_users[int(seg_start * len(all_users)):int(segment * len(all_users))]
print('Current segment:', seg_start, segment)
... | Python | nomic_cornstack_python_v1 |
set students = dict string Alice list string ID001 26 string A ; string Bob list string ID002 26 string A ; string Sam list string ID003 26 string A ; string Pen list string ID004 26 string A ; string Nice list string ID005 26 string A
set student = dict string Alice dict string id string ID001 ; string age 26 ; string... | students = {
"Alice": ["ID001", 26, "A"],
"Bob": ["ID002", 26, "A"],
"Sam": ["ID003", 26, "A"],
"Pen": ["ID004", 26, "A"],
"Nice": ["ID005", 26, "A"],
}
student = {
"Alice": {"id": "ID001", "age": 26, "grade": "A"},
"Bob": {"id": "ID001", "age": 26, "grade": "A"},
"Sam": {"id": "ID001",... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.