code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function assert_dataset_equal ds1 ds2 msg=string Datasets unequal decimal=none begin call assert_equal keys ds1 keys ds2 string %s: different keys (%s vs %s) % tuple msg keys ds1 keys ds2 for k in keys ds1 begin call assert_dataobj_equal ds1 at k ds2 at k msg=msg decimal=decimal end call assert_equal keys info keys inf...
def assert_dataset_equal(ds1, ds2, msg="Datasets unequal", decimal=None): assert_equal(ds1.keys(), ds2.keys(), "%s: different keys (%s vs %s)" % (msg, ds1.keys(), ds2.keys())) for k in ds1.keys(): assert_dataobj_equal(ds1[k], ds2[k], msg=msg, decimal=decimal) assert_equal(ds1.info.k...
Python
nomic_cornstack_python_v1
set ns = decimal input string Geef aantal deeltjes s: set na = 6.02 * 10 ^ 23 set ms = 32.06 set mx1 = ms / na set nx = ns * na set mx2 = mx1 * nx print mx2 print mx1 + nx
ns = float(input(' Geef aantal deeltjes s: ')) na = 6.020 * (10 ** 23) ms = 32.06 mx1 = ms/na nx = ns * na mx2 = mx1 * nx print(mx2) print(mx1 + nx)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string [log stats in db] from pymongo import MongoClient function count_in_collection collection option=none begin string [summary] Args: collection ([type]): [collection] option ([type], optional): [option to search]. Defaults to None. Returns: [type]: [count] set items = dict if option ...
#!/usr/bin/env python3 """[log stats in db] """ from pymongo import MongoClient def count_in_collection(collection, option=None): """[summary] Args: collection ([type]): [collection] option ([type], optional): [option to search]. Defaults to None. Returns: [type]: [count]...
Python
zaydzuhri_stack_edu_python
function extract addon begin set attrs = tuple string id string name string created string last_updated string weekly_downloads string bayesian_rating string average_daily_users string status string type string is_disabled string hotness set d = dictionary zip attrs call call attrgetter *attrs addon comment Coerce the ...
def extract(addon): attrs = ('id', 'name', 'created', 'last_updated', 'weekly_downloads', 'bayesian_rating', 'average_daily_users', 'status', 'type', 'is_disabled', 'hotness') d = dict(zip(attrs, attrgetter(*attrs)(addon))) # Coerce the Translation into a string. d['name'] = un...
Python
nomic_cornstack_python_v1
function test_reciprocal_equivalence_dark self begin set test_v = linear space - 1 1 10 set test_i = call get_j_from_v test_v to_tup=true set ttest_v = call get_v_from_j test_i assert true call allclose test_v ttest_v end function
def test_reciprocal_equivalence_dark(self): test_v = np.linspace(-1, 1, 10) test_i = self.dark_hpc.get_j_from_v(test_v, to_tup=True) ttest_v = self.dark_hpc.get_v_from_j(test_i) self.assertTrue(np.allclose(test_v, ttest_v))
Python
nomic_cornstack_python_v1
function find_palindromes s begin comment Helper function to expand around the center function expand_around_center s left right begin while left >= 0 and right < length s and s at left == s at right begin append palindromes s at slice left : right + 1 : set left = left - 1 set right = right + 1 end end function set pa...
def find_palindromes(s): # Helper function to expand around the center def expand_around_center(s, left, right): while left >= 0 and right < len(s) and s[left] == s[right]: palindromes.append(s[left:right+1]) left -= 1 right += 1 palindromes = [] for i in ran...
Python
jtatman_500k
function get_env_setting setting begin try begin return environ at setting end except KeyError begin set error_msg = string Set the %s env variable % setting raise call ImproperlyConfigured error_msg end end function
def get_env_setting(setting): try: return os.environ[setting] except KeyError: error_msg = "Set the %s env variable" % setting raise ImproperlyConfigured(error_msg)
Python
nomic_cornstack_python_v1
string Write a module that enables the robots to easily recall their passwords through codes when they return home. The cipher grille and the ciphered password are represented as an array (tuple) of strings. Input: A cipher grille and a ciphered password as a tuples of strings. Output: The password as a string. functio...
''' Write a module that enables the robots to easily recall their passwords through codes when they return home. The cipher grille and the ciphered password are represented as an array (tuple) of strings. Input: A cipher grille and a ciphered password as a tuples of strings. Output: The password as a string. ''' de...
Python
zaydzuhri_stack_edu_python
comment Kintamasis ima duomenis is konsoleje ivestu rodmenu set tekstas = input string Iveskite raidžių seką: comment Kintamasis ima duomenis is konsoleje ivestu rodmenu, privalo buti skaicius set daliklis = integer input string Iveskite dalikli: comment Tikrinama ar ivesti duomenys atitinka uzduoties reikalavimus if 0...
#Kintamasis ima duomenis is konsoleje ivestu rodmenu tekstas = input("Iveskite raidžių seką:") #Kintamasis ima duomenis is konsoleje ivestu rodmenu, privalo buti skaicius daliklis = int(input("Iveskite dalikli:")) #Tikrinama ar ivesti duomenys atitinka uzduoties reikalavimus if(0 > daliklis and len(tekstas)%dalikl...
Python
zaydzuhri_stack_edu_python
import sys import requests class Api begin decorator classmethod function authenticate Api api_url user password begin set auth_url = format string {0}auth-token/ api_url set payload = dict string username user ; string password password set r = post auth_url data=payload set token = json r at string token set api = ca...
import sys import requests class Api(): @classmethod def authenticate(Api, api_url, user, password): auth_url = "{0}auth-token/".format(api_url) payload = {"username": user, "password": password} r = requests.post(auth_url, data=payload) token = r.json()["token"] api = ...
Python
zaydzuhri_stack_edu_python
function make_time_bc constraints derivative_fn hamiltonian independent_var begin set hamiltonian_free_final_time = all list comprehension call derivative_fn c independent_var == 0 for c in constraints at string terminal if hamiltonian_free_final_time begin return hamiltonian end else begin return none end end function
def make_time_bc(constraints, derivative_fn, hamiltonian, independent_var): hamiltonian_free_final_time = all([derivative_fn(c, independent_var) == 0 for c in constraints['terminal']]) if hamiltonian_free_final_time: return hamiltonian else: return None
Python
nomic_cornstack_python_v1
function smooth data grid factor=0.5 begin comment Make sure data matches grid if not call data_fits data begin raise call GeogridError string data provided does not fit the Geogrid provided end comment ---------------------------------------------------------------------------------------------- comment Smooth the dat...
def smooth(data, grid, factor=0.5): # Make sure data matches grid if not grid.data_fits(data): raise GeogridError('data provided does not fit the Geogrid provided') # ---------------------------------------------------------------------------------------------- # Smooth the data # # Get ...
Python
nomic_cornstack_python_v1
comment !python comment cython: boundscheck=False comment cython: wraparound=False comment cython: cdivision=True import numpy as np
#!python #cython: boundscheck=False #cython: wraparound=False #cython: cdivision=True import numpy as np
Python
zaydzuhri_stack_edu_python
function KS g rho=50.0 begin set g_max = max call atleast_2d g axis=- 1 at tuple slice : : newaxis set g_diff = g - g_max set exponents = exp rho * g_diff set summation = sum exponents axis=- 1 at tuple slice : : newaxis set KS = g_max + 1.0 / rho * log summation set dsum_dg = rho * exponents set dKS_dsum = 1.0 /...
def KS(g, rho=50.0): g_max = np.max(np.atleast_2d(g), axis=-1)[:, np.newaxis] g_diff = g - g_max exponents = np.exp(rho * g_diff) summation = np.sum(exponents, axis=-1)[:, np.newaxis] KS = g_max + 1.0 / rho * np.log(summation) dsum_dg = rho * exponents dKS_dsum = 1.0 / (rho * summation) ...
Python
nomic_cornstack_python_v1
from abc import ABC , abstractmethod class Sensor extends ABC begin function __init__ self machine objective key criteria begin set __machine = machine set __objective = objective set __key = key set __criteria = criteria end function decorator property function machine self begin return __machine end function decorato...
from abc import ABC, abstractmethod class Sensor(ABC): def __init__(self, machine, objective, key, criteria): self.__machine = machine self.__objective = objective self.__key = key self.__criteria = criteria @property def machine(self): return self.__machine @...
Python
zaydzuhri_stack_edu_python
import time import threading class Header begin function __init__ self seq_num ack_num syn ack fin max_window begin set seq_num = seq_num set ack_num = ack_num set syn = syn set ack = ack set fin = fin set max_window = max_window end function function bits self begin comment 11 bytes header set bits = format string {0:...
import time import threading class Header: def __init__(self, seq_num, ack_num, syn, ack, fin, max_window): self.seq_num = seq_num self.ack_num = ack_num self.syn = syn self.ack = ack self.fin = fin self.max_window = max_window def bits(self): #11 bytes...
Python
zaydzuhri_stack_edu_python
comment Tendo como dados de entrada a altura de uma pessoa, comment construa um algoritmo que calcule seu peso ideal, comment usando a seguinte fórmula: (72.7*altura) - 58 set altura = decimal input string Qual a sua altura? set peso_Ideal = 72.7 * altura - 58 print peso_Ideal
# Tendo como dados de entrada a altura de uma pessoa, # construa um algoritmo que calcule seu peso ideal, # usando a seguinte fórmula: (72.7*altura) - 58 altura = float(input('Qual a sua altura? ')) peso_Ideal = ((72.7*altura)-58) print (peso_Ideal)
Python
zaydzuhri_stack_edu_python
function get_res ds t_srs=none square=false begin set gt = call GetGeoTransform set ds_srs = call get_ds_srs ds comment This is Xres, Yres set res = list gt at 1 absolute gt at 5 if square begin set res = list mean np res mean np res end if t_srs is not none and not call IsSame t_srs begin if true begin comment This di...
def get_res(ds, t_srs=None, square=False): gt = ds.GetGeoTransform() ds_srs = get_ds_srs(ds) #This is Xres, Yres res = [gt[1], np.abs(gt[5])] if square: res = [np.mean(res), np.mean(res)] if t_srs is not None and not ds_srs.IsSame(t_srs): if True: #This diagonal appro...
Python
nomic_cornstack_python_v1
from kivy.app import App from kivy.uix.boxlayout import BoxLayout import random class Forca extends BoxLayout begin function __init__ self begin call loadWord call __init__ call loadScreen end function function loadWord self begin set words = list string banana string roupa string barco string mesa string computador st...
from kivy.app import App from kivy.uix.boxlayout import BoxLayout import random class Forca(BoxLayout): def __init__(self): self.loadWord() super(Forca, self).__init__() self.loadScreen() def loadWord(self): self.words = ["banana", "roupa", "barco", "mesa", "computador"...
Python
zaydzuhri_stack_edu_python
function test_db_dlc_device self begin comment Initializing key variables pass end function
def test_db_dlc_device(self): # Initializing key variables pass
Python
nomic_cornstack_python_v1
function filter_word_list words max_words begin set number_regex = compile string ^[0-9.-]+$ set filtered = list comprehension word for word in words if not call fullmatch word return filtered at slice : max_words : end function
def filter_word_list(words: List[str], max_words: int) -> List[str]: number_regex = re.compile("^[0-9.-]+$") filtered = [word for word in words if not number_regex.fullmatch(word)] return filtered[:max_words]
Python
nomic_cornstack_python_v1
function trimean data begin set tuple H1 M H2 = call quartiles data scheme=1 return H1 + 2 * M + H2 / 4 end function
def trimean(data): H1, M, H2 = quartiles(data, scheme=1) return (H1 + 2*M + H2)/4
Python
nomic_cornstack_python_v1
comment linear regression comment uses least squares - minimises squared error comment between each point and the line comment A GOOD GUIDE TO FORMULA comment https://www.dummies.com/education/math/statistics/how-to-calculate-a-regression-line/ comment line is a slope value and a y intercept comment slope intercept equ...
#linear regression # uses least squares - minimises squared error # between each point and the line # A GOOD GUIDE TO FORMULA # https://www.dummies.com/education/math/statistics/how-to-calculate-a-regression-line/ # line is a slope value and a y intercept #slope intercept equation of a line y=mx+b #(ie in example -...
Python
zaydzuhri_stack_edu_python
function EMA df base target period alpha=false begin set con = concat list mean call rolling window=period df at slice period : : at base if alpha == true begin comment (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period set df at target = round mean call ewm alpha=1 / period adjust=false 2 end ...
def EMA(df, base, target, period, alpha=False): con = pd.concat([df[:period][base].rolling(window=period).mean(), df[period:][base]]) if (alpha == True): # (1 - alpha) * previous_val + alpha * current_val where alpha = 1 / period df[target] = round(con.ewm(alpha=1 / period, adjust=False).m...
Python
nomic_cornstack_python_v1
comment URL: https://leetcode.com/explore/learn/card/array-and-string/203/introduction-to-string/1160/ comment Description: string Given two binary strings a and b, return their sum as a binary string. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" Constraints...
#URL: https://leetcode.com/explore/learn/card/array-and-string/203/introduction-to-string/1160/ #Description: """ Given two binary strings a and b, return their sum as a binary string. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output: "10101" Constraints: 1 <= a...
Python
zaydzuhri_stack_edu_python
function test_param_class_ret self begin set param = call ARGparams assert is instance phi float assert is instance price_ret float assert is instance price_vol float set tuple phi price_ret = tuple - 0.5 5 set theta_true = list phi price_ret set param = call ARGparams phi=phi price_ret=price_ret assert is instance cal...
def test_param_class_ret(self): param = ARGparams() self.assertIsInstance(param.phi, float) self.assertIsInstance(param.price_ret, float) self.assertIsInstance(param.price_vol, float) phi, price_ret = -.5, 5 theta_true = [phi, price_ret] param = ARGparams(phi=p...
Python
nomic_cornstack_python_v1
import urllib.request import json import textwrap set url = string https://www.googleapis.com/books/v1/volumes?q=isbn:1101904224 set url2 = string http://www.abc.es/hemeroteca/neoteo with url open url as f begin set text = read f set decodedtext = decode text string utf-8 print call fill decodedtext width=50 end print ...
import urllib.request import json import textwrap url = "https://www.googleapis.com/books/v1/volumes?q=isbn:1101904224" url2 = "http://www.abc.es/hemeroteca/neoteo" with urllib.request.urlopen(url) as f: text = f.read() decodedtext = text.decode('utf-8') print(textwrap.fill(decodedtext, width=50)) print() obj =...
Python
zaydzuhri_stack_edu_python
import numpy as np for x in array range 0 10.5 0.5 begin set y = x print string y= + string x set z = x ^ 2 print string z= + string z end print string This is the end of loop
import numpy as np for x in np.arange(0,10.5,.5): y = x print('y= '+str(x)) z = x**2 print('z= '+str(z)) print('This is the end of loop')
Python
zaydzuhri_stack_edu_python
function from_err cls mean=none err=none correlation=none names=none begin if err is none begin if mean is none begin raise call ValueError string Must give mean or err end set err = ones like mean end set err = call asarray err dtype=float set n = length err if correlation is none begin set correlation = call eye n en...
def from_err(cls, mean=None, err=None, correlation=None, names=None): if err is None: if mean is None: raise ValueError("Must give mean or err") err = np.ones_like(mean) err = np.asarray(err, dtype=float) n = len(err) if correlation is None: ...
Python
nomic_cornstack_python_v1
import sys import socket import dpkt from dpkt.ip import IP from dpkt.tcp import TCP function inet_to_str inet begin try begin return call inet_ntop AF_INET inet end except ValueError begin return call inet_ntop AF_INET6 inet end end function function contains_SYN segment begin return flags ? TH_SYN end function functi...
import sys import socket import dpkt from dpkt.ip import IP from dpkt.tcp import TCP def inet_to_str(inet): try: return socket.inet_ntop(socket.AF_INET, inet) except ValueError: return socket.inet_ntop(socket.AF_INET6, inet) def contains_SYN(segment): return segment.flags & dpkt.tcp....
Python
zaydzuhri_stack_edu_python
from __future__ import print_function from ROOT import TCanvas , TGraph from ROOT import gROOT from math import sin from array import array set c1 = call TCanvas string c1 string A Simple Graph Example 200 10 700 500 comment c1.SetFillColor( 42 ) comment exit()c1.SetGrid() set tuple x y = tuple array string d array str...
from __future__ import print_function from ROOT import TCanvas, TGraph from ROOT import gROOT from math import sin from array import array c1 = TCanvas( 'c1', 'A Simple Graph Example', 200, 10, 700, 500 ) #c1.SetFillColor( 42 ) #exit()c1.SetGrid() x, y = array( 'd' ), array( 'd' ) x1, y1 = array( 'd' ), array( 'd' ) ...
Python
zaydzuhri_stack_edu_python
function upgrade zpool=none version=none begin string .. versionadded:: 2016.3.0 Enables all supported features on the given pool zpool : string Optional storage pool, applies to all otherwize version : int Version to upgrade to, if unspecified upgrade to the highest possible .. warning:: Once this is done, the pool wi...
def upgrade(zpool=None, version=None): ''' .. versionadded:: 2016.3.0 Enables all supported features on the given pool zpool : string Optional storage pool, applies to all otherwize version : int Version to upgrade to, if unspecified upgrade to the highest possible .. warning...
Python
jtatman_500k
comment Input: รับจำนวนจริง 1 จำนวนจากแป้นพิมพ์ เก็บใน a comment Process: ให้ x มีค่าเป็น 1 จากนั้นทำคำสั่ง x = (x + a/x)/2 จำนวน 4 ครั้ง comment Output: ค่า x ที่ได้จากการทำงานข้างบนน print string Enter Your Real Number set a = decimal input set x = 1 set x = x + a / x / 2 set x = x + a / x / 2 set x = x + a / x / 2 s...
# Input: รับจำนวนจริง 1 จำนวนจากแป้นพิมพ์ เก็บใน a # Process: ให้ x มีค่าเป็น 1 จากนั้นทำคำสั่ง x = (x + a/x)/2 จำนวน 4 ครั้ง # Output: ค่า x ที่ได้จากการทำงานข้างบนน print('Enter Your Real Number') a = float(input()) x = 1 x = (x + a/x)/2 x = (x + a/x)/2 x = (x + a/x)/2 x = (x + a/x)/2 print(x)
Python
zaydzuhri_stack_edu_python
function startInstaPySession self begin set session = call InstaPy username=credentials at 0 password=credentials at 1 headless_browser=false with call smart_run session begin set accs = list string maleke_t call follow_by_list accs times=1 sleep_delay=600 interact=false end end function
def startInstaPySession(self): session = InstaPy(username= self.credentials[0], password= self.credentials[1], headless_browser=False) with smart_run(session): accs = ["maleke_t"] session.follow_by_list(accs, times=1, sleep_delay=600, interact=False)
Python
nomic_cornstack_python_v1
function test_routing_redistribution_uninstall self begin call _common_uninstall_external_and_unintialized string some_id delete dict string rule dict end function
def test_routing_redistribution_uninstall(self): self._common_uninstall_external_and_unintialized( 'some_id', routing_redistribution.delete, {'rule': {}} )
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from sqlalchemy import Column , Integer , String , Text , ForeignKey from sqlalchemy.orm import relationship from base import Base from base import db class Post extends Base begin set __tablename__ = string post set id = call Column Integer primary_key=true set title = call Column call St...
# -*- coding: utf-8 -*- from sqlalchemy import Column, Integer, String, Text, ForeignKey from sqlalchemy.orm import relationship from .base import Base from .base import db class Post(Base): __tablename__ = 'post' id = Column(Integer, primary_key=True) title = Column(String(64), nullable=False) con...
Python
zaydzuhri_stack_edu_python
comment calling to the api ################# comment using json comment import requests comment import json comment url='http://saral.navgurukul.org/api/courses' comment a=requests.get(url) comment B=a.json() comment with open('course.json','w') as love: comment c=json.dump(B,love,indent=2) comment for i in range(len(B...
#calling to the api ################# # using json # import requests # import json # url='http://saral.navgurukul.org/api/courses' # a=requests.get(url) # B=a.json() # with open('course.json','w') as love: # c=json.dump(B,love,indent=2) # for i in range(len(B["availableCourses"])): # print(i,B["availableCourse...
Python
zaydzuhri_stack_edu_python
string BONUS QUESTION: Abigail and Benson are playing Rock, Paper, Scissors. Each game is represented by an array of length 2, where the first element represents what Abigail played and the second element represents what Benson played. Given a sequence of games, determine who wins the most number of matches. If they ti...
"""BONUS QUESTION: Abigail and Benson are playing Rock, Paper, Scissors. Each game is represented by an array of length 2, where the first element represents what Abigail played and the second element represents what Benson played. Given a sequence of games, determine who wins the most number of matches. If they tie, ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np string data preparation for Prediction. Normalising columns and preparing variable to predict
import pandas as pd import numpy as np """data preparation for Prediction. Normalising columns and preparing variable to predict"""
Python
zaydzuhri_stack_edu_python
function test_10_00_create self begin assert true s1 assert true s2 assert true s3 assert true s4 end function
def test_10_00_create(self): self.assertTrue(self.s1) self.assertTrue(self.s2) self.assertTrue(self.s3) self.assertTrue(self.s4)
Python
nomic_cornstack_python_v1
string Github link : https://github.com/wint-thiri-swe/cp1404practicals/blob/master/prac05/state_names.py CP1404/CP5632 Practical State names in a dictionary File needs reformatting set CODE_TO_NAME = dict string QLD string Queensland ; string NSW string New South Wales ; string NT string Northern Territory ; string WA...
""" Github link : https://github.com/wint-thiri-swe/cp1404practicals/blob/master/prac05/state_names.py CP1404/CP5632 Practical State names in a dictionary File needs reformatting """ CODE_TO_NAME = {"QLD": "Queensland", "NSW": "New South Wales", "NT": "Northern Territory", ...
Python
zaydzuhri_stack_edu_python
function bottom_right self begin return tuple tuple x2 y2 end function
def bottom_right(self): return tuple((self.x2, self.y2))
Python
nomic_cornstack_python_v1
function delete_cors_policy ContainerName=none begin pass end function
def delete_cors_policy(ContainerName=None): pass
Python
nomic_cornstack_python_v1
function appearances s low high begin if low > high begin return dict end else begin set dic = dict return call appearances_helper s low high dic end end function function appearances_helper s low high dic begin if low > high begin return end else begin if s at low not in dic begin set dic at s at low = 1 end else be...
def appearances(s, low, high): if low > high: return {} else: dic = {} return appearances_helper(s, low, high, dic) def appearances_helper(s, low, high, dic): if low > high: return else: if s[low] not in dic: dic[s[low]] = 1 else: dic[s[low]] += 1 print(dic) appearances_helper...
Python
zaydzuhri_stack_edu_python
function send_stimulus self begin call send_message cmd=CMD_SEND_STIMULUS end function
def send_stimulus(self): self.send_message(cmd=CMD_SEND_STIMULUS)
Python
nomic_cornstack_python_v1
comment This file is for testing methods for current account from current_account_class_file import CurrentAccount comment Test instance set test = call CurrentAccount string 101 string Hello World 1245 1 11 2019 125000 comment Method test print call info_account print call info_balance print call withdraw 100000 print...
# This file is for testing methods for current account from current_account_class_file import CurrentAccount # Test instance test = CurrentAccount("101", "Hello World", 1245, 1, 11, 2019, 125000) # Method test print(test.info_account()) print(test.info_balance()) print(test.withdraw(100000)) print(test.deposit(1250))...
Python
zaydzuhri_stack_edu_python
comment To change this license header, choose License Headers in Project Properties. comment To change this template file, choose Tools | Templates comment and open the template in the editor. function verificaMaior a b c begin if a > b and a > c begin return a end else if b > a and b > c begin return b end else begin ...
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. def verificaMaior(a,b,c): if a>b and a>c: return a elif b>a and b>c: return b else: return c def verifica...
Python
zaydzuhri_stack_edu_python
import pytest from Bio.Seq import Seq from cargo_oligo_creator import oligo class TestOligo begin function test_create_forward_oligo self begin set test_oligo = call Oligo is_forward=true overlap=call Seq string AAAA start=call Seq string TATC pre_construct_piece=call Seq string GGGG construct=call Seq string CCCC post...
import pytest from Bio.Seq import Seq from cargo_oligo_creator import oligo class TestOligo: def test_create_forward_oligo(self): test_oligo = oligo.Oligo( is_forward = True, overlap = Seq("AAAA"), start = Seq("TATC"), pre_construct_piece = Seq("GGGG"), ...
Python
zaydzuhri_stack_edu_python
function plot_waist_shift_betabeatings_comparison axis before after column=string BBX show_ips=false begin assert column in tuple string BBX string BBY debug string Plotting waist shift induced beta-beating before and after matching. plot S 100 * before at column string o ls=string mfc=string none label=string Bare Wa...
def plot_waist_shift_betabeatings_comparison( axis: matplotlib.axes.Axes, before: pd.DataFrame, after: pd.DataFrame, column: str = "BBX", show_ips: bool = False, ) -> None: assert column in ("BBX", "BBY") logger.debug("Plotting waist shift induced beta-beating before and after matching.") ...
Python
nomic_cornstack_python_v1
with open string input.txt string r as passwords begin set pw = list comprehension strip line for line in passwords set correct = 0 for p in pw begin set tuple times letter string = split p set tuple lower upper = split times string - comment xor the letter for just one occurance if boolean string at integer lower - 1 ...
with open("input.txt", "r") as passwords: pw = [line.strip() for line in passwords] correct = 0 for p in pw: times, letter, string = p.split() lower, upper = times.split("-") #xor the letter for just one occurance if bool(string[int(lower) - 1] == letter[0]) !=\ bool(string[int(upper) - 1] == letter[0]): ...
Python
zaydzuhri_stack_edu_python
class Process begin function __init__ self burstTime arrivalTime priority waitTime=0 finished=0 begin set burstTime = burstTime set arrivalTime = arrivalTime set priority = priority set waitTime = waitTime set finished = finished end function function get_parameters self begin set parameters = list insert parameters 1...
class Process: def __init__(self, burstTime, arrivalTime, priority, waitTime=0, finished=0): self.burstTime = burstTime self.arrivalTime = arrivalTime self.priority = priority self.waitTime = waitTime self.finished = finished def get_parameters(self): pa...
Python
zaydzuhri_stack_edu_python
function setup_user self first_name last_name identifier email_address begin set user = dict string last_name last_name ; string first_name first_name ; string identifier identifier ; string email_address email_address ; string password call create_password append users user comment Compile ldif call compile_template s...
def setup_user(self, first_name, last_name, identifier, email_address): user = { "last_name": last_name, "first_name": first_name, "identifier": identifier, "email_address": email_address, "password": utils.create_password() } self.us...
Python
nomic_cornstack_python_v1
function user_input_module begin set fcheck = string no set scheck = string no set last_check = string no while last_check == string no begin while fcheck == string no begin set fniput = input string Enter first number: if call check_for_integer fniput == false begin print string In order to add, the data type must be ...
def user_input_module(): fcheck = "no" scheck = "no" last_check = "no" while last_check == "no" : while fcheck == "no" : fniput = input("Enter first number: ") if check_for_integer(fniput) == False: print("In order to add, the data ty...
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[221]: import csv import matplotlib.pyplot as plt import numpy as np import sklearn as svm from sklearn.metrics import accuracy_score , precision_score , f1_score , recall_score from sklearn import preprocessing from sklearn.utils import resample from sklearn.model_selection import cross...
# coding: utf-8 # In[221]: import csv import matplotlib.pyplot as plt import numpy as np import sklearn as svm from sklearn.metrics import accuracy_score, precision_score, f1_score, recall_score from sklearn import preprocessing from sklearn.utils import resample from sklearn.model_selection import cross_validate ...
Python
zaydzuhri_stack_edu_python
async function send_all self chunk begin async_with _snd_ch begin await call send call _func chunk await call send none end end function
async def send_all(self, chunk): async with self._snd_ch: await self._snd_ch.send(self._func(chunk)) await self._snd_ch.send(None)
Python
nomic_cornstack_python_v1
import os import sys import time import json import termios from main import getch from models import Message from dumperUtils import clear , download , whois function menu begin clear print string What would you like to download? 1) Only photos 2) Only videos 3) Only audios 4) Only documents 5) Multiple choice 0) Exit...
import os import sys import time import json import termios from main import getch from models import Message from dumperUtils import clear, download, whois def menu(): clear() print("What would you like to download?\n1) Only photos\n2) Only videos\n3) Only audios\n4) Only " "documents\n5) Multiple ...
Python
zaydzuhri_stack_edu_python
set x = input string enter the number whoes power ot be found set y = input string enter the power set z = power x y
x=input("enter the number whoes power ot be found") y=input("enter the power") z=pow(x,y)
Python
zaydzuhri_stack_edu_python
function gen_polygon_pts n_pts=3 radius=list 1.0 begin string Generate points for a polygon with a number of radiuses. This makes it easy to generate shapes with an arbitrary number of sides, regularly angled around the origin. A single radius will give a simple shape such as a square, hexagon, etc. Multiple radiuses w...
def gen_polygon_pts(n_pts=3, radius=[1.0]): '''Generate points for a polygon with a number of radiuses. This makes it easy to generate shapes with an arbitrary number of sides, regularly angled around the origin. A single radius will give a simple shape such as a square, hexagon, etc. Multiple radiuses will give ...
Python
jtatman_500k
from bs4 import BeautifulSoup function parse_html html begin set soup = call BeautifulSoup html string html.parser set paragraphs = find all soup string p set result = list for paragraph in paragraphs begin if string class in attrs and string exclude in paragraph at string class begin continue end append result get te...
from bs4 import BeautifulSoup def parse_html(html): soup = BeautifulSoup(html, 'html.parser') paragraphs = soup.find_all('p') result = [] for paragraph in paragraphs: if 'class' in paragraph.attrs and 'exclude' in paragraph['class']: continue result.append(paragraph.get_tex...
Python
jtatman_500k
function assert_status_with_message status_code=200 response=none message=none begin string Check to see if a message is contained within a response. assert status_code == status_code assert message in string data end function
def assert_status_with_message(status_code=200, response=None, message=None): """ Check to see if a message is contained within a response. """ assert response.status_code == status_code assert message in str(response.data)
Python
zaydzuhri_stack_edu_python
function divide_nums a b begin try begin return a / b end except ZeroDivisionError as e begin print string Error: e error string An error occurred during division. end end function
def divide_nums(a, b): try: return a / b except ZeroDivisionError as e: print('Error:', e) logging.error('An error occurred during division.')
Python
jtatman_500k
class Node begin function __init__ self data begin set data = data set next = none end function end class class Stack begin function __init__ self begin set top = none set bottom = none set length = 0 end function function peek self begin return data end function function push self data begin set new_node = call Node d...
class Node: def __init__(self, data): self.data = data self.next = None class Stack: def __init__(self): self.top = None self.bottom = None self.length = 0 def peek(self): return self.top.data def push(self, data): new_node = Node(data) ...
Python
zaydzuhri_stack_edu_python
function exportValues self begin set nx = call value set ny = call value set cellSizeX = call value set cellSizeY = call value set startX = min nx - 1 max 0 call value set startY = min ny - 1 max 0 call value set endX = min nx - 1 max 0 call value set endY = min ny - 1 max 0 call value set cycles = max 0 call value end...
def exportValues(self): self.maze.nx = self.spinHCells.value() self.maze.ny = self.spinVCells.value() self.maze.cellSizeX = self.spinCellX.value() self.maze.cellSizeY = self.spinCellY.value() self.maze.startX = min(self.maze.nx-1, max(0, self.spin...
Python
nomic_cornstack_python_v1
function GetDataAsObject self begin string Retrieves the data as an object. Returns: object: data as a Python type or None if not available. Raises: WinRegistryValueError: if the value data cannot be read. if not _data begin return none end if _data_type in _STRING_VALUE_TYPES begin try begin return decode _data string...
def GetDataAsObject(self): """Retrieves the data as an object. Returns: object: data as a Python type or None if not available. Raises: WinRegistryValueError: if the value data cannot be read. """ if not self._data: return None if self._data_type in self._STRING_VALUE_TYPES:...
Python
jtatman_500k
function __hash__ self begin return call hash id end function
def __hash__(self): return hash(self.id)
Python
nomic_cornstack_python_v1
string Created on Feb 23, 2019 MqttSubClientTestApp.py: python application to receive message using MQTT protocol @author: GANESHRAM KANAKASABAI from project import MqttClientConnector set UBIDOTS_DEVICE_LABEL = string warehouse/ set UBIDOTS_TOPIC_DEFAULT = string /v1.6/devices/ set QOS = 2 class MqttSubClient extends ...
''' Created on Feb 23, 2019 MqttSubClientTestApp.py: python application to receive message using MQTT protocol @author: GANESHRAM KANAKASABAI ''' from project import MqttClientConnector UBIDOTS_DEVICE_LABEL = "warehouse/" UBIDOTS_TOPIC_DEFAULT = "/v1.6/devices/" QOS = 2 class MqttSubClient(object): ...
Python
zaydzuhri_stack_edu_python
function id self value begin warn string Setting values on id will NOT update the remote Canvas instance. set _id = value end function
def id(self, value): self.logger.warn("Setting values on id will NOT update the remote Canvas instance.") self._id = value
Python
nomic_cornstack_python_v1
function test_ajax_no_formula self begin set response = call handle_ajax string preview_formcalc dict string request_start 1 assert in string error response assert equal response at string error string No formula specified. end function
def test_ajax_no_formula(self): response = self.the_input.handle_ajax( "preview_formcalc", {'request_start': 1, } ) self.assertIn('error', response) self.assertEqual(response['error'], "No formula specified.")
Python
nomic_cornstack_python_v1
comment Python program to reverse a linked list comment Time Complexity : O(n) comment Space Complexity : O(1) comment Node Class class Node begin comment Constructor to initialize the node object function __init__ self data begin set data = data comment In python, None == null set next = none end function end class cl...
# Python program to reverse a linked list # Time Complexity : O(n) # Space Complexity : O(1) # Node Class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None # In python, None == null class LinkedList: # Constructor to initi...
Python
jtatman_500k
from computadora import Computadora class Orden begin set contador_orden = 0 function __init__ self computadoras begin set contador_orden = contador_orden + 1 set __id_orden = contador_orden set __computadoras = computadoras end function function agregar_computadora self computadora begin append __computadoras computad...
from computadora import Computadora class Orden: contador_orden = 0 def __init__(self, computadoras): Orden.contador_orden += 1 self.__id_orden = Orden.contador_orden self.__computadoras = computadoras def agregar_computadora(self, computadora): self.__computadoras.app...
Python
zaydzuhri_stack_edu_python
class Solution begin function maxSubArray self nums begin string :type nums: List[int] :rtype: int set l = length nums if l == 1 begin return nums at 0 end set n = max nums set i = 1 while i < l begin set nums at i = nums at i + nums at i - 1 set i = i + 1 end set p = max nums set i = 0 set m = nums at i for j in range...
class Solution: def maxSubArray(self, nums): """ :type nums: List[int] :rtype: int """ l = len(nums) if l == 1: return nums[0] n = max(nums) i = 1 while i < l: nums[i] = nums[i] + nums[i - 1] i += 1 p...
Python
zaydzuhri_stack_edu_python
comment app.py string @author: Clark Brown @date: 15 April 2020 import math import networkx as nx from networkx import algorithms as alg import csv import numpy as np import collections from matplotlib import pyplot as plt from scipy import stats from scipy import optimize class NeworkDataDriver begin function __init__...
# app.py """ @author: Clark Brown @date: 15 April 2020 """ import math import networkx as nx from networkx import algorithms as alg import csv import numpy as np import collections from matplotlib import pyplot as plt from scipy import stats from scipy import optimize class NeworkDataDriver: def __init__(self, da...
Python
zaydzuhri_stack_edu_python
function distance_measure route_shp begin comment Convert GeoDataFrame to simple pd.DataFrame containing only comment list of 2D coordinates along route. set lines_gdf = call extract_point_df route_shp comment Calculate distance from one point to the next set distance = list for idx in range length lines_gdf - 1 begin...
def distance_measure(route_shp): # Convert GeoDataFrame to simple pd.DataFrame containing only # list of 2D coordinates along route. lines_gdf = extract_point_df(route_shp) # Calculate distance from one point to the next distance = [] for idx in range(len(lines_gdf)-1): # x and y coord...
Python
nomic_cornstack_python_v1
function get_state self room_id event_type tok expect_code=200 state_key=string begin return call _read_write_state room_id event_type none tok expect_code state_key method=string GET end function
def get_state( self, room_id: str, event_type: str, tok: str, expect_code: int = 200, state_key: str = "", ): return self._read_write_state( room_id, event_type, None, tok, expect_code, state_key, method="GET" )
Python
nomic_cornstack_python_v1
function game_counts n_back=20 begin set all_models = glob gfile join path MODELS_DIR string *.meta set model_filenames = sorted list comprehension split base name path m string . at 0 for m in all_models reverse=true for m in model_filenames at slice : n_back : begin set games = glob gfile join path SELFPLAY_DIR m s...
def game_counts(n_back=20): all_models = gfile.Glob(os.path.join(MODELS_DIR, '*.meta')) model_filenames = sorted([os.path.basename(m).split('.')[0] for m in all_models], reverse=True) for m in model_filenames[:n_back]: games = gfile.Glob(os.path.join(SELFPLAY_DIR, m, '*...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string ruote_slash.py ~~~~~~~~~ 演示路由配置特殊URLs/重定向动作行为. :copyright: (c) 2017 by Chinasoft International·ETC. :license: BSD, see LICENSE for more details. :author: CTO Officer (YanHe) :email: yanhe@chinasofti.com comment 导入flask模块库中的Flask类 from flask import Flask comment 创建Flask类实例app set app...
# -*- coding: utf-8 -*- ''' ruote_slash.py ~~~~~~~~~ 演示路由配置特殊URLs/重定向动作行为. :copyright: (c) 2017 by Chinasoft International·ETC. :license: BSD, see LICENSE for more details. :author: CTO Officer (YanHe) :email: yanhe@chinasofti.com ''' # 导入flask模块库中的Flask类 from flask import Flask #...
Python
zaydzuhri_stack_edu_python
class Roman_int begin function __init__ self Roman_num begin set roman_numeral = Roman_num end function decorator staticmethod function get_value char begin if char == string I begin return 1 end else if char == string V begin return 5 end else if char == string X begin return 10 end else if char == string L begin retu...
class Roman_int(): def __init__(self, Roman_num): self.roman_numeral = Roman_num @staticmethod def get_value(char): if(char == 'I'): return 1 elif(char == 'V'): return 5 elif(char == 'X'): return 10 elif(char == 'L'): r...
Python
flytech_python_25k
function loadByte self address begin set chunk_id = address ? CHUNK_BITS set chunk = get __chunks chunk_id if chunk is none begin raise call SegmentationFault address end return chunk at address % CHUNK_SIZE end function
def loadByte(self, address): chunk_id = address >> Memory.CHUNK_BITS chunk = self.__chunks.get(chunk_id) if chunk is None: raise errors.SegmentationFault(address) return chunk[address % Memory.CHUNK_SIZE]
Python
nomic_cornstack_python_v1
function get_user_login_xpaths begin return dict string username get login at string fields at string username string xpath ; string password get login at string fields at string password string xpath end function
def get_user_login_xpaths(): return {'username': login['fields']['username'].get('xpath'), 'password': login['fields']['password'].get('xpath'), }
Python
nomic_cornstack_python_v1
string import pandas as pd #as 별칭 import os print(os.getcwd()) excel = pd.ExcelFile("C:\ITWILL\3_Python-I\workspace\my_test\my_data\의원검색.xlsx") print(excel) person = excel.parse('person') print(person) import pandas as pd from pandas import Series , DataFrame set data2016 = read csv string C:\ITWILL\3_Python-I\workspac...
''' import pandas as pd #as 별칭 import os print(os.getcwd()) excel = pd.ExcelFile("C:\\ITWILL\\3_Python-I\\workspace\\my_test\\my_data\\의원검색.xlsx") print(excel) person = excel.parse('person') print(person) ''' import pandas as pd from pandas import Series,DataFrame data2016 = pd.read_csv("C:\\ITWILL\\3_Python-I\\work...
Python
zaydzuhri_stack_edu_python
function print_window_stats hom_ref_count het_count hom_alt_count chrom window_start window_end min_fraction_window begin set num_called_positions = hom_ref_count + het_count + hom_alt_count set window_size = window_end - window_start if num_called_positions / window_size > min_fraction_window begin set het_rate = het_...
def print_window_stats( hom_ref_count, het_count, hom_alt_count, chrom, window_start, window_end, min_fraction_window, ): num_called_positions = hom_ref_count + het_count + hom_alt_count window_size = window_end - window_start if num_called_positions / window_size > min_fraction_...
Python
nomic_cornstack_python_v1
comment Write a program that allows a user to add/delete items from a comment todolist. Display user input as list comment author: yclept insan function main begin set added = list while true begin set user_response = input if user_response == string q begin print string Bye! exit end else if user_response == string a...
# Write a program that allows a user to add/delete items from a # todolist. Display user input as list # author: yclept insan def main(): added = [] while True: user_response = input() if user_response == 'q': print("Bye!") exit() elif user_response ==...
Python
zaydzuhri_stack_edu_python
import pandas as pd from haversine import haversine , Unit import matplotlib.pyplot as plt import sys import os.path append path directory name path __file__ set ELEVATIONS_FILE = join path path at 0 string ../routemodel/routes/ASC2021/ASC2021_elevations_draft.csv set df = read csv ELEVATIONS_FILE delimiter=string , in...
import pandas as pd from haversine import haversine, Unit import matplotlib.pyplot as plt import sys import os.path sys.path.append(os.path.dirname(__file__)) ELEVATIONS_FILE = os.path.join(sys.path[0], '../routemodel/routes/ASC2021/ASC2021_elevations_draft.csv') df = pd.read_csv(ELEVATIONS_FILE, delimiter=',', index_...
Python
zaydzuhri_stack_edu_python
function generate_rug n begin set retLst = list set intialNumber = integer n - 1 / 2 for i in range intialNumber begin set row = list for j in range i + 1 begin append row intialNumber - j end set loopForIntN = n - i + 1 * 2 if loopForIntN > 0 begin for j in range loopForIntN begin append row intialNumber - i end end...
def generate_rug(n): retLst =[] intialNumber = int((n-1)/2) for i in range(intialNumber): row = [] for j in range(i+1): row.append(intialNumber-j) loopForIntN = n - ((i+1)*2) if loopForIntN > 0: for j in range(loopForIntN): row.app...
Python
zaydzuhri_stack_edu_python
from wit import Wit set client = call Wit string ZF464AV6N4XA4O2W7GKK5RA5ROGMYCLO set resp = none set i = 0 set err = 0 set well = 0 with open string probe_3.wav string rb as f begin set resp = call speech f none dict string Content-Type string audio/wav print string resp at string _text set ref_long = string i know th...
from wit import Wit client = Wit('ZF464AV6N4XA4O2W7GKK5RA5ROGMYCLO') resp = None i = 0 err = 0 well = 0 with open('probe_3.wav', 'rb') as f: resp = client.speech(f, None, {'Content-Type': 'audio/wav'}) print(str(resp['_text'])) ref_long = ('i know the human being and fish can coexist peacefully') print(ref_...
Python
zaydzuhri_stack_edu_python
import urllib2 from bs4 import BeautifulSoup function get_image link begin string Your job is to implement a function that, given a link, can retrieve an image of an offender associated with that link. For example, given this link component: dr_info/colonejoseph.html The function should return this: https://www.tdcj.st...
import urllib2 from bs4 import BeautifulSoup def get_image(link): ''' Your job is to implement a function that, given a link, can retrieve an image of an offender associated with that link. For example, given this link component: dr_info/colonejoseph.html The function should return this: ...
Python
zaydzuhri_stack_edu_python
function storage_state_ub index begin set i = index at 0 return emax * soc_max end function
def storage_state_ub(index): i = index[0] return storage_para[i].emax * storage_para[i].soc_max
Python
nomic_cornstack_python_v1
function __create_partition_samples self input_sample_partitions begin comment Load the GLAD Alerts for 2019 and 2020 set tuple glad_2019 glad_2020 = call __load_glad_alerts_for_partition comment Iterate over each of the paritions function iterate_over_paritions partition begin comment Cast the partition set partition ...
def __create_partition_samples(self, input_sample_partitions): # Load the GLAD Alerts for 2019 and 2020 glad_2019, glad_2020 = self.__load_glad_alerts_for_partition() # Iterate over each of the paritions def iterate_over_paritions (partition) : # C...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import re from analyser.adds import logger function preprocess_bookinfo bookinfo begin set title = call preprocess_title title set authors = call preprocess_authors authors set pagelink = call preprocess_pagelink pagelink set language = call preprocess_language language set summary = call ...
# -*- coding: utf-8 -*- import re from analyser.adds import logger def preprocess_bookinfo(bookinfo): bookinfo.title = preprocess_title(bookinfo.title) bookinfo.authors = preprocess_authors(bookinfo.authors) bookinfo.pagelink = preprocess_pagelink(bookinfo.pagelink) bookinfo.language = preprocess_lang...
Python
zaydzuhri_stack_edu_python
function get_audio path begin return call send_from_directory string audio path end function
def get_audio(path): return send_from_directory('audio', path)
Python
nomic_cornstack_python_v1
from random import randrange from heap_sort import heap_sort function tester begin set fle = open string test_results string w for i in range 20 begin set testing_lst = list comprehension call randrange 1 100 - 1 for x in range call randrange 1 200000 set res = call heap_sort testing_lst set other_res = sorted testing_...
from random import randrange from heap_sort import heap_sort def tester(): fle = open("test_results", 'w') for i in range(20): testing_lst = [ randrange( 1, (100) - 1) for x in range( randrange( 1, ...
Python
zaydzuhri_stack_edu_python
class Movie begin string A class for all the information we need about movies function __init__ self movie_title movie_storyline poster_image trailer_youtube begin string Parameters needed to contruct the class: :parm movie_title: string :parm movie_storyline: string :parm poster_image: string :parm trailer_youtube: st...
class Movie(): """A class for all the information we need about movies""" def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube): """ Parameters needed to contruct the class: :parm movie_title: string :parm movie_storyline: string ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import psycopg2 from openpyxl import Workbook from openpyxl import load_workbook function connect begin set conn = none try begin print string Connecting to the PostgreSQL database... set conn = call connect host=string localhost database=string Election user=string postgres password=strin...
# -*- coding: utf-8 -*- import psycopg2 from openpyxl import Workbook from openpyxl import load_workbook def connect(): conn=None try: print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(host="localhost", database="Election", user="postgres", password="postgres") cur = conn.cursor() c...
Python
zaydzuhri_stack_edu_python
import time import xlrd import os set num = 0 set book = call open_workbook input string Drag file Excel here to: print format string Number of sheets in the workbook {0} nsheets set k = call sheet_names for i in k begin print num string - k at num set num = num + 1 end set ind = input string Enter the worksheets numbe...
import time import xlrd import os num = 0 book = xlrd.open_workbook(input('Drag file Excel here to: ')) print('Number of sheets in the workbook {0}'.format(book.nsheets)) k = book.sheet_names() for i in k: print(num, ' - ', k[num]) num+=1 ind = input('Enter the worksheets number: ') sheet = book.sheet_by...
Python
zaydzuhri_stack_edu_python
function output self output begin set _output = output end function
def output(self, output): self._output = output
Python
nomic_cornstack_python_v1
function upgraded_path proto_path upgraded_package begin return join string / list replace upgraded_package string . string / split proto_path string / at - 1 end function
def upgraded_path(proto_path, upgraded_package): return '/'.join([upgraded_package.replace('.', '/'), proto_path.split('/')[-1]])
Python
nomic_cornstack_python_v1
function generate_fibonacci_sequence n begin comment start with the first two numbers of the sequence set fibonacci_sequence = list 0 1 while fibonacci_sequence at - 1 + fibonacci_sequence at - 2 <= n begin set next_number = fibonacci_sequence at - 1 + fibonacci_sequence at - 2 append fibonacci_sequence next_number end...
def generate_fibonacci_sequence(n): fibonacci_sequence = [0, 1] # start with the first two numbers of the sequence while fibonacci_sequence[-1] + fibonacci_sequence[-2] <= n: next_number = fibonacci_sequence[-1] + fibonacci_sequence[-2] fibonacci_sequence.append(next_number) return fibona...
Python
jtatman_500k
from ftp_client import FTPClient function parse_input text begin set words = split text string set command = words at 0 pop words 0 return tuple command words end function function main begin set client = none set command = none while true begin while client is none begin set tuple command args = call parse_input input...
from ftp_client import FTPClient def parse_input(text): words = text.split(' ') command = words[0] words.pop(0) return command, words def main(): client = None command = None while True: while client is None: command, args = parse_input(input('Необходимо подключиться ...
Python
zaydzuhri_stack_edu_python
class EarlyStopping begin function __init__ self history=5 begin call __init__ set history = history set counter = 0 set best_val_loss = none end function function check self val_loss begin set result = false if best_val_loss is none begin set best_val_loss = val_loss end else if val_loss > best_val_loss begin set coun...
class EarlyStopping(): def __init__(self, history = 5): super().__init__() self.history = history self.counter = 0 self.best_val_loss = None def check(self, val_loss): result = False if(self.best_val_loss is None): self.best_val_loss = val_loss elif(val_loss > self.best_val_loss): ...
Python
zaydzuhri_stack_edu_python
function get_model_name self begin string Return the model name for templates. if model_name is none begin raise call ImproperlyConfigured string %s requires either a definition of 'model_name' or an implementation of 'get_model_name()' % __name__ end return model_name end function
def get_model_name(self): """ Return the model name for templates. """ if self.model_name is None: raise ImproperlyConfigured( "%s requires either a definition of " "'model_name' or an implementation of 'get_model_name()'" % sel...
Python
jtatman_500k