code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
from flask import Flask , jsonify , request , render_template import numpy as np import pandas as pd from model import get_top_20_recommended_products , get_top_5_products_using_sentiment_analysis set app = call Flask __name__ decorator call route string / function home begin return call render_template string index.ht...
from flask import Flask, jsonify, request, render_template import numpy as np import pandas as pd from model import get_top_20_recommended_products,get_top_5_products_using_sentiment_analysis app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route("/recommendations", me...
Python
zaydzuhri_stack_edu_python
function test_parent child parent begin assert string parent == string parent end function
def test_parent(child, parent): assert str(child.parent) == str(parent)
Python
nomic_cornstack_python_v1
import unittest import os import json from urlparse import urlparse comment Configure app to use the testing databse set environ at string CONFIG_PATH = string blog.config.TestingConfig from blog import app from blog import models from blog.database import Base , engine , session class TestAPI extends TestCase begin st...
import unittest import os import json from urlparse import urlparse # Configure app to use the testing databse os.environ["CONFIG_PATH"] = "blog.config.TestingConfig" from blog import app from blog import models from blog.database import Base, engine, session class TestAPI(unittest.TestCase): """ Tests for the ...
Python
zaydzuhri_stack_edu_python
function test_user__repr__ self begin assert equal call repr test_user string <User username=beans4time password=beepboop email=beepboop@aol.com first_name=tommy last_name=pickles> end function
def test_user__repr__(self): self.assertEqual(repr(self.test_user), "<User username=beans4time password=beepboop email=beepboop@aol.com first_name=tommy last_name=pickles>")
Python
nomic_cornstack_python_v1
function Algoritmo3 arr an al la begin set nC = 1 set volumen = call Volumen set C = nC set xmax = largo set ymax = ancho for i in range 1 length arr begin set volumen = volumen + call Volumen if x + largo <= la begin if ancho + y <= an begin if alto + z + alto <= al begin set C = nC if xmax < x + largo begin set xmax ...
def Algoritmo3(arr, an, al, la): nC = 1 volumen = arr[0].Volumen() arr[0].C = nC xmax = arr[0].largo ymax = arr[0].ancho for i in range(1, len(arr)): volumen += arr[i].Volumen() if arr[i-1].x + arr[i].largo <= la: if arr[i].ancho + arr[i-...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from __future__ import division import math set n = integer input string Digite o valor de n: set a = integer input string Digite um número: set b = integer input string Digite outro número: set i = 1
# -*- coding: utf-8 -*- from __future__ import division import math n= int(input('Digite o valor de n: ')) a= int(input('Digite um número:')) b= int(input('Digite outro número: ')) i= 1
Python
zaydzuhri_stack_edu_python
comment Chapter 10 图像上的算术运算 import cv2 import numpy as np set e1 = call getTickCount comment 显示图像函数 function ShowImage name_of_image image rate begin set img_min = call resize image none fx=rate fy=rate interpolation=INTER_CUBIC call namedWindow name_of_image WINDOW_NORMAL image show name_of_image img_min comment wait ...
# Chapter 10 图像上的算术运算 import cv2 import numpy as np e1 = cv2.getTickCount() # 显示图像函数 def ShowImage(name_of_image, image, rate): img_min = cv2.resize(image, None, fx=rate, fy=rate, interpolation=cv2.INTER_CUBIC) cv2.namedWindow(name_of_image, cv2.WINDOW_NORMAL) cv2.imshow(name_of_image, img_min...
Python
zaydzuhri_stack_edu_python
function chooseAction self gameState begin set actions = call getLegalActions index set values = list comprehension evaluate self gameState a for a in actions set maxValue = max values set bestActions = list comprehension a for tuple a v in zip actions values if v == maxValue return random choice bestActions end functi...
def chooseAction(self, gameState): actions = gameState.getLegalActions(self.index) values = [self.evaluate(gameState, a) for a in actions] maxValue = max(values) bestActions = [a for a, v in zip(actions, values) if v == maxValue] return random.choice(bestActions)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: UTF-8 -*- function topla s1 s2 begin print string toplam= s1 + s2 end function set sayi1 = integer input string sayi1 = set sayi2 = integer input string sayi2 = call topla sayi1 sayi2
#!/usr/bin/python # -*- coding: UTF-8 -*- def topla(s1,s2): print("toplam=",s1+s2) sayi1 = int(input("sayi1 = ")) sayi2 = int(input("sayi2 = ")) topla(sayi1,sayi2)
Python
zaydzuhri_stack_edu_python
function test_search_task_type self begin pass end function
def test_search_task_type(self): pass
Python
nomic_cornstack_python_v1
comment 재귀함수 comment 자기자신을 호출하는 함수 string #재귀함수의 구조 기본 파트 : base case 적어도 하나의 recursion에 빠지지 않는 경우가 존재해야 함 유도 파트 : recursive case recursion을 반복하다보면 결국 base case로 수렴해야 함 comment def func(k): comment if k < 0: # base 파트 comment return comment print('hello') comment func(k-1) comment func(5) comment 재귀함수를 이용해서 1~10까지의 합을 ...
#재귀함수 #자기자신을 호출하는 함수 ''' #재귀함수의 구조 기본 파트 : base case 적어도 하나의 recursion에 빠지지 않는 경우가 존재해야 함 유도 파트 : recursive case recursion을 반복하다보면 결국 base case로 수렴해야 함 ''' # def func(k): # if k < 0: # base 파트 # return # print('hello') # func(k-1) # # func(5) #재귀함수를 이용해서 1~10까지의 합을 구하세요 def add(K,result):...
Python
zaydzuhri_stack_edu_python
import math function fruit_exchange name_1 name_2 amount_of_apple amount_of_orange apple_exchange_rate begin set orange_apple_poolratio = amount_of_orange / amount_of_apple set exchanged_apple = amount_of_orange / apple_exchange_rate set exchanged_orange = exchanged_apple * apple_exchange_rate print string { name_1 } :...
import math def fruit_exchange(name_1, name_2, amount_of_apple, amount_of_orange, apple_exchange_rate): orange_apple_poolratio = amount_of_orange / amount_of_apple exchanged_apple = amount_of_orange / apple_exchange_rate exchanged_orange = exchanged_apple * apple_exchange_rate print(f"{name_1}: Hello {name_2}, l...
Python
zaydzuhri_stack_edu_python
import random set le = list string : string ; set ln = list string , string . string > string < string ^ string ` string ' set lm = list string ( string ) string @ string # string 3 string $ string % string ? string { string } string | set i = 0 set user_in = integer input string How many emoticons do you want to gener...
import random le = [":",";"] ln = [",",".",">","<","^","`","\'"] lm = ["(",")","@","#","3","$","%","?","{","}","|"] i = 0 user_in = int(input("How many emoticons do you want to generate? ")) while i < user_in: print(random.choice(le)+random.choice(ln)+random.choice(lm)) i += 1
Python
zaydzuhri_stack_edu_python
function classifier_architecure depth classifier_parameters dropout begin set classifier_depth_0 = sequential ordered dictionary list tuple string fc1 linear classifier_parameters at 0 classifier_parameters at 1 tuple string drop_out dropout p=dropout tuple string output log softmax dim=1 set classifier_depth_1 = seque...
def classifier_architecure(depth,classifier_parameters,dropout): classifier_depth_0 = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(classifier_parameters[0], classifier_parameters[1])), ('drop_out', nn.Dropout(p=dropout)), ('output', nn.LogSoftmax(dim=1))]...
Python
nomic_cornstack_python_v1
function read self targets start=none end=none create_multiindex=true remove_redundant_indices=true begin comment sanity checks if not url begin raise call MetricsReaderError string No URL specified end else begin set url = url join url _render_api end if is instance targets string_types begin set df = call _download_s...
def read(self, targets, start=None, end=None, create_multiindex=True, remove_redundant_indices=True, ): # sanity checks if not self.url: raise MetricsReaderError('No URL specified') else: url = u...
Python
nomic_cornstack_python_v1
comment 203实现Tire(前缀树) class Trie begin function __init__ self begin set root = dict set end_of_word = string # end function function insert self word begin set node = root for char in word begin set node = set default node char dict end set node at end_of_word = end_of_word end function function search self word begi...
#203实现Tire(前缀树) class Trie: def __init__(self): self.root={} self.end_of_word="#" def insert(self, word: str) -> None: node=self.root for char in word: node = node.setdefault(char,{}) node[self.end_of_word]=self.end_of_word def search(self, word: str) ->...
Python
zaydzuhri_stack_edu_python
import pyautogui as pg import webbrowser as web import time as tm import pandas as pd set data = read csv string datos.csv set data_dict = call to_dict string list set celulares = data_dict at string celular set first = true for celular in celulares begin open string https://api.whatsapp.com/send?phone=+57 + string cel...
import pyautogui as pg import webbrowser as web import time as tm import pandas as pd data = pd.read_csv("datos.csv") data_dict = data.to_dict('list') celulares = data_dict['celular'] first = True for celular in celulares: web.open("https://api.whatsapp.com/send?phone=+57"+str(celular)+"&text=¡Hola! Soy Nicolas ...
Python
zaydzuhri_stack_edu_python
function get_parent_list topic_type begin set __result_types = list append __result_types topic_type set __t = topic_type while parent != none begin insert __result_types 0 parent set __t = parent end return __result_types end function
def get_parent_list(topic_type): __result_types = [] __result_types.append(topic_type) __t = topic_type while __t.parent != None: __result_types.insert(0, __t.parent) __t = __t.parent return __result_types
Python
nomic_cornstack_python_v1
function is_read_only cls db logger=none begin string Do we have read-only access? function convert_enums row_ begin comment All these columns are of type enum('N', 'Y'); comment https://dev.mysql.com/doc/refman/5.0/en/enum.html return list comprehension if expression x == string Y then true else if expression x == str...
def is_read_only(cls, db: DATABASE_SUPPORTER_FWD_REF, logger: logging.Logger = None) -> bool: """Do we have read-only access?""" def convert_enums(row_): # All these columns are of type enum('N', 'Y'); # https://dev.mysql.com/doc/refman/...
Python
jtatman_500k
comment !/usr/bin/env python3 import csv function read_employees csv_file_location begin call register_dialect string empDialect skipinitialspace=true strict=true set employee_file = dict reader open csv_file_location dialect=string empDialect set employee_list = list for data in employee_file begin append employee_li...
#!/usr/bin/env python3 import csv def read_employees(csv_file_location): csv.register_dialect('empDialect', skipinitialspace=True, strict=True) employee_file=csv.DictReader(open(csv_file_location), dialect='empDialect') employee_list=[] for data in employee_file: employee_list.append(data) return employee_list ...
Python
zaydzuhri_stack_edu_python
function push self remote=string origin branch=string master options=none begin if options is none begin set options = string end call _execute format string git push {0} {1} {2} remote branch options end function
def push(self, remote='origin', branch='master', options=None): if options is None: options = '' self._execute('git push {0} {1} {2}'.format(remote, branch, options))
Python
nomic_cornstack_python_v1
function data_cleaner doc begin set sw = call words string english set regex_token = call RegexpTokenizer string ([a-zA-Z]+(?:’[a-z]+)?) set doc = call tokenize doc set doc = list comprehension lower word for word in doc set doc = list comprehension word for word in doc if word not in sw comment print(doc) set doc = ca...
def data_cleaner(doc): sw = stopwords.words('english') regex_token = RegexpTokenizer(r"([a-zA-Z]+(?:’[a-z]+)?)") doc = regex_token.tokenize(doc) doc = [word.lower() for word in doc] doc = [word for word in doc if word not in sw] #print(doc) doc = pos_tag(doc) doc = [(word[0], get_wo...
Python
nomic_cornstack_python_v1
import random string 1) Создать список из 20 случайных целых чисел в диапазоне от 1 до 100. Задание можно выполнить и через обычный цикл и через генератор списков. set my_list = list comprehension random integer 1 100 for number in range 1 21 print my_list string 2) Создать словарь triangle в который записать точки A B...
import random """ 1) Создать список из 20 случайных целых чисел в диапазоне от 1 до 100. Задание можно выполнить и через обычный цикл и через генератор списков. """ my_list = [random.randint(1, 100) for number in range(1,21)] print(my_list) ######################################################################## "...
Python
zaydzuhri_stack_edu_python
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity set s1 = string The study of bees , birds, butterflies and animals is Zoology set s2 = string Enneagram is the study of the divrse set of human minds set s3 = string Botony is the study of the plants kingd...
from sklearn.feature_extraction.text import TfidfVectorizer; from sklearn.metrics.pairwise import cosine_similarity; s1 = "The study of bees , birds, butterflies and animals is Zoology"; s2 = "Enneagram is the study of the divrse set of human minds"; s3 = "Botony is the study of the plants kingdom"; q = "Botony is t...
Python
zaydzuhri_stack_edu_python
function _op_generic_Ctz self args begin set piece_size = length args at 0 set wtf_expr = call BVV piece_size piece_size for a in reversed range piece_size begin set bit = extract claripy a a args at 0 set wtf_expr = call If bit == 1 call BVV a piece_size wtf_expr end return wtf_expr end function
def _op_generic_Ctz(self, args): piece_size = len(args[0]) wtf_expr = claripy.BVV(piece_size, piece_size) for a in reversed(range(piece_size)): bit = claripy.Extract(a, a, args[0]) wtf_expr = claripy.If(bit == 1, claripy.BVV(a, piece_size), wtf_expr) return wtf_ex...
Python
nomic_cornstack_python_v1
for i in s begin if i == s at k - 1 begin append l s at k - 1 end else begin append l string * end end print *l sep=string
for i in s: if i == s[k - 1]: l.append(s[k - 1]) else: l.append("*") print(*l, sep="")
Python
zaydzuhri_stack_edu_python
function broadcast_not_equal lhs=none rhs=none name=none attr=none out=none **kwargs begin return tuple 0 end function
def broadcast_not_equal(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs): return (0,)
Python
nomic_cornstack_python_v1
function getalllearnedinfo self expected_state=none timeout=none begin call call_operation string getAllLearnedInfo expected_state timeout end function
def getalllearnedinfo(self, expected_state=None, timeout=None): super(IxnLdpTargetedRouterV6Emulation, self).call_operation('getAllLearnedInfo', expected_state, timeout)
Python
nomic_cornstack_python_v1
function index begin return call render_template string landing.html end function
def index(): return render_template('landing.html')
Python
nomic_cornstack_python_v1
comment Lesson 3 - Variable pointing to functions function BuyMe what begin print string Give me what end function call BuyMe string a new car set StealForMe = BuyMe print type StealForMe call StealForMe string a new car function go_left *args begin print string PLACEHOLDER - turning left with *args end function functi...
# Lesson 3 - Variable pointing to functions def BuyMe(what): print('Give me', what) BuyMe('a new car') StealForMe = BuyMe print(type(StealForMe)) StealForMe("a new car") def go_left(*args): print('PLACEHOLDER - turning left with', *args) def go_right(*args): print('PLACEHOLDER - ...
Python
zaydzuhri_stack_edu_python
import numpy as np import tkinter as tk import random from rubiks_print_2x2 import * class RubiksCube2x2 begin string Class for interacting with a Rubik's Cube Methods: load_cube mix_up_cube manipulate cube: rot_left rot_right rot_upper rot_bottom rot_front checks: is_complete set color_key = dict 0 string whi ; 1 stri...
import numpy as np import tkinter as tk import random from rubiks_print_2x2 import * class RubiksCube2x2: """ Class for interacting with a Rubik's Cube Methods: load_cube mix_up_cube manipulate cube: rot_left rot_right rot_upper rot_bottom rot_front ...
Python
zaydzuhri_stack_edu_python
function test_GradientDescentOptimizer begin pass string optimizer = GradientDescentOptimizer(learning_rate=0.1) print(optimizer) loss = "TODO" optimizer.minimize(loss) sess = session.Session() sess.run(optimizer) end function
def test_GradientDescentOptimizer(): pass """ optimizer = GradientDescentOptimizer(learning_rate=0.1) print(optimizer) loss = "TODO" optimizer.minimize(loss) sess = session.Session() sess.run(optimizer) """
Python
nomic_cornstack_python_v1
function writing filename l begin with open filename string w as f begin for line in l begin write f strip line write f string end end end function
def writing(filename, l): with open (filename, 'w') as f: for line in l: f.write(line.strip()) f.write("\n")
Python
nomic_cornstack_python_v1
function get_mart dataset=string mmusculus_gene_ensembl begin if not dataset in _marts begin set _marts at dataset = call call with_mode NO_CONVERSION useMart string ensembl dataset=dataset end return _marts at dataset end function
def get_mart( dataset = "mmusculus_gene_ensembl" ): if not dataset in _marts: _marts[ dataset ] = rpy.with_mode( rpy.NO_CONVERSION, rpy.r.useMart )( "ensembl", dataset = dataset ) return _marts[ dataset ]
Python
nomic_cornstack_python_v1
function update self state action nextState reward begin set qValue = call getQValue state action set sample = reward + gamma * call computeValueFromQValues nextState set weights at tuple state action = 1 - alpha * qValue + alpha * sample end function
def update(self, state, action, nextState, reward): qValue = self.getQValue(state, action) sample = (reward + self.gamma * self.computeValueFromQValues(nextState)) self.weights[(state, action)] = ((1 - self.alpha) * qValue) + (self.alpha * sample)
Python
nomic_cornstack_python_v1
from subprocess import Popen , check_call from time import time , sleep import os from os import remove import pandas as pd from datetime import datetime , timedelta from numpy import empty , array , sum as np_sum , float32 , timedelta64 , Inf , datetime64 , zeros from io import StringIO from warnings import warn from ...
from subprocess import Popen, check_call from time import time, sleep import os from os import remove import pandas as pd from datetime import datetime, timedelta from numpy import empty, array, sum as np_sum, float32, timedelta64,Inf, datetime64, zeros from io import StringIO from warnings import warn from pandas.plo...
Python
zaydzuhri_stack_edu_python
comment testing tkinter gui import Tkinter as tk import ttk import random import threading import time function change_command_callback event=none root=none comboboxes=list entries=list regrid=list begin print string ------------CHANGED COMMAND------------ comment destroy all previous entries for ent in entries begin...
# testing tkinter gui import Tkinter as tk import ttk import random import threading import time def change_command_callback(event=None, root=None, comboboxes=[], entries=[], regrid=[]): print('------------CHANGED COMMAND------------') # destroy all previous entries for ent in entries: l, e = ent ...
Python
zaydzuhri_stack_edu_python
string Write a program that generates the 26-line block of letters partially shown below. abcdefghijklmnopqrstuvwxyz bcdefghijklmnopqrstuvwxyza cdefghijklmnopqrstuvwxyzab ... yzabcdefghijklmnopqrstuvwx zabcdefghijklmnopqrstuvwxy abcdefghijklmnopqrstuvwxyz comment input words from a to z set input_words = string abcdefg...
''' Write a program that generates the 26-line block of letters partially shown below. abcdefghijklmnopqrstuvwxyz bcdefghijklmnopqrstuvwxyza cdefghijklmnopqrstuvwxyzab ... yzabcdefghijklmnopqrstuvwx zabcdefghijklmnopqrstuvwxy abcdefghijklmnopqrstuvwxyz ''' input_words = "abcdefghijklmnopqrstuvwxyz" ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python set S = input set yy = integer S at slice 0 : 2 : set mm = integer S at slice 2 : : set yymm = false set mmyy = false if yy > 0 and yy < 13 begin set mmyy = true end if mm > 0 and mm < 13 begin set yymm = true end if yymm and mmyy begin print string AMBIGUOUS end else if yymm and not mmyy ...
#!/usr/bin/env python S = input() yy = int(S[0:2]) mm = int(S[2:]) yymm = False mmyy = False if yy > 0 and yy < 13: mmyy = True if mm > 0 and mm < 13: yymm = True if yymm and mmyy : print("AMBIGUOUS") elif yymm and not mmyy: print("YYMM") elif not yymm and mmyy: print("MMYY") else: print("N...
Python
zaydzuhri_stack_edu_python
function trunc input begin return call trunc input end function
def trunc(input): return F.trunc(input)
Python
nomic_cornstack_python_v1
function FileButtonBranch self event=none begin if call GetSurface string VESFile or call GetSurface string ShellScript begin call CloseFiles end else begin call ChooseDirectory end end function
def FileButtonBranch(self, event = None): if self.state.GetSurface("VESFile") or \ self.state.GetSurface("ShellScript"): self.CloseFiles() else: self.ChooseDirectory()
Python
nomic_cornstack_python_v1
comment Class for a Cell in the TemporalMemory data structure import numpy as np from Synapse import Synapse from SDR import SDR import random class Cell extends object begin function __init__ self numSegments begin comment links to other cells (x,y,z) with Permanence values : (x,y,z,p) comment list of 'links' to cells...
# Class for a Cell in the TemporalMemory data structure import numpy as np from Synapse import Synapse from SDR import SDR import random class Cell(object): def __init__(self,numSegments): # links to other cells (x,y,z) with Permanence values : (x,y,z,p) self.feeds = [] # list of 'links' to cells ...
Python
zaydzuhri_stack_edu_python
comment @Cnic 2014.12.27 comment 反向块增长 import numpy as np import time comment 自定义类-- class Block begin function __init__ self a=tuple 0 0 width=2 num=0 begin string 生成一个正方形abcd,num为代号,a为左上角点,宽度为width = 1,矩形包括点数pn = 4,flag为标志位, set num = num set width = width set a = a set b = tuple a at 0 a at 1 + width set c = tuple a...
#@Cnic 2014.12.27 #反向块增长 import numpy as np import time #自定义类-- class Block: def __init__(self, a = (0,0), width = 2,num=0): ''' 生成一个正方形abcd,num为代号,a为左上角点,宽度为width = 1,矩形包括点数pn = 4,flag为标志位,''' self.num = num self.width = width self.a = a self.b = (a[0],a[1]+width) self.c = (a[0]+width,a[1]) self.d = (...
Python
zaydzuhri_stack_edu_python
function shortest list1 begin return min list1 key=len end function set list = list set num = integer input string How many strings do you want to enter? : for i in range 1 num + 1 begin set s = input string Enter a string: append list s end print format string The strings are: {} list print string The shortest string...
def shortest(list1) : return (min(list1,key=len)) list = [] num = int(input("How many strings do you want to enter? : ")) for i in range(1,num+1): s=input("Enter a string: ") list.append(s) print("The strings are: {}".format(list)) print("The shortest string in the list is :",shortest(list))
Python
zaydzuhri_stack_edu_python
comment Import for testing import plotly.express as px import plotly.graph_objs as go from plotly.offline import plot import json import pandas as pd from plotly.subplots import make_subplots comment long form data for 2018 and 2019 each store connected to one closed store set long2018 = read csv string ../static/csv/l...
# Import for testing import plotly.express as px import plotly.graph_objs as go from plotly.offline import plot import json import pandas as pd from plotly.subplots import make_subplots # long form data for 2018 and 2019 each store connected to one closed store long2018 = pd.read_csv('../static/csv/long_format_2018.cs...
Python
zaydzuhri_stack_edu_python
function fit_topic_model self num_topics=10 chunk_size=none visualise=false begin set docs = list comprehension message at string message for message in messages comment set object level topic model set topic_model = call LDAModel docs num_topics chunk_size=chunk_size if visualise begin call visualise end end function
def fit_topic_model(self, num_topics=10, chunk_size=None, visualise=False): docs = [message['message'] for message in self.messages] # set object level topic model self.topic_model = topic_modelling.LDAModel( docs, num_topics, chunk_size=chunk_size) if visualise: ...
Python
nomic_cornstack_python_v1
function revert self paths recurse=false begin call svn_client_revert call _build_path_list paths recurse client iterpool clear iterpool end function
def revert(self, paths, recurse = False): svn_client_revert(self._build_path_list(paths), recurse, self.client, self.iterpool) self.iterpool.clear()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun May 5 11:56:04 2019 @author: Pavan S Gowda import numpy as np import cv2 as cv set face = call CascadeClassifier string haarcascade_frontalface_default.xml set eye = call CascadeClassifier string haarcascade_eye.xml set img = call imread string fg.jpg set gray = call ...
# -*- coding: utf-8 -*- """ Created on Sun May 5 11:56:04 2019 @author: Pavan S Gowda """ import numpy as np import cv2 as cv face=cv.CascadeClassifier('haarcascade_frontalface_default.xml') eye=cv.CascadeClassifier('haarcascade_eye.xml') img=cv.imread('fg.jpg') gray=cv.cvtColor(img,cv.COLOR_BGR2G...
Python
zaydzuhri_stack_edu_python
comment Reto # 1 - Semana 1-2 comment Tema: Empacadora de suministros comment Autor: Pablo Jose Torres Mojica comment Cohorte: 18/05/2021 comment Objetivo: Determinar el tamaño adecuado de la bolsa comment para un grupo de suministros dada la cantidad comment de los mismos. function get_supply_group begin set supply_gr...
# Reto # 1 - Semana 1-2 # Tema: Empacadora de suministros # Autor: Pablo Jose Torres Mojica # Cohorte: 18/05/2021 # Objetivo: Determinar el tamaño adecuado de la bolsa # para un grupo de suministros dada la cantidad # de los mismos. def get_supply_group(): supply_group = {'Laces': abs(int(input()))} ...
Python
zaydzuhri_stack_edu_python
function prepare_dataset self begin set h5_filename = path + name + file_extension call print_timestamp call set_geometry_parameters print string Loading data from file %s % h5_filename set f = call File h5_filename string r comment self.data = rw.h5read(h5_filename, self.data_entry).values()[0] set d0 = f at data_entr...
def prepare_dataset(self): h5_filename = self.path + self.name + self.file_extension self.print_timestamp() self.set_geometry_parameters() print('Loading data from file %s' % h5_filename) f = h5py.File(h5_filename, 'r') # self.data = rw.h5read(h5_filename, self.data_en...
Python
nomic_cornstack_python_v1
function load consumer_key=none consumer_secret=none access_token=none access_secret=none project_dir=none out_dir=none out_extension=none task_file=none full_user_mentions=false appdata_token=APP_DATA_TOKEN user_lookup_interval=DEFAULT_EXPAND_USERS_INTERVAL appdata_timeout=DEFAULT_APP_DATA_CONNECTION_TIMEOUT task_gen=...
def load(consumer_key=None, consumer_secret=None, access_token=None, access_secret=None, project_dir=None, out_dir=None, out_extension=None, task_file=None, full_user_mentions=False, appdata_token: str = APP_DATA_TOKEN, user_lookup_interval=DEFAULT_EXPAND_USERS_INTERVAL, app...
Python
nomic_cornstack_python_v1
from Services.db_connection import connection function insert player_season begin with call cursor as cursor begin comment Create a new Player_Season record set sql = string INSERT INTO player_season (p_id, s_id, t_id, age) VALUES (%s, %s, %s, %s) execute cursor sql tuple p_id s_id t_id age end comment connection is no...
from Services.db_connection import connection def insert(player_season): with connection.cursor() as cursor: # Create a new Player_Season record sql = "INSERT INTO player_season (p_id, s_id, t_id, age) VALUES (%s, %s, %s, %s)" cursor.execute(sql, (player_season.p_id, player_season.s_id, pl...
Python
zaydzuhri_stack_edu_python
function from_string cls string default_func=none begin string Construct a NetAddress from a string and return a (host, port) pair. If either (or both) is missing and default_func is provided, it is called with ServicePart.HOST or ServicePart.PORT to get a default. if not is instance string str begin raise call TypeErr...
def from_string(cls, string, *, default_func=None): '''Construct a NetAddress from a string and return a (host, port) pair. If either (or both) is missing and default_func is provided, it is called with ServicePart.HOST or ServicePart.PORT to get a default. ''' if not isinstance...
Python
jtatman_500k
class Veiculo begin function __init__ self modelo ano qtde_litros_no_tanque begin set __modelo = modelo set __ano = ano set __qtde_litros_no_tanque = qtde_litros_no_tanque end function function getModelo self begin return __modelo end function function setModelo self modelo begin set __modelo = modelo end function func...
class Veiculo: def __init__(self,modelo,ano,qtde_litros_no_tanque): self.__modelo=modelo self.__ano=ano self.__qtde_litros_no_tanque=qtde_litros_no_tanque def getModelo(self): return self.__modelo def setModelo(self,modelo): self.__modelo=modelo def...
Python
zaydzuhri_stack_edu_python
function custom_heartbeat_attrs self begin return dict end function
def custom_heartbeat_attrs(self): return {}
Python
nomic_cornstack_python_v1
function compute_overlap self begin set m_v = 1 / N * absolute dot T set q_v = 1 / N * dot T set m_u = 1 / M * absolute dot T set q_u = 1 / M * dot T comment Store old overlaps set tuple m_v_old q_v_old m_u_old q_u_old = tuple m_v q_v m_u q_u comment Update them set tuple m_v q_v m_u q_u = tuple m_v q_v m_u q_u comment...
def compute_overlap(self): m_v = 1/self.N * np.abs(self.V_hat.dot(self.V.T)) q_v = 1/self.N * self.V_hat.dot(self.V_hat.T) m_u = 1/self.M * np.abs(self.U_hat.dot(self.U.T)) q_u = 1/self.M * self.U_hat.dot(self.U_hat.T) # Store old overlaps self.m_v_old, self.q_v_old, sel...
Python
nomic_cornstack_python_v1
from numpy import * set a = array eval input string presentes: set b = array eval input string faltantes: set i = 0 set x = 1 while b at i != max b begin set i = i + 1 set x = x + 1 end print x
from numpy import* a=array(eval(input("presentes:"))) b=array(eval(input("faltantes:"))) i=0 x=1 while(b[i]!=max(b)): i=i+1 x=x+1 print(x)
Python
zaydzuhri_stack_edu_python
function prime number begin string Проверка на простоту set i = 2 while i * i <= number begin if number % i == 0 begin return false end set i = i + 1 end return true end function print call prime integer input
def prime(number): """Проверка на простоту""" i = 2 while i * i <= number: if number % i == 0: return False i += 1 return True print(prime(int(input())))
Python
zaydzuhri_stack_edu_python
for i in range 0 10 begin set x = integer input string Digite um número para a matriz: append matriz x end sort matriz print matriz
for i in range(0,10): x = int(input('Digite um número para a matriz: ')) matriz.append(x) matriz.sort() print(matriz)
Python
zaydzuhri_stack_edu_python
comment -> voltage:float function get_voltage self begin if voltage is none begin raise call RuntimeError string No voltage reading received yet end return voltage end function
def get_voltage(self) -> float: # -> voltage:float if self.readings.voltage is None: raise RuntimeError("No voltage reading received yet") return self.readings.voltage
Python
nomic_cornstack_python_v1
string Ce fichier contient la classe des amulettes dérivé de la classe Item from Item import * class Amulet extends Item begin function __init__ self name effect actionPoints maxUseTime begin call __init__ self name set effect = effect set actionPoints = actionPoints set remainingUseTime = maxUseTime set maxUseTime = m...
"""Ce fichier contient la classe des amulettes dérivé de la classe Item""" from Item import *; class Amulet(Item): def __init__(self,name,effect,actionPoints,maxUseTime): Item.__init__(self,name); self.effect = effect; self.actionPoints = actionPoints; self.remainingUseTime = maxUs...
Python
zaydzuhri_stack_edu_python
function build_flax_module cls hparams=none dataset_metadata=none begin print string in build_flax_module: has_discriminator get hparams string has_discriminator false set hparams = call build_flax_module hparams dataset_metadata set model_dtype = jax_dtype return tuple partial blocks_per_group=blocks_per_group channel...
def build_flax_module(cls, hparams=None, dataset_metadata=None): print( 'in build_flax_module: has_discriminator', hparams.get('has_discriminator', False), ) hparams = super(WideResnet, cls).build_flax_module(hparams, dataset_metadata) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import pickle from collections import defaultdict import matplotlib.pyplot as plt import numpy as np comment load dictionary set data_enron = load pickle open string final_project_dataset.pkl string r
#!/usr/bin/python import pickle from collections import defaultdict import matplotlib.pyplot as plt import numpy as np #load dictionary data_enron = pickle.load(open("final_project_dataset.pkl", "r"))
Python
zaydzuhri_stack_edu_python
import datetime import time import keyword if __name__ == string __main__ begin print now print time print string %s % time print call iskeyword string async set String = string Hell/oWorld end
import datetime import time import keyword if __name__ == "__main__": print (datetime.datetime.now) print(time.time()) print("%s" % time.time()) print(keyword.iskeyword("async")) String = "Hell/oWorld"
Python
zaydzuhri_stack_edu_python
function parse_temp temp begin set temp = right strip temp string * if temp at - 1 == string * begin set temp = temp at slice : - 1 : end return decimal temp end function
def parse_temp(temp): temp = temp.rstrip('*') if temp[-1] == '*': temp = temp[:-1] return float(temp)
Python
nomic_cornstack_python_v1
comment Definition for singly-linked list. comment class ListNode: comment def __init__(self, val=0, next=None): comment self.val = val comment self.next = next class Solution begin comment find the mid point of the list comment break the mid point link comment reverse the second half of the list comment alter between ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: # find the mid point of the list # break the mid point link # reverse the second half of the list # alter between the two lists ...
Python
zaydzuhri_stack_edu_python
function get_db self id begin set id = string id comment perform cache lookup for this server try begin set ref = _cache at id return ref end comment the object may have been garbage collected while we were referencing it, or just doesn't exist except KeyError begin pass end comment register models set handle = call _e...
def get_db(self, id: Any) -> DatabaseEngine: id = str(id) try: #perform cache lookup for this server ref = self._cache[id] return ref except KeyError: #the object may have been garbage collected while we were referencing it, or just doesn't exist pass ...
Python
nomic_cornstack_python_v1
function set_page_mode self mode begin if mode in pagemodes begin raise call PDFSurgeException format string Invalid PageMode. Must be one of {0} join string , pagemodes end call set_root_property string /PageMode mode end function
def set_page_mode(self, mode): if mode in pagemodes: raise PDFSurgeException('Invalid PageMode. Must be one of {0}'.format(', '.join(pagemodes))) self.set_root_property('/PageMode', mode)
Python
nomic_cornstack_python_v1
function test_equilateral self begin assert equal call triangle_classification 1 1 1 string Equilateral Triangle assert equal call triangle_classification 3.33 3.33 3.33 string Equilateral Triangle assert not equal call triangle_classification 3.33 3.33 3.333 string Equilateral Triangle assert equal call triangle_class...
def test_equilateral(self): self.assertEqual(triangle_classification(1, 1, 1), 'Equilateral Triangle') self.assertEqual(triangle_classification(3.33, 3.33, 3.33), 'Equilateral Triangle') self.assertNotEqual(triangle_classification(3.33, 3.33, 3.333), 'Equilateral Triangle') self.asse...
Python
nomic_cornstack_python_v1
set arr = list 2 6 * 10
arr = [2, 6] * 10
Python
greatdarklord_python_dataset
function GetOutputDirection self begin return call itkResampleImageFilterVIUC3VIUC3_GetOutputDirection self end function
def GetOutputDirection(self) -> "itkMatrixD33 const &": return _itkResampleImageFilterPython.itkResampleImageFilterVIUC3VIUC3_GetOutputDirection(self)
Python
nomic_cornstack_python_v1
function click_compare_this_product_button self begin call click end function
def click_compare_this_product_button(self) -> None: self._driver.find_element(*LocatorsProductPage.COMPARE_THIS_PRODUCT).click()
Python
nomic_cornstack_python_v1
function get_problem_hash self begin comment NOTE: import delayed to enable MP import tensorflow as tf global _problem_hash_cache if _problem_hash_cache is none begin set _problem_hash_cache = dict end if problem_type not in _problem_hash_cache begin set problem_hash_one = call to_hash_bucket_strong problem_type PROBL...
def get_problem_hash(self) -> ProblemTypeIntList: # NOTE: import delayed to enable MP import tensorflow as tf global _problem_hash_cache if _problem_hash_cache is None: _problem_hash_cache = {} if self.agent.problem_type not in _problem_hash_cache: proble...
Python
nomic_cornstack_python_v1
class User begin string User class to allows for creation of new instances of users set user_List = list function __init__ self first_name last_name phone_number email password begin string __init__ method that helps us define properties for our objects. Args: first_name: New user first name. last_name : New user last...
class User: ''' User class to allows for creation of new instances of users ''' user_List = [] def __init__(self,first_name,last_name,phone_number,email,password): ''' __init__ method that helps us define properties for our objects. Args: first_name: New user fi...
Python
zaydzuhri_stack_edu_python
comment 815. 公交路线 import collections class Solution begin function numBusesToDestination self routes source target begin set bus_map = dict for i in range length routes begin for s in routes at i begin if s not in bus_map begin set bus_map at s = list end append bus_map at s i end end if source == target begin return...
# 815. 公交路线 import collections class Solution: def numBusesToDestination(self, routes: list[list[int]], source: int, target: int) -> int: bus_map = {} for i in range(len(routes)): for s in routes[i]: if s not in bus_map: bus_map[s] = [] ...
Python
zaydzuhri_stack_edu_python
import time import torch import argparse import os from utils import load_classes from data.datas import VOC_Dataset from model.yolov3_anchor import YOLOv3 string Python의 ArgParse 모듈을 사용 --images 는 이 argument에 해당하는 값을 넣기 원할 때 먼저 나와야 하는 flag이다 dest: argument에 접근할 수 있는 이름, args.images로 해당 argument의 값에 접근할 수 있다 help: 단순히 ...
import time import torch import argparse import os from utils import load_classes from data.datas import VOC_Dataset from model.yolov3_anchor import YOLOv3 ''' Python의 ArgParse 모듈을 사용 --images 는 이 argument에 해당하는 값을 넣기 원할 때 먼저 나와야 하는 flag이다 dest: argument에 접근할 수 있는 이름, args.images로 해당 argument의 값에 접근할 수 ...
Python
zaydzuhri_stack_edu_python
function mp_table x y begin for i in range 1 y + 1 begin print string { x } * { i } = { x * i } end return end function
def mp_table(x, y): for i in range(1,y+1): print(f'{x} * {i} = {x*i}') return
Python
nomic_cornstack_python_v1
import speech_recognition as sr set r = call Recognizer with call Microphone as source begin set audio = call listen source end try begin call SetValue call recognize_google audio end except UnknownValueError begin print string Google Speech Recognition could not understank what you said end except RequestError as e be...
import speech_recognition as sr r= sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) try: self.txt.SetValue(r.recognize_google(audio)) except sr.UnknownValueError: print ("Google Speech Recognition could not understank what you said") except sr.RequestError as e: print ("Could no...
Python
zaydzuhri_stack_edu_python
function make_absolute_url path begin set site = call get_current set protocol = string http:// set base_url = format string {protocol}{site_url} protocol=protocol site_url=domain return url join base_url path end function
def make_absolute_url(path): site = Site.objects.get_current() protocol = 'http://' base_url = '{protocol}{site_url}'.format( protocol=protocol, site_url=site.domain ) return urljoin(base_url, path)
Python
nomic_cornstack_python_v1
from tkinter import * set root = call Tk title root string Mergi GUI call geometry string 640x480 comment chkvar에 int형으로 값을 저장한다. set chkvar = call IntVar set chkbox = call Checkbutton root text=string 오늘 하루 보지 않기 variable=chkvar comment chkbox.select() #자동 선택 처리 comment chkbox.deselect() #선택 헤제 처리 call pack set chkvar...
from tkinter import * root = Tk() root.title("Mergi GUI") root.geometry("640x480") chkvar = IntVar() #chkvar에 int형으로 값을 저장한다. chkbox = Checkbutton(root, text="오늘 하루 보지 않기", variable=chkvar) # chkbox.select() #자동 선택 처리 # chkbox.deselect() #선택 헤제 처리 chkbox.pack() chkvar2 = IntVar() chkbox2 = Checkbutton(root, text=...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 import tensorflow as tf import numpy as np function build_lstm X_input=none batch_size=32 images_num=20 num_layers=4 num_units=256 * 2 dropout_rate=0.6 train=true name=string lstm reuse=none begin with call variable_scope name reuse=reuse begin with call variable_scope string LSTM_layer begin set c...
#coding:utf-8 import tensorflow as tf import numpy as np def build_lstm(X_input=None, batch_size=32, images_num=20, num_layers=4, num_units=256*2, dropout_rate=0.6, train=True, name='lstm', reuse=None,): with tf.variable_scope(name, reuse=reuse): with tf.variable_scope('LSTM_layer'): ...
Python
zaydzuhri_stack_edu_python
function non_max_suppression prediction conf_thres=0.5 nms_thres=0.5 begin comment (pixels) minimum box width and height set min_wh = 2 set output = list none * length prediction for tuple image_i pred in enumerate prediction begin comment Multiply conf by class conf to get combined confidence set tuple class_conf clas...
def non_max_suppression(prediction, conf_thres=0.5, nms_thres=0.5): min_wh = 2 # (pixels) minimum box width and height output = [None] * len(prediction) for image_i, pred in enumerate(prediction): # Multiply conf by class conf to get combined confidence class_conf, class_pred = pred[:, 5:]...
Python
nomic_cornstack_python_v1
string Program to check that the two matrix that are given are identical or not string for two matrix to be equal, the number of rown and columns should be equal as well as there elemnts should be equal too function aresame A B begin comment 4*4 matrix set n = 4 for i in range n begin for j in range n begin if A at i a...
''' Program to check that the two matrix that are given are identical or not ''' ''' for two matrix to be equal, the number of rown and columns should be equal as well as there elemnts should be equal too ''' def aresame(A,B): n = 4 #4*4 matrix for i in range(n): for j in range(n): if (A[...
Python
zaydzuhri_stack_edu_python
class Solution begin function rob self nums begin comment Dynamic Programming Method: comment Test case if list is empty or null if nums == none or length nums == 0 begin return 0 end comment Test case if length of nums is only 1: if length nums == 1 begin return nums at 0 end comment If the length of nums is more than...
class Solution: def rob(self, nums: List[int]) -> int: # Dynamic Programming Method: # Test case if list is empty or null if nums == None or len(nums) == 0: return 0 # Test case if length of nums is only 1: if len(nums) == 1: return nums[0] ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2 import socket function print_machine_info begin set host_name = call gethostname set ip_address = call gethostbyname host_name end function
#!/usr/bin/env python2 import socket def print_machine_info(): host_name = socket.gethostname() ip_address = socket.gethostbyname(host_name)
Python
zaydzuhri_stack_edu_python
comment 3-10. Every Function: Think of something you could store in a list. For example, you could make a list of mountains, rivers, countries, cities, languages, or anything else you’d like. Write a program that creates a list containing these items and then uses each function introduced in this chapter at least once....
# 3-10. Every Function: Think of something you could store in a list. For example, you could make a list of mountains, rivers, countries, cities, languages, or anything else you’d like. Write a program that creates a list containing these items and then uses each function introduced in this chapter at least once. list...
Python
zaydzuhri_stack_edu_python
function cross_validation y x cat_cols method_flag k_indices k degree=none lambda_=none gamma=none max_iters=none begin set train_indices = call ravel set x_train = x at train_indices set y_train = y at train_indices set x_val = x at k_indices at k set y_val = y at k_indices at k set tuple x_train_num x_train_cat = cal...
def cross_validation(y, x, cat_cols, method_flag, k_indices, k, degree = None, lambda_ = None, gamma = None, max_iters = None): train_indices = np.delete(k_indices,k,axis = 0).ravel() x_train = x[train_indices] y_train = y[train_indices] x_val = x[k_indices[k]] y_val = y[k_indices[k]] x_train_...
Python
nomic_cornstack_python_v1
function readLong self begin return call _readPrimitive c_int64 end function
def readLong(self): return self._readPrimitive(ctypes.c_int64)
Python
nomic_cornstack_python_v1
function __init__ self url user password begin set non_id_char = compile string [^_0-9a-zA-Z] function _name_mangle name begin return sub string _ name end function class DataNode extends object begin function __init__ self begin comment XML attributes and child elements set _attrs = dict comment child text data set d...
def __init__(self, url, user, password): non_id_char = re.compile('[^_0-9a-zA-Z]') def _name_mangle(name): return non_id_char.sub('_', name) class DataNode(object): def __init__(self): self._attrs = {} # XML attributes and child elements ...
Python
nomic_cornstack_python_v1
comment Given a character array, replace all the comment spaces with '%20'"s, assume array is big enough to comment hold additional characters comment O(n) two pass runtime soln, O(1) space function better_insert20 arr len_we_know begin set num_spaces = 0 for c in arr begin if c == string begin set num_spaces = num_sp...
# Given a character array, replace all the # spaces with '%20'"s, assume array is big enough to # hold additional characters # O(n) two pass runtime soln, O(1) space def better_insert20(arr, len_we_know): num_spaces = 0 for c in arr: if c == ' ': num_spaces += 1 # %20 is 3 chars, but one stays i...
Python
zaydzuhri_stack_edu_python
function off self state=none begin if state is none begin if _state == Off begin return true end return _state end if is instance state bool begin if not state begin raise call ValueError string when set off state, bool value should be False end set _state = On return true end if is instance state StateType begin if st...
def off(self, state: Optional[Union[bool, StateType]] = None ) -> Union[bool, StateType]: if state is None: if self._state == StateType.Off: return True return self._state if isinstance(state, bool): if not state: raise Val...
Python
nomic_cornstack_python_v1
function max_mireds self begin return ceil call color_temperature_kelvin_to_mired min_kelvin end function
def max_mireds(self) -> int: return math.ceil( color_util.color_temperature_kelvin_to_mired(self._lamp.min_kelvin) )
Python
nomic_cornstack_python_v1
string 混入(Mixin) class SetOnce begin set __slots__ = tuple function __setitem__ self key value begin if key in self begin raise call KeyError string 不允许为已有的键重新赋值 end return call __setitem__ key value end function end class class MyDict extends SetOnce dict begin pass end class function main begin set items = call MyDi...
""" 混入(Mixin) """ class SetOnce(): __slots__ = () def __setitem__(self, key, value): if key in self: raise KeyError('不允许为已有的键重新赋值') return super().__setitem__(key, value) class MyDict(SetOnce, dict): pass def main(): items = MyDict() try: items['username'] = 'luohao' items['username'] = 'wangdac...
Python
zaydzuhri_stack_edu_python
function search_by_date_ranges dates begin set searched_entries = list for entry in all_entries begin if string parse time dates at 0 string %d/%m/%Y <= string parse time entry at string date string %d/%m/%Y <= string parse time dates at 1 string %d/%m/%Y begin append searched_entries entry end end return searched_ent...
def search_by_date_ranges(dates): searched_entries = [] for entry in all_entries: if datetime.strptime(dates[0], '%d/%m/%Y') <= \ datetime.strptime(entry['date'], '%d/%m/%Y') \ <= datetime.strptime(dates[1], '%d/%m/%Y'): searched_entries.append(entry) retu...
Python
nomic_cornstack_python_v1
function plot_policies δ ρ γ rh rl rmin xaxis=string δ yaxis=string γ prec=100 begin set tuple fig ax = call subplots 1 3 sharey=string row figsize=tuple 6.5 2 comment colors set ov = 0.6 set risky_opt_color = tuple 1.0 ov 0 set cautious_opt_color = tuple 1.0 0 ov set both_sus_color = tuple ov ov 1.0 set cautious_sus_c...
def plot_policies(δ, ρ, γ, rh, rl, rmin, xaxis="δ", yaxis="γ", prec=100): fig, ax = plt.subplots(1, 3, sharey='row', figsize=(6.5, 2)) # colors ov = 0.6 risky_opt_color = (1.0, ov, 0) cautious_opt_color = (1.0, 0, ov) both_sus_color = (ov, ov, 1.0) cautious_sus_color = (0...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- set __author__ = tuple string Anja Stene, Student NMBU string Ghazal Azadi, Student NMBU set __email__ = tuple string anja.stene@nmbu.no string ghazal.azadi@nmbu.no from biosim.cell import Lowland , Highland , Water , Desert from biosim.animal import Carnivore , Herbivore import numpy as n...
# -*- coding: utf-8 -*- __author__ = "Anja Stene, Student NMBU", "Ghazal Azadi, Student NMBU" __email__ = "anja.stene@nmbu.no", "ghazal.azadi@nmbu.no" from biosim.cell import Lowland, Highland, Water, Desert from biosim.animal import Carnivore, Herbivore import numpy as np class Island: """ Island class cre...
Python
zaydzuhri_stack_edu_python
from string import ascii_lowercase set alphabet = ascii_lowercase set ASCII_BIT_COUNT = 7 set BASE = 2 set alphabet_size = length alphabet set alphabet_upper = upper alphabet class CaesarEncoderAndDecoder begin function __init__ self shift begin set shift = integer shift % alphabet_size end function function getneword ...
from string import ascii_lowercase alphabet = ascii_lowercase ASCII_BIT_COUNT = 7 BASE = 2 alphabet_size = len(alphabet) alphabet_upper = alphabet.upper() class CaesarEncoderAndDecoder: def __init__(self, shift): self.shift = int(shift) % alphabet_size def getneword(self, ord, shift): new...
Python
zaydzuhri_stack_edu_python
function process_item self item spider begin set session = call Session set data = data keyword item set jsond = call JsonData jsond=dumps dictionary item try begin add session data commit session add session jsond commit session end except any begin rollback session raise end finally begin close session end return ite...
def process_item(self, item, spider): session = self.Session() data = Data(**item) jsond = JsonData(jsond=json.dumps(dict(item))) try: session.add(data) session.commit() session.add(jsond) session.commit() except: ...
Python
nomic_cornstack_python_v1
import socket set s = call socket AF_INET SOCK_STREAM set host = string 127.0.0.1 set port = 12345 call bind tuple host port call listen 5 print string server started while true begin set tuple conn addr = call accept print string server got connection from: { addr } call send encode string Hello from server set respon...
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = "127.0.0.1" port = 12345 s.bind((host, port)) s.listen(5) print("server started") while True: conn, addr = s.accept() print(f"server got connection from: {addr}") conn.send("Hello from server".encode()) responce = conn.recv(102...
Python
zaydzuhri_stack_edu_python
function discard self item begin try begin remove _data item end except ValueError begin pass end try else begin append __log__ call SetDiscard value=item end end function
def discard(self, item): try: self._data.remove(item) except ValueError: pass else: self.__log__.append(SetDiscard(value=item))
Python
nomic_cornstack_python_v1