code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import sqlite3
class DBConnect
begin
function __init__ self
begin
set db = call connect string personalInformation.db
set row_factory = Row
execute db string create table if not exists Info(Name text, Sex text, Age int)
commit db
end function
end class
function saverecord self name sex age
begin
execute db string inser... | import sqlite3
class DBConnect:
def __init__(self):
self.db = sqlite3.connect("personalInformation.db")
self.db.row_factory = sqlite3.Row
self.db.execute("create table if not exists Info(Name text, Sex text, Age int)")
self.db.commit()
def saverecord(self, name, sex, age):
se... | Python | zaydzuhri_stack_edu_python |
import time
from darkwater_640 import dw_Controller , dw_Motor , dw_Servo
set dw = call dw_Controller addr=96
set m1 = call getMotor 1
set m2 = call getMotor 2
set m3 = call getMotor 3
set m4 = call getMotor 4
set m5 = call getMotor 5
set m6 = call getMotor 6
set s1 = call getServo 1
set s2 = call getServo 2
call off
c... | import time
from darkwater_640 import dw_Controller, dw_Motor, dw_Servo
dw = dw_Controller( addr=0x60 )
m1 = dw.getMotor(1)
m2 = dw.getMotor(2)
m3 = dw.getMotor(3)
m4 = dw.getMotor(4)
m5 = dw.getMotor(5)
m6 = dw.getMotor(6)
s1 = dw.getServo(1)
s2 = dw.getServo(2)
s1.off()
s2.off()
m1.off()
m2.off()
m3.off()
m4.off(... | Python | zaydzuhri_stack_edu_python |
function build_graph self input_df source_target=none
begin
comment This import is needed because the graphframes package is only initialized
comment after the spark session has been created
from graphframes import GraphFrame
if not source_target
begin
set source_target = tuple string character_1 string character_2
end... | def build_graph(self, input_df: DataFrame, source_target: tuple = None) -> None:
# This import is needed because the graphframes package is only initialized
# after the spark session has been created
from graphframes import GraphFrame
if not source_target:
source_target = (... | Python | nomic_cornstack_python_v1 |
comment Resolver ecuación de segundo grado
comment a*x**2+b*x+c=0
import cmath
set a = decimal input string a:
set b = decimal input string b:
set c = decimal input string c:
set d = b ^ 2 - 4 * a * c
set sol1 = - b - square root d / 2 * a
set sol2 = - b + square root d / 2 * a
print format string solución de ax^2+bx+c... | #Resolver ecuación de segundo grado
#a*x**2+b*x+c=0
import cmath
a=float(input('a: '))
b=float(input('b: '))
c=float(input('c: '))
d=(b**2)-4*a*c
sol1=(-b-cmath.sqrt(d))/(2*a)
sol2=(-b+cmath.sqrt(d))/(2*a)
print('solución de ax^2+bx+c=0 son: {0} y {1}:'.format(sol1,sol2))
| Python | zaydzuhri_stack_edu_python |
from flask import Flask
from flask import render_template , request
import RPi.GPIO as GPIO
import threading
import time
comment (RPi 3B+ GPIO14)
set red = 14
comment (RPi 3B+ GPIO15)
set green = 15
comment (RPi 3B+ GPIO18)
set blue = 18
call setmode BCM
call setwarnings false
setup GPIO red OUT
setup GPIO green OUT
se... | from flask import Flask
from flask import render_template, request
import RPi.GPIO as GPIO
import threading
import time
red = 14 #(RPi 3B+ GPIO14)
green = 15 #(RPi 3B+ GPIO15)
blue = 18 #(RPi 3B+ GPIO18)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(red, GPIO.OUT)
GPIO.setup(green,GPIO.OUT)
... | Python | zaydzuhri_stack_edu_python |
import distance as dist
import getADC as ADC
import temperature as tempe
import pompe as pompe
import time
import watreeserver as serv
comment delai entre deux loop en secondes
set DELAY = 3600
function init
begin
call init_distance
call init_pompe
end function
function arrosage
begin
set it = 0
set lumi_tab = list 0 *... | import distance as dist
import getADC as ADC
import temperature as tempe
import pompe as pompe
import time
import watreeserver as serv
DELAY = 3600 # delai entre deux loop en secondes
def init():
dist.init_distance()
pompe.init_pompe()
def arrosage():
it = 0
lumi_tab = [0] * 24
... | Python | zaydzuhri_stack_edu_python |
function _stride_comb_iter x
begin
if not is instance x ndarray
begin
yield tuple x string nop
return
end
set stride_set = list tuple 1 * ndim
set stride_set at - 1 = tuple 1 3 - 4
if ndim > 1
begin
set stride_set at - 2 = tuple 1 3 - 4
end
if ndim > 2
begin
set stride_set at - 3 = tuple 1 - 4
end
for repeats in produc... | def _stride_comb_iter(x):
if not isinstance(x, np.ndarray):
yield x, "nop"
return
stride_set = [(1,)] * x.ndim
stride_set[-1] = (1, 3, -4)
if x.ndim > 1:
stride_set[-2] = (1, 3, -4)
if x.ndim > 2:
stride_set[-3] = (1, -4)
for repeats in itertools.product(*tuple... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Sep 2 10:32:38 2018 @author: shornbec
import pygame
class Background extends Sprite
begin
function __init__ self location
begin
comment call Sprite initializer
call __init__ self
set image = load image string Graphics/background.bmp
set r... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 2 10:32:38 2018
@author: shornbec
"""
import pygame
class Background(pygame.sprite.Sprite):
def __init__(self, location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load('Graphics/b... | Python | zaydzuhri_stack_edu_python |
function __getitem__ self index
begin
comment Load data and get target
set structure_id = list_IDs at index
set normalized = call normalize_morgans values
set X = decimal
if targets is not none
begin
set y = decimal
end
else
begin
comment return a dummy variable
set y = decimal
end
return tuple X y
end function | def __getitem__(self, index):
# Load data and get target
structure_id = self.list_IDs[index]
normalized = normalize_morgans(self.morgans.loc[structure_id].values)
X = torch.from_numpy(normalized).float()
if self.targets is not None:
y = torch.from_numpy(np.array(self.... | Python | nomic_cornstack_python_v1 |
function uwb_id self uwb_id
begin
set _uwb_id = uwb_id
end function | def uwb_id(self, uwb_id):
self._uwb_id = uwb_id | Python | nomic_cornstack_python_v1 |
function make_melons melon_types
begin
set melon_1 = call Melon string yw 8 7 2 string Sheila
set melon_2 = call Melon string yw 3 4 2 string Sheila
set melon_3 = call Melon string yw 9 8 3 string Sheila
set melon_4 = call Melon string cas 10 6 35 string Sheila
set melon_5 = call Melon string cren 8 2 35 string Michael... | def make_melons(melon_types):
melon_1 = Melon('yw', 8, 7, 2, 'Sheila')
melon_2 = Melon('yw', 3, 4, 2, 'Sheila')
melon_3 = Melon('yw', 9, 8, 3, 'Sheila')
melon_4 = Melon('cas', 10, 6, 35, 'Sheila')
melon_5 = Melon('cren', 8, 2, 35, 'Michael')
melon_6 = Melon('cren', 8, 2, 35, 'Michael')... | Python | nomic_cornstack_python_v1 |
import numpy as np
function invert B
begin
comment these gausformations makes B tridiagonal
set number_z = size np B at 0
set B_inv = call diagflat call full number_z 1 dtype=float
if B at 0 at 1 == 1
begin
if B at 1 at 2 < 0
begin
for i in array range 1 number_z
begin
set B at 0 = B at 0 - B at i
set B_inv at 0 = B_in... | import numpy as np
def invert(B):
#these gausformations makes B tridiagonal
number_z=np.size(B[0])
B_inv=np.diagflat(np.full(number_z, 1, dtype=np.float))
if B[0][1]==1:
if B[1][2]<0:
for i in np.arange(1,number_z):
B[0]=B[0]-B[i]
B_inv[0... | Python | zaydzuhri_stack_edu_python |
function names self
begin
return set keys _cluster_idle_events_by_cluster
end function | def names(self):
return set(self._cluster_idle_events_by_cluster.keys()) | Python | nomic_cornstack_python_v1 |
class Solution
begin
function groupAnagrams self strs
begin
string :type strs: List[str] :rtype: List[List[str]]
set solution = list list
set saved = dict
for val in strs
begin
set sorted_str = join string sorted val
print sorted_str
if sorted_str in saved
begin
append saved at sorted_str val
end
else
begin
set saved... | class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
solution = list(list())
saved = {}
for val in strs:
sorted_str = ''.join(sorted(val))
print(sorted_str)
if sorted_... | Python | zaydzuhri_stack_edu_python |
import os
import requests
import urllib3
call disable_warnings InsecureRequestWarning
from prettytable import PrettyTable
function authvc api_url user password
begin
set r = post string { api_url } /rest/com/vmware/cis/session auth=tuple user password verify=false
if status_code == 200
begin
print string Authentication... | import os
import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
from prettytable import PrettyTable
def authvc(api_url,user,password):
r = requests.post(f'{api_url}/rest/com/vmware/cis/session', auth=(user,password), verify=False)
if r.status_code == 200:
... | Python | zaydzuhri_stack_edu_python |
function stop self
begin
info string Shutting down SimpleHTTPServer
set stop_cmd = format string pkill -9 -f '{0}' server_cmd
call _execute_command stop_cmd
end function | def stop(self):
self.logger.info('Shutting down SimpleHTTPServer')
stop_cmd = "pkill -9 -f '{0}'".format(self.server_cmd)
self._execute_command(stop_cmd) | Python | nomic_cornstack_python_v1 |
function get_sender msg
begin
return msg at string From
end function | def get_sender(msg):
return msg['From'] | Python | nomic_cornstack_python_v1 |
from threading import Thread
function worker
begin
print string I am a worker
end function
set threads = list
for _ in range 5
begin
set th = thread target=worker
append threads th
start th
end
for th in threads
begin
join th
end
print string Done | from threading import Thread
def worker():
print("I am a worker")
threads = list()
for _ in range(5):
th = Thread(target=worker)
threads.append(th)
th.start()
for th in threads:
th.join()
print("Done")
| Python | flytech_python_25k |
import boto3
import json
from random import randint
import random
import uuid
import os
from dynamo import dynamoDAO
function handler event context
begin
set body = loads get event string body
print string body: %s % dumps body
set orderNumber = random integer 0 10000000000000
set hashOrder = uuid 4
set purchaseID = fo... | import boto3
import json
from random import randint
import random
import uuid
import os
from dynamo import dynamoDAO
def handler(event, context):
body = json.loads(event.get('body'))
print(f"body: %s" % json.dumps(body))
orderNumber = randint(0, 10000000000000)
hashOrder = uuid.uuid4()
purc... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python
import os
import sys
from difflib import SequenceMatcher
function longestSubstring str1 str2
begin
set seqMatch = call SequenceMatcher none str1 str2
set match = call find_longest_match 0 length str1 0 length str2
if size != 0
begin
return length str1 at slice a : a + size :
end
else
begin
return 0... | #!/bin/python
import os
import sys
from difflib import SequenceMatcher
def longestSubstring(str1,str2):
seqMatch = SequenceMatcher(None,str1,str2)
match = seqMatch.find_longest_match(0, len(str1), 0, len(str2))
if (match.size!=0):
return len((str1[match.a: match.a + match.size]))
else:
r... | Python | zaydzuhri_stack_edu_python |
function runModel startYear epochs
begin
comment initialize test and training data
set tuple train_data test_data current_data = read csv source_file startYear
set train_data = array train_data
set test_data = array test_data
set current_data = array current_data
comment shuffle training data
shuffle random train_data
... | def runModel(startYear, epochs):
#initialize test and training data
train_data,test_data,current_data = read_csv(source_file, startYear)
train_data = np.array(train_data)
test_data = np.array(test_data)
current_data = np.array(current_data)
#shuffle training data
np.random.shuffle(train_dat... | Python | nomic_cornstack_python_v1 |
function maximumProduct2 self nums
begin
set min1 = decimal string inf
set min2 = decimal string inf
set max1 = decimal string -inf
set max2 = decimal string -inf
set max3 = decimal string -inf
for num in nums
begin
if num <= min1
begin
set min2 = min1
set min1 = num
end
else
if num <= min2
begin
set min2 = num
end
if ... | def maximumProduct2(self, nums: List[int]) -> int:
min1 = min2 = float('inf')
max1 = max2 = max3 = float('-inf')
for num in nums:
if num <= min1:
min2 = min1
min1 = num
elif num <= min2:
min2 = num
if num >= max... | Python | nomic_cornstack_python_v1 |
comment Created as exercise to OR!ON's code.
string After pressing RUN, enter a country name or leave it empty to see Poland
from urllib import request
from urllib import error
import json
set api_endpoint = string https://restcountries.eu/rest/v2/name/
set user_input = input or string poland
set api_query = string { a... | # Created as exercise to OR!ON's code.
"""After pressing RUN, enter a country name or leave it empty to see Poland"""
from urllib import request
from urllib import error
import json
api_endpoint = "https://restcountries.eu/rest/v2/name/"
user_input = input() or "poland"
api_query = f"{api_endpoint}{user_input}?full... | Python | zaydzuhri_stack_edu_python |
function fetch_argument op_def arg ws
begin
set desc = if expression is instance arg bytes then arg else s
if version_info >= tuple 3 0
begin
set desc = decode desc string utf-8
end
set desc = replace desc string $HANDLE name
set value = call ToNumpy
if size == 1
begin
return flatten value at 0
end
return value
end fun... | def fetch_argument(op_def, arg, ws):
desc = arg if isinstance(arg, bytes) else arg.s
if sys.version_info >= (3, 0):
desc = desc.decode('utf-8')
desc = desc.replace('$HANDLE', op_def.name)
value = ws.get_tensor(desc).ToNumpy()
if value.size == 1:
return value.flatten()[0]
return v... | Python | nomic_cornstack_python_v1 |
function purification main_state ancilla_state dec get_prob=false
begin
if size np call shape main_state != 1
begin
exit string In purification: the input main GHZ diagonal state is not a vector but a matrix.
end
if size np call shape ancilla_state != 1
begin
exit string In purification: the input ancilla GHZ diagonal ... | def purification(main_state, ancilla_state, dec, get_prob=False):
if np.size(np.shape(main_state)) != 1:
sys.exit("In purification: the input main GHZ diagonal state is not a vector but a matrix.")
if np.size(np.shape(ancilla_state)) != 1:
sys.exit("In purification: the input ancilla GHZ diagona... | Python | nomic_cornstack_python_v1 |
from flask import Flask , request , render_template
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
import pickle
set app = call Flask __name__
decorator call route string /
function hello
begin
return call render_template string index.html
end function
decorator call route string /predict metho... | from flask import Flask,request, render_template
from sklearn.preprocessing import PolynomialFeatures
import numpy as np
import pickle
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('index.html')
@app.route('/predict',methods=['POST'])
def prediction():
model = pickle.... | Python | zaydzuhri_stack_edu_python |
function is_bull_market self
begin
return call port_return call last string 2M >= 0.2
end function | def is_bull_market(self):
return self.port_return(self.data.last('2M')) >= .2 | Python | nomic_cornstack_python_v1 |
from os import listdir , unlink
from os.path import join , dirname , abspath , exists
import os
function get_images folder
begin
return list comprehension join folder file for file in list directory folder
end function
function delete_images folder
begin
list comprehension call unlink directory name absolute path file ... | from os import listdir, unlink
from os.path import join, dirname, abspath, exists
import os
def get_images(folder):
return [join(folder, file) for file in listdir(folder)]
def delete_images(folder):
[unlink(dirname(abspath(file)) + '/' + join(folder, file)) for file in listdir(folder)]
return 'delete-im... | Python | zaydzuhri_stack_edu_python |
function get_neighbors self bmu n_nghbs
begin
set n_items = range 1 n_nghbs + 1
set p_obj = dict string p_i i ; string p_x x ; string p_y y ; string min_x x ; string min_y y ; string max_x x ; string max_y y
for i in n_items
begin
set k = i
set nxmin = floor p_obj at string p_x - pad * k
set nxmax = ceil p_obj at strin... | def get_neighbors(self, bmu, n_nghbs):
n_items = range(1, n_nghbs + 1)
p_obj = {
'p_i': bmu.i,
'p_x': bmu.x,
'p_y': bmu.y,
'min_x': bmu.x,
'min_y': bmu.y,
'max_x': bmu.x,
'max_y': bmu.y
}
for i in n_ite... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string python2/3 This module provides a collection of admin methods currently only implemented for *nix
from datetime import timedelta
import time
import misc
function uptime
begin
string Gets system uptime Args: None Returns: uptime_string (str): output if success, err if failed
with open... | #!/usr/bin/env python3
'''
python2/3
This module provides a collection of admin methods
currently only implemented for *nix
'''
from datetime import timedelta
import time
import misc
def uptime():
'''Gets system uptime
Args:
None
Returns:
uptime_string (str): output if success, err if... | Python | zaydzuhri_stack_edu_python |
from neo4j import GraphDatabase
class NeoDB
begin
string Class created for testing and performance comparison purposes. The Neo4j database is not fully implemented due to problems with Docker
function __init__ self uri=string neo4j://localhost:7687 user=string neo4j password=string 123
begin
set driver = call driver ur... | from neo4j import GraphDatabase
class NeoDB:
"""Class created for testing and performance comparison purposes.
The Neo4j database is not fully implemented due to problems with Docker"""
def __init__(self, uri="neo4j://localhost:7687",
user="neo4j",
password="123"):
... | Python | zaydzuhri_stack_edu_python |
function get_queryset self *args **kwargs
begin
set queryset = queryset
set query_set = filter project__user=user
comment todo groupby project
try
begin
return filter project=kwargs at string project
end
except KeyError
begin
return query_set
end
end function | def get_queryset(self, *args, **kwargs):
queryset = self.queryset
query_set = queryset.filter(
project__user=self.request.user)
# todo groupby project
try:
return query_set.filter(project=self.kwargs["project"])
except KeyError:
return query_se... | Python | nomic_cornstack_python_v1 |
function bootstrap_css_url
begin
return call css_url
end function | def bootstrap_css_url():
return css_url() | Python | nomic_cornstack_python_v1 |
function get_anchors html_data
begin
comment If html_data does not have a <body>, assume the data passed if the <body>
if find html_data string body == none
begin
set html_body = html_data
end
else
begin
set html_body = find html_data string body
end
set anchors = list find all html_body string a
return anchors
end fun... | def get_anchors(html_data):
# If html_data does not have a <body>, assume the data passed if the <body>
if html_data.find("body") == None:
html_body = html_data
else:
html_body = html_data.find("body")
anchors = list(html_body.find_all("a"))
return anchors | Python | nomic_cornstack_python_v1 |
function AsciiArt inputstring
begin
import os
set files = list comprehension f for f in list directory string AsciiArt/ if ends with f string .txt
set names2 = list
for file in files
begin
set h = string ! + file
append names2 replace h string .txt string
end
if inputstring == string !help
begin
set names = list
for fi... | def AsciiArt (inputstring):
import os
files = [f for f in os.listdir("AsciiArt/") if f.endswith('.txt')]
names2 = list()
for file in files:
h = "!"+file
names2.append (h.replace(".txt", ""))
if inputstring == "!help":
names = list()
for file in files:
name... | Python | nomic_cornstack_python_v1 |
function train_or_load_facial_expression_recognition_model train_image_paths train_image_labels
begin
comment TODO - Istrenirati model ako vec nije istreniran, ili ga samo ucitati iz foldera za serijalizaciju
set model = none
try
begin
set model = load string svm2.joblib
end
except any
begin
set model = none
end
if mod... | def train_or_load_facial_expression_recognition_model(train_image_paths, train_image_labels):
# TODO - Istrenirati model ako vec nije istreniran, ili ga samo ucitati iz foldera za serijalizaciju
model=None
try:
model=load('svm2.joblib')
except:
model=None
if model == None:
da... | Python | nomic_cornstack_python_v1 |
function range self key fromTime toTime aggregationType=none bucketSizeSeconds=0
begin
set params = list key fromTime toTime
if aggregationType != none
begin
call appendAggregation params aggregationType bucketSizeSeconds
end
return call execute_command RANGE_CMD *params
end function | def range(self, key, fromTime, toTime,
aggregationType=None, bucketSizeSeconds=0):
params = [key, fromTime, toTime]
if aggregationType != None:
self.appendAggregation(params, aggregationType, bucketSizeSeconds)
return self.execute_command(self.RANGE_CMD, *params) | Python | nomic_cornstack_python_v1 |
function __getitem__ self location
begin
return board at location
end function | def __getitem__(self, location):
return self.board[location] | Python | nomic_cornstack_python_v1 |
function chemprop_msg_update h nbrs ji_idx=none kj_idx=none
begin
if all list kj_idx is not none ji_idx is not none
begin
set graph_size = shape at 0
comment get the h's of these indices
set h_to_add = h at ji_idx
set message = call scatter_add src=h_to_add index=kj_idx dim=0 dim_size=graph_size
return message
end
comm... | def chemprop_msg_update(h,
nbrs,
ji_idx=None,
kj_idx=None):
if all([kj_idx is not None, ji_idx is not None]):
graph_size = h.shape[0]
# get the h's of these indices
h_to_add = h[ji_idx]
message = scatter_add(src... | Python | nomic_cornstack_python_v1 |
function gene_median self gene
begin
return list comprehension median g at gene for g in data at string genes
end function | def gene_median(self, gene):
return [np.median(g[gene]) for g in self.data["genes"]] | Python | nomic_cornstack_python_v1 |
from base_page import BasePage
from selenium.webdriver.common.by import By
from locators import ProductPageLocators
class productPage extends BasePage
begin
function add_to_basket self
begin
set link = call find_element *ProductPageLocators.ADD_TO_BASKET
call click
call solve_quiz_and_get_code
end function
function get... | from .base_page import BasePage
from selenium.webdriver.common.by import By
from .locators import ProductPageLocators
class productPage(BasePage):
def add_to_basket(self):
link = self.browser.find_element(*ProductPageLocators.ADD_TO_BASKET)
link.click()
self.solve_quiz_and_get_code()
... | Python | zaydzuhri_stack_edu_python |
function xrange self k=1
begin
return array list min / max k max / min k
end function | def xrange(self, k=1):
return np.array([self.x.min() / np.max(k), self.x.max() / np.min(k)]) | Python | nomic_cornstack_python_v1 |
import socket
set address = tuple string 192.168.1.64 16197
set s = call socket AF_INET SOCK_STREAM
call connect address
comment data = s.recv(512)
comment print('the data received is', data)
while true
begin
set send_string = input string input:
call send encode send_string
end
close s | import socket
address = ('192.168.1.64', 16197)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(address)
# data = s.recv(512)
# print('the data received is', data)
while True:
send_string = input("input: ")
s.send(send_string.encode())
s.close()
| Python | zaydzuhri_stack_edu_python |
from tkinter import *
import os
import time
from random import *
import tkinter.messagebox as msg
comment "Global" variables
set info = list
set moneylist = list
comment Setting up the window
set root = call Tk
comment Window parameters
title root string Shaman DND V.3
comment root.geometry("350x200")
comment Backgro... | from tkinter import *
import os
import time
from random import *
import tkinter.messagebox as msg
###########################################################################################################################
#"Global" variables
info=[]
moneylist=[]
#########################################################... | Python | zaydzuhri_stack_edu_python |
import os
set processId = call getpid
comment The following two methods only accessiable in unix system
comment userID = os.getuid()
comment operatingSystem = os.uname()
print processId
comment print(userID)
comment print(operatingSystem) | import os
processId = os.getpid()
## The following two methods only accessiable in unix system
# userID = os.getuid()
# operatingSystem = os.uname()
print(processId)
# print(userID)
# print(operatingSystem)
| Python | zaydzuhri_stack_edu_python |
function d_dynamic_programming A B C
begin
comment c = (BC-AB)//(AC-BC+AB), r = (BC-AC)//(AB-BC+AC)
comment Python????????????????
set MOD = 10 ^ 9 + 7
set c = B * C - A * B * power A * C - B * C + A * B MOD - 2 MOD % MOD
set r = B * C - A * C * power A * B - B * C + A * C MOD - 2 MOD % MOD
set ans = format string {} {... | def d_dynamic_programming(A, B, C):
# c = (BC-AB)//(AC-BC+AB), r = (BC-AC)//(AB-BC+AC)
# Python????????????????
MOD = 10**9 + 7
c = ((B * C - A * B) * pow(A * C - B * C + A * B, MOD - 2, MOD)) % MOD
r = ((B * C - A * C) * pow(A * B - B * C + A * C, MOD - 2, MOD)) % MOD
ans = '{} {}'.format... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import pandas_datareader as web
from numpy.linalg import inv
comment Stocks interested
set tickers = list string GME string RKT string ETSY string AAPL string TSLA
comment Get Stock Info from Yahoo
set multpl_stocks = call get_data_yahoo tickers start=string 2021-01-01 end=string 2021-04... | import matplotlib.pyplot as plt
import pandas_datareader as web
from numpy.linalg import inv
# Stocks interested
tickers = ["GME",'RKT','ETSY','AAPL','TSLA ']
# Get Stock Info from Yahoo
multpl_stocks = web.get_data_yahoo(tickers,
start = "2021-01-01",
end = "2021-04-30")
multiStockPrice = multpl_stocks['Adj Close'... | Python | zaydzuhri_stack_edu_python |
function ip_version self
begin
return get pulumi self string ip_version
end function | def ip_version(self) -> int:
return pulumi.get(self, "ip_version") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @ File Inception_v1.py
comment @ Description : GoogLeNet
comment @ Author alexchung
comment @ Time 29/10/2019 AM 10:29
import os
import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers import xavier_initializer , xavier_initializer_con... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @ File Inception_v1.py
# @ Description : GoogLeNet
# @ Author alexchung
# @ Time 29/10/2019 AM 10:29
import os
import numpy as np
import tensorflow as tf
from tensorflow.contrib.layers import xavier_initializer, xavier_initializer_conv2d
class InceptionV1():
"""
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
import sys
import urllib.request
from util import *
string json sample { "camera_id": 0, "file_name": "0-7-2019-06-24-3504-1067-4125-1688-180-180-9722-1561410615-1561410790", "id": 103169, "label_state": 23, "label_state_admin": -1, "start_time": 1561410615, "... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import urllib.request
from .util import *
'''
json sample
{
"camera_id": 0,
"file_name": "0-7-2019-06-24-3504-1067-4125-1688-180-180-9722-1561410615-1561410790",
"id": 103169,
"label_state": 23,
"label_state_admin": -1,
"start_time... | Python | zaydzuhri_stack_edu_python |
string @Autor: xujiahuan @Date: 2020-05-12 21:41:12 @LastEditors: xujiahuan @LastEditTime: 2020-06-03 17:25:59
from flask import Flask , render_template , request
from sklearn.externals import joblib
import json
from utils import extend_maps
import sys
import requests
append path string ..
set app = call Flask __name__... | '''
@Autor: xujiahuan
@Date: 2020-05-12 21:41:12
@LastEditors: xujiahuan
@LastEditTime: 2020-06-03 17:25:59
'''
from flask import Flask, render_template, request
from sklearn.externals import joblib
import json
from utils import extend_maps
import sys
import requests
sys.path.append("..")
app = Flask(__name__)
@app... | Python | zaydzuhri_stack_edu_python |
string Let <var>x</var><sub>1</sub> <var>x</var><sub>2</sub> <var>x<sub>n </sub></var> be a sequence of length <var>n</var> such that<ul><li> <var>x</var><sub>1</sub> 2</li><li>for all 1 lt <var>i</var> le <var> n</var> <var>x</var><sub><var>i</var><i>1</i></sub> lt <var>x<sub>i </sub></var></li><li>for all <var>i</var... | """
Let <var>x</var><sub>1</sub> <var>x</var><sub>2</sub> <var>x<sub>n
</sub></var> be a sequence of length <var>n</var> such that<ul><li>
<var>x</var><sub>1</sub> 2</li><li>for all 1 lt <var>i</var> le <var>
n</var> <var>x</var><sub><var>i</var><i>1</i></sub> lt <var>x<sub>i
</sub></var></li><li>for all <var>i</var>... | Python | zaydzuhri_stack_edu_python |
function migration_season self
begin
for tuple location landscape in items map
begin
call move_all_animals_in_cell location landscape
end
end function | def migration_season(self):
for location, landscape in self.map.items():
self.move_all_animals_in_cell(location, landscape) | Python | nomic_cornstack_python_v1 |
function get_absolute_view_rect self
begin
set view_rect_absolute = call to_absolute_position _view_rect
if _parent_scrollarea is not none
begin
set parent = _parent_scrollarea
if parent is not none
begin
comment Recursive
while true
begin
if parent is none
begin
break
end
set view_rect_absolute = call clip view_rect_a... | def get_absolute_view_rect(self) -> 'pygame.Rect':
view_rect_absolute = self.to_absolute_position(self._view_rect)
if self._parent_scrollarea is not None:
parent = self._parent_scrollarea
if parent is not None:
while True: # Recursive
if paren... | Python | nomic_cornstack_python_v1 |
comment type: (list[elem],int) -> list[elem]
comment Precondicion: n es menorigual a la longitud de la lista
comment Complejidad O(n)
function sinLosPrimeros ls n
begin
if n == 0
begin
return ls
end
return call sinLosPrimeros ls at slice 1 : : n - 1
end function
comment Complejidad O(n)
function sinLosPrimerosImperat... | #type: (list[elem],int) -> list[elem]
#Precondicion: n es menorigual a la longitud de la lista
#Complejidad O(n)
def sinLosPrimeros(ls,n):
if(n == 0):
return ls
return sinLosPrimeros(ls[1:],n-1)
#Complejidad O(n)
def sinLosPrimerosImperativa(ls,n):
return ls[n:]
lista=[5,4,3,2,1,2]
print("forma ... | Python | zaydzuhri_stack_edu_python |
function _verify_options config
begin
if not config at string species
begin
error string You must specify a species (-s/--species)
exit 1
end
if config at string hpc and config at string local
begin
error string You can only use one of the config options (hpc/local)
exit 1
end
if config at string hpc and config at stri... | def _verify_options(config: configuration.Config) -> None:
if not config.config['species']:
log._logger.error('You must specify a species (-s/--species)')
exit(1)
if config.config['hpc'] and config.config['local']:
log._logger.error('You can only use one of the config options (hpc/loca... | Python | nomic_cornstack_python_v1 |
from Movable import Movable
from WeaponException import WeaponException
class Character extends Movable WeaponException
begin
set _life = 50
set _agility = 2
set _strength = 2
set _wit = 2
function __init__ self name RPGCLass
begin
set _name = name
set _RPGClass = RPGCLass
end function
decorator property
function name ... | from Movable import Movable
from WeaponException import WeaponException
class Character(Movable, WeaponException):
_life = 50
_agility= 2
_strength= 2
_wit= 2
def __init__(self, name, RPGCLass):
self._name = name
self._RPGClass = RPGCLass
@property
def name(self):
r... | Python | zaydzuhri_stack_edu_python |
from operator import itemgetter
class hom
begin
string ДОм
function __init__ self id name capacity price comp_id
begin
set id = id
set name = name
set capacity = capacity
set price = price
set comp_id = comp_id
end function
end class
class Str
begin
string Улица
function __init__ self id model
begin
set id = id
set mod... | from operator import itemgetter
class hom:
"""ДОм"""
def __init__(self, id, name, capacity, price, comp_id):
self.id = id
self.name = name
self.capacity = capacity
self.price = price
self.comp_id = comp_id
class Str:
"""Улица"""
def __init__(self, id, model)... | Python | zaydzuhri_stack_edu_python |
import sys
set stdin = open string 4839_sample_input.txt string r
set T = integer input
for i in range T
begin
set info = list map int split input
set Pa = info at 1
set Pb = info at 2
set result = string
set count = list 0 0
for j in range length count
begin
set P = info at 0
set l = 1
set c = 0
while c != info at j ... | import sys
sys.stdin = open('4839_sample_input.txt', 'r')
T = int(input())
for i in range(T):
info = list(map(int, input().split()))
Pa = info[1]
Pb = info[2]
result = ''
count = [0, 0]
for j in range(len(count)):
P = info[0]
l = 1
c = 0
while... | Python | zaydzuhri_stack_edu_python |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
import random
set probs = 10
set counter = 0
set numberCorrect = 0
while counter < probs
begin
set randNum1 = call randrange 1 1000
set randNum2 = call randrange 1 1000
set correctAns = integer randNum1 + randNum2
set yourAns = integer input string what is the answer to { randNum1 } + { randNum2 } ?
if correctAns == yo... | import random
probs=10
counter=0
numberCorrect=0
while counter<probs:
randNum1=random.randrange(1,1000)
randNum2=random.randrange(1,1000)
correctAns=int(randNum1+randNum2)
yourAns=int(input(f"what is the answer to {randNum1}+{randNum2}?"))
if correctAns==yourAns:
print("Yay! you did it!")
... | Python | zaydzuhri_stack_edu_python |
function add self gobj x=none y=none
begin
add _base gobj x y
end function | def add(self, gobj, x=None, y=None):
self._base.add(gobj, x, y) | Python | nomic_cornstack_python_v1 |
string Requirements: * A database created with some data about authors inside.
import sqlite3
from flask import Flask , g , render_template
from import config
set app = call Flask __name__
function connect_db
begin
return call connect DATABASE_NAME
end function
decorator before_request
comment a common procedure for e... | """
Requirements:
* A database created with some data about authors inside.
"""
import sqlite3
from flask import Flask, g, render_template
from . import config
app = Flask(__name__)
def connect_db():
return sqlite3.connect(config.DATABASE_NAME)
# a common procedure for every view function. Define here to acti... | Python | zaydzuhri_stack_edu_python |
import torch
set B = tensor list list 1 2 9 list 2 0 4 list 3 4 5
print B
set B = T
print B
set A = reshape array range 20 dtype=float32 5 4
print A
set B = clone A
print A A + B
print call id A call id B
set x = array range 4 dtype=float32
print x sum
set A = reshape array range 20 * 2 2 5 4
print shape sum
set sum_A ... | import torch
B = torch.tensor([[1, 2, 9], [2, 0, 4], [3, 4, 5]])
print(B)
B = B.T
print(B)
A = torch.arange(20, dtype=torch.float32).reshape(5, 4)
print(A)
B = A.clone()
print(A, A + B)
print(id(A), id(B))
x = torch.arange(4, dtype=torch.float32)
print(x, x.sum())
A = torch.arange(20 * 2).reshape(2, 5, 4)
print(A.s... | Python | zaydzuhri_stack_edu_python |
function tsv_seq_to_concepts self name=string seq_to_concepts.tsv
begin
with open out_dir + name string w as handle
begin
set content = to csv df_seqs_concepts none sep=sep float_format=float_format
write lines handle content
end
end function | def tsv_seq_to_concepts(self, name="seq_to_concepts.tsv"):
with open(self.a.out_dir + name, 'w') as handle:
content = self.df_seqs_concepts.to_csv(None, sep=self.sep, float_format=self.float_format)
handle.writelines(content) | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
string Escriba un programa que pida dos números y que escriba su media aritmética. Se recuerda que la media aritmética de dos números es la suma de ambos números dividida por 2.
print string ===========================
print string CALCULO DE MEDIA ARITMETICA
print string ==========================... | # coding=utf-8
"""
Escriba un programa que pida dos números y que escriba su media aritmética.
Se recuerda que la media aritmética de dos números es la suma de ambos números dividida por 2.
"""
print("===========================")
print("CALCULO DE MEDIA ARITMETICA")
print("===========================")
n1 = int(in... | Python | zaydzuhri_stack_edu_python |
string Routines to solve noiseless advection equation.
import numpy as np
function advect dynamics nodes rho_0 t_span
begin
string Solves the noiseless advection equation when the initial condition is a sum of Dirac-Delta functionals args: dynamics: callable, dynamics( x, jac=False). Outputs the vector field and possib... | """
Routines to solve noiseless advection equation.
"""
import numpy as np
def advect( dynamics, nodes, rho_0, t_span ):
""" Solves the noiseless advection equation when the initial condition is a sum of Dirac-Delta functionals
args:
dynamics: callable, dynamics( x, jac=False). Outputs the vector fi... | Python | zaydzuhri_stack_edu_python |
from collections import OrderedDict
from PyQt5 import QtWidgets , QtGui , Qt
class ColorPicker extends QWidget
begin
function __init__ self width height
begin
set width = width
set height = height
call __init__
set colors = ordered dictionary list tuple string RED tuple 255 0 0 tuple string GREEN tuple 0 255 0 tuple st... | from collections import OrderedDict
from PyQt5 import QtWidgets, QtGui, Qt
class ColorPicker(QtWidgets.QWidget):
def __init__(self, width, height):
self.width = width
self.height = height
super().__init__()
self.colors = OrderedDict([
('RED', (255, 0, 0)),
... | Python | zaydzuhri_stack_edu_python |
comment Aufgabe 05
comment Filtere alle Files aus, die mit File beginnen
comment und mit der Extension PDF oder Doc enden
comment Vorgabe:
comment files = ["File_today.pdf","File_21022099.pdf","file.txt",
comment "File_Bild.jpg","File.doc", "Temp_File.doc"] | # Aufgabe 05
# Filtere alle Files aus, die mit File beginnen
# und mit der Extension PDF oder Doc enden
# Vorgabe:
# files = ["File_today.pdf","File_21022099.pdf","file.txt",
# "File_Bild.jpg","File.doc", "Temp_File.doc"]
| Python | zaydzuhri_stack_edu_python |
function __init__ self mean covar
begin
if not is instance mean Variable and not is instance mean LazyVariable
begin
raise call RuntimeError string The mean of a GaussianRandomVariable must be a Variable
end
if not is instance covar Variable and not is instance covar LazyVariable
begin
raise call RuntimeError string Th... | def __init__(self, mean, covar):
if not isinstance(mean, Variable) and not isinstance(mean, LazyVariable):
raise RuntimeError('The mean of a GaussianRandomVariable must be a Variable')
if not isinstance(covar, Variable) and not isinstance(covar, LazyVariable):
raise RuntimeError... | Python | nomic_cornstack_python_v1 |
from django.shortcuts import render
from models import Books
comment Create your views here.
function index request
begin
set book = call create title=string Pride and Prejudice author=string Jane Austen published_date=string 1813-01-28 category=string Romance
set book = call create title=string Great Expectations auth... | from django.shortcuts import render
from . models import Books
# Create your views here.
def index(request):
book = Books.objects.create(title="Pride and Prejudice", author="Jane Austen", published_date="1813-01-28", category="Romance")
book = Books.objects.create(title="Great Expectations", author="Charles D... | Python | zaydzuhri_stack_edu_python |
function set_preference cls user preference_key preference_value
begin
set tuple user_pref _ = call get_or_create user=user key=preference_key
set value = preference_value
save
end function | def set_preference(cls, user, preference_key, preference_value):
user_pref, _ = cls.objects.get_or_create(user=user, key=preference_key)
user_pref.value = preference_value
user_pref.save() | Python | nomic_cornstack_python_v1 |
import os
comment To ignore AVX2 FMA extensions
set environ at string TF_CPP_MIN_LOG_LEVEL = string 2
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
comment Manipulation of dataset
set mnist = mnist
set tuple tuple x_train y_train tuple x_test y_test = call load_data
set y_train_exp = array ... | import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # To ignore AVX2 FMA extensions
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Manipulation of dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
y_train_exp = np.array([[0]*10]*len(y_train))
... | Python | zaydzuhri_stack_edu_python |
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from scipy import spatial
comment https://www.geeksforgeeks.org/union-find/
from networkx.utils import UnionFind
from shapely.geometry import Point , LineString , Polygon , MultiPolygon
import... | import math
import random
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.pyplot as plt
import numpy as np
from scipy import spatial
# https://www.geeksforgeeks.org/union-find/
from networkx.utils import UnionFind
from shapely.geometry import Point, LineString, Polygon, \
MultiPolygon
imp... | Python | zaydzuhri_stack_edu_python |
comment Vector Graphic Library (VGL) for Python
comment geom.py
comment 2020-2-12 Ver 0.1
comment Author: Uisang Hwang
comment Email : uhwangtx@gmail.com
import numpy as np
from import color , rotation , vertex
from import linetype
from import shape
from import linepat
from import shape
function distP x1 y1 x2 y2
... | # Vector Graphic Library (VGL) for Python
#
# geom.py
#
# 2020-2-12 Ver 0.1
#
# Author: Uisang Hwang
# Email : uhwangtx@gmail.com
#
import numpy as np
from . import color, rotation, vertex
from . import linetype
from . import shape
from . import linepat
from . import shape
def distP(x1,y1,x2,y2): ret... | Python | zaydzuhri_stack_edu_python |
function save_inlets self
begin
try
begin
set inlets = list
set t4_but_rt_name = list
for row in range 0 call rowCount
begin
set item = call QTableWidgetItem
set fid = row + 1
set item = item inlets_tblw row 0
if item is not none
begin
set name = if expression string call text != string then string call text else st... | def save_inlets(self):
try:
inlets = []
t4_but_rt_name = []
for row in range(0, self.inlets_tblw.rowCount()):
item = QTableWidgetItem()
fid = row + 1
item = self.inlets_tblw.item(row, 0)
if item is not None:
... | Python | nomic_cornstack_python_v1 |
for i in range 3 101
begin
for j in range 2 i
begin
if i % j == 0
begin
pass
end
else
begin
print i
end
end
end | for i in range(3,101):
for j in range(2,i):
if i%j == 0:
pass
else:
print(i) | Python | zaydzuhri_stack_edu_python |
function store_data self session id data metadata
begin
raise NotImplementedError
end function | def store_data(self, session, id, data, metadata):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function _add_joints self mujoco_body parent_body geom_colliders geom_bodies
begin
set local_mujoco_body_pos = call _get_position mujoco_body
for joint in joint
begin
if type == string free
begin
continue
end
if type != string hinge
begin
raise call ValueError string Unsupported joint type { type } for { name }
end
com... | def _add_joints(self, mujoco_body: MjcfElement, parent_body: config_pb2.Body,
geom_colliders: List[GeomCollider],
geom_bodies: List[config_pb2.Body]):
local_mujoco_body_pos = self._get_position(mujoco_body)
for joint in mujoco_body.joint:
if joint.type == 'free':
... | Python | nomic_cornstack_python_v1 |
import numpy as np
set a = list comprehension list map int split input for i in range 3
set a = array a
set n = integer input
set b = list
set bingo = zeros like a
for i in range n
begin
set b = integer input
set index = where a == b
if length index at 0 != 0
begin
set bingo at tuple index at 0 at 0 index at 1 at 0 = ... | import numpy as np
a = [list(map(int, input().split())) for i in range(3)]
a = np.array(a)
n = int(input())
b = []
bingo = np.zeros_like(a)
for i in range(n):
b = int(input())
index = np.where(a == b)
if len(index[0]) != 0:
bingo[index[0][0], index[1][0]] = 1
# チェック
if 3 in sum(bingo) or 3 in sum(... | Python | zaydzuhri_stack_edu_python |
function check_if_valid_letters self line letter_case
begin
set string = join string line
if string and not grid
begin
if letter_case == string upper and not is upper string or letter_case == string lower and not lower string
begin
raise call InputError string Text grid letters should be consistent uppercase or lowerc... | def check_if_valid_letters(self, line, letter_case):
string = ''.join(line)
if string and not self.grid:
if (letter_case == 'upper' and not string.isupper()) \
or (letter_case == 'lower' and not string.lower()):
raise InputError(
'Text grid ... | Python | nomic_cornstack_python_v1 |
function getCartItems self
begin
set cart = call getCart
return call getItems
end function | def getCartItems(self):
cart = self.getCart()
return IItemManagement(cart).getItems() | Python | nomic_cornstack_python_v1 |
function experience_function self
begin
return _experience_function
end function | def experience_function(self) -> ExperienceFunctionEnum:
return self._experience_function | Python | nomic_cornstack_python_v1 |
function output_pdf_plot core_result spid models options fit_results
begin
string Function for plotting pdf/pmf
comment PDF/PMF
set hist_bins = 11
set tuple emp_hist edges = call histogram values hist_bins normed=true
set x = array edges at slice : - 1 : + array edges at slice 1 : : / 2
set df = call DataFrame dict s... | def output_pdf_plot(core_result, spid, models, options, fit_results):
""" Function for plotting pdf/pmf """
# PDF/PMF
hist_bins = 11
emp_hist, edges = np.histogram(core_result['y'].values, hist_bins,
normed=True)
x = (np.array(edges[:-1]) + np.array(edges[1:])) / 2... | Python | jtatman_500k |
class Quadrado
begin
function __init__ self tamanho_do_lado
begin
set tamanho_do_lado = tamanho_do_lado
end function
function mudar_valor_lado self novo_valor_lado
begin
set tamanho_do_lado = novo_valor_lado
end function
function retornar_valor_lado self
begin
return tamanho_do_lado
end function
function calcular_area ... | class Quadrado:
def __init__(self,tamanho_do_lado):
self.tamanho_do_lado = tamanho_do_lado
def mudar_valor_lado(self,novo_valor_lado):
self.tamanho_do_lado = novo_valor_lado
def retornar_valor_lado(self):
return self.tamanho_do_lado
def calcular_area(self):
return (self.tamanho_do_lado*self.tamanho_do... | Python | zaydzuhri_stack_edu_python |
function assign_crossval_sets self
begin
set cv_set_assignment = list
set traj_n_frames = list
for n in range length x_trajs
begin
set length = shape at 0
append traj_n_frames length
append cv_set_assignment random integer low=0 high=n_cv_sets size=length
end
set total_n_frames = sum traj_n_frames
set n_frames_in_set... | def assign_crossval_sets(self):
self.cv_set_assignment = []
traj_n_frames = []
for n in range(len(self.x_trajs)):
length = self.x_trajs[n].shape[0]
traj_n_frames.append(length)
self.cv_set_assignment.append(np.random.randint(low=0, high=self.n_cv_sets, size=l... | Python | nomic_cornstack_python_v1 |
function subscribe self node name dynamic=false mark_bound=true
begin
if node == self
begin
raise call ValueError string Cannot subscribe to self
end
set name = call intern name
if call has_subscriber node name
begin
return
end
if dynamic
begin
call add_input name
end
set _subscribers = call Subscriber node=node input=... | def subscribe(
self, node: "BaseCDAGNode", name: str, dynamic: bool = False, mark_bound: bool = True
) -> None:
if node == self:
raise ValueError("Cannot subscribe to self")
name = sys.intern(name)
if self.has_subscriber(node, name):
return
if dynamic:... | Python | nomic_cornstack_python_v1 |
function compute_and_plot_mass_hist raw_images gen_sample_raw display=true ax=none log=true lim=lim_hist confidence=none ylim=none fractional_difference=false algo=string relative loc=1 **kwargs
begin
comment raw_max = 250884
comment lim = [np.log10(1), np.log10(raw_max/3)]
set tuple y_real y_fake x = call mass_hist_re... | def compute_and_plot_mass_hist(raw_images, gen_sample_raw, display=True, ax=None, log=True, lim=lim_hist, confidence=None, ylim=None, fractional_difference=False, algo='relative', loc=1, **kwargs):
# raw_max = 250884
# lim = [np.log10(1), np.log10(raw_max/3)]
y_real, y_fake, x = stats.mass_hist_real_fak... | Python | nomic_cornstack_python_v1 |
string Game This file contains the main game.
comment Main imports
import pygame as pg
comment Relative imports
from import entities
from import constants as C
class Game extends object
begin
string This is the main game logic handler.
function __init__ self width height engine
begin
set image = call convert
set rect... | '''
Game
This file contains the main game.
'''
#Main imports
import pygame as pg
#Relative imports
from . import entities
from . import constants as C
class Game(object):
'''This is the main game logic handler.'''
def __init__(self, width, height, engine):
self.image = pg.surface.Sur... | Python | zaydzuhri_stack_edu_python |
import sys
set lang = argv at 1
for line in stdin
begin
set linelist = split strip line string
if length linelist != 3
begin
continue
end
set thislang = linelist at 0
end | import sys
lang = sys.argv[1]
for line in sys.stdin:
linelist = line.strip().split('\t')
if len(linelist) != 3:
continue
thislang = linelist[0] | Python | zaydzuhri_stack_edu_python |
comment Definition for binary tree with next pointer.
class TreeLinkNode
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
set next = none
end function
end class
class Solution
begin
comment @param root, a tree link node
comment @return nothing
function connect self root
begin
if root ==... | # Definition for binary tree with next pointer.
class TreeLinkNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if root==None:
... | Python | zaydzuhri_stack_edu_python |
function test_past_question self
begin
set past_question = call create_question question_text=string Past Question. days=- 5
set url = reverse string polls:detail args=tuple id
set response = get client url
call assertContains response question_text
end function | def test_past_question( self ) :
past_question = create_question( question_text = 'Past Question.' , days = -5 )
url = reverse( 'polls:detail' , args = ( past_question.id , ) )
response = self.client.get( url )
self.assertContains( response , past_question.question_text ) | Python | nomic_cornstack_python_v1 |
function cublasCgetriBatched handle n A lda P C ldc info batchSize
begin
set status = call cublasCgetriBatched handle n integer A lda integer P integer C ldc integer info batchSize
call cublasCheckStatus status
end function | def cublasCgetriBatched(handle, n, A, lda, P, C, ldc, info, batchSize):
status = _libcublas.cublasCgetriBatched(handle, n,
int(A), lda, int(P),
int(C), ldc, int(info),
batchSize)
... | Python | nomic_cornstack_python_v1 |
function load_filenames data_dir
begin
set filenames = list
for tuple i class_path in enumerate glob glob data_dir + string /*
begin
print i class_path
set curr_images = list
for file_path in glob glob class_path + string /*
begin
append curr_images file_path
end
append filenames curr_images
end
return filenames
end ... | def load_filenames (data_dir):
filenames = []
for i, class_path in enumerate(glob.glob(data_dir + '/*')):
print(i, class_path)
curr_images = []
for file_path in glob.glob(class_path + '/*'):
curr_images.append(file_path)
filenames.append(curr_images)
r... | Python | nomic_cornstack_python_v1 |
function copy self
begin
set copy = call Genome
set node_genes = list comprehension copy node_gene for node_gene in node_genes
set connection_genes = set generator expression copy connection_gene for connection_gene in connection_genes
return copy
end function | def copy(self):
copy = Genome()
copy.node_genes = [node_gene.copy() for node_gene in self.node_genes]
copy.connection_genes = set(connection_gene.copy() for connection_gene
in self.connection_genes)
return copy | Python | nomic_cornstack_python_v1 |
comment -*-coding:utf-8-*-
set x = string X-DSPAM-Confidence: 0.8475
set pos = find x string :
set num = decimal x at slice pos + 1 : : | #-*-coding:utf-8-*-
x = "X-DSPAM-Confidence: 0.8475";
pos = x.find(":")
num = float(x[pos+1:]) | Python | zaydzuhri_stack_edu_python |
function sum a b
begin
if b == 1
begin
return a + 1
end
else
if b == 0
begin
return a
end
else
if a == 0
begin
return b
end
else
begin
return sum a + 1 b - 1
end
end function
print sum a b | def sum(a, b):
if b == 1:
return a + 1
elif b == 0:
return a
elif a == 0:
return b
else:
return sum(a + 1, b - 1)
print(sum(a, b))
| Python | zaydzuhri_stack_edu_python |
import numpy as np
set tuple m n = list map int split input
set b = array list comprehension split input for _ in range m int
set c = array list comprehension split input for _ in range m int
print add np b c
print call subtract b c
print call multiply b c
print call floor_divide b c
print call mod b c
print call power... | import numpy as np
m,n=list(map(int, input().split()))
b = np.array([input().split() for _ in range(m)], int)
c = np.array([input().split() for _ in range(m)], int)
print(np.add(b,c))
print(np.subtract(b,c))
print(np.multiply(b,c))
print(np.floor_divide(b,c))
print(np.mod(b,c))
print(np.power(b,c))
| Python | zaydzuhri_stack_edu_python |
function custom_domain self
begin
return _custom_domain
end function | def custom_domain(self):
return self._custom_domain | Python | nomic_cornstack_python_v1 |
function z_score self x
begin
return x - mean / stddev
end function | def z_score(self, x):
return (x - self.mean) / self.stddev | 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.