code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
for i in range length a begin if a at i in special begin set count = count + 1 end end print count
for i in range(len(a)): if(a[i] in special): count=count+1 print(count)
Python
zaydzuhri_stack_edu_python
try begin from pytube import YouTube from pytube import Playlist end except Exception as e begin print format string some modules are missing{} e end set url = string https://www.youtube.com/watch?v=668nUCeBHyY set ytd = call download print ytd
try: from pytube import YouTube from pytube import Playlist except Exception as e: print("some modules are missing{}".format(e)) url="https://www.youtube.com/watch?v=668nUCeBHyY" ytd =YouTube(url).streams.first().download() print(ytd)
Python
zaydzuhri_stack_edu_python
function withdraw self amount begin if amount < 0 begin return string Amount must be >= 0 end else if _balance < amount begin return string Insufficient funds end else begin set _balance = _balance - amount return none end end function
def withdraw(self, amount): if amount < 0: return 'Amount must be >= 0' elif self._balance < amount: return 'Insufficient funds' else: self._balance -= amount return None
Python
nomic_cornstack_python_v1
function dfs enroll_referral seller credit begin if seller == string - begin set dict at seller = credit + get dict seller 0 return end set dict at seller = get dict seller 0 + credit - credit // 10 set seller = enroll_referral at seller call dfs enroll_referral seller credit // 10 end function function solution enroll...
def dfs(enroll_referral, seller, credit): if seller == "-": dict[seller] = credit + dict.get(seller, 0) return dict[seller] = dict.get(seller, 0) + credit - (credit // 10) seller = enroll_referral[seller] dfs(enroll_referral, seller, credit // 10) def solution(enroll, referral, selle...
Python
zaydzuhri_stack_edu_python
function addDPQueriesToModel self model two_d_vars obj_fxn parent_mask q_set_list=none **kwargs begin import gurobipy as gb call ASSERT_TYPE model Model call ASSERT_TYPE two_d_vars MVar set lb = if expression nnls then 0 else - INFINITY if q_set_list is none begin set q_set_list = DPqueries end for tuple ihist dp_queri...
def addDPQueriesToModel(self, model, two_d_vars, obj_fxn, parent_mask, q_set_list=None, **kwargs): import gurobipy as gb ASSERT_TYPE(model, gb.Model) ASSERT_TYPE(two_d_vars, gb.MVar) lb = 0 if self.nnls else -gb.GRB.INFINITY if q_set_list is None: q_set_list = self.DP...
Python
nomic_cornstack_python_v1
function dfs obj begin call inc call p string DFS + string obj set traversal = list if obj in visited begin set traversal = visited at obj end else begin comment combat recusive loop set visited at obj = list set constraints = map lambda r -> relsDict at r rel set allExtendedPhrases = list for r in sorted constraint...
def dfs(obj): log.inc() log.p("DFS "+str(obj)) traversal=[] if obj in visited: traversal=visited[obj] else: visited[obj] = [] # combat recusive loop constraints=map(lambda r: relsDict[r], obj.rel) allExtendedPhrases=[] for r in sorted(constraints): phrases=...
Python
nomic_cornstack_python_v1
comment Startup helper functions import sys string If your webserver is the PythonWebServer, then 1. you should have the StuyTools.py file in the same directory as your Python file 2. the top of your code should look like: #! /usr/bin/python import StuyTools StuyTools.PWS_startup() comment Force the PythonWebServer to ...
# Startup helper functions import sys '''If your webserver is the PythonWebServer, then 1. you should have the StuyTools.py file in the same directory as your Python file 2. the top of your code should look like: #! /usr/bin/python import StuyTools StuyTools.PWS_startup() ''' # Force the PythonWebServer to change...
Python
zaydzuhri_stack_edu_python
function test_get_vessel_list_throws_DoesNotExistError begin set get_vessel_list = mock_get_vessel_list_throws_DoesNotExistError set release_vessels = mock_release_vessels set response = post string /html/del_resource good_data follow=true assert status_code == 200 assert string Unable to remove in content assert name ...
def test_get_vessel_list_throws_DoesNotExistError(): interface.get_vessel_list = mock_get_vessel_list_throws_DoesNotExistError interface.release_vessels = mock_release_vessels response = c.post('/html/del_resource', good_data, follow=True) assert(response.status_code == 200) assert("Unable to remove"...
Python
nomic_cornstack_python_v1
comment list: set naoAList = tuple 1 2 3 set list1 = list 1 2 3 set list2 = list naoAList print string list2 = list2 print list1 == list2 list1 == naoAList comment list operations: comment add: comment Note the difference between "append()" and "+=" for tuples. append list1 3 print string append() returns None: append ...
# list: naoAList = (1,2,3,) list1 = [1,2,3] list2 = list(naoAList) print("list2 = ", list2) print(list1 == list2, list1 == naoAList) # list operations: # add: # Note the difference between "append()" and "+=" for tuples. list1.append(3) print("append() returns None: ", list1.append(4)) print(list1) list1.append(lis...
Python
zaydzuhri_stack_edu_python
function m2i self pkt x begin comment type: (Optional[Packet], M) -> I set tuple s v = call ReadPackedUInt32 call cast int x return v end function
def m2i(self, pkt, x): # type: (Optional[Packet], M) -> I s, v = ReadPackedUInt32(cast(int, x)) return v
Python
nomic_cornstack_python_v1
import pyautogui as AI call typewrite list string winleft string r call typewrite string devmgmt.msc
import pyautogui as AI AI.typewrite(['winleft', 'r']) AI.typewrite('devmgmt.msc\n')
Python
flytech_python_25k
function _log self level msg *args **kwargs begin string Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) if not is instance level int begin if raiseExceptions ...
def _log(self, level, msg, *args, **kwargs): """ Log 'msg % args' with the integer severity 'level'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.log(level, "We have a %s", "mysterious problem", exc_info=1) """ ...
Python
jtatman_500k
function host self begin return _host end function
def host(self): return self._host
Python
nomic_cornstack_python_v1
import numpy as np import tensorflow as tf set matrix1 = list list 1.0 2.0 list 3.0 40 set matrix2 = array list list 1.0 2.0 list 3.0 40 dtype=float32 set matrix3 = call constant list list 1.0 2.0 list 3.0 40 print type matrix1 print type matrix2 print type matrix3 set tensorForM1 = call convert_to_tensor matrix1 dtype...
import numpy as np import tensorflow as tf matrix1 = [[1.0, 2.0], [3.0, 40]] matrix2 = np.array([[1.0, 2.0], [3.0, 40]], dtype=np.float32) matrix3 = tf.constant([[1.0, 2.0], [3.0, 40]]) print(type(matrix1)) print(type(matrix2)) print(type(matrix3)) tensorForM1 = tf.convert_to_tensor(matrix1, dtype=tf.float32) ten...
Python
zaydzuhri_stack_edu_python
function context self entry_hash begin set entry = call get_entry entry_hash set tuple source_slice sha256sum = call get_entry_slice entry if not is instance entry tuple Balance Transaction begin return tuple entry none none source_slice sha256sum end set entry_accounts = call get_entry_accounts entry set balances = di...
def context( self, entry_hash: str, ) -> tuple[ Directive, dict[str, list[str]] | None, dict[str, list[str]] | None, str, str, ]: entry = self.get_entry(entry_hash) source_slice, sha256sum = get_entry_slice(entry) if not isinstance...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import sys import os import os.path import warnings import cmd import argparse import collections import numpy as np from operator import * from typing import * import json comment Shut up Tensorflow if not warnoptions begin simple filter string ignore end if __name__ == string __main__ be...
#!/usr/bin/env python3 import sys import os import os.path import warnings import cmd import argparse import collections import numpy as np from operator import * from typing import * import json # Shut up Tensorflow if not sys.warnoptions: warnings.simplefilter("ignore") if __name__ == '__main__': # Ensure w...
Python
zaydzuhri_stack_edu_python
function visualize_class_examples data signnames begin set n_classes = length signnames set nrows = round square root n_classes set ncols = round square root n_classes set tuple fig axes = call subplots nrows=nrows ncols=ncols figsize=tuple 10 10 comment use examples from the training split set tuple X y = data at stri...
def visualize_class_examples(data, signnames): n_classes = len(signnames) nrows = ncols = round(math.sqrt(n_classes)) fig, axes = plt.subplots(nrows = nrows, ncols = ncols, figsize = (10,10)) # use examples from the training split X, y = data["train"] examples = [] for label in range(n_class...
Python
nomic_cornstack_python_v1
function _set_input self v load=false begin try begin set t = call YANGDynClass v base=yc_input_pyangbind_example__input is_container=string container yang_name=string input parent=self path_helper=_path_helper extmethods=_extmethods register_paths=true end except tuple TypeError ValueError begin raise call ValueError ...
def _set_input(self, v, load=False): try: t = YANGDynClass(v,base=yc_input_pyangbind_example__input, is_container='container', yang_name="input", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True) except (TypeError, ValueError): raise ValueError("""input mu...
Python
nomic_cornstack_python_v1
class Solution begin function setZeroes self matrix begin string Runtime: 128 ms, faster than 95.86% of Python3 online submissions for Set Matrix Zeroes. set row = set set col = set for i in range 0 length matrix begin for j in range 0 length matrix at 0 begin if matrix at i at j == 0 begin add row i add col j end end ...
class Solution: def setZeroes(self, matrix: List[List[int]]) -> None: """ Runtime: 128 ms, faster than 95.86% of Python3 online submissions for Set Matrix Zeroes. """ row = set() col = set() for i in range(0, len(matrix)): for j in range(0, len(ma...
Python
zaydzuhri_stack_edu_python
function all_methods self obj begin set temp = list for name in directory obj begin set func = get attribute obj name if has attribute func string __call__ begin append temp name end end return temp end function
def all_methods( self, obj ): temp = [] for name in dir( obj ): func = getattr( obj, name ) if hasattr( func, '__call__' ): temp.append( name ) return temp
Python
nomic_cornstack_python_v1
import json import smtplib , ssl function lambda_handler event context begin set message = event at string queryStringParameters at string message set to = event at string queryStringParameters at string to comment For SSL set port = 465 set password = string set senderEmail = string comment Create a secure SSL conte...
import json import smtplib, ssl def lambda_handler(event, context): message = event['queryStringParameters']['message'] to = event['queryStringParameters']['to'] port = 465 # For SSL password = "" senderEmail = "" # Create a secure SSL context server_context = ssl.create_default_context() ...
Python
zaydzuhri_stack_edu_python
import turtle call color string green function draw_square a b begin for i in range 4 begin call forward a call left b end end function set counter = 0 while counter < 12 begin call draw_square 100 90 call right 30 set counter = counter + 1 end call exitonclick
import turtle turtle.color("green") def draw_square(a,b): for i in range(4): turtle.forward(a) turtle.left(b) counter = 0 while counter < 12: draw_square(100,90) turtle.right(30) counter += 1 turtle.exitonclick()
Python
zaydzuhri_stack_edu_python
function slerp_weights angle t begin if angle == 0.0 begin return tuple ones like t zeros like t end return tuple sin 1.0 - t * angle / sin angle sin t * angle / sin angle end function
def slerp_weights(angle, t): if angle == 0.0: return np.ones_like(t), np.zeros_like(t) return (np.sin((1.0 - t) * angle) / np.sin(angle), np.sin(t * angle) / np.sin(angle))
Python
nomic_cornstack_python_v1
function foo x keyword=list begin append keyword string a print keyword end function function bar x foo begin call foo x end function if __name__ == string __main__ begin function f a begin return call foo a keyword=list 1 end function bar 1.0 f bar 1.0 f bar 1.0 f end
def foo(x, keyword=[]): keyword.append('a') print(keyword) def bar(x,foo): foo(x) if __name__ == '__main__': def f(a): return foo(a, keyword=[1]) bar(1.0, f) bar(1.0, f) bar(1.0, f)
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 import re import os import codecs function divide_odd_even_line begin set path = directory name path __file__ set odd_line_list = list set even_line_list = list set filename = join path path string forum_high_freq_sentence_sougou_checkout.txt with open filename encoding=string utf-8 as f begin se...
#coding:utf-8 import re import os import codecs def divide_odd_even_line(): path = os.path.dirname(__file__) odd_line_list = [] even_line_list = [] filename = os.path.join(path, 'forum_high_freq_sentence_sougou_checkout.txt') with codecs.open(filename, encoding='utf-8') as f: new_line_list...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string This script generate `.csv` file with data for training linear regression model for equation: y = 3x + 2 with the domain of X=[0, 20] The data will be altered with noise [-1,1] import csv from collections import defaultdict from random import random , randint function noised_f x beg...
#!/usr/bin/env python3 """ This script generate `.csv` file with data for training linear regression model for equation: y = 3x + 2 with the domain of X=[0, 20] The data will be altered with noise [-1,1] """ import csv from collections import defaultdict from random import random, randint def noised_f(x: float...
Python
zaydzuhri_stack_edu_python
function position_choice begin set position_choice = string while position_choice not in range 1 10 begin set position_choice = input string Enter position choice between 1 and 9 if is digit position_choice == false begin print string Enter a number dammit continue end else begin set position_choice = integer position...
def position_choice(): position_choice = '' while position_choice not in range(1, 10): position_choice = input('Enter position choice between 1 and 9 ') if position_choice.isdigit() == False: print('Enter a number dammit') continue else: posi...
Python
nomic_cornstack_python_v1
function test_cal_params_intake_EK80_BB_complex ek80_cal_path begin set ed = call open_raw ek80_cal_path / string 2018115-D20181213-T094600.raw sonar_model=string EK80 comment BB channels set chan_sel = list string WBT 714590-15 ES70-7C string WBT 714596-15 ES38-7 comment Assemble external freq-dependent cal param set ...
def test_cal_params_intake_EK80_BB_complex(ek80_cal_path): ed = ep.open_raw(ek80_cal_path / "2018115-D20181213-T094600.raw", sonar_model="EK80") # BB channels chan_sel = ["WBT 714590-15 ES70-7C", "WBT 714596-15 ES38-7"] # Assemble external freq-dependent cal param len_cal_frequency = ed["Vendor_sp...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment heartCases_help.py string heartCases is a medical language processing system for case reports involving cardiovascular disease (CVD). This part of the system includes helper functions. import os , sys , urllib , urllib2 from tqdm import * function build_mesh_to_icd10_dict icd10_map_file...
#!/usr/bin/python #heartCases_help.py ''' heartCases is a medical language processing system for case reports involving cardiovascular disease (CVD). This part of the system includes helper functions. ''' import os, sys, urllib, urllib2 from tqdm import * def build_mesh_to_icd10_dict(icd10_map_files): ''' Build ...
Python
zaydzuhri_stack_edu_python
function process_switch self name=none state=1 logical=false num=none obj=none debounced=true begin debug string Processing switch. Name: %s, state: %s, logical: %s,num: %s, obj: %s, debounced: %s name state logical num obj debounced comment Find the switch name comment can't be 'if num:` in case the num is 0. if num i...
def process_switch(self, name=None, state=1, logical=False, num=None, obj=None, debounced=True): self.log.debug("Processing switch. Name: %s, state: %s, logical: %s," "num: %s, obj: %s, debounced: %s", name, state, logical, num, obj, debounce...
Python
nomic_cornstack_python_v1
comment listas comment conjunto de datos, ordenados segun su ingreso, separados por coma "," comment tamaño es 10 set lista_numeros = list 0 1 2 3 4 5 6 7 8 9 print lista_numeros comment las listas comienza por la posicion(indice) 0 (cero)() set lista_datos_distintos = list string uno 2 string tres 4 print lista_datos_...
#listas # conjunto de datos, ordenados segun su ingreso, separados por coma "," lista_numeros = [0,1,2,3,4,5,6,7,8,9] #tamaño es 10 print(lista_numeros) #las listas comienza por la posicion(indice) 0 (cero)() lista_datos_distintos = ["uno",2,"tres",4] print(lista_datos_distintos) #cantidad de elementos = 4 elementos ...
Python
zaydzuhri_stack_edu_python
function queryServiceStatus self serviceId begin if _hothOrNewer begin set raw = call queryServiceInstancesV2 serviceId set decoded = call _convertInstancesV2ToStatuses raw end else begin set decoded = call queryServiceStatusImpl serviceId end return decoded end function
def queryServiceStatus(self, serviceId): if self._hothOrNewer: raw = self.queryServiceInstancesV2(serviceId) decoded = self._convertInstancesV2ToStatuses(raw) else: decoded = self.queryServiceStatusImpl(serviceId) return decoded
Python
nomic_cornstack_python_v1
function load_images_normalize_shift_rotate_random_fs folder n_img img_size no_angles shift=false imrotate=false begin comment image size must be even number assert img_size % 2 == 0 comment Initialize the arrays: set n_im = n_img if shift begin set n_im = 4 * n_img end if imrotate begin set n_im = 4 * n_img end if shi...
def load_images_normalize_shift_rotate_random_fs(folder, n_img, img_size, no_angles, shift = False, imrotate = False): assert(img_size % 2 == 0) # image size must be even number # Initialize the arrays: n_im = n_img if shift: n_im = 4*n_img if imrotate: n_im = 4*n_img if...
Python
nomic_cornstack_python_v1
function plot_tsne_reduction x_values y_values begin set tsne = t sne set x_transformed = fit transform tsne x_values return call plot_dimensionality_reduction x_transformed y_values end function
def plot_tsne_reduction(x_values: np.ndarray, y_values: np.ndarray) -> alt.Chart: tsne = manifold.TSNE() x_transformed = tsne.fit_transform(x_values) return plot_dimensionality_reduction(x_transformed, y_values)
Python
nomic_cornstack_python_v1
class Registry begin string Store classes in one place. Usage examples: >>> import torch.optim as optim >>> my_registry = Registry() >>> my_registry.add(optim.SGD) >>> my_registry["SGD"](*args, *kwargs) Add items using decorator: >>> my_registry = Registry() >>> @my_registry >>> class MyClass: >>> pass function __init_...
class Registry: """Store classes in one place. Usage examples: >>> import torch.optim as optim >>> my_registry = Registry() >>> my_registry.add(optim.SGD) >>> my_registry["SGD"](*args, *kwargs) Add items using decorator: >>> my_registry = Registry() >>> @m...
Python
zaydzuhri_stack_edu_python
from math import sin , cos set m = 4.9e-08 set B = 3.9 set R = 0.92 set T = 0.000577 * 4 set pi = 3.1415926535 comment Q1 comment R = mv/qB comment qvB = m 4pi^2 * R / T^2 = m v^2 / R comment v^2 / R = 4pi^2 * R / T^2 set v = 4 * pi * pi * R / T / T * R ^ 0.5 print v comment Q2 comment careful!!!! there is a negative s...
from math import sin, cos m = 4.9e-8 B = 3.9 R = 0.92 T = 577e-6 * 4 pi = 3.1415926535 # Q1 # R = mv/qB # qvB = m 4pi^2 * R / T^2 = m v^2 / R # v^2 / R = 4pi^2 * R / T^2 v = (4 * pi * pi * R / T / T * R) ** 0.5 print(v) # Q2 # careful!!!! there is a negative sign!!! t1 = 192.2e-6 F = m * v * v / R theta = t1 / T * 4 ...
Python
zaydzuhri_stack_edu_python
function watermark_image self watermark_path pos_name begin set image = open path set watermark = open watermark_path set tuple watermark_width watermark_height = size set pos = call watermark_position pos_name set parent_dir = directory name path output_path if not exists path parent_dir begin make directories parent_...
def watermark_image(self, watermark_path, pos_name): image = Image.open(self.path) watermark = Image.open(watermark_path) self.watermark_width, self.watermark_height = watermark.size pos = self.watermark_position(pos_name) parent_dir = os.path.dirname(self.output_path) i...
Python
nomic_cornstack_python_v1
function test_no_results self begin call create set response = call _get get_kwargs=dict string search string hello call assertEquals status_code 200 call assertTemplateUsed response template_name call assertEquals count context at string object_list 0 end function
def test_no_results(self): self.factory.create() response = self._get(get_kwargs={'search': 'hello'}) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, self.template_name) self.assertEquals(response.context['object_list'].count(), 0)
Python
nomic_cornstack_python_v1
function do_draw self context begin set rect = call get_allocation if juego begin call escalar tuple width height end end function
def do_draw(self, context): rect = self.get_allocation() if self.juego: self.juego.escalar((rect.width, rect.height))
Python
nomic_cornstack_python_v1
function remove_to_deletes self begin set go = true while go begin set go = false for op in queue begin if delete begin remove queue op set go = true break end end end end function
def remove_to_deletes(self): go = True while go: go = False for op in self.queue: if op.delete: self.queue.remove(op) go = True break
Python
nomic_cornstack_python_v1
comment modelos/ProductoServicio.py importo solo la clase comment as P from modelos.Producto import Producto from servicios.ProductoServicio import ProductoServicio comment ventas de productos <-- que es un producto? comment modelo o datos que vamos a trabajar. comment acciones (venta) comment tuple, seq, diccionary, c...
# modelos/ProductoServicio.py importo solo la clase from modelos.Producto import Producto # as P from servicios.ProductoServicio import ProductoServicio # ventas de productos <-- que es un producto? # modelo o datos que vamos a trabajar. # acciones (venta) # tuple, seq, diccionary, clase # clase de modelo (solo prop...
Python
zaydzuhri_stack_edu_python
function test_invalid_menu_print begin with raises Exception begin call print_specific string testing end end function
def test_invalid_menu_print(): with pt.raises(Exception): sc.print_specific('testing')
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python2.7 set adress_avai = list string 8.8.8.8 string 10.1.1.1 string 192.168.1.23 set adress_unavai = list string 123.3.3.4 string 33.4.5.6 string 45.7.8.3 function check_adresses avai unavai begin from tabulate import tabulate set final = list list string 8.8.8.8 string 123.3.3.4 list string 10...
#!/usr/bin/env python2.7 adress_avai=['8.8.8.8','10.1.1.1','192.168.1.23'] adress_unavai=['123.3.3.4','33.4.5.6','45.7.8.3'] def check_adresses(avai,unavai): from tabulate import tabulate final = [['8.8.8.8','123.3.3.4'],['10.1.1.1','33.4.5.6'],['192.168.1.23','45.7.8.3']] final1=list(zip(avai,unavai)) ...
Python
zaydzuhri_stack_edu_python
function get_plugin_media_path instance filename begin return call get_media_path filename end function
def get_plugin_media_path(instance, filename): return instance.get_media_path(filename)
Python
nomic_cornstack_python_v1
import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif from sklearn.model_selection import KFold from sklearn.model_selectio...
import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import f_classif from sklearn.model_selection import KFold from sklearn.model_...
Python
zaydzuhri_stack_edu_python
import read_data import re set COUNTRY_WEIGH = 3.0 set NEIGHBOURS_WEIGH = 0.75 class WorldGuesser begin function __init__ self begin set tuple iso_to_country_dict places_to_iso_dict = call read_country_data end function function create_proba_dict self begin set proba_dict = dict for tuple key value in items iso_to_cou...
import read_data import re COUNTRY_WEIGH = 3.0 NEIGHBOURS_WEIGH = 0.75 class WorldGuesser: def __init__(self): self.iso_to_country_dict, self.places_to_iso_dict = read_data.read_country_data() def create_proba_dict(self) -> dict: proba_dict = {} for key, value in self.iso_to_country...
Python
zaydzuhri_stack_edu_python
class Stack begin function __init__ self size begin set stack = list none * size set top = - 1 end function function isFull self begin return top == length stack - 1 end function function isEmpty self begin return top == - 1 end function function prints self begin return stack end function function push self item begin...
class Stack: def __init__(self, size): self.stack = [None] * size self.top = -1 def isFull(self): return self.top == len(self.stack) - 1 def isEmpty(self): return self.top == -1 def prints(self): return self.stack def push(self, item): if self.isFull(): print("The stack is full!") else: se...
Python
zaydzuhri_stack_edu_python
import math 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 function extract_last_n_primes lst n begin set primes = list for num in reversed lst begin if call is_prime num and num not in...
import math 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 extract_last_n_primes(lst, n): primes = [] for num in reversed(lst): if is_prime(num) and num not in primes: ...
Python
greatdarklord_python_dataset
import datetime set dt = now set date = string format time dt string %c set file = open string ../views/updated.html string w write file string <p class="updated"><i>Updated: + date + string </i></p> close file print date + string update doned
import datetime dt = datetime.datetime.now() date = dt.strftime("%c") file = open("../views/updated.html", "w") file.write('<p class="updated"><i>Updated: ' + date + '</i></p>') file.close() print(date + " update doned")
Python
zaydzuhri_stack_edu_python
comment By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. comment Answer : 4613732 set tuple a b = tuple 0 1 set w = b set answer = 0 while a < 4000000 begin set tuple a b = tuple b a + b set w = b if w % 2 == 0 begin set answer = answer +...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. # Answer : 4613732 a, b = 0, 1 w = b answer = 0 while a < 4000000: a, b = b, a+b w = b if w%2 == 0: answer = answer + w
Python
zaydzuhri_stack_edu_python
comment Declaracoes de importacao import info comment Leitura do arquivo fonte do grafo set fileName = input string Arquivo do grafo: set file = open fileName set str = read line file set str = split str string set numVertices = integer str at 0 set numArestas = integer str at 1 comment Preenchimento das estruturas de ...
#Declaracoes de importacao import info #Leitura do arquivo fonte do grafo fileName = input("Arquivo do grafo: "); file = open(fileName) str = file.readline() str = str.split(" ") numVertices = int(str[0]) numArestas = int(str[1]) #Preenchimento das estruturas de dados listaAdj = [[] for x in range(numVe...
Python
zaydzuhri_stack_edu_python
string This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. from django.test import TestCase from test_42cc.southtut.models import Knight class SimpleTest extends TestCase ...
""" This file demonstrates two different styles of tests (one doctest and one unittest). These will both pass when you run "manage.py test". Replace these with more appropriate tests for your application. """ from django.test import TestCase from test_42cc.southtut.models import Knight class SimpleTest(TestCase): ...
Python
zaydzuhri_stack_edu_python
function belief_propagation T pos psi phi use_log=true begin comment Check that tree is actually a tree set tuple is_tree err = call validate_tree T if not is_tree begin raise call ValueError err end set msgs = dictionary comment Forward step set msgs = call _pass_msgs_from_leaves T pos msgs psi phi use_log false at 0 ...
def belief_propagation(T, pos, psi, phi, use_log=True): # Check that tree is actually a tree is_tree, err = validate_tree(T) if not is_tree: raise ValueError(err) msgs = dict() # Forward step msgs = _pass_msgs_from_leaves(T, pos, msgs, psi, phi, use_log, False)[0] # Backward step, no...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding=utf-8 import sys import os import subprocess import re import csv import argparse import json import pprint set pp = call PrettyPrinter indent=4 stream=stderr if __name__ == string __main__ begin set parser = call ArgumentParser description=string CSVの指定した範囲の数値の合計値を出す call ad...
#!/usr/bin/env python # coding=utf-8 import sys import os import subprocess import re import csv import argparse import json import pprint pp = pprint.PrettyPrinter(indent=4, stream=sys.stderr) if __name__ == "__main__": parser = argparse.ArgumentParser(description=u'CSVの指定した範囲の数値の合計値を出す') parser.add_argume...
Python
zaydzuhri_stack_edu_python
comment CART on the Bank Note dataset from random import seed from random import randrange from csv import reader from tree import * set dataset = list list 2.771244718 1.784783929 0 list 1.728571309 1.169761413 0 list 3.678319846 2.81281357 0 list 3.961043357 2.61995032 0 list 2.999208922 2.209014212 0 list 7.49754586...
# CART on the Bank Note dataset from random import seed from random import randrange from csv import reader from tree import * dataset = [[2.771244718,1.784783929,0], [1.728571309,1.169761413,0], [3.678319846,2.81281357,0], [3.961043357,2.61995032,0], [2.999208922,2.209014212,0], [7.497545867,3.162...
Python
zaydzuhri_stack_edu_python
class Solution begin function numDecodings self s begin if s at 0 == string 0 begin return 0 end set dp = list comprehension 0 for _ in range length s + 1 set dp at 0 = 1 set dp at 1 = 1 for i in range 2 length s + 1 begin set first = integer s at slice i - 1 : i : set second = integer s at slice i - 2 : i : if 1 <= fi...
class Solution: def numDecodings(self, s: str) -> int: if s[0] == '0': return 0 dp = [0 for _ in range(len(s) + 1)] dp[0] = 1 dp[1] = 1 for i in range(2, len(s) + 1): first = int(s[i - 1:i]) second = int(s[i - 2:i]) if 1 <=...
Python
zaydzuhri_stack_edu_python
function dump_analysis_parameters_to_file self file_path params_dict required_parameters=none begin if required_parameters is none or call accept_parameters_from_text params_dict required_parameters begin with open file_path string wb as f begin dump params_dict f info string Parameters Saved end set current_parameterf...
def dump_analysis_parameters_to_file(self, file_path, params_dict, required_parameters=None): if required_parameters is None or self.accept_parameters_from_text(params_dict, required_parameters): with open(file_path, "wb") as f: pickle.dump(params_dict, f) logger.inf...
Python
nomic_cornstack_python_v1
function deploy_installer l_dir=local_directory begin set local_directory = l_dir call deploy_app host_=myhost end function
def deploy_installer(l_dir=env.local_directory): env.local_directory = l_dir deploy_app(host_=env.myhost)
Python
nomic_cornstack_python_v1
function panCameraRightTask self pos begin set x = call getX if x >= pos begin set cameraMoving = 0 if enableMouseCamControl == 1 begin call enableMouseCamControl end return done end else begin call setX x + panSpeed set cameraMoving = 1 return cont end end function
def panCameraRightTask(self, pos): x = camera.getX() if x >= pos: self.cameraMoving = 0 if self.enableMouseCamControl == 1: self.game.app.enableMouseCamControl() return Task.done else: camera.setX(x+self.panSpeed) self.c...
Python
nomic_cornstack_python_v1
function evaluate self test=none test_loader=none ckpt_path=none verbose=true begin if test_loader is none and test is none begin warn string Providing test in fit is deprecated. Not providing `test` or `test_loader` in `evaluate` will cause an error in a future release. end if test_loader is none begin if test is not ...
def evaluate( self, test: Optional[pd.DataFrame] = None, test_loader: Optional[torch.utils.data.DataLoader] = None, ckpt_path: Optional[Union[str, Path]] = None, verbose: bool = True, ) -> Union[dict, list]: if test_loader is None and test is None: warning...
Python
nomic_cornstack_python_v1
function __neg__ self begin return call neg end function
def __neg__(self): return self.neg()
Python
nomic_cornstack_python_v1
for _ in range integer input begin set tuple n k = map int split input set data = input for i in data begin set val1 = ordinal i - ordinal string a set val2 = ordinal i - ordinal string A set val3 = ordinal i - ordinal string 0 if val1 >= 0 and val1 <= 26 begin set val1 = val1 + k % 26 print character ordinal string a ...
for _ in range(int(input())): n, k = map(int, input().split()) data = input() for i in data: val1 = ord(i) - ord('a') val2 = ord(i) - ord('A') val3 = ord(i) - ord('0') if(val1 >= 0 and val1 <= 26): val1 = (val1+k)%26 print(chr( ord('a') +...
Python
zaydzuhri_stack_edu_python
function test_ada_boost_stump_classify_partitions_lt self begin set i = 1 set range_min = min set threshold = range_min * 2 set inequal = string lt set returned = call stump_classify data_matrix i threshold inequal set expected = call mat list 1.0 - 1.0 - 1.0 - 1.0 set delta_between_elements = returned - T assert false...
def test_ada_boost_stump_classify_partitions_lt(self): i = 1 range_min = self.data_matrix[:, i].min() threshold = (range_min * 2) inequal = 'lt' returned = ada_boost.stump_classify(self.data_matrix, i, ...
Python
nomic_cornstack_python_v1
import shapes from random import randint function deck_of_cards begin set deck = dict set deck at string 10 = dict string Diamond 1 ; string Heart 1 ; string Spade 1 ; string Club 1 for face in string A23456789KQJ begin set deck at face = dict string Diamond 1 ; string Heart 1 ; string Spade 1 ; string Club 1 end retu...
import shapes from random import randint def deck_of_cards(): deck = {} deck["10"] = {"Diamond": 1, "Heart":1, "Spade":1, "Club":1} for face in "A23456789KQJ": deck[face] = {"Diamond":1, "Heart":1, "Spade":1, "Club":1} return deck class Card(): deck_left = deck_of_cards() ...
Python
zaydzuhri_stack_edu_python
function colors palette begin set all_colors = dict string cmyk list string cian string magenta string yellow string black ; string rgb list string red string green string blue if palette == string all begin set result = all_colors end else begin set result = dict palette get all_colors palette end return call jsonify ...
def colors(palette): all_colors = { 'cmyk': ['cian', 'magenta', 'yellow', 'black'], 'rgb': ['red', 'green', 'blue'] } if palette == 'all': result = all_colors else: result = {palette: all_colors.get(palette)} return jsonify(result)
Python
nomic_cornstack_python_v1
function get_config config_files toMap=true begin comment get config set confparser = config parser set _interpolation = call ExtendedInterpolation set config_files = read confparser config_files set config = none comment global config if config_files begin if toMap begin set config = call config_section_map confparser...
def get_config(config_files, toMap=True): # get config confparser = configparser.ConfigParser() confparser._interpolation = configparser.ExtendedInterpolation() config_files = confparser.read(config_files) config = None # global config if config_files: if toMap: config ...
Python
nomic_cornstack_python_v1
function reset_backup self backup status begin set backup = call _get_resource Backup backup call reset self status end function
def reset_backup(self, backup, status): backup = self._get_resource(_backup.Backup, backup) backup.reset(self, status)
Python
nomic_cornstack_python_v1
from datetime import datetime , timedelta import texttable from bot.config import RSP_INVALID_PARAMETERS from bot.my_log import get_logger from bot.property import ATON_TAX from bot.mongo import Portfolio as pf , mongo as db set LOG = call get_logger string income_portfolio function for_portfolio words begin if length ...
from datetime import datetime, timedelta import texttable from bot.config import RSP_INVALID_PARAMETERS from bot.my_log import get_logger from bot.property import ATON_TAX from bot.mongo import Portfolio as pf, mongo as db LOG = get_logger('income_portfolio') def for_portfolio(words): if len(words) != 2: ...
Python
zaydzuhri_stack_edu_python
async function test_report_fan_preset_mode hass begin call async_set string fan.preset_mode string eco dict string friendly_name string eco enabled fan ; string supported_features 8 ; string preset_mode string eco ; string preset_modes list string eco string smart string whoosh set properties = await call reported_prop...
async def test_report_fan_preset_mode(hass: HomeAssistant) -> None: hass.states.async_set( "fan.preset_mode", "eco", { "friendly_name": "eco enabled fan", "supported_features": 8, "preset_mode": "eco", "preset_modes": ["eco", "smart", "whoosh"]...
Python
nomic_cornstack_python_v1
comment maxsplit import re set st = string programinglanguage set result = split re string m st maxsplit=1 print result
#maxsplit import re st="programinglanguage" result=re.split(r"m",st,maxsplit=1) print(result)
Python
zaydzuhri_stack_edu_python
function complete_remove_entity self coll_id type_id entity_id default_continuation_url request_params begin set continuation_url = get request_params string completion_url none or default_continuation_url set continuation_url_params = call continuation_params request_params set viewinfo = call DisplayInfo self string ...
def complete_remove_entity(self, coll_id, type_id, entity_id, default_continuation_url, request_params): continuation_url = ( request_params.get('completion_url', None) or default_continuation_url ) continuation_url_params = continuation_para...
Python
nomic_cornstack_python_v1
function check_if_exists self begin set dir_name = directory name path absolute path path __file__ set fucntion_dir = join path dir_name string openfaas name if not is directory path fucntion_dir begin raise call ValueError string Function name ` { name } ` provided does not exist. end set yaml_path = join path fucntio...
def check_if_exists(self): dir_name = os.path.dirname(os.path.abspath(__file__)) fucntion_dir = os.path.join(dir_name, 'openfaas', self.name) if not os.path.isdir(fucntion_dir): raise ValueError( f"Function name `{self.name}` provided does not exist...
Python
nomic_cornstack_python_v1
import PySQLConnection function getNewConnection *args **kargs begin string Quickly Create a new PySQLConnection class @param host: Hostname for your database @param username: Username to use to connect to database @param password: Password to use to connect to database @param schema: Schema to use @param port: Port to...
import PySQLConnection def getNewConnection(*args, **kargs): """ Quickly Create a new PySQLConnection class @param host: Hostname for your database @param username: Username to use to connect to database @param password: Password to use to connect to database @param schema: Schema to use @param port: Port to...
Python
zaydzuhri_stack_edu_python
for i in range m n + 1 begin set num = i set b = true if num != 1 begin for j in range 2 num begin if num % j == 0 begin set b = false break end end if b begin append list num end end end if length list == 0 begin print - 1 end else begin set sum = 0 set min = list at 0 for i in list begin if i < min begin set min = i ...
for i in range(m,n+1): num = i b= True if(num!=1): for j in range(2,num): if(num%j==0): b = False break if(b): list.append(num) if(len(list)==0): print(-1) else: sum = 0 min = list[0] for i in list: if (i < min):...
Python
zaydzuhri_stack_edu_python
function supportSubClasses begin return true end function
def supportSubClasses(): return True
Python
nomic_cornstack_python_v1
import time function optimize_performance function begin set start_time = time function set end_time = time set execution_time = end_time - start_time print string Function took execution_time string seconds to execute. comment perform optimizations set optimized_function = function set start_time = time optimized_func...
import time def optimize_performance(function): start_time = time.time() function end_time = time.time() execution_time = end_time - start_time print("Function took", execution_time, "seconds to execute.") # perform optimizations optimized_function = function start_time = time.time() ...
Python
iamtarun_python_18k_alpaca
function validate_future value begin if value < today begin set err = string { value } est déjà passé raise call ValidationError err end end function
def validate_future(value: date): if value < date.today(): err = f"{value} est déjà passé" raise ValidationError(err)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import vtk import argparse set DEFAULT_COLORMAP = list list 0 1 1 1 list 2500 1 1 1 list 109404 1 0 0 set DEFAULT_PLANE_POS = list 0 0 0 class Visualization extends object begin string docstring for Visualization function clipXSliderHandler self obj event begin set clip_x = call GetValue ca...
#!/usr/bin/env python import vtk import argparse DEFAULT_COLORMAP = [[0, 1, 1, 1], [2500, 1, 1, 1], [109404, 1, 0, 0]] DEFAULT_PLANE_POS = [0, 0, 0] class Visualization(object): """docstring for Visualization""" def clipXSliderHandler(self,obj, event): self.clip_x = obj.GetRepresentation().GetValue() self.u...
Python
zaydzuhri_stack_edu_python
function __getattr__ self name begin set attribute = call _get_ name set __dict__ at name = attribute return attribute end function
def __getattr__(self, name): attribute = self._get_(name) self.__dict__[name] = attribute return attribute
Python
nomic_cornstack_python_v1
function maxSlidingWindow self values k begin set n = length values assert k <= n if k == 0 begin return list end comment Populate queue with first K - 1 values. set mq = call MaxQueue for i in call xrange 0 k - 1 begin call offer values at i end comment Get the maximum for the next N - K + 1 windows. In each iteratio...
def maxSlidingWindow(self, values, k): n = len(values) assert k <= n if k == 0: return [] # Populate queue with first K - 1 values. mq = MaxQueue() for i in xrange(0, k - 1): mq.offer(values[i]) # Get the maximum for the next N - K + 1 w...
Python
nomic_cornstack_python_v1
function __init__ self heat_resource context begin call __init__ heat_resource context comment _requires_own_avail_set marks whether or not a new availabilitySet comment should be defined to support this AutoScalingGroup's translation: set _requires_own_avail_set = false comment _required_avail_set_name holds the ident...
def __init__(self, heat_resource, context): super(AWSAutoScalingGroupARMTranslator, self).__init__( heat_resource, context ) # _requires_own_avail_set marks whether or not a new availabilitySet # should be defined to support this AutoScalingGroup's translation: self....
Python
nomic_cornstack_python_v1
from django.shortcuts import render , redirect from models import UrlMapping from forms import UrlForm from utils.path_generator import ShortPath from django.http import Http404 function shortener request begin set form = call UrlForm POST set short_path = string if method == string POST begin if call is_valid begin s...
from django.shortcuts import render, redirect from .models import UrlMapping from .forms import UrlForm from .utils.path_generator import ShortPath from django.http import Http404 def shortener(request): form = UrlForm(request.POST) short_path = "" if request.method == 'POST': if form.is_valid(): ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sat Apr 18 18:15:08 2020 @author: Nick Machak, Vishesh Khanna, Dominic Fascitelli from scipy.interpolate import BSpline import matplotlib.pyplot as plt import numpy as np function createTestCoefficientVector begin return list - 10 7.5 25 42.5 60 40 20 17.5 36.25 55 end fu...
# -*- coding: utf-8 -*- """ Created on Sat Apr 18 18:15:08 2020 @author: Nick Machak, Vishesh Khanna, Dominic Fascitelli """ from scipy.interpolate import BSpline import matplotlib.pyplot as plt import numpy as np def createTestCoefficientVector(): return [-10,7.5,25,42.5,60,40,20,17.5,36.25,55] ...
Python
zaydzuhri_stack_edu_python
function getTextUnits_old filename begin set doc = call Document filename set units = list set unit_tracker = default dictionary int set non_units = list string name: string date: string date string series string transcriber string thesis: string currently: string note string comment string grandparents: string transcr...
def getTextUnits_old(filename): doc = Document(filename) units = list() unit_tracker = defaultdict(int) non_units = ["name:", "date:", "date", "series", "transcriber", "thesis:", "currently:", "note", "comment", "grandparents:", "transcript:", "note:"] ongoing_answer = "" # ite...
Python
nomic_cornstack_python_v1
function test_order self begin set feed_items = list comprehension call feed_item_factory order=i + 1 for i in call xrange 4 set tuple res data = call _get for tuple i feed_item in enumerate feed_items begin call eq_ data at string objects at i at string id id end end function
def test_order(self): feed_items = [self.feed_item_factory(order=i + 1) for i in xrange(4)] res, data = self._get() for i, feed_item in enumerate(feed_items): eq_(data['objects'][i]['id'], feed_item.id)
Python
nomic_cornstack_python_v1
function infer_triple model u i1 i2 begin set pred = call predict_u u i1 i2 if pred > 0 begin return 0 end else begin return 1 end end function
def infer_triple(model, u, i1, i2): pred = model.predict_u(u, i1, i2) if pred > 0: return 0 else: return 1
Python
nomic_cornstack_python_v1
function update self value begin pass end function
def update(self, value): pass
Python
nomic_cornstack_python_v1
function New *args **kargs begin set obj = call __New_orig__ import itkTemplate call New obj *args keyword kargs return obj end function
def New(*args, **kargs): obj = itkBilateralImageFilterIUS2IUS2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
Python
nomic_cornstack_python_v1
from VaultModel import Vault as VaultModel from Database.Database import Database import bcrypt class Vault begin set db = call Database string test function __init__ self name masterpassword begin set name = name set masterpassword = masterpassword call create_db end function comment self.vault=VaultModel(name=name,ma...
from .VaultModel import Vault as VaultModel from ..Database.Database import Database import bcrypt class Vault: db=Database("test") def __init__(self,name,masterpassword): self.name=name self.masterpassword=masterpassword Vault.db.create_db() #self.vault=...
Python
zaydzuhri_stack_edu_python
string VGG16 network architecture Author: Feng Liu, liufeng@stanford.edu from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np function vgg_net X n_classes begin string VGG16 network architecture Args: X: numpy matrix of n...
"""VGG16 network architecture Author: Feng Liu, liufeng@stanford.edu """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np def vgg_net(X, n_classes): """ VGG16 network architecture Args: X: numpy m...
Python
zaydzuhri_stack_edu_python
function valid_moves self p my_team begin return sorted list comprehension n for n in call adj p if n in adjacency if n not in my_team key=lambda x -> tuple x at 1 x at 0 end function
def valid_moves(self, p, my_team): return sorted([ n for n in adj(p) if n in self.adjacency if n not in my_team ], key=lambda x: (x[1], x[0]))
Python
nomic_cornstack_python_v1
function test_process_ace_directory self begin set ACE = deep copy ACE_EVERYONE_RW set result = call process_ace ACE is_directory=true is_root=false assert equal result at string flags INHERIT_ALL_INHERITED end function
def test_process_ace_directory(self): ACE = deepcopy(qacls_config.ACE_EVERYONE_RW) result = qacls_push.process_ace(ACE, is_directory=True, is_root=False) self.assertEqual(result['flags'], qacls_config.INHERIT_ALL_INHERITED)
Python
nomic_cornstack_python_v1
function SetUseReferenceImage self _arg begin return call itkGenerateImageSourceICF2_SetUseReferenceImage self _arg end function
def SetUseReferenceImage(self, _arg: 'bool const') -> "void": return _itkGenerateImageSourcePython.itkGenerateImageSourceICF2_SetUseReferenceImage(self, _arg)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment _*_ coding: utf-8 _*_ comment Author: TeaEra comment Created date: 2014-11-08 comment Two blank lines; function count_and_say n begin if n == 1 begin return string 1 end else begin set str_prev = call count_and_say n - 1 set str_curr = string set curr_char = string set curr_count = 0 ...
#!/usr/bin/python # _*_ coding: utf-8 _*_ # # Author: TeaEra # Created date: 2014-11-08 # Two blank lines; def count_and_say(n): if n == 1: return "1" else: str_prev = count_and_say(n-1) str_curr = "" curr_char = "" curr_count = 0 for each in str_prev: ...
Python
zaydzuhri_stack_edu_python
comment !/bin/env python3 comment -*- coding: utf-8 -*- comment This program is free software: you can redistribute it and/or modify comment it under the terms of the GNU General Public License as published by comment the Free Software Foundation, either version 3 of the License, or comment (at your option) any later v...
#!/bin/env python3 # -*- coding: utf-8 -*- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program...
Python
zaydzuhri_stack_edu_python
from enum import Enum import random class Form extends Enum begin string Class containing every cells shape set STABLE = dict string BLOC list list string a string a list string a string a ; string PIPE list list string d string a string d list string a string d string a list string d string a string d ; string BOAT li...
from enum import Enum import random class Form(Enum): '''Class containing every cells shape''' STABLE = { 'BLOC': [ ['a', 'a'], ['a', 'a'] ], 'PIPE': [ ['d', 'a', 'd'], ['a', 'd', 'a'], ['d', 'a', 'd'] ], 'BOAT...
Python
zaydzuhri_stack_edu_python
from mpi4py import MPI import numpy as np function psum a begin set s = sum a set rcvBuf = array 0.0 string d call Allreduce s rcvBuf op=SUM return rcvBuf end function function pmean a begin set n = array length a string d set N = array 0.0 string d set local_sum = array sum a string d set s = zeros 1 string d call All...
from mpi4py import MPI import numpy as np def psum(a): s = np.sum(a) rcvBuf = np.array(0.0,'d') MPI.COMM_WORLD.Allreduce(s, rcvBuf, op=MPI.SUM) return rcvBuf def pmean(a): n = np.array(len(a),'d') N = np.array(0.0,'d') local_sum = np.array(np.sum(a),'d') s = np.zeros(1,...
Python
zaydzuhri_stack_edu_python
function __settimeout self sock begin comment type: (socket.socket) -> None debug string Setting sock recv timeout to %f sec recv_timeout call settimeout recv_timeout end function
def __settimeout(self, sock): # type: (socket.socket) -> None self.__log.debug("Setting sock recv timeout to %f sec", self.__options.recv_timeout) sock.settimeout(self.__options.recv_timeout)
Python
nomic_cornstack_python_v1
function import_expenses_from_json json_path begin with open json_path string rt as f begin set expenses = load json f end for exp in expenses begin set exp_record = call ExpenseRecord date=call date amount=exp at 1 category=exp at 2 note=exp at 3 account=exp at 4 add session exp_record end commit session end function
def import_expenses_from_json(json_path: str): with open(json_path, "rt") as f: expenses = json.load(f) for exp in expenses: exp_record = far_core.db.ExpenseRecord( date=datetime.datetime.strptime(exp[0], "%Y-%m-%dT%H:%M:%S.%fZ").date(), amount=exp[1], categor...
Python
nomic_cornstack_python_v1
comment Python program creating a comment context manager class ContextManager begin function __init__ self begin print string init method called end function function __enter__ self begin print string enter method called return self end function function __exit__ self exc_type exc_value exc_traceback begin print strin...
# Python program creating a # context manager class ContextManager(): def __init__(self): print('init method called') def __enter__(self): print('enter method called') return self def __exit__(self, exc_type, exc_value, exc_traceback): print('exit method called') # Dr...
Python
zaydzuhri_stack_edu_python