code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function main layers=none modules=none begin set test_runs = call create_test_runs layers=layers modules=modules set discovered_layers = set generator expression get param string layer string Unknown layer for param in test_runs for layer in discovered_layers begin debug string Discovered: %s layer end debug string Dis...
def main(layers=None, modules=None): test_runs = create_test_runs(layers=layers, modules=modules) discovered_layers = set(param.get("layer", "Unknown layer") for param in test_runs) for layer in discovered_layers: logger.debug("Discovered: %s", layer) logger.debug("Discovered %d layers in total....
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt import random as rn comment translates a random int into a step along the random walk comment parameters: int i for the step index, numpy array x for tracking the left/right location at index i, comment numpy array y for tracking the forward/backward location at index ...
import numpy as np import matplotlib.pyplot as plt import random as rn #translates a random int into a step along the random walk #parameters: int i for the step index, numpy array x for tracking the left/right location at index i, #numpy array y for tracking the forward/backward location at index i #return: none def...
Python
zaydzuhri_stack_edu_python
comment 写方法,跳转的页面,方法名字为跳转的网页的后缀 function index evn response begin comment print(evn,response) call response string 200 ok list tuple string Content-type string text/html_lib if evn at string PATH_INFO at slice 1 : : == string findall begin return list encode string <h1>这是查找所有的页面</h1> string gbk end else if evn at str...
# 写方法,跳转的页面,方法名字为跳转的网页的后缀 def index(evn,response): # print(evn,response) response('200 ok', [('Content-type', 'text/html_lib')]) if evn['PATH_INFO'][1:] == "findall": return ['<h1>这是查找所有的页面</h1>'.encode('gbk')] elif evn['PATH_INFO'][1:] == "addgood": return ['<h1>这是新增可疑人物的页面</h1>'.encode...
Python
zaydzuhri_stack_edu_python
comment !/Library/Frameworks/Python.framework/Versions/4.3/bin/python3 import npyscreen import pdb import imaplib import getpass import Queue from main_menu import MainMenu from main_menu_login_popup import MainMenuPopup from compose_mail import ComposeMail from inbox import Inbox from spell_check_popup import SpellChe...
#!/Library/Frameworks/Python.framework/Versions/4.3/bin/python3 import npyscreen import pdb import imaplib import getpass import Queue from main_menu import MainMenu from main_menu_login_popup import MainMenuPopup from compose_mail import ComposeMail from inbox import Inbox from spell_check_popup import SpellCheckPopu...
Python
zaydzuhri_stack_edu_python
comment author:ZhengNengjin comment date: 2018/8/29 set product_lists = list tuple string iphone6s 5800 tuple string mac book 9000 tuple string coffee 30 tuple string python book 80 tuple string bycle 1500 set saving = input string Please input your money: set shopping_car = list if is digit saving begin set saving = ...
#author:ZhengNengjin #date: 2018/8/29 product_lists = [ ('iphone6s',5800), ('mac book',9000), ('coffee',30), ('python book',80), ('bycle',1500), ] saving = input('Please input your money:') shopping_car = [] if saving.isdigit(): saving =int(saving) while True: # 打印商品内容 for i,v in enumerate (product_lists,1)...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment # Making flood contingency figures (colored) and statistics comment This notebook compares two flood maps and computes hit rate, miss rate, FAR, and correct negatives. IT also prepares a nice looking map over the target area. The following is done: comment - resampling maps to the same res...
# coding: utf-8 # # Making flood contingency figures (colored) and statistics # This notebook compares two flood maps and computes hit rate, miss rate, FAR, and correct negatives. IT also prepares a nice looking map over the target area. The following is done: # - resampling maps to the same resolution (e.g. using th...
Python
zaydzuhri_stack_edu_python
import cv2 as cv import numpy as np from skimage.util import random_noise function Average_Image Imagelist Count begin set Avg_Img = array Imagelist at 0 string f if Count == 5 begin print length Avg_Img length Avg_Img at 0 end for i in range Count - 1 begin set Avg_Img = Avg_Img + array Imagelist at i + 1 end set Avg_...
import cv2 as cv import numpy as np from skimage.util import random_noise def Average_Image(Imagelist, Count): Avg_Img = np.array(Imagelist[0], 'f') if Count == 5: print(len(Avg_Img), len(Avg_Img[0])) for i in range(Count-1): Avg_Img = Avg_Img + np.array(Imagelist[i+1]) Avg_Img = Avg...
Python
zaydzuhri_stack_edu_python
function log_info self message type=string info begin if type == string info begin debug message end else begin error message end end function
def log_info(self, message, type='info'): if type == 'info': logger.debug(message) else: logger.error(message)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import hashlib function create_md5 filename begin set hash_md5 = md5 with open filename string rb as f begin for chunk in iterate lambda -> read f 4096 b'' begin update hash_md5 chunk end end return hex digest hash_md5 end function function save_md5file filename data begin with open filen...
# -*- coding: utf-8 -*- import hashlib def create_md5(filename): hash_md5 = hashlib.md5() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest() def save_md5file(filename, data): with open(filename, 'w', -...
Python
zaydzuhri_stack_edu_python
function shortest_substring words string begin set shortest_word = none set shortest_length = decimal string inf for word in words begin if word in string and length word < shortest_length begin set shortest_word = word set shortest_length = length word end end return shortest_word end function set words = list string ...
def shortest_substring(words, string): shortest_word = None shortest_length = float('inf') for word in words: if word in string and len(word) < shortest_length: shortest_word = word shortest_length = len(word) return shortest_word words = ["apple", "banana", "cat", "do...
Python
jtatman_500k
function handle_node node _ctx tree_style=string line node_renderer=none begin try begin set style = STYLES at tree_style end except KeyError begin set style = call Style *tree_style end set tuple first tail = call uncons call iter_rows node style=style yield call render node_renderer for row in tail begin yield string...
def handle_node(node, _ctx, tree_style="line", node_renderer=None): try: style = STYLES[tree_style] except KeyError: style = Style(*tree_style) first, tail = uncons(iter_rows(node, style=style)) yield first.render(node_renderer) for row in tail: yield "\n" yield row....
Python
nomic_cornstack_python_v1
function getAllClosure index preSet currentSet begin if preSet == currentSet begin return currentSet end else begin set tempCurrent = currentSet for i in copy currentSet begin update currentSet lambdaClosure end return call getAllClosure index tempCurrent currentSet end end function function getValidStates str1 current...
def getAllClosure (index, preSet, currentSet): if preSet == currentSet: return currentSet else: tempCurrent = currentSet for i in currentSet.copy(): currentSet.update(vertexes[i].lambdaClosure) return (getAllClosure(index, tempCurrent, currentSet)) def getValidStates (str1, currentSet): landa = currentSe...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render comment Create your views here. function home request begin return call render request string home/home.html end function function get_time id begin from googleapiclient.discovery import build import os import re from datetime import timedelta set youtube = call build string youtube ...
from django.shortcuts import render # Create your views here. def home(request): return render(request,"home/home.html") def get_time(id): from googleapiclient.discovery import build import os import re from datetime import timedelta youtube = build('youtube','v3',developerKey = 'AIzaSyDid...
Python
zaydzuhri_stack_edu_python
for x in range 1 10 begin set c = a + b set a = b set b = c end
for x in range ( 1, 10 ) : c=a+b a=b b=c
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np import os import string import random import time from shared import LOSE , WIN , DRAW class Nn begin function __init__ self keep_prob=1 greedy=true epsilon=0 verbose=false learnign_rate=1e-05 batch_size=1 epochs=1 begin assert greedy in tuple true false assert verbose in tupl...
import tensorflow as tf import numpy as np import os import string import random import time from shared import LOSE, WIN, DRAW class Nn(): def __init__(self, keep_prob = 1, greedy=True, epsilon=0, verbose=False, learnign_rate=0.00001, batch_size=1, epochs=1): assert(greedy in (True, False)) asser...
Python
zaydzuhri_stack_edu_python
function findAxialMeshIndexOf self heightCm begin for tuple zi currentHeightCm in enumerate axialMesh at slice 1 : : begin if currentHeightCm >= heightCm begin return zi end end raise call ValueError format string The value {} cm is not within range of the reactor axial mesh with max {} heightCm currentHeightCm end fu...
def findAxialMeshIndexOf(self, heightCm): for zi, currentHeightCm in enumerate(self.p.axialMesh[1:]): if currentHeightCm >= heightCm: return zi raise ValueError( "The value {} cm is not within range of the reactor axial mesh with max {}" "".format(heig...
Python
nomic_cornstack_python_v1
function time_stats df begin print string Calculating The Most Frequent Times of Travel... set start_time = time comment display the most common month set popular_month = month_name at mode at 0 print string The most commnon month of travel is popular_month comment display the most common day of week set popular_day = ...
def time_stats(df): print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # display the most common month popular_month = calendar.month_name[df['month'].mode()[0]] print('The most commnon month of travel is ', popular_month) # display the most common day of we...
Python
nomic_cornstack_python_v1
string Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present). For example, [True, True, True, False, True, True, True, True , True, False, True, False, True, False, False, True , True, True, True, Tr...
""" Consider an array/list of sheep where some sheep may be missing from their place. We need a function that counts the number of sheep present in the array (true means present). For example, [True, True, True, False, True, True, True, True , True, False, True, False, True, ...
Python
zaydzuhri_stack_edu_python
function part1 begin set maze = list with open string day5.txt as f begin set temp = read lines f set maze = list map lambda x -> integer x temp end set loc = 0 set steps = 0 set newPos = 0 while length maze > loc > - 1 begin set newPos = loc + maze at loc set maze at loc = maze at loc + 1 set loc = newPos set steps =...
def part1(): maze=[] with open("day5.txt") as f: temp = f.readlines() maze = list(map(lambda x:int(x),temp)) loc = 0 steps = 0 newPos = 0 while(len(maze) > loc > -1): newPos = loc + maze[loc] maze[loc] += 1 loc = newPos steps += 1 print(steps) ...
Python
zaydzuhri_stack_edu_python
comment https://datatrading.info/sharpe-ratio-per-la-misura-delle-prestazioni-del-trading-algoritmico/ import datetime import numpy as np import pandas as pd from pandas_datareader import data as pdr function get_historic_data ticker start_date=tuple 2000 1 1 end_date=call timetuple at slice 0 : 3 : begin string Ottene...
# https://datatrading.info/sharpe-ratio-per-la-misura-delle-prestazioni-del-trading-algoritmico/ import datetime import numpy as np import pandas as pd from pandas_datareader import data as pdr def get_historic_data(ticker, start_date=(2000, 1, 1), end_date=datetime.date.t...
Python
zaydzuhri_stack_edu_python
function read_ascii_large fn dtype=Float begin set tmp = string %s.nodes % fn call runCommand string awk '/^[ ]*vertex[ ]+/{print $2,$3,$4}' '%s' | d2u > '%s' % tuple fn tmp set nodes = reshape call fromfile tmp sep=string dtype=dtype tuple - 1 3 3 return nodes end function
def read_ascii_large(fn,dtype=Float): tmp = '%s.nodes' % fn utils.runCommand("awk '/^[ ]*vertex[ ]+/{print $2,$3,$4}' '%s' | d2u > '%s'" % (fn,tmp)) nodes = fromfile(tmp,sep=' ',dtype=dtype).reshape((-1,3,3)) return nodes
Python
nomic_cornstack_python_v1
comment import the necessary libraries comment this is for data processing with dataframes import pandas as pd comment this is for various number things like the random choice and the zeros array import numpy as np import datetime comment this allows us to access the data in the other file from team_path_map import Bra...
# import the necessary libraries import pandas as pd # this is for data processing with dataframes import numpy as np # this is for various number things like the random choice and the zeros array import datetime from team_path_map import BracketMap # this allows us to access the data in the other file def wei...
Python
zaydzuhri_stack_edu_python
function ParamChange like sr change=string freeze begin if length sr == 0 begin raise call ValueError string No source specified end comment Default freeze everything. for i in call xrange length params begin call freeze i end comment Free up specified sources ("sr") if lower change == string thaw begin for src in sr b...
def ParamChange(like,sr,change='freeze'): if (len(sr) == 0): raise ValueError("No source specified") # Default freeze everything. for i in xrange( len(like.model.params) ): like.freeze(i) # Free up specified sources ("sr") if (change.lower() == 'thaw'): for src in sr: ...
Python
nomic_cornstack_python_v1
import sys comment sys.stdin = open("in1.txt", "rt") set tuple n m = map int split input set a = list map int split input sort a set lt = 0 set rt = n - 1 while true begin set p = lt + rt // 2 if a at p == m begin print p + 1 break end if a at p > m begin set rt = p - 1 set p = p // 2 end if a at p < m begin set lt = p...
import sys #sys.stdin = open("in1.txt", "rt") n,m = map(int,input().split()) a=list(map(int,input().split())) a.sort() lt=0 rt=n-1 while True: p=(lt+rt)//2 if a[p]==m: print(p+1) break if a[p]>m: rt=p-1 p=p//2 if a[p]<m: lt=p+1 # 0 1 2 3 4 5 6 7
Python
zaydzuhri_stack_edu_python
from svm_factory import supportvector from nb_factory import naivebayes from features import sentiment from features import pos comment from features import in_out from features.feature_group import Group from nn_model_factory import neuralnet import itertools from bow import bow from scores import smog , readability i...
from svm_factory import supportvector from nb_factory import naivebayes from features import sentiment from features import pos #from features import in_out from features.feature_group import Group from nn_model_factory import neuralnet import itertools from bow import bow from scores import smog, readability import tr...
Python
zaydzuhri_stack_edu_python
function Undo array changes begin if length changes > 0 begin set lastChange = changes at length changes - 1 at slice : : del changes at length changes - 1 return lastChange end return array end function
def Undo(array, changes): if len(changes) > 0: lastChange = changes[len(changes) - 1][:] del changes[len(changes) - 1] return lastChange return array
Python
nomic_cornstack_python_v1
function get self begin set ops = get request string ops info string get: + ops if ops begin set body = ops post set headers at string Content-Type = string text/html end end function
def get(self): ops = self.request.get('ops') logging.info('get: ' + ops) if ops: self.request.body = ops self.post() self.response.headers['Content-Type'] = 'text/html'
Python
nomic_cornstack_python_v1
import sys import numpy as np from scipy.spatial.distance import cityblock import math set board = zeros tuple 3 5 string Set hound position with value 1 set board at 0 at 1 = 1 set board at 1 at 0 = 1 set board at 2 at 1 = 1 string Set hare position with value 2 set board at 1 at 4 = 2 set player = input string Do you...
import sys import numpy as np from scipy.spatial.distance import cityblock import math board = np.zeros((3, 5)) """ Set hound position with value 1""" board[0][1] = 1 board[1][0] = 1 board[2][1] = 1 """ Set hare position with value 2 """ board[1][4] = 2 player = input('Do you want to be hare or hound...
Python
zaydzuhri_stack_edu_python
comment A - Diverse Word import numpy as np set S = input set alphabet = zeros 26 dtype=int for i in S begin set alphabet at ordinal i - 97 = 1 end if length S < 26 begin set add = argument minimum set ans = S + character add + 97 end else begin set i = 24 while i >= 0 and S at i > S at i + 1 begin set i = i - 1 end if...
# A - Diverse Word import numpy as np S = input() alphabet = np.zeros(26, dtype=int) for i in S: alphabet[ord(i)-97]=1 if len(S)<26: add = alphabet.argmin() ans = S + chr(add+97) else: i = 24 while(i>=0 and S[i]>S[i+1]): i -= 1 if i==-1: ans = '-1' else: j = 25 ...
Python
zaydzuhri_stack_edu_python
comment Description comment Write a program that asks the user to enter an amount of money in the format of dollars and remaining cents. The program should calculate and print the minimum number of coins (quarters, dimes, nickels and pennies) that are equivalent to the given amount. comment Hint: In order to find the m...
#Description #Write a program that asks the user to enter an amount of money in the format of dollars and remaining cents. The program should calculate and print the minimum number of coins (quarters, dimes, nickels and pennies) that are equivalent to the given amount. #Hint: In order to find the minimum number of c...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import RPi.GPIO as GPIO import time comment ''' comment 使用2块L298N驱动控制4个直流电机 comment 前轮驱动:18-ENDA, 22-ENDB, 11-左前前, 12-左前后, 16-右前前, 29-右前后 comment 后轮驱动:38-ENDA, 40-ENDB, 31-左后前, 33-左后后, 35-右后前, 37-右后后 comment ''' comment 初始化设置引脚输出 function init begin comment GPIO.setmode(GPIO.BOARD) setup G...
# -*- coding: utf-8 -*- import RPi.GPIO as GPIO import time # ''' # 使用2块L298N驱动控制4个直流电机 # 前轮驱动:18-ENDA, 22-ENDB, 11-左前前, 12-左前后, 16-右前前, 29-右前后 # 后轮驱动:38-ENDA, 40-ENDB, 31-左后前, 33-左后后, 35-右后前, 37-右后后 # ''' # 初始化设置引脚输出 def init(): # GPIO.setmode(GPIO.BOARD) GPIO.setup(18, GPIO.OUT) GPIO.setup(11,...
Python
zaydzuhri_stack_edu_python
function print_numbers n begin set res = string for i in range 1 n + 1 begin set res = res + string i + string end return res end function function floyd_triangle begin set rows = integer input string Enter row number: set n = 1 for i in range 1 rows + 1 begin print string * rows - i + call print_numbers n set n = n...
def print_numbers(n): res = '' for i in range(1,n+1): res += str(i)+' ' return res def floyd_triangle(): rows = int(input("Enter row number: ")) n = 1 for i in range(1,rows+1): print(' '*(rows - i) + print_numbers(n)) n += 1 fl...
Python
zaydzuhri_stack_edu_python
function rexHist iterable title write=false imgFilePath=none begin set fileList = list iterable set fileList = map expandPath fileList set tempArray = list end function
def rexHist(iterable, title, write=False, imgFilePath=None): fileList = list(iterable) fileList = map(expandPath, fileList) tempArray = []
Python
nomic_cornstack_python_v1
function main begin comment escribe tu código abajo de esta línea set x = 8 set y = 6 while y <= x begin set x = x + 1 set y = y + 2 end print x print y end function if __name__ == string __main__ begin call main end
def main(): #escribe tu código abajo de esta línea x = 8 y = 6 while y <= x: x += 1 y += 2 print(x) print(y) if __name__=='__main__': main()
Python
zaydzuhri_stack_edu_python
class ListNode begin function __init__ self val=0 next=none begin set val = val set next = next end function end class class TreeNode begin function __init__ self val=0 left=none right=none begin set val = val set left = left set right = right end function end class function linkedList llist begin if length llist == 0 ...
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def linkedList(llist): if len(llist)==0: ...
Python
zaydzuhri_stack_edu_python
function parse_basic_info self begin set divs = find all soup class_=CLASS_INFO set info = dict set name = string for div in divs begin if string name in get div string class begin set name = replace get text div strip=true string string end if string value in get div string class begin set value = get text div stri...
def parse_basic_info(self): divs = self.soup.find_all(class_=CLASS_INFO) info = {} name = "" for div in divs: if 'name' in div.get('class'): name = div.get_text(strip=True).replace(u"\xa0", "") if 'value' in div.get('class'): value ...
Python
nomic_cornstack_python_v1
import pymysql.cursors comment http://pymysql.readthedocs.io/en/latest/modules/cursors.html set connection = call connect host=string localhost user=string root password=string admin db=string zhulien_db charset=string utf8mb4 cursorclass=DictCursor try begin comment single inserts with call cursor as cursor begin set ...
import pymysql.cursors # http://pymysql.readthedocs.io/en/latest/modules/cursors.html connection = pymysql.connect(host='localhost', user='root', password='admin', db='zhulien_db', charset='utf8mb4', ...
Python
zaydzuhri_stack_edu_python
import requests from lxml import etree set headers = dict string User-agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 comment 网页页面复杂,很难爬取 set url = string https://vacations.ctrip.com/travel/detail/p22125398/?city=376 set page_text = text se...
import requests from lxml import etree headers = {'User-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'} url = 'https://vacations.ctrip.com/travel/detail/p22125398/?city=376' # 网页页面复杂,很难爬取 page_text = requests.get(url=url,headers = headers).t...
Python
zaydzuhri_stack_edu_python
from osm2networkx import * import random string Searching a street network using Breadth First Search REQUIREMENTS: networkx: http://networkx.github.io/ REFERENCES: [1] Russel, Norvig: "Artificial Intelligene A Modern Approach", 3rd ed, Prentice Hall, 2010 ASSIGNMENT: Extend this program to Tridirectional Search. Find ...
from osm2networkx import * import random """ Searching a street network using Breadth First Search REQUIREMENTS: networkx: http://networkx.github.io/ REFERENCES: [1] Russel, Norvig: "Artificial Intelligene A Modern Approach", 3rd ed, Prentice Hall, 2010 ASSIGNMENT: Extend this program to Tridirectional Sea...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment sms_5c.py import sys , os import StringIO import pycurl , urllib import re function get_content begin set message = string set message = format string {0}:{1} {2}: {3} -> {4} {5} environ at string NOTIFY_NOTIFICATIONTYPE environ at string NOTIFY_SHORTDATETIME environ at string NOTIFY_H...
#!/usr/bin/python #sms_5c.py import sys, os import StringIO import pycurl, urllib import re def get_content(): message = '' message = "{0}:{1}\n{2}: {3} -> {4}\n{5}".format( os.environ['NOTIFY_NOTIFICATIONTYPE'], os.environ['NOTIFY_SHORTDATETIME'], os.environ['NOTIFY_HOSTNAME'], os.environ['NOTIFY_LASTHOST...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2.7 comment Python 2.7 version by Alex Eames of http://RasPi.TV comment functionally similar to the Gertboard motor test by comment Gert Jan van Loo & Myra VanInwegen comment Use at your own risk - I'm pretty sure the code is harmless, check it yourself comment This is the software PWM versi...
#!/usr/bin/env python2.7 # Python 2.7 version by Alex Eames of http://RasPi.TV # functionally similar to the Gertboard motor test by # Gert Jan van Loo & Myra VanInwegen # Use at your own risk - I'm pretty sure the code is harmless, check it yourself # This is the software PWM version. It's not as good as the WiringP...
Python
zaydzuhri_stack_edu_python
for s in strings begin print s set replaced = split s string _ if length replaced == 0 begin print string end else if length replaced == 1 begin print replaced at 0 end else begin set replaced = join string split join string replaced set replaced = split replaced if length replaced >= 1 begin set replaced at 0 = lowe...
for s in strings: print(s) replaced = s.split("_") if len(replaced) == 0: print("") elif len(replaced) == 1: print(replaced[0]) else: replaced = ' '.join(' '.join(replaced).split()) replaced = replaced.split() if len(replaced) >= 1: replaced...
Python
zaydzuhri_stack_edu_python
comment 32000 import numpy as np import wave from scipy import signal from scipy.io import wavfile from scipy.fftpack import dct import matplotlib.pyplot as plt import pickle as pk import random import os from keras.models import Sequential from keras.layers import Dense , Dropout , Activation , Flatten from keras.laye...
#32000 import numpy as np import wave from scipy import signal from scipy.io import wavfile from scipy.fftpack import dct import matplotlib.pyplot as plt import pickle as pk import random import os from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render from django.http import HttpResponse from models import User comment get_object_or_404 用来返回http请求 comment 格式: get_object_or_404(models, **kwargs) from django.shortcuts import get_object_or_404 from django.http import Http404 import traceback comment Create your views here. function i...
from django.shortcuts import render from django.http import HttpResponse from .models import User # get_object_or_404 用来返回http请求 # 格式: get_object_or_404(models, **kwargs) from django.shortcuts import get_object_or_404 from django.http import Http404 import traceback # Create your views here. def index(request): ...
Python
zaydzuhri_stack_edu_python
import unicodedata class Item begin function __init__ self name variants=list begin set name = name set variants = call _generate_variants variants + list name end function function __eq__ self other begin if type other == type self begin return name == name end return false end function function __str__ self begin ret...
import unicodedata class Item: def __init__(self, name, variants=[]): self.name = name self.variants = Item._generate_variants(variants + [name]) def __eq__(self, other): if type(other) == type(self): return self.name == other.name return False def __str__(sel...
Python
zaydzuhri_stack_edu_python
import math function is_prime n begin if n <= 1 begin return false end if n == 2 begin return true end if n % 2 == 0 begin return false end for i in range 3 integer square root n + 1 2 begin if n % i == 0 begin return false end end return true end function comment Define the range set start = 10 set end = 30 comment Co...
import math def is_prime(n): if n <= 1: return False if n == 2: return True if n % 2 == 0: return False for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: return False return True # Define the range start = 10 end = 30 # Convert the range to a ...
Python
jtatman_500k
function teardown cls begin del place end function
def teardown(cls): del cls.place
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import string function checkio text begin set d = dict string a 0 set text = lower text comment for c in text: comment if not c.isalpha(): comment continue comment n = text.count(c) comment values = d.values() comment if max(values) < n: comment d.clear() comment d[c] = n comment elif max(...
# -*- coding: utf-8 -*- import string def checkio(text): d = {'a': 0} text = text.lower() # for c in text: # if not c.isalpha(): # continue # n = text.count(c) # values = d.values() # if max(values) < n: # d.clear() # d[c] = n # e...
Python
zaydzuhri_stack_edu_python
function _set_alt_port app_definition alt_port begin set app_definition at string labels at string HAPROXY_DEPLOYMENT_ALT_PORT = string alt_port return app_definition end function
def _set_alt_port(app_definition, alt_port): app_definition['labels']['HAPROXY_DEPLOYMENT_ALT_PORT'] = str(alt_port) return app_definition
Python
nomic_cornstack_python_v1
function _rle_decode_frame data rows columns nr_samples nr_bits segment_order=string > begin if nr_bits % 8 begin raise call NotImplementedError string Unable to decode RLE encoded pixel data with a (0028,0100) 'Bits Allocated' value of { nr_bits } end comment Parse the RLE Header set offsets = call _parse_rle_header d...
def _rle_decode_frame( data: bytes, rows: int, columns: int, nr_samples: int, nr_bits: int, segment_order: str = ">", ) -> bytearray: if nr_bits % 8: raise NotImplementedError( "Unable to decode RLE encoded pixel data with a (0028,0100) " f"'Bits Allocated' va...
Python
nomic_cornstack_python_v1
function _get_exporter self args begin string Return a :class:`PrometheusExporter` configured with args. set exporter = call PrometheusExporter name description host port registry append on_startup on_application_startup append on_shutdown on_application_shutdown return exporter end function
def _get_exporter(self, args: argparse.Namespace) -> PrometheusExporter: """Return a :class:`PrometheusExporter` configured with args.""" exporter = PrometheusExporter( self.name, self.description, args.host, args.port, self.registry) exporter.app.on_startup.append(self.on_applicatio...
Python
jtatman_500k
function _get_capability self begin return __capability end function
def _get_capability(self): return self.__capability
Python
nomic_cornstack_python_v1
function move_svn_log cls args begin if crash begin exit list string ERROR: Epic Svn Log: Raising an unhandled exception end print string info: Svn Log: greetchars end function
def move_svn_log(cls, args): if args.crash: sys.exit(['ERROR: Epic Svn Log: Raising an unhandled exception']) print('info: Svn Log:', args.greetchars)
Python
nomic_cornstack_python_v1
function main book_filepath books_xml_dir output_filepath begin set book_extra_info_rows = call extract_book_extra_info books_xml_dir set book_extra_info_df = call process_book_extra_info book_extra_info_rows set book_df = read csv book_filepath set book_merged_data_df = call merge_book_data book_df book_extra_info_df ...
def main(book_filepath: str, books_xml_dir: str, output_filepath: str): book_extra_info_rows = extract_book_extra_info(books_xml_dir) book_extra_info_df = process_book_extra_info(book_extra_info_rows) book_df = pd.read_csv(book_filepath) book_merged_data_df = merge_book_data(book_df, book_extra_info_df...
Python
nomic_cornstack_python_v1
from time import sleep import random from selenium import webdriver import argparse set classToSelector = dict string bodypump-mon string ctl00$MainContent$activitiesGrid$ctl19$lnkListCommand ; string bodypump-wed string ctl00$MainContent$activitiesGrid$ctl20$lnkListCommand ; string insanity-mon string ctl00$MainConten...
from time import sleep import random from selenium import webdriver import argparse classToSelector = { "bodypump-mon": "ctl00$MainContent$activitiesGrid$ctl19$lnkListCommand", "bodypump-wed": "ctl00$MainContent$activitiesGrid$ctl20$lnkListCommand", "insanity-mon": "ctl00$MainContent$activitiesGrid$ctl16$l...
Python
zaydzuhri_stack_edu_python
from datetime import datetime from database.db import db class WeatherObservation extends Model begin set id = call Column Integer primary_key=true nullable=false set city = call Column String nullable=false set text = call Column String nullable=false set datetime = call Column DateTime nullable=false default=utcnow f...
from datetime import datetime from database.db import db class WeatherObservation(db.Model): id = db.Column(db.Integer, primary_key=True, nullable=False) city = db.Column(db.String, nullable=False) text = db.Column(db.String, nullable=False) datetime = db.Column(db.DateTime, n...
Python
zaydzuhri_stack_edu_python
function get_incident_priorities db_session=call Depends get_db page=1 items_per_page=query 5 alias=string itemsPerPage query_str=query none alias=string q sort_by=query list alias=string sortBy[] descending=query list alias=string descending[] fields=query list alias=string fields[] ops=query list alias=string ops...
def get_incident_priorities( db_session: Session = Depends(get_db), page: int = 1, items_per_page: int = Query(5, alias="itemsPerPage"), query_str: str = Query(None, alias="q"), sort_by: List[str] = Query([], alias="sortBy[]"), descending: List[bool] = Query([], alias="descending[]"), fields...
Python
nomic_cornstack_python_v1
import requests import json import sys import csv from math import sin , cos , sqrt , atan2 , radians function getlatlong ip begin comment url = "http://api.ipstack.com/163.118.241.234" set url = string http://api.ipstack.com/ + ip print url set querystring = dict string access_key string 91224a4223a5f29f868752bc83c3b2...
import requests import json import sys import csv from math import sin, cos, sqrt, atan2, radians def getlatlong(ip): ##url = "http://api.ipstack.com/163.118.241.234" url = "http://api.ipstack.com/" + ip print (url) querystring = {"access_key":"91224a4223a5f29f868752bc83c3b2a4"} ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 string is_kind_of_class Module function is_kind_of_class obj a_class begin string Returns True if the object is an instance of the class, or an instance of the class that it has inherited from return is instance obj a_class end function
#!/usr/bin/python3 """ is_kind_of_class Module """ def is_kind_of_class(obj, a_class): """Returns True if the object is an instance of the class, or an instance of the class that it has inherited from""" return isinstance(obj, a_class)
Python
zaydzuhri_stack_edu_python
comment Write the function that will measure the area of square based comment on the lenght of it's sides function square_area lenght lenght_2 begin return lenght_2 * lenght end function print call square_area 3 4
# Write the function that will measure the area of square based # on the lenght of it's sides def square_area(lenght, lenght_2): return lenght_2*lenght print(square_area(3,4))
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment ____________developed by paco andres____________________ set fib = list 1 1 2 3 5 8 13 21 set even = list set even1 = list for n in fib begin if n % 2 == 0 begin append even n end end set even1 = list comprehension n for n in fib if n % 2 == 0 if __na...
#!/usr/bin/env python # -*- coding: utf-8 -*- #____________developed by paco andres____________________ fib = [1, 1, 2, 3, 5, 8, 13, 21] even = [] even1 = [] for n in fib: if n % 2 == 0: even.append(n) even1=[n for n in fib if n%2==0] if __name__ == "__main__": print (even) print (even1)
Python
zaydzuhri_stack_edu_python
comment Importing modules from numpy import * from pylab import * set g = 9.8 comment Projectile Function function Projectile_Plot u α begin comment for pronging legend set αd = α comment converting angle in radians set α = call radians α comment Evaluating Range set R = u ^ 2 * sin 2 * α / g comment Evaluating max hei...
# Importing modules from numpy import * from pylab import * g=9.8 # Projectile Function def Projectile_Plot(u,α): # for pronging legend αd=α # converting angle in radians α=radians(α) # Evaluating Range R=u**2*sin(2*α)/g # Evaluating max height h=u**2*(sin(α))**2/(2*g) # Creating array...
Python
zaydzuhri_stack_edu_python
function filteritems predicate dict_ begin string Return a new dictionary comprising of items for which ``predicate`` returns True. :param predicate: Predicate taking a key-value pair, or None .. versionchanged: 0.0.2 ``predicate`` is now taking a key-value pair as a single argument. set predicate = if expression predi...
def filteritems(predicate, dict_): """Return a new dictionary comprising of items for which ``predicate`` returns True. :param predicate: Predicate taking a key-value pair, or None .. versionchanged: 0.0.2 ``predicate`` is now taking a key-value pair as a single argument. """ predicate ...
Python
jtatman_500k
class Employee begin set raise_amt = 1.04 function __init__ self first last pay begin set first = first set last = last set email = first + string . + last + string @email.com set pay = pay end function function fullname self begin return format string {} {} first last end function function apply_raise self begin set p...
class Employee: raise_amt = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.email = first + "." + last + '@email.com' self.pay = pay def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): ...
Python
zaydzuhri_stack_edu_python
function kill self begin if vertical_timer is not none and call is_playing begin call _clean_up_vertical call stop end if horizontal_timer is not none and call is_playing begin call _clean_up_horizontal call stop end end function
def kill(self): if self.vertical_timer is not None \ and self.vertical_timer.is_playing(): self._clean_up_vertical() self.vertical_timer.stop() if self.horizontal_timer is not None and \ self.horizontal_timer.is_playing(): self._clean_up_hor...
Python
nomic_cornstack_python_v1
comment DPL_1_B comment http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_1_B set items = list set used = list set dp = list function knapsack n e begin for i in range 0 n + 1 begin set res = 0 for j in range 0 e begin set tuple v w = items at j if i >= w begin set dp at j + 1 at i = max dp at j at i - w ...
# DPL_1_B # http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DPL_1_B items = [] used = [] dp = [] def knapsack(n, e): for i in range(0, n + 1): res = 0 for j in range(0, e): v, w = items[j] if i >= w: dp[j + 1][i] = max(dp[j][i - w] + v...
Python
zaydzuhri_stack_edu_python
function schema_registry self begin return get pulumi self string schema_registry end function
def schema_registry(self) -> Optional[bool]: return pulumi.get(self, "schema_registry")
Python
nomic_cornstack_python_v1
from application.model.review import Review from application.persistence import review_persistence set __author__ = string Dani Meana function get_by_movie_id movie_id begin return call get_by_movie_id movie_id end function function get_by_movie_id_and_username movie_id username begin return call get_by_movie_id_and_us...
from application.model.review import Review from application.persistence import review_persistence __author__ = 'Dani Meana' def get_by_movie_id(movie_id): return review_persistence.get_by_movie_id(movie_id) def get_by_movie_id_and_username(movie_id, username): return review_persistence.get_by_movie_id_and...
Python
zaydzuhri_stack_edu_python
function _set_misc_params self params begin info string FoscamMJPEG:set_misc_params:%s: %s % tuple name params return call _http_get string set_misc.cgi params end function
def _set_misc_params(self,params): self.parent.logger.info("FoscamMJPEG:set_misc_params:%s: %s" % (self.name,params)) return self._http_get("set_misc.cgi",params)
Python
nomic_cornstack_python_v1
function test_binary_fairness_functional self inputs ignore_index begin set tuple preds target groups = inputs if ignore_index == - 1 begin set target = call inject_ignore_index target ignore_index end call run_functional_metric_test preds=preds target=target metric_functional=binary_fairness reference_metric=partial _...
def test_binary_fairness_functional(self, inputs, ignore_index): preds, target, groups = inputs if ignore_index == -1: target = inject_ignore_index(target, ignore_index) self.run_functional_metric_test( preds=preds, target=target, metric_functiona...
Python
nomic_cornstack_python_v1
class Chicken begin set total_eggs = 0 function __init__ self name species begin set name = name set species = species set eggs = 0 end function function lay_egg self begin set total_eggs = total_eggs + 1 set eggs = eggs + 1 return string { name } layed egg. Total layed egg count is { eggs } end function end class set ...
class Chicken: total_eggs = 0 def __init__(self, name, species): self.name = name self.species = species self.eggs = 0 def lay_egg(self): Chicken.total_eggs += 1 self.eggs += 1 return f"{self.name} layed egg. Total laye...
Python
zaydzuhri_stack_edu_python
string 字符串字面值 comment 1.双引号 set name01 = string 孙悟空 comment 2.单引号 set name02 = string 孙悟空 comment 3.三引号:可见即所得 set name03 = string 孙 悟 空 print name03 set name03 = string 孙悟空 comment 4. set message01 = string 我是"孙悟空"。 set message02 = string 我是'孙悟空'。 set message03 = string 我是'孙'悟"空"。 comment 5. 转义字符:改变原始含义的特殊字符 comment \"...
""" 字符串字面值 """ # 1.双引号 name01 = "孙悟空" # 2.单引号 name02 = '孙悟空' # 3.三引号:可见即所得 name03 = ''' 孙 悟 空''' print(name03) name03 = """孙悟空 """ # 4. message01 = '我是"孙悟空"。' message02 = "我是'孙悟空'。" message03 = '''我是'孙'悟"空"。''' # 5. 转义字符:改变原始含义的特殊字符 # \" \\ r"" 换行\n ... message04 = "我是\"孙悟空\"。" url = r"C:\arogram F...
Python
zaydzuhri_stack_edu_python
function details name age interests begin set a = format string Hello {}!You are {} years old...and you like {} name age interests return a end function print call details string Renu interests=string Coding age=21
def details(name,age,interests): a="Hello {}!You are {} years old...and you like {}".format(name,age,interests) return a print(details("Renu",interests="Coding",age=21))
Python
zaydzuhri_stack_edu_python
string We need a method in the List Class that may count specific digits from a given list of integers. This marked digits will be given in a second list. The method .count_spec_digits()/.countSpecDigits() will accept two arguments, a list of an uncertain amount of integers integers_lists/integersLists (and of an uncer...
''' We need a method in the List Class that may count specific digits from a given list of integers. This marked digits will be given in a second list. The method .count_spec_digits()/.countSpecDigits() will accept two arguments, a list of an uncertain amount of integers integers_lists/integersLists (and of an uncertai...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment user options/args import sys comment import time # see how long it took for the program run import matplotlib.pyplot as plt comment import scipy.io.wavfile # read and spectrograph .wav files from scipy.io import wavfile from pydub import AudioSegment , effects comment convert audio for...
#!/usr/bin/python3 import sys # user options/args #import time # see how long it took for the program run import matplotlib.pyplot as plt #import scipy.io.wavfile # read and spectrograph .wav files from scipy.io import wavfile from pydub import AudioSegment, effects # convert audio formats (.mp3 and .wav) and normal...
Python
zaydzuhri_stack_edu_python
function advance_board self begin set board = board set rules = energy_rules set tuple h w = shape set beta = 1.0 / max 1e-20 temperature if length rules at 0 - 1 == 4 begin set neighborhood = array list list 0 1 0 list 1 0 1 list 0 1 0 end else if length rules at 0 - 1 == 6 begin set neighborhood = array list list 0 1...
def advance_board(self): board = self.board rules = self.energy_rules h, w = board.shape beta = 1.0 / max(1e-20, self.temperature) if len(rules[0]) - 1 == 4: neighborhood = np.array([[0,1,0],[1,0,1],[0,1,0]]) elif len(rules[0]) - 1 == 6: neighborho...
Python
nomic_cornstack_python_v1
function test_check_transaction_threw_old_status begin with raises AssertionError begin call check_transaction_threw dict string this string is ; string a string receipt ; string without string status end end function
def test_check_transaction_threw_old_status(): with pytest.raises(AssertionError): check_transaction_threw({"this": "is", "a": "receipt", "without": "status"})
Python
nomic_cornstack_python_v1
function CamelCase text separator=string _ begin return join string map capitalize split text separator end function
def CamelCase(text, separator='_'): return ''.join(map(str.capitalize, text.split(separator)))
Python
nomic_cornstack_python_v1
while true begin set c1 = input string Password : set c2 = input string Enter password again : if c1 != c2 begin print string Password incorrect.PLease enter password again. end if c1 == c2 begin print string Account successfully registered. break end end
while True : c1 = input("Password :") c2 = input("Enter password again :") if c1 != c2 : print("Password incorrect.PLease enter password again.") if c1 == c2 : print("Account successfully registered.") break
Python
zaydzuhri_stack_edu_python
function run_env self key value begin pass end function
def run_env(self, key, value): pass
Python
nomic_cornstack_python_v1
set s = string rafael print s print s at 0 print s at 1 print s at 2 comment ultimo elemento print s at - 1 comment produz rafa print s at slice 0 : 4 : comment produz afael print s at slice 1 : 6 : print s at slice 5 : 20 : comment produz leafar print s at slice : : - 1 comment salto de 2 em 2 print s at slice : :...
s = "rafael" print(s) print(s[0]) print(s[1]) print(s[2]) print(s[-1]) #ultimo elemento print(s[0:4]) #produz rafa print(s[1:6]) #produz afael print(s[5:20]) print(s[::-1]) #produz leafar print(s[::2]) #salto de 2 em 2 print(s[::4])
Python
zaydzuhri_stack_edu_python
for _ in range integer input begin set tuple n m = map int split input set a = list map int split input set b = list map int split input set tuple sa sb = tuple sum a sum b if sa > sb begin print 0 end else begin set a = sorted a set b = sorted b reverse=true set c = 0 for i in range min n m begin set sa = sa + b at i ...
for _ in range(int(input())): n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) sa, sb = sum(a), sum(b) if sa>sb: print(0) else: a = sorted(a) b = sorted(b, reverse=True) c = 0 for i in range(min(n, m)...
Python
zaydzuhri_stack_edu_python
function set_crystal self file_refl a_bragg=0.0 thickness=0.1 tune_auto=0 tune_units=0 tune_ev=0.0 tune_ang=0.0 begin set F_CRYSTAL = 1 set FILE_REFL = call adjust_shadow_string file_refl if a_bragg != 0.0 begin call set_asymmetric_cut a_bragg thickness end if tune_auto == 0 begin set F_CENTRAL = 0 end else begin call ...
def set_crystal(self, file_refl, a_bragg=0.0, thickness=0.1,\ tune_auto=0, tune_units=0, tune_ev=0.0, tune_ang=0.0): self.F_CRYSTAL = 1 self.FILE_REFL = adjust_shadow_string(file_refl) if a_bragg != 0.0: self.set_asymmetric_cut(a_bragg, thickness) if tune_auto == 0:...
Python
nomic_cornstack_python_v1
function select_database db_name db_type db_url user password repo_conn=none begin try begin if repo_conn is none begin set repo_conn = call _repo_connect end set bmg = call _base_meta_gen set rm = call _repo_manager repo_conn set db_obj = call generate_database_meta db_name db_type db_url user password save db_obj ret...
def select_database(db_name, db_type, db_url, user, password, repo_conn=None): try: if repo_conn is None: repo_conn = _repo_connect() bmg = _base_meta_gen() rm = _repo_manager(repo_conn) db_obj = bmg.generate_database_meta(db_name, db_type, db_url, ...
Python
nomic_cornstack_python_v1
function load self dataframe begin set records = call to_dict orient=string records comment Not proud of this, would love to figure out a way comment around this natively in Pandas for row in records begin for k in row begin if is instance row at k Timestamp begin set row at k = call to_datetime end end end return call...
def load(self, dataframe): records = dataframe.to_dict(orient='records') # Not proud of this, would love to figure out a way # around this natively in Pandas for row in records: for k in row: if isinstance(row[k], pd.tslib.Timestamp): row[...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import time set epoch = time print string epoch epoch set t = call localtime epoch print string local time t set d = tm_mday set m = tm_mon set y = tm_year print string Current date is %d-%d-%d % tuple d m y set te = call ctime epoch print string Ctime : epoch te set t = call ctime print s...
# -*- coding: utf-8 -*- import time epoch =time.time() print("epoch",epoch) t = time.localtime(epoch) print('local time',t) d = t.tm_mday m = t.tm_mon y = t.tm_year print('Current date is %d-%d-%d' %(d,m,y)) te = time.ctime(epoch) print('Ctime : epoch ',te) t = time.ctime() print('ctime ',t) from datetime import * now...
Python
zaydzuhri_stack_edu_python
import time import pandas print string Welcome to Sudoku print string Plese Enter Each Row in Puzzel then Press Enter set board = list function main begin for row in range 0 9 begin comment Removes any spaces in rows append board replace input string string end for tuple index line in enumerate board begin comment co...
import time import pandas print("Welcome to Sudoku") print("Plese Enter Each Row in Puzzel then Press Enter") board = [] def main(): for row in range(0, 9): board.append(input().replace(" ", "")) #Removes any spaces in rows for index, line in enumerate(board): board[index] = lis...
Python
zaydzuhri_stack_edu_python
import cv2 import io import picamera import logging import socketserver from http import server import numpy as np import os import yaml import requests import json set server_url = string http://0.0.0.0:8080 set cascadePath1 = string face_recognization/Cascades/haarcascade_frontalface_default.xml comment cascadePath2 ...
import cv2 import io import picamera import logging import socketserver from http import server import numpy as np import os import yaml import requests import json server_url = 'http://0.0.0.0:8080' cascadePath1 = "face_recognization/Cascades/haarcascade_frontalface_default.xml" # cascadePath2 = "face_recognization/C...
Python
zaydzuhri_stack_edu_python
function create userDetails begin comment Remove id as it's created automatically if string id in userDetails begin del userDetails at string id end comment abort if these fields are set if string showWelcome in userDetails begin call abort 400 string Unable to set isWelcome in POST operation. end comment Admin rights ...
def create(userDetails): # Remove id as it's created automatically if "id" in userDetails: del userDetails["id"] # abort if these fields are set if "showWelcome" in userDetails: abort(400, "Unable to set isWelcome in POST operation.") # Admin rights can't be set via POST nor PUT ca...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from scipy.integrate import solve_ivp as solve string | code in between lines | comment Defining constants comment Mass in kilogramme set m = 1 comment force in newton set F_naught = 1 comment wT dimensionless set freqT = 0.1 comment Maximum ti...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from scipy.integrate import solve_ivp as solve """ | code in between lines | """ #Defining constants m = 1 #Mass in kilogramme F_naught = 1 #force in newton freqT = 0.1 #wT dime...
Python
zaydzuhri_stack_edu_python
import euler set top = 1 set sums = list while length sums == 0 begin set pentagons = set generator expression call pentagon i for i in call xrange 1 top end
import euler top = 1 sums = [] while len(sums) == 0: pentagons = set((euler.pentagon(i) for i in xrange(1,top)))
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import sys import Preprocessing function Adam train label begin comment set the parameters set t = 0 set batch = 64 set epoch = 5000 set alpha = 0.01 set beta1 = 0.9 set beta2 = 0.99 set epsilon = 1e-08 set batch_size = 64 comment momentum set mom = call full shape at 1 0 comment ...
import numpy as np import pandas as pd import sys import Preprocessing def Adam(train, label): # set the parameters t = 0 batch = 64 epoch = 5000 alpha = 0.01 beta1 = 0.9 beta2 = 0.99 epsilon = 1e-8 batch_size = 64 mom = np.full(train.shape[1], 0) # momentum vel = np.full(train.shape[1], 0) # velo...
Python
zaydzuhri_stack_edu_python
string method: swap, put a[i] in position a[i]-1 class Solution extends object begin function firstMissingPositive self nums begin string :type nums: List[int] :rtype: int if length nums == 0 begin return 1 end for i in range length nums begin while nums at i != i + 1 begin if nums at i >= length nums or nums at i <= 0...
''' method: swap, put a[i] in position a[i]-1 ''' class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 0: return 1 for i in range(len(nums)): while nums[i] != i+1: ...
Python
zaydzuhri_stack_edu_python
function is_python_stem string begin return string in list string all string any string argparser string arg string bool string classmethod string cls string cmp string dict string dir string getattr string iter string len string metavar string narg string none string read string self string str string super end functi...
def is_python_stem(string): return string in [ 'all', 'any', 'argparser', 'arg', 'bool', 'classmethod', 'cls', 'cmp', 'dict', 'dir', 'getattr', 'iter', 'len', 'metavar', 'narg', 'none', ...
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn import torchvision.models as models class EncoderCNN extends Module begin function __init__ self embed_size begin call __init__ set resnet = call resnet50 pretrained=true for param in parameters resnet begin call requires_grad_ false end set modules = list call children at slice : - ...
import torch import torch.nn as nn import torchvision.models as models class EncoderCNN(nn.Module): def __init__(self, embed_size): super(EncoderCNN, self).__init__() resnet = models.resnet50(pretrained=True) for param in resnet.parameters(): param.requires_grad_(False) ...
Python
zaydzuhri_stack_edu_python
function reevaluate self choices task begin comment number_finished = len(self.finished_tasks) set overlap = call calculate_overlap_mfa if choices_given is none begin return choices end set tmp = dict if task not in choices_given begin return choices end if not choices_given at task begin return choices end set temp =...
def reevaluate(self, choices, task): # number_finished = len(self.finished_tasks) overlap = self.calculate_overlap_mfa() if self.choices_given is None: return choices tmp = {} if task not in self.choices_given: return choices if not self.choices_gi...
Python
nomic_cornstack_python_v1
function is_deletable self request begin return dict string is_deletable call is_deletable request end function
def is_deletable(self, request): return { "is_deletable": self.is_deletable(request) }
Python
nomic_cornstack_python_v1
function mutate self begin set input_addresses at call randrange length input_addresses = random integer 0 index - 1 end function
def mutate(self): self.input_addresses[randrange(len(self.input_addresses))] = randint( 0, self.index - 1)
Python
nomic_cornstack_python_v1
function test_delete_user self begin set rv = post string /users/ data=dict string name string John Smith assert equal status_code 201 set res = delete string /users/1 assert equal status_code 200 comment Test to see if it exists, should return a 404 set result = get call client string /users/1 assert equal status_code...
def test_delete_user(self): rv = self.client().post( '/users/', data={"name": "John Smith"}) self.assertEqual(rv.status_code, 201) res = self.client().delete('/users/1') self.assertEqual(res.status_code, 200) # Test to see if it exists, should return a 404...
Python
nomic_cornstack_python_v1
function inventory self inventory begin set _inventory = inventory end function
def inventory(self, inventory): self._inventory = inventory
Python
nomic_cornstack_python_v1