code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function euclidean_dist X y begin comment broadcasted calculations return square root sum X - y ^ 2 1 end function
def euclidean_dist(X, y): return np.sqrt(np.sum((X - y) ** 2, 1)) # broadcasted calculations
Python
nomic_cornstack_python_v1
comment project euler problem 68 comment http://projecteuler.net/problem=68 from itertools import permutations set seq = list 1 2 3 4 5 6 7 8 9 10 set maxvalue = 0 function is_valid_list lst begin comment starting from the group of three with the numerically lowest external node if lst at 0 != min list lst at 0 lst at ...
# project euler problem 68 # http://projecteuler.net/problem=68 from itertools import permutations seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] maxvalue = 0 def is_valid_list(lst): # starting from the group of three with the numerically lowest external node if lst[0] != min([lst[0], lst[3], lst[5], lst[7], lst[9]])...
Python
zaydzuhri_stack_edu_python
function make_bool_hist n_true n_false hist_label begin set hist = histogram 2 - 0.5 1.5 function set_bin numer denom ibin label begin set frac = decimal numer / denom set bounds = call err numer denom use_beta=true set err = max absolute frac - bounds at 0 absolute frac - bounds at 1 call set_ibin ibin frac error=err ...
def make_bool_hist(n_true, n_false, hist_label): hist = Hist(2, -0.5, 1.5) def set_bin(numer, denom, ibin, label): frac = float(numer) / denom bounds = fraction_uncertainty.err(numer, denom, use_beta=True) err = max(abs(frac - bounds[0]), abs(frac - bounds[1])) hist.set_ibin(ibi...
Python
nomic_cornstack_python_v1
comment !/bin/python import sys import math set t = integer strip call raw_input for a0 in call xrange t begin set n = integer strip call raw_input set maximum = - 1 set a = 1 set limit = n / 2 while a < limit begin set b1 = n * n - 2 * a / decimal 2 * n - a set b2 = n * n - 2 * a / 2 * n - a if b1 == b2 begin set c = ...
#!/bin/python import sys import math t = int(raw_input().strip()) for a0 in xrange(t): n = int(raw_input().strip()) maximum=-1 a=1 limit =n/2 while a<limit: b1=(n*(n-2*a))/float(2*(n-a)) b2 = (n*(n-2*a))/(2*(n-a)) if b1 == b2: c = a*a + b1*b1 c= c**...
Python
zaydzuhri_stack_edu_python
import scrapy from datetime import datetime from covid_vaccine.items import CovidVaccineItem class CovidSpider extends Spider begin set name = string CovidVaccine set allow_domain = list string https://www.naver.com/ function start_requests self begin yield call Request string https://search.naver.com/search.naver?wher...
import scrapy from datetime import datetime from covid_vaccine.items import CovidVaccineItem class CovidSpider(scrapy.Spider): name = 'CovidVaccine' allow_domain = ['https://www.naver.com/'] def start_requests(self): yield scrapy.Request("https://search.naver.com/search.naver?where=news&query=코로나%...
Python
zaydzuhri_stack_edu_python
function get_edit_url self begin return reverse string update-schedule kwargs=dict string pk pk end function
def get_edit_url(self): return reverse('update-schedule', kwargs={'pk': self.pk})
Python
nomic_cornstack_python_v1
function BuildValuation ctpy date trade_list output_dir file_format mtm_ccy begin if string call Class != string FTmServer and call Name in tuple string Integration Process string System Processes begin set output_dir = string //nfs/fa/reports/EMEA/prod/FAReports/PCGClientValuations/Valuations/ end set filename = forma...
def BuildValuation(ctpy, date, trade_list, output_dir, file_format, mtm_ccy): if (str(acm.Class()) != "FTmServer" and acm.User().UserGroup().Name() in ('Integration Process', 'System Processes')): output_dir = "//nfs/fa/reports/EMEA/prod/FAReports/PCGClientValuations/Valuations/" ...
Python
nomic_cornstack_python_v1
comment --------------------------------------------------- comment This demo program shows the use of IF statements comment Written by Leon Wee, March 2018. comment Anyone may freely copy or modify this program. comment --------------------------------------------------- comment accept some input from user set weight ...
#--------------------------------------------------- # This demo program shows the use of IF statements # Written by Leon Wee, March 2018. # Anyone may freely copy or modify this program. #--------------------------------------------------- weight = eval(input("Please enter your weight:\n")) # accept some input from u...
Python
zaydzuhri_stack_edu_python
function ReadRawData file_name begin set area_raw_data = dict set area_raw_data_flag = dict with open file_name string r as csv_file begin set lines = read lines csv_file for i in range 1 length lines begin print lines at i i set line = split strip lines at i string , set area_raw_data at line at 0 = line at 1 set ar...
def ReadRawData(file_name): area_raw_data={} area_raw_data_flag={} with open(file_name,'r') as csv_file: lines = csv_file.readlines() for i in range(1,len(lines)): print(lines[i],i) line = lines[i].strip().split(',') area_raw_data[line[0]]=line[1] ...
Python
zaydzuhri_stack_edu_python
function get_voc_emoji vocation begin set emoji = dict string none EMOJI at string :hatching_chick: ; string druid EMOJI at string :snowflake: ; string sorcerer EMOJI at string :flame: ; string paladin EMOJI at string :archery: ; string knight EMOJI at string :shield: ; string elder druid EMOJI at string :snowflake: ; ...
def get_voc_emoji(vocation: str) -> str: emoji = {'none': EMOJI[":hatching_chick:"], 'druid': EMOJI[":snowflake:"], 'sorcerer': EMOJI[":flame:"], 'paladin': EMOJI[":archery:"], 'knight': EMOJI[":shield:"], 'elder druid': EMOJI[":snowflake:"], 'master sorcerer': EMOJI[":flame:"], 'roya...
Python
nomic_cornstack_python_v1
comment https://leetcode.com/problems/reverse-integer/ function reverse x begin set ans = if expression x > 0 then integer string x at slice : : - 1 else 0 - integer string absolute x at slice : : - 1 if ans - 2147483647 > 0 or ans + 2147483648 < 0 begin return 0 end else begin return ans end end function
# https://leetcode.com/problems/reverse-integer/ def reverse(x: int) -> int: ans = int(str(x)[::-1]) if x>0 else 0-int(str(abs(x))[::-1]) if ( ( ans - 2147483647 > 0 ) or ( ans + 2147483648 < 0) ): return 0 else: return ans
Python
zaydzuhri_stack_edu_python
import unittest from erika.erika_image_renderer import * from tests.erika_mock import * from tests.erika_mock_unittest import assert_print_output class RendererTest extends TestCase begin function testRenderLineByLineConnect self begin string simple test that printing line by line works with call ErikaMock 6 6 as my_er...
import unittest from erika.erika_image_renderer import * from tests.erika_mock import * from tests.erika_mock_unittest import assert_print_output class RendererTest(unittest.TestCase): def testRenderLineByLineConnect(self): """simple test that printing line by line works""" with ErikaMock(6, 6) a...
Python
zaydzuhri_stack_edu_python
function _calculate_diffuse_color light_color light_vector material normal begin set diffuse_coefficient = max dot - light_vector normal 0 set diffuse_color = call multiply color light_color / 255 * diffuse_coefficient return diffuse_color end function
def _calculate_diffuse_color(light_color, light_vector, material, normal): diffuse_coefficient = max(np.dot(-light_vector, normal), 0) diffuse_color = np.multiply(material.color, light_color / 255) * diffuse_coefficient return diffuse_color
Python
nomic_cornstack_python_v1
function merge_sortK X k begin set n = length X if n == 0 or n == 1 begin comment conquer return X end else begin comment divide set size = integer n / k set r = n % k set previous = 0 set larger = true set container = list for j in range k begin if j >= r begin set larger = false end append container call merge_sortK...
def merge_sortK(X,k): n = len(X) if n == 0 or n == 1: #conquer return X else: #divide size = int(n/k) r = n%k previous = 0 larger = True container = [] for j in range(k): if j >= r: larger = False ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu May 21 01:58:07 2020 @author: saimi comment Self Organizing maps - Credit card applications Study import pandas as pd import numpy as np import matplotlib.pyplot as plt set dataset = read csv string Credit_Card_Applications.csv set X = values comment loading all the i...
# -*- coding: utf-8 -*- """ Created on Thu May 21 01:58:07 2020 @author: saimi """ # Self Organizing maps - Credit card applications Study import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset = pd.read_csv('Credit_Card_Applications.csv') X = dataset.iloc[:, :-1].values y = dat...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 comment In[1]: import cv2 import numpy as np from save import result from filtering import rgb2grayscale set img = as type call imread string imori.jpg float set tuple H W C = shape set b = copy img at tuple slice : : slice : : 0 set g = copy img at tuple slice : : slice : : 1 set r = ...
# coding: utf-8 # In[1]: import cv2 import numpy as np from save import result from filtering import rgb2grayscale img = cv2.imread("imori.jpg").astype(np.float) H, W, C = img.shape b = img[:, :, 0].copy() g = img[:, :, 1].copy() r= img[:, :, 2].copy() gray_img = rgb2grayscale(r, g, b).reshape(128, -1) # In[2]:...
Python
zaydzuhri_stack_edu_python
function to_rna dna begin string Replaces DNA with RNA sequence return replace replace replace replace replace upper dna string A string U string T string A string C string Q string G string C string Q string G end function
def to_rna(dna): '''Replaces DNA with RNA sequence''' return dna.upper().replace('A', 'U').replace('T', 'A').replace('C', 'Q').replace('G', 'C').replace('Q', 'G')
Python
zaydzuhri_stack_edu_python
function plot self bins=100 begin set fr = call frame call plotOn fr call Binning bins call plotOn fr call plotOn fr call Components string Bs peak call LineStyle kDashed call LineColor kGreen call plotOn fr call Components string Bd peak call LineStyle kDashed call LineColor kRed call plotOn fr call Components string ...
def plot(self, bins = 100): fr = self.mass.frame() self.data.plotOn(fr, RooFit.Binning(bins)) self.model.plotOn(fr) self.model.plotOn(fr,RooFit.Components("Bs peak"), RooFit.LineStyle(kDashed), RooFit.LineColor(kGreen)) self.model.plotOn(fr,RooFit.Components("Bd peak"), RooFit.Li...
Python
nomic_cornstack_python_v1
set s = set literal 2 6 4 7 8 9 set g = set literal 8 1 7 7 4 set h = s ? g print h set h = s ? g print h set h = s - g print h set h = s ? g print h
s = {2, 6, 4, 7, 8, 9} g = {8, 1, 7, 7, 4} h = s|g print (h) h = s&g print (h) h = s-g print (h) h = s^g print (h)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Mon Jan 27 22:43:51 2020 @author: RPS import pandas as pd set dataset = read json string http://restcountries.eu/rest/v2/all print dataset at string name from sklearn.preprocessing import LabelEncoder set labelEnc_X = call LabelEncoder set dataset at string name = fit tra...
# -*- coding: utf-8 -*- """ Created on Mon Jan 27 22:43:51 2020 @author: RPS """ import pandas as pd dataset=pd.read_json("http://restcountries.eu/rest/v2/all") print(dataset['name']) from sklearn.preprocessing import LabelEncoder labelEnc_X= LabelEncoder() dataset['name']=labelEnc_X.fit_transform(d...
Python
zaydzuhri_stack_edu_python
comment !/Users/Home/AppData/Local/Programs/Python/Python36-32/python comment -*- coding: UTF-8 -*- comment enable debugging import cgitb call enable print string Content-Type: text/html import cgi set form = call FieldStorage set w = value set X = value set y = value set alpha = value from functions import * comment I...
#!/Users/Home/AppData/Local/Programs/Python/Python36-32/python # -*- coding: UTF-8 -*- # enable debugging import cgitb cgitb.enable() print ("Content-Type: text/html\n") import cgi form = cgi.FieldStorage() w = form["W"].value X = form["X"].value y = form["Y"].value alpha = form["A"].value from functions import * ...
Python
zaydzuhri_stack_edu_python
function __jobSelectedSetup self begin set __jobSelectedLineEdit = call QLineEdit call setMaximumWidth 300 call setFocusPolicy NoFocus call setFont STANDARD_FONT call addWidget __jobSelectedLineEdit call connect __jobSelectedHandle end function
def __jobSelectedSetup(self): self.__jobSelectedLineEdit = QtWidgets.QLineEdit() self.__jobSelectedLineEdit.setMaximumWidth(300) self.__jobSelectedLineEdit.setFocusPolicy(QtCore.Qt.NoFocus) self.__jobSelectedLineEdit.setFont(cuegui.Constants.STANDARD_FONT) self.__toolbar.addWidge...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2018/11/14 10:06 comment @Author : Bilon comment @File : 线程的使用.py import threading from time import sleep , ctime string # ===================================== # 线程的创建、启动、阻塞 # ===================================== function loop nsec begin strin...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/11/14 10:06 # @Author : Bilon # @File : 线程的使用.py import threading from time import sleep, ctime """ # ===================================== # 线程的创建、启动、阻塞 # ===================================== """ def loop(nsec): """ 先申明一个loop函数,传入一个sleep时...
Python
zaydzuhri_stack_edu_python
function inverse matrix begin set num_rows = length matrix set num_cols = length matrix at 0 if num_rows != num_cols begin raise call ValueError string You should pass a square matrix end set dim = num_rows set denom = call determinant matrix if denom == 0 begin raise call ValueError string The determinant is 0. Can't ...
def inverse(matrix): num_rows = len(matrix) num_cols = len(matrix[0]) if num_rows != num_cols: raise ValueError("You should pass a square matrix") dim = num_rows denom = determinant(matrix) if denom == 0: raise ValueError("The determinant is 0. Can't invert matrix") cofac...
Python
nomic_cornstack_python_v1
function _ikernel z_loc begin return call ndtr z_loc end function
def _ikernel(z_loc): return special.ndtr(z_loc)
Python
nomic_cornstack_python_v1
function _request_access_token self begin string Gets client credentials access token set payload = dict string grant_type string authorization_code ; string code code ; string redirect_uri redirect_uri set headers = call _make_authorization_headers client_id client_secret set response = post OAUTH_TOKEN_URL data=paylo...
def _request_access_token(self): """Gets client credentials access token """ payload = {'grant_type': 'authorization_code', 'code': code, 'redirect_uri': self.redirect_uri} headers = _make_authorization_headers(self.client_id, ...
Python
jtatman_500k
import calendar import datetime set color_list = list string Red string Green string White string Black print color_list at 0 + string , + color_list at 3 set exam_st_date = tuple 11 12 2014 print string The examination will start from exam_st_date at 0 string / exam_st_date at 1 string / exam_st_date at 2 set n = inte...
import calendar import datetime color_list = ['Red', 'Green', 'White', 'Black'] print(color_list[0] + ',' + color_list[3]) exam_st_date = (11, 12, 2014) print("The examination will start from", exam_st_date[0], "/", exam_st_date[1], "/", exam_st_date[2]) n = int(input("enter a value")) n1 = int("%s" % n) n2 = int("%...
Python
zaydzuhri_stack_edu_python
from django.core.paginator import Paginator from django.db.models import Index class PgPartialIndex extends Index begin set suffix = string part set max_name_length = 31 function __init__ self fields=list name=none where=none begin if not where begin raise call ValueError string partial index requires WHERE clause end...
from django.core.paginator import Paginator from django.db.models import Index class PgPartialIndex(Index): suffix = 'part' max_name_length = 31 def __init__(self, fields=[], name=None, where=None): if not where: raise ValueError('partial index requires WHERE clause') self.whe...
Python
zaydzuhri_stack_edu_python
function create_dir path begin if exists path path and list directory path != list begin remove tree path make directories path end if not exists path path begin make directories path end end function
def create_dir(path): if (os.path.exists(path)) and (os.listdir(path) != []): shutil.rmtree(path) os.makedirs(path) if not os.path.exists(path): os.makedirs(path)
Python
nomic_cornstack_python_v1
function filterDfByListElement filteringElt df column begin set indexToDrop = list for i in range length df begin try begin set categories = loc at i at column if filteringElt not in list categories begin append indexToDrop i end end except KeyError begin pass end end set df = drop df indexToDrop set df = reset index ...
def filterDfByListElement(filteringElt, df, column): indexToDrop = [] for i in range(len(df)): try: categories = df.loc[i][column] if filteringElt not in list(categories): indexToDrop.append(i) except KeyError: pass df = df.drop(indexToDro...
Python
nomic_cornstack_python_v1
async function async_unload_entry hass entry begin if data at DOMAIN is not none begin set platforms = GATEWAY_PLATFORMS end else begin set platforms = GATEWAY_PLATFORMS_NO_KEY end return true end function
async def async_unload_entry( hass, entry ): if entry.data[DOMAIN] is not None: platforms = GATEWAY_PLATFORMS else: platforms = GATEWAY_PLATFORMS_NO_KEY return True
Python
nomic_cornstack_python_v1
import time class Machine begin function __init__ self initial begin set current = initial call on_start run comment milliseconds set allocated_time = 10 end function comment Template method: function run self begin while true begin set millis = integer round time * 1000 set next = next if next is not current begin cal...
import time class Machine: def __init__(self, initial): self.current = initial self.current.on_start() self.current.run() self.allocated_time = 10 #milliseconds # Template method: def run(self): while True: millis = int(round(time.time() * 1000)) ...
Python
zaydzuhri_stack_edu_python
function add self element begin set e = call __type element if call is_empty begin set __list = e end else begin set __list = __list + format string {}{} __delimiter e end end function
def add(self, element: object) -> None: e = self.__type(element) if self.is_empty(): self.__list = e else: self.__list += "{}{}".format(self.__delimiter, e)
Python
nomic_cornstack_python_v1
function test_search_email_from_address self begin pass end function
def test_search_email_from_address(self): pass
Python
nomic_cornstack_python_v1
import skfuzzy.control as ctrl import numpy as np import skfuzzy as fuzzy class OmegaControl begin function __init__ self begin comment Initialize sparse universe set universe = linear space - 1.0 1.0 20 comment Create fuzzy variables set theta_error = call Antecedent universe string theta_error set out_omega = call Co...
import skfuzzy.control as ctrl import numpy as np import skfuzzy as fuzzy class OmegaControl(): def __init__(self): # Initialize sparse universe universe = np.linspace(-1.0, 1.0, 20) # Create fuzzy variables theta_error = ctrl.Antecedent(universe, 'theta_error') out_omega =...
Python
zaydzuhri_stack_edu_python
import itertools import numpy as np import matplotlib as mpl import numpy.random as random from PhysicsModel import PhysicsModel from Controller import Controller set rcParams at string image.interpolation = string none comment function to get function get_bin_lower_bounds data num_bins begin string calculates lower bo...
import itertools import numpy as np import matplotlib as mpl import numpy.random as random from PhysicsModel import PhysicsModel from Controller import Controller mpl.rcParams['image.interpolation'] = 'none' #function to get def get_bin_lower_bounds(data,num_bins): '''calculates lower bound values for bins w...
Python
zaydzuhri_stack_edu_python
import sys set cardA = list comprehension i for i in map int split read line stdin set cardB = list comprehension i for i in map int split read line stdin set A = 0 set B = 0 set lastWin = string D for i in range 10 begin if cardA at i > cardB at i begin set A = A + 3 set lastWin = string A end else if cardA at i < car...
import sys cardA = [i for i in map(int, sys.stdin.readline().split())] cardB = [i for i in map(int, sys.stdin.readline().split())] A = 0 B = 0 lastWin = 'D' for i in range(10): if cardA[i] > cardB[i]: A += 3 lastWin = 'A' elif cardA[i] < cardB[i]: B += 3 lastWin =...
Python
zaydzuhri_stack_edu_python
import os import numpy as np function generate num_files begin string Help for generate: Creates new .tex files by copying a 'mother file' file1.tex. Quantity specified by num_files. for i in range num_files begin if i != 1 begin set index = integer round call rand * 10 call system string cp file1.tex file%d.tex % inde...
import os import numpy as np def generate(num_files): """Help for generate: Creates new .tex files by copying a 'mother file' file1.tex. Quantity specified by num_files. """ for i in range(num_files): if i != 1: index = int(np.round(np.random.rand()*10)) os.sys...
Python
zaydzuhri_stack_edu_python
function _get_file_content file_name=string jm.js begin set setting_file_name = file_name set setting_file_path = call _get_js_path setting_file_name __file__ with open setting_file_path as f begin set file_data = read f end return file_data end function
def _get_file_content(file_name: str = "jm.js"): setting_file_name = file_name setting_file_path = _get_js_path(setting_file_name, __file__) with open(setting_file_path) as f: file_data = f.read() return file_data
Python
nomic_cornstack_python_v1
string UNIT TEST ON ANOVA GAGE R&R PYTHON MODULE # Description: This is the unit test for ANOVA Gage R&R module. # Dependencies: Numpy # Author: Shin-Fu (Kelvin) Wu # Date: 2017/06/08 # Reference: * https://www.rdocumentation.org/packages/qualityTools/versions/1.31.1/topics/gageRRDesign import os import sys import unit...
""" UNIT TEST ON ANOVA GAGE R&R PYTHON MODULE # Description: This is the unit test for ANOVA Gage R&R module. # Dependencies: Numpy # Author: Shin-Fu (Kelvin) Wu # Date: 2017/06/08 # Reference: * https://www.rdocumentation.org/packages/qualityTools/versions/1.31.1/topics/gageRRDesign """ import os import sys i...
Python
zaydzuhri_stack_edu_python
from binascii import unhexlify from Crypto.Hash import HMAC , SHA256 function preprocess i begin if length hexadecimal i % 2 == 0 begin return call unhexlify encode hexadecimal i at slice 2 : : end else begin return call unhexlify b'0' + encode hexadecimal i at slice 2 : : end end function function deprocess b begin ...
from binascii import unhexlify from Crypto.Hash import HMAC, SHA256 def preprocess(i): if len(hex(i)) % 2 == 0: return unhexlify(hex(i)[2:].encode()) else: return unhexlify(b'0' + hex(i)[2:].encode()) def deprocess(b): return int.from_bytes(b, 'big') def derive_u(A, B): uH = SHA256.new(preprocess(A) ...
Python
zaydzuhri_stack_edu_python
function iterate self called_method *args **kwargs begin comment Add the iteration key in the keyword aguments set kwargs at string iteration = iterations at 0 comment Check the shape of results set result = call called_method *args keyword kwargs set result_type = type result if result_type in list tuple list begin se...
def iterate( self, called_method, *args, **kwargs ): # Add the iteration key in the keyword aguments kwargs['iteration'] = self.iterations[0] # Check the shape of results result = called_method(*args, **kwargs) result_type = type( result ) if result_type in [tuple, list]...
Python
nomic_cornstack_python_v1
import requests import json import wget set HEADERS = dict string User-agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36 class Scraper extends object begin function __init__ self params begin set params = params set chunks = list set scraper...
import requests import json import wget HEADERS = {'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'} class Scraper(object): def __init__(self, params): self.params = params self.chunks = [] self.scraperSessio...
Python
zaydzuhri_stack_edu_python
function preprocess_corpus train_sents begin comment lexicon_dict['stop_words'] = set(open('stop_words').read().split()) set lexicon_dict at string people_name = set split title read open string data\lexicon\firstname.5k update lexicon_dict at string people_name set split title read open string data\lexicon\lastname.50...
def preprocess_corpus(train_sents): #lexicon_dict['stop_words'] = set(open('stop_words').read().split()) lexicon_dict['people_name']=set(open('data\\lexicon\\firstname.5k').read().title().split()) lexicon_dict['people_name'].update(set(open('data\\lexicon\\lastname.5000').read().title().split())) lexico...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python function main begin call fact call table end function function table begin string Draw tabular student data comment determine if the program should autodetect terminal width set useExternalCode = call askExternalCode comment define the data table set Student = dict string John dict string j...
#!/usr/bin/env python def main(): fact() table() def table(): '''Draw tabular student data''' #determine if the program should autodetect terminal width useExternalCode = askExternalCode() #define the data table Student = { "John" : { "join_date" : "05/03/2011", "Percent" : 80.055}, "Don" : { "j...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- function checkio expr begin set mapbract = dict string } string { ; string ) string ( ; string ] string [ set stack = list for i in expr begin if i in values mapbract begin append stack i end else if i in keys mapbract begin if length stack > 0 and stack at - 1 == mapbract at i begin pop ...
# -*- coding: utf-8 -*- def checkio(expr): mapbract = {'}': '{', ')': '(', ']': '['} stack = [] for i in expr: if i in mapbract.values(): stack.append(i) elif i in mapbract.keys(): if len(stack) > 0 and stack[-1] == mapbract[i]: stack.pop() ...
Python
zaydzuhri_stack_edu_python
function to_bytestring s begin if not is instance s string_types begin return s end if is instance s text_type begin return encode s string utf-8 end else begin return s end end function
def to_bytestring(s): if not isinstance(s, six.string_types): return s if isinstance(s, six.text_type): return s.encode('utf-8') else: return s
Python
nomic_cornstack_python_v1
function check_bom file begin string Determines file codec from from its BOM record. If file starts with BOM record encoded with UTF-8 or UTF-16(BE/LE) then corresponding encoding name is returned, otherwise None is returned. In both cases file current position is set to after-BOM bytes. The file must be open in binary...
def check_bom(file): """Determines file codec from from its BOM record. If file starts with BOM record encoded with UTF-8 or UTF-16(BE/LE) then corresponding encoding name is returned, otherwise None is returned. In both cases file current position is set to after-BOM bytes. The file must be open i...
Python
jtatman_500k
function setup_i18n begin set session_ = call _current_obj if session_ begin set session_existed = call accessed comment If session is available, we try to see if there are languages set set languages = get session_ get config string lang_session_key string tg_lang if not session_existed and get config string beaker.se...
def setup_i18n(): session_ = pylons.session._current_obj() if session_: session_existed = session_.accessed() # If session is available, we try to see if there are languages set languages = session_.get(config.get('lang_session_key', 'tg_lang')) if not session_existed and config....
Python
nomic_cornstack_python_v1
function _default_account_journal_id self begin set lc_journal = env at string account.journal set ir_property = search list tuple string name string = string property_stock_journal tuple string company_id string = id limit=1 if ir_property begin set lc_journal = call get_by_record end return lc_journal end function
def _default_account_journal_id(self): lc_journal = self.env['account.journal'] ir_property = self.env['ir.property'].search([ ('name', '=', 'property_stock_journal'), ('company_id', '=', self.env.user.company_id.id) ], limit=1) if ir_property: lc_jour...
Python
nomic_cornstack_python_v1
function _writeSaic self filelike specfile compress begin string Writes the ``.ssic`` container entry of the specified specfile to the ``mrc_saic`` format. For details see :func:`maspy.auxiliary.writeBinaryItemContainer()` :param filelike: path to a file (str) or a file-like object :param specfile: name of an ms-run fi...
def _writeSaic(self, filelike, specfile, compress): """Writes the ``.ssic`` container entry of the specified specfile to the ``mrc_saic`` format. For details see :func:`maspy.auxiliary.writeBinaryItemContainer()` :param filelike: path to a file (str) or a file-like object :para...
Python
jtatman_500k
comment !/usr/local/bin/python3 comment -*- coding: utf-8 -*- from konlpy.tag import Okt from collections import Counter import pymysql import json comment DB 연결에 대한 정보는 class로 묶어주기 class db_con begin set host = string j5checklist.p.ssafy.io set user = string root set passwd = string 비밀번호 set db = string checklist set ...
#!/usr/local/bin/python3 # -*- coding: utf-8 -*- from konlpy.tag import Okt from collections import Counter import pymysql import json # DB 연결에 대한 정보는 class로 묶어주기 class db_con: host = 'j5checklist.p.ssafy.io' user = 'root' passwd = '비밀번호' db = 'checklist' char = 'utf8' if __name__ == '__main_...
Python
zaydzuhri_stack_edu_python
function convert_equivalent_note note begin if ends with note string b begin return HALF_DOWN_EQ at note at 0 end else if note not in STEP begin return STEP at note at 0 end else begin return note end end function function gen_scale_set note scale begin set scale_set = set for step_type in scale begin if step_type == H...
def convert_equivalent_note(note): if note.endswith('b'): return HALF_DOWN_EQ[note[0]] elif note not in STEP: return STEP[note[0]] else: return note def gen_scale_set(note, scale): scale_set = set() for step_type in scale: if step_type == HALF_STEP: not...
Python
zaydzuhri_stack_edu_python
comment String data type is immutable. So it does not support adding a new string or character. comment But can be done by slicing the string and then concatenating a new string. Example from page 94-94 of the book. set food = string Burger set foodShop = food at slice 0 : 6 : + string King print food print foodShop
# String data type is immutable. So it does not support adding a new string or character. # But can be done by slicing the string and then concatenating a new string. Example from page 94-94 of the book. food='Burger' foodShop=food[0:6]+' King' print(food) print(foodShop)
Python
zaydzuhri_stack_edu_python
function zip_dict *args begin for tuple k v in args begin if has attribute v string __iter__ begin for items in v begin yield tuple k items end end else begin yield tuple k v end end end function
def zip_dict(*args): for k, v in args: if hasattr(v, '__iter__'): for items in v: yield k, items else: yield (k, v)
Python
nomic_cornstack_python_v1
function handlemessage self msg begin from ba._lobby import PlayerReadyMessage from ba._messages import PlayerProfilesChangedMessage , UNHANDLED if is instance msg PlayerReadyMessage begin call _on_player_ready chooser end else if is instance msg PlayerProfilesChangedMessage begin comment If we have a current activity ...
def handlemessage(self, msg: Any) -> Any: from ba._lobby import PlayerReadyMessage from ba._messages import PlayerProfilesChangedMessage, UNHANDLED if isinstance(msg, PlayerReadyMessage): self._on_player_ready(msg.chooser) elif isinstance(msg, PlayerProfilesChangedMessage):...
Python
nomic_cornstack_python_v1
function set_team self team begin set team = team end function
def set_team(self, team): self.team = team
Python
nomic_cornstack_python_v1
from tqdm import tqdm import itertools import numpy as np function generate_dimacs_cnf queens k_choice=2 begin set rows = reshape array range 1 queens ^ 2 + 1 tuple queens queens set clauses = list *rows.tolist() for i in call tqdm range queens desc=string rows begin set clauses = list *clauses *map(list, itertools.com...
from tqdm import tqdm import itertools import numpy as np def generate_dimacs_cnf(queens: int, k_choice=2): rows = np.arange(1, queens ** 2 + 1).reshape((queens, queens)) clauses = [*rows.tolist()] for i in tqdm(range(queens), desc="rows"): clauses = [*clauses, *map(list, itertools.combinations(-r...
Python
zaydzuhri_stack_edu_python
function draw_matches img1 img2 kp1 kp2 matches begin set tuple h1 w1 = shape at slice : 2 : set tuple h2 w2 = shape at slice : 2 : set vis = zeros tuple max h1 h2 w1 + w2 3 dtype=string uint8 set vis at tuple slice 0 : h1 : slice 0 : w1 : = img1 set vis at tuple slice 0 : h2 : slice w1 : : = img2 for tuple id...
def draw_matches(img1, img2, kp1, kp2, matches): (h1, w1) = img1.shape[:2] (h2, w2) = img2.shape[:2] vis = np.zeros((max(h1, h2), w1 + w2, 3), dtype="uint8") vis[0:h1, 0:w1] = img1 vis[0:h2, w1:] = img2 for (idx2, idx1) in matches: # x - columns # y - rows (x1, y1) = kp...
Python
nomic_cornstack_python_v1
function clear_ignored_for_calculations self begin string Clears the ignore for calculations flag. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* comment Implemented from template for osid.resource.ResourceForm.clear_group...
def clear_ignored_for_calculations(self): """Clears the ignore for calculations flag. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from templat...
Python
jtatman_500k
function test_body_len self begin set client = call base_scenario frang_config=string http_body_len 10; requests=list tuple post_request string x * 20 call check_response client status_code=string 403 warning_msg=string frang: HTTP body length exceeded for end function
def test_body_len(self): client = self.base_scenario( frang_config="http_body_len 10;", requests=[(self.post_request, "x" * 20)], ) self.check_response( client, status_code="403", warning_msg="frang: HTTP body length exceeded for" )
Python
nomic_cornstack_python_v1
from selenium import webdriver from time import sleep try begin set driver = call Chrome get driver string https://www.baidu.com comment 窗口最大化 call maximize_window comment 窗口最小化 comment driver.minimize_window() comment 获取窗口的尺寸 print call get_window_size call send_keys string 天津 sleep 2 comment 清除搜索框内容 clear call find_e...
from selenium import webdriver from time import sleep try: driver = webdriver.Chrome() driver.get('https://www.baidu.com') # 窗口最大化 driver.maximize_window() # 窗口最小化 # driver.minimize_window() # 获取窗口的尺寸 print(driver.get_window_size()) driver.find_element_by_id('kw').send_keys('天津') ...
Python
zaydzuhri_stack_edu_python
function lst_multiindex lst index begin return list comprehension lst at i for i in index end function
def lst_multiindex(lst, index: List[int]): return [lst[i] for i in index]
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment Jonathan Pritchard string Class for handling a 21cmfast data run maintain list of run data and location of boxes interfaces with the Run class to store data in Slice objects organisation is a little strange here. In some ways should be associated with Run class directly, but python make...
#!/usr/bin/python #Jonathan Pritchard """ Class for handling a 21cmfast data run maintain list of run data and location of boxes interfaces with the Run class to store data in Slice objects organisation is a little strange here. In some ways should be associated with Run class directly, but python makes that harder t...
Python
zaydzuhri_stack_edu_python
function status self begin return get pulumi self string status end function
def status(self) -> Optional[str]: return pulumi.get(self, "status")
Python
nomic_cornstack_python_v1
function _post_switch_events self switch_name state begin comment the following events all fire the moment a switch goes active if state == 1 begin for event in activation_events begin post event end for tag in tags begin post replace switch_tag_event string % tag end end else comment the following events all fire the ...
def _post_switch_events(self, switch_name, state): # the following events all fire the moment a switch goes active if state == 1: for event in self.machine.switches[switch_name].activation_events: self.machine.events.post(event) for tag in self.machine.switches...
Python
nomic_cornstack_python_v1
function annotate_record seqrecord location=string full feature_type=string misc_feature margin=0 **qualifiers begin if location == string full begin set location = tuple margin length seqrecord - margin end set strand = if expression length location == 3 then location at 2 else 1 append features call SeqFeature call F...
def annotate_record( seqrecord, location="full", feature_type="misc_feature", margin=0, **qualifiers ): if location == "full": location = (margin, len(seqrecord) - margin) strand = location[2] if len(location) == 3 else 1 seqrecord.features.append( SeqFeature( FeatureLocatio...
Python
nomic_cornstack_python_v1
comment This is a comment comment and this will conitue comment for couple of lines and comment more print string Hello! set str1 = string My first string print str1 set str2 = string My Second String in a second line > this is a second line print str2 print string line one print string line two
# This is a comment # and this will conitue # for couple of lines and # more print ("Hello!") str1="My first string" print (str1) str2 ="""My Second String in a second line > this is a second line""" print(str2) print ("line one"); print ("line two");
Python
zaydzuhri_stack_edu_python
function test_user_register_password_invalid_characters self begin set response = post url_register data=dumps register_invalid_password content_type=string application/json assert equal status_code HTTP_400_BAD_REQUEST assert is not none data at string errors at string password end function
def test_user_register_password_invalid_characters(self): response = self.client.post(self.url_register, data=json.dumps( register_invalid_password), content_type='application/json') self.ass...
Python
nomic_cornstack_python_v1
comment N X N크기의 농장이 있다. comment 이 농장에는 이상한 규칙이 있다. comment 규칙은 다음과 같다. comment ① 농장은 크기는 항상 홀수이다. (1 X 1, 3 X 3 … 49 X 49) comment ② 수확은 항상 농장의 크기에 딱 맞는 정사각형 마름모 형태로만 가능하다. comment 1 X 1크기의 농장에서 자라는 농작물을 수확하여 얻을 수 있는 수익은 3이다. comment 3 X 3크기의 농장에서 자라는 농작물을 수확하여 얻을 수 있는 수익은 16 (3 + 2 + 5 + 4 + 2)이다. comment 5 X 5크기의 농장...
# N X N크기의 농장이 있다. # 이 농장에는 이상한 규칙이 있다. # 규칙은 다음과 같다. # ① 농장은 크기는 항상 홀수이다. (1 X 1, 3 X 3 … 49 X 49) # ② 수확은 항상 농장의 크기에 딱 맞는 정사각형 마름모 형태로만 가능하다. # 1 X 1크기의 농장에서 자라는 농작물을 수확하여 얻을 수 있는 수익은 3이다. # 3 X 3크기의 농장에서 자라는 농작물을 수확하여 얻을 수 있는 수익은 16 (3 + 2 + 5 + 4 + 2)이다. # 5 X 5크기의 농장에서 자라는 농작물의 수확하여 얻을 수 있는 수익은 25 (3 + 2 + 1...
Python
zaydzuhri_stack_edu_python
function setPageFill ncolor begin call pagfll ncolor end function
def setPageFill(ncolor): dislin.pagfll(ncolor)
Python
nomic_cornstack_python_v1
function GetName self begin set callResult = call _Call string GetName if callResult is none begin return none end return callResult end function
def GetName(self): callResult = self._Call("GetName", ) if callResult is None: return None return callResult
Python
nomic_cornstack_python_v1
function get_social_distancing self begin return _social_distancing end function
def get_social_distancing(self): return self._social_distancing
Python
nomic_cornstack_python_v1
class full_size begin function __init__ self weight height weightunit heightunit begin set weight = weight set weightunit = weightunit set height = height set heightunit = heightunit end function function convert_to_KG self begin if lower weightunit == string lb begin set weight = weight * 0.454 end end function functi...
class full_size(): def __init__(self, weight, height, weightunit, heightunit): self.weight = weight self.weightunit = weightunit self.height = height self.heightunit = heightunit def convert_to_KG(self): if (self.weightunit.lower() == "lb"): self.wei...
Python
zaydzuhri_stack_edu_python
import asyncio import unittest from unittest import IsolatedAsyncioTestCase from pathlib import Path import filecmp from config import PORT , HOST from test_utils import send_message , receive_message , decode_and_trim , NOT_FOUND , SUCCESS set _INPUT_FILE_NAME = string src/assets/test_in.jpeg set _OUTPUT_FILE_NAME = s...
import asyncio import unittest from unittest import IsolatedAsyncioTestCase from pathlib import Path import filecmp from config import PORT, HOST from test_utils import send_message, receive_message, decode_and_trim,\ NOT_FOUND, SUCCESS _INPUT_FILE_NAME = 'src/assets/test_in.jpeg' _OUTPUT_FILE_NAME = 'src/assets...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 import re if expression length find all string AC input > 0 then print string Yes else print string No
#!/usr/bin/env python3 import re print("Yes") if len(re.findall(r"AC", input())) > 0 else print("No")
Python
zaydzuhri_stack_edu_python
if x < 10 begin print string Smaller end if x > 20 begin print string Bigger end print string Done set x = 5 print string Before 5 if x == 5 begin print string X is 5 print string Is still 5 print string Third 5 end print string Afterwards 5 print string Before 6 if x == 6 begin print string Is 6 print string Is still ...
if x < 10: print('Smaller') if x > 20: print('Bigger') print('Done') x = 5 print('Before 5') if x == 5: print('X is 5') print('Is still 5') print('Third 5') print('Afterwards 5') print('Before 6') if x == 6: print('Is 6') print('Is still 6') print("Third 6") print('Afterwards 6') if ...
Python
zaydzuhri_stack_edu_python
function lv time_intervals with_nan=false begin comment convert to array, cast to float set time_intervals = call asarray time_intervals set np_nan = call __variation_check time_intervals with_nan if np_nan is not none begin return np_nan end set cv_i = diff np time_intervals / time_intervals at slice : - 1 : + time_...
def lv(time_intervals, with_nan=False): # convert to array, cast to float time_intervals = np.asarray(time_intervals) np_nan = __variation_check(time_intervals, with_nan) if np_nan is not None: return np_nan cv_i = np.diff(time_intervals) / (time_intervals[:-1] + time_intervals[1:]) ret...
Python
nomic_cornstack_python_v1
function BB n begin string constructs the BB context if n <= 1 begin return call Context string 0 1 end else begin set BB1 = call BB n - 1 set AA1 = call AA n - 1 set r1 = call C1 n - 1 * 2 ^ n - 2 2 ^ n - 1 - AA1 - BB1 set r2 = BB1 - call C1 2 ^ n - 1 2 ^ n - 1 - BB1 return r1 + r2 end end function
def BB(n): """constructs the BB context""" if (n<=1):return Context('0\n1') else: BB1=BB(n-1) AA1=AA(n-1) r1 = C1((n-1)*2**(n-2),2**(n-1)) - AA1 - BB1 r2 = BB1 - C1(2**(n-1),2**(n-1)) - BB1; return r1 + r2
Python
jtatman_500k
import boot import os from time import sleep comment *************** functions ******************* comment Write file function writeFile value begin set f = open string myfile.txt string w write f string value close f end function comment Read File function readFile begin set f = open string myfile.txt string r set myf...
import boot import os from time import sleep #*************** functions ******************* # Write file def writeFile(value): f=open("myfile.txt","w") f.write(str(value)) f.close() # Read File def readFile(): f=open("myfile.txt","r") myfile = f.read() f.close() return myfile #**********...
Python
zaydzuhri_stack_edu_python
import movies import fresh_tomatoes string The instances below record the title, storyline, poster image, and trailer url for the specified movie. As noted above the class Movie is imported from movies.py set a_Team = call Movie string The A-Team string A group of long time friend go on an adventure string https://uplo...
import movies import fresh_tomatoes """The instances below record the title, storyline, poster image, and trailer url for the specified movie. As noted above the class Movie is imported from movies.py""" a_Team = movies.Movie("The A-Team", "A group of long time friend go on an adventure", ...
Python
zaydzuhri_stack_edu_python
for i in range 1500 2701 begin if i % 7 == 0 and i % 3 == 0 begin print string Число { i } делится и на 3: { i / 3 } , и на 7: { i / 7 } end end string * * * * * * * * * * * * * * * * set n = integer input string Впишите число: for i in range n begin print string * * i end
for i in range(1500, 2701): if i % 7 == 0 and i % 3 == 0: print(f'Число {i} делится и на 3: {i / 3}, и на 7: {i / 7}') ''' * * * * * * * * * * * * * * * * ''' n = int(input('Впишите число: ')) for i in range(n): print('* ' * i)
Python
zaydzuhri_stack_edu_python
function test_resolve_missing_create01 self begin set test_index = join path test_root string 20200101000000000 string index.html with open join path test_tree string meta.js string w encoding=string UTF-8 as fh begin write fh string scrapbook.meta({ "20200101000000000": { "index": "20200101000000000/index.html", "titl...
def test_resolve_missing_create01(self): test_index = os.path.join(self.test_root, '20200101000000000', 'index.html') with open(os.path.join(self.test_tree, 'meta.js'), 'w', encoding='UTF-8') as fh: fh.write("""\ scrapbook.meta({ "20200101000000000": { "index": "20200101000000000/index...
Python
nomic_cornstack_python_v1
function set_bet self bet begin set current_bet = integer bet end function
def set_bet(self, bet): self.current_bet = int(bet)
Python
nomic_cornstack_python_v1
function filled_y_area self x_data y_ub y_lb name=none label=none legend=false **options begin call draw_confidence_interval x_data y_ub y_lb name keyword options end function
def filled_y_area( self, x_data: Sequence[float], y_ub: Sequence[float], y_lb: Sequence[float], name: Optional[str] = None, label: Optional[str] = None, legend: bool = False, **options, ): self._curve_drawer.draw_confidence_interval(x_data, y_...
Python
nomic_cornstack_python_v1
function read_color_image path begin with open path string rb as f begin set img = call fromarray call read_ppm f mode=string RGB set img = call img_to_array img dtype=int set img = call convert_to_tensor img return img end end function
def read_color_image(path): with open(path, 'rb') as f: img = Image.fromarray(read_ppm(f), mode='RGB') img = tf.keras.preprocessing.image.img_to_array(img, dtype=int) img = tf.convert_to_tensor(img) return img
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*-coding:utf-8 -*- string Name:HD string Python threading 模块: Python 线程有2种调用方式: 1. 直接调用: 首先要import threading 然后定义一个线程要运行的函数: def sayhi(num): print("running on number:%s" %(num)) time.sleep(3) #停止3秒 这个需要引入time模块 if __name__ == '__main__' t1 = threading.Thread(target=sayhi,agrs=(1,))...
#!/usr/bin/env python #-*-coding:utf-8 -*- ''' Name:HD ''' r''' Python threading 模块: Python 线程有2种调用方式: 1. 直接调用: 首先要import threading 然后定义一个线程要运行的函数: def sayhi(num): print("running on n...
Python
zaydzuhri_stack_edu_python
import Actions import Items class Location begin function __init__ self name begin set name = name set actions = call getDefaultActions set items = list set monsters = list set neighbours = list set explored = false end function function display self begin return name end function function displayDesc self begin ret...
import Actions import Items class Location(): def __init__(self, name): self.name = name self.actions = Actions.getDefaultActions() self.items = [] self.monsters = [] self.neighbours = [] self.explored = False def display(self): return ...
Python
zaydzuhri_stack_edu_python
string Same that 18_the_mocker_fixture.py but we use return the mock from a fixture to be able to use it into multiple functions. test_re_usable_mocker has the same behaviour than 18_the_mocker_fixture.p test_mocker_with_exception add a side_effect to force the other_code.services.db_service to raise an exception when ...
""" Same that 18_the_mocker_fixture.py but we use return the mock from a fixture to be able to use it into multiple functions. test_re_usable_mocker has the same behaviour than 18_the_mocker_fixture.p test_mocker_with_exception add a side_effect to force the other_code.services.db_service to raise an exception when ...
Python
zaydzuhri_stack_edu_python
function get_sql_session begin set session = call sessionmaker call connect_to_db return call session end function
def get_sql_session(): session = sessionmaker(connect_to_db()) return session()
Python
nomic_cornstack_python_v1
string test for iris dataset import faiss from sklearn.datasets import load_iris import numpy as np from collections import Counter from utils.accuracy import accuracy_iris function run_kmeans x nmb_clusters verbose=false use_gpu=false begin string Runs kmeans on 1 GPU. Args: x: data nmb_clusters (int): number of clust...
""" test for iris dataset """ import faiss from sklearn.datasets import load_iris import numpy as np from collections import Counter from utils.accuracy import accuracy_iris def run_kmeans(x, nmb_clusters, verbose=False, use_gpu=False): """Runs kmeans on 1 GPU. Args: x: data nmb_...
Python
zaydzuhri_stack_edu_python
function __setitem__ self key value begin comment it is checked whether you passed a _pint_qty_type as value or not. Throughout the function, errors will be comment thrown if: _pint_qty_type is passed for a property without unit, _pint_qty_type has the wrong dimensionality, comment the content of the _pint_qty_type is ...
def __setitem__(self, key, value): # it is checked whether you passed a _pint_qty_type as value or not. Throughout the function, errors will be # thrown if: _pint_qty_type is passed for a property without unit, _pint_qty_type has the wrong dimensionality, # the content of the _pint_qty_type is ...
Python
nomic_cornstack_python_v1
function test_format_static_fingerprint self begin set pod = call _mock_pod podspec=dict string root string root_path set path_format = call PathFormat pod assert equal string /root_path/test/asdf call format_static string /{root}/test/{fingerprint} fingerprint=string asdf end function
def test_format_static_fingerprint(self): pod = _mock_pod(podspec={ 'root': 'root_path', }) path_format = grow_path_format.PathFormat(pod) self.assertEqual( '/root_path/test/asdf', path_format.format_static( '/{root}/test/{fingerprint}', fingerprin...
Python
nomic_cornstack_python_v1
function make_pie_chart_putin city_tweet_data_dict begin set cities = list string Paris string Brussels string Berlin string Kiev string Moscow set positive_tweets_total = 0 set positive_paris = city_tweet_data_dict at string Paris_putin at 0 set positive_brussels = city_tweet_data_dict at string Brussels_putin at 0 se...
def make_pie_chart_putin(city_tweet_data_dict): cities = ['Paris', 'Brussels', 'Berlin', 'Kiev', 'Moscow'] positive_tweets_total = 0 positive_paris = city_tweet_data_dict['Paris_putin'][0] positive_brussels = city_tweet_data_dict['Brussels_putin'][0] positive_berlin = city_tweet_data_dict['Ber...
Python
nomic_cornstack_python_v1
import os import re import sys import timeit from typing import Set from levenshtein import levenshtein from utils import clear comment clear the terminal screen. clear set input_word = input string Please enter a word. if exists path string /usr/dict/words begin set path_to_words = string /usr/dict/words end else if e...
import os import re import sys import timeit from typing import Set from levenshtein import levenshtein from utils import clear clear() # clear the terminal screen. input_word = input("\n\nPlease enter a word.\n") if os.path.exists('/usr/dict/words'): path_to_words = '/usr/dict/words' elif os.path.exists('/u...
Python
zaydzuhri_stack_edu_python
function get_untrained_ann bool_var data_desc ml_models train_feature train_result test_feature option begin comment just return case we dont want any ann if not bool_var begin return end comment if we want just an optimal configuration, append to it if option != string optimization begin set list num_layers momentum l...
def get_untrained_ann(bool_var, data_desc, ml_models, train_feature, train_result, test_feature, option): # just return case we dont want any ann if not bool_var: return # if we want just an optimal configuration, append to it if option != 'optimization': [num_layers, momen...
Python
nomic_cornstack_python_v1
function reset_all_file_not_finish begin comment select all file not finish or in progress comment files = PdfFile.query.filter(PdfFile.state == 1).all() comment error = -1 comment for file in files: comment LogPdf(pdf_file_id=file.id, message='Au demarage l\'analyse du fichier le fichier a été mit en erreur', type=-1)...
def reset_all_file_not_finish(): # select all file not finish or in progress # files = PdfFile.query.filter(PdfFile.state == 1).all() # error = -1 # for file in files: # LogPdf(pdf_file_id=file.id, message='Au demarage l\'analyse du fichier le fichier a été mit en erreur', type=-1) # file.stat...
Python
nomic_cornstack_python_v1
function read_tokens file_path dropout=none begin set tokens = split read open file_path if dropout is not none begin set tokens_to_keep = round length tokens * 1 - dropout set tokens = random sample tokens tokens_to_keep end return tokens end function
def read_tokens(file_path, dropout=None): tokens = open(file_path).read().split() if dropout is not None: tokens_to_keep = round(len(tokens) * (1 - dropout)) tokens = random.sample(tokens, tokens_to_keep) return tokens
Python
nomic_cornstack_python_v1
import string , csv set file1 = open string iClicker_EID_Score.csv string rb set file2 = open string BlackBoard_EID_Q5.csv string rb set file3 = open string out.csv string w set reader1 = reader file1 set reader2 = reader file2 set writer = writer file3 delimiter=string , quotechar=string " quoting=QUOTE_ALL comment wr...
import string,csv file1 = open("iClicker_EID_Score.csv","rb") file2 = open("BlackBoard_EID_Q5.csv","rb") file3 = open("out.csv","w") reader1 = csv.reader(file1) reader2 = csv.reader(file2) writer = csv.writer(file3, delimiter = ',', quotechar='"', quoting = csv.QUOTE_ALL) #writer = csv.writer(file3, delimiter = ',', ...
Python
zaydzuhri_stack_edu_python
comment cannot find CLR method function __eq__ self *args begin pass end function
def __eq__(self, *args): #cannot find CLR method pass
Python
nomic_cornstack_python_v1