code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
class Packet
begin
string This class is used to represent an AMIE packet The attributes of packet can be accessed directly like packet.packet_rec_id The data of packet should use set and get methods to access. For example, packet.get_value('UserEmail', 'john.deo@example.com') packet.set_value('UserEmail')
function __in... | class Packet():
"""
This class is used to represent an AMIE packet
The attributes of packet can be accessed directly like packet.packet_rec_id
The data of packet should use set and get methods to access.
For example,
packet.get_value('UserEmail', 'john.deo@example.com')
pack... | Python | zaydzuhri_stack_edu_python |
comment Dependecies
comment scipy = 0.17.0
comment gensim = 1.0.1
comment pandas = 0.19.2
comment numpy = 1.11.2
comment I used DATA_HADM.csv created using feature_extraction_nonseq.ipynb
import pandas as pd
import pickle
import random
import re
from gensim.models import Word2Vec
from gensim import utils
from time impo... | #### Dependecies
#scipy = 0.17.0
#gensim = 1.0.1
#pandas = 0.19.2
#numpy = 1.11.2
#### I used DATA_HADM.csv created using feature_extraction_nonseq.ipynb
import pandas as pd
import pickle
import random
import re
from gensim.models import Word2Vec
from gensim import utils
from time import time
class WordVecGenerato... | Python | zaydzuhri_stack_edu_python |
import os
print path
change directory string C:\Users\HP\Desktop\PYTHON WORKS\
change directory string C:\Users\HP\Desktop\..\..
print get current directory
change directory string C:\Users\HP\Desktop\PYTHON WORKS\
comment os.mkdir('C:\\Users\\HP\\Desktop\\PYTHON WORKS\\Python_Path_Creation_Testing')
print get current ... | import os
print(os.path)
os.chdir('C:\\Users\\HP\\Desktop\\PYTHON WORKS\\')
os.chdir('C:\\Users\\HP\\Desktop\\..\\..')
print(os.getcwd())
os.chdir('C:\\Users\\HP\\Desktop\\PYTHON WORKS\\')
#os.mkdir('C:\\Users\\HP\\Desktop\\PYTHON WORKS\\Python_Path_Creation_Testing')
print(os.getcwd())
#os.removedirs('C:... | Python | zaydzuhri_stack_edu_python |
import math
from vector import Vector , intersection
import world as WorldModule
set BOULDER_RADIUS_MODIFIER = 1.0
set CRATER_RADIUS_MODIFIER = 1.0
class PathRecursionDepth extends Exception
begin
pass
end class
function find_path start goal world depth=0
begin
if depth > 10
begin
raise PathRecursionDepth
end
comment F... | import math
from vector import Vector, intersection
import world as WorldModule
BOULDER_RADIUS_MODIFIER = 1.0
CRATER_RADIUS_MODIFIER = 1.0
class PathRecursionDepth(Exception):
pass
def find_path(start, goal, world, depth=0):
if depth > 10:
raise PathRecursionDepth
# Find obstacles along the path ... | Python | zaydzuhri_stack_edu_python |
function inputs list=list
begin
set a = input string Введіть елемент Enter для продовження
if a == string
begin
return list
end
else
begin
append list a
return call inputs list
end
end function
function mins list minind=0 ind=1
begin
if ind == length list
begin
return list at minind
end
else
if decimal list at minind ... | def inputs(list = []):
a = input("Введіть елемент\nEnter для продовження\n")
if a == "":
return list
else:
list.append(a)
return inputs(list)
def mins(list, minind = 0, ind = 1):
if ind == len(list):
return list[minind]
elif float(list[minind]) <= flo... | Python | zaydzuhri_stack_edu_python |
function full_like obj fill_value dtype=none
begin
comment Grab the Flat or Pivot out of the CodedArray
set obj = obj
if dtype is none
begin
set dtype = dtype
end
if type obj is Flat
begin
set vec = call dup dtype=dtype
call vec S ? fill_value
set result = call Flat vec schema dims
end
else
begin
set mat = call dup dty... | def full_like(obj, fill_value, dtype=None):
# Grab the Flat or Pivot out of the CodedArray
obj = obj.obj
if dtype is None:
dtype = obj.data.dtype
if type(obj) is Flat:
vec = obj.vector.dup(dtype=dtype)
vec(vec.S) << fill_value
result = Flat(vec, obj.schema, obj.dims)
... | Python | nomic_cornstack_python_v1 |
comment Lightsensor_TEMT6000.py
import time
import board
from analogio import AnalogIn
comment initiation
set analog_in = call AnalogIn A0
comment Convert 16-bit value to voltage
function get_voltage pin
begin
return value * 3.3 / 65535
end function
while true
begin
print tuple call get_voltage analog_in
sleep 0.1
end | ## Lightsensor_TEMT6000.py
import time
import board
from analogio import AnalogIn
#initiation
analog_in = AnalogIn(board.A0)
#Convert 16-bit value to voltage
def get_voltage(pin):
return (pin.value * 3.3) / 65535
while True:
print((get_voltage(analog_in),))
time.sleep(0.1)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment ==========================================================================
comment Copyright (C) 2012-2014 RidgeRun, LLC (http://www.ridgerun.com)
comment Authors: Jose Pablo Carballo <jose.carballo@ridgerun.com>
comment This program is free software; you can redistribute it and/or ... | #!/usr/bin/env python
# ==========================================================================
#
# Copyright (C) 2012-2014 RidgeRun, LLC (http://www.ridgerun.com)
#
# Authors: Jose Pablo Carballo <jose.carballo@ridgerun.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the ter... | Python | zaydzuhri_stack_edu_python |
function dualValues self
begin
set num = call getNumCols
return list comprehension call glp_get_col_dual lp i for i in range 1 num + 1
end function | def dualValues(self):
num = self.getNumCols()
return [glp_get_col_dual(self.lp, i) for i in range(1, num + 1)] | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
import time
set driver = call Chrome executable_path=string ../Exercise/drivers/chromedriver.exe
call maximize_window
sleep 2
get driver string https://opensource-demo.orangehrmlive.com/
print title
print current_url
get driver string https://www.google.com
call back
sleep 2
call forward
... | from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path='../Exercise/drivers/chromedriver.exe')
driver.maximize_window()
time.sleep(2)
driver.get('https://opensource-demo.orangehrmlive.com/')
print(driver.title)
print(driver.current_url)
driver.get('https://www.google.com')
driver.back()
t... | Python | zaydzuhri_stack_edu_python |
comment 0
comment 1, 0
comment 2, 0, 1
comment 3, 1, 0, 2
comment 4, 2 ,0, 1, 3
set front = list
set back = list
for i in range N
begin
if i % 2 == 0
begin
append back A at i
end
else
begin
append front A at i
end
end
set ans = none
if N % 2 == 0
begin
set ans = front at slice : : - 1 + back
end
else
begin
set ans ... | # 0
# 1, 0
# 2, 0, 1
# 3, 1, 0, 2
# 4, 2 ,0, 1, 3
front = []
back = []
for i in range(N):
if i % 2 == 0:
back.append(A[i])
else:
front.append(A[i])
ans = None
if N % 2 == 0:
ans = front[::-1] + back
else:
ans = back[::-1] + front
print(*ans) | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set inches_moved = 0
set left_motor = call LargeMotor OUTPUT_B
set right_motor = call LargeMotor OUTPUT_C
set arm_motor = call MediumMotor OUTPUT_A
set touch_sensor = call TouchSensor
set running = true
set ir_sensor = call InfraredSensor
set color_sensor = call ColorSensor
assert color_sen... | def __init__(self):
self.inches_moved = 0
self.left_motor = ev3.LargeMotor(ev3.OUTPUT_B)
self.right_motor = ev3.LargeMotor(ev3.OUTPUT_C)
self.arm_motor = ev3.MediumMotor(ev3.OUTPUT_A)
self.touch_sensor = ev3.TouchSensor()
self.running = True
self.ir_sensor = ev3.I... | Python | nomic_cornstack_python_v1 |
function triplet_loss anchor positive negative margin=0.2
begin
set distance_ap = call reduce_sum call square anchor - positive 1
set distance_an = call reduce_sum call square anchor - negative 1
set loss = call maximum 0.0 distance_ap - distance_an + margin
set loss = call reduce_mean loss
return loss
end function | def triplet_loss(anchor, positive, negative, margin=0.2):
distance_ap = tf.reduce_sum(tf.square(anchor - positive), 1)
distance_an = tf.reduce_sum(tf.square(anchor - negative), 1)
loss = tf.maximum(0.0, distance_ap - distance_an + margin)
loss = tf.reduce_mean(loss)
return loss | Python | nomic_cornstack_python_v1 |
import sys
function count_vowel str
begin
set lower = lower str
set count = 0
set vowel = list string a string e string i string o string u
set length = length lower
for i in range 0 length
begin
if lower at i in vowel
begin
set count = count + 1
end
end
return count
end function
while true
begin
set text = strip read ... | import sys
def count_vowel(str):
lower = str.lower()
count = 0
vowel = ['a', 'e', 'i', 'o', 'u']
length = len(lower)
for i in range(0, length):
if(lower[i] in vowel):
count += 1
return count
while(True):
text = sys.stdin.readline().strip()
if text == '#':
... | Python | zaydzuhri_stack_edu_python |
function backward self X w y
begin
comment This function purposefully left blank
raise call ValueError string No need to use this function for the homework :p
end function | def backward(self, X, w, y):
# This function purposefully left blank
raise ValueError('No need to use this function for the homework :p') | Python | nomic_cornstack_python_v1 |
function test_useItem capsys
begin
set outerr = call readouterr
set p = string jumpBreak.txt
set msglog = call MessageLog
set tuple name hp attack speed hunger = tuple string Bob 1000 2000 3000 4000
set player = call Player name hp attack speed hunger
set health = 1
set testMaze = call Maze p player
set actions = list ... | def test_useItem(capsys):
outerr = capsys.readouterr()
p = "jumpBreak.txt"
msglog = dg.MessageLog()
name,hp,attack,speed,hunger = "Bob",1000,2000,3000,4000
player = dg.Player(name,hp,attack,speed,hunger)
player.health = 1
testMaze = dg.Maze(p,player)
actions = ["r","rest","use","food","... | Python | nomic_cornstack_python_v1 |
import sys
import math
import heapq
import copy
set f = open argv at 1
set k = integer argv at 2
set data = read lines f
set input = list
for line in data
begin
if strip line != string
begin
set line = split line string ,
set line = list comprehension strip i for i in line
set line at 0 = decimal line at 0
set line a... | import sys
import math
import heapq
import copy
f = open(sys.argv[1])
k = int(sys.argv[2])
data = f.readlines()
input = []
for line in data:
if line.strip()!= '':
line = line.split(',')
line = [i.strip() for i in line]
line[0] = float(line[0])
line[1] = float(line[1])
line[2... | Python | zaydzuhri_stack_edu_python |
function get_tonic_scale root major
begin
if major
begin
return list call MinorSeventhChord root - 10 call MinorSeventhChord root - 8 call MajorSeventhChord root - 7 call MinorSeventhChord root - 3 call MajorSeventhChord root call MinorSeventhChord root + 2 call MinorSeventhChord root + 4 call MajorSeventhChord root + ... | def get_tonic_scale(root: int, major: bool) -> List[Chord]:
if major:
return [
MinorSeventhChord(root - 10),
MinorSeventhChord(root - 8),
MajorSeventhChord(root - 7),
# MajorSeventhChord(root - 5),
MinorSeventhChord(root... | Python | nomic_cornstack_python_v1 |
function get_table_name query
begin
set find_table_name_from_query = string (FROM `)(\w+.\w+)(`)
set search_result = search find_table_name_from_query query
if search_result
begin
return call group 2
end
return string Unrecognized table name
end function | def get_table_name(query: str) -> str:
find_table_name_from_query = r'(FROM `)(\w+.\w+)(`)'
search_result = re.search(find_table_name_from_query, query)
if search_result:
return search_result.group(2)
return "Unrecognized table name" | Python | nomic_cornstack_python_v1 |
comment From the below array, retrieve the values([[3,4],[5,6]]) using indexing
import numpy as np
set lst1 = list 1 2 3 4 5
set lst2 = list 2 3 4 5 6
set lst3 = list 4 5 6 7 8
set arr1 = array list lst1 lst2 lst3
print arr1 at tuple slice 1 : : slice 1 : 3 : | #From the below array, retrieve the values([[3,4],[5,6]]) using indexing
import numpy as np
lst1 = [1,2,3,4,5]
lst2 = [2,3,4,5,6]
lst3 = [4,5,6,7,8]
arr1 = np.array([lst1, lst2, lst3])
print(arr1[1:,1:3]) | Python | zaydzuhri_stack_edu_python |
function calculate_width_widget width margin=none margin_left=none margin_right=none
begin
string Calculate actual widget width based on given margins.
if margin_left is none
begin
set margin_left = margin
end
if margin_right is none
begin
set margin_right = margin
end
if margin_left is not none
begin
set width = width... | def calculate_width_widget(width, margin = None, margin_left = None, margin_right = None):
"""
Calculate actual widget width based on given margins.
"""
if margin_left is None:
margin_left = margin
if margin_right is None:
margin_right = margin
if ... | Python | jtatman_500k |
from sys import maxsize
function maxSubArraySum a size
begin
set l = list
set max_so_far = - decimal string inf
set max_ending_here = 0
set start = 0
set end = 0
set s = 0
for i in range 0 size
begin
set max_ending_here = max_ending_here + a at i
if max_so_far < max_ending_here
begin
set max_so_far = max_ending_here
s... | from sys import maxsize
def maxSubArraySum(a,size):
l=[]
max_so_far = -float('inf')
max_ending_here = 0
start = 0
end = 0
s = 0
for i in range(0,size):
max_ending_here += a[i]
if max_so_far < max_ending_here:
max_so_far = max_ending_here
... | Python | zaydzuhri_stack_edu_python |
function plus x y
begin
print x + y
end function
function minus x y
begin
print x - y
end function
function multiply x y
begin
print x * y
end function
function divide x y
begin
print x / y
end function
set inputFirstNumber = integer input string First number :
set inputSecondNumber = integer input string Second number... | def plus(x,y):
print(x+y)
def minus(x,y):
print(x-y)
def multiply(x,y):
print(x*y)
def divide(x,y):
print(x/y)
inputFirstNumber = int(input("First number : "))
inputSecondNumber = int(input("Second number : "))
x = inputFirstNumber
y = inputSecondNumber
print("Plus")
plus(x,y)
print("Minus")
minus(x,y... | Python | zaydzuhri_stack_edu_python |
function is_unique str
begin
string Checks whether a string has all unique charecters >>> is_unique("abc123") True >>> is_unique("abcc123") False
comment char_count = {}
comment for char in str:
comment count = char_count.get(char, 0)
comment if count == 1:
comment return False
comment else:
comment char_count[char] = ... | def is_unique(str):
"""Checks whether a string has all unique charecters
>>> is_unique("abc123")
True
>>> is_unique("abcc123")
False
"""
# char_count = {}
# for char in str:
# count = char_count.get(char, 0)
# if count == 1:
# return False
# else:... | Python | zaydzuhri_stack_edu_python |
function get_true_propositions self
begin
set ret = string
if agent in objects
begin
set ret = ret + objects at agent
end
return ret
end function | def get_true_propositions(self):
ret = ""
if self.agent in self.objects:
ret += self.objects[self.agent]
return ret | Python | nomic_cornstack_python_v1 |
string Edit Distance Problem: Find the edit distance between two strings. >>Input: Two strings. >>Output: The edit distance between these strings. ----------------- Sample Input: PLEASANTLY MEANLY ----------------- Sample Output: 5
from os.path import dirname
import numpy
function InitGraph l1 l2
begin
set Graph = zero... | '''
Edit Distance Problem: Find the edit distance between two strings.
>>Input: Two strings.
>>Output: The edit distance between these strings.
-----------------
Sample Input:
PLEASANTLY
MEANLY
-----------------
Sample Output:
5
'''
from os.path import dirname
import numpy
def InitGraph(l1,l2):
Graph = numpy.... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment ansible can understand easily
import json
import time
try
begin
comment used to connect aws
import boto3
import boto.ec2
end
except Exception as e
begin
print string please check boto module is installed or not if not then use 'pip3 install boto3'
print e
end
comment we are getting IPs... | #!/usr/bin/python3
import json #ansible can understand easily
import time
try:
import boto3 #used to connect aws
import boto.ec2
except Exception as e:
print("please check boto module is installed or not\n if not then use 'pip3 install boto3' ")
print(e)
# we are getting IPs and appending in list
def ... | Python | zaydzuhri_stack_edu_python |
function forward self smiles
begin
set embedded_smiles = call smiles_embedding to smiles dtype=int64
comment SMILES Convolutions. Unsqueeze has shape batch_size x 1 x T x H.
set encoded_smiles = list embedded_smiles + list comprehension permute call unsqueeze th embedded_smiles 1 0 2 1 for ind in range length convoluti... | def forward(self, smiles: th.Tensor) -> Tuple[th.Tensor, dict]:
embedded_smiles = self.smiles_embedding(smiles.to(dtype=th.int64))
# SMILES Convolutions. Unsqueeze has shape batch_size x 1 x T x H.
encoded_smiles = [embedded_smiles] + [
self.convolutional_layers[ind](th.unsqueeze(emb... | Python | nomic_cornstack_python_v1 |
comment Way1 O(N**2)
class Solution extends object
begin
function lengthOfLIS self nums
begin
string :type nums: List[int] :rtype: int
if nums == list
begin
return 0
end
else
begin
set res = list 1
for i in range 1 length nums
begin
set ans = 1
for j in range i
begin
if nums at i > nums at j
begin
set ans = max ans re... | # Way1 O(N**2)
class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if nums == []:
return 0
else:
res = [1]
for i in range(1, len(nums)):
ans = 1
for j in ran... | Python | zaydzuhri_stack_edu_python |
import requests
from base_metadata import BaseMetadata
from instagram.client import InstagramAPI
import os
import pdb
import numpy as np
from pymongo import MongoClient , errors
import time
from itertools import cycle
class InstagramMetadata extends BaseMetadata
begin
string Interacts with InstagramAPI to get metadata ... | import requests
from base_metadata import BaseMetadata
from instagram.client import InstagramAPI
import os
import pdb
import numpy as np
from pymongo import MongoClient, errors
import time
from itertools import cycle
class InstagramMetadata(BaseMetadata):
"""Interacts with InstagramAPI to get metadata
Loads ... | Python | zaydzuhri_stack_edu_python |
from pythonping import ping
import os
import time
import smtplib
from email.message import EmailMessage
import threading
from queue import Queue
set address_list = list string 10.0.0.10 string 192.168.43.1 string 10.0.0.11
set q = queue
comment pobieranie z kolejki
set ip = string
function send
begin
comment os.enviro... | from pythonping import ping
import os
import time
import smtplib
from email.message import EmailMessage
import threading
from queue import Queue
address_list = ['10.0.0.10','192.168.43.1','10.0.0.11']
q = Queue()
#pobieranie z kolejki
ip = ''
def send():
EMAIL_ADDRESS = 'hiltkom@gmail.com'#os.environ.... | Python | zaydzuhri_stack_edu_python |
function findRequirements platform
begin
set includePycapnp = platform not in WINDOWS_PLATFORMS
set requirementsPath = call fixPath join path PY_BINDINGS string requirements.txt
return list comprehension strip line for line in read lines open requirementsPath if not starts with line string # and not starts with line st... | def findRequirements(platform):
includePycapnp = platform not in WINDOWS_PLATFORMS
requirementsPath = fixPath(os.path.join(PY_BINDINGS, "requirements.txt"))
return [
line.strip()
for line in open(requirementsPath).readlines()
if not line.startswith("#") and (not line.startswith("pycapnp") or includePy... | Python | nomic_cornstack_python_v1 |
function centroid x1 y1 x2 y2 x3 y3
begin
try
begin
if y2 - y1 / x2 - x1 == y3 - y1 / x3 - x1
begin
return false
end
end
except any
begin
pass
end
return tuple round x1 + x2 + x3 / 3 2 round y1 + y2 + y3 / 3 2
end function | def centroid(x1, y1, x2, y2, x3, y3):
try:
if ((y2-y1)/(x2-x1)) == ((y3-y1)/(x3-x1)): return False
except: pass
return round((x1+x2+x3)/3, 2), round((y1+y2+y3)/3, 2)
| Python | zaydzuhri_stack_edu_python |
function upgrade_to_float *types
begin
set conv : Mapping at tuple Type Type = dict bool float32 ; int8 float32 ; int16 float32 ; int32 float64 ; int64 float64 ; uint8 float32 ; uint16 float32 ; uint32 float64 ; uint64 float64
return tuple call get_scalar_type call upcast *[conv.get(type, type) for type in types]
end f... | def upgrade_to_float(*types):
conv: Mapping[Type, Type] = {
bool: float32,
int8: float32,
int16: float32,
int32: float64,
int64: float64,
uint8: float32,
uint16: float32,
uint32: float64,
uint64: float64,
}
return (
get_scalar_t... | Python | nomic_cornstack_python_v1 |
function plot_scores scores names=none kind=string beside save_as=none
begin
set tuple pipes dim = shape
set X = array range dim
set step = 0.8 / pipes
set xlabels = if expression dim * pipes < 100 then list comprehension string i + 1 for i in range dim else string * dim
set titles = if expression not names is none th... | def plot_scores(scores, names = None, kind = 'beside', save_as = None):
pipes, dim = scores.shape
X = np.arange(dim)
step = 0.8/pipes
xlabels = [str(i+1) for i in range(dim)] if dim * pipes < 100 else ''*dim
titles = names if not (names is None) else ''*pipes
if kind == 'beside':
... | Python | nomic_cornstack_python_v1 |
for op1 in ops
begin
for op2 in ops
begin
for op3 in ops
begin
set left = a
set left = left + if expression op1 == string + then b else - b
set left = left + if expression op2 == string + then c else - c
set left = left + if expression op3 == string + then d else - d
if left == 7
begin
set done = true
break
end
end
if ... | for op1 in ops:
for op2 in ops:
for op3 in ops:
left = a
left += b if op1 == '+' else -b
left += c if op2 == '+' else -c
left += d if op3 == '+' else -d
if left == 7:
done = True
break
if done:
br... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.neighbors import KNeighborsClassifier
set df = read csv string songs.csv
set X = df at list string artist string title string lyrics
set y = values
comment Vectorize Text
set vectorizer = call CountVectorizer... | import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.neighbors import KNeighborsClassifier
df = pd.read_csv('songs.csv')
X = df[['artist', 'title', 'lyrics']]
y = df['genre'].values
# Vectorize Text
vectorizer = CountVectorizer()
X_lyrics = vectorizer.fit_tr... | Python | iamtarun_python_18k_alpaca |
function main
begin
set n = integer input
set r_n_1 = integer n ^ 0.5 + 1
set divider = list
set divided = list
for i in range 1 r_n_1 + 1
begin
if n % i == 0
begin
append divider i
end
end
for i in divider
begin
append divided n // i
end
comment print(divider)
comment print(divided)
set output = set divider + divide... | def main():
n = int(input())
r_n_1 = int(n ** 0.5) + 1
divider = []
divided = []
for i in range(1, r_n_1 + 1):
if n % i == 0:
divider.append(i)
for i in divider:
divided.append(n // i)
# print(divider)
# print(divided)
output = set(divider + d... | Python | zaydzuhri_stack_edu_python |
function notification self
begin
return _notification
end function | def notification(self):
return self._notification | Python | nomic_cornstack_python_v1 |
function get_auth
begin
set scope = list string https://spreadsheets.google.com/feeds string https://www.googleapis.com/auth/drive
set credentials = call from_json_keyfile_name string client_secret.json scope
set client = call authorize credentials
return client
end function | def get_auth():
scope = ['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name(
'client_secret.json', scope)
client = gspread.authorize(credentials)
return client | Python | nomic_cornstack_python_v1 |
import csv
import numpy as np
import collider
from collider import PointCollider , CircleCollider , RectangleCollider
class WorkSpace
begin
function __init__ self limits
begin
set obstacles = dict
set limits = limits
end function
function setObsticle self id collider
begin
set obstacles at id = collider
end function
f... | import csv
import numpy as np
import collider
from collider import PointCollider, CircleCollider, RectangleCollider
class WorkSpace:
def __init__(self, limits):
self.obstacles = {}
self.limits = limits
def setObsticle(self, id, collider):
self.obstacles[id] = collider
def removeObsticle(self, id):
if i... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import simpy
from Fleet_sim.location import find_zone
from Fleet_sim.read import charging_threshold
from Fleet_sim.trip import Trip
comment This function give us the available vehicles for a trip
function available_vehicle vehicles trip SOC_threshold=20 max_distance=10
begin
set available_vehicles =... | import pandas as pd
import simpy
from Fleet_sim.location import find_zone
from Fleet_sim.read import charging_threshold
from Fleet_sim.trip import Trip
# This function give us the available vehicles for a trip
def available_vehicle(vehicles, trip, SOC_threshold=20, max_distance=10):
available_vehicles = list()
... | Python | zaydzuhri_stack_edu_python |
function content self
begin
return get pulumi self string content
end function | def content(self) -> pulumi.Input[str]:
return pulumi.get(self, "content") | Python | nomic_cornstack_python_v1 |
comment https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/
import math
function solution X Y D
begin
return ceil Y - X / D
end function | # https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/
import math
def solution(X, Y, D):
return math.ceil((Y-X)/D) | Python | zaydzuhri_stack_edu_python |
function from_dict cls d
begin
string Restores its state from a dictionary, used in de-JSONification. :param d: the object dictionary :type d: dict
set conf = dict
for k in d at string config
begin
set v = d at string config at k
if is instance v dict
begin
set conf at string k = call call get_dict_handler d at string... | def from_dict(cls, d):
"""
Restores its state from a dictionary, used in de-JSONification.
:param d: the object dictionary
:type d: dict
"""
conf = {}
for k in d["config"]:
v = d["config"][k]
if isinstance(v, dict):
conf[st... | Python | jtatman_500k |
comment path_map = {"a": {"b": 4, "c": 2},
comment "b": {"a": 4, "d": 5},
comment "c": {"a": 2, "e": 10},
comment "d": {"b": 5, "z": 6},
comment "e": {"c": 10, "z": 5},
comment "z": {"e": 5, "d": 6},
comment }
comment should look into: if the path wants to go somewhere its already gone before that should be skipped or ... | # path_map = {"a": {"b": 4, "c": 2},
# "b": {"a": 4, "d": 5},
# "c": {"a": 2, "e": 10},
# "d": {"b": 5, "z": 6},
# "e": {"c": 10, "z": 5},
# "z": {"e": 5, "d": 6},
# }
# should look into: if the path wants to go somewhere its already gone before t... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
string An quite easy stream editor based on python.
import argparse
import os
import pyse
function init_arg
begin
set parser = call ArgumentParser
call add_argument string script type=str nargs=string *
call add_argument string -f type=str dest=string file default=none
call add_argument string ... | #!/usr/bin/python
"""
An quite easy stream editor based on python.
"""
import argparse
import os
import pyse
def init_arg():
parser = argparse.ArgumentParser()
parser.add_argument('script', type=str, nargs='*')
parser.add_argument('-f', type=str, dest='file', default=None)
parser.add_argument('-F... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment James Fitzwater
comment CS 325.400
comment Project 3 - The Travelling Salesman Problem
comment Solution Type: "Hill Climbing"
comment Primary Resource:
comment Marsland, Stephen. Machine Learning: An Algorithmic
comment Perspective, 2nd ed. Boca Raton, FL: CRC Press, 2015.
comment seat.... | #!/usr/bin/python
## James Fitzwater
## CS 325.400
## Project 3 - The Travelling Salesman Problem
## Solution Type: "Hill Climbing"
# Primary Resource:
#
#
# Marsland, Stephen. Machine Learning: An Algorithmic
# Perspective, 2nd ed. Boca Raton, FL: CRC Press, 2015.
# seat.massey.ac.nz/personal/s.r.marsland/MLbook... | Python | zaydzuhri_stack_edu_python |
function patience self
begin
return _patience
end function | def patience(self):
return self._patience | Python | nomic_cornstack_python_v1 |
import hzaq_tools
while true
begin
call show_menu
set action_str = input string 请输入操作对应序号:
if action_str in list string 1 string 2
begin
if action_str == string 1
begin
set username = input string 请输入账号:
set password = input string 请输入密码:
comment 请求用户输入账号密码并输出登陆结果
print call user_login username password
end
else
if act... | import hzaq_tools
while True:
hzaq_tools.show_menu()
action_str = input("请输入操作对应序号:")
if action_str in ["1", "2"]:
if action_str == "1":
username = input("请输入账号:")
password = input("请输入密码:")
# 请求用户输入账号密码并输出登陆结果
print(hzaq_tools.user_login(username, pa... | Python | zaydzuhri_stack_edu_python |
function finish self
begin
call status string %s is ending % _name
comment forward the termination signal to downstream nodes
call end
end function | def finish(self):
logger.status("%s is ending" % self._name)
# forward the termination signal to downstream nodes
self.end() | Python | nomic_cornstack_python_v1 |
function get_target_regions_df target_transcripts region_parent region expand_3prime expand_5prime
begin
set target_transcript_info = list
for transcript in target_transcripts
begin
set transcript_info = call get_ensembl_id_information transcript
set region_info = call get_trainscript_region_info transcript_info regio... | def get_target_regions_df(target_transcripts, region_parent, region,
expand_3prime, expand_5prime):
target_transcript_info = []
for transcript in target_transcripts:
transcript_info = ensembl.get_ensembl_id_information(transcript)
region_info = get_trainscript_region_in... | Python | nomic_cornstack_python_v1 |
from object import MentionDB , AuthorInfoDB
from engine import Engine as ConverterEngine
from database import Database
from data import Data
from curtsies import fmtstr
import pymongo
class ConverterInterface
begin
function __init__ self
begin
pass
end function
decorator classmethod
function multiple_convert_and_save s... | from .object import MentionDB, AuthorInfoDB
from .engine import Engine as ConverterEngine
from ..database import Database
from ..data import Data
from curtsies import fmtstr
import pymongo
class ConverterInterface:
def __init__(self):
pass
@classmethod
def multiple_convert_and_save(self, data=None):
... | Python | zaydzuhri_stack_edu_python |
comment !#!/usr/bin/env python
comment -*- coding: utf-8 -*-
string Modelo de la tabla vendedores con sus métodos de acceso a datos. Esos métodos son los que deben usarse para acceder a la BD. Forma parte del paquete modelos.
from sistema import conectarBD
class Vendedor extends object
begin
string La clase que define ... | #!#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Modelo de la tabla vendedores con sus métodos de acceso a datos.
Esos métodos son los que deben usarse para acceder a la BD.
Forma parte del paquete modelos.
"""
from sistema import conectarBD
class Vendedor(object):
"""
La clase que define el registro de la... | Python | zaydzuhri_stack_edu_python |
function add_forecast self
begin
comment Fetch forecast using One Call API from OpenWeatherMap
set tuple hourly_forecasts daily_forecasts timezone_offset = call fetch_forecast location=location
set day_temps = list
set day_feels = list
comment Hour level
for hour_forecast in hourly_forecasts
begin
set is_this_day = d... | def add_forecast(self):
# Fetch forecast using One Call API from OpenWeatherMap
hourly_forecasts, daily_forecasts, timezone_offset = forecast.fetch_forecast(location=self.location)
day_temps = []
day_feels = []
# Hour level
for hour_forecast in hourly_forecasts:
... | Python | nomic_cornstack_python_v1 |
function _check_grain_pcre_minions self expr delimiter greedy
begin
string Return the minions found by looking via grains with PCRE
return call _check_cache_minions expr delimiter greedy string grains regex_match=true
end function | def _check_grain_pcre_minions(self, expr, delimiter, greedy):
'''
Return the minions found by looking via grains with PCRE
'''
return self._check_cache_minions(expr,
delimiter,
greedy,
... | Python | jtatman_500k |
comment Author: zzk
comment 集合set类似数学集合
set list1 = set list 1 2 3 4 5 6 7 3 5 2 1
set list2 = set list 6 7 8 9 0 2 7 3 6 4 7
set list3 = intersection list1 list2
comment 集合无重复元素
comment list1 = set(list1)
comment print(list1)
comment 关系判断
comment 交集
print intersection list1 list2 list 2 3 4
print list1 ? list2 ? set l... | # Author: zzk
# 集合set类似数学集合
list1 = set([1, 2, 3, 4, 5, 6, 7, 3, 5, 2, 1])
list2 = set([6, 7, 8, 9, 0, 2, 7, 3, 6, 4, 7])
list3 = list1.intersection(list2)
# 集合无重复元素
#list1 = set(list1)
# print(list1)
# 关系判断
# 交集
print(list1.intersection(list2, [2, 3, 4]))
print(list1 & list2 & {6})
# 并集
print(list1.union(list2))
p... | Python | zaydzuhri_stack_edu_python |
import Canvas
set x = 0
set y = 0
set new_commands = dict
function position new_x new_y
begin
global x y
set x = integer new_x
set y = integer new_y
end function
function line new_x new_y
begin
global x y
set new_x = integer new_x
set new_y = integer new_y
call create_line x y x + new_x y + new_y
set x = x + new_x
set... | import Canvas
x = 0
y = 0
new_commands = {}
def position(new_x,new_y):
global x,y
x = int(new_x)
y = int(new_y)
def line(new_x,new_y):
global x,y
new_x = int(new_x)
new_y = int(new_y)
Canvas.create_line(x,y,(x+new_x),(y+new_y))
x += new_x
y += new_y
def circle(radius):
globa... | Python | zaydzuhri_stack_edu_python |
comment 10-6 addition_calculator.py
print string (Press 'q' to quit)
while true
begin
try
begin
set num1 = input string Enter first number:
if num1 == string q
begin
break
end
set num1 = integer num1
set num2 = input string Enter second number:
if num1 == string q
begin
break
end
set num2 = integer num2
print
end
excep... | #10-6 addition_calculator.py
print("(Press 'q' to quit)")
while True:
try:
num1 = input("\nEnter first number: ")
if num1 == 'q':
break
num1 = int(num1)
num2 = input("Enter second number: " )
if num1 == 'q':
break
num2 = int(num2)
print()
except ValueError:
print("You must enter a number no... | Python | zaydzuhri_stack_edu_python |
string Given a string, return the number of times "am" appears in the string BUT ONLY WHEN "am" is not followed or preceded by any other LETTERS
function name input
begin
set number = 0
for word in split input string
begin
if lower word == string am
begin
set number = number + 1
end
end
return number
end function | '''Given a string, return the number of times "am"
appears in the string BUT ONLY WHEN "am"
is not followed or preceded by any other LETTERS'''
def name(input):
number = 0
for word in input.split(" "):
if word.lower() == "am":
number = number + 1
return number | Python | zaydzuhri_stack_edu_python |
import re
function get_company_address_info document
begin
set pl_diacritics = string ąćęłńóśźż
comment Substrings of regex
set postal_code_regex_str = string [0-9]{2}-[0-9]{3}
set city_name_regex_str = string [A-z%s][a-z%s]+ % tuple upper pl_diacritics pl_diacritics
set street_name_regex_str = string ([A-Z%s][a-z%s]+ ... | import re
def get_company_address_info(document):
pl_diacritics = "ąćęłńóśźż"
# Substrings of regex
postal_code_regex_str = "[0-9]{2}-[0-9]{3}"
city_name_regex_str = "[A-z%s][a-z%s]+" % (pl_diacritics.upper(), pl_diacritics)
street_name_regex_str = "([A-Z%s][a-z%s]+ )+" % (pl_diacritics.uppe... | Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
return string {segs= + join string generator expression string seg for seg in segments + string + string final= + string call end_state + string }
end function | def __str__(self):
return "{segs=\n" + "\n".join(str(seg)for seg in self.segments) + "\n" +\
"final=" + str(self.end_state()) + "}" | Python | nomic_cornstack_python_v1 |
function test_user_landing_view_GET self
begin
set response = get client user_landing_url
assert equal status_code 200
call assertTemplateUsed response string anonticket/user_landing.html
end function | def test_user_landing_view_GET(self):
response = self.client.get(self.user_landing_url)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'anonticket/user_landing.html') | Python | nomic_cornstack_python_v1 |
import random
set numlist = list
set list_length = random integer 5 20
while length numlist < list_length
begin
append numlist random integer 1 80
end
set list_even = list comprehension num for num in numlist if num % 2 == 0
print numlist
print list_even | import random
numlist = []
list_length = random.randint(5,20)
while len(numlist) < list_length:
numlist.append(random.randint(1,80))
list_even = [num for num in numlist if num % 2 == 0]
print(numlist)
print(list_even) | Python | zaydzuhri_stack_edu_python |
function filled self fill_value
begin
set sdata = data
set new_data = call filled sdata fill_value=fill_value
if new_data == sdata
begin
return self
end
else
begin
return call type self new_data bset
end
end function | def filled(self, fill_value):
sdata = self.data
new_data = numpy.ma.filled(sdata, fill_value=fill_value)
if new_data == sdata:
return self
else:
return type(self)(new_data, self.bset) | Python | nomic_cornstack_python_v1 |
function getMedian list_values
begin
comment sort the list
sort list_values
comment get the length of the list
set list_len = length list_values
comment check if list is even or odd
if list_len % 2 == 0
begin
comment if even, get the two middle elements
comment and calculate the average
set idx = integer list_len / 2 -... | def getMedian(list_values):
# sort the list
list_values.sort()
# get the length of the list
list_len = len(list_values)
# check if list is even or odd
if list_len % 2 == 0:
# if even, get the two middle elements
# and calculate the average
idx = int((list_le... | Python | flytech_python_25k |
function compute_gradient self grad=none
begin
set tuple x y = list comprehension output_value for node in input_nodes
if grad is none
begin
set grad = ones like output_value
end
set grad_wrt_x = grad * y
while call ndim grad_wrt_x > length call shape x
begin
set grad_wrt_x = sum grad_wrt_x axis=0
end
for tuple axis si... | def compute_gradient(self, grad=None):
x, y = [node.output_value for node in self.input_nodes]
if grad is None:
grad = backend.ones_like(self.output_value)
grad_wrt_x = grad * y
while backend.ndim(grad_wrt_x) > len(backend.shape(x)):
grad_wrt_x = backend.sum(grad... | Python | nomic_cornstack_python_v1 |
comment Question 1
comment Define a function named is_two. It should accept one input and
comment return True if the passed input is either the number or the
comment string 2, False otherwise.
function is_two x
begin
return x == 2 or x == string 2
end function
comment Question 2
comment Define a function named is_vowel... | # Question 1
# Define a function named is_two. It should accept one input and
# return True if the passed input is either the number or the
# string 2, False otherwise.
def is_two (x):
return x == 2 or x == ('2')
# Question 2
# Define a function named is_vowel. It should return True if the passed string is a vow... | Python | zaydzuhri_stack_edu_python |
from itertools import permutations
print list permutations list 1 2 3 | from itertools import permutations
print(list(permutations([1,2,3]))) | Python | zaydzuhri_stack_edu_python |
function all_players self
begin
set name = list
set indx = list
for i in range length first
begin
set p = call mapped_player first at i
try
begin
set t = index sn fullname
append name fullname
append indx t
end
except any
begin
set t = - 1
end
end
return tuple name indx
end function | def all_players(self):
name = []
indx = []
for i in range(len(self.first)):
p = self.mapped_player(self.first[i])
try:
t = self.sn.index(p.fullname)
name.append(p.fullname)
indx.append(t)
except:
... | Python | nomic_cornstack_python_v1 |
string program to encrypt a message using a recursive function nasreen hoosain 06/05/14
comment recursive function to encrypt a string
function encrypt string
begin
if string == string
begin
return string
end
else
comment if there is a space, keep it
if string at 0 == string
begin
return string + call encrypt string... | '''program to encrypt a message using a recursive function
nasreen hoosain
06/05/14'''
#recursive function to encrypt a string
def encrypt (string):
if string == '':
return string
elif string[0] == ' ': #if there is a space, keep it
return ' ' + encrypt(string[1:])
elif (ord(strin... | Python | zaydzuhri_stack_edu_python |
string Тестирование лексического анализатора
import sys
append path string ..
import tokens
if __name__ == string __main__
begin
set data = string stream
set index = 0
function next_char
begin
global index
set index = index + 1
if index > length data
begin
return - 1
end
else
begin
return data at index - 1
end
end func... | '''
Тестирование лексического анализатора
'''
import sys
sys.path.append('..')
import tokens
if __name__ == '__main__':
data = 'stream '
index = 0
def next_char():
global index
index += 1
if index > len(data):
return -1
else:
return data[index - 1]
... | Python | zaydzuhri_stack_edu_python |
function compute_accuracy output target
begin
set num_samples = size target 0
set sigmoid_output = sigmoid output
set correct_pred = call eq call long
set accuracy = sum correct_pred dim=0
return call numpy * 100.0 / num_samples
end function | def compute_accuracy(output, target):
num_samples = target.size(0)
sigmoid_output = torch.sigmoid(output)
correct_pred = target.eq(sigmoid_output.round().long())
accuracy = torch.sum(correct_pred, dim=0)
return accuracy.cpu().numpy() * (100. / num_samples) | Python | nomic_cornstack_python_v1 |
import re
import math
function load_file file
begin
set lines = list
comment just load all the lines
with open file string r as reader
begin
set lines = list comprehension strip line for line in reader
end
return lines
end function
function day_twelve_part_one file
begin
set lines = call load_file file
comment facing ... | import re
import math
def load_file(file: str):
lines = []
# just load all the lines
with open(file, 'r') as reader:
lines = [line.strip() for line in reader]
return lines
def day_twelve_part_one(file: str):
lines = load_file(file)
heading = 0 # facing east initially
dx = 0
... | Python | zaydzuhri_stack_edu_python |
comment You are implementing a binary search tree class from scratch, which, in addition
comment to insert, find, and delete, has a method getRandomNode() which returns a random node
comment from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm
comment for getRandomNode, and ... | # You are implementing a binary search tree class from scratch, which, in addition
# to insert, find, and delete, has a method getRandomNode() which returns a random node
# from the tree. All nodes should be equally likely to be chosen. Design and implement an algorithm
# for getRandomNode, and explain how you would im... | Python | zaydzuhri_stack_edu_python |
string Script to perform self-absorption correction for the water doped with Zn and Ni. Alan Kastengren, XSD, Argonne Started: April 28, 2014
import h5py
import numpy as np
import os
import ALK_Utilities as ALK
function fcorrect_signal_trapping_fitted hdf_file dataset_names line_energies x_name=string 7bmb1:m26.VAL out... | '''Script to perform self-absorption correction for the water doped with Zn and Ni.
Alan Kastengren, XSD, Argonne
Started: April 28, 2014
'''
import h5py
import numpy as np
import os
import ALK_Utilities as ALK
def fcorrect_signal_trapping_fitted(hdf_file,dataset_names,line_energies,x_name='7bmb1:m26.VAL',
... | Python | zaydzuhri_stack_edu_python |
import os
set default environ string DJANGO_SETTINGS_MODULE string CodePrepProject.settings
import django
setup django
from CodePrep.models import Provider , Course , Subject , LearningStyle , Review
from django.contrib.auth.models import User
from django.db.models import Avg
function populate
begin
set courses = dict ... | import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'CodePrepProject.settings')
import django
django.setup()
from CodePrep.models import Provider, Course, Subject, LearningStyle, Review
from django.contrib.auth.models import User
from django.db.models import Avg
def populate():
cours... | Python | zaydzuhri_stack_edu_python |
function add_input_distortions flip_left_right random_crop random_scale random_brightness module_spec
begin
string Creates the operations to apply the specified distortions. During training it can help to improve the results if we run the images through simple distortions like crops, scales, and flips. These reflect th... | def add_input_distortions(flip_left_right, random_crop, random_scale,
random_brightness, module_spec):
"""Creates the operations to apply the specified distortions.
During training it can help to improve the results if we run the images
through simple distortions like crops, scales, and... | Python | jtatman_500k |
comment !/usr/bin/env python
comment _*_ coding:utf-8 _*_
comment File_type:
comment Filename:
comment Author:
import binascii
print string 编码转换HEX
set aa = input string 请输入字符串:
set aa = call b2a_hex encode aa string utf-8
print string 0x%s % decode aa | #!/usr/bin/env python
# _*_ coding:utf-8 _*_
# File_type:
# Filename:
# Author:
import binascii
print("编码转换HEX")
aa = input("请输入字符串:")
aa = binascii.b2a_hex(aa.encode("utf-8"))
print('0x%s' % aa.decode())
| Python | zaydzuhri_stack_edu_python |
string CSC111 Final Project: AI Player for Reversi Instructions: This Python module contains the game board and rules of Reversi Copyright and Usage Information: This file is Copyright (c) 2021 Yupeng Chang, Huiru Tan, Xi Chen.
import copy
set BLACK_PIECE = 2
set WHITE_PIECE = 1
set EMPTY_PIECE = 0
class Reversi
begin
... | """CSC111 Final Project: AI Player for Reversi
Instructions:
This Python module contains the game board and rules of Reversi
Copyright and Usage Information:
This file is Copyright (c) 2021 Yupeng Chang, Huiru Tan, Xi Chen.
"""
import copy
BLACK_PIECE = 2
WHITE_PIECE = 1
EMPTY_PIECE = 0
class Reversi:
"""The c... | Python | zaydzuhri_stack_edu_python |
function wait self timeout=none
begin
string Return the result, or throw the exception if result is a failure. It may take an unknown amount of time to return the result, so a timeout option is provided. If the given number of seconds pass with no result, a TimeoutError will be thrown. If a previous call timed out, add... | def wait(self, timeout=None):
"""
Return the result, or throw the exception if result is a failure.
It may take an unknown amount of time to return the result, so a
timeout option is provided. If the given number of seconds pass with
no result, a TimeoutError will be thrown.
... | Python | jtatman_500k |
comment Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
comment Input: [-2,1,-3,4,-1,2,1,-5,4],
comment Output: 6
comment Explanation: [4,-1,2,1] has the largest sum = 6.
class Solution
begin
function maxSubArray self nums
begin
se... | # Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
# Input: [-2,1,-3,4,-1,2,1,-5,4],
# Output: 6
# Explanation: [4,-1,2,1] has the largest sum = 6.
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxsum ... | Python | zaydzuhri_stack_edu_python |
function compile_kernel context queue source_code function_name compiler_flags=none
begin
if nbytes >= 8
begin
set type_definitions = string #define cdouble double
end
else
begin
print string WARNING: no 64bit float support available for this device.
set type_definitions = string #define cdouble float
end
comment The d... | def compile_kernel(context, queue, source_code, function_name,
compiler_flags=None):
if cdouble(queue)(42).nbytes >= 8:
type_definitions = """
#define cdouble double
"""
else:
print('WARNING: no 64bit float support available for this device.')
type_defi... | Python | nomic_cornstack_python_v1 |
function check_requirements
begin
comment Fail hard if Python does not have minimum required version
if version_info < tuple 3 5
begin
raise call EnvironmentError string PyInstaller requires at Python 3.5 or newer.
end
end function | def check_requirements():
# Fail hard if Python does not have minimum required version
if sys.version_info < (3, 5):
raise EnvironmentError('PyInstaller requires at Python 3.5 or newer.') | Python | nomic_cornstack_python_v1 |
string abecedarian.py Author: Patrick Rummage [patrickbrumage@gmail.com] Objective: A word is abecedarian if all its letters are in alphabetical order. Create a program that reads through a word list and prints out all abecedarian words, as well as the total found.
import sys
set word_file = open argv at 1
function is_... | '''
abecedarian.py
Author: Patrick Rummage
[patrickbrumage@gmail.com]
Objective:
A word is abecedarian if all its letters are in alphabetical
order. Create a program that reads through a word list and prints
out all abecedarian words, as well as the total found.
'''
import sys
word_file = open(sy... | Python | zaydzuhri_stack_edu_python |
function and_ self
begin
raise call NotImplementedError string This should have been implemented.
end function | def and_(self):
raise NotImplementedError("This should have been implemented.") | Python | nomic_cornstack_python_v1 |
import json
import random
from decimal import Decimal
import pylab as pl
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
function load_viewer_data
begin
set f = open string viewers.json
set user_list = list
for line in f
begin
set viewers = loads line
end
close f
set p_list =... | import json
import random
from decimal import Decimal
import pylab as pl
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
def load_viewer_data():
f = open("viewers.json")
user_list = []
for line in f:
viewers = json.loads(line)
f.close()
p_list = ... | Python | zaydzuhri_stack_edu_python |
function get_num_gpus testall=false
begin
comment Default zero or None
set gpu_count = none
for method in METHODS
begin
set gpu_count = call
if is instance gpu_count int and not testall
begin
return gpu_count
end
end
return none
end function | def get_num_gpus(testall=False):
# Default zero or None
gpu_count = None
for method in METHODS:
gpu_count = METHODS[method]()
if isinstance(gpu_count, int) and not testall:
return gpu_count
return None | Python | nomic_cornstack_python_v1 |
function test_get_component_revision_list_src_map_text self mock_get_url_content mock_get_config
begin
set return_value = call MockConfigOSSFuzz
set return_value = string oss-fuzz
set side_effect = mock_get_url_content
set result = call get_component_range_list 1337 9001 SRCMAP_JOB_TYPE
set result_as_html = call format... | def test_get_component_revision_list_src_map_text(self, mock_get_url_content,
mock_get_config):
mock_get_config.return_value = self.MockConfigOSSFuzz()
self.mock.default_project_name.return_value = 'oss-fuzz'
mock_get_url_content.side_effect = self.mock_ge... | Python | nomic_cornstack_python_v1 |
function input_fn data_file feature_dim label_dim is_training is_predicting is_shuffle is_padding buffer_size pad_shape batch_size label_shape=call TensorShape list epoch=1 feature_type=float32 label_type=float32 label_onehot=false
begin
set features = none
set labels = none
comment TODO: create features and labels fro... | def input_fn(
data_file,
feature_dim,
label_dim,
is_training,
is_predicting,
is_shuffle,
is_padding,
buffer_size,
pad_shape,
batch_size,
label_shape=tf.TensorShape([]),
epoch=1,
feature_type=tf.float32,
label_type=tf.float32,
label_onehot=False
):
... | Python | nomic_cornstack_python_v1 |
function plot_confusion_matrix subject y y_pred class_names=none normalize=false cmap=Blues target_dir=none
begin
comment prepare filename
set filename = call _get_filename subject string confusion target_dir
comment prepare class names
if class_names is none
begin
set class_names = list string Left hand string Right h... | def plot_confusion_matrix(subject, y, y_pred, class_names=None, normalize=False, cmap=plt.cm.Blues,
target_dir=None):
# prepare filename
filename = _get_filename(subject, "confusion", target_dir)
# prepare class names
if class_names is None:
class_names = ["Left hand",... | Python | nomic_cornstack_python_v1 |
function pg_dsn settings
begin
string :param settings: settings including connection settings :return: DSN url suitable for sqlalchemy and aiopg.
return string call URL database=DB_NAME password=DB_PASSWORD host=DB_HOST port=DB_PORT username=DB_USER drivername=string postgres
end function | def pg_dsn(settings: Settings) -> str:
"""
:param settings: settings including connection settings
:return: DSN url suitable for sqlalchemy and aiopg.
"""
return str(URL(
database=settings.DB_NAME,
password=settings.DB_PASSWORD,
host=settings.DB_HOST,
port=settings.DB... | Python | jtatman_500k |
function repeat_strings s1 s2 n
begin
return s1 + s2 * n
end function
print call repeat_strings string Hello string World 3
comment Output: HelloWorldHelloWorldHelloWorld
print call repeat_strings string abc string def 5
comment Output: abcdefabcdefabcdefabcdefabcdef
print call repeat_strings string 123 string 456 2
co... | def repeat_strings(s1, s2, n):
return (s1 + s2) * n
print(repeat_strings("Hello", "World", 3))
# Output: HelloWorldHelloWorldHelloWorld
print(repeat_strings("abc", "def", 5))
# Output: abcdefabcdefabcdefabcdefabcdef
print(repeat_strings("123", "456", 2))
# Output: 123456123456
| Python | jtatman_500k |
function reader self
begin
return call TFRecordReader
end function | def reader(self):
return tf.TFRecordReader() | Python | nomic_cornstack_python_v1 |
function generate_message name age gender
begin
if lower gender != string male and lower gender != string female
begin
raise call ValueError string Invalid gender. Please enter either 'male' or 'female'.
end
set message = string Hello, { name } ! You are a { gender } who is { age } years old.
return message
end functio... | def generate_message(name, age, gender):
if gender.lower() != "male" and gender.lower() != "female":
raise ValueError("Invalid gender. Please enter either 'male' or 'female'.")
message = f"Hello, {name}! You are a {gender} who is {age} years old."
return message
| Python | jtatman_500k |
string Computational Cancer Analysis Library Authors: Huwate (Kwat) Yeerna (Medetgul-Ernar) kwat.medetgul.ernar@gmail.com Computational Cancer Analysis Laboratory, UCSD Cancer Center Pablo Tamayo ptamayo@ucsd.edu Computational Cancer Analysis Laboratory, UCSD Cancer Center
import rpy2.robjects as ro
from numpy import f... | """
Computational Cancer Analysis Library
Authors:
Huwate (Kwat) Yeerna (Medetgul-Ernar)
kwat.medetgul.ernar@gmail.com
Computational Cancer Analysis Laboratory, UCSD Cancer Center
Pablo Tamayo
ptamayo@ucsd.edu
Computational Cancer Analysis Laboratory, UCSD Cancer Center
"""
im... | Python | zaydzuhri_stack_edu_python |
function _build_surface self prices offset intervals days
begin
assert length prices == 2 and length prices at 0 == length prices at 1
assert length prices at 0 >= offset + days
set opening = prices at 0
set closing = prices at 1
set surface = zeros tuple intervals + 2 days
comment opening and closing return on day 0
f... | def _build_surface(self, prices, offset, intervals, days):
assert len(prices) == 2 and len(prices[0]) == len(prices[1])
assert len(prices[0]) >= (offset + days)
opening = prices[0]
closing = prices[1]
surface = np.zeros((intervals + 2, days))
# opening and closing return... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Fri Jul 9 16:29:40 2021 @author: Gerald
comment !/usr/bin/python3
comment Importing the required packages
comment import pandas as pd
comment import os
comment Loading the csv file
comment data = pd.read_csv(r"C:\Users\Gerald\Desktop\DataScienceProject\sentences.csv")
com... | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 9 16:29:40 2021
@author: Gerald
"""
#!/usr/bin/python3
#Importing the required packages
#import pandas as pd
#import os
#Loading the csv file
#data = pd.read_csv(r"C:\Users\Gerald\Desktop\DataScienceProject\sentences.csv")
#Viewing the data in the csv
... | Python | zaydzuhri_stack_edu_python |
function prepare self
begin
set config = call read_config
call set_log_lvl config at string log_lvl name
set db = call DB keyword config at string mysql
call disable_warnings
end function | def prepare(self):
self.config = read_config()
set_log_lvl(self.config["log_lvl"], self.name)
self.db = DB(**self.config["mysql"])
urllib3.disable_warnings() | Python | nomic_cornstack_python_v1 |
function generate_xy_data x y
begin
set x_list = list
set y_list = list
for tuple key value in items x
begin
append x_list value
append y_list y at key
comment Data Agumentation
set img = copy value
set img = call flip value 0
append x_list img
append y_list y at key
set img = call flip value 1
append x_list img
appe... | def generate_xy_data(x,y):
x_list = []
y_list = []
for key,value in x.items():
x_list.append(value)
y_list.append(y[key])
# Data Agumentation
img = value.copy()
img = cv2.flip(value,0)
x_list.append(img)
y_list.append(y[key])
img = cv2.flip(va... | 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.