code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function get_max_speeds self begin return _default_max_speeds end function
def get_max_speeds(self) -> AxisMaxSpeeds: return self._default_max_speeds
Python
nomic_cornstack_python_v1
function to_date str begin try begin return string parse time str string %Y/%m/%d %H:%M end except ValueError begin return string parse time str string %Y/%m/%d end end function
def to_date(str): try: return datetime.datetime.strptime(str,"%Y/%m/%d %H:%M") except ValueError: return datetime.datetime.strptime(str,"%Y/%m/%d")
Python
nomic_cornstack_python_v1
function fib n fibs=dict 1 1 ; 2 1 begin if n not in fibs begin set fibs at n = call fib n - 2 + call fib n - 1 print n end return fibs at n end function function fib2 n fibs=none begin if fibs is none begin set fibs = dict 1 1 ; 2 1 end if n not in fibs begin set fibs at n = call fib2 n - 2 fibs + call fib2 n - 1 fibs...
def fib(n, fibs={1:1, 2:1}): if n not in fibs: fibs[n] = fib(n-2) + fib(n-1) print(n) return fibs[n] def fib2(n, fibs=None): if fibs is None: fibs = {1:1, 2:1} if n not in fibs: fibs[n] = fib2(n-2, fibs) + fib2(n-1, fibs) print(n) return fibs[n] def fib3(n):...
Python
zaydzuhri_stack_edu_python
function moving_wall_bc state dim t qbc num_ghost begin if on_lower_boundary begin set qbc at tuple 0 slice : num_ghost : = qbc at tuple 0 num_ghost set t = t set t1 = problem_data at string t1 set tw1 = problem_data at string tw1 set a1 = problem_data at string a1 set t0 = t - t1 / tw1 if absolute t0 <= 1.0 begin se...
def moving_wall_bc(state,dim,t,qbc,num_ghost): if dim.on_lower_boundary: qbc[0,:num_ghost]=qbc[0,num_ghost] t=state.t; t1=state.problem_data['t1']; tw1=state.problem_data['tw1'] a1=state.problem_data['a1']; t0 = (t-t1)/tw1 if abs(t0)<=1.: vwall = -a1*(1.+np.cos(t0*np.p...
Python
nomic_cornstack_python_v1
function favorite_book title begin print string One of my favorite books is { title title } end function
def favorite_book(title): print(f"One of my favorite books is {title.title()}")
Python
nomic_cornstack_python_v1
function _adc self arg immediate begin set v = if expression not immediate then read memory arg else arg if D and support_BCD begin comment On the NES, the D flag has no effect - set support_BCD to False comment the following horror is based on the behaviour described in [5], Appendix A set result_bin = A + v + C ? 255...
def _adc(self, arg, immediate): v = self.memory.read(arg) if not immediate else arg if self.D and self.support_BCD: # On the NES, the D flag has no effect - set support_BCD to False # the following horror is based on the behaviour described in [5], Appendix A result_...
Python
nomic_cornstack_python_v1
function gone begin set status = string 410 Gone call header string Content-Type string text/html return call output string gone end function
def gone(): ctx.status = '410 Gone' header('Content-Type', 'text/html') return output("gone")
Python
nomic_cornstack_python_v1
from functools import wraps from protocol.messages import CMD_LOGIN , CMD_LOGOUT , CMD_MESSAGE from protocol.messages import Message , NormalMessage , PayloadMessage from protocol.data_utils import DataParser from test.lib.client import TestClient class NotConnectedException extends Exception begin pass end class funct...
from functools import wraps from protocol.messages import CMD_LOGIN, CMD_LOGOUT, CMD_MESSAGE from protocol.messages import Message, NormalMessage, PayloadMessage from protocol.data_utils import DataParser from test.lib.client import TestClient class NotConnectedException(Exception): pass def connected(func): ...
Python
zaydzuhri_stack_edu_python
function test_trending_for_week self begin set this_week_date = call week_for_date today set previous_week_date = this_week_date - time delta weeks=1 set previous_month_date = call get_previous_month this_week_date set previous_year_date = call get_previous_year this_week_date call create metric=metric1 num=5 created=t...
def test_trending_for_week(self): this_week_date = week_for_date(datetime.date.today()) previous_week_date = this_week_date - datetime.timedelta(weeks=1) previous_month_date = get_previous_month(this_week_date) previous_year_date = get_previous_year(this_week_date) MetricW...
Python
nomic_cornstack_python_v1
function canceling self request queryset begin set updated = count queryset if updated == 1 begin set message = call _ string Order was Successfully Canceling. end else begin set message = call _ string Orders were Successfully Canceling. end for order in queryset begin call cancel end call message_user request string ...
def canceling(self, request, queryset): updated = queryset.count() if updated == 1: message = _(" Order was Successfully Canceling.") else: message = _(" Orders were Successfully Canceling.") for order in queryset: order.cancel() self.message_user(request, str(updated) + message...
Python
nomic_cornstack_python_v1
comment from answer_modified import answers import csv set answers = dict string hello string Hi ; string how are you? string I am fine ; string bye string Bye with open string export.csv string w encoding=string utf-8 as f begin set new_dict1 = dict string question string hello ; string answer string Hi set new_dict2 ...
#from answer_modified import answers import csv answers={"hello":"Hi", "how are you?":"I am fine", "bye":"Bye"} with open('export.csv', 'w', encoding='utf-8') as f: new_dict1={'question':'hello', 'answer':'Hi'} new_dict2={'question':'how are you?', 'answer':'I am fine'} new_dict3={'question':'bye', 'an...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment -*- coding: utf-8 -*- string all_tests.py Runs a series of tests contained in text files, using the doctest framework. All the tests are asssumed to be located in the "/tests" sub-directory whereas this file is assumed to be in another sub-directory at the same level. import doctes...
#! /usr/bin/env python # -*- coding: utf-8 -*- ''' all_tests.py Runs a series of tests contained in text files, using the doctest framework. All the tests are asssumed to be located in the "/tests" sub-directory whereas this file is assumed to be in another sub-directory at the same level. ''' import doctest import ...
Python
zaydzuhri_stack_edu_python
function compute_values_for_density brs_pos brs_neg c1 c2 min_window_size delta alpha beta prune_pos prune_neg lag filter=none begin set pos = call increase_window brs_pos c1 c2 min_window_size delta alpha beta prune_pos lag if brs_neg is not none begin set neg = call increase_window brs_neg c1 c2 min_window_size delta...
def compute_values_for_density(brs_pos, brs_neg, c1, c2, min_window_size, delta, alpha, beta, prune_pos, prune_neg, lag, filter=None): pos = increase_window(brs_pos, c1, c2, min_window_size, delta, alpha, beta, prune_pos, lag) if brs_neg is not None: neg = increase_window(...
Python
nomic_cornstack_python_v1
import pymysql from dbconfig import dbconfig class db_Connect begin comment 创建数据库 set flag = 0 function __init__ self begin try begin set db = call Connect host=dbconfig at string host user=dbconfig at string user passwd=dbconfig at string passwd db=dbconfig at string db charset=dbconfig at string charset end except Ba...
import pymysql from dbconfig import dbconfig class db_Connect: #创建数据库 flag = 0 def __init__(self): try: self.db = pymysql.Connect( host=dbconfig['host'], user=dbconfig['user'], passwd=dbconfig['passwd'], db=dbco...
Python
zaydzuhri_stack_edu_python
comment python3.4 import re , requests set r = get requests string http://fashion.qq.com/visual/photo.shtml set p = compile string src="(.+?\.jpg)" set image = find all text set x = 1 for item in image begin try begin set img_get = get requests strip item set name = string x + string .jpg set sz = write open name strin...
#python3.4 import re, requests r = requests.get("http://fashion.qq.com/visual/photo.shtml") p = re.compile('src="(.+?\.jpg)"') image = p.findall(r.text) x=1 for item in image: try: img_get = requests.get(item.strip()) name=str(x)+'.jpg' sz = open(name, 'wb').write(img_get.conten...
Python
zaydzuhri_stack_edu_python
comment filepath=r'C:\Users\loeoe\Desktop\Python Codes\Learn1\1.txt' set f = open filepath mode=string r comment 存储key,存在的字符有哪些 set list1 = list for i in f begin comment print(i) for j in i begin comment print(j) if j not in list1 begin append list1 j end end end print list1
#filepath=r'C:\Users\loeoe\Desktop\Python Codes\Learn1\1.txt' f=open(filepath, mode='r') #存储key,存在的字符有哪些 list1=[] for i in f: #print(i) for j in i: #print(j) if j not in list1: list1.append(j) print(list1)
Python
zaydzuhri_stack_edu_python
function sigmoid z begin comment START CODE HERE ### (≈ 1 line of code) set s = 1 / 1 + exp - z comment END CODE HERE ### return s end function
def sigmoid(z): ### START CODE HERE ### (≈ 1 line of code) s = 1 / (1 + np.exp(-z)) ### END CODE HERE ### return s
Python
nomic_cornstack_python_v1
function timestamp input_line begin set month_nr = dict string Jan string 01 ; string Aug string 08 set lst = split input_line string , set year = lst at 6 set month = month_nr at lst at 3 set day = lst at 4 set time = lst at 5 return year + string - + month + string - + day + string + time end function function user ...
# # # # # def timestamp(input_line): month_nr = {'Jan':'01', 'Aug':'08'} lst = input_line.split(',') year = lst[6] month = month_nr[lst[3]] day = lst[4] time = lst[5] return year + '-' + month + '-' + day + ' ' + time def user(input_line): lst = input_line.split(',') retur...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd from scipy.spatial import ConvexHull from optparse import OptionParser set __version__ = string 1.041 comment Add line mode for Oxygen to line between Nb comment No abs comment --------------- function ReadPoscr2Cartesian filename begin string Filename: VASP, POSCAR TYPE Function:...
import numpy as np import pandas as pd from scipy.spatial import ConvexHull from optparse import OptionParser ############################################################ __version__ = "1.041" # Add line mode for Oxygen to line between Nb # No abs ############################################################ #-------...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- from tools import * from string import * comment su = suffixe, c-a-d un couple (offset,id_str) class Suffix_array begin function __init__ self begin set path_array = list set str_array = list set suffix_array = list set fusion = string set equiv = list end...
#!/usr/bin/env python # -*- coding: utf-8 -*- from tools import * from string import * # su = suffixe, c-a-d un couple (offset,id_str) class Suffix_array: def __init__(self): self.path_array = [] self.str_array = [] self.suffix_array = [] self.fusion = '' self.equiv = [] ...
Python
zaydzuhri_stack_edu_python
comment coding=utf-8 comment script de collecte des compétences des fiches ROME de l'ANPE comment auteur: GABRIEL Alex import httplib from bs4 import BeautifulSoup comment connection sur le site ANPE set conn = call HTTPConnection string candidat.pole-emploi.fr call request string GET string /marche-du-travail/fichemet...
# coding=utf-8 #script de collecte des compétences des fiches ROME de l'ANPE #auteur: GABRIEL Alex import httplib from bs4 import BeautifulSoup conn= httplib.HTTPConnection("candidat.pole-emploi.fr") # connection sur le site ANPE conn.request("GET", "/marche-du-travail/fichemetierrome?codeRome=G1202") r1 = conn.getr...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function compareVersion self version1 version2 begin string :type version1: str :type version2: str :rtype: int set versions1 = list comprehension integer v for v in split version1 string . set versions2 = list comprehension integer v for v in split version2 string . while length ver...
class Solution(object): def compareVersion(self, version1, version2): """ :type version1: str :type version2: str :rtype: int """ versions1 = [int(v) for v in version1.split('.')] versions2 = [int(v) for v in version2.split('.')] while len(ver...
Python
zaydzuhri_stack_edu_python
function test_empty self begin set response = get client reverse string admin:admin_views_podcast_changelist call assertNotContains response string release_date__year= call assertNotContains response string release_date__month= call assertNotContains response string release_date__day= end function
def test_empty(self): response = self.client.get( reverse('admin:admin_views_podcast_changelist')) self.assertNotContains(response, 'release_date__year=') self.assertNotContains(response, 'release_date__month=') self.assertNotContains(response, 'release_date__day=')
Python
nomic_cornstack_python_v1
function train_r_1 self begin comment the rules generated predict for label 0, so we hvae to comment invert the labels to generate rules that predict comment for label 1. set br_1 = call BooleanRuleCG CNF=false set inverted_train_labels = list for label in train_labels begin if label begin append inverted_train_labels...
def train_r_1(self): # the rules generated predict for label 0, so we hvae to # invert the labels to generate rules that predict # for label 1. br_1 = BooleanRuleCG(CNF = False) inverted_train_labels = [] for label in self.train_labels: if label: inverted_train_labels.append(0) else: inverte...
Python
nomic_cornstack_python_v1
import discord from discord.ext import commands from auth import bot_token import datetime set bot = call Bot command_prefix=string / decorator event async function on_typing channel user time begin print string { name } # { discriminator } is typing in # { name } - { name } at { time } end function decorator event asy...
import discord from discord.ext import commands from auth import bot_token import datetime bot = commands.Bot(command_prefix='/') @bot.event async def on_typing(channel, user, time): print(f'{user.name}#{user.discriminator} is typing in #{channel.name} - {channel.guild.name} at {time}') @bot.event async def on_m...
Python
zaydzuhri_stack_edu_python
class Solution begin class _Node begin function __init__ self val begin set val = val set left = none set right = none set left_size = 0 end function end class function countSmaller self nums begin set tree = none set res = list for n in nums at slice : : - 1 begin append res call build_BST tree n end return res at ...
class Solution: class _Node: def __init__(self, val): self.val = val self.left = None self.right = None self.left_size = 0 def countSmaller(self, nums): self.tree = None res = [] for n in nums[::-1]: res.append(self.bui...
Python
zaydzuhri_stack_edu_python
import cv2 as cv import numpy as np set img = call imread string lena.jpg comment grayscale set img = call cvtColor img COLOR_BGR2GRAY comment blur image comment blur is dependent on the (x,y), its odd and greater the value more it blur set img_blur = call GaussianBlur img tuple 51 51 0 comment edges comment larger val...
import cv2 as cv import numpy as np img=cv.imread("lena.jpg") #grayscale img=cv.cvtColor(img,cv.COLOR_BGR2GRAY) #blur image img_blur=cv.GaussianBlur(img,(51,51),0) #blur is dependent on the (x,y), its odd and greater the value more it blur #edges img_edge=cv.Canny(img,110,210) #larger value finds initial edges a...
Python
zaydzuhri_stack_edu_python
function test_message self begin set msg = call MessageType list connection string hello call _send msg assert equal count objects 1 call _check_message msg get objects end function
def test_message(self): msg = self.MessageType([self.connection], 'hello') self._send(msg) self.assertEqual(Message.objects.count(), 1) self._check_message(msg, Message.objects.get())
Python
nomic_cornstack_python_v1
function arn self begin return get pulumi self string arn end function
def arn(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "arn")
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- function AddTwoString s1 s2 carry=0 padding=string left begin if length s1 > length s2 begin set length = length s1 if padding == string left begin set s2 = list string 0 * length s1 - length s2 + list s2 end else begin set s2 = list s2 + list string 0 * length s1 - length s2 end end else b...
# -*- coding:utf-8 -*- def AddTwoString(s1, s2, carry=0, padding='left'): if len(s1) > len(s2): length = len(s1) if padding == 'left': s2 = ['0'] * (len(s1) - len(s2)) + list(s2) else: s2 = list(s2) + ['0'] * (len(s1) - len(s2)) else: length = len(s2) ...
Python
zaydzuhri_stack_edu_python
from functools import reduce function factors n begin return set reduce __add__ generator expression list i n // i for i in range 1 integer power n 0.5 + 1 if n % i == 0 end function set A = list function prime_factors number begin set A = list call factors number sort A comment print(A) set count = 0 set prime = true...
from functools import reduce def factors(n): return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(pow(n, 0.5) + 1)) if n % i == 0))) A = [] def prime_factors(number): A = list(factors(number)) A.sort() # print(A) count = 0 prime = True for i in range(1,len(A)): ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import math import numpy as np import pandas as pd set MyFile = string D:\PYTHON ML\DataFile.csv set df = read csv MyFile print df set x = array df at string x set y = array df at string y set Row = 2 set Col = 3 set xp = linear space - 2 20 100 subplot Row Col 1 scatter plt x y grid x l...
import matplotlib.pyplot as plt import math import numpy as np import pandas as pd MyFile = "D:\PYTHON ML\\DataFile.csv" df = pd.read_csv(MyFile) print (df) x = np.array(df['x']) y = np.array(df['y']) Row =2 Col=3 xp = np.linspace(-2,20,100) plt.subplot(Row,Col,1) plt.scatter(x,y) plt.grid() plt.xlab...
Python
zaydzuhri_stack_edu_python
function remove_identity cls sh_db ident_id begin string Delete an identity from SortingHat. :param sh_db: SortingHat database :param ident_id: identity identifier set success = false try begin call delete_identity sh_db ident_id debug string Identity %s deleted ident_id set success = true end except Exception as e beg...
def remove_identity(cls, sh_db, ident_id): """Delete an identity from SortingHat. :param sh_db: SortingHat database :param ident_id: identity identifier """ success = False try: api.delete_identity(sh_db, ident_id) logger.debug("Identity %s delete...
Python
jtatman_500k
function paint self painter option index begin raise NotImplementedError end function
def paint(self, painter, option, index): raise NotImplementedError
Python
nomic_cornstack_python_v1
function retrieve_build_results self build begin pass end function
def retrieve_build_results(self, build): pass
Python
nomic_cornstack_python_v1
function __init__ self depth_limit=decimal string inf begin set root = none set depth_limit = depth_limit end function
def __init__(self, depth_limit=float("inf")): self.root = None self.depth_limit = depth_limit
Python
nomic_cornstack_python_v1
for i in range 0 n - 1 begin for j in range i + 1 n begin append distance absolute l at i - l at j end end sort distance print distance at k - 1
for i in range(0,n-1): for j in range (i+1,n): distance.append(abs(l[i]-l[j])) distance.sort() print(distance[k-1])
Python
zaydzuhri_stack_edu_python
from matplotlib import pyplot as plt import numpy as np set x = list 1 2 3 4 set y = list 12 2 10 4 set x2 = list 3 4 5 6 7 set y2 = list 8 9 10 11 12 bar x y show
from matplotlib import pyplot as plt import numpy as np x = [1,2,3,4] y = [12,2,10,4] x2 = [ 3,4,5,6,7] y2 = [ 8,9,10,11,12 ] plt.bar (x, y ) plt.show()
Python
zaydzuhri_stack_edu_python
function to_smiles rdm begin set smi = call MolToSmiles rdm return smi end function
def to_smiles(rdm): smi = _rd_chem.MolToSmiles(rdm) return smi
Python
nomic_cornstack_python_v1
function _is_tcp_syn tcp_flags begin if tcp_flags == 2 begin return 1 end else begin return 0 end end function
def _is_tcp_syn(tcp_flags): if tcp_flags == 2: return 1 else: return 0
Python
nomic_cornstack_python_v1
with open string d7_data as f begin set puzzle = split read f string end set assignments = dict set wire_operations = dict for element in puzzle begin set tuple operands results = split element string -> set results = strip results set current_operands = split strip operands string comment Assignment if length curren...
with open("d7_data") as f: puzzle = f.read().split("\n") assignments = {} wire_operations = {} for element in puzzle: operands, results = element.split("->") results = results.strip() current_operands = operands.strip().split(" ") # Assignment if len(current_operands) == 1: try: ...
Python
zaydzuhri_stack_edu_python
string HackTheBox colorize module. from colorama import Fore function colorize color message begin string Colorize output. :param str color : color name. :param str message: message string. :rtype: str set color = lower color if color == string red begin set color = RED end else if color == string lightred begin set co...
'''HackTheBox colorize module.''' from colorama import Fore def colorize(color: str, message: str) -> str: '''Colorize output. :param str color : color name. :param str message: message string. :rtype: str ''' color = color.lower() if color == 'red': color = Fore.RED elif co...
Python
zaydzuhri_stack_edu_python
function get_motif meme motif=string MOTIF begin set pwm_dictionary = dict set pwm_dictionary at string A = list set pwm_dictionary at string C = list set pwm_dictionary at string G = list set pwm_dictionary at string T = list set pwm_dictionary at string N = list set flag = 0 set check = 0 with open meme string ...
def get_motif(meme, motif="MOTIF"): pwm_dictionary = {} pwm_dictionary["A"] = [] pwm_dictionary["C"] = [] pwm_dictionary["G"] = [] pwm_dictionary["T"] = [] pwm_dictionary["N"] = [] flag = 0 check = 0 with open(meme, "r") as f1: for line in f1: if str(motif) in li...
Python
nomic_cornstack_python_v1
function sieve_of_eratosthenes n begin comment Create a list of boolean values representing whether each number is prime set primes = list true * n + 1 set primes at 0 = false set primes at 1 = false comment Iterate through all numbers up to square root of n for i in range 2 integer n ^ 0.5 + 1 begin if primes at i beg...
def sieve_of_eratosthenes(n): # Create a list of boolean values representing whether each number is prime primes = [True] * (n+1) primes[0] = primes[1] = False # Iterate through all numbers up to square root of n for i in range(2, int(n**0.5) + 1): if primes[i]: # Mark all multi...
Python
greatdarklord_python_dataset
function get_data self begin call read_expression call read_tfs call read_metadata call set_gold_standard_and_priors end function
def get_data(self): self.read_expression() self.read_tfs() self.read_metadata() self.set_gold_standard_and_priors()
Python
nomic_cornstack_python_v1
function append self mode metric step value begin string Append (step, value) pair to history for the given mode and metric. if mode not in _values begin set _values at mode = default dictionary list end append _values at mode at metric tuple step value end function
def append(self, mode, metric, step, value): """Append (step, value) pair to history for the given mode and metric.""" if mode not in self._values: self._values[mode] = collections.defaultdict(list) self._values[mode][metric].append((step, value))
Python
jtatman_500k
function chaos_color_at2 self t begin set i = t / breath_period * 512 % 512 if i > 256 begin set i = 512 - i end return tuple i 0 256 - i end function
def chaos_color_at2(self,t): i=(t/self.breath_period*512)%512 if i > 256: i=512-i return (i,0,256-i)
Python
nomic_cornstack_python_v1
function fft_plot self xlim=none ylim=none label=none begin set X = fft sig / length sig set freqs = call frequency_range plot freqs at slice 0 : integer length sig / 2 : absolute X at slice 0 : integer length sig / 2 : label=label x label string Frequency in Hertz [Hz] y label string Frequency Domain (Spectrum) Magn...
def fft_plot(self,xlim=None,ylim=None,label=None): X = np.fft.fft(self.sig)/len(self.sig) freqs = self.frequency_range() plt.plot(freqs[0:int(len(self.sig)/2)], np.abs(X)[0:int(len(self.sig)/2)],label=label) plt.xlabel('Frequency in Hertz [Hz]') plt.ylabel('Frequency Domain (Spec...
Python
nomic_cornstack_python_v1
comment my_list.index() comment my_list.reverse() set dust = 100 comment str set lang = string python comment list set samsung = list string elec string sds string s1 print capitalize lang print replace lang string on string off print lang sort samsung print samsung index samsung string sds comment 원본이 바뀐다 append samsu...
#my_list.index() #my_list.reverse() dust = 100 lang= 'python' #str samsung = ["elec", "sds", "s1"] #list print(lang.capitalize()) print(lang.replace('on', 'off')) print(lang) samsung.sort() print(samsung) samsung.index('sds') samsung.append('bio') #원본이 바뀐다 print(samsung)
Python
zaydzuhri_stack_edu_python
comment Course 7 comment Exploratory Data Analysis in Python comment Chapter 1 comment Read, clean, and validate comment Exploring the NSFG data comment Calculate the number of rows and columns in the DataFrame nsfg. shape comment Display the names of the columns in nsfg. columns comment Select the column 'birthwgt_oz1...
# Course 7 # Exploratory Data Analysis in Python # Chapter 1 # Read, clean, and validate #Exploring the NSFG data #Calculate the number of rows and columns in the DataFrame nsfg. nsfg.shape #Display the names of the columns in nsfg. nsfg.columns #Select the column 'birthwgt_oz1' and assign it to a ne...
Python
zaydzuhri_stack_edu_python
function calculate_expression begin set result = 2 ^ 2 + 4 - 3 * 6 / 7 - 3 * 8 / 2 return result end function print call calculate_expression
def calculate_expression(): result = (2 ** 2 + 4 - 3 * 6) / (7 - 3) * (8 / 2) return result print(calculate_expression())
Python
jtatman_500k
function set_size self begin try begin if not file_size begin set file_size = get size path file_name end end except OSError begin set file_size = 0 end end function
def set_size( self ): try: if not self.file_size: self.file_size = os.path.getsize( self.file_name ) except OSError: self.file_size = 0
Python
nomic_cornstack_python_v1
import json set filename = string lessons/files_and_exceptions/username.json with open filename as f_obj begin set username = load json f_obj end print string С возвращением, + username
import json filename='lessons/files_and_exceptions/username.json' with open(filename)as f_obj: username=json.load(f_obj) print('С возвращением, ' + username)
Python
zaydzuhri_stack_edu_python
function isThisInputAlignmentComplete self individual_alignment=none data_dir=none returnFalseIfInexitentFile=true **keywords begin set stockAnswer = call isThisAlignmentComplete individual_alignment=individual_alignment data_dir=data_dir returnFalseIfInexitentFile=returnFalseIfInexitentFile keyword keywords if stockAn...
def isThisInputAlignmentComplete(self, individual_alignment=None, data_dir=None, returnFalseIfInexitentFile=True, \ **keywords): stockAnswer = self.db.isThisAlignmentComplete(individual_alignment=individual_alignment, data_dir=data_dir,\ returnFalseIfInexitentFile=returnFalseIfInexitentFile, **k...
Python
nomic_cornstack_python_v1
function check_thresholds_and_peaks v t spike_indexes peak_indexes upstroke_indexes end=none max_interval=0.005 thresh_frac=0.05 filter=10.0 dvdt=none begin if not end begin set end = t at - 1 end set overlaps = call flatnonzero spike_indexes at slice 1 : : <= peak_indexes at slice : - 1 : if size begin set spike_ma...
def check_thresholds_and_peaks(v, t, spike_indexes, peak_indexes, upstroke_indexes, end=None, max_interval=0.005, thresh_frac=0.05, filter=10., dvdt=None): if not end: end = t[-1] overlaps = np.flatnonzero(spike_indexes[1:] <= peak_indexes[:-1]) if overlaps.size: ...
Python
nomic_cornstack_python_v1
string Shared utility functions from typing import Any , Generator , Iterable , Sequence , Union from dataclasses import is_dataclass , asdict from common.types import Serializable from enum import Enum import numpy as np import json import cv2 function add_to_key d key value begin if key in d begin set d at key = d at...
""" Shared utility functions """ from typing import Any, Generator, Iterable, Sequence, Union from dataclasses import is_dataclass, asdict from common.types import Serializable from enum import Enum import numpy as np import json import cv2 def add_to_key(d: dict, key: Any, value: Any): if key in d: d[key] += v...
Python
zaydzuhri_stack_edu_python
string Adjusts weights of analysts according to past performance, with parameters for learning import pyalgotrade import numpy as np from pyalgotrade.barfeed import yahoofeed from pyalgotrade.tools import yahoofinance from time import gmtime , strftime from datetime import timedelta from players import Analyst , Organi...
""" Adjusts weights of analysts according to past performance, with parameters for learning """ import pyalgotrade import numpy as np from pyalgotrade.barfeed import yahoofeed from pyalgotrade.tools import yahoofinance from time import gmtime, strftime from datetime import timedelta from players import Analyst, Organi...
Python
zaydzuhri_stack_edu_python
function changed_event self name begin return call value_changed_signal end function
def changed_event(self, name): return self.params[name].value_handler.value_changed_signal()
Python
nomic_cornstack_python_v1
function are_concurrent self *lines begin raise call NotImplementedError end function
def are_concurrent(self, *lines): raise NotImplementedError()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import nltk import random import pickle import Timer import time import codecs import sys import threading import FeatureGenerator from AnnotationUnit import * comment Experiments # function instance_filter aus classification_method multiple_cancer_terms concept begin string filters and alt...
#!/usr/bin/env python import nltk import random import pickle import Timer import time import codecs import sys import threading import FeatureGenerator from AnnotationUnit import * ############### # Experiments # ############### def instance_filter(aus, classification_method, multiple_cancer_terms, concept): """ ...
Python
zaydzuhri_stack_edu_python
comment pylint: disable=invalid-name function CreateStubTest phases=none begin set test_metadata = call TestMetadata string foo return call phase_data test_metadata phases or list end function
def CreateStubTest(phases=None): # pylint: disable=invalid-name test_metadata = phase_data.TestMetadata('foo') return phase_data.phase_data(test_metadata, phases or [])
Python
nomic_cornstack_python_v1
comment Debo presentar el nombre completo de los pospulantes de una vecindad comment ademas debo mostrar tantas "x" como votos obtenidos por cada postulante set nombre = input string Nombre del postulante: set apellido = input string Apellido del postulante: set votos = integer input string Cantidad de votos: set canti...
#Debo presentar el nombre completo de los pospulantes de una vecindad #ademas debo mostrar tantas "x" como votos obtenidos por cada postulante nombre = input("Nombre del postulante: ") apellido = input("Apellido del postulante: ") votos = int(input("Cantidad de votos: ")) cantidad_x = ('x' * votos) print('(',votos,')'...
Python
zaydzuhri_stack_edu_python
function _cacheAnnouncement begin set confs = call fetch projection=list name if confs begin comment If there are almost sold out conferences, comment format announcement and set it in memcache set announcement = ANNOUNCEMENT_TPL % join string , generator expression name for conf in confs set MEMCACHE_ANNOUNCEMENTS_KEY...
def _cacheAnnouncement(): confs = Conference.query(ndb.AND( Conference.seatsAvailable <= 5, Conference.seatsAvailable > 0) ).fetch(projection=[Conference.name]) if confs: # If there are almost sold out conferences, # format announcement and set it...
Python
nomic_cornstack_python_v1
import pygame import pygame.camera from pygame.locals import * from pygame import Surface from sys import exit from time import sleep import time set SIZE = tuple 640 480 function tryInitCamera begin call init print string Initializing camera end=string flush=true for i in range 0 10 begin call init print string . end...
import pygame import pygame.camera from pygame.locals import * from pygame import Surface from sys import exit from time import sleep import time SIZE = (640, 480) def tryInitCamera(): pygame.init() print("Initializing camera", end='', flush=True) for i in range(0, 10): pygame.camera.init() ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 set stack = list function push_it begin set item = input string item to push: append stack item end function function pop_it begin if stack begin print string Popped%s % pop stack end else begin print string Empty stack end end function function view_it begin print s...
#!/usr/bin/env python3 stack=[] def push_it(): item=input('item to push:') stack.append(item) def pop_it(): if stack: print('\033[31;1mPopped%s\033[0m' % stack.pop()) else: print('\033[31;1mEmpty stack\033[0m') def view_it(): print('\033[32;1m%s\033[0m' % stack) def show_menu()...
Python
zaydzuhri_stack_edu_python
function __init__ self begin call init set _screen = none set _passed = false set _max_distance = 100 set _min_distance = - 20 set _current = tuple 0 0 set _cube = list for _ in range 30 begin append _cube call Cube _max_distance _min_distance end set tuple _camera_x _camera_y _camera_z = tuple none none none end func...
def __init__(self): pygame.init() self._screen = None self._passed = False self._max_distance = 100 self._min_distance = -20 self._current = (0, 0) self._cube = [] for _ in range(30): self._cube.append(Cube(self._max_distance, self._min_dist...
Python
nomic_cornstack_python_v1
function __init__ self metadata state_dispatcher begin call __init__ state_dispatcher set _activated = false set metadata = metadata end function
def __init__(self, metadata: Metadata, state_dispatcher: ProtocolStateDispatcher): super().__init__(state_dispatcher) self._activated = False self.metadata = metadata
Python
nomic_cornstack_python_v1
import numpy as np from visdom import Visdom class Graph begin function __init__ self env begin set last1 = 0.0 set last2 = 0.0 set last3 = 0.0 set last4 = 0.0 set last5 = 0.0 set last6 = 0.0 set x = 0.0 set legend = list string source_generator string target_generator string source_disc string target_disc string disc ...
import numpy as np from visdom import Visdom class Graph: def __init__(self, env): self.last1 = 0. self.last2 = 0. self.last3 = 0. self.last4 = 0. self.last5 = 0. self.last6 = 0. self.x = 0. self.legend = ['source_generator', 'target_generator', 'sou...
Python
zaydzuhri_stack_edu_python
function setTag self filename begin if not string .mp3 or string .MP3 in filename begin return end set audio = load eyed3 filename if not audio begin error string failed to add tag for %s, invalid load filename return end print string Processing filename exit 1 comment ==================================================...
def setTag(self, filename): if not ".mp3" or ".MP3" in filename: return self.audio = eyed3.load(filename) if not self.audio: logging.error('failed to add tag for %s, invalid load', filename) return print ("Processing ", filename) exit(1) ...
Python
nomic_cornstack_python_v1
function rotate_points self pts theta begin assert shape at 1 == 3 comment get the rotation axis set rot = call vector at slice : 3 : comment normalize the rotation axis set rot = rot / square root sum call square rot comment get the axes set tuple a b c = rot comment compute the quaternion from the rotation axis and...
def rotate_points(self, pts, theta): assert(pts.shape[1] == 3) # get the rotation axis rot = (self.omega.vector())[:3] # normalize the rotation axis rot = rot/np.sqrt(np.sum(np.square(rot))) # get the axes a, b, c = rot # compute the quater...
Python
nomic_cornstack_python_v1
function discard self begin pop stack end function
def discard(self,): self.stack.pop()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string follow_the_key_word.py DESCRIPTION set __author__ = string k-machida set __version__ = string 1.0.0 set __date__ = string 2018/06/19 import argparse import requests import cchardet import logging import logging.config from os import path from bs4 import BeautifulSoup from urllib.par...
# -*- coding: utf-8 -*- """ follow_the_key_word.py DESCRIPTION """ __author__ = 'k-machida' __version__ = '1.0.0' __date__ = '2018/06/19' import argparse import requests import cchardet import logging import logging.config from os import path from bs4 import BeautifulSoup from urllib.parse import urljoin log_fil...
Python
zaydzuhri_stack_edu_python
from apps.article.models import Article from django.utils.safestring import mark_safe , mark_for_escaping from rede_gsti.celery import app import bleach import re from html5lib.tokenizer import HTMLTokenizer decorator task function clean_article_links article_id begin set portal_rule = compile string http(.+)(portalgst...
from apps.article.models import Article from django.utils.safestring import mark_safe, mark_for_escaping from rede_gsti.celery import app import bleach import re from html5lib.tokenizer import HTMLTokenizer @app.task def clean_article_links(article_id): portal_rule = re.compile(r'http(.+)(portalgsti\.com\.br)') ...
Python
zaydzuhri_stack_edu_python
function lti_get lti=lti begin comment print(request.headers.get('Authorization')) comment print(request.cookies.get('session')) comment print(request.cookies.get('test')) comment print(session) set user = first filter by query session User lti_user_id=name print user if get cookies string session_is_set == string true...
def lti_get(lti=lti): #print(request.headers.get('Authorization')) #print(request.cookies.get('session')) #print(request.cookies.get('test')) #print(session) user = db.session.query(User).filter_by(lti_user_id=lti.name).first() print(user) if request.cookies.get('session_is_set') == 'true': ...
Python
nomic_cornstack_python_v1
function round_filters filters width_coefficient depth_divisor begin set filters = filters * width_coefficient set new_filters = integer filters + depth_divisor / 2 // depth_divisor * depth_divisor set new_filters = max depth_divisor new_filters comment Make sure that round down does not go down by more than 10%. if ne...
def round_filters(filters, width_coefficient, depth_divisor): filters *= width_coefficient new_filters = int(filters + depth_divisor / 2) // depth_divisor * depth_divisor new_filters = max(depth_divisor, new_filters) # Make sure that round down does not go down by more than 10%. if new_filters < 0.9...
Python
nomic_cornstack_python_v1
function _broadcast_scores self participants game_id round_num begin set pscores = dict for p in participants begin set pscores at plus_id = dict string score score ; string game_score game_score ; string hangout_score hangout_score end set message = dumps dict string scores_info dict string participant_scores pscores...
def _broadcast_scores(self, participants, game_id, round_num): pscores = {} for p in participants: pscores[p.plus_id] = ( {'score': p.score, 'game_score': p.game_score, 'hangout_score': p.hangout_score}) message = simplejson.dumps( {'scores_info': {'participant_sc...
Python
nomic_cornstack_python_v1
function GetApiConfigs self cgi_env dev_appserver begin set request = call ApiRequest cgi_env dev_appserver set path = string BackendService.getApiConfigs set body = string {} return call BuildCGIRequest cgi_env request dev_appserver end function
def GetApiConfigs(self, cgi_env, dev_appserver): request = ApiRequest(cgi_env, dev_appserver) request.path = 'BackendService.getApiConfigs' request.body = '{}' return BuildCGIRequest(cgi_env, request, dev_appserver)
Python
nomic_cornstack_python_v1
comment import tkinter comment root = tkinter.Tk() comment root.geometry("400x240") comment var = tkinter.IntVar() comment var.set(0) comment rdo1 = tkinter.Radiobutton(root,value=0 comment ,variable=var,text='ストアカ' ).pack() comment rdo2=tkinter.Radiobutton(root,value=1 comment ,variable=var,text='Python' ).pack() comm...
# import tkinter # root = tkinter.Tk() # root.geometry("400x240") # var = tkinter.IntVar() # var.set(0) # rdo1 = tkinter.Radiobutton(root,value=0 # ,variable=var,text='ストアカ' ).pack() # rdo2=tkinter.Radiobutton(root,value=1 # ,variable=var,text='Python' ).pack() # rdo3 = tkinter.Radiobutton(root,value=2 # ,variable...
Python
zaydzuhri_stack_edu_python
function updateWebsiteForm websiteData begin comment Unpack current resource data set tuple siteID siteTitle url description topic pictureURL logoURL = websiteData at 0 comment Show form partially filled out with some fields left unchangeable print string <!-- UPDATE WEBSITE FORM --> <h2>Update Website Information</h2>...
def updateWebsiteForm(websiteData): ## Unpack current resource data (siteID, siteTitle, url, description, topic, pictureURL, logoURL) = websiteData[0] ## Show form partially filled out with some fields left unchangeable print(""" <!-- UPDATE WEBSITE FORM --> <h2>Update Website Information</h2>...
Python
nomic_cornstack_python_v1
from manimlib.imports import * class ThreeDSpace extends ThreeDScene begin function construct self begin set axes = call ThreeDAxes call set_stroke width=1 color=GOLD add self axes call set_camera_orientation phi=70 * DEGREES theta=110 * DEGREES set line1 = call Line color=YELLOW opacity=350 start=ORIGIN end=list 0.5 2...
from manimlib.imports import * class ThreeDSpace(ThreeDScene): def construct(self): axes = ThreeDAxes() axes.set_stroke(width=1,color=GOLD) self.add(axes) self.set_camera_orientation(phi = 70*DEGREES,theta =110*DEGREES) line1 = Line(color = YELLOW,opacity=350,start = ORIGIN,end = [0.5,2,2]) s...
Python
zaydzuhri_stack_edu_python
function db_connect begin return call create_engine call URL keyword DATABASE end function
def db_connect(): return create_engine(URL(**DATABASE))
Python
nomic_cornstack_python_v1
set num = 1 while num <= 100 begin set is_prime = true if num > 1 begin for i in range 2 integer num / 2 + 1 begin if num % i == 0 begin set is_prime = false break end end end if is_prime begin print num end set num = num + 1 end
num = 1 while num <= 100: is_prime = True if num > 1: for i in range(2, int(num/2) + 1): if num % i == 0: is_prime = False break if is_prime: print(num) num += 1
Python
jtatman_500k
function match_sequences sentence_a_fw sentence_a_bw sentence_b_fw sentence_b_bw sentence_a_mask sentence_b_mask multi_perspective_dims with_full_match with_pool_match with_attentive_match with_max_attentive_match begin set matched_representations = list set sentence_b_len = call reduce_sum sentence_b_mask 1 set sente...
def match_sequences(sentence_a_fw, sentence_a_bw, sentence_b_fw, sentence_b_bw, sentence_a_mask, sentence_b_mask, multi_perspective_dims, with_full_match, with_pool_match, with_attentive_match,with_max_attentive_match): matched_representations = [] sentence_b_len = tf.red...
Python
nomic_cornstack_python_v1
set a = list 1 3 2 5 4 set b = sort a print a b
a=[1,3,2,5,4] b= a.sort() print(a,b)
Python
zaydzuhri_stack_edu_python
string Реализуйте рекурсивную функцию нарезания прямоугольника с заданными пользователем сторонами a и b на квадраты с наибольшей возможной на каждом этапе стороной. Выведите длины ребер получаемых квадратов и кол-во полученных квадратов function square_rec aa bb nn=0 begin if aa == bb begin print string Сторона квадра...
""" Реализуйте рекурсивную функцию нарезания прямоугольника с заданными пользователем сторонами a и b на квадраты с наибольшей возможной на каждом этапе стороной. Выведите длины ребер получаемых квадратов и кол-во полученных квадратов """ def square_rec(aa, bb, nn=0): if aa == bb: print("Сторон...
Python
zaydzuhri_stack_edu_python
function get_queryset self begin return call active end function
def get_queryset(self): return self.get_model().objects.active()
Python
nomic_cornstack_python_v1
function flatten self name codes new_name=none text_key=none begin if not new_name begin if string . in name begin set new_name = format string {}_rec split name string . at 0 end else begin set new_name = format string {}_rec name end end if not text_key begin set text_key = text_key end set label = _meta at string ma...
def flatten(self, name, codes, new_name=None, text_key=None): if not new_name: if '.' in name: new_name = '{}_rec'.format(name.split('.')[0]) else: new_name = '{}_rec'.format(name) if not text_key: text_key = self.text_key label = self._met...
Python
nomic_cornstack_python_v1
function test_traceroute_centos_7_7 self begin assert equal parse traceroute centos_7_7_traceroute quiet=true centos_7_7_traceroute_json end function
def test_traceroute_centos_7_7(self): self.assertEqual(jc.parsers.traceroute.parse(self.centos_7_7_traceroute, quiet=True), self.centos_7_7_traceroute_json)
Python
nomic_cornstack_python_v1
print string Enter list of elements set list = input set newList = split list string sort newList set midIndex = integer length newList / 2
print('Enter list of elements') list=input() newList=list.split(' ') newList.sort() midIndex=int(len(newList)/2)
Python
zaydzuhri_stack_edu_python
comment Supress unnecessary warnings so that presentation looks clean import warnings filter warnings string ignore comment Read raw data from the file comment provides data structures to quickly analyze data import pandas comment Since this code runs on Kaggle server, data can be accessed directly in the 'input' folde...
# Supress unnecessary warnings so that presentation looks clean import warnings warnings.filterwarnings('ignore') # Read raw data from the file import pandas #provides data structures to quickly analyze data #Since this code runs on Kaggle server, data can be accessed directly in the 'input' folder #Read the train da...
Python
zaydzuhri_stack_edu_python
import numpy as np class operationSurLesFacettesEtLesNormales begin function __init__ self listeNormales listeFacettes masseBateau begin set __listeN = listeNormales set __listeF = listeFacettes set __masseBateau = masseBateau set __forcePoids = __masseBateau * 9.8 set __forceArchimede = 0 set __coodDeG = list set __f...
import numpy as np class operationSurLesFacettesEtLesNormales(): def __init__(self, listeNormales, listeFacettes, masseBateau): self.__listeN = listeNormales self.__listeF = listeFacettes self.__masseBateau = masseBateau self.__forcePoids = self.__masseBateau * 9.8 self.__f...
Python
zaydzuhri_stack_edu_python
string implementation of autostep according to this paper: http://incompleteideas.net/609%20dropbox/other%20readings%20and%20resources/Tuning-free%20step-size%20adapt.pdf import numpy as np from src.util import Config , check_attribute class AutoStep begin function __init__ self config begin string Parameters in config...
""" implementation of autostep according to this paper: http://incompleteideas.net/609%20dropbox/other%20readings%20and%20resources/Tuning-free%20step-size%20adapt.pdf """ import numpy as np from src.util import Config, check_attribute class AutoStep: def __init__(self, config: Config): """ Param...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from ODESolver import * class Region extends object begin string Class that defines a region function __init__ self name S_0 E2_0 begin string Takes name of region together with initial susceptible population and infected set name = name set S_0 = S_0 set E1_0 = 0 set ...
import numpy as np import matplotlib.pyplot as plt from ODESolver import * class Region(object): """Class that defines a region""" def __init__(self, name, S_0, E2_0): """Takes name of region together with initial susceptible population and infected""" self.name = name self.S_0 = S_0; s...
Python
zaydzuhri_stack_edu_python
function remove_label_from_nodes label value manager=none begin set client = call get_docker_client manager set nodes = list set matching_nodes = list comprehension n for n in nodes if label in attrs at string Spec at string Labels and attrs at string Spec at string Labels at label == value print string Matches { match...
def remove_label_from_nodes(label, value, manager=None): client = get_docker_client(manager) nodes = client.nodes.list() matching_nodes = [n for n in nodes if label in n.attrs['Spec']['Labels'] and n.attrs['Spec']['Labels'][label] == value] print(f'Matches {m...
Python
nomic_cornstack_python_v1
comment Classifiers (10 Fold Cross Validation) comment 60-473 Assignment 1 Q4 comment Determine the 'best' value of k for the K Nearest Neighbor classifier. comment Compare its efficiency with that of the 1-NN and Naive Bayes classifier. from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import...
# # Classifiers (10 Fold Cross Validation) # 60-473 Assignment 1 Q4 # # Determine the 'best' value of k for the K Nearest Neighbor classifier. # Compare its efficiency with that of the 1-NN and Naive Bayes classifier. # from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB from ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt comment 用于数组的文件输入输出 comment numpy能够读写磁盘上的文本数据或二进制数据 comment 将数组以二进制格式保存到磁盘 comment np.load和np.save是读写磁盘数组数据的两个主要函数 comment 默认情况下,数组是以未压缩的原始二进制格式保存在扩展名为.npy的文件中的 comment arr = np.arange(10) comment np.save('some_array', arr) comment 如果文件路径末尾没有扩展名.npy,则该扩展名会被自动加上,然后就可以通过...
import numpy as np import matplotlib.pyplot as plt # 用于数组的文件输入输出 # numpy能够读写磁盘上的文本数据或二进制数据 # # # 将数组以二进制格式保存到磁盘 # np.load和np.save是读写磁盘数组数据的两个主要函数 # 默认情况下,数组是以未压缩的原始二进制格式保存在扩展名为.npy的文件中的 # arr = np.arange(10) # np.save('some_array', arr) # 如果文件路径末尾没有扩展名.npy,则该扩展名会被自动加上,然后就可以通过 # np.load读取磁盘上的数组 # arr = np...
Python
zaydzuhri_stack_edu_python
import sys import re comment files read out and write to set inputFile = string bgpMRTFormat.mrt set outputFile = string ../../html/controller/bgpDump.json comment open readable file function openReadFile file begin set f = open file string r return f end function comment open writable file function openWriteFile file ...
import sys import re # files read out and write to inputFile = 'bgpMRTFormat.mrt' outputFile = '../../html/controller/bgpDump.json' # open readable file def openReadFile(file): f = open(file, 'r') return f # open writable file def openWriteFile(file): f = open(file, 'w') return f #main program
Python
zaydzuhri_stack_edu_python
from utilities import prepare_data from utilities import GMVP_functions from utilities import portfolio_performance_functions as perf import numpy as np import pandas as pd import argparse set parser = call ArgumentParser comment data_period = 'validation' or 'test' call add_argument string --data_period type=str comme...
from utilities import prepare_data from utilities import GMVP_functions from utilities import portfolio_performance_functions as perf import numpy as np import pandas as pd import argparse parser = argparse.ArgumentParser() parser.add_argument('--data_period', type=str) # data_period = 'validation' or 'test' parse...
Python
zaydzuhri_stack_edu_python
comment answer: 7295372 set d = 2 set n = 1 set tmp = list while d <= 12000 begin set n = 1 while n < d begin if n / d > 1 / 3 and n / d < 1 / 2 begin append tmp n / d end set n = n + 1 end set d = d + 1 end set tmp = list call fromkeys tmp print length tmp
###answer: 7295372 d = 2 n = 1 tmp=[] while d <= 12000: n = 1 while n < d: if (n/d) > (1/3) and (n/d) < (1/2): tmp.append(n/d) n+=1 d+=1 tmp = list(dict.fromkeys(tmp)) print(len(tmp))
Python
zaydzuhri_stack_edu_python
function encode self text begin comment taken from htmlcss1 writer comment @@@ A codec to do these and all other HTML entities would be nice. set text = replace text string & string &amp; set text = replace text string < string &lt; set text = replace text string " string &quot; set text = replace text string > string ...
def encode(self, text): # taken from htmlcss1 writer # @@@ A codec to do these and all other HTML entities would be nice. text = text.replace("&", "&amp;") text = text.replace("<", "&lt;") text = text.replace('"', "&quot;") text = text.replace(">", "&gt;") text = ...
Python
nomic_cornstack_python_v1