code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment noqa function cells_area data begin comment get latitudes and longitude set lat = array values set lon = array values comment get ther sizes set nlat = size set mlon = size comment check monotonic increase or decrease call check_monotonic lat call check_monotonic lon comment get distances x and y using any 2 co...
def cells_area(data): # noqa # get latitudes and longitude lat = np.array(data.latitude.values) lon = np.array(data.longitude.values) # get ther sizes nlat = data.latitude.size mlon = data.longitude.size # check monotonic increase or decrease utils.check_monotonic(lat) utils.chec...
Python
nomic_cornstack_python_v1
string Вам дан массив с числами. Нужно найти целое число, которое встречается нечетное число раз. Такое число всегда будет только одно. set N = list 20 1 - 1 2 - 2 3 3 5 5 1 2 4 20 4 - 1 - 2 5 20 20 20 20 function func n begin set counter = dict for elem in n begin set counter at elem = get counter elem 0 + 1 end prin...
''' Вам дан массив с числами. Нужно найти целое число, которое встречается нечетное число раз. Такое число всегда будет только одно. ''' N = [ 20, 1, -1, 2, -2, 3, 3, 5, 5, 1, 2, 4, 20, 4, -1, -2, 5, 20, 20, 20, 20 ] def func(n): counter = {} for elem in n: counter[elem] = counter.get(elem, 0) + 1 ...
Python
zaydzuhri_stack_edu_python
comment ===================================== comment --*-- coding: utf-8 --*-- comment @Author : TRHX comment @Blog : www.itrhx.com comment @CSDN : itrhx.blog.csdn.net comment @FileName: 【12】Create Intervals.py comment ===================================== function create_intervals data begin set tuple start end = tup...
# ===================================== # --*-- coding: utf-8 --*-- # @Author : TRHX # @Blog : www.itrhx.com # @CSDN : itrhx.blog.csdn.net # @FileName: 【12】Create Intervals.py # ===================================== def create_intervals(data): start, end = [], [] for i in data: if i...
Python
zaydzuhri_stack_edu_python
function configure_ceph_keyring self key cluster_name=none begin set keyring_absolute_path = call configure_ceph_keyring key cluster_name comment TODO: add support for custom permissions into charms.openstack if exists path keyring_absolute_path begin comment NOTE: triliovault access the keyring as the nova user, so co...
def configure_ceph_keyring(self, key, cluster_name=None): keyring_absolute_path = super().configure_ceph_keyring( key, cluster_name ) # TODO: add support for custom permissions into charms.openstack if os.path.exists(keyring_absolute_path): # NOTE: triliovault acc...
Python
nomic_cornstack_python_v1
function add_marks marks mark begin return list comprehension m + mark for m in marks end function
def add_marks(marks, mark): return [m + mark for m in marks]
Python
jtatman_500k
import unittest from Connect4 import connect4_controller from unittest.mock import patch class AddNewPlayerTest extends TestCase begin string Test functionality of add_new_player function. function setUp self begin set new_controller = call Connect4Controller end function function tearDown self begin del new_controller...
import unittest from Connect4 import connect4_controller from unittest.mock import patch class AddNewPlayerTest(unittest.TestCase): """Test functionality of add_new_player function.""" def setUp(self): self.new_controller = connect4_controller.Connect4Controller() def tearDown(self): del ...
Python
zaydzuhri_stack_edu_python
from export import Writer import csv class CSV extends Writer begin function __init__ self begin set __headers = none set __rows = list end function decorator property function headers self begin return __headers end function decorator setter function headers self headers begin set __headers = headers end function fun...
from export import Writer import csv class CSV(Writer): def __init__(self): self.__headers = None self.__rows = [] @property def headers(self): return self.__headers @headers.setter def headers(self, headers): self.__headers = headers def add_row(self, data):...
Python
zaydzuhri_stack_edu_python
for i in range N begin set S at i = input end sort S for i in range N begin print S at i end=string end
for i in range(N): S[i] = input() S.sort() for i in range(N): print(S[i], end = "")
Python
zaydzuhri_stack_edu_python
function coltypes df begin set cols = call tolist set floattypes = compile string ^[Ll]atitude$|^LATITUDE$|^[Ll]ongitude$|^LONGITUDE$|^ELEVATION.*?$|^[Ee]levation.*?$|^[A-Za-z]{2,4}$|^[A-Za-z]{2}[0-9]{1}$ set objectypes = compile string ^[Dd]ate.*?$|^DATE.*?$|[Yy]ear.*?$|^YEAR.*?$|^[Tt]ime$|^[Dd]ay.*?$|^[Mm]onth.*?$|^M...
def coltypes(df): cols = df.columns.tolist() floattypes = re.compile(r"^[Ll]atitude$|^LATITUDE$|^[Ll]ongitude$|^LONGITUDE$|^ELEVATION.*?$|^[Ee]levation.*?$|^[A-Za-z]{2,4}$|^[A-Za-z]{2}[0-9]{1}$") objectypes = re.compile(r"^[Dd]ate.*?$|^DATE.*?$|[Yy]ear.*?$|^YEAR.*?$|^[Tt]ime$|^[Dd]ay.*?$|^[Mm]onth.*?$|^M...
Python
nomic_cornstack_python_v1
function change_right self player_num begin if player_num == 1 begin set image = load image string player1_right.png end else begin set image = load image string player2_right.png end end function
def change_right(self, player_num): if player_num == 1: self.image = pygame.image.load("player1_right.png") else: self.image = pygame.image.load("player2_right.png")
Python
nomic_cornstack_python_v1
function add_ROCR100 self timeperiod=10 type=string line color=string tertiary **kwargs begin if not has_close begin raise exception end call kwargs_check kwargs VALID_TA_KWARGS if string kind in kwargs begin set type = kwargs at string kind end set name = format string ROCR100({}) string timeperiod set sec at name = d...
def add_ROCR100(self, timeperiod=10, type='line', color='tertiary', **kwargs): if not self.has_close: raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if 'kind' in kwargs: type = kwargs['kind'] name = 'ROCR100({})'.format(str(timeperiod)) self.sec[name...
Python
nomic_cornstack_python_v1
import sys import multiresolutionimageinterface as mir from queue import * from threading import Thread function single_file_conversion slide_num begin set output_path = string /mnt/ai/uni_warwick/camelyon16_dataset/training/Ground_Truth_Extracted/Mask/tumor_ + call zfill 3 + string .tif set reader = call MultiResoluti...
import sys import multiresolutionimageinterface as mir from queue import * from threading import Thread def single_file_conversion(slide_num): output_path = '/mnt/ai/uni_warwick/camelyon16_dataset/training/Ground_Truth_Extracted/Mask/tumor_' + str( slide_num).zfill(3) + '.tif' reader = mir.MultiResol...
Python
zaydzuhri_stack_edu_python
if value > limit begin print string Over the limit end
if value > limit : print ("Over the limit")
Python
zaydzuhri_stack_edu_python
function test_boottime_no_network test_microvm_with_api record_property metrics begin set vm = test_microvm_with_api update extra_args dict string boot-timer none set _ = call _configure_and_run_vm vm set boottime_us = call _test_microvm_boottime vm print string Boot time with no network is: { boottime_us } us call rec...
def test_boottime_no_network(test_microvm_with_api, record_property, metrics): vm = test_microvm_with_api vm.jailer.extra_args.update({"boot-timer": None}) _ = _configure_and_run_vm(vm) boottime_us = _test_microvm_boottime(vm) print(f"Boot time with no network is: {boottime_us} us") record_prope...
Python
nomic_cornstack_python_v1
function sell_open_order_quantity self begin string [int] 卖方向挂单量 return sum generator expression unfilled_quantity for order in open_orders if side == SELL and position_effect == OPEN end function
def sell_open_order_quantity(self): """ [int] 卖方向挂单量 """ return sum(order.unfilled_quantity for order in self.open_orders if order.side == SIDE.SELL and order.position_effect == POSITION_EFFECT.OPEN)
Python
jtatman_500k
import numpy as np from sklearn.datasets import load_iris from scipy.stats import norm import matplotlib.pyplot as plt function load_iris_dataset begin set iris = call load_iris return tuple iris at string data iris at string target end function function get_statistics inputs begin set min_vals = call amin inputs axis=...
import numpy as np from sklearn.datasets import load_iris from scipy.stats import norm import matplotlib.pyplot as plt def load_iris_dataset(): iris = load_iris() return iris['data'], iris['target'] def get_statistics(inputs): min_vals = np.amin(inputs, axis=0) max_vals = np.amax(inputs, axis=0) ...
Python
zaydzuhri_stack_edu_python
function build_R_phen S K pops phenos df map_file begin if K == 1 begin return ones tuple K K end set tuple df pop_pheno_tuples = call filter_for_phen_corr df map_file if length df == 0 begin print string print RED + string WARNING: No files specified for R_phen generation. print string Assuming independent effects. + ...
def build_R_phen(S, K, pops, phenos, df, map_file): if K == 1: return np.ones((K, K)) df, pop_pheno_tuples = filter_for_phen_corr(df, map_file) if len(df) == 0: print("") print(Fore.RED + "WARNING: No files specified for R_phen generation.") print("Assuming independent effec...
Python
nomic_cornstack_python_v1
function app_install fn prefix=root_dir begin import conda.plan as plan set index = call get_index set actions = call install_actions prefix index list call _fn2spec fn call execute_actions actions index end function
def app_install(fn, prefix=config.root_dir): import conda.plan as plan index = get_index() actions = plan.install_actions(prefix, index, [_fn2spec(fn)]) plan.execute_actions(actions, index)
Python
nomic_cornstack_python_v1
function newmodel self **kwargs begin set model = model keyword kwargs set _parent = self call _addfeature model return model end function
def newmodel(self, **kwargs): model = Model(**kwargs) model._parent = self self._addfeature(model) return model
Python
nomic_cornstack_python_v1
function serialize_link self obj *args **kwargs begin set resource = call get_serializer_for_object obj assert resource return dict string method string GET ; string href call get_href obj *args keyword kwargs ; string title call get_object_title obj *args keyword kwargs end function
def serialize_link(self, obj, *args, **kwargs): resource = self.get_serializer_for_object(obj) assert resource return { 'method': 'GET', 'href': resource.get_href(obj, *args, **kwargs), 'title': resource.get_object_title(obj, *args, **kwargs), }
Python
nomic_cornstack_python_v1
function beat_period_to_tempo beat Fs begin set tempo = 60 / beat / Fs return tempo end function
def beat_period_to_tempo(beat, Fs): tempo = 60 / (beat / Fs) return tempo
Python
nomic_cornstack_python_v1
function image_url self begin return _image_url end function
def image_url(self): return self._image_url
Python
nomic_cornstack_python_v1
function _check_by_changing begin set current_settings = call read_from_archive archive_path TRAINING_SETTINGS_FILENAME set is_changed = false for tuple key obj in items current_settings begin if key == string mark_up_source begin if obj != training_settings at key begin set is_changed = true break end end else if key ...
def _check_by_changing(): current_settings = read_from_archive( archive_path, TRAINING_SETTINGS_FILENAME ) is_changed = False for key, obj in current_settings.items(): if key == "mark_up_source": if obj != training_settings[key]: ...
Python
nomic_cornstack_python_v1
function classBasename self begin comment "<class 'foo.bar'>" set klass = string type self return sub string .*[\.\']([^\.]+)\'>$ string \1 klass end function
def classBasename(self): klass = str(type(self)) # "<class 'foo.bar'>" return re.sub(r'.*[\.\']([^\.]+)\'>$', r'\1', klass)
Python
nomic_cornstack_python_v1
function resolvepy expr safe=DEFAULT_SAFE tostr=DEFAULT_TOSTR scope=DEFAULT_SCOPE besteffort=DEFAULT_BESTEFFORT begin string Resolve input expression. :param str expr: configuration expression to resolve in this language. :param bool safe: safe run execution context (True by default). :param bool tostr: format the resu...
def resolvepy( expr, safe=DEFAULT_SAFE, tostr=DEFAULT_TOSTR, scope=DEFAULT_SCOPE, besteffort=DEFAULT_BESTEFFORT ): """Resolve input expression. :param str expr: configuration expression to resolve in this language. :param bool safe: safe run execution context (True by default). ...
Python
jtatman_500k
function sm3_store_ad_request match pod_id begin set timestamp = call group string timestamp set points = get loads call group string json string points for point in points begin if get point string _debug begin set url = get get point string _debug string vmapRequestUrl if url begin set url = join string list timesta...
def sm3_store_ad_request(match, pod_id): timestamp = match.group('timestamp') points = json.loads(match.group('json')).get('points') for point in points: if point.get('_debug'): url = point.get('_debug').get('vmapRequestUrl') if url: url = ' '.join([timestamp,...
Python
nomic_cornstack_python_v1
import math function check_integer num begin try begin integer num return true end except ValueError begin return false end end function function is_prime num begin if num < 2 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 fu...
import math def check_integer(num): try: int(num) return True except ValueError: return False def is_prime(num): if num < 2: return False for i in range(2, int(math.sqrt(num)) + 1): if num % i == 0: return False return True def is_palindrome(num...
Python
greatdarklord_python_dataset
function probs_tensor_to_list tensor begin set new_list = list for sample in tensor begin set temp_list = list for row in sample begin set sub_temp_list = list for i in row begin append sub_temp_list decimal i end append temp_list sub_temp_list end append new_list temp_list end return new_list end function
def probs_tensor_to_list(tensor): new_list = [] for sample in tensor: temp_list = [] for row in sample: sub_temp_list = [] for i in row: sub_temp_list.append(float(i)) temp_list.append(sub_temp_list) ...
Python
nomic_cornstack_python_v1
function lazy self begin return not stride == call shape_to_stride shape end function
def lazy(self): return not self.stride == shape_to_stride(self.shape)
Python
nomic_cornstack_python_v1
function get_z_position self focus_drive_id=none auto_focus_id=none force_recall_focus=false trials=3 reference_object_id=none verbose=true begin comment get communications object as link to microscope hardware set communicatons_object = connection set focus_drive_instance = call _get_microscope_object focus_drive_id s...
def get_z_position( self, focus_drive_id=None, auto_focus_id=None, force_recall_focus=False, trials=3, reference_object_id=None, verbose=True, ): # get communications object as link to microscope hardware communicatons_object = self._get_contro...
Python
nomic_cornstack_python_v1
function mean array begin set mapped = map float array return sum mapped / length mapped end function
def mean(array): mapped = map(float,array) return sum(mapped) / len(mapped)
Python
zaydzuhri_stack_edu_python
string Define evaluation buffers that can be used between the MTCS and the evaluation of the leaves. The advantages of using such buffer are: 1. we can seen node to the evaluator object by batch. And, in this project, the evaluation function (transformers-based NN) are more efficient when the input are sent by batches....
""" Define evaluation buffers that can be used between the MTCS and the evaluation of the leaves. The advantages of using such buffer are: 1. we can seen node to the evaluator object by batch. And, in this project, the evaluation function (transformers-based NN) are more efficient when the input are sent by batches. ...
Python
zaydzuhri_stack_edu_python
function getOwnerTuple series begin set resulting_names = list set namestr = series at string name set innerText = series at string inner text if type namestr == float begin comment no name return list end if find innerText string (4) != - 1 begin return call fourNames series end if find innerText string (3) != - 1 b...
def getOwnerTuple(series): resulting_names = [] namestr = series['name'] innerText = series['inner text'] if type(namestr) == float: #no name return [] if innerText.find('(4)') != -1: return fourNames(series) if innerText.find('(3)') != -1: return threeN...
Python
nomic_cornstack_python_v1
string Create a bar plot showing the average value of transaction in each month between the start and end of the dataset. here we want to take the values for all the transactions for a month and add them up, then devide by the total number of transactions that month don't need to do fancy things, just the total amount ...
"""Create a bar plot showing the average value of transaction in each month between the start and end of the dataset. here we want to take the values for all the transactions for a month and add them up, then devide by the total number of transactions that month don't need to do fancy things, just the total amount fo...
Python
zaydzuhri_stack_edu_python
function send_emails begin set cmd = string sendmail -f git@dev.rtsoft.ru for msg in EMAIL_MESSAGES begin for rec in RECIPIENTS begin call string echo '%s' | %s %s % tuple msg cmd rec none true end end end function
def send_emails(): cmd = "sendmail -f git@dev.rtsoft.ru" for msg in EMAIL_MESSAGES: for rec in RECIPIENTS: call("echo '%s' | %s %s" % (msg, cmd, rec), None, True)
Python
nomic_cornstack_python_v1
function genbank_to_faa gbkf complexheader=false skip_pseudo=true begin set tuple seqs handle = call genbank_seqio gbkf for seq in seqs begin for feat in features begin set cid = call cds_details seq feat complexheader skip_pseudo if not cid begin continue end if string translation in qualifiers begin yield tuple id ci...
def genbank_to_faa(gbkf, complexheader=False, skip_pseudo=True): seqs, handle = genbank_seqio(gbkf) for seq in seqs: for feat in seq.features: cid = cds_details(seq, feat, complexheader, skip_pseudo) if not cid: continue if 'tran...
Python
nomic_cornstack_python_v1
function get_is_pricebooks_enabled self begin return is_pricebooks_enabled end function
def get_is_pricebooks_enabled(self): return self.is_pricebooks_enabled
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Jan 10 20:08:24 2019 @author: 45570 set a = integer input string Please input a number: set b = integer input string Please input another number: while b != 0 begin set tuple a b = tuple b a % b end print string The GCD is a
# -*- coding: utf-8 -*- """ Created on Thu Jan 10 20:08:24 2019 @author: 45570 """ a = int(input("Please input a number:")) b = int(input("Please input another number:")) while b!=0: a, b = b, a % b print("The GCD is ",a)
Python
zaydzuhri_stack_edu_python
function loadtable header rows major=string = minor=string - thousands=true begin string Print a tabular output, with horizontal separators set formatted = call load_csv header rows sep=string thousands=thousands set tuple header rows = tuple formatted at 0 formatted at slice 1 : : return call banner header rows end...
def loadtable(header, rows, major='=', minor='-', thousands=True): """ Print a tabular output, with horizontal separators """ formatted = load_csv(header, rows, sep=" ", thousands=thousands) header, rows = formatted[0], formatted[1:] return banner(header, rows)
Python
jtatman_500k
string Input: 00000000000000000000000000001011 Output: 3 class Solution extends object begin function hammingWeight self n begin string :type n: int :rtype: int if not n begin return 0 end set count = 0 while n != 0 begin set count = count + 1 set n = n ? n - 1 end return count end function function hammingWeight self ...
""" Input: 00000000000000000000000000001011 Output: 3 """ class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ if not n: return 0 count = 0 while n != 0: count += 1 n = n & (n-1) ret...
Python
zaydzuhri_stack_edu_python
function delete_many self *keys begin remove collection dict string _id dict string $in keys return true end function
def delete_many(self, *keys): self.collection.remove({'_id': {'$in': keys}}) return True
Python
nomic_cornstack_python_v1
string Created: @Chandi_Bhandari for Teaching for ML Student Nearest Neighbor Method: Using Association Rule comment importing the general packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import sys comment to generate all permutation and combination import itertools...
''' Created: @Chandi_Bhandari for Teaching for ML Student Nearest Neighbor Method: Using Association Rule ''' # importing the general packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import sys # to generate all permutation and combination import itertool...
Python
zaydzuhri_stack_edu_python
import io import math import os import sys from dotenv import load_dotenv import pandas as pd import requests call load_dotenv comment https://epc.opendatacommunities.org/docs/api/domestic#domestic-pagination set API_RESULT_LIMIT = 10000 set API_PAGE_SIZE_LIMIT = 5000 function get_api_credentials begin set user = call ...
import io import math import os import sys from dotenv import load_dotenv import pandas as pd import requests load_dotenv() # https://epc.opendatacommunities.org/docs/api/domestic#domestic-pagination API_RESULT_LIMIT = 10000 API_PAGE_SIZE_LIMIT = 5000 def get_api_credentials(): user = os.getenv('EPC_API_USER')...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string /** * created by M. Im 2017-08-03 */ function get_paths directory begin import os try begin exists path directory return list comprehension join path directory f for f in list directory directory end except any begin print string Path doesn't exists or it is not a directory! end end...
# -*- coding: utf-8 -*- '''/** * created by M. Im 2017-08-03 */''' def get_paths(directory): import os try: os.path.exists(directory) return [os.path.join(directory,f) for f in os.listdir(directory)] except: print('Path doesn\'t exists or it is not a directory! ...
Python
zaydzuhri_stack_edu_python
function update self json_path begin with open json_path as f begin set params = load json f update __dict__ params end end function
def update(self, json_path): with open(json_path) as f: params = json.load(f) self.__dict__.update(params)
Python
nomic_cornstack_python_v1
string This script is a benchmark to test different FIR filter on real time implementation (sample by sample) Author. Gabriel Galeote Checa email: gabriel@imse-cnm.csic.es GNU license import matplotlib.pylab as plt import numpy as np from scipy import signal import iir comment Set your sampling frequency comment Hertz ...
""" This script is a benchmark to test different FIR filter on real time implementation (sample by sample) Author. Gabriel Galeote Checa email: gabriel@imse-cnm.csic.es GNU license """ import matplotlib.pylab as plt import numpy as np from scipy import signal import iir #Set your sampling frequency fs ...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self node=none value=none begin set value = value set pRight = none set pLeft = node if node != none begin set pRight = self end end function end class class LinkedList begin function __init__ self begin set pHead = call Node set pLast = pHead set len = 0 end function function __getno...
class Node: def __init__(self,node=None,value=None): self.value=value self.pRight=None self.pLeft=node if node!=None: node.pRight=self class LinkedList: def __init__(self): self.pHead=Node() self.pLast=self.pHead self.len=0 def __getnode__...
Python
zaydzuhri_stack_edu_python
import os import requests function call_api request begin set api_key = get environ string API_KEY set endpoint = get environ string ENDPOINT set response = get requests endpoint params=dict string api_key api_key return json response end function if __name__ == string __main__ begin set environ at string API_KEY = str...
import os import requests def call_api(request): api_key = os.environ.get('API_KEY') endpoint = os.environ.get('ENDPOINT') response = requests.get(endpoint, params={'api_key': api_key}) return response.json() if __name__ == '__main__': os.environ['API_KEY'] = 'abc1234' os.environ['ENDPOINT'] = 'https://exampl...
Python
flytech_python_25k
import AST from SymbolTable import Scope from collections import defaultdict from dataclasses import dataclass decorator dataclass class ArrayT begin set dims : int set eltype : any set size : any function __hash__ self begin return call hash tuple dims eltype size end function end class set AnyT = string any set IntT ...
import AST from SymbolTable import Scope from collections import defaultdict from dataclasses import dataclass @dataclass class ArrayT: dims: int eltype: any size: any def __hash__(self): return hash((self.dims, self.eltype, self.size)) AnyT = 'any' IntT = 'int' FloatT = 'float' StringT = 's...
Python
zaydzuhri_stack_edu_python
from const import Matrix import math import random class LinerModel begin function __init__ self m_x m_y **query begin set b = call LUP_inverse * transpose m_x * m_y end function function predict self m_x begin return integer round value at 0 at 0 end function end class class RidgeModel begin function __init__ self m_x...
from const import Matrix import math import random class LinerModel: def __init__(self, m_x, m_y, **query): self.b = (m_x.transpose() * m_x).LUP_inverse() * m_x.transpose() * m_y def predict(self, m_x): return int(round((m_x * self.b).value[0][0])) class RidgeModel: def __init__(self,m_...
Python
zaydzuhri_stack_edu_python
comment # 迭代器 comment list = [2,3,4,5,6,7] comment it = iter(list) comment a = next(it) comment print(a) comment a_list = input("请输入符合条件的单词:") comment b = a_list.split() comment print(b) comment c =len(b[1]) comment print(c) comment word_list = input().split(' ') comment last_word = word_list[-1] comment print(len(last...
# # 迭代器 # list = [2,3,4,5,6,7] # it = iter(list) # a = next(it) # # print(a) # a_list = input("请输入符合条件的单词:") # b = a_list.split() # print(b) # c =len(b[1]) # print(c) # word_list = input().split(' ') # last_word = word_list[-1] # print(len(last_word))awd # a = input().lower() # # b= input().lower() # # c = a.count...
Python
zaydzuhri_stack_edu_python
function standardize *args **kwargs begin set channels = pop kwargs string channels list set copy = pop kwargs string copy false set reg = pop kwargs string reg 10 ^ - 10 if length kwargs begin raise call TypeError format string following kwargs are invalid: {} kwargs end assert length args > 0 comment treat channels p...
def standardize(*args, **kwargs): channels = kwargs.pop('channels', []) copy = kwargs.pop('copy', False) reg = kwargs.pop('reg', 10**-10) if len(kwargs): raise TypeError('following kwargs are invalid: {}'.format(kwargs)) assert len(args) > 0 # treat channels properly if channels ...
Python
nomic_cornstack_python_v1
function build_person first_name last_name age=string begin set person = dict string first first_name ; string last last_name if age begin set person at string age = age end return person end function
def build_person(first_name, last_name, age=''): person = {'first': first_name, 'last': last_name} if age: person['age'] = age return person
Python
nomic_cornstack_python_v1
function check_ev n begin if n % 2 == 0 begin return true end else begin return false end end function function check_odd n begin if n % 2 != 0 begin return true end else begin return false end end function function check_prime n begin for a in range 3 n + 1 begin if n % a == 0 begin return false end end for else begin...
def check_ev(n): if(n%2==0): return True else: return False def check_odd(n): if(n%2!=0): return True else: return False def check_prime(n): for a in range(3,n+1): if(n%a==0): return False else: return True def check_armstro...
Python
zaydzuhri_stack_edu_python
function total_ducks_in_pond begin comment 50% set percentage_muscovy = 0.5 comment 30% set percentage_female_muscovy = 0.3 comment as given in the problem set female_muscovy_ducks = 6 comment Set up the equation: 0.30 * (0.50 * D) = 6 comment D = 6 / (0.30 * 0.50) set total_ducks = female_muscovy_ducks / percentage_fe...
def total_ducks_in_pond(): percentage_muscovy = 0.50 # 50% percentage_female_muscovy = 0.30 # 30% female_muscovy_ducks = 6 # as given in the problem # Set up the equation: 0.30 * (0.50 * D) = 6 # D = 6 / (0.30 * 0.50) total_ducks = female_muscovy_ducks / (percentage_female_muscovy * percenta...
Python
dbands_pythonMath
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment Author: Wangzhenqing <wangzhenqing1008@163.com> comment Date: 2015年01月28日13:06:13 string Problem 4: Write a function treemap to map a function over nested list. function treemap f a y=none begin string >>> treemap(lambda x: x*x, [1, 2, [3, 4, [5]]]) [1,...
# !/usr/bin/env python # -*- coding: utf-8 -*- # Author: Wangzhenqing <wangzhenqing1008@163.com> # Date: 2015年01月28日13:06:13 """ Problem 4: Write a function treemap to map a function over nested list. """ def treemap(f, a, y=None): """ >>> treemap(lambda x: x*x, [1, 2, [3, 4, [5]]]) [1, 4, [9, 16...
Python
zaydzuhri_stack_edu_python
function factorial n begin comment Check if the input is a non-negative integer if not is instance n int or n < 0 begin raise call ValueError string Input must be a non-negative integer end comment Base case: factorial of 0 is 1 if n == 0 begin return 1 end comment Recursive case comment Check if the factorial has alre...
def factorial(n): # Check if the input is a non-negative integer if not isinstance(n, int) or n < 0: raise ValueError("Input must be a non-negative integer") # Base case: factorial of 0 is 1 if n == 0: return 1 # Recursive case # Check if the factorial has already been ...
Python
jtatman_500k
import bpy function generate_cube_mesh parameter begin set verts = list tuple 0 0 0 tuple 1 0 0 tuple 1 1 0 tuple 0 1 0 tuple 0 0 parameter tuple 1 0 parameter tuple 1 1 parameter tuple 0 1 parameter set edges = list tuple 0 1 tuple 1 2 tuple 2 3 tuple 3 0 tuple 4 5 tuple 5 6 tuple 6 7 tuple 7 4 tuple 0 4 tuple 1 5 tup...
import bpy def generate_cube_mesh(parameter): verts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, parameter), (1, 0, parameter), (1, 1, parameter), (0, 1, parameter)] edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)] mesh = bpy.data.meshes.ne...
Python
jtatman_500k
function dequip equipment_list slot item begin if equipment_list at slot == item begin set equipment_list at slot = none return true end else begin return false end end function
def dequip(equipment_list, slot, item): if equipment_list[slot] == item: equipment_list[slot] = None return True else: return False
Python
nomic_cornstack_python_v1
for j in range 1 integer input begin set l = list set f = j set m = 0 while j > 0 begin set a = j % 10 set j = j // 10 append l a end for tuple key value in enumerate l at slice : : - 1 begin if count l key != value begin break end end for else begin print f end end
for j in range(1,int(input())): l=[] f=j m=0 while j>0: a=j%10 j=j//10 l.append(a) for key,value in enumerate(l[::-1]): if l.count(key)!=value: break else: print(f)
Python
zaydzuhri_stack_edu_python
function get_action_value self begin set restart_current = call isChecked set restart_all = call isChecked set no_restart = not any list restart_all restart_current return tuple restart_all restart_current no_restart end function
def get_action_value(self): restart_current = self._restart_current.isChecked() restart_all = self._restart_all.isChecked() no_restart = not any([restart_all, restart_current]) return restart_all, restart_current, no_restart
Python
nomic_cornstack_python_v1
function calculate_sum my_list begin comment Create an empty set to store unique elements set unique_elements = set comment Iterate through each element in the list for element in my_list begin comment Add the element to the set add unique_elements element end comment Initialize the sum to 0 set sum_of_elements = 0 com...
def calculate_sum(my_list): # Create an empty set to store unique elements unique_elements = set() # Iterate through each element in the list for element in my_list: # Add the element to the set unique_elements.add(element) # Initialize the sum to 0 sum_of_elements = 0 ...
Python
jtatman_500k
function get_curr_prices index_list url begin set curr_prices = dict for tuple symbol name in items index begin comment create url with index symbol set new_url = format url symbol symbol comment get the index html data from yahoo finance set r = get requests new_url comment save name and price information in dictiona...
def get_curr_prices(index_list, url): curr_prices = {} for symbol, name in index.items(): # create url with index symbol new_url = url.format(symbol, symbol) # get the index html data from yahoo finance r = requests.get(new_url) # save...
Python
nomic_cornstack_python_v1
class Person begin function __init__ self name surname number begin set name = name set surname = surname set number = number end function end class class LearnerMixin begin function __init__ self begin set classes = list end function function enrol self course begin append classes course end function end class class ...
class Person: def __init__(self, name, surname, number): self.name = name self.surname = surname self.number = number class LearnerMixin: def __init__(self): self.classes = [] def enrol(self, course): self.classes.append(course) class TeacherMixin: def __init...
Python
zaydzuhri_stack_edu_python
while true begin set tuple valor1 valor2 = map int split input if valor1 <= 0 or valor2 <= 0 begin break end set maior = if expression valor1 > valor2 then valor1 else valor2 set menor = if expression valor2 < valor1 then valor2 else valor1 if maior > menor begin set x = maior set maior = menor set menor = x end set so...
while True: valor1, valor2 = map(int, input().split()) if valor1 <= 0 or valor2 <= 0: break maior = valor1 if valor1 > valor2 else valor2 menor = valor2 if valor2 < valor1 else valor1 if maior > menor: x = maior maior = menor menor = x soma = 0 while maio...
Python
zaydzuhri_stack_edu_python
import sys import random import signal import time import copy class TimedOutExc extends Exception begin pass end class function handler signum frame begin comment print 'Signal handler called with signal', signum raise call TimedOutExc end function class Player16 begin function __init__ self begin set Approx_win_score...
import sys import random import signal import time import copy class TimedOutExc(Exception): pass def handler(signum, frame): #print 'Signal handler called with signal', signum raise TimedOutExc() class Player16(): def __init__(self): self.Approx_win_score=11 self.Board_weight=31 self.win_score=10**6 sel...
Python
zaydzuhri_stack_edu_python
function pop_prefix self begin pop _prefix_stack set _prefix_str = join string _prefix_stack end function
def pop_prefix(self): self._prefix_stack.pop() self._prefix_str = "".join(self._prefix_stack)
Python
nomic_cornstack_python_v1
function importInterface begin if call _master_checks and call _check_plugin string MYSQL_FIREWALL begin if not call _exec_bulk_inject_firewall_rules begin print string ERROR: Please Check Interface Table MYSQL_SECURITY_METADATA.FIREWALL_WHITELIST, ABORTED ! print string Run security.addFirewallInterface() if t...
def importInterface(): if _master_checks() and _check_plugin('MYSQL_FIREWALL'): if not _exec_bulk_inject_firewall_rules(): print("\n\033[1mERROR:\033[0m Please Check Interface Table MYSQL_SECURITY_METADATA.FIREWALL_WHITELIST, ABORTED ! \n") print("Run security.addFirewallInterface() ...
Python
nomic_cornstack_python_v1
function main_layout app data content begin set layout = call Div list call Header call get_header app data call Main id=string page-content children=list content call Footer call get_footer return layout end function
def main_layout(app: dash.Dash, data: GameData, content: html) -> html: layout = html.Div([ html.Header(get_header(app, data)), html.Main(id='page-content', children=[content]), html.Footer(get_footer()) ]) return layout
Python
nomic_cornstack_python_v1
function hd_to_ang_v hd_activations centers jitter=0.01 begin set n_samples = shape at 0 set indices = argument maximum hd_activations axis=1 set angs = centers at indices + call normal loc=0 scale=jitter size=tuple n_samples comment Note: 1D array needs a vstack and a transpose instead of an hstack for the shape to be...
def hd_to_ang_v(hd_activations, centers, jitter=0.01): n_samples = hd_activations.shape[0] indices = np.argmax(hd_activations, axis=1) angs = centers[indices] + np.random.normal(loc=0, scale=jitter, size=(n_samples,)) # Note: 1D array needs a vstack and a transpose instead of an hstack for the shape...
Python
nomic_cornstack_python_v1
function test_load_excel self begin set xl_project = call Project string test_excel set ideal_iris = call load_dataset string iris set actual_iris = call load_dataset string iris call assertDataFrameEqual ideal_iris actual_iris end function
def test_load_excel(self): xl_project = pr.Project("test_excel") ideal_iris = self.project.load_dataset("iris") actual_iris = xl_project.load_dataset("iris") self.assertDataFrameEqual(ideal_iris, actual_iris)
Python
nomic_cornstack_python_v1
import re import nltk import ngdl_classes import global_vars import ngdl_parse import ngdl_write function start_dialog output_file=string test.txt begin if not initialized begin call init end else begin call reset_global_vars end set output = open output_file string w end function
import re import nltk import ngdl_classes import global_vars import ngdl_parse import ngdl_write def start_dialog(output_file="test.txt"): if not global_vars.initialized: global_vars.init() else: reset_global_vars() output = open(output_file, "w")
Python
jtatman_500k
function _parse_dict dct begin return dictionary comprehension split k string : 1 at - 1 : v for tuple k v in items dct end function
def _parse_dict(dct): return {k.split(":", 1)[-1]: v for k, v in dct.items()}
Python
nomic_cornstack_python_v1
function testExtendedSuccessMessageWithCreatedIDs self begin set json_message = json_message set msg = call json_message true message=string Test created=list 1 2 3 set msg = loads msg assert equal length msg 4 assert equal msg at string status string success assert equal msg at string statuscode string 200 assert equa...
def testExtendedSuccessMessageWithCreatedIDs(self): json_message = current.xml.json_message msg = json_message(True, message="Test", created=[1, 2, 3]) msg = json.loads(msg) self.assertEqual(len(msg), 4) self.assertEqual(msg["status"], "success") self.assertEqual(msg["s...
Python
nomic_cornstack_python_v1
from random import choice , sample , random from string import letters , printable comment Population Generator ##### class Generation begin function __init__ self population_size individual_size values begin set population_size = population_size set individual_size = individual_size set values = values end function co...
from random import choice, sample, random from string import letters, printable ##### Population Generator ##### class Generation(): def __init__(self, population_size, individual_size, values): self.population_size = population_size self.individual_size = individual_size self.values = values ##### Mathemati...
Python
zaydzuhri_stack_edu_python
function postorder_traversal self begin comment Reset to to guarantee we start from root. call reset comment Go down to the first leaf. while call can_move_down begin call down end comment Traverse forever (or until we break on some ending condition). while true begin comment Yield the current node. set yielded_node = ...
def postorder_traversal(self) -> Generator[MappingTree, None, None]: # Reset to to guarantee we start from root. self.reset() # Go down to the first leaf. while self.can_move_down(): self.down() # Traverse forever (or until we break on some ending condition). ...
Python
nomic_cornstack_python_v1
import random comment creates list set num = list comment appeds a random int between 0 and 100 to the list 10 times creating a list with 10 rand ints between 0 and 100 for values in range 0 10 begin append num random integer 0 100 end comment prints list print num comment prints min of list print min num comment prin...
import random num=[ ]#creates list for values in range(0,10):#appeds a random int between 0 and 100 to the list 10 times creating a list with 10 rand ints between 0 and 100 num.append(random.randint(0,100)) print(num)#prints list print(min(num))#prints min of list print(max(num))#prints max of list print(sum(num)/...
Python
zaydzuhri_stack_edu_python
class MathDojo extends object begin function __init__ self *args begin set result = 0 end function function add self *args begin comment *args can take multiple arguments into one parameter for val in args begin if type val == list or type val == tuple begin comment takes value of integers within lists and tuples into ...
class MathDojo(object): def __init__(self, *args): self.result=0 def add(self, *args): # *args can take multiple arguments into one parameter for val in args: if type(val)== list or type(val) == tuple: # takes value of integers within lists and tuples into account for i in val: self.result+=i ...
Python
zaydzuhri_stack_edu_python
import pandas as pd from sklearn import preprocessing from sklearn.decomposition import PCA import matplotlib.pyplot as plt import numpy as np set df = read csv string ../data/CSV/p53_33%_(5,409 fields, 10,231 records).csv low_memory=false set df = drop missing replace df string $null$ nan set num_active = length df at...
import pandas as pd from sklearn import preprocessing from sklearn.decomposition import PCA import matplotlib.pyplot as plt import numpy as np df = pd.read_csv("../data/CSV/p53_33%_(5,409 fields, 10,231 records).csv", low_memory=False) df = df.replace('$null$', np.nan).dropna() num_active = len(df[df['in...
Python
zaydzuhri_stack_edu_python
function write_swap_all self begin for pd_desc in keys _cache begin call write_swap pd_desc end end function
def write_swap_all(self): for pd_desc in self._cache.keys(): self.write_swap(pd_desc)
Python
nomic_cornstack_python_v1
function init_GD_model self begin function emb_init_wrapper target_params begin function emb_init shape dtype=none begin return target_params end function return emb_init end function comment Network inputs set emb_index = input shape=tuple 1 name=string pred_emb_index comment Retrieve the predicted parameters from the...
def init_GD_model(self): def emb_init_wrapper(target_params): def emb_init(shape, dtype=None): return target_params return emb_init # Network inputs emb_index = Input(shape=(1,), name="pred_emb_index") # Retrieve the predicted parameters from the...
Python
nomic_cornstack_python_v1
function red_fish target_size=none rgb=true begin return call imread HERE + string red_fish.jpg target_size=target_size rgb=rgb end function
def red_fish(target_size: Optional[Tuple[int, int]] = None, rgb: bool = True) -> Tensor: return imread(HERE+'red_fish.jpg', target_size=target_size, rgb=rgb)
Python
nomic_cornstack_python_v1
function calmar_ratio returns period=DAILY annualization=none begin string Determines the Calmar ratio, or drawdown ratio, of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum_returns`. period : str, op...
def calmar_ratio(returns, period=DAILY, annualization=None): """ Determines the Calmar ratio, or drawdown ratio, of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. - See full explanation in :func:`~empyrical.stats.cum...
Python
jtatman_500k
function get_w2v begin set model = load Word2Vec string model/person.model with open string data/vec.txt string w as f begin for word in keys vocab begin set vec_string = replace replace replace replace call array2string wv at word string [ string string ] string string [ string string string set line = format string ...
def get_w2v(): model = word2vec.Word2Vec.load('model/person.model') with open('data/vec.txt', 'w') as f: for word in model.wv.vocab.keys(): vec_string = np.array2string(model.wv[word]).replace('[ ', '').replace(']', '').replace('[', '').replace('\n', '') line = "{0} {1}\n".format...
Python
nomic_cornstack_python_v1
function psd_units self c psd=none begin set dev = call selectedDevice c set units = dict string OFF 0 ; string ON 1 if psd is none begin set resp = yield query dev string PSDU?0 set psd = call long resp end else begin if is instance psd str begin if upper psd not in units begin raise exception string Can only turn ON ...
def psd_units(self, c, psd=None): dev = self.selectedDevice(c) units = { 'OFF': 0, 'ON': 1, } if psd is None: resp = yield dev.query('PSDU?0') psd = long(resp) else: if isinstance(psd, str): if psd.up...
Python
nomic_cornstack_python_v1
comment # To add a new cell, type '# %%' comment # To add a new markdown cell, type '# %% [markdown]' comment # %% comment # Write a Python program to flip a coin 1000 times and count heads and tails. comment ______ ra__ comment ______ it.. comment results _ { comment 'heads': 0, comment 'tails': 0, comment } comment s...
# # To add a new cell, type '# %%' # # To add a new markdown cell, type '# %% [markdown]' # # %% # # Write a Python program to flip a coin 1000 times and count heads and tails. # # ______ ra__ # ______ it.. # # results _ { # 'heads': 0, # 'tails': 0, # } # # sides _ li.. ?.k.. # # ___ i __ ra.. 10000 # ? ra...
Python
zaydzuhri_stack_edu_python
string Class for simulating and measuring performance over a single day on a mean reversion strategy. import pandas as pd from pandas.stats.moments import rolling_mean from Tools import average_true_range , snf , test_fixed_stop_target , test_fixed_bar_exit comment DATA_DIR = "/Users/peterharrington/Documents/GitHub/ev...
""" Class for simulating and measuring performance over a single day on a mean reversion strategy. """ import pandas as pd from pandas.stats.moments import rolling_mean from Tools import average_true_range, snf, test_fixed_stop_target, test_fixed_bar_exit #DATA_DIR = "/Users/peterharrington/Documents/GitHub/evolvingt...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function maxProfit self prices begin set max_profit = 0 append prices - 1 set buy_price = none for i in range length prices - 1 begin comment Need to buy if buy_price is none begin if prices at i + 1 > prices at i begin set buy_price = prices at i end end else comment Need to sell if...
class Solution(object): def maxProfit(self, prices): max_profit = 0 prices.append(-1) buy_price = None for i in range(len(prices) - 1): if buy_price is None: # Need to buy if prices[i+1] > prices[i]: buy_price = prices[i] e...
Python
zaydzuhri_stack_edu_python
function traverse node begin for child in node begin call traverse child end call apply_change node end function
def traverse(node: Node): for child in node: traverse(child) self.apply_change(node)
Python
nomic_cornstack_python_v1
function type_guess df strict=false begin set guesses = list set types = list _STRING_TYPE _INTEGER_TYPE _DECIMAL_TYPE _BOOLEAN_TYPE _DATE_TYPE set type_instances = list comprehension i for t in types for i in call instances if strict begin set at_least_one_value = list for row in call iterrows begin comment ri = row...
def type_guess(df, strict=False): guesses = [] types = [_STRING_TYPE, _INTEGER_TYPE, _DECIMAL_TYPE, _BOOLEAN_TYPE, _DATE_TYPE] type_instances = [i for t in types for i in t.instances()] if strict: at_least_one_value = [] for row in df.iterrows(): # ri = row[0] cel...
Python
nomic_cornstack_python_v1
function F k begin string With exactly k digits, return the number of ways to have numbers that do not have 0, 1 or A return 14 + 14 + 15 * 15 ^ k - 1 - 13 + 14 + 14 * 14 ^ k - 1 + 13 * 13 ^ k - 1 end function comment Numbers that dont have 1, A, or 0 comment Numbers that dont have 1 + A, 1 + 0, A + 0 comment Numbers t...
def F( k ): """ With exactly k digits, return the number of ways to have numbers that do not have 0, 1 or A """ return ( # Numbers that dont have 1, A, or 0 ( 14 + 14 + 15 ) * 15 ** ( k - 1 ) - # Numbers that dont have 1 + A, 1 + 0, A + 0 ( 13 + 14 + 14 ) * 14 ** ( k - 1 ) +...
Python
zaydzuhri_stack_edu_python
import pygame from pygame.sprite import Sprite class Bullet extends Sprite begin function __init__ self ai_game begin call __init__ set shanbi = true set time = - 1 set speed = bul_speed set screen = screen set settings = settings end function function update self begin set y = y - speed set y = y end function function...
import pygame from pygame.sprite import Sprite class Bullet(Sprite): def __init__(self,ai_game): super().__init__() self.shanbi = True self.time = -1 self.speed = ai_game.ship.bul_speed self.screen = ai_game.screen self.settings = ai_game.settings def update(se...
Python
zaydzuhri_stack_edu_python
import requests import re function get_one_page url begin set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0 set reponse = get requests url headers=headers if status_code == 200 begin return text end return none end function function main begin set ...
import requests import re def get_one_page(url): headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0'} reponse = requests.get(url, headers=headers) if reponse.status_code == 200: return reponse.text return None def main(): url = 'https:...
Python
zaydzuhri_stack_edu_python
from sklearn.cluster import KMeans from sklearn.cluster import MeanShift , estimate_bandwidth import numpy as np import operator from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D function get_random_data begin set x1 = uniform - 1 1 100 set y1 = uniform - 1 1 100 set z1 = uniform - 1 1 100 se...
from sklearn.cluster import KMeans from sklearn.cluster import MeanShift, estimate_bandwidth import numpy as np import operator from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D def get_random_data(): x1 = np.random.uniform(-1, 1, 100) y1 = np.random.uniform(-1, 1, 100) z1 = np....
Python
zaydzuhri_stack_edu_python
from ExpertSystem.Business.Parser.KnowledgeBase.RulesListener import RulesListener from ExpertSystem.Structure.Enums import LogicalOperator from ExpertSystem.Structure.RuleBase import Rule , Expression , ExpressionNode if __name__ is not none and string . in __name__ begin from RulesParser import RulesParser end else b...
from ExpertSystem.Business.Parser.KnowledgeBase.RulesListener import RulesListener from ExpertSystem.Structure.Enums import LogicalOperator from ExpertSystem.Structure.RuleBase import Rule, Expression, ExpressionNode if __name__ is not None and "." in __name__: from .RulesParser import RulesParser else: from R...
Python
zaydzuhri_stack_edu_python
comment visulaise windturbine in a world map or respective country map comment Default plot all wind turbines on a world map function plot_windturbine csv_path country=string world begin import pandas as pd import matplotlib.pyplot as plt import descartes import geopandas as gpd from shapely.geometry import Point , Pol...
#visulaise windturbine in a world map or respective country map #Default plot all wind turbines on a world map def plot_windturbine(csv_path,country='world'): import pandas as pd import matplotlib.pyplot as plt import descartes import geopandas as gpd from shapely.geometry import Point, Polygon import os base_...
Python
zaydzuhri_stack_edu_python
function fairRations queue begin set count = 0 set index = 0 set should_increment = false while index < length queue - 1 begin set current_val = queue at index set next_val = queue at index + 1 if should_increment begin set current_val = current_val + 1 end set is_current_odd = current_val % 2 == 1 set is_next_even = n...
def fairRations(queue) -> str: count = 0 index = 0 should_increment = False while index < len(queue) - 1: current_val = queue[index] next_val = queue[index + 1] if should_increment: current_val += 1 is_current_odd = current_val % 2 == 1 is_next_even...
Python
nomic_cornstack_python_v1
function build_tree df begin comment initialize empty tree as a dictionary set tree = dict comment find column associated with best information gain set next_att = call best_inf_gain_att df comment next_att = find_winner(df) set tree at next_att = dict comment for each value of the attribute at hand for val in unique...
def build_tree(df) -> dict: # initialize empty tree as a dictionary tree = {} # find column associated with best information gain next_att = best_inf_gain_att(df) # next_att = find_winner(df) tree[next_att] = {} # for each value of the attribute at hand for val in np.unique(df[...
Python
nomic_cornstack_python_v1
for x in range 0 q begin set queries = call raw_input set queries = split queries set l = integer queries at 0 set r = integer queries at 1 set x = integer queries at 2 for y in range l - 1 r - 1 begin set num = integer array at y set k = num set xor = num ? x set low = 0 for z in range l - 1 r - 1 begin set num1 = int...
for x in range(0, q): queries = raw_input() queries = queries.split() l = int(queries[0]) r = int(queries[1]) x = int(queries[2]) for y in range(l-1, r-1): num = int(array[y]) k = num xor = num ^ x low = 0 for z in range(l-1, r-1): num1 = int(a...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 string Defines unittests for models/engine/file_storage.py. Unittest classes: TestFileStorage_instantiation TestFileStorage_methods import os import json import models import unittest from datetime import datetime from models.base_model import BaseModel from models.engine.file_storage import F...
#!/usr/bin/python3 """Defines unittests for models/engine/file_storage.py. Unittest classes: TestFileStorage_instantiation TestFileStorage_methods """ import os import json import models import unittest from datetime import datetime from models.base_model import BaseModel from models.engine.file_storage import...
Python
zaydzuhri_stack_edu_python