code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function _print self msg msg_args begin comment XXX: Not using the logger framework: need to comment learn to use logger better. if not verbose begin return end if verbose < 50 begin set writer = write end else begin set writer = write end set msg = msg % msg_args writer string [%s]: %s % tuple self msg end function
def _print(self, msg, msg_args): # XXX: Not using the logger framework: need to # learn to use logger better. if not self.verbose: return if self.verbose < 50: writer = sys.stderr.write else: writer = sys.stdout.write msg = msg...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import rospy import signal import sys import numpy as np import math from std_msgs.msg import Int16 from std_msgs.msg import Float32 from geometry_msgs.msg import Pose from nav_msgs.msg import Odometry comment allow user to terminate script with CTRL+C function signal_handler signal frame b...
#!/usr/bin/env python import rospy import signal import sys import numpy as np import math from std_msgs.msg import Int16 from std_msgs.msg import Float32 from geometry_msgs.msg import Pose from nav_msgs.msg import Odometry # allow user to terminate script with CTRL+C def signal_handler(signal, frame): sys....
Python
zaydzuhri_stack_edu_python
function test_fma_invalid_param_str_floatnum_intarray_floatarray_1308 self begin comment This version is expected to pass. call fma floatarrayx floatnumy floatarrayz floatarrayout comment This is the actual test. with assert raises TypeError begin call fma strx floatnumy intarrayz floatarrayout end end function
def test_fma_invalid_param_str_floatnum_intarray_floatarray_1308(self): # This version is expected to pass. arrayfunc.fma(self.floatarrayx, self.floatnumy, self.floatarrayz, self.floatarrayout) # This is the actual test. with self.assertRaises(TypeError): arrayfunc.fma(self.strx, self.floatnumy, self.intarr...
Python
nomic_cornstack_python_v1
function _set_cost self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=call RestrictedClassType base_type=long restriction_dict=dict string range list string 0..4294967295 int_size=32 is_leaf=true yang_name=string cost parent=self path_help...
def _set_cost(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="cost", parent=self, path_helper=self._path_helper, extmethods=self._extm...
Python
nomic_cornstack_python_v1
class Good extends object begin function __init__ self price begin set price = price end function end class class House extends Good begin function __init__ self begin call __init__ price=200000.0 end function end class
class Good(object): def __init__(self, price): self.price = price class House(Good): def __init__(self): super().__init__(price=2e5)
Python
zaydzuhri_stack_edu_python
function vim_command_mode_exterm cmd begin set v = call VimMode call set_command_mode_exterm insert actions cmd end function
def vim_command_mode_exterm(cmd: str): v = VimMode() v.set_command_mode_exterm() actions.insert(cmd)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python set str1 = string abcdefghiJKLmnopqrstuvwxyz print upper str1 print is upper str1 set guido = string ABCDEFGHIJKLMNOPQRSTUVWXYZ print is upper guido
#!/usr/bin/python str1 = "abcdefghiJKLmnopqrstuvwxyz" print (str1.upper()) print (str1.isupper()) guido = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' print(guido.isupper())
Python
zaydzuhri_stack_edu_python
function to_str self begin return call pformat call to_dict end function
def to_str(self): return pprint.pformat(self.to_dict())
Python
nomic_cornstack_python_v1
function test_extended_dn self begin set client = call LDAPClient url assert raises TypeError lambda -> call set_extended_dn string A assert raises ValueError lambda -> call set_extended_dn 2 set extended_dn_format = 0 assert equal extended_dn_format 0 set conn = call connect set root_dse = call get_rootDSE set resul...
def test_extended_dn(self): client = LDAPClient(self.url) self.assertRaises(TypeError, lambda: client.set_extended_dn("A")) self.assertRaises(ValueError, lambda: client.set_extended_dn(2)) client.extended_dn_format = 0 self.assertEqual(client.extended_dn_format, 0) conn =...
Python
nomic_cornstack_python_v1
function _labels_to_state scan_label compscan_label begin if not scan_label or scan_label == string slew begin return string slew end if scan_label == string cal begin return string track end return if expression compscan_label == string track then string track else string scan end function
def _labels_to_state(scan_label, compscan_label): if not scan_label or scan_label == 'slew': return 'slew' if scan_label == 'cal': return 'track' return 'track' if compscan_label == 'track' else 'scan'
Python
nomic_cornstack_python_v1
function dotProduct v1 v2 begin set n1 = call normalize v1 set n2 = call normalize v2 return n1 at 0 * n2 at 0 + n1 at 1 * n2 at 1 + n1 at 2 * n2 at 2 end function
def dotProduct(v1, v2): n1 = normalize(v1) n2 = normalize(v2) return n1[0] * n2[0] + n1[1] * n2[1] + n1[2] * n2[2]
Python
nomic_cornstack_python_v1
function run self begin set rate = call Rate _run_rate while not call is_shutdown begin try begin sleep end except any begin break end end end function
def run(self): rate = rospy.Rate(self._run_rate) while not rospy.is_shutdown(): try: rate.sleep() except: break
Python
nomic_cornstack_python_v1
function invert_safe x begin try begin return call invert x end except ZeroDivisionError as e begin return string e end end function
def invert_safe(x): try: return invert(x) except ZeroDivisionError as e: return str(e)
Python
nomic_cornstack_python_v1
from typing import List string 解法:双指针 - 时间复杂度:O(N) - 空间复杂度:O(1) class Solution begin function validMountainArray self A begin set tuple l r = tuple 0 length A - 1 while l < r and A at l < A at l + 1 begin set l = l + 1 end while r > l and A at r < A at r - 1 begin set r = r - 1 end return l == r and l != 0 and r != len...
from typing import List """解法:双指针 - 时间复杂度:O(N) - 空间复杂度:O(1) """ class Solution: def validMountainArray(self, A: List[int]) -> bool: l,r=0,len(A)-1 while l<r and A[l]<A[l+1]: l+=1 while r>l and A[r]<A[r-1]: r-=1 return l==r and l!=0 and r!=len(A)-1 if __name__ == "__main__": A =...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python function solve B O seq begin set Bpos = 1 set Opos = 1 set sec = 0 set pushed = false while length B > 0 or length O > 0 begin if B != list begin if B at 0 < Bpos begin set Bpos = Bpos - 1 end else if B at 0 > Bpos begin set Bpos = Bpos + 1 end else if B at 0 == Bpos and seq at 0 == string...
#!/usr/bin/env python def solve(B, O, seq): Bpos = 1 Opos = 1 sec = 0 pushed = False while (len(B) > 0 or len(O) > 0): if B != []: if B[0] < Bpos: Bpos -= 1 elif B[0] > Bpos: Bpos += 1 elif B[0] == Bpos and seq[0] == 'B': del B[0] pushed = True if O != []: if O[0] < Opos: Opos...
Python
zaydzuhri_stack_edu_python
function get_hands_copy self begin set copied_hands = dict for player in PLAYERS begin set copied_hands at player = dictionary hands at player end return copied_hands end function
def get_hands_copy(self) -> Dict[str, Dict[str, int]]: copied_hands = {} for player in PLAYERS: copied_hands[player] = dict(self.hands[player]) return copied_hands
Python
nomic_cornstack_python_v1
import tensorflow as tf import numpy as np set Nclass = 500 set D = 2 set M = 3 set K = 3 set X1 = randn Nclass 2 + array list 0 - 2 set X2 = randn Nclass 2 + array list 2 2 set X3 = randn Nclass 2 + array list - 2 2 set X = as type vertical stack list X1 X2 X3 float32 set Y = array list 0 * Nclass + list 1 * Nclass + ...
import tensorflow as tf import numpy as np Nclass = 500 D = 2 M = 3 K = 3 X1 = np.random.randn(Nclass, 2) + np.array([0,-2]) X2 = np.random.randn(Nclass, 2) + np.array([2, 2]) X3 = np.random.randn(Nclass, 2) + np.array([-2, 2]) X = np.vstack([X1, X2, X3]).astype(np.float32) Y = np.array([0]*Nclass + [1]*Nclass + [2]...
Python
zaydzuhri_stack_edu_python
function _convert_by_score score_path max_pixels_to_convert out_raster_path convert_value stats_cache score_weight begin function _flush_cache_to_band data_array row_array col_array valid_index dirty_blocks out_band stats_counter begin string Flush block cache to the output band. Provided as an internal function becaus...
def _convert_by_score( score_path, max_pixels_to_convert, out_raster_path, convert_value, stats_cache, score_weight): def _flush_cache_to_band( data_array, row_array, col_array, valid_index, dirty_blocks, out_band, stats_counter): """Flush block cache to the output ba...
Python
nomic_cornstack_python_v1
function has_app self begin if app is none begin return false end return true end function
def has_app(self): if self.app is None: return False return True
Python
nomic_cornstack_python_v1
function factorial n begin if n < 0 begin raise call ValueError string Factorial is not defined for negative numbers end else if n == 0 begin return 1 end else begin set result = 1 for i in range 1 n + 1 begin set result = result * i end return result end end function
def factorial(n): if n < 0: raise ValueError("Factorial is not defined for negative numbers") elif n == 0: return 1 else: result = 1 for i in range(1, n+1): result *= i return result
Python
jtatman_500k
function test_files_present self changes_file begin for filename in call get_files begin debug string Looking whether %s was actually uploaded % filename if is file path join path config at string debexpo.upload.incoming filename begin debug string %s is present % filename end else begin critical string %s is not prese...
def test_files_present(self, changes_file): for filename in changes_file.get_files(): log.debug('Looking whether %s was actually uploaded' % filename) if os.path.isfile(os.path.join(pylons.config['debexpo.upload.incoming'], filename)): log.debug('%s is present' % filename...
Python
nomic_cornstack_python_v1
import random import numpy as np import GameConstants as game from PlayerData import PlayerData from Card import Card from Tile import Tile class State begin function __init__ self adversarial=true do_reset=true begin comment Game set turn = 0 set current_player = 0 set TARGET_REACHED = false set GAME_ENDED = false com...
import random import numpy as np import GameConstants as game from PlayerData import PlayerData from Card import Card from Tile import Tile class State: def __init__(self, adversarial=True, do_reset=True): # Game self.turn = 0 self.current_player = 0 self.TARGET_REACHED = False ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import datetime as dt import os class PriceHistoryBuilder begin function __init__ self symbol=none interval=61 begin set symbol = symbol set interval = interval set filename = get current directory + string / + symbol + string .csv end function function BuildHistory self begin string Prompt for the ...
import pandas as pd import datetime as dt import os class PriceHistoryBuilder: def __init__(self, symbol=None, interval=61): self.symbol = symbol self.interval = interval self.filename = os.getcwd() + '/' + self.symbol + '.csv' def BuildHistory(self): '''Prompt for the input o...
Python
zaydzuhri_stack_edu_python
function cp_with_ignore file_name_ignore source_dir target_dir ignore_path=string exps begin comment file_names = os.listdir(source_dir) if file_name_ignore is not none begin with open file_name_ignore string r+ as f begin set ignore_files = read lines f set ignore_files = list comprehension strip strip ignore_file str...
def cp_with_ignore(file_name_ignore, source_dir, target_dir, ignore_path='exps'): # file_names = os.listdir(source_dir) if file_name_ignore is not None: with open(file_name_ignore, 'r+') as f: ignore_files = f.readlines() ignore_files = [ignore_file.strip('\r').strip('\n') for i...
Python
nomic_cornstack_python_v1
import re class SocialMediaExtractor begin string This class should extract social medias cited in some text as well as generic hiperlinks to be used eventually in natural language processing projects. set __social_media = set list string facebook string instagram string twitter string youtube decorator staticmethod fu...
import re class SocialMediaExtractor(): """ This class should extract social medias cited in some text as well as generic hiperlinks to be used eventually in natural language processing projects. """ __social_media = set(['facebook', 'instagram', 'twitter', 'youtube']) @staticmethod ...
Python
zaydzuhri_stack_edu_python
from Data_Structures.Double_Linked_List import Double_Linked_List class Header extends Double_Linked_List begin function __init__ self begin call __init__ self end function function insert self new_node begin comment list empty and retur node first if first is none begin set first = new_node set last = new_node return ...
from Data_Structures.Double_Linked_List import Double_Linked_List class Header(Double_Linked_List): def __init__(self): Double_Linked_List.__init__(self) def insert(self, new_node): if self.first is None: #list empty and retur node first self.first = new_node self.last ...
Python
zaydzuhri_stack_edu_python
import unittest from random import random from tdasm import Runtime from renmas3.base import ColorManager from renmas3.macros import create_assembler class SpectrumToRGBTest extends TestCase begin function setUp self begin pass end function function asm_code1 self mgr begin set code = string #DATA set code = code + cal...
import unittest from random import random from tdasm import Runtime from renmas3.base import ColorManager from renmas3.macros import create_assembler class SpectrumToRGBTest(unittest.TestCase): def setUp(self): pass def asm_code1(self, mgr): code = """ #DATA """ code +...
Python
zaydzuhri_stack_edu_python
function _parse_skip_option self begin string Parse the ``skip`` option of skipped module names. try begin set skip_text = options at string skip end except KeyError begin return list end set modules = list comprehension strip module for module in split skip_text string , return modules end function
def _parse_skip_option(self): """Parse the ``skip`` option of skipped module names. """ try: skip_text = self.options['skip'] except KeyError: return [] modules = [module.strip() for module in skip_text.split(',')] return modules
Python
jtatman_500k
function nodeFlow self node begin return sum values edges - sum segment end function
def nodeFlow(self, node): return sum(self[node].edges.values()) - sum(self[node].segment)
Python
nomic_cornstack_python_v1
class HashTable begin function __init__ self begin set MAX = 10 set arr = list comprehension list for i in range MAX end function function get_hash self key begin set hash = 0 for char in key begin comment ord() is used to get the ascii code of inputs. set hash = hash + ordinal char end return hash % MAX end function ...
class HashTable: def __init__(self): self.MAX = 10 self.arr = [[] for i in range(self.MAX)] def get_hash(self, key): hash = 0 for char in key: hash += ord(char) # ord() is used to get the ascii code of inputs. return hash % self.MAX def __setit...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 import logging import pytest set log = call getLogger __name__ from sudoku.rules.value_restrictions import main as vr_main from sudoku.rules.binary_pairs import main as bp_main decorator fixture function p_bpm p_bp begin set cloned = clone p_bp call add_pencil_marks 4 ...
#!/usr/bin/env python # coding: utf-8 import logging import pytest log = logging.getLogger(__name__) from sudoku.rules.value_restrictions import main as vr_main from sudoku.rules.binary_pairs import main as bp_main @pytest.fixture def p_bpm(p_bp): cloned = p_bp.clone() cloned[9,4].add_pencil_marks(4,5) ...
Python
zaydzuhri_stack_edu_python
function on_fetch self url extra begin set driver = call PhantomJS desired_capabilities=desired_capabilities get driver url return page_source end function
def on_fetch(self, url, extra): driver = webdriver.PhantomJS( desired_capabilities=self.desired_capabilities ) driver.get(url) return driver.page_source
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment client.py import config as cfg import sys import socket string def main(elems): e = tuple(map(int, elems)) try: for e in elems: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() client.connect((host, cfg.PORT)) client.send(e) client.shutdown(sock...
#!/usr/bin/env python # client.py import config as cfg import sys import socket """ def main(elems): e = tuple(map(int, elems)) try: for e in elems: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() client.connect((host, cfg.POR...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Dec 30 14:36:05 2020 @author: hua_yang comment The algorithm starts at x=3 set cur_x = 3 comment Learning rate set lr = 0.1 comment This tells us when to stop the algorithm set precision = 1e-06 set previous_step_size = 1 comment maximum number of iterations set max_i...
# -*- coding: utf-8 -*- """ Created on Wed Dec 30 14:36:05 2020 @author: hua_yang """ cur_x = 3 # The algorithm starts at x=3 lr = 0.1 # Learning rate precision = 0.000001 #This tells us when to stop the algorithm previous_step_size = 1 # max_iters = 10000 # maximum number of iterations iters = 0 #iteration counter d...
Python
zaydzuhri_stack_edu_python
function cond pred true_fn=none false_fn=none name=none begin string Return either `true_fn()` if predicate `pred` is true else `false_fn()`. If `pred` is a bool or has a constant value, we return either `true_fn()` or `false_fn()`, otherwise we use `tf.cond` to dynamically route to both. Arguments: pred: A scalar dete...
def cond(pred, true_fn=None, false_fn=None, name=None): """Return either `true_fn()` if predicate `pred` is true else `false_fn()`. If `pred` is a bool or has a constant value, we return either `true_fn()` or `false_fn()`, otherwise we use `tf.cond` to dynamically route to both. Arguments: pred: A scalar ...
Python
jtatman_500k
function vmware_clone_vm self service_instance vm_template vm_name vm_datacenter=none vm_datastore=none vm_folder=none vm_cluster=none vm_rpool=none vm_network=none vm_poweron=false custspec=none begin set content = call RetrieveContent comment Get the template set template = call vmware_get_obj content list VirtualMac...
def vmware_clone_vm(self, service_instance, vm_template, vm_name, vm_datacenter=None, vm_datastore=None, vm_folder=None, vm_cluster=None, vm_rpool=None, vm_network=None, vm_poweron=False, custspec=None): content = service_instance.RetrieveContent() ## Get the template template = self.vmware_get_obj(content, [vi...
Python
nomic_cornstack_python_v1
function corners self begin comment needs to handle unbounded cases. return generator expression call asarray x for x in product *zip(self.bounds.lb, self.bounds.ub) end function
def corners(self): # needs to handle unbounded cases. return (np.asarray(x) for x in itertools.product(*zip(self.bounds.lb, self.bounds.ub)))
Python
nomic_cornstack_python_v1
function sum x y begin return x + y end function comment testing comment Output: 5 print sum 2 3
def sum(x, y): return x + y # testing print(sum(2, 3)) # Output: 5
Python
iamtarun_python_18k_alpaca
string Dices consists of reusable components that are used to build different games using one or several dices. Dices class encapsulates attributes commonly used in dice games (pot and bet) and functions roll and check. Checking is done according to the rules of each game. Dices ver0.4 adds a new functionality 'tenner'...
''' Dices consists of reusable components that are used to build different games using one or several dices. Dices class encapsulates attributes commonly used in dice games (pot and bet) and functions roll and check. Checking is done according to the rules of each game. Dices ver0.4 adds a new functionality 'tenne...
Python
zaydzuhri_stack_edu_python
function _do_request_delete self __button begin set _return = false set tuple _model _row = call get_selected set _node_id = call get_value _row 9 set _level = call get_value _row 11 if not call request_do_delete _node_id begin call _on_select_revision module_id=_revision_id end else begin set _prompt = format call _ s...
def _do_request_delete(self, __button): _return = False _model, _row = self.treeview.get_selection().get_selected() _node_id = _model.get_value(_row, 9) _level = _model.get_value(_row, 11) if not self._dtc_data_controller.request_do_delete(_node_id): self._on_select...
Python
nomic_cornstack_python_v1
function add_validator self validator name begin if get call _get_hcell string UNTRANSLATED begin raise call AttributeError string Cannot invoke Cell.add_validator: cell must be translated first end return call add_validator validator name=name end function
def add_validator(self, validator: Callable, name: str) -> None: if self._get_hcell().get("UNTRANSLATED"): raise AttributeError( "Cannot invoke Cell.add_validator: cell must be translated first" ) return self.handle.add_validator(validator, name=name)
Python
nomic_cornstack_python_v1
function load_command_class app_name name begin set module = call import_module string %s.management.commands.%s % tuple app_name name return call Command end function
def load_command_class(app_name, name): module = import_module('%s.management.commands.%s' % (app_name, name)) return module.Command()
Python
nomic_cornstack_python_v1
string This provides the feature importance by using Random forests. author: Younggue Bae from sklearn.ensemble import RandomForestRegressor function feature_importance X y begin set clf = random forest regressor n_jobs=2 n_estimators=1000 set model = fit clf X y set values = sorted zip columns feature_importances_ key...
""" This provides the feature importance by using Random forests. author: Younggue Bae """ from sklearn.ensemble import RandomForestRegressor def feature_importance(X, y): clf = RandomForestRegressor(n_jobs=2, n_estimators=1000) model = clf.fit(X, y) values = sorted(zip(X.columns, model.feature_importan...
Python
zaydzuhri_stack_edu_python
set gen = generator expression value for value in range 10 if value > 5 print min gen
gen = (value for value in range(10) if value > 5) print(min(gen))
Python
zaydzuhri_stack_edu_python
function startNextRound self begin call startNextRound end function
def startNextRound(self): self.game.startNextRound()
Python
nomic_cornstack_python_v1
function attach self observer begin if observer not in __observers begin append __observers observer end end function
def attach(self, observer): if observer not in self.__observers: self.__observers.append(observer)
Python
nomic_cornstack_python_v1
function display_topics df n_rows=10 n_cols=12 begin set tuple exemplar_scores hovers = call topic_exemplars df set top_columns = sorted range length exemplar_scores key=lambda i -> exemplar_scores at i reverse=true at slice : n_cols : comment I comented this line Im not 100% sure what was the purpuse of this comment...
def display_topics(df, n_rows=10, n_cols=12): exemplar_scores, hovers = topic_exemplars(df) top_columns = sorted(range(len(exemplar_scores)), key=lambda i: exemplar_scores[i], reverse=True)[:n_cols] #I comented this line Im not 100% sure what was the purpus...
Python
nomic_cornstack_python_v1
function to_kebab_case name begin return replace name string _ string - end function
def to_kebab_case(name): return name.replace("_", "-")
Python
nomic_cornstack_python_v1
function get_possible_moves self begin raise NotImplementedError end function
def get_possible_moves(self) -> List: raise NotImplementedError
Python
nomic_cornstack_python_v1
function main begin set parser = call ArgumentParser formatter_class=RawDescriptionHelpFormatter description=DESC epilog=EPILOG call add_argument string name help=string the streamer's name call add_argument string -c string --config metavar=string configfile help=string Path of a JSON file containing a valid config. s...
def main(): parser = argparse.ArgumentParser( formatter_class=argparse.RawDescriptionHelpFormatter, description=DESC, epilog=EPILOG ) parser.add_argument('name', help='the streamer\'s name') parser.add_argument('-c', '--config', metavar='configfile', help='Path of a JSON ...
Python
nomic_cornstack_python_v1
function viewCity self index begin set city = call getCity index if city is not none begin set controller = call CityController city run end end function
def viewCity(self, index): city = self.screen.getCity(index) if city is not None: controller = CityController(city) controller.run()
Python
nomic_cornstack_python_v1
function sumNumbers self root begin return call sum_helper root 0 end function function sum_helper self root current begin if root is none begin return 0 end if left is none and right is none begin return 10 * current + val end set new_current = 10 * current + val return call sum_helper left new_current + call sum_help...
def sumNumbers(self, root: TreeNode) -> int: return self.sum_helper(root, 0) def sum_helper(self, root, current): if root is None: return 0 if root.left is None and root.right is None: return 10 * current + root.val new_current = 10 * current + root.val return self.sum_helper(roo...
Python
zaydzuhri_stack_edu_python
function _fit self X y=none begin call _checkXy X y set cv = _cv set _inv_X = fit transform cv X comment self._fit_X = np.asarray(X) set n_docs = length X set _y = if expression y is none then array range n_docs else call asarray y set n_docs = n_docs return self end function
def _fit(self, X, y=None): _checkXy(X, y) cv = self._cv self._inv_X = cv.fit_transform(X) # self._fit_X = np.asarray(X) n_docs = len(X) self._y = np.arange(n_docs) if y is None else np.asarray(y) self.n_docs = n_docs return self
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 string square9 class Square begin string comparing squares function __init__ self size=0 begin set size = size end function decorator property function size self begin string getter return __size end function decorator setter function size self value begin string setter if not type value is in...
#!/usr/bin/python3 """square9""" class Square: """comparing squares""" def __init__(self, size=0): self.size = size @property def size(self): """getter""" return self.__size @size.setter def size(self, value): """setter""" if not type(value) is int and...
Python
zaydzuhri_stack_edu_python
comment Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. comment Implement the Solution class: comment Solution(ListNode head) Initializes the object with the head of the singly-linked list head. comment int getRandom() Chooses a no...
# Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. # # Implement the Solution class: # # # Solution(ListNode head) Initializes the object with the head of the singly-linked list head. # int getRandom() Chooses a node randomly from...
Python
zaydzuhri_stack_edu_python
string command line options, ini-file and conftest.py processing. import argparse import warnings import py comment DON't import pytest here because it causes import cycle troubles import sys , os set FILE_OR_DIR = string file_or_dir class Parser begin string Parser for command line arguments and ini-file values. :ivar...
""" command line options, ini-file and conftest.py processing. """ import argparse import warnings import py # DON't import pytest here because it causes import cycle troubles import sys, os FILE_OR_DIR = 'file_or_dir' class Parser: """ Parser for command line arguments and ini-file values. :ivar extra_inf...
Python
zaydzuhri_stack_edu_python
function pandi x begin set x = string x if length x == 9 and string 0 not in x begin for i in x begin if count x i > 1 begin return false end else begin return true end end end else begin return false end end function
def pandi(x): x=str(x) if len(x)==9 and '0' not in x: for i in x: if x.count(i)>1: return False else: return True else: return False
Python
zaydzuhri_stack_edu_python
import datetime from django.http import HttpResponse from django.shortcuts import render import os from django.conf import settings function file_list request date=none begin set template_name = string index.html set my_path = FILES_PATH comment Реализуйте алгоритм подготавливающий контекстные данные для шаблона по при...
import datetime from django.http import HttpResponse from django.shortcuts import render import os from django.conf import settings def file_list(request, date=None): template_name = 'index.html' my_path = settings.FILES_PATH # Реализуйте алгоритм подготавливающий контекстные данные для шаблона по пример...
Python
zaydzuhri_stack_edu_python
comment !/usr/local/bin/python3 string Hera, a basketball statistics tracker Tracks (per quarter): - Kick outs - Passes: swing passes, skip passes, perimeter passes, low post passes, mid post passes, high post passes, outlet passes, hand-offs, cross court passes, lobs, , dump offs, short corner passes, and miscellaneou...
#!/usr/local/bin/python3 ''' Hera, a basketball statistics tracker Tracks (per quarter): - Kick outs - Passes: swing passes, skip passes, perimeter passes, low post passes, mid post passes, high post passes, outlet passes, hand-offs, cross court passes, lobs, , dump offs, short corner pa...
Python
zaydzuhri_stack_edu_python
function lswords self irc msg args word begin call reply string %s in list ? %s % tuple word word in words end function
def lswords (self,irc,msg,args,word): irc.reply('%s in list ? %s' % (word,word in self.words))
Python
nomic_cornstack_python_v1
comment Rectangulos class rectangulo begin function __init__ self x0 y0 lx_0 ly_0 begin comment Punto de un solo vertice 1 inicial con coordenadas (x,y) set x1 = x0 set y1 = y0 comment Lados del rectangulo, horizontal inferior set lx = absolute lx_0 comment vertical derecho set ly = absolute ly_0 comment ----->Los lado...
##Rectangulos class rectangulo: def __init__(self, x0, y0, lx_0, ly_0): self.x1=x0 #Punto de un solo vertice 1 inicial con coordenadas (x,y) self.y1=y0 self.lx=abs(lx_0) #Lados del rectangulo, horizontal inferior self.ly=abs(ly_0) #vertical derecho #----->Los lados deben ser siempre positivos<-----# #ve...
Python
zaydzuhri_stack_edu_python
function populate self compound_dict=none x=none y=none z=none begin if dimension == 3 begin set a = lattice_spacings at 0 set b = lattice_spacings at 1 set c = lattice_spacings at 2 if x is none begin set x = 1 end if y is none begin set y = 1 end if z is none begin set z = 1 end if x < 1 or y < 1 or z < 1 begin raise...
def populate(self, compound_dict=None, x=None, y=None, z=None): if self.dimension == 3: a = self.lattice_spacings[0] b = self.lattice_spacings[1] c = self.lattice_spacings[2] if x is None: x = 1 if y is None: y = 1 ...
Python
nomic_cornstack_python_v1
string lis[][0]:Petrol lis[][1]:Distance comment Your task isto complete this function comment Your function should return the starting point function tour lis n begin comment Code here set i = 0 set balance_petrol = lis at i at 0 set start = 0 while i < n begin if balance_petrol < lis at i at 1 begin set balance_petro...
''' lis[][0]:Petrol lis[][1]:Distance ''' #Your task isto complete this function #Your function should return the starting point def tour(lis, n): #Code here i=0 balance_petrol = lis[i][0] start = 0 while i<n: if balance_petrol<lis[i][1]: balance_petrol = l...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 string 常用自带函数 函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”; abs() max() min() sum() 其他数据类型转换类的函数。。 print absolute - 199 set test = sum print call test list 1 2 string 类型转换 int(x [,base ]) 将x转换为一个整数 long(x [,base ]) 将x转换为一个长整数 float(x ) 将x转换到一个浮点数 complex(real [,imag ]) 创建一个复数 str(x ) 将对象 x 转换...
# coding=utf-8 """ 常用自带函数 函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名”; abs() max() min() sum() 其他数据类型转换类的函数。。 """ print(abs(-199)) test = sum print(test([1, 2])) """ 类型转换 int(x [,base ]) 将x转换为一个整数 long(x [,base ]) 将x转换为一个长整数 float(x ) 将x转换到一个浮点数 complex(real [,imag ]) 创建一个复数 ...
Python
zaydzuhri_stack_edu_python
import argparse import os import cv2 import json import pickle from multiprocessing import Pool import numpy as np from graphviz import Digraph class prd begin function __init__ self rel obj2 score begin set rel = rel set obj2 = obj2 set score = score end function function __str__ self begin return string dict string r...
import argparse import os import cv2 import json import pickle from multiprocessing import Pool import numpy as np from graphviz import Digraph class prd(): def __init__(self, rel, obj2, score): self.rel = rel self.obj2 = obj2 self.score = score def __str__(self): return str({'r...
Python
zaydzuhri_stack_edu_python
function updateCoords self coords in_road=none begin if none in list values four_corners begin set cur_coords = none end else begin set cur_coords = list four_corners at string front_left at 0 + four_corners at string front_right at 0 / 2 four_corners at string front_left at 1 + four_corners at string back_left at 1 / ...
def updateCoords(self,coords,in_road=None): if None in list(self.four_corners.values()): cur_coords = None else: cur_coords = [(self.four_corners["front_left"][0]+self.four_corners["front_right"][0])/2,\ (self.four_corners["front_left"][1]+self.four_corners["...
Python
nomic_cornstack_python_v1
function as_hff self parent_group name=string colour args=none begin assert is instance parent_group Group set parent_group at name = value comment group = parent_group.create_group(name) comment group[u'rgba'] = self.value return parent_group end function
def as_hff(self, parent_group, name=u"colour", args=None): assert isinstance(parent_group, h5py.Group) parent_group[name] = self.value # group = parent_group.create_group(name) # group[u'rgba'] = self.value return parent_group
Python
nomic_cornstack_python_v1
function test_add_category self begin call _set_policy_rules dict string add_category string @ call expect_policy_check string add_category set fake_now = call utcnow set override_time = fake_now set expected = dict string name string new_category ; string created call isotime fake_now at slice : - 1 : ; string updat...
def test_add_category(self): self._set_policy_rules({'add_category': '@'}) self.expect_policy_check('add_category') fake_now = timeutils.utcnow() timeutils.utcnow.override_time = fake_now expected = { 'name': 'new_category', 'created': timeutils.isotime...
Python
nomic_cornstack_python_v1
function download url pathname begin set buffer_size = 1024 comment if path doesn't exist, make that path dir if not is directory path pathname begin make directories pathname end comment download the body of response by chunk, not immediately set response = get requests url stream=true comment get the total file size ...
def download(url, pathname): buffer_size = 1024 # if path doesn't exist, make that path dir if not os.path.isdir(pathname): os.makedirs(pathname) # download the body of response by chunk, not immediately response = requests.get(url, stream=True) # get the total file size file_size = ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import getopt import sys from PIL import Image function calc_metric cover_image watermarked_image begin if size != size begin return - 2 end return 100 end function function main args begin set cover_filename = none set watermarked_filename = none comment print...
#!/usr/bin/env python # -*- coding: utf-8 -*- import getopt import sys from PIL import Image def calc_metric(cover_image, watermarked_image): if cover_image.size != watermarked_image.size: return -2 return 100 def main(args): cover_filename = None watermarked_filename = None # print('A...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import sys from bisect import bisect_left from itertools import accumulate set INF = decimal string inf function solve N M A begin sort A comment 幸福度X以上を得られる握手をカウントし、M以上となる境界を探す comment Xが小さい方が握手の個数は多く、Xが大きい方が握手の個数は少ない set left = 0 set right = 3 * 10 ^ 5 while right - left > 1 begin set X ...
#!/usr/bin/env python3 import sys from bisect import bisect_left from itertools import accumulate INF = float("inf") def solve(N: int, M: int, A: "List[int]"): A.sort() # 幸福度X以上を得られる握手をカウントし、M以上となる境界を探す # Xが小さい方が握手の個数は多く、Xが大きい方が握手の個数は少ない left = 0 right = 3*(10**5) while right - left > 1: ...
Python
zaydzuhri_stack_edu_python
from zipfile import ZipFile import os function prRed skk begin print format string  {} skk end function function prCyan skk begin print format string  {} skk end function function prYellow skk begin print format string  {} skk end function function open_zip_file password begin global is_pa...
from zipfile import ZipFile import os def prRed(skk): print("\033[91m {}\033[00m" .format(skk)) def prCyan(skk): print("\033[96m {}\033[00m" .format(skk)) def prYellow(skk): print("\033[93m {}\033[00m" .format(skk)) def open_zip_file(password): global is_password_found str_zipFile = os.path.dirname(os.path.absp...
Python
zaydzuhri_stack_edu_python
string Challenge021 from pemjh.numbers import divisors function main begin string challenge021 set maximum = 10000 set total = 0 set known_divisors = dict for number in range 1 maximum begin comment Get the divisors total set sum_of_divisors = 0 for divisor in call divisors number false begin set sum_of_divisors = sum...
""" Challenge021 """ from pemjh.numbers import divisors def main(): """ challenge021 """ maximum = 10000 total = 0 known_divisors = {} for number in range(1, maximum): # Get the divisors total sum_of_divisors = 0 for divisor in divisors(number, False): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python comment -*- coding: utf-8 -*- comment Author: Wandrille Duchemin # comment Created: 23-Jul-2015 # comment Last modified: 13-Jan-2017 # from ete3 import Tree , TreeNode import random class CCP_distribution begin string Distribution of CCP This class is linked to the ete3.TreeNode class for tree ...
#!/usr/bin/python # -*- coding: utf-8 -*- ######################################### ## Author: Wandrille Duchemin # ## Created: 23-Jul-2015 # ## Last modified: 13-Jan-2017 # ######################################### from ete3 import Tree,TreeNode import random class CCP_distribu...
Python
zaydzuhri_stack_edu_python
function AplusB a b begin return a + b end function set result = call AplusB 1 2 print result print call AplusB 10 12 function circle r begin set area = r ^ 2 * 3.14 return area end function print call circle 5 function circle2 r pi begin set area = r ^ 2 * pi return area end function print call circle2 6 3.14 set a = ...
def AplusB(a,b): return a+b result=AplusB(1,2) print(result) print(AplusB(10,12)) def circle(r): area=r**2*3.14 return area print(circle(5)) def circle2(r,pi): area=r**2*pi return area print(circle2(6,3.14)) a=2 def main(): b=3 print(a) main() print(b) circle3=lambda r,pi:r**2*pi print(c...
Python
zaydzuhri_stack_edu_python
comment Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. function diff21 n begin set absolute = absolute 21 - n if n > 21 begin return 2 * absolute end else begin return absolute end end function if __name__ == string __main__ begin print cal...
# Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21. def diff21(n): absolute = abs(21 - n) if n > 21: return 2 * absolute else: return absolute if __name__ == '__main__': print(diff21(25))
Python
zaydzuhri_stack_edu_python
function get_instance self payload begin string Build an instance of CredentialInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance ret...
def get_instance(self, payload): """ Build an instance of CredentialInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance :rtype: twilio.rest.api.v2010.account.sip.credential_list.cr...
Python
jtatman_500k
function parse_args begin set parser = call ArgumentParser description=string Align and compute RMSD call add_argument string pdb_input_file type=str help=string Original pdb file. call add_argument string pdb_to_smarts type=str help=string JSON file connecting pdbs to SMARTS call add_argument string ids_to_smarts type...
def parse_args(): parser = argparse.ArgumentParser(description="Align and compute RMSD") parser.add_argument("pdb_input_file", type=str, help="Original pdb file.") parser.add_argument("pdb_to_smarts", type=str, help="JSON file connecting pdbs to SMARTS") parser.add_argument("ids_to_smarts", type=str, he...
Python
nomic_cornstack_python_v1
comment import LCD import time function processData data begin comment example data: comment "ETA 143\nTASK MAIL\n" set commands = split data string for command in commands begin set args = split command string if args at 0 == string ETA begin call smartStoolLCD args end else if args at 0 == string TASK begin call smar...
#import LCD import time def processData(data): # example data: # "ETA 143\nTASK MAIL\n" commands = data.split('\n') for command in commands: args = command.split(' ') if args[0] == 'ETA': smartStoolLCD(args) elif args[0] == 'TASK': smartStoolLCD(args)
Python
zaydzuhri_stack_edu_python
async function get_optimal_commute self startpoint endpoint current_time client i begin set list_of_commute = list if tran_tool at BIKE and call is_available startpoint begin set route = await call get_route_from_motis startpoint endpoint current_time true client i end else begin set route = await call get_route_from_...
async def get_optimal_commute(self, startpoint, endpoint, current_time, client, i): list_of_commute = [] if self.tran_tool[config.BIKE] and \ self.tran_tool[config.BIKE].is_available(startpoint): route = await self.get_route_from_motis(startpoint, endpoint, ...
Python
nomic_cornstack_python_v1
function count_occurrences lst begin comment Create an empty dictionary to store the counts set counts = dict comment Iterate over each item in the list for item in lst begin comment Check if the item is already in the dictionary if item in counts begin comment If it is, increment the count by 1 set counts at item = c...
def count_occurrences(lst): # Create an empty dictionary to store the counts counts = {} # Iterate over each item in the list for item in lst: # Check if the item is already in the dictionary if item in counts: # If it is, increment the count by 1 counts[item] +=...
Python
greatdarklord_python_dataset
comment define a funciton function filter_choose size multiplexer begin print string the size of filter is { size } print string the function of filter is { multiplexer } end function set size = string A set filter1 = 3525 set filter2 = string triplexer comment first method call filter_choose 1608 string diplexer print...
# define a funciton def filter_choose(size, multiplexer): print(f"the size of filter is {size}") print(f"the function of filter is {multiplexer}") size = 'A' filter1 = 3525 filter2 = 'triplexer' # first method filter_choose(1608, 'diplexer') print('*'*1) # second method filter_choose(filter1, filter2) print(...
Python
zaydzuhri_stack_edu_python
string Text Type (String) comment s = 'this is a single line string' comment print (s) comment print (type(s)) comment ========================== comment s = """ this is a multi line comment string example""" comment print (s) comment ================================ comment Find character by index comment s = 'string ...
''' Text Type (String) ''' #s = 'this is a single line string' #print (s) #print (type(s)) #========================== #s = """ this is a multi line #string example""" #print (s) #================================ #Find character by index #s = 'string sample' #print (s[5]) # slicing #s= 'string sample' #print ...
Python
zaydzuhri_stack_edu_python
function resize img width begin set wpercent = decimal width / decimal size at 0 set hsize = integer decimal size at 1 * decimal wpercent set img = call resize tuple width hsize ANTIALIAS return img end function
def resize(img,width): wpercent = float(width / float(img.size[0])) hsize = int((float(img.size[1])*float(wpercent))) img = img.resize((width ,hsize), Image.ANTIALIAS) return img
Python
nomic_cornstack_python_v1
comment Dictionary of numbers and words set DAYS = dict 1 string one ; 2 string two ; 3 string three ; 4 string four ; 5 string five ; 6 string six ; 7 string seven ; 8 string eight ; 9 string nine ; 10 string ten function num_to_str num begin if num in DAYS begin return DAYS at num end else begin return string invalid...
# Dictionary of numbers and words DAYS = { 1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten', } def num_to_str(num): if num in DAYS: return DAYS[num] else: return "invalid number" if __name__ == '__main__'...
Python
flytech_python_25k
function plot_spike_histogram Blk Config save=none begin comment gather all spike amplitudes set Spike_amps = list for seg in segments begin set tuple SpikeTrain = call select_by_dict spiketrains kind=string all_spikes set spike_amps = flatten magnitude append Spike_amps spike_amps end set Spike_amps = concatenate Spi...
def plot_spike_histogram(Blk, Config, save=None): # gather all spike amplitudes Spike_amps = [] for seg in Blk.segments: SpikeTrain, = select_by_dict(seg.spiketrains, kind='all_spikes') spike_amps = SpikeTrain.waveforms.rescale(default_volt).magnitude.flatten() Spike_amps.append(spi...
Python
nomic_cornstack_python_v1
for i in range 0 n begin if i == l at i begin append res l at i end end if length res == 0 begin print string -1 end else begin sort res for i in res begin print i end=string end end
for i in range(0,n): if(i==l[i]): res.append(l[i]) if(len(res)==0): print("-1") else: res.sort() for i in res: print(i,end=" ")
Python
zaydzuhri_stack_edu_python
function display_metrics history begin set tuple f ax = call subplots 1 2 figsize=tuple 15 5 plot history at string loss linewidth=3 plot history at string val_loss linewidth=3 call set_title string Loss fontsize=16 call set_ylabel string Loss fontsize=16 call set_xlabel string Epoch fontsize=16 legend list string trai...
def display_metrics(history): f, ax = plt.subplots(1, 2, figsize=(15, 5)) ax[0].plot(history.history['loss'], linewidth=3) ax[0].plot(history.history['val_loss'], linewidth=3) ax[0].set_title('Loss', fontsize=16) ax[0].set_ylabel('Loss', fontsize=16) ax[0].set_xlabel('Epoch', fontsize=16) ax...
Python
nomic_cornstack_python_v1
from search_engine.models import Article from search_engine.search_engine import load_list function fill_data res_path art_path begin set file_list = call load_list res_path string file_list set doc_list = list for file in file_list begin with open art_path + file string r as myfile begin append doc_list read myfile e...
from search_engine.models import Article from search_engine.search_engine import load_list def fill_data(res_path, art_path): file_list = load_list(res_path, 'file_list') doc_list = [] for file in file_list: with open(art_path + file, 'r') as myfile: doc_list.append(myfile.read()) ...
Python
zaydzuhri_stack_edu_python
function makedirs path begin string Create directories if they do not exist, otherwise do nothing. Return path for convenience if not is directory path path begin make directories path end return path end function
def makedirs(path): """ Create directories if they do not exist, otherwise do nothing. Return path for convenience """ if not os.path.isdir(path): os.makedirs(path) return path
Python
jtatman_500k
import sys import re from xml.etree import ElementTree as ET comment r = sys.stdin.buffer.read(16).decode('cp1251') function get_table_coll table_text begin set row_coll = split table_text string set row_coll = list generator expression left strip r for r in row_coll set row_coll = list generator expression sub string ...
import sys import re from xml.etree import ElementTree as ET #r = sys.stdin.buffer.read(16).decode('cp1251') def get_table_coll(table_text: object) -> list: row_coll = table_text.split("\n") row_coll = list(r.lstrip() for r in row_coll) row_coll = list(re.sub(r"[ ]+", " ", r) for r in row_coll) return ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python from __future__ import absolute_import , division , print_function import numpy as np import gensim as gs from itertools import combinations function verify clue words begin if string _ in clue begin return false end for word in words begin if lower word in lower clue or lower clue in lower...
#!/usr/bin/env python from __future__ import absolute_import, division, print_function import numpy as np import gensim as gs from itertools import combinations def verify(clue, words): if '_' in clue: return False for word in words: if word.lower() in clue.lower() or clue.lower() in word.lowe...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/python comment -*- coding: utf-8 -*- import sys import os import getopt if not __package__ begin set path = join path directory name path __file__ pardir insert path 0 path end from Queue import Queue from lightspider.muti_thread_spider import index_spider , detail_spider , zip_spider
#! /usr/bin/python # -*- coding: utf-8 -*- import sys import os import getopt if not __package__: path = os.path.join(os.path.dirname(__file__), os.pardir) sys.path.insert(0, path) from Queue import Queue from lightspider.muti_thread_spider import index_spider, detail_spider, zip_spider
Python
zaydzuhri_stack_edu_python
function base_currency self base_currency begin set _base_currency = base_currency end function
def base_currency(self, base_currency): self._base_currency = base_currency
Python
nomic_cornstack_python_v1
comment planet.py from planetPy.parameter import Parameter from planetPy.constants import G from numpy import pi , sqrt class Body begin function __init__ self name body_type begin set name = name set body_type = body_type set mass = 0.0 set radius = 0.0 set density = 0.0 set gravity = 0.0 set rotation_period = 0.0 set...
# planet.py from planetPy.parameter import Parameter from planetPy.constants import G from numpy import pi, sqrt class Body: def __init__(self, name, body_type): self.name = name self.body_type = body_type self.mass = 0.0 self.radius = 0.0 self.density = 0.0 self.gr...
Python
zaydzuhri_stack_edu_python
function get_line_to self target begin set m = y - y / x - x set b = y - m * x return tuple m b end function
def get_line_to(self,target): m = (target.y - self.y) / (target.x - self.x) b = self.y - m * self.x return (m,b)
Python
nomic_cornstack_python_v1
function main begin string 5 <= N <= 55 ai is prime ai != aj sum(ai...ai5) is not prime set N = integer input f dist N end function function f N begin set max_num = 55555 set e = call eratosthenes max_num * 5 set ps = list for i in range 2 max_num + 1 begin if e at i begin append ps i end end comment print(len(ps)): 5...
def main(): """ 5 <= N <= 55 ai is prime ai != aj sum(ai...ai5) is not prime """ N = int(input()) f(N) def f(N): max_num = 55555 e = eratosthenes(max_num * 5) ps = [] for i in range(2, max_num+1): if e[i]: ps.append(i) # print(len(ps)): 5637 ...
Python
zaydzuhri_stack_edu_python
import serial import time set ArduinoSerial = call Serial string com18 9600 sleep 2
import serial import time ArduinoSerial = serial.Serial('com18',9600) time.sleep(2)
Python
zaydzuhri_stack_edu_python
from src.loja.models.stock import Stock from src.loja.models.product import Product from src.loja.repositories.stock import StockDAO class StockController begin function __init__ self dao begin set dao = dao end function function new_product self product quantity begin set new = call Stock product=product quantity=quan...
from src.loja.models.stock import Stock from src.loja.models.product import Product from src.loja.repositories.stock import StockDAO class StockController: def __init__(self, dao: StockDAO): self.dao = dao def new_product(self, product: Product, quantity: int): new = Stock(product=product, qu...
Python
zaydzuhri_stack_edu_python
import pandas as pd from pycaret.regression import * function predict_fp data model begin set data2 = drop data list string PLAYER \nFULL NAME string TEAM axis=1 set prediction = call predict_model model data2 rename columns=dict string Label string fantasy points inplace=true return concat list data at list string PLA...
import pandas as pd from pycaret.regression import * def predict_fp(data,model): data2 = data.drop(['PLAYER \\nFULL NAME','TEAM'],axis=1) prediction = predict_model(model, data2) prediction.rename(columns={'Label':'fantasy points'},inplace=True) return pd.concat([data[['PLAYER \\nFULL NAME','TEAM']],pr...
Python
zaydzuhri_stack_edu_python