code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function test_was_published_recently_with_old_question self begin set time = now - time delta days=1 seconds=1 set old_question = call Question pub_date=time call assertIs call was_published_recently false end function
def test_was_published_recently_with_old_question(self): time = timezone.now() - datetime.timedelta(days=1, seconds=1) old_question = Question(pub_date=time) self.assertIs(old_question.was_published_recently(), False)
Python
nomic_cornstack_python_v1
comment 实例15 comment 分数归档 利用条件运算符:学习成绩>=90的同学用a来表示 60~89用b表示,60以下c表示 set points = integer input string 输入考试分数: if points >= 90 begin set grade = string A end else if points < 60 begin set grade = string C end else begin set grade = string B end print grade
#实例15 #分数归档 利用条件运算符:学习成绩>=90的同学用a来表示 60~89用b表示,60以下c表示 points=int(input('输入考试分数:')) if points>=90: grade='A' elif points<60: grade='C' else: grade='B' print(grade)
Python
zaydzuhri_stack_edu_python
string Set up the queue and the graph class Queue begin function __init__ self begin set queue = list end function function enqueue self value begin append queue value end function function dequeue self begin if size self > 0 begin return pop queue 0 end else begin return none end end function function size self begin...
''' Set up the queue and the graph ''' class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): ...
Python
zaydzuhri_stack_edu_python
function detectWebOSTablet self begin return deviceWebOShp in __userAgent and deviceTablet in __userAgent end function
def detectWebOSTablet(self): return UAgentInfo.deviceWebOShp in self.__userAgent \ and UAgentInfo.deviceTablet in self.__userAgent
Python
nomic_cornstack_python_v1
import sys import json from datetime import datetime function welcome_screen begin set message = list string Hello and Welcome! string Choose an option. string 1. meal - to write what are you eating now. string 2. list <dd.mm.yyyy> - lists all the meals that you ate that day, return join string message end function fu...
import sys import json from datetime import datetime def welcome_screen(): message = ["Hello and Welcome!", "Choose an option.", "1. meal - to write what are you eating now.", "2. list <dd.mm.yyyy> - lists all the meals that you ate that day,...
Python
zaydzuhri_stack_edu_python
function merge left right lst begin set i = 0 set j = 0 set k = 0 while i < length left and j < length right begin if left at i at 0 <= right at j at 0 begin set lst at k = left at i set i = i + 1 end else begin set lst at k = right at j set j = j + 1 end set k = k + 1 end while i < length left begin set lst at k = lef...
def merge(left, right, lst): i = j = k = 0 while i < len(left) and j < len(right): if left[i][0] <= right[j][0]: lst[k] = left[i] i += 1 else: lst[k] = right[j] j += 1 k += 1 while i < len(left): lst[k] = left[i] i += ...
Python
jtatman_500k
function main data points begin comment TODO: modify for no_hurry set cur = data at 0 at slice 2 : 4 : set point = points + absolute data at 0 at 2 - data at 0 at 0 + absolute data at 0 at 3 - data at 0 at 1 set time = data at 0 at 4 + absolute data at 0 at 2 - data at 0 at 0 + absolute data at 0 at 3 - data at 0 at 1...
def main(data, points): #TODO: modify for no_hurry cur = data[0][2:4] point = points + abs(data[0][2] - data[0][0]) + abs(data[0][3] - data[0][1]) time = data[0][4] + abs(data[0][2] - data[0][0]) + abs(data[0][3] - data[0][1]) del data[0] while True: search_data = current_data(time, data...
Python
zaydzuhri_stack_edu_python
import re import urllib.request import os import requests import logging call basicConfig format=string %(asctime)s %(levelname)-8s %(message)s level=DEBUG datefmt=string %Y-%m-%d %H:%M:%S set url = string https://voice.baidu.com/Page/soundmuseum set queries = dict string query string 超级玛丽音效 ; string srcid string 31354...
import re import urllib.request import os import requests import logging logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S') url = "https://voice.baidu.com/Page/soundmuseum" queries = {"query": "超级玛丽音效", "srcid": "31354"} headers = { ...
Python
zaydzuhri_stack_edu_python
function shelf_read table_key SHELVE_FILEPATH=SHELVE_FILEPATH begin try begin with open SHELVE_FILEPATH writeback=false as db begin set flag = table_key in db if flag begin return dict table_key db at table_key end else begin return none end end end except Exception as msg begin error string shelf read error: { msg } r...
def shelf_read(table_key: str, SHELVE_FILEPATH: str= SHELVE_FILEPATH): try: with shelve.open(SHELVE_FILEPATH, writeback=False) as db: flag = table_key in db if flag: return {table_key: db[table_key]} else: return N...
Python
nomic_cornstack_python_v1
comment Binary byte file import struct comment create packed binary data set packed = call pack string >i4sh 7 b'spam' 8 comment 10bytes, not objects or text print packed comment Open binary output file ('wb' is for write binary) set file = open string data.bin string wb comment Write packed binary data write file pack...
#Binary byte file import struct packed = struct.pack('>i4sh',7,b'spam',8) #create packed binary data print(packed) #10bytes, not objects or text file = open('data.bin', 'wb') #Open binary output file ('wb' is for write binary) file.write(packed) #Write packed binary data file.close() #reading bin file and unpacking d...
Python
zaydzuhri_stack_edu_python
function __init__ self code messages begin set code = code set messages = messages end function
def __init__(self, code, messages): self.code = code self.messages = messages
Python
nomic_cornstack_python_v1
comment Python中一切事物都是对象 class MyType extends type begin function __init__ self *args **kwargs begin print string 123 end function function __call__ self *args **kwargs begin print string MyType call end function end class class Foo extends object begin function __init__ self begin print string Foo init end function fun...
# Python中一切事物都是对象 class MyType(type): def __init__(self, *args, **kwargs): print("123") def __call__(self, *args, **kwargs): print("MyType call") class Foo(object, metaclass=MyType): def __init__(self): print("Foo init") def func(self): print("hello world") def _...
Python
zaydzuhri_stack_edu_python
import pubchempy as pcp import random import argparse from time import sleep import os function downloadfrompubchem cid output_dir begin try begin set c = call from_cid cid set element = elements set name = iupac_name set name = join string split name if length name > 80 begin set name = name at slice 0 : 80 : end se...
import pubchempy as pcp import random import argparse from time import sleep import os def downloadfrompubchem(cid, output_dir): try: c = pcp.Compound.from_cid(cid) element = c.elements name = c.iupac_name name =''.join(name.split()) if(len(name)>80): name = na...
Python
zaydzuhri_stack_edu_python
function setTargetPeriod self *args begin return call BufferedPortBottle_setTargetPeriod self *args end function
def setTargetPeriod(self, *args): return _yarp.BufferedPortBottle_setTargetPeriod(self, *args)
Python
nomic_cornstack_python_v1
import classifier import sys import yaml from PIL import Image , ImageDraw , ImageColor import colorsys set config = call safe_load open string config.yml set w = config at string training at string patch_width set h = config at string training at string patch_height set input_path = argv at 1 set predictions = call cl...
import classifier import sys import yaml from PIL import Image, ImageDraw, ImageColor import colorsys config = yaml.safe_load(open("config.yml")) w = config['training']['patch_width'] h = config['training']['patch_height'] input_path = sys.argv[1] predictions = classifier.classify(input_path) s...
Python
zaydzuhri_stack_edu_python
string Link to (question)[https://www.codechef.com/SEPT20B/problems/CRDGAME2] The key idea here is that the maximum never changes the pile it belongs to while every other number will change the pile it belongs to and reduce by 1 So we can focus on the number of maximum values. if the number of maximum values is odd, it...
""" Link to (question)[https://www.codechef.com/SEPT20B/problems/CRDGAME2] The key idea here is that the maximum never changes the pile it belongs to while every other number will change the pile it belongs to and reduce by 1 So we can focus on the number of maximum values. if the number of maximum values is odd, it d...
Python
zaydzuhri_stack_edu_python
function standard_error A b begin set mse = call mean_standard_error_residuals A b set C = call inv T @ A return square root call diag C * mse end function
def standard_error(A, b): mse = mean_standard_error_residuals(A, b) C = inv(A.T @ A) return sqrt(diag(C) * mse)
Python
nomic_cornstack_python_v1
comment coding:utf-8 import pygame , sys from pygame.locals import * string 坦克大战的主窗口 class TankMain begin comment 游戏开始 function startGame self begin comment 创建一个屏幕的宽和高,和窗口特性(0,RESIZABLE ,FULLSCREEN),颜色位数 set screem = call set_mode tuple 640 480 RESIZABLE 32 comment 设置一个标题 call set_caption string 坦克大战 while true begin c...
#coding:utf-8 import pygame,sys from pygame.locals import * '''坦克大战的主窗口''' class TankMain(): #游戏开始 def startGame(self): #创建一个屏幕的宽和高,和窗口特性(0,RESIZABLE ,FULLSCREEN),颜色位数 screem=pygame.display.set_mode((640, 480),RESIZABLE ,32) #设置一个标题 pygame.display.set_caption("坦克大战") whi...
Python
zaydzuhri_stack_edu_python
import numpy as np import os import pandas as pd import matplotlib.pyplot as plt import seaborn as sns set data_directory = join path string ../ string data comment %matplotlib inline set style=string white font_scale=0.9 set cleaned_data_path = join path string ../ string Cleaned_AcceptedLoanData.csv set loan = read c...
import numpy as np import os import pandas as pd import matplotlib.pyplot as plt import seaborn as sns data_directory = os.path.join('../', 'data') #%matplotlib inline sns.set(style='white', font_scale=0.9) cleaned_data_path = os.path.join('../', 'Cleaned_AcceptedLoanData.csv') loan = pd.read_csv(cleaned_data_path, ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Spyder Editor This is a temporary script file. from pylab import * set img = call imread string chick.png set tuple d1 d2 d3 = shape for i in range d1 begin for j in range d2 begin comment for k in range(d3): comment img[i,j,k] = 1 - img[i,j,k] set pixel = img at tuple i j comment i...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ from pylab import * img = imread('chick.png') (d1, d2, d3) = img.shape for i in range(d1): for j in range(d2): #for k in range(d3): #img[i,j,k] = 1 - img[i,j,k] pixel = img[i,j] #if ...
Python
zaydzuhri_stack_edu_python
set x = decimal input string Coordenada x: set y = decimal input string Coordenada y if 2 * x + y == 3 begin print string ponto pertence a reta end else begin print string ponto nao pertence a reta end
x = float(input("Coordenada x:")) y = float(input("Coordenada y")) if(2*x+y == 3): print("ponto pertence a reta") else: print("ponto nao pertence a reta")
Python
zaydzuhri_stack_edu_python
comment !/bin/python3 import sys set t = integer strip input for a0 in range t begin set tuple b w = split strip input string set tuple b w = list integer b integer w set tuple x y z = split strip input string set tuple x y z = list integer x integer y integer z set xa = min x y + z set ya = min y x + z print b * xa + ...
#!/bin/python3 import sys t = int(input().strip()) for a0 in range(t): b,w = input().strip().split(' ') b,w = [int(b),int(w)] x,y,z = input().strip().split(' ') x,y,z = [int(x),int(y),int(z)] xa = min(x,y+z) ya = min(y,x+z) print(b*xa + w*ya)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 import sys from collections import defaultdict set infile = if expression length argv > 1 then argv at 1 else string 9.in set data = strip read open infile set lines = list comprehension x for x in split data string function adjust H T begin set dr = H at 0 - T at 0 set dc = H at 1 - T at 1 if...
#!/usr/bin/python3 import sys from collections import defaultdict infile = sys.argv[1] if len(sys.argv)>1 else '9.in' data = open(infile).read().strip() lines = [x for x in data.split('\n')] def adjust(H,T): dr = (H[0]-T[0]) dc = (H[1]-T[1]) if abs(dr)<=1 and abs(dc)<=1: # ok pass elif ...
Python
zaydzuhri_stack_edu_python
function update_inputs t inputs begin update inputs t inputs end function
def update_inputs(t, inputs): lv.inputs.update(t, inputs)
Python
nomic_cornstack_python_v1
function getSchema base begin set schemas = list function visit arg directory files begin append schemas tuple right strip directory string / list comprehension join path directory filename for filename in files if ends with filename string .cql end function walk base visit none return schemas end function
def getSchema(base): schemas = [] def visit(arg, directory, files): schemas.append( (directory.rstrip('/'), [os.path.join(directory, filename) for filename in files if filename.endswith('.cql')])) os.path.walk(base, visit, None) return schemas
Python
nomic_cornstack_python_v1
function del_node self n begin if n in node_dict begin del node_dict at n for node in node_dict begin try begin call del_edge node n end except any begin pass end end end else begin raise call KeyError string Cannot remove node that does not exist. end end function
def del_node(self, n): if n in self.node_dict: del self.node_dict[n] for node in self.node_dict: try: self.del_edge(node, n) except: pass else: raise KeyError("Cannot remove node that does not exi...
Python
nomic_cornstack_python_v1
function __init__ self begin call __init__ comment input image will have the size of 128x128x3 set first_conv_layer = call TransitionDown in_channels=3 out_channels=32 kernel_size=5 set second_conv_layer = call TransitionDown in_channels=32 out_channels=64 kernel_size=5 set third_conv_layer = call TransitionDown in_cha...
def __init__(self): super(LocalDiscriminator, self).__init__() # input image will have the size of 128x128x3 self.first_conv_layer = TransitionDown(in_channels=3, out_channels=32, kernel_size=5) self.second_conv_layer = TransitionDown(in_channels=32, out_channels=64, kernel_size=5) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Fri Dec 18 16:17:48 2020 @author: ryanfinegan comment to deal with the data from the yahoo finance api import pandas as pd comment for tensorflow and sklearn import numpy as np comment plotting import matplotlib.pyplot as plt comment datetime...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Dec 18 16:17:48 2020 @author: ryanfinegan """ import pandas as pd #to deal with the data from the yahoo finance api import numpy as np #for tensorflow and sklearn import matplotlib.pyplot as plt #plotting import datetime as dt #datetime adjusting impor...
Python
zaydzuhri_stack_edu_python
import torch import matplotlib comment Don't show graph call use string Agg import matplotlib.pyplot as plt from sklearn.manifold import TSNE class config begin function __init__ self begin set embedding_save_path = string ../data/vectors.txt set plot_only = 500 set tsne_save_file = string ../data/Glove.png end functio...
import torch import matplotlib # Don't show graph matplotlib.use('Agg') import matplotlib.pyplot as plt from sklearn.manifold import TSNE class config: def __init__(self): self.embedding_save_path = '../data/vectors.txt' self.plot_only = 500 self.tsne_save_file='../data/Glove.png...
Python
zaydzuhri_stack_edu_python
function description self begin if _description_present begin return _description_value end else begin return none end end function
def description(self): if self._description_present: return self._description_value else: return None
Python
nomic_cornstack_python_v1
function stringGetNodeList self value begin set ret = call xmlStringGetNodeList _o value if ret is none begin raise call treeError string xmlStringGetNodeList() failed end set __tmp = call xmlNode _obj=ret return __tmp end function
def stringGetNodeList(self, value): ret = libxml2mod.xmlStringGetNodeList(self._o, value) if ret is None:raise treeError('xmlStringGetNodeList() failed') __tmp = xmlNode(_obj=ret) return __tmp
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment Generate a combined requirements file from install_requires in setup.py files import re import subprocess set rx_install_requires = compile string .*install_requires.*?=.*?\[([^\]]+) set output_filename = string requirements-combined.txt function get_required_packages path=string s...
#!/usr/bin/env python3 # # Generate a combined requirements file from install_requires in setup.py files import re import subprocess rx_install_requires = re.compile(r'.*install_requires.*?=.*?\[([^\]]+)') output_filename = 'requirements-combined.txt' def get_required_packages(path='setup.py'): """Return a lis...
Python
zaydzuhri_stack_edu_python
function add_gauge self progress_gauge begin set progress_gauge = progress_gauge end function
def add_gauge(self, progress_gauge): self.progress_gauge = progress_gauge
Python
nomic_cornstack_python_v1
function set_freq_all_phase_continuous self freq begin call set_simultaneous_update true call set_phase_continuous true for channel_num in range 4 begin call set_freq channel_num freq end comment send command necessary to update all channels at the same time call _ser_send string I p end function
def set_freq_all_phase_continuous(self, freq): self.set_simultaneous_update(True) self.set_phase_continuous(True) for channel_num in range(4): self.set_freq(channel_num, freq) # send command necessary to update all channels at the same time self._ser_send("I p")
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding:utf-8 -*- string Author: pirogue Purpose: 白名单端口表操作 Site: http://pirogue.org Created: 2018-08-03 17:32:54 from dbs.initdb import DBSession from dbs.models.Whiteport import Whiteport from sqlalchemy import desc , asc comment import sys comment sys.path.append("..") class Wh...
#!/usr/bin/env python # -*- coding:utf-8 -*- """ Author: pirogue Purpose: 白名单端口表操作 Site: http://pirogue.org Created: 2018-08-03 17:32:54 """ from dbs.initdb import DBSession from dbs.models.Whiteport import Whiteport from sqlalchemy import desc,asc # import sys # sys.path.append("..") class WhitePort: ...
Python
zaydzuhri_stack_edu_python
import six import csv if PY2 begin comment pylint: disable=C0103 class uwriter extends object begin string csv.reader with six.text_type support function __init__ self fobj *args **kwargs begin if is instance get kwargs string delimiter text_type begin set kwargs at string delimiter = string kwargs at string delimiter ...
import six import csv if six.PY2: class uwriter(object): # pylint: disable=C0103 """csv.reader with six.text_type support""" def __init__(self, fobj, *args, **kwargs): if isinstance(kwargs.get("delimiter"), six.text_type): kwargs["delimiter"] = str(kwargs["delimiter"])...
Python
zaydzuhri_stack_edu_python
function pct_change initial final begin return final - initial / initial * 100 end function
def pct_change(initial, final): return ((final - initial) / initial) * 100
Python
nomic_cornstack_python_v1
function minimal_block self points begin if not call is_transitive begin return false end set n = degree set gens = generators comment initialize the list of equivalence class representatives set parents = list range n set ranks = list 1 * n set not_rep = list set k = length points comment the block size must divide t...
def minimal_block(self, points): if not self.is_transitive(): return False n = self.degree gens = self.generators # initialize the list of equivalence class representatives parents = list(range(n)) ranks = [1]*n not_rep = [] k = len(points) ...
Python
nomic_cornstack_python_v1
function __starting_data_mode_empty self model_structure begin return dictionary end function
def __starting_data_mode_empty(self, model_structure): return dict()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2020/5/18 20:14 comment @Author : XXX comment @title : 孩子们的游戏(圆圈中最后剩下的数) comment @Site : comment @File : 孩子们的游戏(圆圈中最后剩下的数).py comment @Software: PyCharm class Solution begin function LastRemaining_Solution self n m begin comment write code here ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/5/18 20:14 # @Author : XXX # @title : 孩子们的游戏(圆圈中最后剩下的数) # @Site : # @File : 孩子们的游戏(圆圈中最后剩下的数).py # @Software: PyCharm class Solution: def LastRemaining_Solution(self, n, m): # write code here if n <= 0 or m <= 0: return -1 ...
Python
zaydzuhri_stack_edu_python
class numbers begin function __init__ self begin set value = integer input string Enter the first value end function function chkprime self begin set a = 0 for i in range value begin if value % i + 1 == 0 begin set a = a + 1 end end if a <= 2 begin return true end else begin return false end end function function chkpe...
class numbers(): def __init__(self): self.value = int(input("Enter the first value ")); def chkprime(self): a = 0; for i in range(self.value): if (self.value % (i+1) == 0): a = a + 1; if a <= 2: return(True); else: return(False); def chkperfect(...
Python
zaydzuhri_stack_edu_python
from swampy.TurtleWorld import * import math function polyline turtle numberofmoves length angle begin string Poly line takes the turtle, the number of moves, the length of each move and the angle that the turtle should turn at the end of each move and prints the turtle's movement set delay = 0.01 for i in range number...
from swampy.TurtleWorld import * import math def polyline(turtle, numberofmoves, length, angle): """ Poly line takes the turtle, the number of moves, the length of each move and the angle that the turtle should turn at the end of each move and prints the turtle's movement """ turtle.delay=0.01 for i in range (...
Python
zaydzuhri_stack_edu_python
class Car begin function __init__ self make model year begin set make = make set model = model set year = year end function function __str__ self begin return string { make } { model } ( { year } ) end function end class
class Car: def __init__(self, make, model, year): self.make = make self.model = model self.year = year def __str__(self): return f"{self.make} {self.model} ({self.year})"
Python
flytech_python_25k
function isWidgetNameExist self widgetName begin comment Go over the widget list for widget in widgets begin comment Check whether the widget name given by the user is equal to one of the widget names in the list if name == widgetName begin comment If the widget exist, returns True return true end end comment If the wi...
def isWidgetNameExist(self, widgetName): #Go over the widget list for widget in self.widgets: #Check whether the widget name given by the user is equal to one of the widget names in the list if widget.name == widgetName: #If the widget exist, returns True return True #If the widget doesn't ex...
Python
nomic_cornstack_python_v1
string Functions and Debugging Проверка: https://judge.softuni.bg/Contests/Compete/Index/922#1 02. Sign of Integer Number Условие: Create a function that prints the sign of an integer number n. Examples Input Output 2 The number 2 is positive. -5 The number -5 is negative. 0 The number 0 is zero. function sign_of_integ...
""" Functions and Debugging Проверка: https://judge.softuni.bg/Contests/Compete/Index/922#1 02. Sign of Integer Number Условие: Create a function that prints the sign of an integer number n. Examples Input Output 2 The number 2 is positive. -5 The number -5 is negative. 0 The number 0 is zero....
Python
zaydzuhri_stack_edu_python
from copy import deepcopy set FILE_NAME = string input11.in set g = list for line in read lines open FILE_NAME begin set line = strip line set arr = list for char in line begin append arr char end append g line end set changes = list tuple - 1 0 tuple 1 0 tuple 0 - 1 tuple 0 1 tuple 1 1 tuple 1 - 1 tuple - 1 1 tuple ...
from copy import deepcopy FILE_NAME = "input11.in" g = [] for line in open(FILE_NAME).readlines(): line = line.strip() arr = [] for char in line: arr.append(char) g.append(line) changes = [(-1, 0), (1, 0), (0, -1), (0, 1), (1, 1), (1, -1), (-1, 1), (-1, -1)] def apply_change_...
Python
zaydzuhri_stack_edu_python
function test_full_progress self begin p + 100 assert equal string p string 100% [####################] p + 100 assert equal string p string 100% [####################] end function
def test_full_progress(self): self.p + 100 self.assertEqual(str(self.p), '100% [####################]') self.p + 100 self.assertEqual(str(self.p), '100% [####################]')
Python
nomic_cornstack_python_v1
from __future__ import print_function import pickle import numpy as np import os import gzip import matplotlib.pyplot as plt from model import Model from utils import * import tensorflow as tf from datetime import datetime from tensorboard_evaluation import Evaluation function read_data datasets_dir=string ./data frac=...
from __future__ import print_function import pickle import numpy as np import os import gzip import matplotlib.pyplot as plt from model import Model from utils import * import tensorflow as tf from datetime import datetime from tensorboard_evaluation import Evaluation def read_data(datasets_dir="./data", frac = 0.1)...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment Dette er oppgave fem. import nltk import re function beskriver regeksp ord begin set reg = string ^( + regeksp + string )$ if search reg ord begin return true end else begin return false end end function comment kaller og leser fila: comment oppgave a set filename = string Python_I...
# -*- coding: utf-8 -*- #Dette er oppgave fem. ############################################# import nltk import re def beskriver(regeksp, ord): reg= "^("+regeksp+")$" if re.search(reg, ord): return True else: return False # kaller og leser fila: # oppgave a filename =("Python_INF2820_v2017.txt") pyt_raw = o...
Python
zaydzuhri_stack_edu_python
function is_building_eye self begin pass end function
def is_building_eye(self): pass
Python
nomic_cornstack_python_v1
function get_max_color_by_post_id post_id begin set ordered_records = all if ordered_records begin return hex_value end else begin return string #FFFFFF end end function
def get_max_color_by_post_id(post_id): ordered_records = db.session.query(Result).filter(Result.post_id == post_id).order_by(Result.tone_score.desc()).all() if ordered_records: return ordered_records[0].hex_value else: return "#FFFFFF"
Python
nomic_cornstack_python_v1
function po n begin set lst = list list 1 1 list 1 0 if n == 0 begin return 0 end for i in range 2 n begin set lst = call mul lst end return lst at 0 at 0 end function function mul lst begin set lst1 = list list 1 1 list 1 0 set x = lst at 0 at 0 * lst1 at 0 at 0 + lst at 0 at 1 * lst1 at 1 at 0 set y = lst at 0 at 0 *...
def po(n): lst=[[1,1],[1,0]] if n == 0: return 0 for i in range(2,n): lst = mul(lst) return lst[0][0] def mul(lst): lst1=[[1,1],[1,0]] x=lst[0][0] * lst1[0][0]+ lst[0][1] * lst1[1][0] y=lst[0][0] * lst1[0][1]+ lst[0][1] * lst1[1][1] z=lst[1][0] * lst1[0][0]+ lst[1][1] * ...
Python
zaydzuhri_stack_edu_python
function user_by_username_soft_delete username begin set jwt_claims : dict = call get_claims request set jwt_username = get jwt_claims string sub if username == jwt_username begin info string User { jwt_username } is soft deleting their user. end else begin info string User { jwt_username } is not authorized to soft de...
def user_by_username_soft_delete(username) -> Response: jwt_claims: dict = get_claims(request) jwt_username = jwt_claims.get("sub") if username == jwt_username: current_app.logger.info(f"User {jwt_username} is soft deleting their user.") else: current_app.logger.info( f"User...
Python
nomic_cornstack_python_v1
import pandas as pd import os function dataFormating begin comment 1st excel file set cols_1 = tuple 2 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 set df_1 = call read_excel string ./Data/branch_wise_aging_stock.xlsx usecols=cols_1 set writer = call Exc...
import pandas as pd import os def dataFormating(): # 1st excel file cols_1 = 2, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76 df_1 = pd.read_excel('./Data/branch_wise_aging_stock.xlsx', usecols=cols_1) ...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function licenseKeyFormatting self S K begin string :type S: str :type K: int :rtype: str set result = list for i in reversed range length S begin if S at i == string - begin continue end if length result % K + 1 == K begin set result = result + string - end set result = result + up...
class Solution(object): def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ result = [] for i in reversed(range(len(S))): if S[i] == '-': continue if len(result) % (K + 1) == K: ...
Python
zaydzuhri_stack_edu_python
function create_theme self begin call update_ttk_theme_settings call theme_create name TTK_CLAM settings end function
def create_theme(self): self.update_ttk_theme_settings() self.style.theme_create(self.theme.name, TTK_CLAM, self.settings)
Python
nomic_cornstack_python_v1
function obw v rf_params span=none rel=25 atten=20 rbw=30 count=0 point=none current=none rename=none exs=false snappath=none delay=5 begin set freq = get rf_params string freq set loss = get rf_params string loss set bandwidth = get rf_params string bandwidth if span is none begin comment span = float(int(bandwidth) *...
def obw(v: VisaConnection, rf_params: Dict[str, str], span: int = None, rel: float = 25, atten: int = 20, rbw: int = 30, count: int = 0, point: int = None, current: str = None, rename: str = None, exs: bool = False, snappath: str = None, delay: int = 5) -> float: freq = rf_params.get('freq')...
Python
nomic_cornstack_python_v1
import sys import re import io function extract_names filename begin set f = open filename encoding=string utf-8-sig set content = read f set year = find all string Popularity in \d+ content set year = year at 0 set year = year at slice 14 : : set name = find all string tr align="right"><td>(\d+)<\/td><td>(\w+)<\/td>...
import sys import re import io def extract_names(filename): f = open(filename, encoding='utf-8-sig') content = f.read() year=re.findall("Popularity in \d+",content) year=year[0] year=year[14:] name=re.findall('tr align="right"><td>(\d+)<\/td><td>(\w+)<\/td><td>(\w+)<',content) rank_1=[...
Python
zaydzuhri_stack_edu_python
comment There are some goats and ducks in a farm. There are 60 eyes and 86 foot in total. comment Write a Python program to find number of goats and ducks in the farm comment You can use Cramer’s rule to solve the following 2 × 2 system of linear equation: comment ax + by = e comment cx + dy = f comment x = (ed – bf) /...
# There are some goats and ducks in a farm. There are 60 eyes and 86 foot in total. # Write a Python program to find number of goats and ducks in the farm # You can use Cramer’s rule to solve the following 2 × 2 system of linear equation: # ax + by = e # cx + dy = f # # x = (ed – bf) / (ad – bc). # y = (af – ec) / (ad...
Python
zaydzuhri_stack_edu_python
function reorder_database_affinities cmd begin set st = call storage set db = call exa_db db_name try begin call db_reorder_affinities db st log=lambda X -> write stdout string %s % X end except Exception as err begin print string ERROR: %s % string err return 1 end end function
def reorder_database_affinities(cmd): st = exacos.storage() db = exacos.exa_db(cmd.db_name) try: db_reorder_affinities(db, st, log = lambda X: sys.stdout.write('%s\n' % X)) except Exception as err: print('ERROR: %s' % str(err)) return 1
Python
nomic_cornstack_python_v1
function read self n begin set msg = call readexactly n set n2 = n - length msg if n2 > 0 begin set msg = msg + call readbuf n2 end return msg end function
def read(self, n): msg = self.readexactly(n) n2 = n - len(msg) if n2 > 0: msg += self.readbuf(n2) return msg
Python
nomic_cornstack_python_v1
function _get_save_choice self begin set desc = input _lang at string desc if lower desc == _lang at string no begin set save = false end else begin set save = true set desc = desc end return save end function
def _get_save_choice(self): desc = input(self._lang["desc"]) if desc.lower() == self._lang["no"]: self._state.save = False else: self._state.save = True self._state.desc = desc return self._state.save
Python
nomic_cornstack_python_v1
from typing import * class Solution begin function mergeTwoLists self l1 l2 begin set head = call ListNode 0 set ans = head while l1 != none and l2 != none begin if val < val begin set next = l1 set l1 = next end else begin set next = l2 set l2 = next end set head = next end while l1 != none begin set next = l1 set hea...
from typing import * class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: head = ListNode(0) ans = head while(l1 != None and l2 != None): if(l1.val < l2.val): head.next = l1 l1 = l1.next else: ...
Python
zaydzuhri_stack_edu_python
function terminal board begin if call winner board != none begin return true end for i in range 3 begin for j in range 3 begin if board at i at j == EMPTY begin return false end end end return true end function
def terminal(board): if (winner(board) != None): return True for i in range(3): for j in range(3): if board[i][j] == EMPTY: return False return True
Python
nomic_cornstack_python_v1
function extract_user self begin if length primary_fbids < 1 and length secondary_fbids < 1 begin return end set fbid = if expression length primary_fbids > 0 then pop primary_fbids else pop secondary_fbids comment null fbids :\ if not fbid begin return end call seek_user fbid commit pconn info format string Extracted ...
def extract_user(self): if len(self.primary_fbids) < 1 and len(self.secondary_fbids) < 1: return fbid = self.primary_fbids.pop() if len(self.primary_fbids) > 0 else self.secondary_fbids.pop() # null fbids :\ if not fbid: return self.seek_user(fbid) self.pconn.commit() ...
Python
nomic_cornstack_python_v1
function create_node driver **kwargs begin set kw = call DefaultMunch comment Bail on conflicting arguments if get kwargs string ssh_key and get kwargs string password begin raise call ClickException string Use either --ssh-key or --password end comment Process arguments common for all compute drivers. set name = pop k...
def create_node(driver: BaseDriver, **kwargs: Any) -> None: kw = DefaultMunch() # Bail on conflicting arguments if kwargs.get("ssh_key") and kwargs.get("password"): raise click.ClickException("Use either --ssh-key or --password") # Process arguments common for all compute drivers. kw.name ...
Python
nomic_cornstack_python_v1
import os import sys set environ at string TF_CPP_MIN_LOG_LEVEL = string 2 import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras import numpy as np from tensorflow.keras.layers.experimental.preprocessing import Normalization , Rescaling , CenterCrop from tensorflow.keras import layers fro...
import os import sys os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras import numpy as np from tensorflow.keras.layers.experimental.preprocessing import Normalization, Rescaling, CenterCrop from tensorflow.keras import layers from sklearn.metri...
Python
zaydzuhri_stack_edu_python
function _get_pieces tiles ports players_opts pieces_opts begin string Generate a dictionary of pieces using the given options. pieces options supported: - Opt.empty -> no locations have pieces - Opt.random -> - Opt.preset -> robber is placed on the first desert found - Opt.debug -> a variety of pieces are placed aroun...
def _get_pieces(tiles, ports, players_opts, pieces_opts): """ Generate a dictionary of pieces using the given options. pieces options supported: - Opt.empty -> no locations have pieces - Opt.random -> - Opt.preset -> robber is placed on the first desert found - Opt.debug -> a variety of pie...
Python
jtatman_500k
function resolve_cert_reqs candidate begin if candidate is none begin return CERT_NONE end if is instance candidate str begin set res = get attribute ssl candidate none if res is none begin set res = get attribute ssl string CERT_ + candidate end return res end return candidate end function
def resolve_cert_reqs(candidate): if candidate is None: return CERT_NONE if isinstance(candidate, str): res = getattr(ssl, candidate, None) if res is None: res = getattr(ssl, 'CERT_' + candidate) return res return candidate
Python
nomic_cornstack_python_v1
while length vetor < 110 begin set numero = 1 / 6 + vetor at i append vetor numero set i = i + 1 end set total = 3 + vetor at valor print string %.10f % total
while len(vetor)<110 : numero = 1/(6+ vetor[i]) vetor.append(numero) i += 1 total = 3 + vetor[valor] print("%.10f" %total)
Python
zaydzuhri_stack_edu_python
import unittest from lispy.helpers import split from lispy.helpers import convert from lispy.helpers import brush_equ class TestSplit extends TestCase begin function test_wrong_equ_no_brackets self begin with assert raises ValueError begin split string + 1 2 end end function function test_wrong_equ_no_right_bracket sel...
import unittest from lispy.helpers import split from lispy.helpers import convert from lispy.helpers import brush_equ class TestSplit(unittest.TestCase): def test_wrong_equ_no_brackets(self): with self.assertRaises(ValueError): split("+ 1 2") def test_wrong_equ_no_right_bracket(self): ...
Python
zaydzuhri_stack_edu_python
from monogusa.events import EventParser , subscription from monogusa.events import Message decorator call subscribe Message function echo ev begin print string ! content end function function read begin import sys set p = call EventParser sep=string , for line in stdin begin set ev = parse p line call subscription ev e...
from monogusa.events import EventParser, subscription from monogusa.events import Message @subscription.subscribe(Message) def echo(ev: Message) -> None: print("!", ev.content) def read(): import sys p = EventParser(sep=",") for line in sys.stdin: ev = p.parse(line) subscription(ev)...
Python
zaydzuhri_stack_edu_python
import operator class Hotel begin function __init__ self name rating begin set name = name set rating = rating set price_details = list set hotel_rate = string end function function add_price_details self regular_weekday regular_weekend reward_weekday reward_weekend begin append price_details regular_weekday append p...
import operator class Hotel: def __init__(self, name, rating): self.name = name self.rating = rating self.price_details = [] self.hotel_rate = "" def add_price_details(self, regular_weekday, regular_weekend, reward_weekday, reward_weekend): self.price_details.append(r...
Python
zaydzuhri_stack_edu_python
function adjCheck num begin set num = string num set i = 0 while i < length num - 1 begin if num at i == num at i + 1 begin return true end set i = i + 1 end return false end function function incCheck num begin set num = string num set i = 0 while i < length num - 1 begin if integer num at i > integer num at i + 1 beg...
def adjCheck(num): num = str(num) i = 0 while i < len(num) - 1: if num[i] == num[i+1]: return True i += 1 return False def incCheck(num): num = str(num) i = 0 while i < len(num) - 1: if int(num[i]) > int(num[i+1]): return False i += 1 ...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function detectCycle self head begin string :type head: ListNode :rtype: ListNode set seen = set while head begin if head in seen begin return head end add seen head set head = next end return none end function end class
class Solution(object): def detectCycle(self, head): """ :type head: ListNode :rtype: ListNode """ seen = set() while head: if head in seen: return head seen.add(head) head = head.next return None
Python
zaydzuhri_stack_edu_python
function connect_post_namespaced_node_proxy self name **kwargs begin set kwargs at string _return_http_data_only = true if get kwargs string callback begin return call connect_post_namespaced_node_proxy_with_http_info name keyword kwargs end else begin set data = call connect_post_namespaced_node_proxy_with_http_info n...
def connect_post_namespaced_node_proxy(self, name, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.connect_post_namespaced_node_proxy_with_http_info(name, **kwargs) else: (data) = self.connect_post_namespaced_node_proxy_with_http_...
Python
nomic_cornstack_python_v1
function remove_punctuation words begin set table = call maketrans string string punctuation return list comprehension call translate table for w in words end function
def remove_punctuation(words): table = str.maketrans('', '', string.punctuation) return [w.translate(table) for w in words]
Python
nomic_cornstack_python_v1
function create_pretraining_dataloader hdf5_fpath max_masked_tokens_per_input batch_size begin set pretraining_data = call PretrainingDataset hdf5_fpath=hdf5_fpath max_masked_tokens_per_input=max_masked_tokens_per_input set train_sampler = call RandomSampler pretraining_data set train_dataloader = call DataLoader pretr...
def create_pretraining_dataloader( hdf5_fpath: str, max_masked_tokens_per_input: int, batch_size: int ): pretraining_data = PretrainingDataset( hdf5_fpath=hdf5_fpath, max_masked_tokens_per_input=max_masked_tokens_per_input ) train_sampler = RandomSampler(pretraini...
Python
nomic_cornstack_python_v1
function _draw_hierarchical_visualisation actions_per_section colour_dict save_path file initial_img=none img_height=600 top_margin=0 vertical_gap=100 return_img=false skip_ground_truth=false skip_prediction=false split_long_words=false font_scale=0.35 coarse_action_to_label_id=none fine_action_to_label_id=none write_l...
def _draw_hierarchical_visualisation(actions_per_section, colour_dict, save_path, file, initial_img=None, img_height=600, top_margin=0, vertical_gap=100, return_img=False, skip_ground_truth=False, skip_prediction=False, split_long_words=False, ...
Python
nomic_cornstack_python_v1
function subgroups self begin set db = db set my_subgroups = set comprehension group_id for tuple group_id in call db string select distinct subgroup_id from subgroups, groups where id = group_id and group_id = %s and groups.type = 'U' _id return my_subgroups end function
def subgroups(self): db = self['__store'].db my_subgroups = { group_id for group_id, in db(""" select distinct subgroup_id from subgroups, groups where id = group_id and group_id =...
Python
nomic_cornstack_python_v1
comment coding=utf8 set __author__ = string luocheng import sqlite3 import math comment ljd = logarithm of the score assigned by judge j to document d comment J the total number of all judges( unique) comment sjd = 10^(ljd + u - uj) comment uj = 1/n*(sigma{d} ljd) comment u = all documents set cx = call connect string ...
#coding=utf8 __author__ = 'luocheng' import sqlite3 import math # ljd = logarithm of the score assigned by judge j to document d # J the total number of all judges( unique) # sjd = 10^(ljd + u - uj) # uj = 1/n*(sigma{d} ljd) # u = all documents cx = sqlite3.connect('../data/db.sqlite3') cu = cx.cursor() from co...
Python
zaydzuhri_stack_edu_python
function check_movement self delta_x=none delta_y=none delta_angular=none movement_object=none begin set tuple x0_value y0_value yaw0 = call get_x_y_yaw _odom_pose set movement_achieved = false comment 10hz set rate = call Rate 10 while not movement_achieved and not call is_shutdown begin call logerr string Movement NO...
def check_movement(self, delta_x = None, delta_y = None, delta_angular = None, movement_object= None): x0_value, y0_value, yaw0 = self.get_x_y_yaw(self._odom_pose) movement_achieved = False rate = rospy.Rate(10) # 10hz while not movement_achieved and not rospy.is_shutdown(): ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment this file is executed automatically at startup import math import os import time import socket import sys from datetime import datetime import glob function ClientSocket begin comment Create a TCP/IP socket set sock = call socket AF_INET SOCK_STREAM call se...
#!/usr/bin/python # -*- coding: utf-8 -*- # this file is executed automatically at startup import math import os import time import socket import sys from datetime import datetime import glob def ClientSocket(): # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeo...
Python
zaydzuhri_stack_edu_python
comment Find All Missing Number (easy) string We are given an unsorted array containing numbers taken from the range 1 to ‘n’. The array can have duplicates, which means some numbers will be missing. Find all those missing numbers. Time Complexity: O(N) Space Complexity: O(1) function find_missing_numbers nums begin se...
#Find All Missing Number (easy) """ We are given an unsorted array containing numbers taken from the range 1 to ‘n’. The array can have duplicates, which means some numbers will be missing. Find all those missing numbers. Time Complexity: O(N) Space Complexity: O(1) """ def find_missing_numbers(nums): i = 0 while...
Python
zaydzuhri_stack_edu_python
import gym import random import numpy as np from collections import deque from tensorflow import keras from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam set GAMMA = 0.95 set EPSILON_MAX = 1.0 set EPSILON_DECAY = 0.995 set EPSILON_MIN = 0.01 set BATCH_SIZE = 20 set ALPH...
import gym import random import numpy as np from collections import deque from tensorflow import keras from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam GAMMA = 0.95 EPSILON_MAX = 1.0 EPSILON_DECAY = 0.995 EPSILON_MIN = 0.01 BATCH_SIZE = 20 ALPHA = 0.01 APLHA_DECAY = ...
Python
zaydzuhri_stack_edu_python
import numpy as np from sklearn.base import ClassifierMixin , BaseEstimator , clone import strlearn as sl class BLS extends BaseEstimator ClassifierMixin begin function __init__ self base_estimator budget=0.5 random_state=none begin set budget = budget set base_estimator = base_estimator set random_state = random_state...
import numpy as np from sklearn.base import ClassifierMixin, BaseEstimator, clone import strlearn as sl class BLS(BaseEstimator, ClassifierMixin): def __init__(self, base_estimator, budget=0.5, random_state=None): self.budget = budget self.base_estimator = base_estimator self.random_state ...
Python
zaydzuhri_stack_edu_python
function compare_brain_and_stimulus_input_data self begin comment first check which (unique) patches are presented set stim_info = call loadtxt call runFile stage=string processed/behavior extension=string .txt postFix=list string stim_info_all set unique_stim = unique stim_info at tuple slice : : 2 set stimuli = ar...
def compare_brain_and_stimulus_input_data(self): # first check which (unique) patches are presented stim_info = np.loadtxt(self.runFile(stage = 'processed/behavior', extension = '.txt', postFix = ['stim_info_all'])) unique_stim = np.unique(stim_info[:,2]) stimuli = np.array(self.rescale_images(patches = list(...
Python
nomic_cornstack_python_v1
function sample_images ds_path n_sample begin comment Grab a list of paths that matches the pathname set files = glob glob join path ds_path string * string *.txt set n_files = length files if n_sample == none begin set n_sample = n_files end comment Randomly sample from the training/testing dataset comment Depending o...
def sample_images(ds_path, n_sample): # Grab a list of paths that matches the pathname files = glob.glob(os.path.join(ds_path, "*", "*.txt")) n_files = len(files) if n_sample == None: n_sample = n_files # Randomly sample from the training/testing dataset # Depending on the purpose, we ...
Python
nomic_cornstack_python_v1
comment 제어문 comment 조건부 표현식 set score = 70 if score >= 60 begin set message = string success end else begin set message = string Failure end print message comment 위의 조건문은 조건부 표현식으로 변환하기 comment 조건문이 참인 경우 if 조건문 else 조건문이 참이 아닌경우 set message = if expression score >= 70 then string success else string Failure comment wh...
# 제어문 # 조건부 표현식 score = 70 if score >= 60 : message = "success" else : message = "Failure" print(message) #위의 조건문은 조건부 표현식으로 변환하기 # 조건문이 참인 경우 if 조건문 else 조건문이 참이 아닌경우 message = "success" if score >= 70 else "Failure" # while 문 # 조건문이 참인 동안에 while 문을 반복 수행 treehit = 0 while treehit < 10 : treehit = t...
Python
zaydzuhri_stack_edu_python
comment 绘制一条余弦曲线 import numpy as np import matplotlib.pyplot as mp comment 创建8个数的数组 set yarray = array list 64 89 12 36 49 80 45 34 comment 随机抛出8个数 comment xarray=np.arange(8) comment 画直线工具 plot yarray comment mp.show() comment vertical 绘制垂直线 call vlines 4 10 80 comment horizotal 绘制水平线 call hlines 40 1 7 call hlines li...
#绘制一条余弦曲线 import numpy as np import matplotlib.pyplot as mp #创建8个数的数组 yarray=np.array([64,89,12,36,49,80,45,34]) #随机抛出8个数 # xarray=np.arange(8) #画直线工具 mp.plot(yarray) # mp.show() # vertical 绘制垂直线 mp.vlines(4, 10, 80) # horizotal 绘制水平线 mp.hlines(40, 1, 7) mp.hlines([10,20,30,50],[1,8,4,6],[7,1,5,5]) #显示图表:阻塞函数 mp.sh...
Python
zaydzuhri_stack_edu_python
function serve drafts=false bundle_exec=_bundle_exec force_polling=_fpolling incremental_build=_incremental begin set core_command = string jekyll serve set exec_lst = list core_command comment Icluding _site_dest append exec_lst string -d + _site_dest comment Listening given port and hostname append exec_lst string --...
def serve(drafts=False, bundle_exec=_bundle_exec, force_polling=_fpolling, incremental_build=_incremental): core_command = 'jekyll serve' exec_lst = [core_command] # Icluding _site_dest exec_lst.append('-d ' + _site_dest) # Listening given port and hostname exec_lst.append('--host ' ...
Python
nomic_cornstack_python_v1
import math set t = integer input for i in range 1 t + 1 begin set tuple n p = list comprehension integer s for s in split input string set stalls = list n for j in range p begin set maximum = max stalls if maximum % 2 == 0 begin set r = integer maximum / 2 set l = r - 1 end else begin set l = integer maximum - 1 / 2 s...
import math t = int(input()) for i in range(1, t + 1): n, p = [int(s) for s in input().split(" ")] stalls = [n] for j in range(p): maximum = max(stalls) if maximum % 2 == 0: r = int(maximum/2) l = r - 1 else: l = r = int((maximum-1)/...
Python
zaydzuhri_stack_edu_python
class Student extends object begin function __init__ self sno=string sname=string sex=string sgrade=string begin set sno = sno set sname = sname set sex = sex set sgrade = sgrade end function function setSno self sno begin set sno = sno end function function getSno self begin return sno end function function setSnam...
class Student(object): def __init__(self,sno='',sname='',sex='',sgrade=''): self.sno = sno self.sname = sname self.sex = sex self.sgrade = sgrade def setSno(self,sno): self.sno = sno def getSno(self): return self.sno def setSname(self,sname): ...
Python
zaydzuhri_stack_edu_python
import math class Solution begin function longestPalindrome self s begin if length s == 0 begin return s end set sol = s at 0 for i in range 1 length s begin set j = 1 comment Test for palindrome of odd length starting with middle point s[i] while j < min i + 1 length s - i and s at i - j == s at i + j begin set j = j ...
import math class Solution: def longestPalindrome(self, s: str) -> str: if len(s)==0: return s sol = s[0] for i in range(1,len(s)): j = 1 while j < min(i+1,len(s)-i) and s[i-j] == s[i+j]: #Test for palindrome of odd length starting with middle point s[i] ...
Python
zaydzuhri_stack_edu_python
function input_num prompt=string float_or_int=false bound_lower=false bound_upper=false inclusive_lower=true inclusive_upper=true convert_string=false begin set bound = list bound_lower bound_upper set inclusive = list inclusive_lower inclusive_upper set input_type_2 = string set inclusive_0 = string set inclusive_1...
def input_num(prompt="", float_or_int=False, bound_lower=False, bound_upper=False, inclusive_lower=True, inclusive_upper=True, convert_string=False): bound = [bound_lower, bound_upper] inclusive = [inclusive_lower, inclusive_upper] input_type_2 = "" inclusive_0 = "" inclusive_1 = "" inpu...
Python
nomic_cornstack_python_v1
function parse self begin comment Temporary "file" to hold the zipped content set out = call StringIO with open RESOURCE string rb as f begin write out call _xor read f _buffer end try begin set temp = zip file out end except BadZipfile begin raise BadZipfile end if ALIAS + string .xml in name list temp begin set t = o...
def parse(self): out = StringIO.StringIO() # Temporary "file" to hold the zipped content with open(self.RESOURCE, 'rb') as f: out.write(self._xor(f.read(self._buffer))) try: temp = zipfile.ZipFile(out) except zipfile.BadZipfile: raise zipfile.BadZipf...
Python
nomic_cornstack_python_v1
function _normalize_sentence sent begin comment sent = sent[sent.find('\n\n\n'):] set removed = string [\n ]+ set sent = sub removed string sent return strip sent end function
def _normalize_sentence(sent): #sent = sent[sent.find('\n\n\n'):] removed = r'[\n ]+' sent = re.sub(removed, ' ', sent) return sent.strip()
Python
nomic_cornstack_python_v1
function printMax x y begin string Bla bla bla (here must be description of function) Blah blah blah corectly... set x = integer x set y = integer y if x > y begin print x string the most end else if x < y begin print y string the most end end function call printMax 3 5 print __doc__
def printMax(x, y): '''Bla bla bla (here must be description of function) Blah blah blah corectly...''' x = int(x) y = int(y) if x > y: print(x, 'the most') elif x < y: print(y, 'the most') printMax(3, 5) print(printMax.__doc__)
Python
zaydzuhri_stack_edu_python
function send_mail self template subject recipient sender body html user **kwargs begin from flask_mail import Message set msg = call Message subject sender=sender recipients=list recipient set body = body set html = html set mail = get extensions string mail call send msg end function
def send_mail( self, template, subject, recipient, sender, body, html, user, **kwargs ): from flask_mail import Message msg = Message(subject, sender=sender, recipients=[recipient]) msg.body = body msg.html = html mail = current_app.extensions.get("mail") m...
Python
nomic_cornstack_python_v1
string 503. Next Greater Element II Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search ...
""" 503. Next Greater Element II Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search ci...
Python
zaydzuhri_stack_edu_python