code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import numpy as np comment 矩阵的转置 function Matrix_transpose matrix begin return T end function comment 矩阵求逆 function Matrix_inversion matrix begin return call inv matrix end function comment 矩阵加法 function Matrix_addition matrixA matrixB begin try begin set res = matrixA + matrixB return matrixA + matrixB end except any ...
import numpy as np #矩阵的转置 def Matrix_transpose(matrix): return matrix.T #矩阵求逆 def Matrix_inversion(matrix): return np.linalg.inv(matrix) #矩阵加法 def Matrix_addition(matrixA,matrixB): try: res = matrixA + matrixB return matrixA + matrixB except: print("请检查矩阵的形状是否...
Python
zaydzuhri_stack_edu_python
function show_all_errors begin for error in error_list begin print error_msg end end function function add_error error_type error_msg begin append error_list error error_type error_msg end function class Error begin function __init__ self error_type error_msg begin string :param error_type: :type error_type: str :param...
def show_all_errors(): for error in error_list: print(error.error_msg) def add_error(error_type, error_msg): error_list.append(Error(error_type, error_msg)) class Error: def __init__(self, error_type, error_msg): """ :param error_type: :type error_type: str :para...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self key begin set left = none set right = none set val = key end function end class function inorder_traversal head result begin if head is not none begin call inorder_traversal left result append result val call inorder_traversal right result end end function set head = call Node 5 ...
class Node: def __init__(self, key): self.left = None self.right = None self.val = key def inorder_traversal(head, result): if head is not None: inorder_traversal(head.left, result) result.append(head.val) inorder_traversal(head.right, result) head = Node(5) h...
Python
zaydzuhri_stack_edu_python
class Employee begin set no_of_leaves = 8 function __init__ self aname asalary arole begin set name = aname set salary = asalary set role = arole end function function printdetails self begin return string name is { name } salary is { salary } role is { role } end function decorator classmethod function change_leaves c...
class Employee: no_of_leaves=8 def __init__(self,aname,asalary,arole): self.name=aname self.salary=asalary self.role=arole def printdetails(self): return f"name is {self.name} salary is {self.salary} role is {self.role}" @classmethod def change_leaves(cls,newleaves): ...
Python
zaydzuhri_stack_edu_python
function sortSEs self begin comment Starting off by printing to screen all of the information I need to know to do the sorting for tuple i cluster in enumerate clusters begin print format string Cluster ID: {:g} Cluster: {:s} i cluster end set df_info = list for SE in unique side_effects begin comment Intelligently ha...
def sortSEs(self): # Starting off by printing to screen all of the information I need to know to do the sorting for i,cluster in enumerate(self.clusters): print("Cluster ID: {:g}\t\t Cluster: {:s}".format(i, cluster)) df_info = [] for SE in np.unique(self.side_effect...
Python
nomic_cornstack_python_v1
function style self begin return tuple string max-height:%spx % call get_min_height end function
def style(self): return 'max-height:%spx' % self.get_min_height(),
Python
nomic_cornstack_python_v1
string Pseudo-Código Inicio digitar coeficiente_a digitar coeficiente_b digitar coeficiente_c Se a = 0 Então Se b != 0 Então Imprimir "A equação possui uma única raiz" r_um <- -c/b Imprimir r_um Senão b = 0 Então Imprimir "Indeterminação/Singularidade" Sair da subrotina Fim do Se Senão delta <- b ** 2 - 4 * a * c Se de...
"""Pseudo-Código Inicio digitar coeficiente_a digitar coeficiente_b digitar coeficiente_c Se a = 0 Então Se b != 0 Então Imprimir "A equação possui uma única raiz" r_um <- -c/b Imprimir r_um Senão b = 0 Então Imprimir "Indeterminação/Singul...
Python
zaydzuhri_stack_edu_python
function sum inputList begin comment the sum of the list starts from 0 set sum = 0 for num in inputList begin comment add all number in the list set sum = sum + num end print string the sum is sum end function
def sum(inputList): sum=0#the sum of the list starts from 0 for num in inputList: sum=sum+num#add all number in the list print("the sum is",sum)
Python
nomic_cornstack_python_v1
function print_info self message end=string begin write stdout string  + strip message + string  + end end function
def print_info(self,message, end = '\n'): sys.stdout.write('\x1b[1;34m' + message.strip() + '\x1b[0m' + end)
Python
nomic_cornstack_python_v1
import socket import struct set RP_BASEADDRESS = 1073741824 function get_ip begin set ip_address = string set s = call socket AF_INET SOCK_DGRAM call connect tuple string 8.8.8.8 80 set ip_address = call getsockname at 0 close s return ip_address end function function int2base x b alphabet=string 0123456789abcdefghijk...
import socket import struct RP_BASEADDRESS = 0x40000000 def get_ip(): ip_address = ''; s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8",80)) ip_address = s.getsockname()[0] s.close() return ip_address def int2base(x,b,alphabet='0123456789abcdefghijklmnopqrstuvwxyz'): ...
Python
zaydzuhri_stack_edu_python
comment noqa: E501 function __init__ self private_ip=none begin set openapi_types = dict string private_ip bool set attribute_map = dict string private_ip string private_ip set _private_ip = private_ip end function
def __init__(self, private_ip=None): # noqa: E501 self.openapi_types = { 'private_ip': bool } self.attribute_map = { 'private_ip': 'private_ip' } self._private_ip = private_ip
Python
nomic_cornstack_python_v1
comment coding: utf-8 import CaboCha import re set fname = string ./file/neko.txt set fname_parsed = string ./file/neko.txt.cabocha comment Morphの構造体(Cの意味)定義 class Morph begin function __init__ self surface base pos pos1 begin set surface = surface set base = base set pos = pos set pos1 = pos1 end function function __s...
# coding: utf-8 import CaboCha import re fname = './file/neko.txt' fname_parsed = './file/neko.txt.cabocha' # Morphの構造体(Cの意味)定義 class Morph: def __init__(self, surface, base, pos, pos1): self.surface = surface self.base = base self.pos = pos self.pos1 = pos1 def __str__(self...
Python
zaydzuhri_stack_edu_python
import sys import json from netmiko import ConnectHandler comment def print1(s): comment print ("I am back {}".format(s)) set device = call ConnectHandler device_type=string cisco_ios ip=argv at 1 username=argv at 2 password=argv at 3 set output = call send_command input string What is the command print output comment ...
import sys import json from netmiko import ConnectHandler # def print1(s): # print ("I am back {}".format(s)) device = ConnectHandler(device_type="cisco_ios",ip=sys.argv[1], username=sys.argv[2],password=sys.argv[3]) output = device.send_command(input("What is the command\n")) print (output) # if __name__=="_...
Python
zaydzuhri_stack_edu_python
class Deque begin string A double-ended queue implemented using a Circular Array function __init__ self begin string Initializes an empty Deque comment Data Members print string Hello I am a Circular Array Deque, What is it that you require? set capacity_ = 4 set size_ = 0 comment Arry set data_ = list none * capacity_...
class Deque: """ A double-ended queue implemented using a Circular Array """ def __init__(self): """ Initializes an empty Deque """ #Data Members print("Hello I am a Circular Array Deque, What is it that you require?") self.capacity_=4 self.s...
Python
zaydzuhri_stack_edu_python
async function close self begin await call aclose set _client = none set connected = false debug string Connection closed. end function
async def close(self): await self.socket.aclose() self._client = None self.connected = False self.logger.debug('Connection closed.')
Python
nomic_cornstack_python_v1
function com_google_fonts_check_046 ttFont begin from fontbakery.utils import getGlyph comment It would be good to also check comment for .notdef (codepoint = unspecified) set null = call getGlyph ttFont 0 set CR = call getGlyph ttFont 13 set space = call getGlyph ttFont 32 set missing = list if null is none begin app...
def com_google_fonts_check_046(ttFont): from fontbakery.utils import getGlyph # It would be good to also check # for .notdef (codepoint = unspecified) null = getGlyph(ttFont, 0x0000) CR = getGlyph(ttFont, 0x000D) space = getGlyph(ttFont, 0x0020) missing = [] if null is None: missing.append("0x0000") ...
Python
nomic_cornstack_python_v1
function close_visit self result begin return result end function
def close_visit(self, result): return result
Python
nomic_cornstack_python_v1
function cluster_name self begin return get pulumi self string cluster_name end function
def cluster_name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "cluster_name")
Python
nomic_cornstack_python_v1
import spacy import sys import recognizer as r comment Clase encargada del procesamiento del texto dado por el comment usuario para obtener secciones claves de la frase class NLP begin function __init__ self text begin set POS = dictionary set STOP = list set lemma = dictionary set entities = list comment audio.get_tex...
import spacy import sys import recognizer as r # Clase encargada del procesamiento del texto dado por el # usuario para obtener secciones claves de la frase class NLP: def __init__(self, text): self.POS = dict() self.STOP = list() self.lemma = dict() self.entities = list() ...
Python
zaydzuhri_stack_edu_python
comment V12 condicionales comment Ejemplo1 comment edad=100 comment if 0<edad<100: #contatenacion de operadores comment print("Edad correcta") comment else: comment print("edad incorrecta") comment Ejemplo2 set salario_presidente = input string Introduce salario de el presidente print string Salario presidente: + strin...
# V12 condicionales #Ejemplo1 # edad=100 # if 0<edad<100: #contatenacion de operadores # print("Edad correcta") # else: # print("edad incorrecta") #Ejemplo2 salario_presidente= input("Introduce salario de el presidente ") print("Salario presidente: ") + str(salario_presidente) salario_director= input("Introdu...
Python
zaydzuhri_stack_edu_python
function random website begin set g = call get_conn set result = random debug string get credential { result } return result end function
def random(website): g = get_conn() result = getattr(g, f'{website}_{credential}').random() logger.debug(f'get credential {result}') return result
Python
nomic_cornstack_python_v1
from django.core.management.base import BaseCommand from gallery.models import Album , TrashCan from io import BytesIO from selenium import webdriver from multiprocessing import Pool import os import re import requests import time import uuid class Command extends BaseCommand begin set help = string seulgi image crawle...
from django.core.management.base import BaseCommand from gallery.models import Album, TrashCan from io import BytesIO from selenium import webdriver from multiprocessing import Pool import os import re import requests import time import uuid class Command(BaseCommand): help = "seulgi image crawler" def sa...
Python
zaydzuhri_stack_edu_python
import math import random set file_res_record = string function _createResRecord list_mutant_line dict_mutant_information file_res_record_temp begin global file_res_record if length list_mutant_line == 0 begin set file_res_record = file_res_record + file_res_record_temp + string return end for mutant_item in dict_mut...
import math import random file_res_record = "" def _createResRecord(list_mutant_line, dict_mutant_information, file_res_record_temp): global file_res_record if len(list_mutant_line) == 0: file_res_record = file_res_record + file_res_record_temp + '\n' return for mutant_item in dict_mutant...
Python
zaydzuhri_stack_edu_python
function update_shallow route csv remaining_pairs begin set dest_id = route at - 1 for i in range length route - 1 begin set cur_node_id = route at i comment if this route was already computed, then we know the remainder of the route is already in the csv comment so we can stop here. if csv at cur_node_id at dest_id is...
def update_shallow(route, csv, remaining_pairs): dest_id = route[-1] for i in range(len(route) - 1): cur_node_id = route[i] # if this route was already computed, then we know the remainder of the route is already in the csv # so we can stop here. if csv[cur_node_id][dest_id] i...
Python
nomic_cornstack_python_v1
string The class handling the LED board import time import RPi.GPIO as GPIO class LED begin string The lED class function __init__ self begin set pin0 = 6 set pin1 = 13 set pin2 = 19 set single_led_handling = dict 0 tuple pin2 pin0 pin1 pin0 pin1 ; 1 tuple pin2 pin0 pin1 pin1 pin0 ; 2 tuple pin0 pin1 pin2 pin1 pin2 ; 3...
"""The class handling the LED board""" import time import RPi.GPIO as GPIO class LED: """The lED class""" def __init__(self): self.pin0 = 6 self.pin1 = 13 self.pin2 = 19 self.single_led_handling = {0: (self.pin2, self.pin0, self.pin1, self.pin0, self.pin1), ...
Python
zaydzuhri_stack_edu_python
class Solution begin string @param nums: an array with positive and negative numbers @param k: an integer @return: the maximum average function maxAverage self nums k begin comment write your code here set tuple start end = tuple min nums max nums while end - start > 1e-05 begin set mid = start + end / 2 if call check_...
class Solution: """ @param nums: an array with positive and negative numbers @param k: an integer @return: the maximum average """ def maxAverage(self, nums, k): # write your code here start, end = min(nums), max(nums) while end - start > 1e-5: ...
Python
zaydzuhri_stack_edu_python
comment I denne oppgaven skal vi modellere en kapselmaskin for espresso. comment Maskinen har to innstillinger, espresso (liten kopp) og lungo (større kopp). comment Maskinen kan ikke startes uten nok vann. En espresso krever 40ml, og en comment lungo krever 110ml. Maskinens vanntank er på 1000ml -- én liter. comment G...
# I denne oppgaven skal vi modellere en kapselmaskin for espresso. # Maskinen har to innstillinger, espresso (liten kopp) og lungo (større kopp). # Maskinen kan ikke startes uten nok vann. En espresso krever 40ml, og en # lungo krever 110ml. Maskinens vanntank er på 1000ml -- én liter. # Gitt "skjelettet" under, fy...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 string This file tests student written cachelab traces. It tests them by running the trace on csim-ref and comparing the hits/misses/evictions with the expected hits/misses/evictions. It also checks if the trace is well written. If run with the -f [tracefile] it only judges whether tracefile i...
#!/usr/bin/python3 ''' This file tests student written cachelab traces. It tests them by running the trace on csim-ref and comparing the hits/misses/evictions with the expected hits/misses/evictions. It also checks if the trace is well written. If run with the -f [tracefile] it only judges whether tracefile is well w...
Python
zaydzuhri_stack_edu_python
import random function gerar begin set recargas = string for x in range 0 9 begin set i = call randrange 0 9 set recargas = recargas + string i end comment recargas1 = int(recargas) return recargas end function function comprar begin comment criar um ficheiro do tipo Csv no teu diretorio set data = string D:\Abdu\Prog...
import random def gerar(): recargas ='' for x in range(0,9): i = random.randrange(0,9) recargas = recargas + str(i) #recargas1 = int(recargas) return recargas def comprar(): #criar um ficheiro do tipo Csv no teu diretorio data ='D:\Abdu\Programação Python-C\Base de Dados\Recargas.csv' data_write = op...
Python
zaydzuhri_stack_edu_python
function not_lasagne_and_moussaka_within_seven_days meals date combined_history begin set relevant_meal_names = call get_close_history_meal_names combined_history date n_days=7 if string Moussaka in relevant_meal_names begin set meals = dictionary comprehension name : meal_info for tuple name meal_info in items meals i...
def not_lasagne_and_moussaka_within_seven_days( meals: Dict[str, Dict], date: dt.date, combined_history: Dict[dt.date, Meal], ) -> Dict[str, Dict]: relevant_meal_names = get_close_history_meal_names( combined_history, date, n_days=7 ) if "Moussaka" in relevant_meal_names: meals...
Python
nomic_cornstack_python_v1
function test_cost_cvt alph=1e-08 vect=0 begin set d = call DalecDataTwin 1999 2000 string nee nc_file=string ../../alice_holt_data/ah_data_daily_test_nee3.nc scale_nee=1 set m = call DalecModel d size_ens=1 set pvals = edinburgh_mean set zvals = call pvals2zvals pvals set gradj = call gradcost_cvt zvals end function
def test_cost_cvt(alph=1e-8, vect=0): d = dC.DalecDataTwin(1999, 2000, 'nee', nc_file='../../alice_holt_data/ah_data_daily_test_nee3.nc', scale_nee=1) m = mc.DalecModel(d, size_ens=1) pvals = d.edinburgh_mean zvals = m.pvals2zvals(pvals) gradj = m.gradcost_cvt(zvals)
Python
nomic_cornstack_python_v1
string c^2 = (r-s)^2 = r^2 -2rs + s^2 = r^2 + s^2 -2|r||s|cos(theta) r.s = |r||s|cos(theta) ==> |s|cos(theta) = (r.s)/|r| s / / / / / theta ----------- | | r <-x -> (scalar projection) |x| = |s|cos(theta) = (r.s)/|r| unit vector with direction r r/|r| (vector projection) x = |x|*(r/|r|) = ((r.s)/|r|)/(r/|r|) = (r.s)*r/...
""" c^2 = (r-s)^2 = r^2 -2rs + s^2 = r^2 + s^2 -2|r||s|cos(theta) r.s = |r||s|cos(theta) ==> |s|cos(theta) = (r.s)/|r| s / / / / / theta ----------- | | r <-x -> (scalar projection) |x| = |s|cos(theta) = (r.s)/|r| unit vector with direction r r/|r| (vector projection) ...
Python
zaydzuhri_stack_edu_python
function description self newDescription=none begin pass end function
def description(self, newDescription=None): pass
Python
nomic_cornstack_python_v1
while fifo begin set tuple r c = pop fifo if r == N - 1 or grid at r + 1 at c == string V begin pass end else if grid at r + 1 at c == string . begin set grid at r + 1 at c = string V append fifo tuple r + 1 c end else if grid at r + 1 at c == string # begin if c > 0 and grid at r at c - 1 == string . begin set grid at...
while fifo: r, c = fifo.pop() if r == N-1 or grid[r+1][c] == 'V': pass elif grid[r+1][c] == '.': grid[r+1][c] = 'V' fifo.append((r+1, c)) elif grid[r+1][c] == '#': if c > 0 and grid[r][c-1] == '.': grid[r][c-1] = 'V' fifo.append((r, c-1)) if c < M-1 and grid[r][c+1] == '.': grid[r][c+1] = 'V' ...
Python
zaydzuhri_stack_edu_python
function open_document self path encoding=none replace_tabs_by_spaces=true clean_trailing_whitespaces=true safe_save=true restore_cursor_position=true preferred_eol=0 autodetect_eol=true show_whitespaces=false **kwargs begin string Opens a document. :param path: Path of the document to open :param encoding: The encodin...
def open_document(self, path, encoding=None, replace_tabs_by_spaces=True, clean_trailing_whitespaces=True, safe_save=True, restore_cursor_position=True, preferred_eol=0, autodetect_eol=True, show_whitespaces=False, **kwargs): """ Opens a ...
Python
jtatman_500k
string "" --------------------------------------------------------------------------------------- --> Deque means it will add the elements from front end or from last in queue --> it consists front ad rear 1. front --> front of the queue 2.rear --> last of the queue -----------------------------------------------------...
""""" --------------------------------------------------------------------------------------- --> Deque means it will add the elements from front end or from last in queue --> it consists front ad rear 1. front --> front of the queue 2.rear --> last of the queue -------------------------------------------------...
Python
zaydzuhri_stack_edu_python
class BaseTemplateError extends Exception begin function __init__ self msg=string begin set msg = msg call __init__ msg end function function __repr__ self begin return msg end function function __str__ self begin set __str__ = call __repr__ return __str__ end function end class class UnitConverterError extends BaseTem...
class BaseTemplateError(Exception): def __init__(self, msg=""): self.msg = msg super().__init__(self.msg) def __repr__(self): return self.msg def __str__(self): self.__str__ = self.__repr__() return self.__str__ class UnitConverterError(BaseTemplateError): """...
Python
zaydzuhri_stack_edu_python
function chunk_upload_file self name folder_id file_path progress_callback=none chunk_size=1024 * 1024 * 1 begin string Upload a file chunk by chunk. The whole file is never loaded in memory. Use this function for big file. The callback(transferred, total) to let you know the upload progress. Upload can be cancelled if...
def chunk_upload_file(self, name, folder_id, file_path, progress_callback=None, chunk_size=1024*1024*1): """Upload a file chunk by chunk. The whole file is never loaded in memory. Use this function for big file. The callback(trans...
Python
jtatman_500k
comment coding=utf-8 comment 读文件 comment 定义一个变量接受open函数打开文件后的内容 set file = open string f:\1.txt string r encoding=string utf8 print file for i in file begin print i end close file comment 写文件 set str1 = string oh my dear mom!!! set file = open string f:\2.txt string w write file str1 close file print string 已经写入 commen...
#coding=utf-8 #读文件 #定义一个变量接受open函数打开文件后的内容 file=open('f:\\1.txt','r',encoding='utf8') print(file) for i in file: print(i) file.close() #写文件 str1='oh my dear mom!!!' file=open('f:\\2.txt','w') file.write(str1) file.close() print('已经写入') #追加文件 file=open('f:\\2.txt','a') file.write('\ncome on baby!...
Python
zaydzuhri_stack_edu_python
comment file: webScraping.py comment author: Jack Dunbar comment date: 12/3/2017 comment get average cost of flight data from faredetective.com comment webscraping guidance from https://abhgog.gitbooks.io/webscraping/content/ import requests function getAverageCost airports start finish begin comment Url follows a pred...
# file: webScraping.py # author: Jack Dunbar # date: 12/3/2017 # get average cost of flight data from faredetective.com # webscraping guidance from https://abhgog.gitbooks.io/webscraping/content/ import requests def getAverageCost(airports, start, finish): # Url follows a predictable pattern url = "http://www...
Python
zaydzuhri_stack_edu_python
function predict_logit self x begin with no grad begin set y_ = call tr_model x end return y_ end function
def predict_logit(self, x): with torch.no_grad(): y_ = self.tr_model(x) return y_
Python
nomic_cornstack_python_v1
comment 射气球 class Solution begin function findMinArrowShots self points begin if not points begin return 0 end comment 先按左端点进行排序 sort points key=lambda x -> x at 0 print string ponits: points set length = length points set right = points at 0 at 1 set count = 1 for i in range 1 length begin print string right: right co...
# 射气球 class Solution: def findMinArrowShots(self, points: list) -> int: if not points: return 0 # 先按左端点进行排序 points.sort(key=lambda x:x[0]) print('ponits:',points) length = len(points) # right = points[0][1] count = 1 for i in rang...
Python
zaydzuhri_stack_edu_python
import sys from collections import deque set r = readline set tuple N M = map int split call r set board = list for _ in range N begin append board list map int split call r end set wallcnt = 0 for i in range N begin for j in range M begin if board at i at j == 1 begin set wallcnt = wallcnt + 1 end end end set dx = li...
import sys from collections import deque r=sys.stdin.readline N,M=map(int,r().split()) board=[] for _ in range(N): board.append(list(map(int,r().split()))) wallcnt=0 for i in range(N): for j in range(M): if board[i][j]==1: wallcnt+=1 dx=[1,-1,0,0] dy=[0,0,1,-1] visited=[[False]*N for _ in ra...
Python
zaydzuhri_stack_edu_python
from KMeansClustering import KMeansClustering from GaussianMixtureModel import GaussianMixtureModel from sklearn.utils import shuffle from scipy.stats import zscore import pandas as pd function LoadData path begin set dataSet = read csv filepath_or_buffer=path header=none set dataSet = fill missing dataSet 0 set iloc a...
from KMeansClustering import KMeansClustering from GaussianMixtureModel import GaussianMixtureModel from sklearn.utils import shuffle from scipy.stats import zscore import pandas as pd def LoadData(path): dataSet = pd.read_csv(filepath_or_buffer=path, header=None) dataSet = dataSet.fillna(0) dataSet.iloc...
Python
zaydzuhri_stack_edu_python
function _wrap_el self value begin string Convert WebElement Object to {'Element': 1234} Args: value(str|list|dict): The local value. Returns: The wrapped value. if is instance value dict begin return dictionary comprehension k : call _wrap_el v for tuple k v in items value end else if is instance value WebElement begi...
def _wrap_el(self, value): """Convert WebElement Object to {'Element': 1234} Args: value(str|list|dict): The local value. Returns: The wrapped value. """ if isinstance(value, dict): return {k: self._wrap_el(v) for k, v in value.items()} ...
Python
jtatman_500k
function binarySearch arr x begin set l = 0 set h = length arr - 1 while l <= h begin set mid = integer l + h - l / 2 comment Check if x is present at mid if arr at mid == x begin return mid end else comment If x is greater, ignore left half if arr at mid < x begin set l = mid + 1 end else begin comment If x is smaller...
def binarySearch(arr, x): l = 0 h = len(arr) - 1 while l <= h: mid = int(l + (h - l)/2) # Check if x is present at mid if arr[mid] == x: return mid # If x is greater, ignore left half elif arr[mid] < x: l = mid + 1 ...
Python
jtatman_500k
from aa_graphMap_node_simulation import StigmergicGraph import aa_graphMap_node_simulation string Convention: -2 pheromone: exploration. More density -> more explored -1 pheromone: classic distance pheromone placed anywhere 0 -> indices < PHEROMONE_ID_STAGGER: node indices of self.nodes that correspond to candidate hol...
from aa_graphMap_node_simulation import StigmergicGraph import aa_graphMap_node_simulation """ Convention: -2 pheromone: exploration. More density -> more explored -1 pheromone: classic distance pheromone placed anywhere 0 -> indices < PHEROMONE_ID_STAGGER: node indices of self.nodes that cor...
Python
zaydzuhri_stack_edu_python
comment json comment json python comment -------------------------------------- comment {} dict comment [] list comment "string" str comment 123.55 int 或 float comment true/false True/False comment null None import json set d = dictionary name=string Bob age=20 score=88 comment dumps()方法返回一个str 内容是一个标准的json comment 类似的...
#json # json python # -------------------------------------- # {} dict # [] list # "string" str # 123.55 int 或 float # true/false True/False # null None import json d = dict(name =...
Python
zaydzuhri_stack_edu_python
import random from pokemon import Pokemon from trainer import Trainer set __author__ = string @masterfung set BATTLE_WINNER_USER = 0 set BATTLE_WINNER_COMPUTER = 1 set scores = dict
import random from pokemon import Pokemon from trainer import Trainer __author__ = '@masterfung' BATTLE_WINNER_USER = 0 BATTLE_WINNER_COMPUTER = 1 scores = {}
Python
zaydzuhri_stack_edu_python
function sepconv_relu_sepconv inputs filter_size output_size first_kernel_size=tuple 1 1 second_kernel_size=tuple 1 1 padding=string LEFT nonpadding_mask=none dropout=0.0 name=none begin with call variable_scope name string sepconv_relu_sepconv list inputs begin set inputs = call maybe_zero_out_padding inputs first_ker...
def sepconv_relu_sepconv(inputs, filter_size, output_size, first_kernel_size=(1, 1), second_kernel_size=(1, 1), padding="LEFT", nonpadding_mask=None, ...
Python
nomic_cornstack_python_v1
function ndigits x begin string x: An integer, either positive or negative return: the number of digits in inpuit x if x < 0 begin set x = - x end if x < 10 begin return 1 end else begin return 1 + call ndigits x / 10 end end function
def ndigits(x): ''' x: An integer, either positive or negative return: the number of digits in inpuit x ''' if x < 0: x = -x if x < 10: return 1 else: return 1 + ndigits(x/10)
Python
zaydzuhri_stack_edu_python
import cv2 comment now read the video set my_video = call VideoCapture string shortclip.mp4 comment write a loop to show each video frame while true begin set tuple is_it_success my_frame = read my_video 0 if is_it_success == true begin image show string sssup my_frame if call waitKey 48 ? 255 == ordinal string q begin...
import cv2 # now read the video my_video = cv2.VideoCapture('shortclip.mp4') # write a loop to show each video frame while True: is_it_success, my_frame = my_video.read(0) if is_it_success == True: cv2.imshow('sssup', my_frame) if cv2.waitKey(48) & 0xFF == ord('q'): break el...
Python
zaydzuhri_stack_edu_python
function sample_data self indices begin comment transitions sampled randomly from replay buffer set initialized = false for idx in indices begin set batch = call sample_transitions _batch_size if not initialized begin set o = batch at string observations at newaxis set a = batch at string actions at newaxis set r = bat...
def sample_data(self, indices): # transitions sampled randomly from replay buffer initialized = False for idx in indices: batch = self._replay_buffers[idx].sample_transitions( self._batch_size) if not initialized: o = batch['observations'][...
Python
nomic_cornstack_python_v1
function set_dry_run self dry_run begin set dry_run = dry_run end function
def set_dry_run(self, dry_run: bool) -> None: self.dry_run = dry_run
Python
nomic_cornstack_python_v1
comment Definir una función la cual nos permita conocer cuantos dígitos posee un número. comment La función debe tener por nombre _cantidaddigitos. comment La función debe poseer el parámetro numero. comment La función debe retornar la cantidad de dígitos del parámetro. comment No es posible utilizar la función str. co...
# Definir una función la cual nos permita conocer cuantos dígitos posee un número. # La función debe tener por nombre _cantidaddigitos. # La función debe poseer el parámetro numero. # La función debe retornar la cantidad de dígitos del parámetro. # No es posible utilizar la función str. # Ejemplos # >>> cantitdad_dig...
Python
zaydzuhri_stack_edu_python
function sadd self *values begin set values = list comprehension call serialize v for v in call _parse_values values return call sadd key *values end function
def sadd(self, *values): values = [self.serialize(v) for v in _parse_values(values)] return self.redis.sadd(self.key, *values)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python from __future__ import print_function function solve n k begin set dx = list 1 0 - 1 0 set dy = list 0 - 1 0 1 function move x y d begin if x == k and y == n - k begin return 1 end if d == 0 begin return 0 end set sol = 0 for i in range 4 begin set sol = sol + move x + dx at i y + dy at i d - 1...
#!/usr/bin/python from __future__ import print_function def solve(n, k): dx = [ 1, 0, -1, 0] dy = [ 0,-1, 0, 1] def move(x, y, d): if x == k and y == n - k: return 1 if d == 0: return 0 sol = 0 for i in range(4): sol += move(x + dx[i], y + dy[i], d - 1) ...
Python
zaydzuhri_stack_edu_python
function publish_message connection message begin set channel = none try begin set channel = call channel set properties = call BasicProperties keyword call get_properties call basic_publish exchange=AMQP_EXCHANGE routing_key=routing_key properties=properties body=to json message end finally begin if channel and is_ope...
def publish_message(connection, message): channel = None try: channel = connection.channel() properties = pika.BasicProperties(**message.get_properties()) channel.basic_publish( exchange=AMQP_EXCHANGE, routing_key=message.routing_key, properties=pro...
Python
nomic_cornstack_python_v1
function concat str1 str2 begin string Concatenate two strings. Args: str1: The first string str2: The second string Returns: str: The concatenated string return str1 + str2 end function
def concat(str1: str, str2: str) -> str: """Concatenate two strings. Args: str1: The first string str2: The second string Returns: str: The concatenated string """ return str1 + str2
Python
iamtarun_python_18k_alpaca
function traffic_permutation request begin global AVP_MAC NVP_MAC UDP_SPORT SRC_IP DST_IP OUTER_SRC_MAC OUTER_DST_MAC PKT_TYPE comment Values common to all packet types set SRC_IP = VTEP_PEER_IP set DST_IP = S1_LO_IP set OUTER_SRC_MAC = HOST3_MAC set OUTER_DST_MAC = SW_MAC set AVP_MAC = AVP1_MAC comment NVP_MAC updated...
def traffic_permutation(request): global AVP_MAC, NVP_MAC, UDP_SPORT, SRC_IP, DST_IP, OUTER_SRC_MAC,\ OUTER_DST_MAC, PKT_TYPE # Values common to all packet types SRC_IP = VTEP_PEER_IP DST_IP = S1_LO_IP OUTER_SRC_MAC = HOST3_MAC OUTER_DST_MAC = SW_MAC AVP_MAC = AVP1_MAC # NVP_MA...
Python
nomic_cornstack_python_v1
function cleanup_path x begin if x begin set x = replace right strip x sep sep string / end if x == string . begin set x = string end if x begin set x = x + string / end return x end function
def cleanup_path(x): if x: x = x.rstrip(os.path.sep).replace(os.path.sep, '/') if x == '.': x = '' if x: x += '/' return x
Python
nomic_cornstack_python_v1
function test_delete_post_route_auth_redirects_to_home_route testapp csrf_token begin set response = post string /journal/3/delete-entry dict string csrf_token csrf_token set home = path assert ends with location home end function
def test_delete_post_route_auth_redirects_to_home_route(testapp, csrf_token): response = testapp.post("/journal/3/delete-entry", {'csrf_token': csrf_token}) home = testapp.app.routes_mapper.get_route('home').path assert response.location.endswith(home)
Python
nomic_cornstack_python_v1
function merge_dl2_runs data_tag runs columns_to_read=none n_process=4 begin from functools import partial from glob import glob comment Current format of LST data path set filepath_glob = glob string /fefs/aswg/data/real/DL2/*/ { data_tag } /* set pool = pool n_process set filelist = list comment Create a list of fil...
def merge_dl2_runs(data_tag, runs, columns_to_read=None, n_process=4): from functools import partial from glob import glob filepath_glob = glob(f'/fefs/aswg/data/real/DL2/*/{data_tag}/*') # Current format of LST data path pool = Pool(n_process) filelist = [] # Create a list of files with matchi...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding:utf-8 -*- set num = integer input string set list1 = list while num != - 1 begin append list1 num set num = integer input string end sort list1 print list1 insert list1 3 10 print list1 print count list1 10 sort list1 reverse=true print list1
#!/usr/bin/env python3 # -*- coding:utf-8 -*- num = int(input("")) list1 = [] while num != -1: list1.append(num) num = int(input("")) list1.sort() print(list1) list1.insert(3,10) print(list1) print(list1.count(10)) list1.sort(reverse=True) print(list1)
Python
zaydzuhri_stack_edu_python
comment tau comment Input : TB(brightness temperature)(K), comment T0(temperature at groud)(K) comment Output : T(Temperature)(K) function T_m T0 begin return 0.72 * T0 + 70.2 end function from math import log function tau TB T0 begin set Tc = 2.9 set Tm = call T_m T0 set inm = Tm - Tc / Tm - TB set result = log absolu...
# tau # Input : TB(brightness temperature)(K), # T0(temperature at groud)(K) # Output : T(Temperature)(K) def T_m(T0): return 0.72 * T0 + 70.2 from math import log def tau(TB, T0): Tc = 2.9 Tm = T_m(T0) inm = (Tm-Tc) / (Tm-TB) result = log(abs(inm)) return result
Python
zaydzuhri_stack_edu_python
from mongoengine import * from pprint import pprint import datetime call connect string mydb function dd var begin call pprint var exit end function class Cluster extends Document begin set cid = call IntField required=true set avg = call FloatField required=true end class set model = call Cluster set cid = 101 set avg...
from mongoengine import * from pprint import pprint import datetime connect('mydb') def dd(var): pprint(var) exit() class Cluster(Document): cid = IntField(required=True) avg = FloatField(required=True) model = Cluster() model.cid = 101 model.avg = 55 model.save() model = Cluster() model.cid = 102 ...
Python
zaydzuhri_stack_edu_python
function readTest dataTestSet begin with open testingFile string rb as csvfile begin set dataTestList = reader csvfile next dataTestList none set dataSetTest = list dataTestList for y in range length dataSetTest begin set inp = list comment print dataSetTest[y] for x in range 1 11 begin append inp decimal dataSetTest ...
def readTest(dataTestSet) : with open (testingFile, 'rb') as csvfile: dataTestList = csv.reader(csvfile) next(dataTestList, None) dataSetTest = list(dataTestList) for y in range(len(dataSetTest)) : inp = [] # print dataSetTest[y] for x in r...
Python
nomic_cornstack_python_v1
string Examples of using lists in a simple game from random import randint set rolls : list at int = list while length rolls == 0 or rolls at length rolls - 1 != 1 begin append rolls random integer 1 6 end print rolls pop rolls length rolls - 1 print rolls set i : int = 0 set sum : int = 0 while i < length rolls begin ...
"""Examples of using lists in a simple game""" from random import randint rolls: list[int] = list() while len(rolls) == 0 or rolls[len(rolls)-1] != 1: rolls.append(randint(1,6)) print(rolls) rolls.pop(len(rolls)-1) print(rolls) i: int = 0 sum: int = 0 while i < len(rolls): sum = sum + rolls[i] i = i +...
Python
zaydzuhri_stack_edu_python
function get_incoming_set spatial_set direction_set mincosine=1e-08 begin set v = directions set bp = boundary_points_3d set bnorm = boundary_normals set direction_cosines = call tensordot bnorm v axes=list - 1 - 1 set incoming_bolean = direction_cosines < - mincosine set shifts = sum - 1 set stops = cumulative sum shi...
def get_incoming_set(spatial_set, direction_set, mincosine=1e-8): v = direction_set.directions bp = spatial_set.boundary_points_3d bnorm = spatial_set.boundary_normals direction_cosines = tensordot(bnorm, v, axes=[(-1),(-1)]) incoming_bolean = direction_cosines < -mincosine shifts = incomin...
Python
nomic_cornstack_python_v1
function _on_connect client userdata flags rc begin info string Connected with result code { rc } . comment Subscribing in on_connect means that if we lose connection and reconnect comment then subscriptions will be renewed call subscribe string $SYS/# end function
def _on_connect(client: Client, userdata: Any, flags: Any, rc: int): logger.info(f'Connected with result code {rc}.') # Subscribing in on_connect means that if we lose connection and reconnect # then subscriptions will be renewed client.subscribe('$SYS/#')
Python
nomic_cornstack_python_v1
function calibrate_camera_charuco self allCorners allIds imsize begin print string CAMERA CALIBRATION print imsize if imsize at 1 < 1100 begin set cameraMatrixInit = array list list 857.1668 0.0 643.9126 list 0.0 856.0823 387.56018 list 0.0 0.0 1.0 end else begin set cameraMatrixInit = array list list 3819.8801 0.0 191...
def calibrate_camera_charuco(self, allCorners, allIds, imsize): print("CAMERA CALIBRATION") print(imsize) if imsize[1] < 1100: cameraMatrixInit = np.array([[857.1668, 0.0, 643.9126], [0.0, 856.0823, 387.56018], ...
Python
nomic_cornstack_python_v1
class Bmi extends object begin function __init__ self height weight begin set height = height set weight = weight end function function bmiindex self begin return weight / height ^ 2 * 10000 end function function bmiinde2 self begin set score = integer call bmiindex set index = string if score >= 35 begin set index = ...
class Bmi(object): def __init__(self, height, weight): self.height = height self.weight = weight def bmiindex(self): return self.weight / self.height ** 2 * 10000 def bmiinde2(self): score = int(self.bmiindex()) index = '' if score >= 35: index =...
Python
zaydzuhri_stack_edu_python
function load_data self begin set tuple tuple _train_data _train_labels tuple _test_data _test_labels = call load_data set _train_labels = call to_categorical _train_labels set _test_labels = call to_categorical _test_labels return data end function
def load_data(self): ((self._train_data, self._train_labels), (self._test_data, self._test_labels)) = cifar10.load_data() self._train_labels = tf.keras.utils.to_categorical(self._train_labels) self._test_labels = tf.keras.utils.to_categorical(self._test_labels) return self.da...
Python
nomic_cornstack_python_v1
function default begin set model = call DenseNet output_size image_size depth dense_blocks growth_rate filters dropout weight_decay return model end function
def default(): model = DenseNet(mf.output_size, mf.image_size, mf.depth, mf.dense_blocks, mf.growth_rate, mf.filters, mf.dropout, mf.weight_decay) return model
Python
nomic_cornstack_python_v1
import shodan import time import sys set SHODAN_API_KEY = string set api = call Shodan SHODAN_API_KEY set ioc_filename = string netblock.txt function retrieve_api_results query begin set results = search string net:%s % query end function comment Show the results
import shodan import time import sys SHODAN_API_KEY = "" api = shodan.Shodan(SHODAN_API_KEY) ioc_filename = "netblock.txt" def retrieve_api_results(query): results = api.search('net:%s' % query) #Show the results
Python
zaydzuhri_stack_edu_python
function test_circle_area_set begin set c = call Circle 2 with raises AttributeError begin set area = 42 end end function
def test_circle_area_set(): c = Circle(2) with pytest.raises(AttributeError): c.area = 42
Python
nomic_cornstack_python_v1
function puts self str_val begin call _puts encode str_val end function
def puts(self, str_val): self._puts(str_val.encode())
Python
nomic_cornstack_python_v1
function to_dict self base=none begin set base = if expression base then base else dict for i in range min size length _keys begin set base at _keys at i = self at i end return base end function
def to_dict(self, base: Dict[str, Number] = None) -> Dict[str, Number]: base = base if base else {} for i in range(min(self.size, len(self._keys))): base[self._keys[i]] = self[i] return base
Python
nomic_cornstack_python_v1
function __init__ __self__ cluster_name cluster_overrides begin set __self__ string cluster_name cluster_name set __self__ string cluster_overrides cluster_overrides end function
def __init__(__self__, *, cluster_name: pulumi.Input[str], cluster_overrides: pulumi.Input[Sequence[pulumi.Input[Mapping[str, Any]]]]): pulumi.set(__self__, "cluster_name", cluster_name) pulumi.set(__self__, "cluster_overrides", cluster_overrides)
Python
nomic_cornstack_python_v1
function test begin function test_set_params begin set kwargs = dict string model string CDD1 ; string n 0.0013 try begin from import set_params call set_params keyword kwargs end except any begin return false end set status = true for i in _RECOGNIZED_ELEMENTS_ begin if settings at i != call fractional i study=string...
def test(): def test_set_params(): kwargs = { "model": "CDD1", "n": 1.3e-03 } try: from .. import set_params set_params(**kwargs) except: return False status = True for i in _RECOGNIZED_ELEMENTS_: if settings[i] != fractional(i, study = "iwamoto99", **kwargs): status = Fa...
Python
nomic_cornstack_python_v1
string Created on Oct 9, 2014 @author: jiayi lu(jl6583) import sys import math as mt import re from custom_exception import * from operational_functions import * from interval import * from user_interface import * function main begin comment get the input list set interval_list = call getInputList comment Starting to r...
''' Created on Oct 9, 2014 @author: jiayi lu(jl6583) ''' import sys import math as mt import re from custom_exception import * from operational_functions import * from interval import * from user_interface import * def main(): #get the input list interval_list = getInputList() #Starting to receive ...
Python
zaydzuhri_stack_edu_python
function get_jyutping characters begin set result = list for ch in characters begin append result call search_single ch end return result end function
def get_jyutping(characters): result = [] for ch in characters: result.append(search_single(ch)) return result
Python
nomic_cornstack_python_v1
comment 748 最短的完整词 class Solution begin function shortestCompletingWord self licensePlate words begin set newPlate = list comprehension lower i for i in licensePlate if is alpha i comment newPlate = filter(str.isalpha,str(licensePlate.lower())) set words = sorted words key=lambda x -> length x for word in words begin s...
# 748 最短的完整词 class Solution: def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str: newPlate = [ i.lower() for i in licensePlate if i.isalpha()] # newPlate = filter(str.isalpha,str(licensePlate.lower())) words = sorted(words, key=lambda x: len(x)) for w...
Python
zaydzuhri_stack_edu_python
comment M A I N comment ################################################################################ comment cd /media/user/_home1/apps/python/DL/Agri comment cd D:/Apps/Python/DL/Agri import math import numpy as np import h5py import matplotlib.pyplot as plt from tf_utils import load_dataset from sklearn.svm impor...
################################################################################ # # M A I N # # ################################################################################ #cd /media/user/_home1/apps/python/DL/Agri #cd D:/Apps/Python/DL/Agri import math import numpy as np import h5py import matplotlib.pyplot a...
Python
zaydzuhri_stack_edu_python
class Stack begin string Define a stack class with the operations push pop peek is_empty size Chose a built-in python list as data structure for items attribute and the end as the top of the stack. push is O(1) constant time pop is O(1) for removing from the end of a python list peek is O(1) for indexing is_empty is O(...
class Stack: """Define a stack class with the operations push pop peek is_empty size Chose a built-in python list as data structure for items attribute and the end as the top of the stack. push is O(1) constant time pop is O(1) for removing fr...
Python
zaydzuhri_stack_edu_python
from Roll20 import * from Template_dnd4epower import * class _Basic_Attack extends Power_Normal begin string Common Basic Attack w : number of [W] to use (1[W], or 2[W] at 21st level) function __init__ self power_num begin string Initialize self. power_num : the power number used for Power attributes call __init__ self...
from .Roll20 import * from .Template_dnd4epower import * class _Basic_Attack(Power_Normal): """Common Basic Attack w : number of [W] to use (1[W], or 2[W] at 21st level) """ def __init__(self, power_num): """Initialize self. power_num : the power number used for Power attributes ...
Python
zaydzuhri_stack_edu_python
from lojinha import Produto from criador_pedido import CriadorPedido class Loja begin function __init__ self begin set produtos = list end function function get_produtos self begin return produtos end function function cadastrar_produto self nome quantidade begin set novo_produto = call Produto nome call adicionar_est...
from lojinha import Produto from criador_pedido import CriadorPedido class Loja: def __init__(self): self.produtos = [] def get_produtos(self): return self.produtos def cadastrar_produto(self, nome, quantidade): novo_produto = Produto(nome) novo_produto.adicionar_estoque(quantidade) self.produtos.append...
Python
zaydzuhri_stack_edu_python
import os import twitter import pickle import time comment these come from creating a twitter application via dev.twitter.com set CONSUMER_KEY = string see documentation set CONSUMER_SECRET = string see documentation comment file path to twitter credentials set oauth_filename = string twitter_oauth comment check to see...
import os import twitter import pickle import time #these come from creating a twitter application via dev.twitter.com CONSUMER_KEY = "see documentation" CONSUMER_SECRET = "see documentation" #file path to twitter credentials oauth_filename = 'twitter_oauth' #check to see if doesn't exist if not os.path.exists(oauth...
Python
zaydzuhri_stack_edu_python
function __init__ self input_dict=none begin if input_dict is none begin set manager = dict set total_ic = 0 set chemistry = 0 set rating = 0 set strength = 0 set price = 0 set formation = dict end else begin set manager = deep copy input_dict at string manager set total_ic = input_dict at string total_ic set chemist...
def __init__(self, input_dict=None): if input_dict is None: self.manager = {} self.total_ic = 0 self.chemistry = 0 self.rating = 0 self.strength = 0 self.price = 0 self.formation = {} else: self.manager = co...
Python
nomic_cornstack_python_v1
string Prepares training data. Creates .ark files, .htk files, wordList, dict, grammar, and all_labels.mlf. Methods ------- prepare_data import os import sys import glob import argparse import numpy as np import pandas as pd from import create_ark_files , create_htk_files from generate_text_files import generate_text_...
"""Prepares training data. Creates .ark files, .htk files, wordList, dict, grammar, and all_labels.mlf. Methods ------- prepare_data """ import os import sys import glob import argparse import numpy as np import pandas as pd from . import create_ark_files, create_htk_files from .generate_text_files import generate_t...
Python
zaydzuhri_stack_edu_python
import os import sys import board import displayio import supervisor import adafruit_displayio_sh1107 from pockey.app import App from pockey.button import Button from pockey.textcanvas import TextCanvas from pockey.trellis import Trellis call release_displays call disable_autoreload class Pockey begin set PRESSED = 1 s...
import os import sys import board import displayio import supervisor import adafruit_displayio_sh1107 from pockey.app import App from pockey.button import Button from pockey.textcanvas import TextCanvas from pockey.trellis import Trellis displayio.release_displays() supervisor.disable_autoreload() class Pockey: ...
Python
zaydzuhri_stack_edu_python
comment A script to help doing the deliveries. comment Now using the Casava directory structure comment The user is asked to provide a project ID, a run name, and an UPPMAX project import sys , os , yaml , glob , shutil from datetime import datetime import optparse set def_casava_path = string /proj/a2010002/nobackup/i...
# A script to help doing the deliveries. # Now using the Casava directory structure # The user is asked to provide a project ID, a run name, and an UPPMAX project import sys, os, yaml, glob, shutil from datetime import datetime import optparse def_casava_path = '/proj/a2010002/nobackup/illumina/' def_log_path = '/pro...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn comment import torchvision comment import cv2 import numpy as np import string import os import random from convulutional_neural_network import Conv_NeuralNetwork comment Get all the images (numpy arrays) in the said folder and transform them in a normalised PyTorch tensor. comment Gi...
import torch import torch.nn as nn # import torchvision # import cv2 import numpy as np import string import os import random from convulutional_neural_network import Conv_NeuralNetwork # Get all the images (numpy arrays) in the said folder and transform them in a normalised PyTorch tensor. # Gives a list of lists o...
Python
zaydzuhri_stack_edu_python
function remove_task self task begin for tuple i item in enumerate tasks begin if item is task begin del tasks at i end end end function
def remove_task(self, task): for i, item in enumerate(self.tasks): if item is task: del self.tasks[i]
Python
nomic_cornstack_python_v1
function simple self begin return _simple end function
def simple(self) -> bool: return self._simple
Python
nomic_cornstack_python_v1
comment * The Plan class for the <i>materialize</i> operator. comment * @author Edward Sciore from simpledb.materialize.TempTable import TempTable from simpledb.plan.Plan import Plan from simpledb.record.Layout import Layout import math class MaterializePlan extends Plan begin comment * Create a materialize plan for th...
# # * The Plan class for the <i>materialize</i> operator. # * @author Edward Sciore # from simpledb.materialize.TempTable import TempTable from simpledb.plan.Plan import Plan from simpledb.record.Layout import Layout import math class MaterializePlan(Plan): # # * Create a materialize plan for the speci...
Python
zaydzuhri_stack_edu_python
import pygame import math class Rope begin function __init__ self x y r a m begin set x1 = x set y1 = y set r = r set a = a set m = m set point1 = list x1 y1 set acc = 0 set vel = 0 set x2 = integer r * sin a + x1 set y2 = integer r * cos a set point2 = list x2 y2 set color = tuple 255 255 255 end function function sho...
import pygame import math class Rope: def __init__(self, x, y, r, a, m): self.x1 = x self.y1 = y self.r = r self.a = a self.m = m self.point1 = [self.x1, self.y1] self.acc = 0 self.vel = 0 self.x2 = int(self.r * math.sin(self.a)) + self.x1 ...
Python
zaydzuhri_stack_edu_python
function env_yaml_deep_handle key value known_values begin if is instance value list begin set output_list = list for i in range length value begin set v = value at i set output = call env_yaml_deep_handle key v known_values append output_list output end return output_list end else if is instance value dict begin set ...
def env_yaml_deep_handle(key, value, known_values): if isinstance(value, list): output_list = [] for i in range(len(value)): v = value[i] output = env_yaml_deep_handle(key, v, known_values) output_list.append(output) return output_list elif isinstanc...
Python
nomic_cornstack_python_v1
import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestClassifier import matplotlib.pyplot as plt import plotly.graph_obj...
import pandas as pd from sklearn.linear_model import LinearRegression from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error from sklearn.preprocessing import LabelEncoder from sklearn.ensemble import RandomForestClassifier import matplotlib.pyplot as plt import plotly.graph_ob...
Python
zaydzuhri_stack_edu_python
function test_ionq_retrieve monkeypatch mapper_factory begin function mock_retrieve *args **kwargs begin return dict string nq 3 ; string shots 10 ; string output_probs dict string 3 0.4 ; string 0 0.6 ; string meas_mapped list 0 1 ; string meas_qubit_ids list 1 2 end function set attribute _ionq_http_client string ret...
def test_ionq_retrieve(monkeypatch, mapper_factory): def mock_retrieve(*args, **kwargs): return { 'nq': 3, 'shots': 10, 'output_probs': {'3': 0.4, '0': 0.6}, 'meas_mapped': [0, 1], 'meas_qubit_ids': [1, 2], } monkeypatch.setattr(_ionq...
Python
nomic_cornstack_python_v1