code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
from glob import glob from subprocess import Popen , PIPE , STDOUT function check_har_objects begin string Check if all objects in the original wpr file are in the pc wpr file set data_path = string ../data/wpr_source/* set data_files = list comprehension f for f in glob data_path if string .json not in f set sorted_fi...
from glob import glob from subprocess import Popen, PIPE, STDOUT def check_har_objects(): """Check if all objects in the original wpr file are in the pc wpr file""" data_path = '../data/wpr_source/*' data_files = [f for f in glob(data_path) if '.json' not in f] sorted_files = sorted(data_files)
Python
zaydzuhri_stack_edu_python
function client_receives begin set test_str = string t35t1nG cl13nT r3c31\/1NG set server = call start_server set client = call start_client call write_to client test_str set segments = call read_segments_from server if not segments begin return false end comment The first segment should be one received from the client...
def client_receives(): test_str = "t35t1nG cl13nT r3c31\/1NG\n" server = start_server() client = start_client() write_to(client, test_str) segments = read_segments_from(server) if not segments: return False # The first segment should be one received from the client, and should have # the correct l...
Python
nomic_cornstack_python_v1
function __init__ self database i_face gui test=false begin set i_face = i_face set po_db = database set connection = call connect db_name set layer = none set test = test if not test begin set c_box = cboxTimelineSelect end end function
def __init__(self, database, i_face, gui, test=False): self.i_face = i_face self.po_db = database self.connection = db.connect(database.db_name) self.layer = None self.test = test if not self.test: self.c_box = gui.cboxTimelineSelect
Python
nomic_cornstack_python_v1
comment encoding=utf8 import sys call reload sys call setdefaultencoding string utf8 import csv from collections import Counter import json import numpy as np import igraph import dateparser import datetime import filters function parse_csv filename begin set first = true set keys = list set dataset = list with open ...
# encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8') import csv from collections import Counter import json import numpy as np import igraph import dateparser import datetime import filters def parse_csv(filename): first = True keys = [] dataset = [] with open(filename, 'rb') as f: ...
Python
zaydzuhri_stack_edu_python
string written for python 2.7 -> converted to 3.6 Created on Feb 12, 2018 - revised May 22 @author: Kyle Objective: -create a sending socket / client -start independently the tcpSocketIn_py2_ex python program, -this will listen on the same socket that is sending -it will print whenever a full message is made -then cont...
''' written for python 2.7 -> converted to 3.6 Created on Feb 12, 2018 - revised May 22 @author: Kyle Objective: -create a sending socket / client -start independently the tcpSocketIn_py2_ex python program, -this will listen on the same socket that is sending -it will print whenever a full message is made...
Python
zaydzuhri_stack_edu_python
import numpy as np import math function angle_between_radians v1 v2 begin set v1_u = call normalize_vec v1 set v2_u = call normalize_vec v2 return call arccos call clip dot v1_u v2_u - 1.0 1.0 end function function angle_between_degrees v1 v2 begin return call degrees call angle_between_radians v1 v2 end function funct...
import numpy as np import math def angle_between_radians(v1, v2): v1_u = normalize_vec(v1) v2_u = normalize_vec(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) def angle_between_degrees(v1, v2): return math.degrees(angle_between_radians(v1, v2)) def euclidean_distance(vec1, vec2): ...
Python
zaydzuhri_stack_edu_python
function write_segments input_image pixel_classes output_dir=string /tmp height=256 width=256 begin set class_colours = array list list 255 255 255 list 152 78 163 list 55 126 184 list 255 255 51 list 77 175 74 list 228 26 28 list 166 86 40 comment white: background/unlabeled comment purple: residential comment blue: c...
def write_segments(input_image, pixel_classes, output_dir="/tmp", height=256, width=256): class_colours = np.array([ [255,255,255], # white: background/unlabeled [152,78,163], # purple: residential [55,126,184], # blue: commercial [255,255,51], # yellow: industrial [77,175...
Python
nomic_cornstack_python_v1
function get self fontStyle=none mode=none begin set key = call key fontStyle if key in fonts begin return get fonts key end return call create fontStyle mode end function
def get( self, fontStyle= None, mode=None ): key = self.key (fontStyle) if key in self.fonts: return self.fonts.get( key ) return self.create( fontStyle, mode )
Python
nomic_cornstack_python_v1
import os import collections class Solution begin function __init__ self begin set count = 0 set group = set set group_members = 0 end function function part_one self begin set tuple count group = tuple 0 set set script_dir = directory name path __file__ with open join path script_dir string input.txt string r as f beg...
import os import collections class Solution(): def __init__(self): self.count = 0 self.group = set() self.group_members = 0 def part_one(self): self.count, self.group = 0, set() script_dir = os.path.dirname(__file__) with open(os.path.join(script_dir, "input.txt...
Python
zaydzuhri_stack_edu_python
while ans == string y begin set ch = input string press 1 add name 2 shlow 3 Update 4 Exit if ch == string 1 begin set name = input string student name for i in range 3 begin set a = input string inte subject name set b = input string enter marks set subject at a = b set dic at name = subject end end else if ch == stri...
while ans=='y': ch=input('press\n 1 add name \n 2 shlow \n 3 Update \n 4 Exit ') if ch=='1': name=input('student name') for i in range(3): a=input('inte subject name') b=input('enter marks') subject[a]=b dic[name]=subject elif ch=='2...
Python
zaydzuhri_stack_edu_python
function test_cat_real self alpha phi begin set prog = call Program 1 with context as q begin call Catstate alpha phi representation=string real ampl_cutoff=1e-06 D=1 ? q at 0 end set backend = call BosonicBackend call run_prog prog set state = call state set num_weights = num_weights assert call allclose sum call weig...
def test_cat_real(self, alpha, phi): prog = sf.Program(1) with prog.context as q: sf.ops.Catstate(alpha, phi, representation="real", ampl_cutoff=1e-6, D=1) | q[0] backend = bosonic.BosonicBackend() backend.run_prog(prog) state = backend.state() num_weights = ...
Python
nomic_cornstack_python_v1
function burndown request begin set context = dict comment Person.objects.all().exclude(is_superuser=True) set context at string persons = list filter last_name__gt=string comment Try retrieving values from the database ... try begin set year = get session string capacities_year year set person_id = get session string...
def burndown(request): context = {} context["persons"] = list(Person.objects.filter(last_name__gt=''))#Person.objects.all().exclude(is_superuser=True) try:#Try retrieving values from the database ... year = request.session.get('capacities_year', datetime.datetime.now().year) person_id = req...
Python
nomic_cornstack_python_v1
import math import copy import random from chromosome import Chromosome import csv from statistics import mean function write_csv filename population generation begin string Write generations results in a csv file Args: filename (string): name of the file to be created population (list): A list of individuals AKA popul...
import math import copy import random from chromosome import Chromosome import csv from statistics import mean def write_csv(filename, population, generation): """Write generations results in a csv file Args: filename (string): name of the file to be created population (list): A list of indivi...
Python
zaydzuhri_stack_edu_python
string Пример программы для работы с асинхронностью import asyncio async function print_counter x begin for number in range x begin print number await sleep 0.5 end end function async function start x begin set coroutines = list for number in range x begin append coroutines call create_task call print_counter x end aw...
""" Пример программы для работы с асинхронностью """ import asyncio async def print_counter(x): for number in range(x): print(number) await asyncio.sleep(.5) async def start(x): coroutines = [] for number in range(x): coroutines.append( asyncio.create_task(print_counter...
Python
zaydzuhri_stack_edu_python
if s0 == string Vacant begin exit end set l = 0 set r = N - 1 while r - l > 1 begin comment 中央値のクエリを送る set m = l + r // 2 print m flush=true set s = input if s == string Vacant begin exit end comment r-lが奇数であることと同義 if m % 2 == 1 begin comment 異性ならば if s != s0 begin comment 前半部分に空席はないから下限をあげる set l = m end else begin co...
if s0 == 'Vacant': exit() l = 0 r = N-1 while r - l > 1: m = (l+r) // 2 # 中央値のクエリを送る print(m, flush=True) s = input() if s == 'Vacant': exit() if m % 2 == 1: # r-lが奇数であることと同義 if s != s0: # 異性ならば l = m # 前半部分に空席はないから下限をあげる else: # 同性ならば r = m ...
Python
zaydzuhri_stack_edu_python
function minswaps arr n begin set ans = 0 set temp = copy arr sort temp for i in range n begin if arr at i != temp at i begin set ans = ans + 1 call swap arr i index arr temp at i end end return ans end function function swap arr i j begin set temp = arr at i set arr at i = arr at j set arr at j = temp end function fun...
def minswaps(arr,n): ans=0 temp=arr.copy() temp.sort() for i in range(n): if arr[i]!=temp[i]: ans=ans+1 swap(arr,i,index(arr,temp[i])) return ans def swap(arr,i,j): temp=arr[i] arr[i]=arr[j] arr[j]=temp def index(arr,ele): for i in range(...
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np function resize_image img size begin string Resize an image. Args: img: The image to be resized. size: The target size. Returns: The resized image. set r = size / shape at 1 set dim = tuple size integer shape at 0 * r return call resize img dim interpolation=INTER_AREA end function functio...
import cv2 import numpy as np def resize_image(img, size): """Resize an image. Args: img: The image to be resized. size: The target size. Returns: The resized image. """ r = size / img.shape[1] dim = (size, int(img.shape[0] * r)) return cv2.resize(img, dim, interpolation =...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import math from Crypto.Cipher import AES function hash_string message begin string Compute the hash of message. if message = B1;B2;B3;...Bn and Bi are blocks of 128 bits computers DEC(....DEC(DEC(B1, B2), B3)...), Bn) where DEC is AES decryption set block = message at slice : 16 : comme...
#!/usr/bin/env python3 import math from Crypto.Cipher import AES def hash_string(message): """ Compute the hash of message. if message = B1;B2;B3;...Bn and Bi are blocks of 128 bits computers DEC(....DEC(DEC(B1, B2), B3)...), Bn) where DEC is AES decryption """ block = message[:16] # pad ...
Python
zaydzuhri_stack_edu_python
function cast obj begin return call itkHistogramToIntensityImageFilterHDIF2_cast obj end function
def cast(obj: 'itkLightObject') -> "itkHistogramToIntensityImageFilterHDIF2 *": return _itkHistogramToIntensityImageFilterPython.itkHistogramToIntensityImageFilterHDIF2_cast(obj)
Python
nomic_cornstack_python_v1
from art import stages , logo from words import word_list from utils import chose_word , check_if_completed , is_guessed , update_board , check_guess function main begin print logo set lives = 6 set generate_hangman = call chose_word word_list set chosen_word = generate_hangman at 0 set board = generate_hangman at 1 pr...
from art import stages, logo from words import word_list from utils import chose_word, check_if_completed, is_guessed, update_board, check_guess def main(): print(logo) lives = 6 generate_hangman = chose_word(word_list) chosen_word = generate_hangman[0] board = generate_hangman[1] print(" ".joi...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Spyder Editor This is a temporary script file. 5 / 8 comment division print string Hello 5 string World print string Goodbye 0 string World print string Crown
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ 5/8 #division print("Hello",5, "World") print("Goodbye" ,0, "World") print ("Crown")
Python
zaydzuhri_stack_edu_python
from clustering.tokenizer.happyfuntokenizing import Tokenizer from unicodedata import normalize import re from clustering.data import excluded function tokenize_text text begin if text is none begin set text = string end comment TODO: quitar vocales repetidas de palabras set t = call Tokenizer set text = encode call n...
from clustering.tokenizer.happyfuntokenizing import Tokenizer from unicodedata import normalize import re from clustering.data import excluded def tokenize_text(text): if text is None: text = '' # TODO: quitar vocales repetidas de palabras t = Tokenizer() text = normalize('NFKD', text).encode(...
Python
zaydzuhri_stack_edu_python
comment Flask modules used from flask import Flask , jsonify , request , make_response comment Files from Controllers package from Controllers import prepareAssessment , showQuestion , answerQuestion , getAsstTimes , getAllQuestions comment Files from Entities package from Entities.Assessment import Assessment comment ...
from flask import Flask, jsonify, request, make_response #Flask modules used from Controllers import prepareAssessment, showQuestion, answerQuestion, getAsstTimes, getAllQuestions #Files from Controllers package from Entities.Assessment import Assessment #Files from Entities package from Utils import checkEmail, checkD...
Python
zaydzuhri_stack_edu_python
function submit_from_samples self samples length=20 begin set cdf = call from_samples samples length return call create_measurement id cdf end function
def submit_from_samples( self, samples: Union[np.ndarray, pd.Series], length: int = 20 ) -> requests.Response: cdf = ForetoldCdf.from_samples(samples, length) return self.foretold.create_measurement(self.id, cdf)
Python
nomic_cornstack_python_v1
function buildTiles self items attributes begin pass end function
def buildTiles(self, items, attributes): pass
Python
nomic_cornstack_python_v1
function solution dic1 begin set key_list = keys dic1 set val_list = values dic1 set sor_list = list for i in range length key_list begin set c = tuple key_list at i val_list at i append sor_list c end sorted sor_list key=lambda l -> l at 0 reverse=true end function
def solution(dic1): key_list = dic1.keys() val_list = dic1.values() sor_list = [] for i in range(len(key_list)): c = (key_list[i], val_list[i]) sor_list.append(c) sorted(sor_list,key=lambda l:l[0], reverse=True)
Python
zaydzuhri_stack_edu_python
function add_expression_diff_study session sample_name data_path table ref_a_path ref_b_path ui=none begin set rr = call RunRecord string add_expression_diff_study set sample = call _one filter by query session Sample name=sample_name if not sample begin rollback session call dieOnCritical string querying sample string...
def add_expression_diff_study(session, sample_name, data_path, table, ref_a_path, ref_b_path, ui=None): rr = RunRecord('add_expression_diff_study') sample = _one(session.query(Sample).filter_by(name=sample_name)) if not sample: session.rollback() rr.dieOnCritical('querying sample...
Python
nomic_cornstack_python_v1
comment @Date: 2017-01-17T21:57:19-06:00 comment @Last modified time: 2017-01-18T13:07:06-06:00 comment This program is a password validator.
# @Date: 2017-01-17T21:57:19-06:00 # @Last modified time: 2017-01-18T13:07:06-06:00 #This program is a password validator.
Python
zaydzuhri_stack_edu_python
function _flash_needed self **kwargs begin raise call NotImplementedError string flashing needed check not implemented! end function
def _flash_needed(self, **kwargs): raise NotImplementedError("flashing needed check not implemented!")
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- set st1 = input set st1Lista = list map float split st1 string set A = st1Lista at 0 set B = st1Lista at 1 set C = st1Lista at 2 set pi = 3.14159 set AreaCirculo = pi * C ^ 2 set AreaTriRet = A * C / 2 set AreaTrapezio = A + B * C / 2 set AreaQuad = B * B set AreaRet = A * B print string T...
# -*- coding: utf-8 -*- st1=input() st1Lista=list(map(float,st1.split(" "))) A=st1Lista[0] B=st1Lista[1] C=st1Lista[2] pi= 3.14159 AreaCirculo=pi*(C**2) AreaTriRet=(A*C)/2 AreaTrapezio=(((A+B)*C)/2) AreaQuad=B*B AreaRet=A*B print("""TRIANGULO: %.3f CIRCULO: %.3f TRAPEZIO: %.3f QUADRADO: %.3f RETANGULO: %.3f"""%(AreaT...
Python
zaydzuhri_stack_edu_python
function fit_fixed_points self begin function SetInstParms Inst begin set dataType = Inst at string Type at 0 set insVary = list set insNames = list set insVals = list for parm in Inst begin append insNames parm append insVals Inst at parm at 1 if parm in list string U string V string W string X string Y string Z st...
def fit_fixed_points(self): def SetInstParms(Inst): dataType = Inst['Type'][0] insVary = [] insNames = [] insVals = [] for parm in Inst: insNames.append(parm) insVals.append(Inst[parm][1]) if parm in ['U'...
Python
nomic_cornstack_python_v1
for tuple a b in ab begin if a >= f begin set ans = ans + 1 set f = b end end print ans + 1
for a,b in ab: if a >= f: ans += 1 f = b print(ans+1)
Python
zaydzuhri_stack_edu_python
function _init_object self cl d setProp=dict begin if d at string graph is none and d at string r is not none and d at string s is not none begin try begin set r = call _db_read cl query=dict string spx_r d at string r ; string spx_s d at string s kargs=d set d at string zooid = r at string zooid end except KeyError as...
def _init_object(self, cl, d, setProp={}): if d["graph"] is None and d["r"] is not None and d["s"] is not None: try: r = self._db_read(cl, query={"spx_r": d["r"], "spx_s": d["s"]}, kargs=d) d["zooid"] = r["zooid"] ...
Python
nomic_cornstack_python_v1
function plot_centroid self label=false **kwargs begin if label begin set text = string { i } end else begin set text = none end if string marker not in kwargs begin set kwargs at string marker = list string bx string bo set kwargs at string fillstyle = string none end for tuple i blob in enumerate self begin call plot...
def plot_centroid(self, label=False, **kwargs): if label: text = f"{i}" else: text = None if 'marker' not in kwargs: kwargs['marker'] = ['bx', 'bo'] kwargs['fillstyle'] = 'none' for i, blob in enumerate(self): plot_poin...
Python
nomic_cornstack_python_v1
string Draft bizlogic import os from django.conf import settings from app.usrlib import image_utils , common import shutil from app.models import Post , Tag , Year import datetime import re from app.bizlogic import image_bizlogic function register_all_archive_posts begin string Extract data from __drafts, archives fold...
"""Draft bizlogic """ import os from django.conf import settings from app.usrlib import image_utils, common import shutil from app.models import Post, Tag, Year import datetime import re from app.bizlogic import image_bizlogic def register_all_archive_posts() -> None: """Extract data from __drafts, archives fold...
Python
zaydzuhri_stack_edu_python
import unittest from main import linear_search class SearchTest extends TestCase begin function test_linear_search_ok self begin set num_list = list 1 2 3 4 5 6 set target = 3 set returns = call linear_search num_list target assert true returns at 0 assert equal returns at 1 2 end function function test_linear_search_t...
import unittest from main import linear_search class SearchTest(unittest.TestCase): def test_linear_search_ok(self): num_list = [1, 2, 3, 4, 5, 6] target = 3 returns = linear_search(num_list, target) self.assertTrue(returns[0]) self.assertEqual(returns...
Python
zaydzuhri_stack_edu_python
function test_errs self begin set b1 = call BaseModel with assert raises AttributeError begin __objects __File_path end with assert raises TypeError begin call new call new self b1 save b1 call reload b1 all b1 end end function
def test_errs(self): b1 = BaseModel() with self.assertRaises(AttributeError): FileStorage.__objects FileStorage.__File_path with self.assertRaises(TypeError): models.storage.new() models.storage.new(self, b1) models.save(b1) ...
Python
nomic_cornstack_python_v1
function get_full_url article_id begin set full_url = string http://maitron-en-ligne.univ-paris1.fr/spip.php?page=article_long&id_article= set full_url = full_url + article_id return full_url end function
def get_full_url(article_id): full_url = 'http://maitron-en-ligne.univ-paris1.fr/spip.php?page=article_long&id_article=' full_url = full_url + article_id return full_url
Python
nomic_cornstack_python_v1
comment https://www.acmicpc.net/problem/2504 comment 백준 2504번 괄호의 값(문자열) import sys set input = readline set s = right strip input set stack = list set result = 0 for i in s begin if i == string ) begin set last = 0 while length stack != 0 begin set top = pop stack if top == string ( begin if last == 0 begin append st...
#https://www.acmicpc.net/problem/2504 #백준 2504번 괄호의 값(문자열) import sys input = sys.stdin.readline s = input().rstrip() stack = [] result = 0 for i in s: if i == ')': last = 0 while len(stack) != 0: top = stack.pop() if top == '(': if last == 0: ...
Python
zaydzuhri_stack_edu_python
function hand self g player=none begin if not player begin set player = whoseTurn end end function
def hand(self, g, player=None): if not player: player = g.whoseTurn
Python
nomic_cornstack_python_v1
function filter_detect self x begin set tuple b a = c_detect return filtfilt b a x end function
def filter_detect(self, x): b, a = self.c_detect return filtfilt(b, a, x)
Python
nomic_cornstack_python_v1
import sys import time import numpy as np comment update_progress() : Displays or updates a console progress bar comment Accepts a float between 0 and 1. Any int will be converted to a float. comment A value under 0 represents a 'halt'. comment A value at 1 or bigger represents 100% function update_progress progress be...
import sys import time import numpy as np # update_progress() : Displays or updates a console progress bar ## Accepts a float between 0 and 1. Any int will be converted to a float. ## A value under 0 represents a 'halt'. ## A value at 1 or bigger represents 100% def update_progress(progress): barLength = 10 # Modif...
Python
zaydzuhri_stack_edu_python
function check a b begin if length a != length b begin return false end else if sorted list a == sorted list b begin return true end else begin return false end end function function main begin set list1 = list string a string b string c string d set list2 = list string d string b string a string c set str1 = string ab...
def check(a, b): if(len(a) != len(b)): return False elif(sorted(list(a)) == sorted(list(b))): return True else: return False def main(): list1 = ['a', 'b', 'c', 'd'] list2 = ['d', 'b', 'a', 'c'] str1 = 'abcd' str2 = 'cdba' print(check(str1, str2)) result = c...
Python
zaydzuhri_stack_edu_python
function get_queryset self begin set user = user if is_superuser begin return all end else begin return filter pk=pk end end function
def get_queryset(self): user = self.request.user if user.is_superuser: return CUser.objects.all() else: return CUser.objects.filter(pk=user.pk)
Python
nomic_cornstack_python_v1
from math import sqrt , ceil , floor set N = integer input set arr = list comprehension integer x for x in split input sort arr set local = floor 1 + square root 8 * N + 1 // 2 print local - 1
from math import sqrt,ceil,floor N=int(input()) arr = [int(x) for x in input().split()] arr.sort() local = floor(1+sqrt(8*N+1))//2 print(local-1)
Python
zaydzuhri_stack_edu_python
function generate_observation_pairs self eval_mode augment_frames=none augment_goals=none begin function _get_observation_pair observations start end episode_idx augment_frames begin set obs = observations at start set goal_obs = observations at end if augment_frames begin set tuple obs goal_obs = call random_crop_imag...
def generate_observation_pairs( self, eval_mode, augment_frames=None, augment_goals=None): def _get_observation_pair( observations, start, end, episode_idx, augment_frames): obs = observations[start] goal_obs = observations[end] if augment_frames: obs, goal_obs = image_utils....
Python
nomic_cornstack_python_v1
import argparse import json function main f begin comment with open('2fa-basic.json', 'r') as f: set data = loads read f for ins in data begin if ins at string type == string output begin print ins at string value end else begin input ins at string value end end end function if __name__ == string __main__ begin set par...
import argparse import json def main(f): # with open('2fa-basic.json', 'r') as f: data = json.loads(f.read()) for ins in data: if ins['type'] == 'output': print(ins['value']) else: input(ins["value"]) if __name__ == '__main__': parser = argparse.ArgumentParser...
Python
zaydzuhri_stack_edu_python
function is_prime num begin for i in range 2 integer num / 2 + 1 begin if num % i == 0 begin return false end end return true end function
def is_prime(num): for i in range(2, int(num / 2 + 1)): if num % i == 0: return False return True
Python
nomic_cornstack_python_v1
function hsv2rgb_360 hsv begin set tuple h s v = hsv set tuple r g b = call hsv_to_rgb h / 360.0 s v return tuple integer r * 255.0 integer g * 255.0 integer b * 255.0 end function
def hsv2rgb_360(hsv): h, s, v = hsv r, g, b = colorsys.hsv_to_rgb(h / 360.0, s, v) return (int(r * 255.0), int(g * 255.0), int(b * 255.0))
Python
nomic_cornstack_python_v1
async function _build_plashet_for_assembly self name el_version arches signing_advisory begin info string Building plashet %s for EL%s... name el_version set base_dir = working_dir / string plashets/el { el_version } / { assembly } set plashet_dir = base_dir / name if exists plashet_dir begin remove tree plashet_dir en...
async def _build_plashet_for_assembly(self, name: str, el_version: int, arches: List[str], signing_advisory: Optional[int]) -> Tuple[Path, str]: self.logger.info("Building plashet %s for EL%s...", name, el_version) base_dir = self.runtime.working_dir / f"plashets/el{el_version}/{self.assembly}" ...
Python
nomic_cornstack_python_v1
function clean_email self begin if string email in cleaned_data begin try begin set user = get objects email=cleaned_data at string email end except DoesNotExist begin return cleaned_data at string email end except MultipleObjectsReturned begin raise call ValidationError string There is already more than one account re...
def clean_email(self): if 'email' in self.cleaned_data: try: user = User.objects.get(email = self.cleaned_data['email']) except User.DoesNotExist: return self.cleaned_data['email'] except User.MultipleObjectsReturned: rai...
Python
nomic_cornstack_python_v1
from fundamentals.test_time import test_time class Solution begin function __init__ self begin pass end function string 我的方法 decorator test_time function checkInclusion self s1 s2 begin set window = dict set need = dict for item in s1 begin set need at item = get need item 0 + 1 if item not in window begin set window...
from fundamentals.test_time import test_time class Solution(): def __init__(self): pass '''我的方法''' @test_time def checkInclusion(self, s1, s2): window = {} need = {} for item in s1: need[item] = need.get(item, 0) + 1 if item not in window: wind...
Python
zaydzuhri_stack_edu_python
function write_output_file self xml_text xml_file begin set xml_fo = open xml_file string w write xml_fo xml_text + string </xml> close xml_fo return end function
def write_output_file(self, xml_text, xml_file): xml_fo = open(xml_file, 'w') xml_fo.write(xml_text+'</xml>') xml_fo.close() return
Python
nomic_cornstack_python_v1
function RelayDirectly self inventory begin string Relay the inventory to the remote client. Args: inventory (neo.Network.Inventory): Returns: bool: True if relayed successfully. False otherwise. set relayed = false set RelayCache at call ToBytes = inventory for peer in Peers begin set relayed = relayed ? call Relay in...
def RelayDirectly(self, inventory): """ Relay the inventory to the remote client. Args: inventory (neo.Network.Inventory): Returns: bool: True if relayed successfully. False otherwise. """ relayed = False self.RelayCache[inventory.Hash.T...
Python
jtatman_500k
function user_logout request begin try begin info string %s trying to log out from employee dashboard session at string username del session at string username call logout request info string logged out...... end except KeyError begin error string Error occur : employee can't logged out end return call redirect string ...
def user_logout(request): try: LOGGER.info("%s trying to log out from employee dashboard ", request.session['username']) del request.session['username'] logout(request) LOGGER.info("logged out......") except KeyError: LOGGER.error("Error occur : emplo...
Python
nomic_cornstack_python_v1
import pandas as pd from datetime import datetime from predictor import Cleaner function test_year_month begin comment lets predict June given a year's data set months_2018 = list comprehension call datetime 2018 x 1 for x in range 1 13 set months_2019 = list comprehension call datetime 2019 x 1 for x in range 1 13 set...
import pandas as pd from datetime import datetime from predictor import Cleaner def test_year_month(): # lets predict June given a year's data months_2018 = [datetime(2018, x, 1) for x in range(1, 13)] months_2019 = [datetime(2019, x, 1) for x in range(1, 13)] g1, g2, g3 = [1] * 5, [2] * 12, [3] * ...
Python
zaydzuhri_stack_edu_python
from enum import Enum class APIResponseMessage extends str Enum begin string User-Friendly API response messages enumerable. These messages are consumed by front-end, for communicating status of the request made by the API user. comment Success messages set ITEM_DELETED_SUCCESSFULLY = string Elemento eliminado correcta...
from enum import Enum class APIResponseMessage(str, Enum): """User-Friendly API response messages enumerable. These messages are consumed by front-end, for communicating status of the request made by the API user. """ # Success messages ITEM_DELETED_SUCCESSFULLY = "Elemento eliminado corr...
Python
zaydzuhri_stack_edu_python
function create_meeting self email_address start_time end_time subject body required_attendees optional_attendees location begin set ms_graph_calender_event_url = format string {0}/users/{1}/calendar/events ms_graph_url email_address comment Get the time zone of the organizer. set ms_graph_timezone_url = format string ...
def create_meeting(self, email_address, start_time, end_time, subject, body, required_attendees, optional_attendees, location): ms_graph_calender_event_url = u'{0}/users/{1}/calendar/events'.format(self.ms_graph_url, email_address) # Get the time zone of the organizer. ms...
Python
nomic_cornstack_python_v1
function getCGroupInfoURL cgroup begin set cgroupid = if expression is instance cgroup basestring then cgroup else cgroup at string cgroup_id return string powerscript/cs.vp.classification.oplan/cgroup?cgroup_id=%s % quote encode cgroupid string utf8 end function
def getCGroupInfoURL(cgroup): cgroupid = cgroup if isinstance(cgroup, basestring) else cgroup["cgroup_id"] return "powerscript/cs.vp.classification.oplan/cgroup?cgroup_id=%s" % ( urllib.quote(cgroupid.encode("utf8")))
Python
nomic_cornstack_python_v1
comment coding=utf8 comment Esqueleto de código Python para uso no Dojo-SE comment Escrito por Wagner Luís de Araújo Menezes Macêdo <wagnerluis1982@gmail.com>. comment Para executar os testes, chame o interpretador Python com esse arquivo como comment parâmetro. Ex: python <caminho_do_arquivo> import unittest function ...
# coding=utf8 # Esqueleto de código Python para uso no Dojo-SE # Escrito por Wagner Luís de Araújo Menezes Macêdo <wagnerluis1982@gmail.com>. # # Para executar os testes, chame o interpretador Python com esse arquivo como # parâmetro. Ex: python <caminho_do_arquivo> import unittest def problema_para_resolver(): ...
Python
zaydzuhri_stack_edu_python
comment Exercise 16 LPTHW: Reading and Writing Files comment Learn to read write files. remember think of a file as a linear DVD comment Make a text editor from sys import argv set tuple script filename = argv print string We're going to erase { filename } . print string If you do not want that, hit CTRL-C (^C). print ...
#Exercise 16 LPTHW: Reading and Writing Files #Learn to read write files. remember think of a file as a linear DVD #Make a text editor from sys import argv script, filename = argv print(f"We're going to erase {filename}.") print("If you do not want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN.")...
Python
zaydzuhri_stack_edu_python
comment collections : counter, namedTuple,orderedDict, defaultdict comment deque string from collections import Counter a = 'aaaabbbccccc' my_counter = Counter(a) print(my_counter) print(my_counter.most_common(1)[0]) print (list(my_counter.elements())) from collections import namedtuple Point = namedtuple("Point", 'nam...
#collections : counter, namedTuple,orderedDict, defaultdict #deque ''' from collections import Counter a = 'aaaabbbccccc' my_counter = Counter(a) print(my_counter) print(my_counter.most_common(1)[0]) print (list(my_counter.elements())) from collections import namedtuple Point = namedtuple("Point", 'name ,surname') ...
Python
zaydzuhri_stack_edu_python
import sys function MI begin return map int split right strip read line stdin end function set tuple A B = call MI if A == B begin print string Draw exit end if A == 1 begin set A = 14 end if B == 1 begin set B = 14 end print if expression A > B then string Alice else string Bob
import sys def MI(): return map(int,sys.stdin.readline().rstrip().split()) A,B = MI() if A == B: print('Draw') exit() if A == 1: A = 14 if B == 1: B = 14 print('Alice' if A > B else 'Bob')
Python
zaydzuhri_stack_edu_python
from consts import * class Configurator begin decorator staticmethod comment Returns the value of the option I find using the path from a passed config comment Can also return a value (that you can pass to the fucntion) if it can't find the path function GetOption config path defaultReturnValue=none begin try begin set...
from consts import * class Configurator(): # Returns the value of the option I find using the path from a passed config # Can also return a value (that you can pass to the fucntion) if it can't find the path @staticmethod def GetOption(config, path, defaultReturnValue=None): try: ...
Python
zaydzuhri_stack_edu_python
from functools import reduce set file = read open string input_d5.txt comment Challenge 1 function sameLetter x y begin if 1 > length x begin return false end else if lower x at - 1 == lower y and x at - 1 != y begin return true end end function function reduction x y begin if call sameLetter x y begin return x at slic...
from functools import reduce file = open("input_d5.txt").read() # Challenge 1 def sameLetter(x, y): if 1 > len(x): return False elif x[-1].lower() == y.lower() and x[-1] != y: return True def reduction(x, y): if sameLetter(x, y): return x[:-1] else: return x + y prin...
Python
zaydzuhri_stack_edu_python
comment smoothing the weather set pin = string 7 32.6 31.2 35.2 37.4 44.9 42.1 44.1 set plist = list comprehension decimal x for x in split pin set pcase = pop plist 0
#smoothing the weather pin = """ 7 32.6 31.2 35.2 37.4 44.9 42.1 44.1 """ plist = [float(x) for x in pin.split()] pcase = plist.pop(0)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Converts tabs into spaces import argparse import os.path import sys set __version__ = string 0.0.1 function parse_arguments begin string Parse commandline arguments set parser = call ArgumentParser description=string Replace tabs with spaces call add_ar...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Converts tabs into spaces ''' import argparse import os.path import sys __version__ = '0.0.1' def parse_arguments(): ''' Parse commandline arguments ''' parser = argparse.ArgumentParser(description='Replace tabs with spaces') parser.add_argument...
Python
zaydzuhri_stack_edu_python
function get self row begin return item self self index _data_model row 0 end function
def get(self, row): return self.Item(self, self._data_model.index(row, 0))
Python
nomic_cornstack_python_v1
import logging import traceback call basicConfig filename=string app.log filemode=string a format=string %(name)s - %(levelname)s - %(asctime)s - %(message)s level=INFO set log_app = call getLogger string LOGG function log func begin function decor *args begin set main_func = call extract_stack none 2 at 0 at 2 set nam...
import logging import traceback logging.basicConfig( filename='app.log', filemode='a', format='%(name)s - %(levelname)s - %(asctime)s - %(message)s', level=logging.INFO ) log_app =logging.getLogger('LOGG') def log(func): def decor(*args): main_func = traceback.extract_stack(None, 2)[0][...
Python
zaydzuhri_stack_edu_python
function provider_available request provider_name begin set site = call get_current_site request set available = exists filter name=provider_name site=site return available end function
def provider_available(request, provider_name): site = get_current_site(request) available = Provider.objects.filter( name=provider_name, site=site).exists() return available
Python
nomic_cornstack_python_v1
function make_path *parts begin if ends with parts at 0 string : and call windows_platform begin comment On NT based systems a separator still needs to follow drive letters ex C: comment os.path.join does not seem to understand this, so we have to force it to happen by adding os.sep comment to the list of parts to pass...
def make_path(*parts): if parts[0].endswith(':') and windows_platform(): # On NT based systems a separator still needs to follow drive letters ex C: # os.path.join does not seem to understand this, so we have to force it to happen by adding os.sep # to the list of parts to pass to os.path.jo...
Python
nomic_cornstack_python_v1
function create_clusters attrs=none count=2 begin set clusters = list for n in range 0 count begin append clusters call create_one_cluster attrs end return clusters end function
def create_clusters(attrs=None, count=2): clusters = [] for n in range(0, count): clusters.append(create_one_cluster(attrs)) return clusters
Python
nomic_cornstack_python_v1
function shuffle_arrays *arrays seed=none begin if not all generator expression shape at 0 == shape at 0 for arr in arrays begin warn string Arrays provided to `shuffle_arrays` function are not of the same shape end if seed is not none begin seed seed end set state = call get_state for array in arrays begin call set_st...
def shuffle_arrays(*arrays, seed=None): if not all(arr.shape[0] == arrays[0].shape[0] for arr in arrays): warn("Arrays provided to `shuffle_arrays` function are not of the same shape") if seed is not None: np.random.seed(seed) state = np.random.get_state() for array in arrays: ...
Python
nomic_cornstack_python_v1
function render_inline parser token begin set nodelist = parse parser tuple string end_render_inline call delete_first_token return call RenderInlineNode nodelist end function
def render_inline(parser, token): nodelist = parser.parse(('end_render_inline',)) parser.delete_first_token() return RenderInlineNode(nodelist)
Python
nomic_cornstack_python_v1
function close self begin set closed = true end function
def close(self): self.closed = True
Python
nomic_cornstack_python_v1
function _addWakeEmitter begin debug none method=string _addWakeEmitter message=string Adding wake emmiter now.. verbose=false comment get camera from current view set currentPanel = call getPanel withFocus=true or string modelPanel4 debug none method=string _addWakeEmitter message=string currentPanel: %s % currentPane...
def _addWakeEmitter(): debug(None, method = '_addWakeEmitter', message = 'Adding wake emmiter now..', verbose = False) #get camera from current view currentPanel = cmds.getPanel(withFocus= True) or 'modelPanel4' debug(None, method = '_addWakeEmitter', message = 'currentPanel: %s' % currentPanel, verbose...
Python
nomic_cornstack_python_v1
function recover_from_szut_failure begin print string Drat, 'szut' broke, but I'm OK now. end function
def recover_from_szut_failure(): print("Drat, 'szut' broke, but I'm OK now.")
Python
nomic_cornstack_python_v1
string Utilities for interacting with DAS-Menagerie. from typing import Callable import urllib.request import tempfile import numpy as np comment from github import Github from typing import Optional function _npz_loader fname begin set out = dict with load np fname as f begin for key in keys f begin try begin set out...
"""Utilities for interacting with DAS-Menagerie.""" from typing import Callable import urllib.request import tempfile import numpy as np # from github import Github from typing import Optional def _npz_loader(fname: str): out = {} with np.load(fname) as f: for key in f.keys(): try: ...
Python
zaydzuhri_stack_edu_python
import tweepy set consumer_key = string set consumer_secret = string set access_token = string set access_token_secret = string set auth = call OAuthHandler consumer_key consumer_secret call set_access_token access_token access_token_secret set api = call API auth set search = search string for tweets in search beg...
import tweepy consumer_key = "" consumer_secret = "" access_token = "" access_token_secret = "" auth = tweepy.OAuthHandler(consumer_key,consumer_secret) auth.set_access_token(access_token,access_token_secret) api = tweepy.API(auth) search = api.search('') for tweets in search: print(tweets.text)
Python
zaydzuhri_stack_edu_python
import math from torchvision import transforms from datasets.utils import create_transforms from datasets.nyuv2 import NYUv2 import torch import time import numpy as np from model import RealTimeDepth from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter comment default `log_dir` is ...
import math from torchvision import transforms from datasets.utils import create_transforms from datasets.nyuv2 import NYUv2 import torch import time import numpy as np from model import RealTimeDepth from torch.utils.data import DataLoader from torch.utils.tensorboard import SummaryWriter # default `log_dir` is "runs...
Python
zaydzuhri_stack_edu_python
function neville x y _x_ begin set n = length y set Q = list comprehension list comprehension 0 for i in range n for j in range n for tuple i el in enumerate y begin set Q at i at 0 = el end for i in range n begin for j in range i begin set j = j + 1 set Q at i at j = _x_ - x at i - j * Q at i at j - 1 - _x_ - x at i *...
def neville(x, y, _x_): n = len(y) Q = [[0 for i in range(n)] for j in range(n)] for i, el in enumerate(y): Q[i][0] = el for i in range(n): for j in range(i): j += 1 Q[i][j] = ((_x_ - x[i - j]) * Q[i][j - 1] - (_x_ - x[i]) * Q[i - 1][j - 1]) / (x[i] - x[i - j]) ...
Python
zaydzuhri_stack_edu_python
function get_mod cls begin string Returns the string identifying the module that cls is defined in. if is instance cls tuple type FunctionType begin set ret = __module__ end else begin set ret = __module__ end return ret end function
def get_mod(cls): '''Returns the string identifying the module that cls is defined in. ''' if isinstance(cls, (type, types.FunctionType)): ret = cls.__module__ else: ret = cls.__class__.__module__ return ret
Python
jtatman_500k
comment Han Yu comment ID 1700012921 import requests from bs4 import BeautifulSoup import re import time set OUTPUT = open string StatData.txt string w encoding=string utf-8 errors=string ignore set DOOR_LINK = string http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2019/index.html set BASE_URL = DOOR_LINK at slice 0 :...
# Han Yu # ID 1700012921 import requests from bs4 import BeautifulSoup import re import time OUTPUT=open("StatData.txt","w",encoding="utf-8",errors="ignore") DOOR_LINK="http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2019/index.html" BASE_URL=DOOR_LINK[0:DOOR_LINK.rfind("/")] ITEM=["provincetr","citytr","countyt...
Python
zaydzuhri_stack_edu_python
function randomString stringLength=10 begin set letters = ascii_lowercase set res_df = call DataFrame columns=list string Password comment 685956 for x in range 7287 begin set txtpass = string for i in range stringLength begin set txtpass = txtpass + random choice letters end set newrow = dict string Password txtpass ...
def randomString(stringLength=10): letters =string.ascii_lowercase res_df=pd.DataFrame(columns=['Password']) #685956 for x in range(7287): txtpass="" for i in range(stringLength): txtpass=txtpass + (random.choice(letters)) newrow={'Password':txtpass} ...
Python
nomic_cornstack_python_v1
function dm st begin string dm(string) -> (string, string or None) returns the double metaphone codes for given string - always a tuple there are no checks done on the input string, but it should be a single word or name. set st = decode st comment st is short for string. I usually prefer descriptive over short, commen...
def dm(st) : """dm(string) -> (string, string or None) returns the double metaphone codes for given string - always a tuple there are no checks done on the input string, but it should be a single word or name.""" st = decode(st) # st is short for string. I usually prefer descriptive over s...
Python
jtatman_500k
function getQuality_control_results sample final_results_dict ectyperdb_dict begin if string O in final_results_dict at sample begin set Otype = final_results_dict at sample at string O at string serogroup set Otypealleles = keys final_results_dict at sample at string O at string alleles end else begin set Otype = stri...
def getQuality_control_results(sample, final_results_dict, ectyperdb_dict): if 'O' in final_results_dict[sample]: Otype = final_results_dict[sample]['O']['serogroup'] Otypealleles = final_results_dict[sample]['O']['alleles'].keys() else: Otype = "-" Otypealleles=[] if 'H' i...
Python
nomic_cornstack_python_v1
import boto import urllib2 from StringIO import StringIO set req = call Request string http://ec2-52-30-7-5.eu-west-1.compute.amazonaws.com:81/key set response = url open req set the_page = read response set tuple key1 key2 = split the_page string : print string Boto version: Version print string user key: key1 print s...
import boto import urllib2 from StringIO import StringIO req = urllib2.Request('http://ec2-52-30-7-5.eu-west-1.compute.amazonaws.com:81/key') response = urllib2.urlopen(req) the_page = response.read() key1, key2 = the_page.split(':') print ("Boto version: ", boto.Version) print ("user key: ", key1) print ("pass key:...
Python
zaydzuhri_stack_edu_python
function is_empty self begin return length _data == 0 end function
def is_empty(self): return len(self._data) == 0
Python
nomic_cornstack_python_v1
function get_field_absolute_offset self field_name begin return __file_offset__ + __field_offsets__ at field_name end function
def get_field_absolute_offset(self, field_name): return self.__file_offset__ + self.__field_offsets__[field_name]
Python
nomic_cornstack_python_v1
function validatePointings self begin if deg > 8.0 begin raise call IOError string Angular separation between the two target + string beams is more than 8 degrees. end end function
def validatePointings(self): if self.coordPoint1.separation(self.coordPoint2).deg > 8.: raise IOError('Angular separation between the two target '+\ 'beams is more than 8 degrees.')
Python
nomic_cornstack_python_v1
function __optimizers self Gen_loss D_A_loss D_B_loss begin function make_optimizer loss variables name=string Adam begin string Adam optimizer with learning rate 0.0002 for the first 100k steps (~100 epochs) and a linearly decaying rate that goes to zero over the next 100k steps set global_step = call Variable 0 train...
def __optimizers(self, Gen_loss, D_A_loss, D_B_loss): def make_optimizer(loss, variables, name='Adam'): """ Adam optimizer with learning rate 0.0002 for the first 100k steps (~100 epochs) and a linearly decaying rate that goes to zero over the next 100k steps """ ...
Python
nomic_cornstack_python_v1
function arch_lines func start end offset=50 begin set d = 1 set delta = 0.3 set coords = list set x = start + 1 comment we start from the range of X values on the X axis, comment we create a new list X of x coords along the curve comment we exploit the first order derivative to place values in X comment so that f(X) ...
def arch_lines(func, start, end, offset=50): d = 1 delta = 0.3 coords = [] x = start + 1 # we start from the range of X values on the X axis, # we create a new list X of x coords along the curve # we exploit the first order derivative to place values in X # so that f(X) is equally dista...
Python
nomic_cornstack_python_v1
import tensorflow as tf from tensorflow import keras import numpy as np from keras.models import Sequential from keras.layers import Activation , Dense , Flatten function get_dataset training=true begin set mnist = mnist set tuple tuple train_images train_labels tuple test_images test_labels = call load_data if trainin...
import tensorflow as tf from tensorflow import keras import numpy as np from keras.models import Sequential from keras.layers import Activation, Dense, Flatten def get_dataset(training=True): mnist = tf.keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() ...
Python
zaydzuhri_stack_edu_python
comment 7kyu - Apparently-Modifying Strings string For every string, after every occurrence of 'and' and 'but', insert the substring 'apparently' directly after the occurrence. If input does not contain 'and' or 'but', return the original string. If a blank string, return ''. If substring 'apparently' is already direct...
# 7kyu - Apparently-Modifying Strings """ For every string, after every occurrence of 'and' and 'but', insert the substring 'apparently' directly after the occurrence. If input does not contain 'and' or 'but', return the original string. If a blank string, return ''. If substring 'apparently' is already directly aft...
Python
zaydzuhri_stack_edu_python
comment Lazaro Herrera comment modify the fraction shown below comment NOTE, you should indent by using 4 spaces for each indent, and not tab comment and the gcd is different below than in the book you will need to call it as in the __add__ method comment we have made the gcd method part of the class so it is now calle...
#Lazaro Herrera # modify the fraction shown below # NOTE, you should indent by using 4 spaces for each indent, and not tab # and the gcd is different below than in the book you will need to call it as in the __add__ method # we have made the gcd method part of the class so it is now called as self.gcd(n1,n...
Python
zaydzuhri_stack_edu_python
import discord as dc from discord.ext import commands from random import choice from discord.ext.commands import bot class Fun extends Cog begin function __init__ self bot begin set bot = bot end function decorator call command name=string mulaney aliases=list string Mulaney help=string Responds with a random John Mula...
import discord as dc from discord.ext import commands from random import choice from discord.ext.commands import bot class Fun(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name='mulaney', aliases=['Mulaney'], help='Responds with a random John Mulaney quote!') async...
Python
zaydzuhri_stack_edu_python
import sys , time set allcorrect = false set runningcode = input string enter x to close files and code if runningcode != string x begin if allcorrect == false begin set file = open string en(rypt storage.txt string r+ set filecontent = read line file set filecontent = string filecontent print filecontent if fileconten...
import sys,time allcorrect=False runningcode=input('enter x to close files and code') if runningcode!='x': if allcorrect==False: file=open('en(rypt storage.txt','r+') filecontent=file.readline() filecontent=str(filecontent) print(filecontent) if filecontent=='blank':...
Python
zaydzuhri_stack_edu_python
function main number begin for _ in range 5 begin append number integer input end sort number for i in range 5 begin print number at i end end function
def main(number): for _ in range(5): number.append(int(input())) number.sort() for i in range(5): print(number[i])
Python
nomic_cornstack_python_v1
from matching_function import * from processing_distribution_function import * import itertools from sklearn.metrics import confusion_matrix , classification_report , precision_recall_fscore_support as score , plot_roc_curve from evaluation import plot_accuracy from IPython.core.display import HTML function match_mesh ...
from matching_function import * from processing_distribution_function import * import itertools from sklearn.metrics import confusion_matrix, classification_report, precision_recall_fscore_support as score, \ plot_roc_curve from evaluation import plot_accuracy from IPython.core.display import HTML def match_mesh(...
Python
zaydzuhri_stack_edu_python
import time import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data comment 加载mnist_inference.py和mnist_train.py中定义的常量和函数。 import mnist_inference import mnist_train comment 每10秒加载一次最新的模型,并在测试数据上测试最新模型的正确率。 set EVAL_INTERVAL_SECS = 10 function evaluate mnist begin with call as_default as g begi...
import time import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 加载mnist_inference.py和mnist_train.py中定义的常量和函数。 import mnist_inference import mnist_train # 每10秒加载一次最新的模型,并在测试数据上测试最新模型的正确率。 EVAL_INTERVAL_SECS = 10 def evaluate(mnist): with tf.Graph().as_default() as g: # 定义输入输...
Python
zaydzuhri_stack_edu_python