code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function _AssertActions self changes actions
begin
for change in changes
begin
set action_history = call GetActionsForChanges list change
assert equal list comprehension action for x in action_history actions
end
end function | def _AssertActions(self, changes, actions):
for change in changes:
action_history = self.fake_db.GetActionsForChanges([change])
self.assertEqual([x.action for x in action_history], actions) | Python | nomic_cornstack_python_v1 |
function resetEncodersRaw self
begin
return call IEncodersRaw_resetEncodersRaw self
end function | def resetEncodersRaw(self):
return _yarp.IEncodersRaw_resetEncodersRaw(self) | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
import time
set img1 = string //img[@src='http://www.marinespecies.org/aphia/images/pnode.gif']
set img2 = string //img[@src='http://www.marinespecies.org/aphia/images/plastnode.gif']
comment driver = webdriver.PhantomJS(executable_path='/usr/bin/phantomjs')
set driver = call Firefox
slee... | from selenium import webdriver
import time
img1="//img[@src='http://www.marinespecies.org/aphia/images/pnode.gif']"
img2="//img[@src='http://www.marinespecies.org/aphia/images/plastnode.gif']"
#driver = webdriver.PhantomJS(executable_path='/usr/bin/phantomjs')
driver = webdriver.Firefox()
time.sleep(2)
driver.get("ht... | Python | zaydzuhri_stack_edu_python |
function reorder_mxml self temp_data
begin
set data = list
set start_events = list filter lambda x -> x at string event_type == string start temp_data
set finish_events = list filter lambda x -> x at string event_type == string complete temp_data
for tuple x y in zip start_events finish_events
begin
append data diction... | def reorder_mxml(self, temp_data):
data = list()
start_events = list(filter(lambda x: x['event_type'] == 'start', temp_data))
finish_events = list(filter(lambda x: x['event_type'] == 'complete', temp_data))
for x, y in zip(start_events, finish_events):
data.append(dict(caseid... | Python | nomic_cornstack_python_v1 |
function to_base58 self
begin
return decode call b58encode raw string utf-8
end function | def to_base58(self) -> str:
return base58.b58encode(self.raw).decode('utf-8') | Python | nomic_cornstack_python_v1 |
comment Frances Ding, Lily Zhang, Kimberley Yu
import featureExtractor , util
import random
import itertools
comment Basic Q learner with simple features:
comment x and y position of ball + x position of paddle
class QLearner
begin
function __init__ self legalActions epsilon=0.05 gamma=0.99 alpha=0.2 numTraining=1000
b... | ### Frances Ding, Lily Zhang, Kimberley Yu
import featureExtractor, util
import random
import itertools
# Basic Q learner with simple features:
# x and y position of ball + x position of paddle
class QLearner:
def __init__(self, legalActions, epsilon=0.05,gamma=0.99,alpha=0.2, numTraining=1000):
"""
... | Python | zaydzuhri_stack_edu_python |
function getTime self
begin
acquire semaphore
try
begin
set t = time
end
except any
begin
set e = call exc_info at 1
error string getTime: %s % tuple e
end
release semaphore
return t
end function | def getTime(self):
self.semaphore.acquire()
try:
t = self.__nmea.time
except:
e = sys.exc_info()[1]
self._log.error("getTime: %s"%(e,))
self.semaphore.release()
return t | Python | nomic_cornstack_python_v1 |
function teardown_command ctx
begin
set repo = obj at string CHDIR
set fs_yaml_file = obj at string FS_YAML_FILE
call cli_check_repo repo fs_yaml_file
set repo_config = call load_repo_config repo fs_yaml_file
teardown repo_config repo
end function | def teardown_command(ctx: click.Context):
repo = ctx.obj["CHDIR"]
fs_yaml_file = ctx.obj["FS_YAML_FILE"]
cli_check_repo(repo, fs_yaml_file)
repo_config = load_repo_config(repo, fs_yaml_file)
teardown(repo_config, repo) | Python | nomic_cornstack_python_v1 |
import torch
from torch import nn
from torch.nn import functional as F
from utils.constants import PAD , SOS , EOS
class RNN extends Module
begin
function __init__ self config input_dim embed_dim hidden_dim output_dim
begin
call __init__
set config = config
set output_dim = output_dim
set embed = embedding input_dim em... | import torch
from torch import nn
from torch.nn import functional as F
from utils.constants import PAD, SOS, EOS
class RNN(nn.Module):
def __init__(self, config, input_dim, embed_dim, hidden_dim, output_dim):
super().__init__()
self.config = config
self.output_dim = output_dim
sel... | Python | zaydzuhri_stack_edu_python |
comment 1. Написать программу, которая будет складывать,
comment вычитать, умножать или делить два числа.
comment Числа и знак операции вводятся пользователем.
comment После выполнения вычисления программа не завершается,
comment а запрашивает новые данные для вычислений.
comment Завершение программы должно выполняться... | # 1. Написать программу, которая будет складывать,
# вычитать, умножать или делить два числа.
# Числа и знак операции вводятся пользователем.
# После выполнения вычисления программа не завершается,
# а запрашивает новые данные для вычислений.
# Завершение программы должно выполняться при вводе
# символа '0' в кач... | Python | zaydzuhri_stack_edu_python |
comment This program contains a function for generating a makefile from a
comment list of Fortran source files.
comment State: Functional
comment Last modified 13.06.2017 by Lars Frogner
import sys
import os
import makemake_lib
class fortran_source
begin
comment This class extracts relevant information from a Fortran s... | #
# This program contains a function for generating a makefile from a
# list of Fortran source files.
#
# State: Functional
#
# Last modified 13.06.2017 by Lars Frogner
#
import sys
import os
import makemake_lib
class fortran_source:
# This class extracts relevant information from a Fortran source
# file and... | Python | zaydzuhri_stack_edu_python |
comment IMPORTS ###
import grid
import nengo
import numpy as np
import nengo.spa as spa
import nengo.networks as networks
comment CONSTANTS ###
set MAP = string ####### # M # # # # # # #B# # #G Y R# #######
comment Number of colors to find before stopping (max. 5)
set COLORS_TO_FIND = 4
comment Number of neurons for Ne... | ### IMPORTS ###
import grid
import nengo
import numpy as np
import nengo.spa as spa
import nengo.networks as networks
### CONSTANTS ###
MAP="""
#######
# M #
# # # #
# #B# #
#G Y R#
#######
"""
COLORS_TO_FIND = 4 # Number of colors to find before stopping (max. 5)
N_NEURONS = 50 # Number of neurons for Nengo e... | Python | zaydzuhri_stack_edu_python |
import os
import sys
import random
import argparse
import numpy as np
import tensorflow as tf
set __author__ = string Jocelyn
set emotion_dict = dict string anger 0 ; string disgust 1 ; string happiness 2 ; string like 3 ; string sadness 4 ; string none 5
set id2emotion = dictionary comprehension idx : emotion for tupl... | import os
import sys
import random
import argparse
import numpy as np
import tensorflow as tf
__author__ = "Jocelyn"
emotion_dict = {"anger": 0, "disgust": 1, "happiness": 2, "like": 3, "sadness": 4, "none": 5}
id2emotion = {idx: emotion for emotion, idx in emotion_dict.items()}
FLAGS = None
class H... | Python | zaydzuhri_stack_edu_python |
for i in range N
begin
for j in range i
begin
if A at j < A at i
begin
set count at i at 0 = count at i at 0 + 1
end
end
for j in range i + 1 N
begin
if A at j < A at i
begin
set count at i at 1 = count at i at 1 + 1
end
end
end
set ans = 0
set mod = 10 ^ 9 + 7
for i in range N
begin
set ans = ans + 1 + K - 1 * K - 1 /... | for i in range(N):
for j in range(i):
if A[j] < A[i]:
count[i][0] += 1
for j in range(i+1, N):
if A[j] < A[i]:
count[i][1] += 1
ans = 0
mod = 10**9 + 7
for i in range(N):
ans += (1+K-1)*(K-1) // 2 * count[i][0]
ans += (1+K)*K // 2 * count[i][1]
ans %= mod
pr... | Python | zaydzuhri_stack_edu_python |
for i in lista
begin
try
begin
print 10 / i
end
except ZeroDivisionError
begin
print string Dzielisz przez zero
end
except TypeError
begin
print string Dzielisz przez coś co nie jest liczbą
end
except any
begin
pass
end
end
comment CTRL + ALT + L Poprawia stylistykę kodu | for i in lista:
try:
print(10 / i)
except ZeroDivisionError:
print("Dzielisz przez zero")
except TypeError:
print("Dzielisz przez coś co nie jest liczbą")
except:
pass
# CTRL + ALT + L Poprawia stylistykę kodu | Python | zaydzuhri_stack_edu_python |
with open string data_new.txt string w+ as f
begin
set loca_list = list
for loca in loca_list
begin
write f loca + string ns
end
end | with open("data_new.txt",'w+') as f:
loca_list = []
for loca in loca_list:
f.write(loca + " ns\n") | Python | zaydzuhri_stack_edu_python |
function plot_dataset self
begin
comment load random 30 images from dataset
set rows = 10
set cols = 5
set p = glob call Path dataroot / phase string **/*
set files = list comprehension x for x in p if call is_file
set image_grid = tensor list
for i in range rows
begin
set image_row = tensor list
for j in range cols
be... | def plot_dataset(self):
# load random 30 images from dataset
rows = 10
cols = 5
p = (Path(self.opt.dataroot) / self.opt.phase).glob('**/*')
files = [x for x in p if x.is_file()]
image_grid = torch.tensor([])
for i in range(rows):
image_row = torch.te... | Python | nomic_cornstack_python_v1 |
import tkinter
import sqlite3
class Information
begin
function __init__ self
begin
set window = call Tk
title window string 信息处理
call geometry string 700x370+600+100
set window at string background = string blanchedalmond
comment 隐藏主窗口标题栏
call overrideredirect true
comment self.window.wm_attributes('-topmost',1) # 强制窗口... | import tkinter
import sqlite3
class Information():
def __init__(self):
self.window = tkinter.Tk()
self.window.title('信息处理')
self.window.geometry('700x370+600+100')
self.window["background"] = "blanchedalmond"
self.window.overrideredirect(True) # 隐藏主窗口标题栏
# self.win... | Python | zaydzuhri_stack_edu_python |
function total_request_cost self
begin
set object_list = filter traveller__request=self
return call nz call aggregate dsum=sum string amount_cad at string dsum 0
end function | def total_request_cost(self):
object_list = TravellerCost.objects.filter(traveller__request=self)
return nz(object_list.values("amount_cad").order_by("amount_cad").aggregate(dsum=Sum("amount_cad"))['dsum'], 0) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
from numpy import *
from matplotlib.pyplot import *
import os
function poliplot fnom
begin
set data = call loadtxt fnom
comment data[where(data == 0)] = nan
x label string b
y label string $\lambda$
title string Henon map
comment print data
set data2 = zeros tu... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from numpy import *
from matplotlib.pyplot import *
import os
def poliplot(fnom):
data = loadtxt(fnom)
## data[where(data == 0)] = nan
xlabel('b'); ylabel(r'$\lambda$'); title('Henon map')
## print data
data2 = zeros((data.shape[0], data.shape[1], 3),... | Python | zaydzuhri_stack_edu_python |
while n != 0
begin
set v = integer input
set tuple n v = tuple v n
if v == n
begin
set d = d + 1
end
if d > b
begin
set b = d
end
if n != v
begin
set d = 1
end
end
print b | while n != 0:
v = int(input())
n, v = v, n
if v == n:
d += 1
if d > b:
b = d
if n != v:
d = 1
print(b)
| Python | zaydzuhri_stack_edu_python |
function send self command callbackstdout=none callbackstderr=none
begin
raise NotImplementedError
end function | def send(self, command:Command, callbackstdout=None, callbackstderr=None)->Response:
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function lcn_gpu img3d noise_level=5 filter_size=tuple 27 27 1
begin
set img3d_siz = shape
set volume = filter_size at 0 * filter_size at 1 * filter_size at 2
set conv3d_model = call conv3d_keras filter_size img3d_siz
set img3d = call expand_dims img3d axis=tuple 0 4
set avg = predict conv3d_model img3d / volume
set di... | def lcn_gpu(img3d, noise_level=5, filter_size=(27, 27, 1)):
img3d_siz = img3d.shape
volume = filter_size[0] * filter_size[1] * filter_size[2]
conv3d_model = conv3d_keras(filter_size, img3d_siz)
img3d = np.expand_dims(img3d, axis=(0,4))
avg = conv3d_model.predict(img3d) / volume
diff_sqr = np.squ... | Python | nomic_cornstack_python_v1 |
function dumpwav wavfile ostream opts
begin
function format_sample_big_endian sample
begin
string Format PCM sample as big-endian. Args: sample (bytes): PCM sample. Returns: str: Formatted string.
return print_fmt % call unpack unpack_fmt sample
end function
function format_sample_little_endian sample
begin
string Form... | def dumpwav(wavfile: str, ostream: TextIO, opts: argparse.Namespace) -> None:
def format_sample_big_endian(sample: bytes) -> str:
"""Format PCM sample as big-endian.
Args:
sample (bytes): PCM sample.
Returns:
str: Formatted string.
"""
return print_f... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
set img1 = call imread string Square-circle.png 0
comment Q 1##########
set kernelCircle = call getStructuringElement MORPH_ELLIPSE tuple 5 5
set kernelRect = call getStructuringElement MORPH_RECT tuple 5 5
set dilation1 = call dilate img1 kernelCircle iterations=1
set dilation2 = call dil... | import cv2;
import numpy as np
img1=cv2.imread ('Square-circle.png',0)
#########Q 1##########
kernelCircle= cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
kernelRect= cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
dilation1 = cv2.dilate(img1,kernelCircle,iterations = 1)
dilation2 = cv2.dilate(img1,kernelRect,ite... | Python | zaydzuhri_stack_edu_python |
function crawle_body_dataframe self urlSearch
begin
call get_page_with call ExampleUrl urlSearch call MyRequester lambda result -> call scrap_with result lambda result -> call if_templatize_with_dataframe_do result call ScrapperTemplate lambda templateValue -> call list comprehension iloc at 1 at 0 at i for i in range ... | def crawle_body_dataframe(self, urlSearch: str):
OneBodyParser().get_page_with(
ExampleUrl(urlSearch),
MyRequester(),
lambda result : ExampleScrapper().scrap_with(
result,
lambda result: ExampleScrapper().if_templatize_with_dataframe_do(
... | Python | nomic_cornstack_python_v1 |
function encode mstr
begin
set wordsize = 0
set encoded_msg = string
for i in range length mstr
begin
set ch = mstr at i
set wordsize = wordsize + 1
comment ch is last char in mstr
if i == length mstr - 1
begin
set encoded_msg = encoded_msg + string wordsize + ch
break
end
else
comment look ahead and check if next up ... | def encode(mstr):
wordsize = 0
encoded_msg = ''
for i in range(len(mstr)):
ch = mstr[i]
wordsize = wordsize + 1
if i == len(mstr)-1: # ch is last char in mstr
encoded_msg = encoded_msg + str(wordsize) + ch
break
else:
if ch == mstr[i+1]:... | Python | zaydzuhri_stack_edu_python |
comment Day_20_01_LogisticRegression_indians.py
comment 문제
comment 피마 인디언 당뇨병 데이터로부터
comment 70% 데이터로 학습하고 30% 데이터로 정확도를 계산하세요
comment Day_19_03_LogisticRegression.py
import tensorflow as tf
import numpy as np
from sklearn import model_selection , preprocessing
import pandas as pd
comment def logistic_regression_indian... | # Day_20_01_LogisticRegression_indians.py
# 문제
# 피마 인디언 당뇨병 데이터로부터
# 70% 데이터로 학습하고 30% 데이터로 정확도를 계산하세요
# Day_19_03_LogisticRegression.py
import tensorflow as tf
import numpy as np
from sklearn import model_selection, preprocessing
import pandas as pd
# def logistic_regression_indians():
# pima = pd.read_csv('da... | Python | zaydzuhri_stack_edu_python |
function escribeHola usuario=string Usuario
begin
print string Hola { usuario } . Que tal estás?
end function
function escribeAdios usuario=string Usuario
begin
print string Hasta la proxima { usuario } .
end function | def escribeHola(usuario: str = "Usuario"):
print(f"Hola {usuario}.\nQue tal estás?")
def escribeAdios(usuario: str = "Usuario"):
print(f"Hasta la proxima {usuario}.") | Python | zaydzuhri_stack_edu_python |
comment Даны два действительных числа x и y. Проверьте, принадлежит ли точка
comment с координатами(x,y) заштрихованному квадрату (включая его границу).
comment Если точка принадлежит квадрату, выведите слово YES,иначе выведите слово
comment NO. На рисунке сетка проведена с шагом 1
comment Решение должно содержать функ... | # Даны два действительных числа x и y. Проверьте, принадлежит ли точка
# с координатами(x,y) заштрихованному квадрату (включая его границу).
# Если точка принадлежит квадрату, выведите слово YES,иначе выведите слово
# NO. На рисунке сетка проведена с шагом 1
# Решение должно содержать функцию IsPointInSquare(x, y), воз... | Python | zaydzuhri_stack_edu_python |
import re
function is_palindrome sentence
begin
comment Remove spaces, punctuation marks, and special characters
set cleaned_sentence = sub string [^a-zA-Z0-9] string sentence
comment Convert to lowercase
set cleaned_sentence = lower cleaned_sentence
comment Check if the cleaned sentence is equal to its reverse
if cle... | import re
def is_palindrome(sentence):
# Remove spaces, punctuation marks, and special characters
cleaned_sentence = re.sub(r'[^a-zA-Z0-9]', '', sentence)
# Convert to lowercase
cleaned_sentence = cleaned_sentence.lower()
# Check if the cleaned sentence is equal to its reverse
if cleaned_s... | Python | jtatman_500k |
import sys
string ***NOTE***: Tabs and spaces will be counted as individual characters as well! However, newline characters do not count as characters, and even when they're encapsulated in strings, they're counted as 2 separate characters when parsing through. ##### Referred Example Text/Program: ##### //1 ABCDEFG //2... | import sys
#############################################
'''
***NOTE***: Tabs and spaces will be counted as individual characters as well!
However, newline characters do not count as characters, and even
when they're encapsulated in strings, they're counted as 2 separate
characters ... | Python | zaydzuhri_stack_edu_python |
import pygame as pg
function visualize nn fade=false
begin
call init
set screen = call set_mode tuple 600 600
set input_range = tuple 1 1
set start = tuple 0 0
set step_size = 0.001
for i in range integer input_range at 0 / step_size
begin
for j in range integer input_range at 1 / step_size
begin
set res = predict nn l... | import pygame as pg
def visualize(nn, fade=False):
pg.init()
screen = pg.display.set_mode((600, 600))
input_range = (1, 1)
start = (0, 0)
step_size = 0.001
for i in range(int(input_range[0] / step_size)):
for j in range(int(input_range[1] / step_size)):
res = nn.... | Python | zaydzuhri_stack_edu_python |
for i in range list1
begin
append nlist1 integer input string enter the values :
end
print string list: nlist1
function convert list
begin
return tuple nlist1
end function
print string converted to tuple call convert nlist1 | for i in range(list1):
nlist1.append(int(input("enter the values :")))
print("list:",nlist1)
def convert(list):
return tuple(nlist1)
print("converted to tuple", convert(nlist1)) | Python | zaydzuhri_stack_edu_python |
import numpy as np
import urllib
import json
import cv2
import os
import sys
function image_to_sketch image
begin
try
begin
comment convert to gray scale
set grayImage = call cvtColor image COLOR_BGR2GRAY
comment invert the gray image
set grayImageInv = 255 - grayImage
comment Apply gaussian blur
set grayImageInv = cal... | import numpy as np
import urllib
import json
import cv2
import os
import sys
def image_to_sketch(image):
try:
# convert to gray scale
grayImage = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# invert the gray image
grayImageInv = 255 - grayImage
# Apply gaussian blur
gra... | Python | zaydzuhri_stack_edu_python |
function iter_path_urls node_ids cursor
begin
for tuple i node_id in enumerate node_ids
begin
yield call find_node_url_by_id node_id cursor
end
end function | def iter_path_urls(node_ids, cursor):
for i, node_id in enumerate(node_ids):
yield find_node_url_by_id(node_id, cursor) | Python | nomic_cornstack_python_v1 |
function autolabel rects
begin
for rect in rects
begin
set height = call get_height
if height > 0
begin
annotate format string {} height xy=tuple call get_x + call get_width / 2 height xytext=tuple 0 3 textcoords=string offset points ha=string center va=string bottom
end
end
end function
comment 3 points vertical offse... | def autolabel(rects):
for rect in rects:
height = rect.get_height()
if height > 0:
ax.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 3), # 3 points vertical offset
textcoo... | Python | nomic_cornstack_python_v1 |
import networkx as nx
import matplotlib.pyplot as plt
set G = call Graph
comment pos=nx.spring_layout(G)
call add_nodes_from list range 1 31881
comment Generate trip =================================
set tripsfileopen = open string tripPaths.txt string r
set line = read line tripsfileopen
set tripDict = dict
while lin... | import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
# pos=nx.spring_layout(G)
G.add_nodes_from(list(range(1, 31881)))
# Generate trip =================================
tripsfileopen = open("tripPaths.txt", "r")
line = tripsfileopen.readline()
tripDict = {}
while line!="":
tripStrings = line.strip(... | Python | zaydzuhri_stack_edu_python |
function create_tables
begin
set commands = tuple string CREATE TABLE users (user_id serial PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, picture VARCHAR(255)); string CREATE TABLE categories (id integer PRIMARY KEY, name VARCHAR(255) NOT NULL, user_id integer, FOREIGN KEY (user_id) REFERENCES u... | def create_tables():
commands = (
"""
CREATE TABLE users (user_id serial PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
picture VARCHAR(255));
""",
""" CREATE TABLE categories (id integer PRIMARY KEY,
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from dolfin import UnitSquareMesh , UnitIntervalMesh , FunctionSpace , grad , DirichletBC , Expression , inner , dx , Constant , plot , ds , Function , DOLFIN_EPS , TestFunction
from nlpmodel import NLPModel
from pdemodel import PDENLPModel
import numpy as np | # -*- coding: utf-8 -*-
from dolfin import UnitSquareMesh, UnitIntervalMesh, FunctionSpace, grad, \
DirichletBC, Expression, inner, dx, Constant, plot, ds, \
Function, DOLFIN_EPS, TestFunction
from nlpmodel import NLPModel
from pdemodel import PDENLPModel
import numpy as np
| Python | zaydzuhri_stack_edu_python |
function test amount=string 27.00 zip_code=string 85030
begin
import os , time
from livesettings import config_get_group
comment Set up some dummy classes to mimic classes being passed through Satchmo
class testContact extends object
begin
pass
end class
class testCC extends object
begin
pass
end class
class testOrder ... | def test(amount="27.00",zip_code="85030"):
import os, time
from livesettings import config_get_group
# Set up some dummy classes to mimic classes being passed through Satchmo
class testContact(object):
pass
class testCC(object):
pass
class testOrder(object):
def __init__... | Python | nomic_cornstack_python_v1 |
function to_type_name name
begin
return join string generator expression upper part at slice : 1 : + part at slice 1 : : for part in split name string _
end function | def to_type_name(name):
return "".join(part[:1].upper() + part[1:] for part in name.split("_")) | Python | nomic_cornstack_python_v1 |
string Written by Jyo Pari and Joseph L. Hora Parts of the code for using MobileNets were taken from: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/label_image/label_image.py
import cv2
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from operator import itemget... | '''
Written by Jyo Pari and Joseph L. Hora
Parts of the code for using MobileNets were taken from:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/label_image/label_image.py
'''
import cv2
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from operator import ite... | Python | zaydzuhri_stack_edu_python |
function summarize_article text
begin
set sentence_list = split text string .
set summary = list
for sentence in sentence_list
begin
if string imagination in sentence or string inventiveness in sentence
begin
append summary sentence
end
end
return join string . summary + string .
end function
print call summarize_arti... | def summarize_article(text):
sentence_list = text.split(". ")
summary = []
for sentence in sentence_list:
if "imagination" in sentence or "inventiveness" in sentence:
summary.append(sentence)
return '. '.join(summary) + '.'
print(summarize_article(text))
# Output
"Einstein once sai... | Python | iamtarun_python_18k_alpaca |
function __eq__ self other
begin
if not is instance other SignResponse
begin
return false
end
return __dict__ == __dict__
end function | def __eq__(self, other):
if not isinstance(other, SignResponse):
return False
return self.__dict__ == other.__dict__ | Python | nomic_cornstack_python_v1 |
from imutils import paths
import face_recognition
import pickle
import cv2
import os
comment get paths of each file in folder named data
comment Different folders are created to hold different persons images separately
set imagePaths = list call list_images string data
set knownEncodings = list
set knownNames = list
... | from imutils import paths
import face_recognition
import pickle
import cv2
import os
#get paths of each file in folder named data
#Different folders are created to hold different persons images separately
imagePaths = list(paths.list_images('data'))
knownEncodings = []
knownNames = []
# loop over the image paths
for... | Python | zaydzuhri_stack_edu_python |
import sys
import json
import os
if __name__ == string __main__
begin
if length argv != 3
begin
print string Usage: python nouns_counter.py [input_directory] [output_file]
exit - 1
end
set input_dir = argv at 1
set output_file = argv at 2
comment Only use files ending with 'triples.json' in the input directory
set file... | import sys
import json
import os
if __name__ == '__main__':
if len(sys.argv) != 3:
print('Usage: python nouns_counter.py [input_directory] [output_file]')
sys.exit(-1)
input_dir = sys.argv[1]
output_file = sys.argv[2]
# Only use files ending with 'triples.json' in the input directory... | Python | zaydzuhri_stack_edu_python |
comment 导包 json
import json
comment #打开json文件并获取文件流
comment with open("../data/login.json","r",encoding="utf-8")as f:
comment #调用load方法加文件流
comment data=json.load(f)
comment print("获取的数据为:",data)
comment 使用函数进行封装
comment def read_json():
comment with open("../data/login.json","r",encoding="utf-8")as f:
comment #调用load方... | #导包 json
import json
# #打开json文件并获取文件流
# with open("../data/login.json","r",encoding="utf-8")as f:
# #调用load方法加文件流
# data=json.load(f)
# print("获取的数据为:",data)
#使用函数进行封装
# def read_json():
# with open("../data/login.json","r",encoding="utf-8")as f:
# #调用load方法加文件流
# return json.load(f)
... | Python | zaydzuhri_stack_edu_python |
import math
print string Welcome to Quadratic Equation Solver
while true
begin
print string Please input your variables: a, b, c
try
begin
set a_input = input string a:
set b_input = input string b:
set c_input = input string c:
set a = integer a_input
set b = integer b_input
set c = integer c_input
set delta = b * b -... | import math
print("Welcome to Quadratic Equation Solver")
while True:
print("Please input your variables: a, b, c")
try:
a_input = input("a: ")
b_input = input("b: ")
c_input = input("c: ")
a = int(a_input)
b = int(b_input)
c = int(c_input)
delta = b*b... | Python | zaydzuhri_stack_edu_python |
for num in square
begin
set sum = sum + num
end
print string suare of sum is { sum } | for num in square:
sum += num
print(f"suare of sum is {sum}")
| Python | zaydzuhri_stack_edu_python |
function initGrid self name suffix n ni nj ifields=list rfields=list lsize=10
begin
comment print "initGrid: initializing %s"%(name)
set name = name
set suffix = suffix
set n = n
set ni = ni
set nj = nj
set ifields = ifields
set rfields = rfields
comment print "ifields=%s\nrfields=%s\nlsize=%d"%(temp_ifields, temp_rf... | def initGrid( self, name, suffix, n, ni, nj, ifields=[],rfields=[], lsize=10):
#print "initGrid: initializing %s"%(name)
self.name = name
self.suffix = suffix
self.n = n
self.ni = ni
self.nj = nj
self.ifields = ifields
self.rfields = rfields
#prin... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
import dlib
from imutils import face_utils
from playsound import playsound
import time
import requests
set cap = call VideoCapture 0
set detector = call get_frontal_face_detector
set predictor = call shape_predictor string shape_predictor_68_face_landmarks.dat
set sleep = 0
set drowsy = 0
... | import cv2
import numpy as np
import dlib
from imutils import face_utils
from playsound import playsound
import time
import requests
cap = cv2.VideoCapture(0)
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
sleep = 0
drowsy = 0
active = 0
status="... | Python | zaydzuhri_stack_edu_python |
comment https://xlsxwriter.readthedocs.io/index.html
comment conda install XlsxWriter
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell , xl_range_abs
set nrow = 1
set nline = 64
set xlsxname = string DAT/mus.xlsx
set wb = call Workbook xlsxname
set Nst = 50
set Ned = 50
for k in range Nst Ned - 1 - 1
... | # https://xlsxwriter.readthedocs.io/index.html
# conda install XlsxWriter
import xlsxwriter
from xlsxwriter.utility import xl_rowcol_to_cell, xl_range_abs
nrow = 1
nline = 64
xlsxname = 'DAT/mus.xlsx'
wb = xlsxwriter.Workbook(xlsxname)
Nst = 50
Ned = 50
for k in range(Nst, Ned-1, -1):
dirname = 'MELT_{0:03d}... | Python | zaydzuhri_stack_edu_python |
function pop tree val key=_key_func
begin
if tree is none
begin
return tuple tree none
end
else
if call key call value tree == call key val
begin
if call left tree
begin
set tuple left_node new_val = call pop_max call left tree
return tuple call make_node left_node new_val call right tree val
end
else
begin
return tupl... | def pop(tree, val, key=_key_func):
if tree is None:
return tree, None
elif key(value(tree)) == key(val):
if left(tree):
left_node, new_val = pop_max(left(tree))
return make_node(left_node, new_val, right(tree)), val
else:
return right(tree), val
el... | Python | nomic_cornstack_python_v1 |
comment pylint: disable=R0914
function main notebook_json file_descriptor process_cells command skip_celltags dont_skip_bad_cells
begin
set cells = notebook_json at string cells
set result = list
set cell_mapping = dict 0 string cell_0:0
set index = index line_number=0 cell_number=0
set trailing_semicolons = set
set t... | def main( # pylint: disable=R0914
notebook_json: MutableMapping[str, Any],
file_descriptor: int,
process_cells: Sequence[str],
command: str,
skip_celltags: Sequence[str],
*,
dont_skip_bad_cells: bool,
) -> NotebookInfo:
cells = notebook_json["cells"]
result = []
cell_mapping = ... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import math
import numpy as np
comment good posture csv
set DFGOOD = read csv string goodOutputs/CSV/ytc1good.csv
set DFGOOD = replace DFGOOD 0 nan
set DFGOOD = drop DFGOOD columns=list string framenum
set DFGOOD = drop DFGOOD columns at slice 2 : : 3 axis=1
comment input posture csv
set DFBAD = re... | import pandas as pd
import math
import numpy as np
#good posture csv
DFGOOD = pd.read_csv('goodOutputs/CSV/ytc1good.csv')
DFGOOD = DFGOOD.replace(0, np.nan)
DFGOOD= DFGOOD.drop(columns=['framenum'])
DFGOOD = DFGOOD.drop(DFGOOD.columns[2::3], axis=1)
#input posture csv
DFBAD = pd.read_csv('badOutputs/CSV/ytc1bad.csv')... | Python | zaydzuhri_stack_edu_python |
string Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000. Example 1: Input: "bbbab" Output: 4 One possible longest palindromic subsequence is "bbbb". Example 2: Input: "cbbd" Output: 2 One possible longest palindromic subsequence is "bb".
class... | """
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
Example 1:
Input:
"bbbab"
Output:
4
One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"
Output:
2
One possible longest palindromic subsequence is "bb".
"""
... | Python | zaydzuhri_stack_edu_python |
import urllib.request
import re
import os
class HtmlParser
begin
function __init__ self html
begin
set html_address = html
end function
function __get_html self
begin
with url open html_address as html
begin
set content = string decode read html string utf-8
end
end function
function __references_substitution self cont... | import urllib.request
import re
import os
class HtmlParser:
def __init__(self, html):
self.html_address = html
def __get_html(self):
with urllib.request.urlopen(self.html_address) as html:
self.content = str(html.read().decode('utf-8'))
def __references_substit... | Python | zaydzuhri_stack_edu_python |
string This module contains ImageURL class representing website image absolute url.
import re
class ImageURL
begin
string Represents website image absolute url. The class is responsible for url validation and normalization.
set EXTENSION_WHITE_LIST = list string jpg string png
function __init__ self image_url extension... | """This module contains ImageURL class representing website image absolute url."""
import re
class ImageURL:
"""Represents website image absolute url. The class is responsible for url validation and normalization."""
EXTENSION_WHITE_LIST = ['jpg', 'png']
def __init__(self, image_url, extension_white_lis... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
set n = input string Digite o número de elementos da primeira lista:
set l1 = list
for i in range 0 n 1
begin
append l1 decimal input string digite o valor%d: % i + 1
end
set n = input string Digite o número de elementos da segunda lista:
set l2 = list
for i in range 0 n 1
begin
append l... | # -*- coding: utf-8 -*-
n=input('Digite o número de elementos da primeira lista:')
l1=[]
for i in range(0,n,1):
l1.append(float(input('digite o valor%d:' %(i+1))))
n=input('Digite o número de elementos da segunda lista:')
l2=[]
for i in range(0,n,1):
l2.append(float(input('digite o valor%d:' %(i+1))))
lf=[x f... | Python | zaydzuhri_stack_edu_python |
function test_character_move_to_room self character other_character room other_room
begin
with raises TypeError
begin
call move_to_room none
end
set msgs = list string {s} leave{ss}. string {s} arrive{ss}.
assert not room
call move_to_room room *msgs
comment They had no room to leave from, so no departure message.
asse... | def test_character_move_to_room(self, character, other_character,
room, other_room):
with pytest.raises(TypeError):
character.move_to_room(None)
msgs = ["{s} leave{ss}.", "{s} arrive{ss}."]
assert not character.room
character.move_to_room(r... | Python | nomic_cornstack_python_v1 |
function __init__ self users M delta S_thresh
begin
set users = users
set M = M
set delta = delta
set S_thresh = S_thresh
set all_users_digraphs_train = list comprehension none for user in users
set all_users_digraphs_valid = list comprehension none for user in users
set all_users_digraphs_test = list comprehension non... | def __init__(self, users, M, delta, S_thresh):
self.users = users
self.M = M
self.delta = delta
self.S_thresh = S_thresh
self.all_users_digraphs_train = [None for user in self.users]
self.all_users_digraphs_valid = [None for user in self.users]
self.all_users_dig... | Python | nomic_cornstack_python_v1 |
function rotate img angle=random integer - 1 1 center=none scale=1.0 u=0.5
begin
if random < u
begin
set tuple h w = shape at slice : 2 :
if center is none
begin
set center = tuple w / 2 h / 2
end
comment perform the rotation
set M = call getRotationMatrix2D center angle scale
set img = call warpAffine img M tuple w ... | def rotate(img, angle=randint(-1, 1), center=None, scale=1.0, u=0.5):
if np.random.random() < u:
(h, w) = img.shape[:2]
if center is None:
center = (w / 2, h / 2)
# perform the rotation
M = cv2.getRotationMatrix2D(center, angle, scale)
img = cv2.warpAffine(img, ... | Python | nomic_cornstack_python_v1 |
string Caesar Ciphers are one of the most basic forms of encryption. It consists of a message and a key, and it shifts the letters of the message for the value of the key. Your task is to create a function encryptor that takes 2 arguments - key and message - and returns the encrypted message. A message 'Caesar Cipher' ... | '''
Caesar Ciphers are one of the most basic forms of encryption.
It consists of a message and a key, and it shifts the letters of the message for the value of the key.
Your task is to create a function encryptor that takes 2 arguments
- key and message - and returns the encrypted message.
A message 'Caesar Cipher' ... | Python | zaydzuhri_stack_edu_python |
function get self project
begin
try
begin
set data = call request project + string /
end
except any
begin
raise
end
if not is instance data CLAMData
begin
raise exception string Unable to retrieve CLAM Data
end
else
begin
return data
end
end function | def get(self, project):
try:
data = self.request(project + '/')
except:
raise
if not isinstance(data, clam.common.data.CLAMData):
raise Exception("Unable to retrieve CLAM Data")
else:
return data | Python | nomic_cornstack_python_v1 |
function __lt__ self argument
begin
raise NotImplementedError
end function | def __lt__(self, argument):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function update_action_space_internal self
begin
set B = call predict_goal_location - pos at tuple agent_number slice : :
set n = array list 0.0 0.0 - 1.0
set nB = call cross n B
set BnB = call cross B nB
set action_space = zeros 6 object
set action_space at 0 = B
set action_space at 1 = - B
set action_space at 2 = ... | def update_action_space_internal(self) -> np.ndarray:
B = self.predict_goal_location()-self.pos[self.agent_number, :]
n = np.array([0., 0., -1.])
nB = np.cross(n, B)
BnB = np.cross(B, nB)
action_space = np.zeros(6, object)
action_space[0] = B
action_space[1] = ... | Python | nomic_cornstack_python_v1 |
comment Write code that uses the string stored in org and creates an acronym which is assigned to the variable acro.
comment Only the first letter of each word should be used, each letter in the acronym should be a capital letter,
comment and there should be nothing to separate the letters of the acronym.
comment Words... | #Write code that uses the string stored in org and creates an acronym which is assigned to the variable acro.
# Only the first letter of each word should be used, each letter in the acronym should be a capital letter,
# and there should be nothing to separate the letters of the acronym.
# Words that should not be inclu... | Python | zaydzuhri_stack_edu_python |
function back self
begin
string Go back in history if possible. Return the undone item.
if _index <= 0
begin
return none
end
set undone = current_item
set _index = _index - 1
call _check_index
return undone
end function | def back(self):
"""Go back in history if possible.
Return the undone item.
"""
if self._index <= 0:
return None
undone = self.current_item
self._index -= 1
self._check_index()
return undone | Python | jtatman_500k |
function setup self
begin
setup ScriptedLoadableModuleWidget self
comment Load widget from .ui file (created by Qt Designer).
comment Additional widgets can be instantiated manually and added to self.layout.
set uiWidget = call loadUI call resourcePath string UI/LeadOR.ui
call addWidget uiWidget
set ui = call childWidg... | def setup(self):
ScriptedLoadableModuleWidget.setup(self)
# Load widget from .ui file (created by Qt Designer).
# Additional widgets can be instantiated manually and added to self.layout.
uiWidget = slicer.util.loadUI(self.resourcePath('UI/LeadOR.ui'))
self.layout.addWidget(uiWidget)
self.ui = ... | Python | nomic_cornstack_python_v1 |
function user self
begin
return user
end function | def user(self):
return self._project.user | Python | nomic_cornstack_python_v1 |
function from_cli_args cls args
begin
set params_str = pop args string user_params none
set params_file = pop args string user_params_file none
if params_str
begin
set user_params = call read_yaml params_str user_params_schema
end
else
if params_file
begin
set user_params = call read_yaml_from_file_path params_file use... | def from_cli_args(cls, args: dict):
params_str = args.pop("user_params", None)
params_file = args.pop("user_params_file", None)
if params_str:
user_params = util.read_yaml(params_str, cls.user_params_schema)
elif params_file:
user_params = util.read_yaml_from_fil... | Python | nomic_cornstack_python_v1 |
function add_vertex self vertex_id dirs
begin
set vertices at vertex_id = dictionary comprehension i : string ? for i in dirs
end function | def add_vertex(self, vertex_id, dirs):
self.vertices[vertex_id] = {i: "?" for i in dirs} | Python | nomic_cornstack_python_v1 |
function load_label self rec ann=none sampfrom=none sampto=none fmt=string a
begin
set header = call rdheader string call get_absolute_path rec
set label = comments at 0
if lower fmt in list string a string abbr string abbreviation
begin
set label = _labels_f2a at label
end
else
if lower fmt in list string n string num... | def load_label(
self,
rec: Union[str, int],
ann: Optional[wfdb.Annotation] = None,
sampfrom: Optional[int] = None,
sampto: Optional[int] = None,
fmt: str = "a",
) -> str:
header = wfdb.rdheader(str(self.get_absolute_path(rec)))
label = header.comments[... | Python | nomic_cornstack_python_v1 |
function start logger full_id hyperparameter=none dataset_id=none server=string local insights=false
begin
set id = none
if count full_id string / == 1
begin
set tuple owner name = split full_id string /
end
else
if count full_id string / >= 2
begin
set tuple owner name id = call unpack_full_job_id full_id
end
else
beg... | def start(logger, full_id, hyperparameter=None, dataset_id=None, server='local', insights=False):
id = None
if full_id.count('/') == 1:
owner, name = full_id.split('/')
elif full_id.count('/') >= 2:
owner, name, id = unpack_full_job_id(full_id)
else:
logger.error("Invalid id %s ... | Python | nomic_cornstack_python_v1 |
import json
import pandas as pd
class PandasDataFrameDeserializer
begin
string Base class implementing deserialization of data from API to Pandas DataFrames. Inheriting from this class it is required to: Override attribute ``field_mapping`` OR Override class method ``get_field_mapping()`` You may want to use ``get_fiel... | import json
import pandas as pd
class PandasDataFrameDeserializer:
"""
Base class implementing deserialization of data from API to Pandas DataFrames.
Inheriting from this class it is required to:
Override attribute ``field_mapping``
OR
Override class method ``get_field_mapping()`... | Python | zaydzuhri_stack_edu_python |
function get_trial_idx_from_win_idx spikes col=string win_idx
begin
return as type ceil drop missing spikes at col / 2 int - 1
end function | def get_trial_idx_from_win_idx(spikes, col='win_idx'):
return np.ceil(spikes[col].dropna() / 2).astype(np.int) - 1 | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment File created on 02 May 2013
from __future__ import division
from qiime.util import parse_command_line_parameters , make_option
import qiime.fizzy as fizzy
set __author__ = string Gregory Ditzler
set __copyright__ = string Copyright 2011, The QIIME project
set __credits__ = list stri... | #!/usr/bin/env python
# File created on 02 May 2013
from __future__ import division
from qiime.util import parse_command_line_parameters, make_option
import qiime.fizzy as fizzy
__author__ = "Gregory Ditzler"
__copyright__ = "Copyright 2011, The QIIME project"
__credits__ = ["Gregory Ditzler", "Calvin Morrison","Gail... | Python | zaydzuhri_stack_edu_python |
comment random password generator (16 digit password)
comment import the 'random' module
import random
import string
comment if statement here to prompt user to say yes or no to a random generated password
set inp = input string Would you like to generate a password? Type yes or no: + string
if inp == string yes
begin
... | # random password generator (16 digit password)
# import the 'random' module
import random
import string
# if statement here to prompt user to say yes or no to a random generated password
inp = input('Would you like to generate a password? Type yes or no: ' + '\n')
if inp == 'yes':
# this will just c... | Python | zaydzuhri_stack_edu_python |
from collections import deque
function get_pandigitals current=0 remaining=set literal 0 1 2 3 4 5 6 7 8 9
begin
if not remaining
begin
yield current
end
for number in remaining
begin
if current == 0 and number == 0
begin
continue
end
set current = current * 10
set current = current + number
yield from call get_pandigi... | from collections import deque
def get_pandigitals(current=0, remaining={0, 1, 2, 3, 4, 5, 6, 7, 8, 9}):
if not remaining:
yield current
for number in remaining:
if current == 0 and number == 0:
continue
current *= 10
current += number
yield from get_pandigit... | Python | zaydzuhri_stack_edu_python |
function fibonacci
begin
set a = 0
set b = 1
while true
begin
yield b
set tuple a b = tuple b a + b
end
end function
for tuple i n in enumerate call fibonacci start=1
begin
if length string n == 1000
begin
break
end
end
print i | def fibonacci():
a = 0
b = 1
while True:
yield b
a, b = b, a + b
for i, n in enumerate(fibonacci(), start=1):
if len(str(n)) == 1000:
break
print(i)
| Python | zaydzuhri_stack_edu_python |
import csv
function read_line_by_line
begin
with open string input-data.csv as csv_file
begin
set csv_reader = reader csv_file delimiter=string ,
set line_count = 0
for row in csv_reader
begin
if line_count == 0
begin
print string Column names are { join string , row }
set line_count = line_count + 1
end
else
begin
pri... | import csv
def read_line_by_line():
with open('input-data.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count += 1
... | Python | zaydzuhri_stack_edu_python |
function make_jk_id N2d edges mask ra_ref ra_range dec_range ncen maxiter tol
begin
set radec = zeros tuple length flatten N2d 2
set Ngal = zeros tuple length flatten N2d 1
set ii = list
set jj = list
set nn = list
for i in range length N2d
begin
for j in range length N2d at 0
begin
set ra_fixed = edges at 1 at j + ... | def make_jk_id(N2d, edges, mask, ra_ref, ra_range, dec_range, ncen, maxiter, tol):
radec = np.zeros((len(N2d.flatten()),2))
Ngal = np.zeros((len(N2d.flatten()),1))
ii = []
jj = []
nn = []
for i in range(len(N2d)):
for j in range(len(N2d[0])):
ra_fixed = ((edges[1][j]+edges[1]... | Python | nomic_cornstack_python_v1 |
function generate_and_save_images model epoch test_input
begin
comment Training is set to false
comment so all layers run in inference mode (batchnorm)(?)
set predictions = model test_input training=false
set fig = figure figsize=tuple 4 4
for i in range shape at 0
begin
subplot 4 4 i + 1
comment Turn prediction into t... | def generate_and_save_images(model, epoch, test_input):
#Training is set to false
#so all layers run in inference mode (batchnorm)(?)
predictions = model(test_input, training=False)
fig = plt.figure(figsize=(4,4))
for i in range(predictions.shape[0]):
plt.subplot(4,4, i+1)
img = tf.c... | Python | nomic_cornstack_python_v1 |
function encrypt_file key in_filename out_filename=none chunksize=64 * 1024
begin
if not out_filename
begin
set out_filename = in_filename + string .enc
end
string Initialize a vector to prevent repetition in encryption. Generate an encryptor
set iv = join string generator expression character random integer 0 255 for... | def encrypt_file(key, in_filename, out_filename=None, chunksize=64*1024):
if not out_filename:
out_filename = in_filename + '.enc'
""" Initialize a vector to prevent repetition in encryption.
Generate an encryptor
"""
iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
en... | Python | nomic_cornstack_python_v1 |
function _link_jobs self
begin
for tuple i j in enumerate jobs
begin
call link self i
call claim_artifacts
end
end function | def _link_jobs(self):
for i, j in enumerate(self.jobs):
j.link(self, i)
j.claim_artifacts() | Python | nomic_cornstack_python_v1 |
set num1 = decimal call raw_input string Enter a number:
set num2 = decimal call raw_input string Enter another number:
set num3 = decimal call raw_input string Enter other number: | num1 = float(raw_input("Enter a number: "))
num2 = float(raw_input("Enter another number: "))
num3 = float(raw_input("Enter other number: "))
| Python | zaydzuhri_stack_edu_python |
function _has_hash path expected_hash
begin
if not exists path path
begin
return false
end
return call file_hash path == expected_hash
end function | def _has_hash(path: str, expected_hash: str) -> bool:
if not os.path.exists(path):
return False
return file_hash(path) == expected_hash | Python | nomic_cornstack_python_v1 |
function basicFeatureExtractor datum
begin
set features = zeros like datum dtype=int
set features at datum > 0 = 1
return flatten features
end function | def basicFeatureExtractor(datum):
features = np.zeros_like(datum, dtype=int)
features[datum > 0] = 1
return features.flatten() | Python | nomic_cornstack_python_v1 |
function compound
begin
comment Create a compound
set compound = call TopoDS_Compound
set builder = call BRep_Builder
call MakeCompound compound
comment Populate the compound
add builder compound call box_shape
add builder compound call sphere_shape
return compound
end function | def compound():
# Create a compound
compound = OCC.TopoDS.TopoDS_Compound()
builder = OCC.BRep.BRep_Builder()
builder.MakeCompound(compound)
# Populate the compound
builder.Add(compound, box_shape())
builder.Add(compound, sphere_shape())
return compound | Python | nomic_cornstack_python_v1 |
function get_long_description
begin
set descr = list
for fname in tuple string README.md
begin
with open fname encoding=string utf-8 as f
begin
append descr read f
end
end
return join string descr
end function | def get_long_description():
descr = []
for fname in ('README.md',):
with io.open(fname, encoding='utf-8') as f:
descr.append(f.read())
return '\n\n'.join(descr) | Python | nomic_cornstack_python_v1 |
function reshape self partial_shaping=false allow_up_sizing=false **kwargs
begin
string Return a new executor with the same symbol and shared memory, but different input/output shapes. For runtime reshaping, variable length sequences, etc. The returned executor shares state with the current one, and cannot be used in p... | def reshape(self, partial_shaping=False, allow_up_sizing=False, **kwargs):
"""Return a new executor with the same symbol and shared memory,
but different input/output shapes.
For runtime reshaping, variable length sequences, etc.
The returned executor shares state with the current one,
... | Python | jtatman_500k |
function RecordMonitoringStats self start_time request response prpc_context now=none
begin
set now = now or time
set elapsed_ms = integer now - start_time * 1000
set method_name = __name__
if ends with method_name string Request
begin
set method_name = method_name at slice : - length string Request :
end
set method_... | def RecordMonitoringStats(
self, start_time, request, response, prpc_context, now=None):
now = now or time.time()
elapsed_ms = int((now - start_time) * 1000)
method_name = request.__class__.__name__
if method_name.endswith('Request'):
method_name = method_name[:-len('Request')]
method_id... | Python | nomic_cornstack_python_v1 |
function timestamps indexed=false
begin
return tuple call Column string created_at timestamp sa timezone=true server_default=now nullable=false index=indexed call Column string updated_at timestamp sa timezone=true server_default=now nullable=false index=indexed
end function | def timestamps(indexed: bool = False) -> Tuple[sa.Column, sa.Column]:
return (
sa.Column(
"created_at",
sa.TIMESTAMP(timezone=True),
server_default=sa.func.now(),
nullable=False,
index=indexed,
),
sa.Column(
"updated_at"... | Python | nomic_cornstack_python_v1 |
function cognito_callback staff_site request
begin
set settings = ferlysettings
set code = get params string code
if not code or length code > 100
begin
raise call HTTPBadRequest
end
set token_url = string https://%s/oauth2/token % cognito_domain
set token_data = list tuple string grant_type string authorization_code t... | def cognito_callback(staff_site, request):
settings = request.ferlysettings
code = request.params.get('code')
if not code or len(code) > 100:
raise HTTPBadRequest()
token_url = 'https://%s/oauth2/token' % settings.cognito_domain
token_data = [
('grant_type', 'authorization_code'),
... | Python | nomic_cornstack_python_v1 |
import socket
import hashlib
function get_remote_machine_info
begin
set host = string www.ifce.edu.br
end function | import socket
import hashlib
def get_remote_machine_info():
host = 'www.ifce.edu.br' | Python | zaydzuhri_stack_edu_python |
string NAME Archivo_Fasta VERSION 1.0 AUTHOR Victor Jesus Enriquez Castro <victorec@lcg.unam.mx> DESCRIPTION El modulo Archivo_Fasta.py del package Modulos se utiliza para convertir archivos con secuencias en formato .txt a .fasta CATEGORY Fasta Files USAGE import Modulos.Archivo_Fasta import Modulos.Archivo_Fasta.[fun... | '''
NAME
Archivo_Fasta
VERSION
1.0
AUTHOR
Victor Jesus Enriquez Castro <victorec@lcg.unam.mx>
DESCRIPTION
El modulo Archivo_Fasta.py del package Modulos se utiliza para
convertir archivos con secuencias en formato .txt a .fasta
CATEGORY
Fasta Files
USAGE
... | Python | zaydzuhri_stack_edu_python |
function td2_ex_h1 h1 p1 p2 t1 df1 df2
begin
return call td_ex_pv h1 / 100 * call pv t1 p1 df1 p2 df2
end function | def td2_ex_h1(h1, p1, p2, t1, df1, df2):
return td_ex_pv(h1/100*pv(t1, p1, df1), p2, df2) | Python | nomic_cornstack_python_v1 |
function genkeys ssh_folder password
begin
set out = call gen_keypair ssh_folder password
call echo out
end function | def genkeys(ssh_folder, password):
out = gen_keypair(ssh_folder, password)
click.echo(out) | Python | nomic_cornstack_python_v1 |
function select_tiles_by_geom self geom sref=none active_only=true apply_mask=true
begin
set intsctd_raster_geom = call slice_by_geom geom snap_to_grid=true inplace=false
if intsctd_raster_geom is none
begin
return none
end
set tuple intsctd_mosaic_height intsctd_mosaic_width = shape
set selected_tiles = dictionary
for... | def select_tiles_by_geom(self, geom, sref=None, active_only=True, apply_mask=True) -> dict:
intsctd_raster_geom = self._raster_geom.slice_by_geom(geom, snap_to_grid=True, inplace=False)
if intsctd_raster_geom is None:
return None
intsctd_mosaic_height, intsctd_mosaic_width = intsctd... | 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.