code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function softmax_loss_naive W X y reg begin comment Initialize the loss and gradient to zero. set loss = 0.0 set dW = zeros like W comment TODO: Compute the softmax loss and its gradient using explicit loops. # comment Store the loss in loss and the gradient in dW. If you are not careful # comment here, it is easy to r...
def softmax_loss_naive(W, X, y, reg): # Initialize the loss and gradient to zero. loss = 0.0 dW = np.zeros_like(W) ############################################################################# # TODO: Compute the softmax loss and its gradient using explicit loops. # # Store the loss in loss...
Python
nomic_cornstack_python_v1
string ' import requests import json url = "https://api.checkin.hml.sebrae.al/gpt/question" data = {"question": "anything now. Escreva em um estilo coloquial e relacionável e responda essa pergunta como se fosse analista do SEBRAE Alagoas, de forma fácil de ser entendida. Envolva o tema empreendedorismo e mundo empresa...
'''' import requests import json url = "https://api.checkin.hml.sebrae.al/gpt/question" data = {"question": "anything now. Escreva em um estilo coloquial e relacionável e responda essa pergunta como se fosse analista do SEBRAE Alagoas, de forma fácil de ser entendida. Envolva o tema empreendedorismo e mundo empresari...
Python
zaydzuhri_stack_edu_python
async function aesthetic self ctx text begin set out = string for char in text begin set out = out + get fullwidth_transform char char end await call send out end function
async def aesthetic(self, ctx, *, text): out = "" for char in text: out += utils.fullwidth_transform.get(char, char) await ctx.send(out)
Python
nomic_cornstack_python_v1
function parsedocx path *args **kwargs begin return content end function
def parsedocx(path, *args, **kwargs): return DOCX(path, *args, **kwargs).content
Python
nomic_cornstack_python_v1
function suppresses self other_describer begin return false end function
def suppresses(self, other_describer): return False
Python
nomic_cornstack_python_v1
function prefixed self key_prefix begin set prefixed_assets = call prefix_assets assets key_prefix return call AssetGroup assets=prefixed_assets source_assets=source_assets resource_defs=resource_defs executor_def=executor_def end function
def prefixed(self, key_prefix: CoercibleToAssetKeyPrefix): prefixed_assets = prefix_assets(self.assets, key_prefix) return AssetGroup( assets=prefixed_assets, source_assets=self.source_assets, resource_defs=self.resource_defs, executor_def=self.executor_d...
Python
nomic_cornstack_python_v1
function nitems_written self *args **kwargs begin return call BCH_encoder_ATSC_sptr_nitems_written self *args keyword kwargs end function
def nitems_written(self, *args, **kwargs): return _mack_sdr_rossi_swig.BCH_encoder_ATSC_sptr_nitems_written(self, *args, **kwargs)
Python
nomic_cornstack_python_v1
function mlflow_setup self begin call export_env call set_experiment mlflow_experiment end function
def mlflow_setup(self): export_env() mlflow.set_experiment(self.mlflow_experiment)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 string Проверить что в массиве есть значение set arr = list string bubujka string zuzujka print string bubujka in arr print string jujujka in arr
#!/usr/bin/env python3 """ Проверить что в массиве есть значение """ arr = ['bubujka', 'zuzujka'] print('bubujka' in arr) print('jujujka' in arr)
Python
zaydzuhri_stack_edu_python
string 풀이방법 1. for문을 돌리면서 숫자 하나씩을 stack에 저장한다. 2. 그런데 for문을 통해서 들어오는 숫자가 stack의 top보다 크면 stack top꺼내서 삭제 3. stack_top이 크거나 같을 때까지 계속함 4. 만약 삭제 하는게 k개 만큼 했다면 남은 숫자 꺼냄 5. 만약 for문을 다 돌았는데도 k가 남아있으면 스택에는 [9,8,7,6,5,4,3,2,1] 이런식으로 내림차순으로 정렬됨 6. 따라서 stack[:-k]를 해줌 7. 마지막으로 "".join(stack) 을 return 해주면 끝! function solution num...
""" 풀이방법 1. for문을 돌리면서 숫자 하나씩을 stack에 저장한다. 2. 그런데 for문을 통해서 들어오는 숫자가 stack의 top보다 크면 stack top꺼내서 삭제 3. stack_top이 크거나 같을 때까지 계속함 4. 만약 삭제 하는게 k개 만큼 했다면 남은 숫자 꺼냄 5. 만약 for문을 다 돌았는데도 k가 남아있으면 스택에는 [9,8,7,6,5,4,3,2,1] 이런식으로 내림차순으로 정렬됨 6. 따라서 stack[:-k]를 해줌 7. 마지막으로 "".join(stack) 을 return 해주면 끝! """ def solution(number...
Python
zaydzuhri_stack_edu_python
function get_stored self begin return tuple call __prepare pred call __prepare labels end function
def get_stored(self): return self.__prepare(self.pred), self.__prepare(self.labels)
Python
nomic_cornstack_python_v1
import math import pygame from pygame.locals import * comment Test line for commit set FONT = none class wheelVector begin function __init__ self begin set x = 0.0 set y = 0.0 set mag = 0.0 set tarTheta = 0.0 set curTheta = 0.0 set turnVel = 0.0 end function end class class robot_ extends object begin set FL = 0 set FR...
import math import pygame from pygame.locals import * #Test line for commit FONT = None class wheelVector: def __init__(self): x =0.0 y =0.0 mag =0.0 tarTheta=0.0 curTheta=0.0 turnVel =0.0 class robot_(object): FL=0 FR=1 BR=2 BL=3...
Python
zaydzuhri_stack_edu_python
function find_args A begin if call shape A at 0 == call shape A at 1 begin set sz = call shape A at 0 end end function
def find_args(A): if pl.shape(A)[0] == pl.shape(A)[1]: sz = pl.shape(A)[0]
Python
nomic_cornstack_python_v1
function set_high_score self begin comment pop a window for player's name set answer = call askstring string Cheers string What's your name? parent=_master if answer is not none begin comment set the player's record(str) set record = string == + _filename + string == + answer + string : + string call get_score + string...
def set_high_score(self): # pop a window for player's name answer = simpledialog.askstring("Cheers", "What's your name?", parent=self._master) if answer is not None: # set the player's record(str) record = '==' + self._filename + '=...
Python
nomic_cornstack_python_v1
function compute_combination_column train test features new_name=none unfrequent_threshold=0 begin set feature_train = zeros length train dtype=string int set feature_test = zeros length test dtype=string int if new_name is none begin set new_name = join string _ features end for feature in features begin set train_f =...
def compute_combination_column(train, test, features, new_name=None, unfrequent_threshold=0): feature_train = numpy.zeros(len(train), dtype='int') feature_test = numpy.zeros(len(test), dtype='int') if new_name is None: new_name = '_'.join(features) for feature in features: train_f = tr...
Python
nomic_cornstack_python_v1
function main override_args=none begin set starter = call BaseScripts comment Load initial args set parser = start starter string Add tags and/or comments to a specified list of hashkeys. call add_argument string hashkeys help=string hashkeys of the threat to add tags and/or the comment nargs=string * call add_argument...
def main(override_args=None): starter = BaseScripts() # Load initial args parser = starter.start('Add tags and/or comments to a specified list of hashkeys.') parser.add_argument( 'hashkeys', help='hashkeys of the threat to add tags and/or the comment', nargs='*', ) parse...
Python
nomic_cornstack_python_v1
function __call__ self *args **kwargs begin return call method receiver *args keyword kwargs end function
def __call__(self, *args, **kwargs): return self.method(self.receiver, *args, **kwargs)
Python
nomic_cornstack_python_v1
function execute_by_wrappers exec_items container_=none begin set tuple name module function = exec_items set func_obj = get attribute module function return dict string Name name ; string Module_Name __name__ ; string Function_Name function ; string Module module ; string Function function ; string Input copy containe...
def execute_by_wrappers(exec_items, container_: any = None): name, module, function = exec_items func_obj = getattr(module, function) return { 'Name': name, 'Module_Name': module.__name__, 'Function_Name': function, 'Module': module, 'Function':...
Python
nomic_cornstack_python_v1
function _read_cwl_record rec begin string Read CWL records, handling multiple nesting and batching cases. set keys = set list set out = list if is instance rec dict begin set is_batched = all list comprehension is instance v tuple list tuple for v in values rec set cur = list comprehension dict for _ in range if exp...
def _read_cwl_record(rec): """Read CWL records, handling multiple nesting and batching cases. """ keys = set([]) out = [] if isinstance(rec, dict): is_batched = all([isinstance(v, (list, tuple)) for v in rec.values()]) cur = [{} for _ in range(len(rec.values()[0]) if is_batched else ...
Python
jtatman_500k
comment !/usr/bin/env python comment -*- coding:utf-8 -*- set tuple n d = map int split input set l = list for i in range n begin set tuple loc num = map int split input append l tuple loc num end sort l function find s e begin if l at e at 0 - l at s at 0 < d begin return s end while l at e at 0 - l at s at 0 >= d be...
#!/usr/bin/env python # -*- coding:utf-8 -*- n, d = map(int, input().split()) l = [] for i in range(n): loc, num = map(int, input().split()) l.append((loc, num)) l.sort() def find(s,e): if l[e][0]-l[s][0]<d: return s while l[e][0]-l[s][0]>=d: s += 1 return s-1 if len(l) <= 1 or l...
Python
zaydzuhri_stack_edu_python
for i in range k begin set x = integer input set lst2 = list map int split input for j in range x begin if lst at lst2 at j - 1 == 0 begin set lst at lst2 at j - 1 = 1 end end end set ans = 0 for i in range n begin if lst at i == 0 begin set ans = ans + 1 end end print ans
for i in range(k): x = int(input()) lst2 = list(map(int,input().split())) for j in range(x): if (lst[lst2[j] - 1] == 0): lst[lst2[j] - 1] = 1 ans = 0 for i in range(n): if (lst[i] == 0): ans = ans + 1 print(ans)
Python
zaydzuhri_stack_edu_python
function get_game_count console_name begin set c = group by df string Platform return count c at string Name at console_name end function
def get_game_count(console_name: str) -> int: c = df.groupby('Platform') return c['Name'].count()[console_name]
Python
nomic_cornstack_python_v1
import numpy as np from glob import glob import scipy import os import imageio class Data_loader extends object begin function __init__ self begin string :param is_training: True set source = string /Users/Mike/Documents/machine learning/deep learning/da-gan/CUB_200_2011/ comment self.is_training = is_training set dict...
import numpy as np from glob import glob import scipy import os import imageio class Data_loader(object): def __init__(self): ''' :param is_training: True ''' self.source = '/Users/Mike/Documents/machine learning/deep learning/da-gan/CUB_200_2011/' #self.is_training = is_tra...
Python
zaydzuhri_stack_edu_python
function _parse_axes_panel self side ax begin comment Get gridspec and subplotspec indices set ss = call get_subplotspec set offset = length _panel_dict at side + 1 set tuple row1 row2 col1 col2 = call _get_rows_columns if side in tuple string left string right begin set iratio = if expression side == string left then ...
def _parse_axes_panel(self, side, ax): # Get gridspec and subplotspec indices ss = ax.get_subplotspec() offset = len(ax._panel_dict[side]) + 1 row1, row2, col1, col2 = ss._get_rows_columns() if side in ('left', 'right'): iratio = col1 - offset if side == 'left' else c...
Python
nomic_cornstack_python_v1
import urllib.request import shutil from os.path import join , dirname , abspath set base_path_for_files = string C:/podyplomowka/lod1/ with open join directory name absolute path __file__ string lista_powiatow.txt string r as f begin set powiaty = list comprehension strip string x for x in f end for pow in powiaty beg...
import urllib.request import shutil from os.path import join, dirname, abspath base_path_for_files = r'C:/podyplomowka/lod1/' with open(join(dirname(abspath(__file__)),'lista_powiatow.txt'), 'r') as f: powiaty = [str(x).strip() for x in f] for pow in powiaty: print(pow) file_name = join(base_path_for_fil...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import RPi.GPIO as GPIO import time call setmode BCM setup GPIO 4 OUT function main begin for x in range 6 begin call output 4 true sleep 0.5 call output 4 false sleep 0.5 end call cleanup end function if __name__ == string __main__ begin call main end
#!/usr/bin/python import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(4, GPIO.OUT) def main(): for x in range(6): GPIO.output(4, True) time.sleep(.5) GPIO.output(4, False) time.sleep(.5) GPIO.cleanup() if __name__ == "__main__": main()
Python
zaydzuhri_stack_edu_python
function test_fma_nan_param_infarray_infnum_infnum_okarray_a_338 self begin comment This version is expected to pass. call fma okarrayx oknumy oknumz arrayout matherrors=true comment This should raise an error. with assert raises ArithmeticError begin call fma infarrayx infnumy infnumz arrayout end end function
def test_fma_nan_param_infarray_infnum_infnum_okarray_a_338(self): # This version is expected to pass. arrayfunc.fma(self.okarrayx, self.oknumy, self.oknumz, self.arrayout, matherrors=True) # This should raise an error. with self.assertRaises(ArithmeticError): arrayfunc.fma(self.infarrayx, self.infnumy, sel...
Python
nomic_cornstack_python_v1
import os import pandas as pd from sklearn.externals import joblib import numpy as np function load_manage_csv method_name begin comment If rewrite column doesnt exist, add it return call DataFrame end function function save_in_csv method_name param_dict output_files output_names begin set method_csv = call load_manage...
import os import pandas as pd from sklearn.externals import joblib import numpy as np def load_manage_csv(method_name): # If rewrite column doesnt exist, add it return pd.DataFrame() def save_in_csv(method_name, param_dict, output_files, output_names): method_csv = load_manage_csv(method_name) # If a...
Python
zaydzuhri_stack_edu_python
while true begin set tuple n x = map int split input if n == 0 and x == 0 begin break end set ans = 0 for i in range 1 n + 1 begin for j in range 1 n + 1 begin if j <= i begin continue end set k = x - i + j if k > j and k <= n begin set ans = ans + 1 end end end print ans end
while True: n,x = map(int,input().split()) if n == 0 and x == 0: break ans = 0 for i in range(1,n+1): for j in range(1,n+1): if j <= i: continue k = x-(i+j) if k > j and k <= n: ans += 1 print(ans)
Python
zaydzuhri_stack_edu_python
comment Desenvolva um programa que **leia** a **altura** e o peso de uma pessoa, calcule o **IMC** e mostre seu status de acordo com a tabela abaixo: comment < 18.5 | Abaixo do Peso comment < 25 | Peso Ideal comment < 30 | Sobrepeso comment < 40 | Obesidade comment >= 40 | Obesidade Mórbida set altura = decimal input s...
# Desenvolva um programa que **leia** a **altura** e o peso de uma pessoa, calcule o **IMC** e mostre seu status de acordo com a tabela abaixo: # < 18.5 | Abaixo do Peso # < 25 | Peso Ideal # < 30 | Sobrepeso # < 40 | Obesidade # >= 40 | Obesidade Mórbida altura = float(input('Informe a sua altura: ')) peso = float(inp...
Python
zaydzuhri_stack_edu_python
class Solution begin comment recursive solution function isUgly self num begin if num == 1 begin return true end if num <= 0 begin return false end set factors = list 2 3 5 function dfs num begin if num in factors begin return true end for f in factors begin if num % f == 0 and call dfs num // f begin return true end e...
class Solution: # recursive solution def isUgly(self, num: int) -> bool: if num == 1: return True if num <= 0: return False factors = [2, 3, 5] def dfs(num): if num in factors: return True for ...
Python
zaydzuhri_stack_edu_python
function input_user_space count begin for i in range count begin set user_space = integer input append list_spaces user_space end return list_spaces end function function fit_in_overal_space overal_space list_user_spaces begin sort list_user_spaces set fit_in = sum list_user_spaces if fit_in <= overal_space begin print...
def input_user_space(count): for i in range(count): user_space = int(input()) list_spaces.append(user_space) return list_spaces def fit_in_overal_space(overal_space, list_user_spaces): list_user_spaces.sort() fit_in = sum(list_user_spaces) if fit_in <= overal_space: print(l...
Python
zaydzuhri_stack_edu_python
function parameters self begin return dict string maximum_soil_moisture_storage _config at string parameters at 0 ; string initial_soil_moisture_storage _config at string store_ini at 0 ; string solver call get_solver _config ; string start time call get_marrmot_time _config string start ; string end time call get_marr...
def parameters(self) -> dict[str, Any]: return { "maximum_soil_moisture_storage": self._config["parameters"][0], "initial_soil_moisture_storage": self._config["store_ini"][0], "solver": get_solver(self._config), "start time": get_marrmot_time(self._config, "start"...
Python
nomic_cornstack_python_v1
comment coding=utf-8 comment -------------------------------------------------------------------------- comment Copyright (c) Microsoft Corporation. All rights reserved. comment Licensed under the MIT License. See License.txt in the project root for license information. comment Code generated by Microsoft (R) AutoRest ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
Python
jtatman_500k
function kernel self cosmo z ell begin set z = call atleast_1d z comment Extract parameters set tuple pzs m = params at slice : 2 : set kernel = call weak_lensing_kernel cosmo pzs z ell comment If IA is enabled, we add the IA kernel if config at string ia_enabled begin set bias = params at 2 set kernel = kernel + cal...
def kernel(self, cosmo, z, ell): z = np.atleast_1d(z) # Extract parameters pzs, m = self.params[:2] kernel = weak_lensing_kernel(cosmo, pzs, z, ell) # If IA is enabled, we add the IA kernel if self.config["ia_enabled"]: bias = self.params[2] kernel...
Python
nomic_cornstack_python_v1
function create_prefix_list self begin return dict string DEVICES string /aegis/rest/v { api_version } /services/targets/devices ; string JOBS string /aegis/rest/v { api_version } /services/state-machines/jobs ; string INSTANCES string /aegis/rest/v { api_version } /services/state-machines/instances ; string DEBUGGING ...
def create_prefix_list(self): return { # Device Endpoints "DEVICES": f"/aegis/rest/v{self.api_version}/services/targets/devices", # State Machine Endpoints "JOBS": f"/aegis/rest/v{self.api_version}/services/state-machines/jobs", "INSTANCES": f"/aegis/r...
Python
nomic_cornstack_python_v1
string Problem 2 assignment 2 Euler method for differential eqn Name: SAGAR DAM; DNAP import numpy as np from matplotlib import pyplot as plt function f t y begin set z = y / t - y / t ^ 2 return z end function set a = 1 set b = 2 set h = 0.1 set n = b - a / h set t = array range a b h set y = zeros length t set y at 0...
'''Problem 2 assignment 2 Euler method for differential eqn Name: SAGAR DAM; DNAP''' import numpy as np from matplotlib import pyplot as plt def f(t,y): z=(y/t)-(y/t)**2 return z a=1 b=2 h=0.1 n=(b-a)/h t=np.arange(a,b,h) y=np.zeros(len(t)) y[0]=1 ysol=t/(1+np.log(t)) # Solving the given eqn for i in rang...
Python
zaydzuhri_stack_edu_python
import mysql.connector from mysql.connector import errorcode set libDB = none function open_connection begin string Function to open the connection and return it so cursors can be made elsewhere try begin global libDB set libDB = call connect host=string localhost user=string root passwd=string database=string comment...
import mysql.connector from mysql.connector import errorcode libDB=None def open_connection(): """Function to open the connection and return it so cursors can be made elsewhere""" try: global libDB libDB = mysql.connector.connect( host="localhost", user="root", ...
Python
zaydzuhri_stack_edu_python
function penn_to_wn self tag begin if starts with tag string N begin return string n end if starts with tag string V begin return string v end if starts with tag string J begin return string a end if starts with tag string R begin return string r end return none end function
def penn_to_wn(self,tag): if tag.startswith('N'): return 'n' if tag.startswith('V'): return 'v' if tag.startswith('J'): return 'a' if tag.startswith('R'): return 'r' return None
Python
nomic_cornstack_python_v1
function __init__ self ai_game begin call __init__ set screen = screen set settings = settings comment Load the pinata image and set its rect attribute. set image = load image string images/la_pinata.png set rect = call get_rect set zoomed_image = image comment Start each new pinata at the center of the screen set x = ...
def __init__(self, ai_game): super().__init__() self.screen = ai_game.screen self.settings = ai_game.settings # Load the pinata image and set its rect attribute. self.image = pygame.image.load('images/la_pinata.png') self.rect = self.image.get_rect() self.zoomed_image = self.image # Start each new pin...
Python
nomic_cornstack_python_v1
function score_calculator_ai game begin comment Accumulator: store the calculated utility score so far set score_so_far = 0 set board = call get_board comment Score center column set center_array = list for i in list board at tuple slice : : COLUMN // 2 begin append center_array integer i end set center_count = cou...
def score_calculator_ai(game: connect4_game.Connect4Game) -> float: # Accumulator: store the calculated utility score so far score_so_far = 0 board = game.get_board() # Score center column center_array = [] for i in list(board[:, connect4_game.COLUMN // 2]): center_array.append(int(i)) ...
Python
nomic_cornstack_python_v1
string Created on Jun 9, 2016 @author: Lazar-PC function sacuvatiRobu fajl lista begin with open fajl string w as f begin for roba in lista begin write f oznaka write f string | write f naziv write f string | write f opis write f string | write f string tezinaRobe write f string | write f identifikacioniKodPotrazitelja...
''' Created on Jun 9, 2016 @author: Lazar-PC ''' def sacuvatiRobu(fajl,lista): with open(fajl,"w")as f: for roba in lista: f.write(roba.oznaka) f.write("|") f.write(roba.naziv) f.write("|") f.write(roba.opis) f.write("|") ...
Python
zaydzuhri_stack_edu_python
comment @author Tilman Kerl comment @version 2019.01.15 comment Crack higher lower game via selenium comment and brute force learning. comment For further informations see: comment https://github.com/MisterXY89/hlc comment START IMPORT # import pickle from hlc import * comment END IMPORT # function main begin comment i...
############################################# # # @author Tilman Kerl # @version 2019.01.15 # # Crack higher lower game via selenium # and brute force learning. # For further informations see: # https://github.com/MisterXY89/hlc # ############################################# # START IMPORT # import pickle from ...
Python
zaydzuhri_stack_edu_python
import httplib , urllib , urllib2 , cookielib import logging from urlparse import urlparse class RequestHelper begin decorator staticmethod function postCall url headers data begin return call httpCall string POST url headers data end function decorator staticmethod function getConnection scheme host begin set conn = n...
import httplib, urllib, urllib2, cookielib import logging from urlparse import urlparse class RequestHelper: @staticmethod def postCall(url, headers, data): return RequestHelper.httpCall("POST", url, headers, data) @staticmethod def getConnection(scheme, host): conn = None if(scheme...
Python
zaydzuhri_stack_edu_python
from array import array function sort_alphabet_array text begin string Converts text to its corresponding integer alphabet representation set sigma = 0 for c in text begin if ordinal c > sigma begin set sigma = ordinal c end end set b = array string l list 0 * sigma + 1 for c in text begin set b at ordinal c = 1 end se...
from array import array def sort_alphabet_array(text): """Converts text to its corresponding integer alphabet representation""" sigma = 0 for c in text: if ord(c) > sigma: sigma = ord(c) b = array("l", [0] * (sigma + 1)) for c in text: b[ord(c)] = 1 alpha = [] ...
Python
zaydzuhri_stack_edu_python
function taggedSentsWithTranslations self begin set sents = list for tuple infile tree in annotationtrees begin for utterance in call getTree begin if locale != none and utterance at 4 != locale begin continue end if participant != none and utterance at 5 != participant begin continue end set words = list for word in...
def taggedSentsWithTranslations(self): sents = [] for (infile, tree) in self.annotationtrees: for utterance in tree.getTree(): if self.locale != None and utterance[4] != self.locale: continue if self.participant != None and utterance[5] != ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import datetime comment Data set donors_amts = dict string Gates dict string title string Mr. ; string donations 150000 ; string num_of_donations 3 ; string Brin dict string title string Mr. ; string donations 150000 ; string num_of_donations 3 ; string Cerf dict string title string Mr. ; ...
#!/usr/bin/env python3 import datetime # Data donors_amts = {'Gates': {'title': 'Mr.', 'donations': 150000, 'num_of_donations': 3}, 'Brin': {'title': 'Mr.', 'donations': 150000, 'num_of_donations': 3}, 'Cerf': {'title': 'Mr.', 'donations': ...
Python
zaydzuhri_stack_edu_python
import json import requests import re import sys from pprint import pprint from docopt import docopt from stations_name import stations from stations_name import stations_res from prettytable import PrettyTable string url1 = 'https://kyfw.12306.cn/otn/leftTicket/queryA?leftTicketDTO.train_date=2018-10-04&leftTicketDTO....
import json import requests import re import sys from pprint import pprint from docopt import docopt from stations_name import stations from stations_name import stations_res from prettytable import PrettyTable '''url1 = 'https://kyfw.12306.cn/otn/leftTicket/queryA?leftTicketDTO.train_date=2018-10-04&leftTic...
Python
zaydzuhri_stack_edu_python
from os import name from webcrawlers.models import Brand import scrapy from items import BrandScraperItem class BrandsSpider extends Spider begin set name = string brands set start_urls = list string http://www.sephora.com/brands-list function parse self response begin for brand in call xpath string //a[@data-at="brand...
from os import name from webcrawlers.models import Brand import scrapy from ..items import BrandScraperItem class BrandsSpider(scrapy.Spider): name = 'brands' start_urls = ['http://www.sephora.com/brands-list'] def parse(self, response): for brand in response.xpath('//a[@data-at="brand_link"]'):...
Python
zaydzuhri_stack_edu_python
from CorpusToolkit.ply_parser.token import Token import ply.lex as lex import ply.yacc as yacc comment option to process function set option_merge_sub_token = false set tokens = tuple string SLASH string OPEN_BRACE string CLOSE_BRACE string OPEN_BRACKET string CLOSE_BRACKET string TOKEN_OR_POS_OR_PINYIN comment Tokens ...
from CorpusToolkit.ply_parser.token import Token import ply.lex as lex import ply.yacc as yacc # option to process function option_merge_sub_token = False tokens = ( 'SLASH', 'OPEN_BRACE', 'CLOSE_BRACE', 'OPEN_BRACKET', 'CLOSE_BRACKET', 'TOKEN_OR_POS_OR_PINYIN', ) # Tokens t_SLASH = r'/' t_OPEN_B...
Python
zaydzuhri_stack_edu_python
while want == true begin set inp = input string Quer digitar um numero ? (Y or N): if inp == string y or inp == string Y begin set number = input string Digite: print number set count = count + 1 end else begin set want = false print string ok print string voce inseriu + string count + string vezes end end
while want==True : inp = input("Quer digitar um numero ? (Y or N): ") if inp=="y" or inp=="Y": number = input("Digite:") print(number) count=count+1 else : want = False print("ok") print("voce inseriu " + str(count) + " vezes")
Python
zaydzuhri_stack_edu_python
function indexLocations self begin from ent.dom.Location import Location set index = dict set locations = call fetchall Location for location in locations begin set index at id = location end return index end function
def indexLocations(self): from ent.dom.Location import Location index = {} locations = self.db.fetchall(Location) for location in locations: index[location.id] = location return index
Python
nomic_cornstack_python_v1
comment None # Python's version of null comment Returns nothing, but the data type is set properly comment none comment returns NameError: name 'none' is not defined comment Ex: Application requires user PII, such as Name, age, child, child age: set name = string Daisy set age = 30 comment Daisy has no children -> This...
# None # Python's version of null # Returns nothing, but the data type is set properly # none # returns NameError: name 'none' is not defined # Ex: Application requires user PII, such as Name, age, child, child age: name = "Daisy" age = 30 child = None # Daisy has no children -> This allows us to call the variable...
Python
zaydzuhri_stack_edu_python
comment Automatically adapted for scipy Oct 21, 2005 by comment Author: Travis Oliphant set __all__ = list string odeint import _odepack from copy import copy set _msgs = dict 2 string Integration successful. ; - 1 string Excess work done on this call (perhaps wrong Dfun type). ; - 2 string Excess accuracy requested (t...
## Automatically adapted for scipy Oct 21, 2005 by # Author: Travis Oliphant __all__ = ['odeint'] import _odepack from copy import copy _msgs = {2: "Integration successful.", -1: "Excess work done on this call (perhaps wrong Dfun type).", -2: "Excess accuracy requested (tolerances too small).", ...
Python
zaydzuhri_stack_edu_python
function test_load_unsupported_format self tmpdir begin set source_f = join tmpdir string foo.xml write source_f string <foo>bar</foo> set schema_f = join tmpdir string bar.xml write schema_f string <foo>bar</foo> with raises CoreError as ex begin call Core source_file=string source_f end assert string Unable to load s...
def test_load_unsupported_format(self, tmpdir): source_f = tmpdir.join("foo.xml") source_f.write("<foo>bar</foo>") schema_f = tmpdir.join("bar.xml") schema_f.write("<foo>bar</foo>") with pytest.raises(CoreError) as ex: Core(source_file=str(source_f)) assert ...
Python
nomic_cornstack_python_v1
function bdev_crypto_create client base_bdev_name name crypto_pmd=none key=none cipher=none key2=none key_name=none begin set params = dict string base_bdev_name base_bdev_name ; string name name if crypto_pmd is not none begin set params at string crypto_pmd = crypto_pmd end if key is not none begin set params at stri...
def bdev_crypto_create(client, base_bdev_name, name, crypto_pmd=None, key=None, cipher=None, key2=None, key_name=None): params = {'base_bdev_name': base_bdev_name, 'name': name} if crypto_pmd is not None: params['crypto_pmd'] = crypto_pmd if key is not None: params['key'] = key if key2 ...
Python
nomic_cornstack_python_v1
import math function is_prime num begin string Function to check if a number is prime. if num <= 1 begin return false end for i in range 2 integer square root num + 1 begin if num % i == 0 begin return false end end return true end function function sum_of_primes n begin string Function to find the sum of all prime num...
import math def is_prime(num): """ Function to check if a number is prime. """ if num <= 1: return False for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True def sum_of_primes(n): """ Function to find the sum of all prime num...
Python
greatdarklord_python_dataset
import random from functools import wraps import os import copy class Tetris begin function __init__ self height=20 width=10 begin set mapWidth = width set mapHeight = height set map = list set emptyMapVal = - 1 set score = 0 set blocksCounter = 0 set destroyedLines = 0 set holdedBlock = 7 set lastHoldedBlockNumber = ...
import random from functools import wraps import os import copy class Tetris: def __init__(self, height=20, width=10): self.mapWidth = width self.mapHeight = height self.map = [] self.emptyMapVal = -1 self.score = 0 self.blocksCounter = 0 self.destroyedLine...
Python
zaydzuhri_stack_edu_python
function GetParams self begin raise call NotImplementedError end function
def GetParams(self): raise NotImplementedError()
Python
nomic_cornstack_python_v1
comment !/bin/python3 import math set x = integer input set y = integer input print string integer round call degrees call atan x / y + string °
#!/bin/python3 import math x = int(input()) y = int(input()) print(str(int(round(math.degrees(math.atan(x/y)))))+'°')
Python
zaydzuhri_stack_edu_python
function dtype self begin warning string %s dtype unimplemented self return int end function
def dtype(self) -> Type: self.LOGGER.warning("%s dtype unimplemented", self) return int
Python
nomic_cornstack_python_v1
function download_to_stream self filename begin debug string -> downloading to stream: + filename set key = _basename + filename try begin set response = call get_object Bucket=_bucket Key=key end except ClientError as e begin set code = response at string Error at string Code if code == string NoSuchKey or code == str...
def download_to_stream(self, filename): logger.debug("-> downloading to stream: " + filename) key = self._basename + filename try: response = self._s3.get_object(Bucket=self._bucket, Key=key) except botocore.exceptions.ClientError as e: code = e.response['Error'][...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Jun 28 20:30:54 2019 @author: barbara.barbosa string 1) Faça um script para estimar o valor de π utilizando o método de Monte Carlo.0 import random import numpy as np import matplotlib.pyplot as plt import pandas as pd set N = 100000 set x = call rand N set y = call r...
# -*- coding: utf-8 -*- """ Created on Fri Jun 28 20:30:54 2019 @author: barbara.barbosa """ """ 1) Faça um script para estimar o valor de π utilizando o método de Monte Carlo.0 """ import random import numpy as np import matplotlib.pyplot as plt import pandas as pd N=100000 x=np.random.rand(N) ...
Python
zaydzuhri_stack_edu_python
async function logging self ctx begin set author = author set server = server set channel = channel set isAdmin = administrator if not isAdmin begin set checkAdmin = call getServerStat server string AdminArray for role in roles begin for aRole in checkAdmin begin comment Get the role that corresponds to the id if aRole...
async def logging(self, ctx): author = ctx.message.author server = ctx.message.server channel = ctx.message.channel isAdmin = ctx.message.author.permissions_in(ctx.message.channel).administrator if not isAdmin: checkAdmin = self.settings.getServerStat(ctx.message.s...
Python
nomic_cornstack_python_v1
comment case 1 class Person begin comment class attriburte because it is defined inside class and not inside any method set no_of_people = 0 function __init__ self name begin set name = name print string { name } end function end class set p1 = call Person string harry set p2 = call Person string mosh print no_of_peopl...
#case 1 class Person: no_of_people = 0#class attriburte because it is defined inside class and not inside any method def __init__(self, name): self.name = name print(f"{self.name}") p1 = Person("harry") p2 = Person("mosh") print(Person.no_of_people) #or print(p1.no_of_people) print("---------------------...
Python
zaydzuhri_stack_edu_python
comment noqa: E501 function get_user_role_by_id role_id begin return string do some magic! end function
def get_user_role_by_id(role_id): # noqa: E501 return 'do some magic!'
Python
nomic_cornstack_python_v1
function home begin return call render_template string index.html title=string Automation Center year=year message=string Welcome to the Automation Center end function
def home(): return render_template( 'index.html', title='Automation Center', year=datetime.now().year, message='Welcome to the Automation Center' )
Python
nomic_cornstack_python_v1
function put self key val begin comment tree already has a root if root begin call _put key val root end else begin set root = call TreeNode key val end set size = size + 1 end function
def put(self, key, val): if self.root: # tree already has a root self._put(key, val, self.root) else: self.root = TreeNode(key, val) self.size += 1
Python
nomic_cornstack_python_v1
from math import sin , cos , pi import pygame from constants import BACKGROUND , GRASS , WIN , RED class Vision begin string Vision object represent vision for every single Car object function __init__ self begin set visible = false end function function make_points self center angle begin string determinate distances ...
from math import sin, cos, pi import pygame from .constants import BACKGROUND, GRASS, WIN, RED class Vision(): ''' Vision object represent vision for every single Car object ''' def __init__(self): self.visible = False def make_points(self, center, angle): ''' ...
Python
zaydzuhri_stack_edu_python
string Neural net implementation of electric load forecasting. import pickle import numpy as np import pandas as pd from datetime import datetime as dt from scipy.stats import zscore comment NERC6 holidays with inconsistent dates. Created with python holidays package comment years 1990 - 2024 with open string holidays....
""" Neural net implementation of electric load forecasting. """ import pickle import numpy as np import pandas as pd from datetime import datetime as dt from scipy.stats import zscore # NERC6 holidays with inconsistent dates. Created with python holidays package # years 1990 - 2024 with open('holidays.pickle', 'rb') ...
Python
zaydzuhri_stack_edu_python
function string_to_decimal value strict=true begin string Return a decimal corresponding to the string representation of a number. @param value: a string representation of an decimal number. @param strict: indicate whether the specified string MUST be of a valid decimal number representation. @return: the decimal value...
def string_to_decimal(value, strict=True): """ Return a decimal corresponding to the string representation of a number. @param value: a string representation of an decimal number. @param strict: indicate whether the specified string MUST be of a valid decimal number representation. @...
Python
jtatman_500k
function batch_rodrigues theta dtype=float32 begin set l1norm = norm theta + 1e-08 p=2 dim=1 set angle = unsqueeze torch l1norm - 1 set normalized = call div theta angle set angle = angle * 0.5 set v_cos = cos angle set v_sin = sin angle set quat = call cat list v_cos v_sin * normalized dim=1 return decimal end functio...
def batch_rodrigues(theta, dtype=torch.float32): l1norm = torch.norm(theta + 1e-8, p = 2, dim = 1) angle = torch.unsqueeze(l1norm, -1) normalized = torch.div(theta, angle) angle = angle * 0.5 v_cos = torch.cos(angle) v_sin = torch.sin(angle) quat = torch.cat([v_cos, v_sin * normalized], dim...
Python
nomic_cornstack_python_v1
function start_date self value begin set _start_date = value end function
def start_date(self, value): self._start_date = value
Python
nomic_cornstack_python_v1
import os import re import json import math import time import doctest function find target lst property begin for o in lst begin if target == o at property begin return o end end end function function read filename file_type=string json begin try begin set data = call readFile filename file_type=file_type end except a...
import os import re import json import math import time import doctest def find(target, lst, property): for o in lst: if target == o[property]: return o def read(filename, file_type='json'): try: data = readFile(filename, file_type=file_type) except: bakfilename = '%s_b...
Python
zaydzuhri_stack_edu_python
function setAllData self newdata begin set listdata = newdata call beginResetModel call endResetModel end function
def setAllData(self, newdata): self.listdata = newdata self.beginResetModel() self.endResetModel()
Python
nomic_cornstack_python_v1
function resequence associations begin set counters = default dictionary lambda -> default dictionary Counter for asn in associations begin set sequence = next counters at data at string asn_id at data at string asn_type end end function
def resequence(associations): counters = defaultdict(lambda: defaultdict(Counter)) for asn in associations: asn.sequence = next( counters[asn.data['asn_id']][asn.data['asn_type']] )
Python
nomic_cornstack_python_v1
function learn_without_outcome self begin set PE = 0 - values at stim_chosen set values at stim_chosen = values at stim_chosen + alpha_n * PE return values at stim_chosen end function
def learn_without_outcome(self): self.PE = 0 - self.values[self.stim_chosen] self.values[self.stim_chosen] += self.alpha_n * self.PE return self.values[self.stim_chosen]
Python
nomic_cornstack_python_v1
function clone self begin return call Rule_clone self end function
def clone(self): return _libsbml.Rule_clone(self)
Python
nomic_cornstack_python_v1
async function test_state_color aresponses begin add aresponses string example.com:9123 string /elgato/lights string GET call Response status=200 headers=dict string Content-Type string application/json text=call load_fixture string state-color.json async_with call ClientSession as session begin set elgato = call Elgat...
async def test_state_color(aresponses): aresponses.add( "example.com:9123", "/elgato/lights", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, text=load_fixture("state-color.json"), ), ) async wi...
Python
nomic_cornstack_python_v1
function crccat vec begin return 0 == call calc call unhex sub string [^0-9a-fA-F] string vec end function
def crccat(vec): return 0 == calc(unhex(re.sub(r"[^0-9a-fA-F]", "", vec)))
Python
nomic_cornstack_python_v1
function test_fma_invalid_param_intarray_bytes_bytes_none_698 self begin comment This version is expected to pass. call fma floatarrayx floatarrayy floatarrayz comment This is the actual test. with assert raises TypeError begin call fma intarrayx bytesy bytesz end end function
def test_fma_invalid_param_intarray_bytes_bytes_none_698(self): # This version is expected to pass. arrayfunc.fma(self.floatarrayx, self.floatarrayy, self.floatarrayz) # This is the actual test. with self.assertRaises(TypeError): arrayfunc.fma(self.intarrayx, self.bytesy, self.bytesz)
Python
nomic_cornstack_python_v1
import os from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session , sessionmaker comment database engine object from SQLAlchemy that manages connections to the database set engine = call create_engine call getenv string DATABASE_URL comment DATABASE_URL is an environment variable that indicates w...
import os from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker # database engine object from SQLAlchemy that manages connections to the database engine = create_engine(os.getenv("DATABASE_URL")) # DATABASE_URL is an environment variable that indicates where the database lives #...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment # **NEURAL NETWORK USING STOCHASTIC GRADIENT DESCENT** comment by **Jean Carlo Codogno** - 17/03/2018 comment <br/> comment + **INTRODUCTION** comment + **DATA EXPLORATION** comment + IMPORT THE DATASET comment + VISUALIZATION OF THE DATA comment + COUNT OF EXAMPLES PER DIGIT comment + NOR...
# coding: utf-8 # # **NEURAL NETWORK USING STOCHASTIC GRADIENT DESCENT** # by **Jean Carlo Codogno** - 17/03/2018 # # <br/> # # + **INTRODUCTION** # + **DATA EXPLORATION** # + IMPORT THE DATASET # + VISUALIZATION OF THE DATA # + COUNT OF EXAMPLES PER DIGIT # + NORMALIZATION # ...
Python
zaydzuhri_stack_edu_python
function retract self begin comment close the gripper call close_gripper force=60 sleep 1.0 comment lift object set delta = 0.2 set joints = call get_joints joint_listener set T = call forward_kinematics joints at slice : - 2 : print string T in retract T set T_lift = copy T set T_lift at tuple 2 3 = T_lift at tuple 2...
def retract(self): # close the gripper self.moveit.close_gripper(force=60) rospy.sleep(1.0) # lift object delta = 0.20 joints = get_joints(self.joint_listener) T = self.moveit.forward_kinematics(joints[:-2]) print('T in retract', T) T_lift = T...
Python
nomic_cornstack_python_v1
function plot_cloud_mask mask figsize=tuple 15 15 fig=none begin if fig == none begin figure figsize=figsize end image show mask cmap=gray end function
def plot_cloud_mask(mask, figsize=(15, 15), fig=None): if fig == None: plt.figure(figsize=figsize) plt.imshow(mask, cmap=plt.cm.gray)
Python
nomic_cornstack_python_v1
while loop == true begin set username = input string Please input your username: if username != string techkids begin print string You are not superuser end else if username == string techkids begin set password = input string Please input the pass word: if password == string codethechange begin print string Welcome, s...
while loop == True: username = input("Please input your username: ") if username != "techkids": print("You are not superuser") elif username == "techkids" : password = input("Please input the pass word: ") if password == "codethechange": print("Welcome, superuser") ...
Python
zaydzuhri_stack_edu_python
function explode_left match begin set left = integer match at 0 set right = integer pair at 1 return string { left + right } end function
def explode_left(match: re.Match) -> str: left = int(match[0]) right = int(pair[1]) return f"{left + right}"
Python
nomic_cornstack_python_v1
function _validate_column column column_name df_name schema_def begin set errors = list if get schema_def string unique begin if call nunique != length column begin append errors string Column { column_name } in dataframe { df_name } is not unique. end end if string nullable in schema_def and not schema_def at string ...
def _validate_column(column, column_name, df_name, schema_def): errors = [] if schema_def.get("unique"): if column.nunique() != len(column): errors.append(f"Column {column_name} in dataframe {df_name} is not unique.") if "nullable" in schema_def and not schema_def["nullable"]: ...
Python
nomic_cornstack_python_v1
function data_for_sorting fletcher_type fletcher_array begin return call fletcher_array data_for_sorting dtype=dtype end function
def data_for_sorting(fletcher_type, fletcher_array): return fletcher_array(fletcher_type.data_for_sorting, dtype=fletcher_type.dtype)
Python
nomic_cornstack_python_v1
function _watchFolder self begin set wm = call WatchManager call add_watch gdocs_folder IN_MODIFY rec=true set handler = call EventHandler self set notifier = call Notifier wm handler end function
def _watchFolder(self): wm = pyinotify.WatchManager() wm.add_watch(self.gdocs_folder, pyinotify.IN_MODIFY, rec=True) handler = EventHandler(self) notifier = pyinotify.Notifier(wm, handler)
Python
nomic_cornstack_python_v1
function name self begin return get pulumi self string name end function
def name(self) -> str: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
function test_token_aulteration self begin set token_values = call create_token set a = encode string a string utf-8 set token = token_values at string token + a assert false call verify_authentication_token token end function
def test_token_aulteration(self): token_values = self.create_token() a = 'a'.encode('utf-8') token = token_values['token'] + a self.assertFalse( token_values['user'].verify_authentication_token(token) )
Python
nomic_cornstack_python_v1
function RebinHist hist name bins begin import array set bins_ = array string d bins return call Rebin length bins_ - 1 string rebinned_ + name bins_ end function
def RebinHist(hist,name,bins): import array bins_ = array.array('d',bins) return hist.Rebin(len(bins_)-1,"rebinned_"+name,bins_)
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python import os import random import pygame set environ at string SDL_VIDEO_CENTERED = string 1 set walls = list set rec_width = 16 set width = 20 * rec_width set height = rec_width * 20 set player = none set BLACK = tuple 0 0 0 set previous_rect = none comment Class for the orange dude class P...
#! /usr/bin/env python import os import random import pygame os.environ["SDL_VIDEO_CENTERED"] = "1" walls = [] rec_width = 16 width = 20*rec_width height =rec_width*20 player = None BLACK = ( 0, 0, 0) previous_rect =None # Class for the orange dude class Player(object): def __init__(self, positionx,positio...
Python
zaydzuhri_stack_edu_python
function gram_matrix self begin try begin return __gram_matrix end except AttributeError begin pass end set M = list set A = __basis set B = list comprehension call conjugate for z in __basis set two = call QQ 2 set m = list comprehension two * call reduced_trace for b in B for a in A set M44 = call MatrixSpace QQ 4 s...
def gram_matrix(self): try: return self.__gram_matrix except AttributeError: pass M = [] A = self.__basis B = [z.conjugate() for z in self.__basis] two = QQ(2) m = [two*(a*b).reduced_trace() for b in B for a in A] M44 = MatrixSpace(QQ, 4) G = M44(m...
Python
nomic_cornstack_python_v1
import praw import json import boto3 import os set s3 = call resource string s3 comment enter reddit credentials here set reddit = call Reddit client_id=string ot3GaEquEnOMGg client_secret=string bIjzZxOdVUlmH-Ljdr4AqvLuv18 user_agent=string scrapey username=string hcde_research password=string hcde_research function s...
import praw import json import boto3 import os s3 = boto3.resource('s3') #enter reddit credentials here reddit = praw.Reddit(client_id='ot3GaEquEnOMGg', \ client_secret='bIjzZxOdVUlmH-Ljdr4AqvLuv18', \ user_agent='scrapey', \ username='hcde_research', \ ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- class Installation begin string Variable and class declaration set installationName = string set installation_id = 0 set cityName = string set zipCode = string set installationAdress = string set longitude = 0 set latitude = 0 set disabledAdapted = false f...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Installation: """ Variable and class declaration """ installationName = "" installation_id = 0 cityName = "" zipCode = "" installationAdress ="" longitude = 0 latitude = 0 disabledAdapted = False def __init__(self, in...
Python
zaydzuhri_stack_edu_python
import pygame from constants import * from groups import projectile_group from loaders.imageloader import animation_lists from abstract.gravityobject import GravityObject from projectiles.bullet import Bullet class Entity extends GravityObject begin function __init__ self x y char_type health speed shoot_delay begin ca...
import pygame from constants import * from groups import projectile_group from loaders.imageloader import animation_lists from abstract.gravityobject import GravityObject from projectiles.bullet import Bullet class Entity(GravityObject): def __init__(self, x: int, y: int, char_type: str, health: int, speed: int, ...
Python
zaydzuhri_stack_edu_python
function subsets_of_string string begin set subset_string = list set length = length string for i in range length begin for j in range i length begin append subset_string string at slice i : j + 1 : end end return subset_string end function
def subsets_of_string(string): subset_string = [] length = len(string) for i in range(length): for j in range(i, length): subset_string.append(string[i:j+1]) return subset_string
Python
nomic_cornstack_python_v1
function sum A i j begin set sum = 0 for k in range i j begin set sum = sum + A at k end return sum end function function max_subarray_sum_cubic A n begin set max_subarray = list set max_subarray_sum = 0 for i in range n begin for j in range i n begin if sum A i j > max_subarray_sum begin set max_subarray_sum = sum A ...
def sum(A,i,j): sum=0 for k in range(i,j): sum+=A[k] return sum def max_subarray_sum_cubic(A,n): max_subarray=[] max_subarray_sum=0 for i in range(n): for j in range(i,n): if(sum(A,i,j)>max_subarray_sum): max_subarray_sum=sum(A,i,j) ...
Python
zaydzuhri_stack_edu_python