code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import numpy as np import sys , os set fileName = string bla.dat set file = open fileName string r set lines = read lines file for line in lines begin if strip line begin set tempLine = strip line set tempLine = strip tempLine string ] set content = split tempLine string comment last_entry = content[-1] set last_entry ...
import numpy as np import sys, os fileName = "bla.dat" file = open(fileName,"r") lines = file.readlines() for line in lines: if line.strip(): tempLine = line.strip() tempLine = tempLine.strip("]") content = tempLine.split(" ") # last_entry = content[-1] last_entry = co...
Python
zaydzuhri_stack_edu_python
import pytest comment num1 = int(input('Qual a quantidade de caixa de fosforo? ')) set num1 = 10 print string O numero escolhido foi: { num1 } print string Lembrete: A caixa contém 40 palitos set num2 = 40 function calcular_fosforos num1 num2 begin return num1 * num2 end function print string O numero total de palitos ...
import pytest # num1 = int(input('Qual a quantidade de caixa de fosforo? ')) num1 = 10 print(f'O numero escolhido foi: {num1}') print('Lembrete: A caixa contém 40 palitos') num2 = 40 def calcular_fosforos(num1, num2): return num1 * num2 print(f'O numero total de palitos é: {calcular_fosforos(num1, num2)}') # ...
Python
zaydzuhri_stack_edu_python
import serial from flask import Flask set ser = call Serial string /dev/tty.usbmodem1411 9600 set app = call Flask __name__ decorator call route string / function hello begin return string Hello World! end function decorator call route string /command/<int:option> function command option begin write ser string %d % opt...
import serial from flask import Flask ser = serial.Serial('/dev/tty.usbmodem1411', 9600) app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" @app.route('/command/<int:option>') def command(option): ser.write("%d" % option) answer = ser.readline() return answer if __name__ =...
Python
zaydzuhri_stack_edu_python
comment Sort data based on keys in alphabetical order set sorted_data = sorted items data key=lambda x -> x at 0 comment Iterate over sorted data for tuple name details in sorted_data begin print string Name: { details at string name } comment Reverse order of languages set reversed_languages = details at string langua...
# Sort data based on keys in alphabetical order sorted_data = sorted(data.items(), key=lambda x: x[0]) # Iterate over sorted data for name, details in sorted_data: print(f"Name: {details['name']}") # Reverse order of languages reversed_languages = details["languages"][::-1] print(f"Languages: {', '.jo...
Python
greatdarklord_python_dataset
function read self begin return __items__ at 0 end function
def read(self): return self.__items__[0]
Python
nomic_cornstack_python_v1
function counter s begin set ans = list for l in letters begin set n = count s l if n != 0 begin append ans n end end if sum ans - max ans == max ans begin return string YES end else begin return string NO end end function set ANS = list set T = integer strip input string for l in range T begin set str1 = input appen...
def counter(s): ans = [] for l in letters: n = s.count(l) if n != 0: ans.append(n) if sum(ans) - max(ans) == max(ans): return 'YES' else: return 'NO' ANS = [] T = int(input().strip(' ')) for l in range(T): str1 = input() ANS.appen...
Python
zaydzuhri_stack_edu_python
function shouldhave self thisfile begin if not is file path thisfile begin call logtxt string ERROR: expected file (%s/%s) does not exist! % tuple get current directory thisfile string error end end function
def shouldhave(self, thisfile): if not os.path.isfile(thisfile): self.logtxt("ERROR: expected file (%s/%s) does not exist!" % (os.getcwd(), thisfile), 'error')
Python
nomic_cornstack_python_v1
function title self begin return _title end function
def title(self) -> str: return self._title
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- set content = string 我是中文 set content_unicode = decode content string utf-8 set content_gbk = encode content_unicode string gbk
# -*- coding:utf-8 -*- content = "我是中文" content_unicode = content.decode("utf-8") content_gbk = content_unicode.encode("gbk")
Python
zaydzuhri_stack_edu_python
from __future__ import division import sys import Adafruit_BMP.BMP085 as BMP085 comment Calibrate the altitude to output a value more close to the GPS comment altitude calculated. This calibrated altitude will be used for comment pressure and sea level pressure calculations set altOffset = 98.6 comment The average sea ...
from __future__ import division import sys import Adafruit_BMP.BMP085 as BMP085 # Calibrate the altitude to output a value more close to the GPS # altitude calculated. This calibrated altitude will be used for # pressure and sea level pressure calculations altOffset = 98.6 # The average sea level pressure. Take thi...
Python
zaydzuhri_stack_edu_python
function dense_stack inputs num_outputs hiddens hidden_activation_fn=elu last_activation_fn=none is_bn=false is_dropout=false keep_prob=0.5 is_reuse=false name_scope=string dense_stack var_scope=string dense_stack_vars begin set n_hidden_layers = length hiddens with call name_scope name_scope begin with call variable_s...
def dense_stack(inputs, num_outputs, hiddens, hidden_activation_fn=tf.nn.elu, last_activation_fn=None, is_bn=False, is_dropout=False, keep_prob=0.5, is_reuse=False, name_scope=...
Python
nomic_cornstack_python_v1
class Solution extends object begin function letterCombinations self digits begin string :type digits: str :rtype: List[str] comment Using Queue if length digits == 0 begin return list end set digit_char_map = list string 0 string 1 string abc string def string ghi string jkl string mno string pqrs string tuv string w...
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ # Using Queue if len(digits) == 0: return [] digit_char_map = ["0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"] letter_combi...
Python
zaydzuhri_stack_edu_python
from app import app from flask import render_template , request from app.models.player import * from app.models.game import * from app.models.game_play import * decorator call route string / comment @app.route('/') comment def index(): comment return "Hello World!" comment @app.route('/<choice1>/<choice2>') comment def...
from app import app from flask import render_template, request from app.models.player import * from app.models.game import * from app.models.game_play import * # @app.route('/') # def index(): # return "Hello World!" # @app.route('/<choice1>/<choice2>') # def player_choices(choice1, choice2): # return game_re...
Python
zaydzuhri_stack_edu_python
function test_attention_net self begin comment Checks that torch and tf embedding matrices are the same with call as_default as sess begin assert call allclose eval session=sess call numpy end comment B is batch size set B = 32 comment D_in is attention dim, L is memory_tau set tuple L D_in D_out = tuple 2 16 2 for tup...
def test_attention_net(self): # Checks that torch and tf embedding matrices are the same with tf1.Session().as_default() as sess: assert np.allclose( relative_position_embedding(20, 15).eval(session=sess), relative_position_embedding_torch(20, 15).numpy()) ...
Python
nomic_cornstack_python_v1
function breweries id begin try begin return call brewery id at string data end except Exception begin return list end end function
def breweries(id): try: return BreweryDb.brewery(id)['data'] except Exception: return []
Python
nomic_cornstack_python_v1
comment 동명이인 찾기 comment 입력 : 이름이 n개 들어있는 리스트 comment 출력 : n개의 이름 중 반복되는 이름의 집합 function find_same_name a begin comment 1단계 : 각 이름이 등장한 횟수를 딕셔너리로 만듦 set name_dict = dict comment 리스트 a에 있는 자료들을 차례로 반복 for name in a begin comment 이름이 name_dict에 있으면 if name in name_dict begin comment 등장 횟수를 1증가 set name_dict at name = nam...
# 동명이인 찾기 # 입력 : 이름이 n개 들어있는 리스트 # 출력 : n개의 이름 중 반복되는 이름의 집합 def find_same_name(a): # 1단계 : 각 이름이 등장한 횟수를 딕셔너리로 만듦 name_dict = {} for name in a: # 리스트 a에 있는 자료들을 차례로 반복 if name in name_dict: # 이름이 name_dict에 있으면 name_dict[name] += 1 # 등장 횟수를 1증가 else: # 새 이름이면 ...
Python
zaydzuhri_stack_edu_python
function SliceEmbeddingIds self input_batch begin return call GetSlice feature_names end function
def SliceEmbeddingIds( self, input_batch: py_utils.NestedMap ) -> py_utils.NestedMap: return input_batch.GetSlice(self.feature_names)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import subprocess import statistics comment first is baseline set executables = list string strlen-clang string strlen-asan string strlen-asan-introspection string strlen-softbound string strlen-mpx string strlen-mpx-introspection string strlen-softbound-introspection set string_lengths = ...
#!/usr/bin/env python3 import subprocess import statistics # first is baseline executables = ['strlen-clang', 'strlen-asan', 'strlen-asan-introspection', 'strlen-softbound', 'strlen-mpx', 'strlen-mpx-introspection', 'strlen-softbound-introspection'] string_lengths = [10, 100, 10000] baseline = [0] * len(string_lengths...
Python
zaydzuhri_stack_edu_python
function _set_restart_time self v load=false begin if has attribute v string _utype begin set v = call _utype v end try begin set t = call YANGDynClass v base=call RestrictedClassType base_type=long restriction_dict=dict string range list string 0..4294967295 int_size=32 is_leaf=true yang_name=string restart-time paren...
def _set_restart_time(self, v, load=False): if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), is_leaf=True, yang_name="restart-time", parent=self, path_helper=self._path_helper, extme...
Python
nomic_cornstack_python_v1
function target_temperature_high self begin set target_temperature_high = none if _dual_setpoint begin set target_temperature_high = _target_temp_heat end return target_temperature_high end function
def target_temperature_high(self) -> Optional[float]: target_temperature_high = None if self._dual_setpoint: target_temperature_high = self._target_temp_heat return target_temperature_high
Python
nomic_cornstack_python_v1
function __stash_pop git_repo begin try begin if string Automatic stash in call stash string list begin set asd = call stash string pop if string error: could not restore untracked files from stash in asd begin raise call GitCommandError asd end end end except GitCommandError as error begin print string Error: %s % err...
def __stash_pop(git_repo): try: if 'Automatic stash' in git_repo.git.stash('list'): asd = git_repo.git.stash('pop') if 'error: could not restore untracked files from stash' in asd: raise exc.GitCommandError(asd) except exc.GitCommandError as error: print("...
Python
nomic_cornstack_python_v1
class Account begin function __init__ self owner balance begin set owner = owner set balance = balance end function function acc_owner self begin print string Account owner: { owner } end function function acc_balance self begin print string Account balance: { balance } end function function deposit self add_balance be...
class Account(): def __init__(self,owner,balance): self.owner = owner self.balance = balance def acc_owner(self): print(f"Account owner: {self.owner}") def acc_balance(self): print(f"Account balance: {self.balance}") def deposit(self,add_balance): self.balance ...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import os , sys import numpy as np from scipy.misc import factorial import scipy.stats as stats import csv function read_csv_as_ndarray csvDir begin set csv_file = open csvDir set csv_reader_list = reader csv_file set tmp_list = list for ln in csv_reader_list begin append tmp_list ln end s...
# -*- coding:utf-8 -*- import os, sys import numpy as np from scipy.misc import factorial import scipy.stats as stats import csv def read_csv_as_ndarray(csvDir): csv_file = open(csvDir) csv_reader_list = csv.reader(csv_file) tmp_list = [] for ln in csv_reader_list: tmp_list.append(ln) csv_...
Python
zaydzuhri_stack_edu_python
string Ever wonder what actually happens during lunch? There's actually a Behind-The-Door Break Room Cafe where all the instructors show off what they brought in for lunch. Create an invoice store that would take orders from our makeshift Behind-The-Door Break Room Cafe. Requirements: Create a function for the invoice ...
''' Ever wonder what actually happens during lunch? There's actually a Behind-The-Door Break Room Cafe where all the instructors show off what they brought in for lunch. Create an invoice store that would take orders from our makeshift Behind-The-Door Break Room Cafe. Requirements: Create a function for the invo...
Python
zaydzuhri_stack_edu_python
from collections import deque set customers = deque generator expression integer c for c in split input string , set taxis = deque reversed list comprehension integer t for t in split input string , set total_time = 0 while length taxis > 0 begin set first_customer = call popleft set last_taxi = call popleft if last_ta...
from collections import deque customers = deque(int(c) for c in input().split(', ')) taxis = deque(reversed([int(t) for t in input().split(', ')])) total_time = 0 while len(taxis) > 0: first_customer = customers.popleft() last_taxi = taxis.popleft() if last_taxi >= first_customer: tota...
Python
zaydzuhri_stack_edu_python
function assemble self codim=0 mask=none begin comment first compute the operator specific entries comment --> nE x nB [x nB] set entries = call _compute_entries codim=codim comment get the dof map for the desired entities comment --> nB x nE set dim = dimension - codim set dof_map = call get_dof_map d=dim mask=mask se...
def assemble(self, codim=0, mask=None): # first compute the operator specific entries # --> nE x nB [x nB] entries = self._compute_entries(codim=codim) # get the dof map for the desired entities # --> nB x nE dim = self.fe_space.mesh.dimension - codim dof_map = ...
Python
nomic_cornstack_python_v1
function dataset self begin return get pulumi self string dataset end function
def dataset(self) -> 'outputs.DatasetReferenceResponse': return pulumi.get(self, "dataset")
Python
nomic_cornstack_python_v1
function canCancel self begin Ellipsis end function
def canCancel(self) -> bool: ...
Python
nomic_cornstack_python_v1
function pretrained name=string wordseg_pku lang=string zh remote_loc=none begin from sparknlp.pretrained import ResourceDownloader return call downloadModel WordSegmenterModel name lang remote_loc end function
def pretrained(name="wordseg_pku", lang="zh", remote_loc=None): from sparknlp.pretrained import ResourceDownloader return ResourceDownloader.downloadModel(WordSegmenterModel, name, lang, remote_loc)
Python
nomic_cornstack_python_v1
comment noqa B002 function subf self repl string count=0 begin return sub call _auto_compile repl true string count end function
def subf(self, repl, string, count=0): # noqa B002 return self.pattern.sub(self._auto_compile(repl, True), string, count)
Python
nomic_cornstack_python_v1
import os import shutil import subprocess import time from datetime import datetime function create_new begin with open trash string wb as f begin set data = call urandom 4096 write f data end return data end function comment cdb set cdb = string cdb.exe set program = string program set crashdir = string C:\ set trash ...
import os import shutil import subprocess import time from datetime import datetime def create_new(): with open(trash, "wb") as f: data = os.urandom(4096) f.write(data) return data cdb = "cdb.exe" # cdb program = "program" crashdir = "C:\\" trash = "trash" def startapp(trash): print() ...
Python
zaydzuhri_stack_edu_python
async function async_turn_off self **kwargs begin set data = dict ATTR_ENTITY_ID _entity_ids if ATTR_TRANSITION in kwargs begin set data at ATTR_TRANSITION = kwargs at ATTR_TRANSITION end await call async_call DOMAIN SERVICE_TURN_OFF data blocking=true context=_context end function
async def async_turn_off(self, **kwargs): data = {ATTR_ENTITY_ID: self._entity_ids} if ATTR_TRANSITION in kwargs: data[ATTR_TRANSITION] = kwargs[ATTR_TRANSITION] await self.hass.services.async_call( light.DOMAIN, light.SERVICE_TURN_OFF, data, ...
Python
nomic_cornstack_python_v1
function sayHello name age=string reservada tu edad begin print string Hola %s con que tienes %s % tuple name age end function function pintar_linea longitud datos=dict string punta string * ; string extremo string ? ; string relleno string + isTop=false begin set line = datos at string relleno * longitud - 1 if isTop ...
def sayHello(name,age="reservada tu edad"): print("Hola %s con que tienes %s" % (name, age)) def pintar_linea(longitud, datos={'punta': '*', 'extremo': '?', 'relleno': '+'}, isTop=False): line = datos['relleno']*(longitud-1) if isTop: line += datos['punta'] else: line += datos['extremo'...
Python
zaydzuhri_stack_edu_python
function sortColors self nums begin set s = string asd print s at slice 1 : 2 : set p0 = 0 set p2 = length nums - 1 function swap i j begin set t = nums at i set nums at i = nums at j set nums at j = t end function set i = 0 while i <= p2 begin if nums at i == 0 begin call swap i p0 set p0 = p0 + 1 set i = i + 1 end el...
def sortColors(self, nums: list) -> None: s="asd" print(s[1:2]) p0=0 p2=len(nums)-1 def swap(i,j): t=nums[i] nums[i]=nums[j] nums[j]=t i=0 while i<=p2: if(nums[i]==0): swap(i,p0) p0...
Python
nomic_cornstack_python_v1
function security_indicator self begin return __security_indicator end function
def security_indicator(self): return self.__security_indicator
Python
nomic_cornstack_python_v1
import random set rock = string _______ ---' ____) (_____) (_____) (____) ---.__(___) set paper = string _______ ---' ____)____ ______) _______) _______) ---.__________) set scissors = string _______ ---' ____)____ ______) __________) (____) ---.__(___) print string Welcome to rock-paper-scissors challenge. set my_move...
import random rock = ''' _______ ---' ____) (_____) (_____) (____) ---.__(___) ''' paper = ''' _______ ---' ____)____ ______) _______) _______) ---.__________) ''' scissors = ''' _______ ---' ____)____ ______) ___...
Python
zaydzuhri_stack_edu_python
string def factorial(n): if n == 0: return 1 return n * factorial(n-1) function factorial n begin set factorial = none if n == 0 begin return 1 end else if n > 0 begin set factorial = 1 for number in range 1 n + 1 begin set factorial = factorial * number end end return factorial end function print call factorial 3
'''def factorial(n): if n == 0: return 1 return n * factorial(n-1) ''' def factorial(n): factorial = None if n == 0: return 1 elif n > 0 : factorial = 1 for number in range(1,n+1): factorial *= number return factorial print(factorial(3))
Python
zaydzuhri_stack_edu_python
function print_thank_you_txt txt begin print print print print txt end function
def print_thank_you_txt(txt): print() print() print() print(txt)
Python
nomic_cornstack_python_v1
function divide_column_by_criteria row_grouping_criteria_header target_column_name dataset output=string list begin from preprocessor.legacy_functions.select_column import select_column comment Compatibilty column for history_nback function. Can be ignored. if row_grouping_criteria_header is none begin return list call...
def divide_column_by_criteria(row_grouping_criteria_header, target_column_name, dataset, output="list"): ############################################################################################################# from preprocessor.legacy_functions.select_column import select_column # Compatibilty colum...
Python
nomic_cornstack_python_v1
function validate cls name config admin=none users=none task=none begin if call meta name string admin_only is true begin print string Admin Access end if call meta name string operator is true begin print string Operator end end function
def validate(cls, name, config, admin=None, users=None, task=None): if cls.meta(name, "admin_only") is True: print("Admin Access") if cls.meta(name, "operator") is True: print("Operator")
Python
nomic_cornstack_python_v1
function smoothed self angle=0.4 begin string Return a version of the current mesh which will render nicely, without changing source mesh. Parameters ------------- angle : float Angle in radians, face pairs with angles smaller than this value will appear smoothed Returns --------- smoothed : trimesh.Trimesh Non waterti...
def smoothed(self, angle=.4): """ Return a version of the current mesh which will render nicely, without changing source mesh. Parameters ------------- angle : float Angle in radians, face pairs with angles smaller than this value will appear smoothed...
Python
jtatman_500k
function fit_lorentizan curve p0=none N_points=1000 begin string Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess. It returns a curve with N_points. function lorentzian x x0 A gamma begin return A * gamma ^ 2 / x - x0 ^ 2 + gamma ^ 2 end function set N = length curve set x = list comprehension curve at...
def fit_lorentizan(curve,p0=None,N_points=1000): '''Fits a lorentzian curve using p0=[x0,A,gamma] as an initial guess. It returns a curve with N_points.''' def lorentzian(x,x0,A,gamma): return A*gamma**2/((x-x0)**2+gamma**2) N=len(curve) x=[curve[i][0] for i in range(N)] y=[curve[i][1] for i in range(N)] ...
Python
jtatman_500k
import math import os from sequential import sequential from util import insert_number if __name__ == string __main__ begin print string Cannon’s algorithm for matrix multiplication while true begin set size = call insert_number string Insert the matrix dimensions(nxn), just one number(n): if size > 1 begin break end p...
import math import os from sequential import sequential from util import insert_number if __name__ == '__main__': print("Cannon’s algorithm for matrix multiplication") while True: size = insert_number("Insert the matrix dimensions(nxn), just one number(n): ") if size > 1: break ...
Python
zaydzuhri_stack_edu_python
set sentence = string Hello, World! set new_sentence = replace sentence string Hello, string Goodbye, 1 print new_sentence
sentence = "Hello, World!" new_sentence = sentence.replace("Hello, ", "Goodbye, ", 1) print(new_sentence)
Python
jtatman_500k
import math set t = ceil square root n for i in range t 1 - 1 begin if n % i == 0 begin print i - 1 + n // i - 1 break end end for else begin print n - 1 end
import math t = math.ceil(math.sqrt(n)) for i in range(t,1,-1): if n%i == 0: print(i-1+(n//i)-1) break else:print(n-1)
Python
zaydzuhri_stack_edu_python
function listen card interval begin global screensaverstate while 1 begin comment Screen.wrapper(datascreen) comment print("now is the time to exit the program by CTRL-C") comment time.sleep(2) if select card begin set post = call logOnboarding readerid uid comment print data comment print ("aantal punten: " + str(data...
def listen(card, interval): global screensaverstate while 1: # Screen.wrapper(datascreen) #print("now is the time to exit the program by CTRL-C") # time.sleep(2) if card.select(): post= logOnboarding(readerid, card.uid) # print data # print ("aantal punten: " + str(data['credits'])) # print (...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import time import requests import sqlite3 from argparse import ArgumentParser from datetime import datetime , timedelta , date from sqlite3 import Error string Scans submissions and comments: collects ids with its dates and/or ranks by author 'Count' and 'ranking' tables are ready for vis...
#!/usr/bin/env python3 import time import requests import sqlite3 from argparse import ArgumentParser from datetime import datetime, timedelta, date from sqlite3 import Error """ Scans submissions and comments: collects ids with its dates and/or ranks by author 'Count' and 'ranking' tables are ready for visualiza...
Python
zaydzuhri_stack_edu_python
import os , unittest from confparse import properties , ini from tempfile import mkstemp from test import test_support class propertiesFormatTestCase extends TestCase begin function setUp self begin set line = line end function set options = tuple tuple string b=c tuple string b string c none tuple string c=d#e tuple s...
import os, unittest from confparse import properties, ini from tempfile import mkstemp from test import test_support class propertiesFormatTestCase(unittest.TestCase): def setUp(self): self.line=properties.line options=(("b=c ", ('b','c',None)), ("c=d#e", ('c','d#e',None)), ...
Python
zaydzuhri_stack_edu_python
function create_test_users self begin for user_obj in test_user begin call set_password call make_random_password end end function
def create_test_users(self): for user_obj in test_user: User.objects.create( username=user_obj['username'], first_name=user_obj['first_name'], last_name=user_obj['last_name'], email=user_obj['email'] ).set_password( ...
Python
nomic_cornstack_python_v1
function get_data self state=none request=none begin raise NotImplementedError end function
def get_data(self, state=None, request=None): raise NotImplementedError
Python
nomic_cornstack_python_v1
function get_name self begin return name end function
def get_name(self): return self.name
Python
nomic_cornstack_python_v1
function convertImage file maxDim scale ext begin set args = list join path call getenv string HFS string bin string icp set scale = scale / 100.0 set resolution = call imageResolution file set width = decimal resolution at 0 * scale set height = decimal resolution at 1 * scale set resizeFactor = 1.0 comment Only calcu...
def convertImage(file, maxDim, scale, ext): args = [os.path.join(hou.getenv('HFS'), 'bin', 'icp')] scale /= 100.0 resolution = hou.imageResolution(file) width = float(resolution[0]) * scale height = float(resolution[1]) * scale resizeFactor = 1.0 if maxDim != -1: # Only calculate if user hasn't selected 'None'...
Python
nomic_cornstack_python_v1
function process self activations **kwargs begin comment pylint: disable=arguments-differ import itertools as it comment use only the activations > threshold (init offset to be added later) set first = 0 if threshold begin set idx = call nonzero activations >= threshold at 0 if any begin set first = max first min idx s...
def process(self, activations, **kwargs): # pylint: disable=arguments-differ import itertools as it # use only the activations > threshold (init offset to be added later) first = 0 if self.threshold: idx = np.nonzero(activations >= self.threshold)[0] ...
Python
nomic_cornstack_python_v1
function recurse_access_key current_val keys begin if not keys begin return current_val end else begin set current_key = pop keys 0 try begin set current_key = integer current_key end except ValueError begin pass end return call recurse_access_key current_val at current_key keys end end function
def recurse_access_key(current_val, keys): if not keys: return current_val else: current_key = keys.pop(0) try: current_key = int(current_key) except ValueError: pass return recurse_access_key(current_val[current_key], keys)
Python
nomic_cornstack_python_v1
function test_good_phone begin set good_phone = string 213-555-1212 set m = match good_phone comment print getmembers(m) assert m is not none msg string Canned RegEx phone test failed for %s % good_phone assert string == good_phone end function
def test_good_phone(): good_phone = "213-555-1212" m = CannedRe.PHONE.match(good_phone) # print getmembers(m) assert m is not None, "Canned RegEx phone test failed for %s" % good_phone assert m.string == good_phone
Python
nomic_cornstack_python_v1
comment Imports from itertools import zip_longest function single_byte_xor_letters ciphertext begin string Performs xor between every possible key uptil 256 and returns the key that gives the most ascii characters. set ascii_text_chars = list range 97 122 + list 32 set best_candidate = none comment for every possible k...
# Imports from itertools import zip_longest def single_byte_xor_letters(ciphertext: bytes) -> dict: """ Performs xor between every possible key uptil 256 and returns the key that gives the most ascii characters. """ ascii_text_chars = list(range(97, 122)) + [32] best_candidate = None ...
Python
zaydzuhri_stack_edu_python
import mimetypes import re from six import string_types from import exceptions , thumbnailers function create_thumbnail source_file resize_to=none begin if is instance source_file string_types begin set source_file = open source_file string rb end set tuple mime_type encoding = call guess_type name strict=false if mim...
import mimetypes import re from six import string_types from . import exceptions, thumbnailers def create_thumbnail(source_file, resize_to=None): if isinstance(source_file, string_types): source_file = open(source_file, 'rb') mime_type, encoding = mimetypes.guess_type(source_file.name, strict=False)...
Python
zaydzuhri_stack_edu_python
comment adadakontakti.write("IME - PEZIME - EMAIL - TELEFON - MESTO STANOVANJA\n") set odgovor = input string Da li zelite da unesete Kontakt? (da/Ne): if strip upper odgovor == string DA begin set ime = input string Unesite Ime Kontakta: set ime = string ime set prezime = input string Unesite Prezime Kontakta: set pre...
#adadakontakti.write("IME - PEZIME - EMAIL - TELEFON - MESTO STANOVANJA\n") odgovor = input("Da li zelite da unesete Kontakt? (da/Ne): ") if odgovor.upper().strip() == 'DA': ime = input("Unesite Ime Kontakta: ") ime = str(ime) prezime = input("Unesite Prezime Kontakta: ") prezime = str(prezime) ...
Python
zaydzuhri_stack_edu_python
comment The entire hardware specification of an experiment is stored as a pandas comment DataFrame. It is straightforward to search and slice this object for comment subsets on which to run algorithms. The DataFrame specification contains comment one row per channel, and each column specifies which hardware is connecte...
# The entire hardware specification of an experiment is stored as a pandas # DataFrame. It is straightforward to search and slice this object for # subsets on which to run algorithms. The DataFrame specification contains # one row per channel, and each column specifies which hardware is connected # to that channel upst...
Python
zaydzuhri_stack_edu_python
import numpy as np import os from itertools import combinations , combinations_with_replacement import re import copy from multiprocessing import Process , Manager import random set ROW = 0 set COLUMN = 1 set INVALID = set literal string TL string TW string DL string DW none set L_MULTI = dict string DL 2 ; string TL 3...
import numpy as np import os from itertools import combinations, combinations_with_replacement import re import copy from multiprocessing import Process, Manager import random ROW = 0 COLUMN = 1 INVALID = {'TL','TW','DL','DW',None} L_MULTI = {'DL':2,'TL':3} W_MULTI = {'DW':2,'TW':3} STAR = '*' SPACE = "-" AMOUNT = { ...
Python
zaydzuhri_stack_edu_python
import numpy as np import pennylane as qml from ttn import ttn_circuit from gates import two_qubit_gate from hamiltonians import tfi_chain from observables import sigma_z set num_qubits = 8 comment The simulator. set dev = device string default.qubit wires=num_qubits analytic=true comment The TFI model at the critical ...
import numpy as np import pennylane as qml from ttn import ttn_circuit from gates import two_qubit_gate from hamiltonians import tfi_chain from observables import sigma_z num_qubits = 8 # The simulator. dev = qml.device('default.qubit', wires=num_qubits, analytic=True) # The TFI model at the critical point. h ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy as np import datetime as DT from matplotlib.dates import date2num class MatPlotLib begin function __init__ self begin print string 1.Write a Python program to draw a line with suitable label in the x axis, y axis and a title print strin...
import matplotlib.pyplot as plt import pandas as pd import pylab as pl import numpy as np import datetime as DT from matplotlib.dates import date2num class MatPlotLib: def __init__(self): print("1.Write a Python program to draw a line with suitable label in the x axis, y axis and a title") ...
Python
zaydzuhri_stack_edu_python
comment ----------------------------------------------------------------------------- comment Name: beliefs comment Purpose: Homework 7 comment Author: Yulan Jin comment ----------------------------------------------------------------------------- string Module to track the belief distribution over all possible grid po...
# ----------------------------------------------------------------------------- # Name: beliefs # Purpose: Homework 7 # # Author: Yulan Jin # # ----------------------------------------------------------------------------- """ Module to track the belief distribution over all possible grid positions Your task for h...
Python
zaydzuhri_stack_edu_python
function Fibonacci n begin if n < 0 begin print string Incorrect input end else comment First Fibonacci number is 0 if n == 1 begin return 0 end else comment Second Fibonacci number is 1 if n == 2 begin return 1 end else begin return call Fibonacci n - 1 + call Fibonacci n - 2 end end function comment Driver Program se...
def Fibonacci(n): if n<0: print("Incorrect input") # First Fibonacci number is 0 elif n==1: return 0 # Second Fibonacci number is 1 elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2) # Driver Program result = [] for i in range(1,10): ...
Python
iamtarun_python_18k_alpaca
function get_or_create_default_history self begin comment There must be a user to fetch a default history. if not user begin return call new_history end comment Look for default history that (a) has default name + is not deleted and comment (b) has no datasets. If suitable history found, use it; otherwise, create comme...
def get_or_create_default_history(self): # There must be a user to fetch a default history. if not self.galaxy_session.user: return self.new_history() # Look for default history that (a) has default name + is not deleted and # (b) has no datasets. If suitable history found,...
Python
nomic_cornstack_python_v1
function twoSum self array target begin set nums = list for num in range length array begin set potentialSum = target - array at num if potentialSum in nums begin return list index array potentialSum num end else begin append nums array at num end end return list end function
def twoSum(self,array,target): nums=[] for num in range(len(array)): potentialSum = target - array[num] if potentialSum in nums: return [array.index(potentialSum),num] else: nums.append(array[num]) return []
Python
nomic_cornstack_python_v1
import random import numpy as np from enum import Enum from collections import namedtuple import random import math from functools import cmp_to_key from abc import ABC , abstractmethod import copy set EMPTY_FIELD = string set O_MARK = string O set X_MARK = string X set PUSH_UP = string PUSH_UP set PUSH_DOWN = string ...
import random import numpy as np from enum import Enum from collections import namedtuple import random import math from functools import cmp_to_key from abc import ABC, abstractmethod import copy EMPTY_FIELD = ' ' O_MARK = 'O' X_MARK = 'X' PUSH_UP = 'PUSH_UP' PUSH_DOWN = 'PUSH_DOWN' PUSH_LEFT = 'PUSH_LEFT' PUSH_RIG...
Python
zaydzuhri_stack_edu_python
function insert self resource data verb=string insert **kwargs begin if not _get_key_field begin raise call ValueError string Repository was created without a valid key_field argument. Cannot execute insert request. end set arguments = dict _get_key_field resource ; string body data if kwargs begin update arguments kwa...
def insert(self, resource, data, verb='insert', **kwargs): if not self._get_key_field: raise ValueError('Repository was created without a valid ' 'key_field argument. Cannot execute insert ' 'request.') arguments = { self....
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import binascii import argparse set SPACE = ordinal string function decode ciphertexts begin set char_cipher = list set line_cipher = list set pad_array = list comment 64 is number of columns for j in range 0 64 begin comment I will create a matrix where, for every line of ciphertexts, ...
#!/usr/bin/env python3 import binascii import argparse SPACE = ord(' ') def decode(ciphertexts): char_cipher = [] line_cipher = [] pad_array = [] for j in range(0, 64): #64 is number of columns #I will create a matrix where, for every line of ciphertexts, I will assign a number to each bi...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function arrangeCoins self n begin string :type n: int :rtype: int 964ms beats:15.19% set i = 0 set sum = 0 while true begin if sum == n begin return i end else if sum > n begin return i - 1 end set i = i + 1 set sum = sum + i end end function end class
class Solution(object): def arrangeCoins(self, n): """ :type n: int :rtype: int 964ms beats:15.19% """ i = 0 sum = 0 while True: if sum == n: return i elif sum > n: return i - 1 i += 1...
Python
zaydzuhri_stack_edu_python
function floor expr begin return call function string floor expr end function
def floor(expr: vecpy.base.Expr): return vecpy.function("floor", expr)
Python
nomic_cornstack_python_v1
function find2 self image frame dim shape=string circle confirm=false **kw begin set alive = true set tuple dx dy = tuple none none set st = time set targets = call _find_targets image frame dim shape=shape do_arc_filter=use_arc_approximation keyword kw debug format string time to find targets={:0.5f} time - st if targ...
def find2(self, image, frame, dim, shape="circle", confirm=False, **kw): self.alive = True dx, dy = None, None st = time.time() targets = self._find_targets( image, frame, dim, shape=shape, do_arc_filter=self.use_arc_approximat...
Python
nomic_cornstack_python_v1
function shutdown self begin print string shutting down ... set name_hash = call hash_string name_ set del_name_node = call find_successor name_hash call user_command string delete_name dumps dict string name name_ for ch in list joined_channels begin call leave_channel ch end set migrate_chan = dictionary for tuple ch...
def shutdown(self): print("shutting down ...") name_hash = hash_string(self.name_) del_name_node = self.local_.find_successor(name_hash) del_name_node.user_command("delete_name", json.dumps({ 'name': self.name_ })) for ch in list(self.joined_channels): ...
Python
nomic_cornstack_python_v1
function flip n begin set t = split binary n string b at 1 set x = bytearray t set l = length x for i in range l 32 begin set x = string 0 + x end comment print x set l = length x for i in range 0 l begin if x at i == 49 begin set x at i = 48 end else begin set x at i = 49 end end end function comment print x
def flip(n): t = bin(n).split('b')[1] x=bytearray(t) l=len(x) for i in range(l,32): x='0'+x #print x l=len(x) for i in range(0,l): if x[i] == 49: x[i] = 48 else: x[i] = 49 #print x
Python
zaydzuhri_stack_edu_python
function get cls id begin set response = json call get_by_endpoint string processors/ + string id return call Processor keyword response end function
def get(cls, id): response = get_by_endpoint("processors/" + str(id)).json() return Processor(**response)
Python
nomic_cornstack_python_v1
comment Added to speed up program function debug_visible self begin set start = min total current_num + 2 set end = max 1 current_num - height for i in range start end - 1 begin set error = false call error_test number end end function
def debug_visible(self): # Added to speed up program start = min(self.lines.total, self.current_num + 2) end = max(1, self.current_num - self.window.height) for i in range(start, end, -1): self.lines.db[i].error = False self.error_test(self.lines.db[i].number)
Python
nomic_cornstack_python_v1
function reverse_integers integers begin set reversed_integers = list comprehension string integer for integer in reversed integers return join string ; reversed_integers end function set integers = list 1 2 3 4 5 set result = call reverse_integers integers print result
def reverse_integers(integers): reversed_integers = [str(integer) for integer in reversed(integers)] return ';'.join(reversed_integers) integers = [1, 2, 3, 4, 5] result = reverse_integers(integers) print(result)
Python
greatdarklord_python_dataset
comment !/usr/bin/python set string = string haha set string2 = string hehe set str3 = string + string2
#!/usr/bin/python string="haha" string2="hehe" str3 = string + string2
Python
zaydzuhri_stack_edu_python
comment author: aspiring encoding: utf-8 import requests import re import json class Qiushi begin function __init__ self begin set start_url = string https://www.qiushibaike.com/text/page/{}/ set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chr...
# author: aspiring encoding: utf-8 import requests import re import json class Qiushi: def __init__(self): self.start_url = "https://www.qiushibaike.com/text/page/{}/" self.headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrom...
Python
zaydzuhri_stack_edu_python
function __init__ self embedding_or_raw_data_file=string voc_limit=none model_name=string word2vec intersecting_embedding=string config_file=string begin comment get the configuration set config = call read_config config_file set embedding_model_name = model_name set max_seq_length = 20 set check_other_embedding = co...
def __init__(self, embedding_or_raw_data_file="", voc_limit=None, model_name="word2vec", intersecting_embedding="", config_file=""): # get the configuration self.config = utils.read_config(config_file) self.emb...
Python
nomic_cornstack_python_v1
import pandas as pd function load_data full_path begin set data = read csv full_path header=none set len_data = length index set ch1 = list 0 * len_data set ch2 = list 0 * len_data for tuple i line in enumerate values begin set tuple ch1 at i ch2 at i = list comprehension decimal x for x in split line at 0 string ; end...
import pandas as pd def load_data(full_path): data = pd.read_csv(full_path,header=None) len_data = len(data.index) ch1 = [0]*len_data ch2 = [0]*len_data for i,line in enumerate(data.values): ch1[i],ch2[i] = [float(x) for x in line[0].split(";")] return [ch1,ch2]
Python
zaydzuhri_stack_edu_python
function _txs self _ __ begin set SP = X end function
def _txs(self, _, __): self.SP = self.X
Python
nomic_cornstack_python_v1
function macsEqual mac1 mac2 begin set cmpKey = call urandom 32 comment log.debug("macsEqual lengths:%s:%s:%s", len(cmpKey), len(mac1), len(mac2)) set hmac1 = call digest set hmac2 = call digest return hmac1 == hmac2 end function
def macsEqual(mac1, mac2): cmpKey = os.urandom(32) # log.debug("macsEqual lengths:%s:%s:%s", len(cmpKey), len(mac1), len(mac2)) hmac1 = hmac.new(cmpKey, mac1, 'sha256').digest() hmac2 = hmac.new(cmpKey, mac2, 'sha256').digest() return hmac1 == hmac2
Python
nomic_cornstack_python_v1
import inspect import hw2 function modified_func func *fixated_args **fixated_kwargs begin function new_func *fixed_args **fixed_kwargs begin string A func implementation of {func_name} with pre-applied arguments being: fixated_args: {fixated_args}, fixated_kwargs: {fixated_kwargs} source_code: {source} set fixed_args ...
import inspect import hw2 def modified_func(func, *fixated_args, **fixated_kwargs): def new_func(*fixed_args, **fixed_kwargs): """A func implementation of {func_name} with pre-applied arguments being: fixated_args: {fixated_args}, fixated_kwargs: {fixated_kwargs} source_cod...
Python
zaydzuhri_stack_edu_python
function test_wrongsyn begin assert call wrongsyn string sdf == none end function
def test_wrongsyn(): assert _socli.wrongsyn("sdf") == None
Python
nomic_cornstack_python_v1
function test_access_user_token self logged_in user testapp begin set res = get testapp call url_for string user.token call mustcontain no=string 401 end function
def test_access_user_token(self, logged_in, user, testapp): res = testapp.get(url_for('user.token')) res.mustcontain(no="401")
Python
nomic_cornstack_python_v1
function disable_login_password_reuse_interval device begin set cmd = string no login password-reuse-interval try begin call configure cmd end except SubCommandFailure as e begin raise call SubCommandFailure string Could not configure no login password-reuse-interval: { e } end end function
def disable_login_password_reuse_interval(device): cmd="no login password-reuse-interval" try: device.configure(cmd) except SubCommandFailure as e: raise SubCommandFailure( f'Could not configure no login password-reuse-interval:\n{e}' )
Python
nomic_cornstack_python_v1
function frequencies self frequencies begin set _frequencies = frequencies end function
def frequencies(self, frequencies): self._frequencies = frequencies
Python
nomic_cornstack_python_v1
class Board begin string Represents a SpiNNaker board *Side effects*: Upon instantiation, the parent machine is updated to include a reference to this board instance. :param `pacman103.lib.lib_machine` machine: parent machine. :param int idx: board ID. :param int boardtype = the actual physical type of board (TODO: sho...
class Board: """ Represents a SpiNNaker board *Side effects*: Upon instantiation, the parent machine is updated to include a reference to this board instance. :param `pacman103.lib.lib_machine` machine: parent machine. :param int idx: board ID. :param int boardtype = the actual...
Python
zaydzuhri_stack_edu_python
function handler signum frame spinner begin call fail call stop end function
def handler(signum, frame, spinner): spinner.fail() spinner.stop()
Python
nomic_cornstack_python_v1
function validate data schema ac_schema_safe=true ac_schema_errors=false **options begin string Validate target object with given schema object, loaded from JSON schema. See also: https://python-jsonschema.readthedocs.org/en/latest/validate/ :parae data: Target object (a dict or a dict-like object) to validate :param s...
def validate(data, schema, ac_schema_safe=True, ac_schema_errors=False, **options): """ Validate target object with given schema object, loaded from JSON schema. See also: https://python-jsonschema.readthedocs.org/en/latest/validate/ :parae data: Target object (a dict or a dict-like objec...
Python
jtatman_500k
set people = list string Stephany string Josh string Vanessa string Kristian set cancelled = pop people 3 insert people 3 string Miko print string I cordinally invite you, + pop people 0 + string , to join us for dinner. print string I cordinally invite you, + pop people 0 + string , to join us for dinner. print string...
people = ['Stephany', 'Josh', 'Vanessa', 'Kristian'] cancelled = people.pop(3) people.insert(3, 'Miko') print("I cordinally invite you, " + people.pop(0) + ", to join us for dinner.") print("I cordinally invite you, " + people.pop(0) + ", to join us for dinner.") print("I cordinally invite you, " + people.pop(0) + ",...
Python
zaydzuhri_stack_edu_python
function setup_distributed_tf self begin info string Setting up distributed TensorFlow execution mode. comment Create the Server object. set server = call Server server_or_cluster_def=distributed_spec at string cluster_spec job_name=distributed_spec at string job task_index=distributed_spec at string task_index protoco...
def setup_distributed_tf(self): self.logger.info("Setting up distributed TensorFlow execution mode.") # Create the Server object. self.server = tf.train.Server( server_or_cluster_def=self.distributed_spec["cluster_spec"], job_name=self.distributed_spec["job"], ...
Python
nomic_cornstack_python_v1
comment 1.求2+4+6+8+...+100的求和 set sum = 0 set number = 2 while number < 101 begin set sum = sum + number set number = number + 2 end print sum
# 1.求2+4+6+8+...+100的求和 sum = 0 number = 2 while number < 101: sum = sum + number number = number + 2 print(sum)
Python
zaydzuhri_stack_edu_python
function get_cmd begin set a = args set cmd = none try begin set cmd = a at string command end except any begin set cmd = none end return cmd end function
def get_cmd(): a = request.args cmd = None try: cmd = a['command'] except: cmd = None return cmd
Python
nomic_cornstack_python_v1
function play_current_song self begin if _current_song_id == INITIAL_SONG_ID begin if call song_available begin call next_song end else begin return false end end else begin set song_path = call get_song_path_by_song_id _current_song_id comment Should never be None since we checked for songs above. if song_path is none...
def play_current_song(self) -> bool: if self._current_song_id == INITIAL_SONG_ID: if self._song_service.song_available(): self.next_song() else: return False else: song_path = self._song_service.get_song_path_by_song_id(self._current_so...
Python
nomic_cornstack_python_v1
function normalized_accuracy y_true y_pred begin set acc_known_samples = call accuracy_known_samples y_true y_pred set acc_unknown_samples = call accuracy_unknown_samples y_true y_pred if acc_known_samples is none begin return acc_unknown_samples end if acc_unknown_samples is none begin return acc_known_samples end ret...
def normalized_accuracy(y_true, y_pred): acc_known_samples = accuracy_known_samples(y_true, y_pred) acc_unknown_samples = accuracy_unknown_samples(y_true, y_pred) if acc_known_samples is None: return acc_unknown_samples if acc_unknown_samples is None: return acc_known_samples ret...
Python
nomic_cornstack_python_v1
comment ppt 내장함수 실습하기 ~ 4월 말 string step01 func_basic comment 1. 사용자 정의함수 comment 1) 인수가 있는것 comment 2) 인수가 없는것 comment 3) 리턴이 있는것 comment 2. 라이브러리 함수 comment 1) built - in : sum, max, min, len, abs comment 2) import : import statistics comment 해당 모듈의 정보 print directory statistics string ctrl + 클릭 : module or function ...
# ppt 내장함수 실습하기 ~ 4월 말 ''' step01 func_basic ''' # 1. 사용자 정의함수 # 1) 인수가 있는것 # 2) 인수가 없는것 # 3) 리턴이 있는것 # 2. 라이브러리 함수 # 1) built - in : sum, max, min, len, abs # 2) import : import statistics print(dir(statistics)) # 해당 모듈의 정보 ''' ctrl + 클릭 : module or function source 보기 ''' ''' step02 사용자 정의 ...
Python
zaydzuhri_stack_edu_python
function pc_nproduced_avg self begin return call FreqOffCalc_sptr_pc_nproduced_avg self end function
def pc_nproduced_avg(self): return _ncofdm_swig.FreqOffCalc_sptr_pc_nproduced_avg(self)
Python
nomic_cornstack_python_v1
function _on_access_token self future response begin if error begin call set_exception call AuthError string Google auth error: %s % string response return end set args = call json_decode body call set_result args end function
def _on_access_token(self, future, response): if response.error: future.set_exception(AuthError('Google auth error: %s' % str(response))) return args = escape.json_decode(response.body) future.set_result(args)
Python
nomic_cornstack_python_v1