code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function flatten_list a result=none begin comment Flattens a nested list. comment flatten_list([ [1, 2, [3, 4] ], [5, 6], 7]) comment [1, 2, 3, 4, 5, 6, 7] if result is none begin set result = list end for x in a begin if is instance x list begin call flatten_list x result end else begin append result x end end return...
def flatten_list(a,result=None): # Flattens a nested list. # flatten_list([ [1, 2, [3, 4] ], [5, 6], 7]) # [1, 2, 3, 4, 5, 6, 7] if result is None: result=[] for x in a: if isinstance(x,list): flatten_list(x,result) else: result.append(x) ret...
Python
zaydzuhri_stack_edu_python
function get_slots self tag begin assert tag in list string ADJ string NP return slots at tag end function
def get_slots(self, tag): assert tag in ["ADJ", "NP"] return self.slots[tag]
Python
nomic_cornstack_python_v1
function create_time self create_time begin set _create_time = create_time end function
def create_time(self, create_time): self._create_time = create_time
Python
nomic_cornstack_python_v1
class User extends object begin function __init__ self name email begin set name = name set email = email set books = dict end function end class
class User(object): def __init__(self, name, email): self.name = name self.email = email self.books = {}
Python
zaydzuhri_stack_edu_python
function add_position_recur lst number_from=0 begin comment base case empty list returns the empty list if lst == list begin return list end else begin set initial_value = lst at 0 return list initial_value + number_from + call add_position_recur lst at slice 1 : : number_from + 1 end end function
def add_position_recur(lst, number_from=0): # base case empty list returns the empty list if lst == []: return [] else: initial_value = lst[0] return [initial_value + number_from] + \ add_position_recur(lst[1:], number_from + 1)
Python
nomic_cornstack_python_v1
comment http://www.ricardonarvaja.info/WEB/EXPLOITING/Nivel%20Basico/013%20stack10.idb/ import struct import subprocess set argv1 = string A set argv2 = string I comment 49 bytes de basura set buf = string I * 49 comment Redirijo eax hacia 0x10101010 que se encuentra en el address space y contiene "\x55\x8b" ebp set va...
# http://www.ricardonarvaja.info/WEB/EXPLOITING/Nivel%20Basico/013%20stack10.idb/ import struct import subprocess argv1 = "A" argv2 = "I" buf = "\x49" * 49 #49 bytes de basura var_8 = struct.pack("<I", 0x10101010) #Redirijo eax hacia 0x10101010 que se encuentra en el address space y contiene "\x55\x8b" ebp var_4 = "Y...
Python
zaydzuhri_stack_edu_python
comment Plotting Script for February 19th Data comment Steven Large comment February 22nd 2017 import matplotlib.pyplot as plt function PlotAllK1 begin set filename1 = string WorkTotal_25_k1.dat set filename2 = string WorkTotal_50_k1.dat set filename3 = string WorkTotal_75_k1.dat set filename4 = string WorkTotal_90_k1....
#Plotting Script for February 19th Data # #Steven Large #February 22nd 2017 import matplotlib.pyplot as plt def PlotAllK1(): filename1 = 'WorkTotal_25_k1.dat' filename2 = 'WorkTotal_50_k1.dat' filename3 = 'WorkTotal_75_k1.dat' filename4 = 'WorkTotal_90_k1.dat' filename5 = 'WorkTotal_95_k1.dat' filename6 = 'Wor...
Python
zaydzuhri_stack_edu_python
function read_opensubs_data dirname max_len=20 fast_preprocessing=true begin set dataset = call OpenSubsData dirname set conversations = call get_conversations return call split_conversations conversations max_len=max_len fast_preprocessing=fast_preprocessing end function
def read_opensubs_data(dirname, max_len=20, fast_preprocessing=True): dataset = OpenSubsData(dirname) conversations = dataset.get_conversations() return split_conversations(conversations, max_len=max_len, fast_preprocessing=fast_preprocessing)
Python
nomic_cornstack_python_v1
function register name factory begin set _formatters at name = factory end function
def register(name: str, factory: Callable[[str], Formatter]) -> None: _formatters[name] = factory
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment Tests for the ReplayDB that will help us connect and test the DB -> DRL connection import time import unittest import logging from ascar import IntfDaemon from ascar import MonitorAgent from ascar import ControlAgent from ascar import ReplayDB from ascar import PythonQLearning from ...
#!/usr/bin/env python #Tests for the ReplayDB that will help us connect and test the DB -> DRL connection import time import unittest import logging from ascar import IntfDaemon from ascar import MonitorAgent from ascar import ControlAgent from ascar import ReplayDB from ascar import PythonQLearning from ascar import...
Python
zaydzuhri_stack_edu_python
function load_configuration opts begin comment Set up a configuration parser with default values set config = call SafeConfigParser call add_section string Simulator set string Simulator string url string http://127.0.0.1:8800 set string Simulator string workload string sawtooth_xo.xo_workload.XoWorkload set string Sim...
def load_configuration(opts): # Set up a configuration parser with default values config = ConfigParser.SafeConfigParser() config.add_section('Simulator') config.set('Simulator', 'url', 'http://127.0.0.1:8800') config.set('Simulator', 'workload', 'sawtooth_xo.xo_workload.XoWorkload') config.set...
Python
nomic_cornstack_python_v1
while true begin set nome = input string Coloque o nome: if nome == string begin break end set alunos at nome = list integer input string nota 1: integer input string nota 2: end set nome = input string Qual o aluno que deseja ver a media? print sum alunos at nome / length alunos at nome
while True: nome = input("Coloque o nome:") if nome == "": break alunos[nome] = [int(input("nota 1: ")), int(input("nota 2: "))] nome = input("Qual o aluno que deseja ver a media?\n") print(sum(alunos[nome])/len(alunos[nome]))
Python
zaydzuhri_stack_edu_python
class Solution begin comment @param num, a list of integer comment @return an integer function maximumGap self num begin if length num < 2 begin return 0 end set num = call radixSort num set res = 0 for i in range 1 length num begin set res = max num at i - num at i - 1 res end return res end function function radixSor...
class Solution: # @param num, a list of integer # @return an integer def maximumGap(self, num): if len(num) < 2: return 0 num = self.radixSort(num) res = 0 for i in range(1, len(num)): res = max(num[i] - num[i - 1], res) return res def rad...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment vim: set ts=2 sw=2 expandtab: from optparse import OptionParser import sys import types import game import shape function main begin set parser = call OptionParser call add_option string -U string --username dest=string username help=string username of login call add_option string -...
#!/usr/bin/env python # vim: set ts=2 sw=2 expandtab: from optparse import OptionParser import sys import types import game import shape def main(): parser = OptionParser() parser.add_option("-U", "--username", dest="username", help="username of login") parser.add_option("-P", "--password",...
Python
zaydzuhri_stack_edu_python
function cast obj begin return call itkNotImageFilterISS2ISS2_cast obj end function
def cast(obj: 'itkLightObject') -> "itkNotImageFilterISS2ISS2 *": return _itkNotImageFilterPython.itkNotImageFilterISS2ISS2_cast(obj)
Python
nomic_cornstack_python_v1
while active begin set name = input string Please tell me your name. if name == string stop begin set active = false end else begin print string Hello, + name + string ! with open file_name string a as file_object begin write file_object name + string end end end
while active: name = input("Please tell me your name.") if name == 'stop': active = False else: print("Hello, " + name + "!\n") with open(file_name, 'a') as file_object: file_object.write(name + "\n")
Python
zaydzuhri_stack_edu_python
from collections import defaultdict class Solution extends object begin function tallestBillboard self rods begin set dp = default dictionary lambda -> 0 set dp at 0 = 0 for i in rods begin for tuple key val in items dp begin set dp at key + i = max dp at key + i val set t = absolute key - i set dp at t = max dp at t ...
from collections import defaultdict class Solution(object): def tallestBillboard(self, rods): dp = defaultdict(lambda: 0) dp[0] = 0 for i in rods: for key, val in dp.items(): dp[key+i] = max(dp[key+i], val) t = abs(key-i) dp[t] = ...
Python
zaydzuhri_stack_edu_python
function convert_bam_to_df data_fp begin set als = list with call AlignmentFile data_fp ignore_truncation=true check_sq=false as bam_fh begin for al in bam_fh begin set tuple cellBC UMI readCount grpFlag = split query_name string _ set seq = query_sequence set qual = query_qualities set encode_qual = call array_to_qua...
def convert_bam_to_df(data_fp: str) -> pd.DataFrame: als = [] with pysam.AlignmentFile( data_fp, ignore_truncation=True, check_sq=False ) as bam_fh: for al in bam_fh: cellBC, UMI, readCount, grpFlag = al.query_name.split("_") seq = al.query_sequence qual =...
Python
nomic_cornstack_python_v1
function __init__ self m g l begin call __init__ self call __init__ self n=2 m=1 set tuple m g l = tuple m g l end function
def __init__(self, m, g, l): AffineDynamics.__init__(self) SystemDynamics.__init__(self,n=2,m=1) self.m, self.g, self.l = m, g, l
Python
nomic_cornstack_python_v1
import os import json import numpy as np from PIL import Image from typing import Callable import torch from torch.utils.data import Dataset function get_iCLEVR_data root_folder mode begin with open join path root_folder string { mode } .json string r as json_file begin set data = load json json_file end with open join...
import os import json import numpy as np from PIL import Image from typing import Callable import torch from torch.utils.data import Dataset def get_iCLEVR_data(root_folder, mode): with open(os.path.join(root_folder, f'{mode}.json'), 'r') as json_file: data = json.load(json_file) with open(os.path.jo...
Python
zaydzuhri_stack_edu_python
from math import sqrt set prime = list true * 100001 set prime at 0 = false set prime at 1 = false for i in range 2 1001 begin if prime at i begin for p in range i * i 100001 i begin set prime at p = false end end end set tt = integer input for _ in range tt begin set inp = list comprehension integer s for s in split i...
from math import sqrt prime = [True]*100001 prime[0] = False prime[1] = False for i in range(2,1001): if prime[i]: for p in range(i*i, 100001, i): prime[p] = False tt = int(input()) for _ in range(tt): inp = [int(s) for s in input().split()] ans = 0 for i in range(inp[0], inp[1]+1)...
Python
zaydzuhri_stack_edu_python
function export_type_to_library self lib name type_obj begin set _name = none if name is not none begin set _name = call QualifiedName name end if not is instance lib TypeLibrary begin raise call TypeError string lib must be a TypeLibrary object end if is instance type_obj str begin set tuple type_obj new_name = call p...
def export_type_to_library(self, lib: typelibrary.TypeLibrary, name: Optional[str], type_obj: StringOrType) -> None: _name = None if name is not None: _name = _types.QualifiedName(name) if not isinstance(lib, typelibrary.TypeLibrary): raise TypeError("lib must be a TypeLibrary object") if isinstance(type_...
Python
nomic_cornstack_python_v1
import math function fuel_needed x begin return x // 3 - 2 end function function total_fuel x begin set fuel_sum = 0 set curr = call fuel_needed x while curr > 0 begin set fuel_sum = fuel_sum + curr set curr = call fuel_needed x end return fuel_sum end function if __name__ == string __main__ begin with open string ../i...
import math def fuel_needed(x): return (x // 3) - 2 def total_fuel(x): fuel_sum = 0 curr = fuel_needed(x) while curr > 0: fuel_sum += curr curr = fuel_needed(x) return fuel_sum if __name__ == "__main__": with open("../input/01-1.txt") as f: answer1 = sum(map(transforma...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import subprocess import sys import time import measure comment ./multiMeasure.py <measurementCount> <outputDirectory> <commands to run one measurement...> function main begin set mCount = integer argv at 1 set outDir = argv at 2 set mCommands = argv at slice 3 : : end function
#!/usr/bin/env python import subprocess import sys import time import measure # ./multiMeasure.py <measurementCount> <outputDirectory> <commands to run one measurement...> def main(): mCount = int(sys.argv[1]) outDir = sys.argv[2] mCommands = sys.argv[3:]
Python
zaydzuhri_stack_edu_python
string MPI allreduce computation, with Horovod. Execution: $ horovodrun -np 10 -H localhost:10 python ../mpi/ex_allreduce.py comment import horovod.keras as hvd import horovod.tensorflow.keras as hvd import numpy as np call init set world = size hvd set rank = integer call rank set D = 100 assert D % world == 0 msg str...
""" MPI allreduce computation, with Horovod. Execution: $ horovodrun -np 10 -H localhost:10 python ../mpi/ex_allreduce.py """ # import horovod.keras as hvd import horovod.tensorflow.keras as hvd import numpy as np hvd.init() world = hvd.size() rank = int(hvd.rank()) D = 100 assert D % world == 0, "world size shoul...
Python
zaydzuhri_stack_edu_python
function on_change original_function begin decorator wraps original_function function decorated *args **kwargs begin string Just run the event. return call original_function *args keyword kwargs end function set attribute decorated string _on_change_event true return decorated end function
def on_change(original_function): @wraps(original_function) def decorated(*args, **kwargs): """Just run the event.""" return original_function(*args, **kwargs) setattr(decorated, "_on_change_event", True) return decorated
Python
nomic_cornstack_python_v1
from django.db import models from django.utils import timezone comment Create your models here. class Habit extends Model begin set name = call CharField max_length=50 set date_added = call DateField default=now set is_important = call BooleanField default=false function __str__ self begin return name end function end ...
from django.db import models from django.utils import timezone # Create your models here. class Habit(models.Model): name = models.CharField(max_length=50) date_added = models.DateField(default=timezone.now) is_important = models.BooleanField(default=False) def __str__(self): return self.name...
Python
zaydzuhri_stack_edu_python
function _get_mpls_label self begin return __mpls_label end function
def _get_mpls_label(self): return self.__mpls_label
Python
nomic_cornstack_python_v1
function read_numeric begin try begin comment read for Python 2.x return decimal call raw_input end except NameError begin comment read for Python 3.x return decimal input end end function set entrada = call read_numeric if entrada >= 0 and entrada <= 25 begin print string Intervalo [0,25] end else if entrada > 25 and ...
def read_numeric(): try: # read for Python 2.x return float(raw_input()) except NameError: # read for Python 3.x return float(input()) entrada = read_numeric() if entrada >= 0 and entrada <= 25: print("Intervalo [0,25]") elif entrada > 25 and entrada <= 50: print("Intervalo (25,50]") elif entr...
Python
zaydzuhri_stack_edu_python
comment Input is a newline-separated list of ZIP codes comment Prints a list of ZIP codes and their miidpoint lat / long to stdout import requests import argparse set GEOCODE_URL = string https://maps.googleapis.com/maps/api/geocode/json?address=USA+06512&key=AIzaSyAisfdc4BXXv8fzte0VpptDSdqHvLybpzg function get_cli_arg...
# Input is a newline-separated list of ZIP codes # Prints a list of ZIP codes and their miidpoint lat / long to stdout import requests import argparse GEOCODE_URL = 'https://maps.googleapis.com/maps/api/geocode/json?address=USA+06512&key=AIzaSyAisfdc4BXXv8fzte0VpptDSdqHvLybpzg' def get_cli_args(): parser = argpa...
Python
zaydzuhri_stack_edu_python
function train self corpus begin comment TODO: Train on each word pass end function
def train(self, corpus): # TODO: Train on each word pass
Python
nomic_cornstack_python_v1
function f n s begin global li while true begin if li at n != s begin pop li n end else begin break end end end function try begin f dist 0 string h f dist 1 string e f dist 2 string i f dist 3 string d f dist 4 string i end except any begin print string NO end try else begin print string YES end
def f(n,s): global li while True: if li[n] != s: li.pop(n) else: break try: f(0,'h') f(1,'e') f(2,'i') f(3,'d') f(4,'i') except: print("NO") else: print("YES")
Python
jtatman_500k
function portals_id_image_folders_rel_fk_delete_with_http_info self id fk **kwargs begin set all_params = list string id string fk append all_params string callback append all_params string _return_http_data_only set params = locals for tuple key val in call iteritems params at string kwargs begin if key not in all_par...
def portals_id_image_folders_rel_fk_delete_with_http_info(self, id, fk, **kwargs): all_params = ['id', 'fk'] all_params.append('callback') all_params.append('_return_http_data_only') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_pa...
Python
nomic_cornstack_python_v1
function _from self _from begin set __from = _from end function
def _from(self, _from): self.__from = _from
Python
nomic_cornstack_python_v1
function test_user_data2 self begin set response_payload = dict string login string agrawalo set fake_session = call MagicMock set fake_response = return_value comment attribute error -- why OP want to mock get_json(), from where? set return_value = response_payload set ud = call get_user_data string agrawalo fake_sess...
def test_user_data2(self): response_payload = {"login": "agrawalo"} fake_session = mock.MagicMock() fake_response = fake_session.get.return_value # attribute error -- why OP want to mock get_json(), from where? fake_response.get_json.return_value = response_payload ud = g...
Python
nomic_cornstack_python_v1
comment Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. comment Example: comment Given a = 1 and b = 2, return 3. comment Credits: comment Special thanks to @fujiaozhu for adding this problem and creating all test cases. class Solution begin comment 下面两种方案 都是 时间超限 , java ...
# Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. # Example: # Given a = 1 and b = 2, return 3. # Credits: # Special thanks to @fujiaozhu for adding this problem and creating all test cases. class Solution: # 下面两种方案 都是 时间超限 , java 可以 原因不明很可能是 Python 的内部原因 # def ge...
Python
zaydzuhri_stack_edu_python
function format_data PATH download=false begin comment iterate over files in directory for file_name in list directory PATH begin comment skip .DS_Store and other hidden files if file_name at 0 == string . begin continue end comment open each JSON file with open PATH + string / + file_name as json_file begin set data =...
def format_data(PATH, download=False): # iterate over files in directory for file_name in listdir(PATH): if file_name[0] == '.': # skip .DS_Store and other hidden files continue # open each JSON file with open(PATH+'/'+file_name) as json_file: data = json.load(js...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sat Jun 1 11:31:38 2019 @author: George import numpy as np import matplotlib.pyplot as plt from sklearn import cluster , datasets , mixture from sklearn.neighbors import kneighbors_graph from itertools import cycle , islice from sklearn.preprocessing import StandardScaler...
# -*- coding: utf-8 -*- """ Created on Sat Jun 1 11:31:38 2019 @author: George """ import numpy as np import matplotlib.pyplot as plt from sklearn import cluster, datasets, mixture from sklearn.neighbors import kneighbors_graph from itertools import cycle, islice from sklearn.preprocessing import StandardScaler fro...
Python
zaydzuhri_stack_edu_python
function fibonacci n begin set a = 0 set b = 1 if n < 0 begin print string Incorrect input end else if n == 0 begin return a end else if n == 1 begin return b end else begin for i in range 2 n begin set c = a + b set a = b set b = c end return b end end function
def fibonacci(n): a = 0 b = 1 if n < 0: print("Incorrect input") elif n == 0: return a elif n == 1: return b else: for i in range(2,n): c = a + b a = b b = c return b
Python
iamtarun_python_18k_alpaca
function tensorflow_version self begin return get pulumi self string tensorflow_version end function
def tensorflow_version(self) -> pulumi.Output[str]: return pulumi.get(self, "tensorflow_version")
Python
nomic_cornstack_python_v1
comment Create tests for functions/classes in firmware.py comment Run this file with "pytest tests.py -v" import unittest import firmware class FirmwareTest extends TestCase begin function setUp self begin pass end function function tearDown self begin pass end function function test_add_integers self begin assert equa...
# # Create tests for functions/classes in firmware.py # Run this file with "pytest tests.py -v" # import unittest import firmware class FirmwareTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_add_integers(self): self.assertEqual(5 + 5, 10)...
Python
zaydzuhri_stack_edu_python
function disable_table self name begin raise call NotImplementedError string The Cloud Bigtable API has no concept of enabled or disabled tables. end function
def disable_table(self, name): raise NotImplementedError('The Cloud Bigtable API has no concept of ' 'enabled or disabled tables.')
Python
nomic_cornstack_python_v1
function _get_all_wgraphs self nvertices nloops nhairs nws begin comment Idea: just take the wgraphs produced above, and attach an extra hair and or an eps tadpole for G in call _get_pre_wgraphs_wk_memo nvertices nloops nhairs nws begin yield G end for G in call _get_pre_wgraphs_wk_memo nvertices nloops nhairs - 1 nws ...
def _get_all_wgraphs(self, nvertices, nloops, nhairs, nws): # Idea: just take the wgraphs produced above, and attach an extra hair and or an eps tadpole for G in self._get_pre_wgraphs_wk_memo(nvertices, nloops, nhairs, nws): yield G for G in self._get_pre_wgraphs_wk_memo(nvertices, n...
Python
nomic_cornstack_python_v1
function gen_input_ix self _exprs index begin set _expr = _exprs at index set ent_vec = call expr_to_vec _expr return call vec_to_ix ent_vec end function
def gen_input_ix(self, _exprs, index): _expr = _exprs[index] ent_vec = self.expr_to_vec(_expr) return self.vec_to_ix(ent_vec)
Python
nomic_cornstack_python_v1
string for each number i in n, we put it as the root node and count all the possibilities G(3) (1,3) + (2,3) + (3,3) G(0)*G(2) G(1)*G(1) G(2)*G(0) class Solution begin function numTrees self n begin set G = call fromkeys range n + 1 0 set G at 0 = 1 set G at 1 = 1 for i in range 2 n + 1 begin for j in range 1 i + 1 beg...
''' for each number i in n, we put it as the root node and count all the possibilities G(3) (1,3) + (2,3) + (3,3) G(0)*G(2) G(1)*G(1) G(2)*G(0) ''' class Solution: def numTrees(self, n) -> int: G = dict.fromkeys(range(n+1),0) G[0] = G[1] = 1 for i in r...
Python
zaydzuhri_stack_edu_python
function draw self begin string 使用draw方法将图形绘制在窗口里 call update_all call draw gl call glLoadIdentity end function
def draw(self): """ 使用draw方法将图形绘制在窗口里 """ self.update_all() self.vertex_list.draw(self.gl) pyglet.gl.glLoadIdentity()
Python
jtatman_500k
class Solution extends object begin function firstMissingPositive self nums begin string :type nums: List[int] :rtype: int set length = length nums for i in range length begin if nums at i <= 0 begin set nums at i = length + 1 end end for i in range length begin if absolute nums at i <= length begin set curr = absolute...
class Solution(object): def firstMissingPositive(self, nums): """ :type nums: List[int] :rtype: int """ length = len(nums) for i in range(length): if nums[i] <= 0: nums[i] = length + 1 for i in range(length): if abs(num...
Python
zaydzuhri_stack_edu_python
from app import db set metadata = call MetaData comment ========================================================================================================= comment таблица, описывающая сущность КВАРТИРА class Flat extends Model begin comment query = db.session.query_property() set __tablename__ = string flat comm...
from app import db metadata = db.MetaData() #========================================================================================================= #таблица, описывающая сущность КВАРТИРА class Flat(db.Model): # query = db.session.query_property() __tablename__ = 'flat' id = db.Column(db.Integer, prima...
Python
zaydzuhri_stack_edu_python
import numpy as np from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier comment Define the hyperparameters to optimize set param_grid = dict string n_estimators array range 2 30 2 ; string max_depth array range 2 12 2 ; string min_samples_leaf array range 1 10 2 comment C...
import numpy as np from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier # Define the hyperparameters to optimize param_grid={ 'n_estimators': np.arange(2, 30, 2), 'max_depth': np.arange(2, 12, 2), 'min_samples_leaf': np.arange(1, 10, 2) } # Create GridSearchCV m...
Python
jtatman_500k
class Score begin function __init__ self begin set score = string 0 end function function plusFiveScore self begin set score = eval score + string 5 return string score end function function plusTenScore self begin set score = eval score + string 10 return string score end function function minusFiveScore self begin se...
class Score: def __init__(self): self.score = "0" def plusFiveScore(self): self.score = eval(self.score + "5") return str(self.score) def plusTenScore(self): self.score = eval(self.score + "10") return str(self.score) def minusFiveScore(self): self.scor...
Python
zaydzuhri_stack_edu_python
import random import stdarray import stdio import sys set moves = integer argv at 1 set n = call readInt call readInt set p = call create2D n n 0.0 for i in range n begin for j in range n begin set p at i at j = call readFloat end end set hits = call create1D n 0 set page = 0 for i in range moves begin set r = random s...
import random import stdarray import stdio import sys moves=int(sys.argv[1]) n=stdio.readInt() stdio.readInt() p=stdarray.create2D(n,n,0.0) for i in range(n): for j in range(n): p[i][j]=stdio.readFloat() hits=stdarray.create1D(n,0) page=0 for i in range(moves): r=random.random() total=0.0 for j in range(0,n): ...
Python
zaydzuhri_stack_edu_python
import pytorch_lightning as pl import pandas as pd from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader import torch import torchvision import os from pathlib import Path class Dataset extends Dataset begin function __init__ self path imgs labels trans=none begin set path = path ...
import pytorch_lightning as pl import pandas as pd from sklearn.model_selection import train_test_split from torch.utils.data import DataLoader import torch import torchvision import os from pathlib import Path class Dataset(torch.utils.data.Dataset): def __init__(self, path, imgs, labels, trans = None...
Python
zaydzuhri_stack_edu_python
function skip_plaintext_padding plaintext_padding begin global intermediate_string global modified_blocks global plaintext_string global current_padding set cur_block_index = length BLOCKS - ARRAY_INDEX - 1 set new_padding = plaintext_padding + 1 set new_padding_chars = character ordinal intermediate_string ? new_paddi...
def skip_plaintext_padding(plaintext_padding): global intermediate_string global modified_blocks global plaintext_string global current_padding cur_block_index = (len(BLOCKS) - ARRAY_INDEX) - 1 new_padding = plaintext_padding + 1 new_padding_chars = chr(ord(intermediate_string) ^ new_padding...
Python
nomic_cornstack_python_v1
function findRecontructMatchingRules self nodeId begin set tokens = call node nodeId assert length tokens > 0 if length tokens == 1 begin return list end set nodeTag = call getTagOfNode nodeId set rc = call Reconstructor ruletable model sense tokens nodeTag set rules = parse rc if rules begin call recordDependentSites...
def findRecontructMatchingRules(self, nodeId): tokens = self.tree.node(nodeId) assert len(tokens) > 0 if len(tokens) == 1: return [] nodeTag = self.getTagOfNode(nodeId) rc = Reconstructor(self.ruletable, self.model, self.sense, tokens, nodeTag) rules = rc.parse() ...
Python
nomic_cornstack_python_v1
function StrLower InputString begin pass end function
def StrLower(InputString) -> str: pass
Python
nomic_cornstack_python_v1
from django.shortcuts import render from django.http import HttpResponse , HttpResponseRedirect from django.views import View from models import Blog from forms import PostForm from django.contrib import messages from django.urls import reverse from django.core.paginator import Paginator , EmptyPage , PageNotAnInteger ...
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.views import View from .models import Blog from .forms import PostForm from django.contrib import messages from django.urls import reverse from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger ...
Python
zaydzuhri_stack_edu_python
from hooks import HOOKS , Hook from utils import build_from_cfg from priority import Priority , get_priority class MyRunner extends object begin string 1.Runner 对象初始化 2.注册各类 Hook 到 Runner 中 3.调用 Runner 的 resume 或者 load_checkpoint 方法对权重进行加载 4.运行给定的工作流,此时才真正开启了工作流 function __init__ self begin pass set _hooks = list end ...
from .hooks import HOOKS, Hook from ..utils import build_from_cfg from .priority import Priority, get_priority class MyRunner(object): ''' 1.Runner 对象初始化 2.注册各类 Hook 到 Runner 中 3.调用 Runner 的 resume 或者 load_checkpoint 方法对权重进行加载 4.运行给定的工作流,此时才真正开启了工作流 ''' def __init__(self ): pass ...
Python
zaydzuhri_stack_edu_python
import math import random from turtle import * set wesley = call Turtle set tatem = call Turtle set olivia = call Turtle set courtney = call Turtle set veronica = call Turtle set liam = call Turtle set tyler = call Turtle set emma = call Turtle call speed 50 call penup call goto 0 0 call pendown call setheading 90 call...
import math import random from turtle import * wesley = Turtle() tatem = Turtle() olivia = Turtle() courtney = Turtle() veronica = Turtle() liam = Turtle() tyler = Turtle() emma = Turtle() wesley.speed(50) wesley.penup() wesley.goto(0,0) wesley.pendown() wesley.setheading(90) wesley.color('blue') ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np set avgStd = list list list set avgOur = list list 67857 64202 61656 64463 61698 list 184 184 190 183 185 set avgOld = list list 237392 238268 238268 238817 239878 list 237392 157959 158088 158865 159119
import matplotlib.pyplot as plt import numpy as np avgStd = [ [], [] ] avgOur = [ [67857, 64202, 61656, 64463, 61698], [184, 184, 190, 183, 185] ] avgOld = [ [237392, 238268, 238268, 238817, 239878], [237392, 157959, 158088, 158865, 159119] ]
Python
zaydzuhri_stack_edu_python
function run self begin comment () -> None for tuple name scenario in items test_scenarios begin run name end end function
def run(self): # () -> None for name, scenario in self.test_scenarios.items(): scenario.run(name)
Python
nomic_cornstack_python_v1
function get_video_links_from_youtube_api key service=string youtube version=string v3 begin set youtube = call build service version developerKey=YOUTUBE_API_KEY set request = list part=string snippet type=string video order=string date q=key set response = execute request set video_urls = list for item in response a...
def get_video_links_from_youtube_api(key, service='youtube', version='v3'): youtube = build(service, version, developerKey=settings.YOUTUBE_API_KEY) request = youtube.search().list( part='snippet', type='video', order='date', q=key, ) response = request.execute() v...
Python
nomic_cornstack_python_v1
function handle_script self http_context begin set data = call json_body try begin set p = popen list string bash string -c data at string script stdout=PIPE stderr=PIPE close_fds=true set tuple o e = communicate p get data string input none end except CalledProcessError as e begin raise call EndpointError e end except...
def handle_script(self, http_context): data = http_context.json_body() try: p = subprocess.Popen( ['bash', '-c', data['script']], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True ) o, e = p...
Python
nomic_cornstack_python_v1
function num_interaction_features self begin return __proxy__ at string num_interaction_features end function
def num_interaction_features(self): return self.__proxy__['num_interaction_features']
Python
nomic_cornstack_python_v1
comment conunting lines for spliting with open string trainingData.data string r as file_data begin set count = sum generator expression 1 for line in file_data set part = count / 10 end
#conunting lines for spliting with open("trainingData.data", 'r') as file_data: count = sum(1 for line in file_data) part = count / 10
Python
zaydzuhri_stack_edu_python
function test_one_item self begin set argument = call is_sorted list 1 set expected = true assert equal expected argument string The list has one item. end function
def test_one_item(self): argument = is_sorted([1]) expected = True self.assertEqual(expected, argument, "The list has one item.")
Python
nomic_cornstack_python_v1
function findFringesInScan self fsu=string FSUB plot=false calibrated=true begin set fringes_pos = list set weight = list if plot begin figure 0 call clf title plt filename + string | + fsu + string | + insmode x label string OPD + DLtrack + string (m) end for k in range scan_nscans begin set x = call getScan k isola...
def findFringesInScan(self, fsu='FSUB', plot=False, calibrated=True): fringes_pos = [] weight = [] if plot: plt.figure(0) plt.clf() plt.title(self.filename+' | '+fsu+' | '+self.insmode) plt.xlabel('OPD '+self.DLtrack+' (m)') for k in rang...
Python
nomic_cornstack_python_v1
function iid_sample sample_fn sample_shape begin set sample_shape = call expand_to_vector call cast sample_shape int32 tensor_name=string sample_shape set n = call cast call reduce_prod sample_shape dtype=int32 set static_n = call get_static_value call convert_to_tensor n function unflatten x begin set sample_dims = if...
def iid_sample(sample_fn, sample_shape): sample_shape = distribution_util.expand_to_vector( ps.cast(sample_shape, np.int32), tensor_name='sample_shape') n = ps.cast(ps.reduce_prod(sample_shape), dtype=np.int32) static_n = tf.get_static_value(tf.convert_to_tensor(n)) def unflatten(x): sample_dims = 0 ...
Python
nomic_cornstack_python_v1
function to_one_hot y n_dims=none begin set y_tensor = if expression is instance y Variable then data else y set y_tensor = view type LongTensor - 1 1 set n_dims = if expression n_dims is not none then n_dims else integer max y_tensor + 1 set y_one_hot = call scatter_ 1 y_tensor 1 set y_one_hot = view y_one_hot *y.shap...
def to_one_hot(y, n_dims=None): y_tensor = y.data if isinstance(y, Variable) else y y_tensor = y_tensor.type(torch.LongTensor).view(-1, 1) n_dims = n_dims if n_dims is not None else int(torch.max(y_tensor)) + 1 y_one_hot = torch.zeros(y_tensor.size()[0], n_dims).scatter_(1, y_tensor, 1) y_one_hot = ...
Python
nomic_cornstack_python_v1
import json import random import sys from math import ceil from numbers import Number from tkinter import ALL from typing import Callable , Dict , Iterable , List , Set , Tuple from pyparsing import col set INDENT : str = string * 4 set LONG : int = 20 set ANY_COLOR : str = string ! set ANY_THING : str = string ? set ...
import json import random import sys from math import ceil from numbers import Number from tkinter import ALL from typing import Callable, Dict, Iterable, List, Set, Tuple from pyparsing import col INDENT: str = ' '*4 LONG: int = 20 ANY_COLOR: str = '!' ANY_THING: str = '?' UNDECIDED: List[str] = [ANY_THING, ANY_COLO...
Python
zaydzuhri_stack_edu_python
function filter_test self filt begin return dictionary comprehension char : call permits char for char in char_list + classes end function
def filter_test(self, filt): return { char: filt.permits(char) for char in self.char_list + self.classes }
Python
nomic_cornstack_python_v1
import pygame function duckimage begin set duckpic = load image string duckhunt/bird.gif call scale duckpic tuple 30 30 call blit image tuple 600 600 end function
import pygame def duckimage(): duckpic = pygame.image.load(r"duckhunt/bird.gif") pygame.transform.scale(duckpic, (30, 30)) display_surface.blit(image, (600, 600))
Python
zaydzuhri_stack_edu_python
function is_tic self begin return string I don't know how to find this yet end function
def is_tic(self): return "I don't know how to find this yet"
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python import argparse import re import sys set parser = call ArgumentParser description=string Flatten TH2s to TH1s. call add_argument string inputs metavar=string input nargs=string + help=string The ROOT input file containing histograms call add_argument string -r string --regex metavar=string...
#! /usr/bin/env python import argparse import re import sys parser = argparse.ArgumentParser(description='Flatten TH2s to TH1s.') parser.add_argument('inputs', metavar='input', nargs='+', help='The ROOT input file containing histograms') parser.add_argument('-r', '--regex', metavar='myHist_.*', nargs='+', help='Rege...
Python
zaydzuhri_stack_edu_python
from game import GameListener from OpenGL.GL import * class GLRenderer extends GameListener begin function __init__ self game begin set _game = game call glClearColor 1.0 1.0 1.0 1.0 end function function update self begin pass end function function render self begin call glClear GL_COLOR_BUFFER_BIT for tan in _game be...
from game import GameListener from OpenGL.GL import * class GLRenderer(GameListener): def __init__(self, game): self._game = game glClearColor(1.0, 1.0, 1.0, 1.0) def update(self): pass def render(self): glClear(GL_COLOR_BUFFER_BIT) for tan in self._game: if tan.is_selected(): glColor(0.3,...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python comment Author: (c) David Marques, June 1, 2016, Victoria BC, Canada comment Written for Python 3.4.3 comment Changelog: comment 2016-09-21: adapted to loop across array of window SFS import argparse , os import numpy as np set parser = call ArgumentParser description=string dxy from two a...
#! /usr/bin/env python # Author: (c) David Marques, June 1, 2016, Victoria BC, Canada # Written for Python 3.4.3 # Changelog: # 2016-09-21: adapted to loop across array of window SFS import argparse, os import numpy as np parser=argparse.ArgumentParser(description='dxy from two angsd .saf.idx files and one bed file ...
Python
zaydzuhri_stack_edu_python
function unAuthorizedClientCall self begin set client = call client string s3 config=call Config signature_version=UNSIGNED return client end function
def unAuthorizedClientCall(self): client = boto3.client("s3", config=botocore.config.Config(signature_version=botocore.UNSIGNED)) return(client)
Python
nomic_cornstack_python_v1
import os from unittest import TestCase from outline.outline import Outline from outline.outline_node import OutlineNode import tests.test_utilities.test_config as tcfg class TestOutlineNode extends TestCase begin set local_path = join path string outline string outline_node set test_outline = join path input_files_roo...
import os from unittest import TestCase from outline.outline import Outline from outline.outline_node import OutlineNode import tests.test_utilities.test_config as tcfg class TestOutlineNode(TestCase): local_path = os.path.join('outline', 'outline_node') test_outline = os.path.join(tcfg.input_files_root, loca...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Oct 22 17:12:44 2020 @author: Rodrigo set emails = list set labels = list set namen = list set email_text = list set text = string set P = list import pandas as pd import email as ml from sklearn.model_selection import train_test_split from sklearn.feature_extra...
# -*- coding: utf-8 -*- """ Created on Thu Oct 22 17:12:44 2020 @author: Rodrigo """ emails=[] labels=[] namen=[] email_text=[] text = "" P = [] import pandas as pd import email as ml from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer import numpy as np fr...
Python
zaydzuhri_stack_edu_python
async function _queue self ctx page=1 begin if length songs == 0 begin return await call send string Empty queue. end set items_per_page = 10 set pages = ceil length songs / items_per_page set start = page - 1 * items_per_page set end = start + items_per_page set queue = string for tuple i song in enumerate songs at s...
async def _queue(self, ctx: commands.Context, *, page: int = 1): if len(ctx.voice_state.songs) == 0: return await ctx.send('Empty queue.') items_per_page = 10 pages = math.ceil(len(ctx.voice_state.songs) / items_per_page) start = (page - 1) * items_per_page end = s...
Python
nomic_cornstack_python_v1
function _search self node term i begin if not term begin comment No search term, no results return set end if i == length term begin comment We hit the end of the search term, everything at comment the current node is a match for the term return call get_elements end set char = term at i set children = call get_childr...
def _search(self, node, term, i): if not term: # No search term, no results return set() if i == len(term): # We hit the end of the search term, everything at # the current node is a match for the term return node.get_elements() char ...
Python
nomic_cornstack_python_v1
function getThumbnailPath self filePath begin set thumbnailDir : str = config at string fileStorage at string thumbnailPath set thumbnailPath : str = thumbnailDir + base name path filePath return thumbnailPath end function
def getThumbnailPath(self, filePath: str) -> str: thumbnailDir: str = self.config["fileStorage"]["thumbnailPath"] thumbnailPath: str = thumbnailDir + os.path.basename(filePath) return thumbnailPath
Python
nomic_cornstack_python_v1
comment Python Program to find Largest of Three Numbers using Elif Statement set e = decimal input string Please Enter the First value: set f = decimal input string Please Enter the First value: set g = decimal input string Please Enter the First value: if e > f and e > g begin print format string {0} is Greater Than b...
# Python Program to find Largest of Three Numbers using Elif Statement e = float(input("Please Enter the First value: ")) f = float(input("Please Enter the First value: ")) g = float(input("Please Enter the First value: ")) if (e > f and e > g): print("{0} is Greater Than both {1} and {2}". format(e, f, g))...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Oct 14 19:33:43 2015 @author: root import numpy as np import Helpers as helpers from scipy.interpolate import RegularGridInterpolator class ProductionInventoryModel begin string states and control format s,p,q,x = s[0],s[1],a[0],a[1] --- state --- s - stock inventory ...
# -*- coding: utf-8 -*- """ Created on Wed Oct 14 19:33:43 2015 @author: root """ import numpy as np import Helpers as helpers from scipy.interpolate import RegularGridInterpolator class ProductionInventoryModel: ''' states and control format s,p,q,x = s[0],s[1],a[0],a[1] --- state --- s - s...
Python
zaydzuhri_stack_edu_python
function _generate_literal literal_type begin seed 0 set m = search string bits\[(\d+)\]$ literal_type if m begin return call _random_bits_value integer call group 1 end else begin set m = search string bits\[(\d+)\]\[(\d+)\]$ literal_type if not m begin raise call ValueError string Invalid or unsupported type { litera...
def _generate_literal(literal_type: str) -> str: random.seed(0) m = re.search(r'bits\[(\d+)\]$', literal_type) if m: return _random_bits_value(int(m.group(1))) else: m = re.search(r'bits\[(\d+)\]\[(\d+)\]$', literal_type) if not m: raise ValueError(f'Invalid or unsupported type {literal_type}'...
Python
nomic_cornstack_python_v1
import math class Solution begin comment @param A : integer comment @return a list of integers function sieve self A begin set x = list none * A + 1 set res = list for i in range 2 A + 1 begin if x at i == false begin continue end else begin set x at i = call isPrime i if x at i begin set j = 2 while j * i < A begin s...
import math class Solution: # @param A : integer # @return a list of integers def sieve(self, A): x = [None]*(A+1) res = [] for i in range(2,A+1): if x[i] == False: continue else: x[i] = self.isPrime(i) if x[i]:...
Python
zaydzuhri_stack_edu_python
string A simple program that asks for name, age and address. The details entered will be displayed in a certain format at the end. comment These variables are for the needed details set name = input string Enter your name: set age = input string Enter your age: set address = input string Enter your address: comment Thi...
""" A simple program that asks for name, age and address. The details entered will be displayed in a certain format at the end. """ #These variables are for the needed details name = input('Enter your name: ') age = input('Enter your age: ') address = input('Enter your address: ') #This statement displays the details...
Python
zaydzuhri_stack_edu_python
function test_delete1 self begin pass end function
def test_delete1(self): pass
Python
nomic_cornstack_python_v1
string Input data will contain in the first line the number of triplets to follow. Next lines will contain one triplet each. Answer should contain selected minimums of triplets, separated by spaces. Example: data: 3 7 3 5 15 20 40 300 550 137 answer: 3 15 137 set tuple n list = tuple integer input list for i in range ...
''' Input data will contain in the first line the number of triplets to follow. Next lines will contain one triplet each. Answer should contain selected minimums of triplets, separated by spaces. Example: data: 3 7 3 5 15 20 40 300 550 137 answer: 3 15 137 ''' n, list = int(input()), [] for i in range(n): x = ...
Python
zaydzuhri_stack_edu_python
function train_generator_fn xs bs ys begin for tuple x b y in zip xs bs ys begin comment the key in the following dictionary comment should be identical to the key of the output_types and output_shapes comment in the train_input_fn. set features = dict string x x ; string b b ; string y y yield features end end functio...
def train_generator_fn(xs, bs, ys): for (x, b, y) in zip(xs, bs, ys): # the key in the following dictionary # should be identical to the key of the output_types and output_shapes # in the train_input_fn. features = {'x': x, 'b': b, 'y': y} yield features
Python
nomic_cornstack_python_v1
function read_image path begin set image = call imread path set image = call cvtColor image COLOR_BGR2RGB return image end function
def read_image(path): image = cv2.imread(path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) return image
Python
nomic_cornstack_python_v1
async function _show_form self errors=none begin return call async_show_form step_id=string user data_schema=cloud_api_schema errors=errors or dict end function
async def _show_form(self, errors=None): return self.async_show_form( step_id="user", data_schema=self.cloud_api_schema, errors=errors or {}, )
Python
nomic_cornstack_python_v1
function combine x y begin set deleteX = true set deleteY = true set merge = false set workout = list for i in range length x begin if x at i != y at i begin if x at i == string * begin append workout y at i set deleteX = false end else if y at i == string * begin append workout x at i set deleteY = false end else if ...
def combine(x,y): deleteX = True deleteY = True merge = False workout = [] for i in range(len(x)): if x[i] != y[i]: if x[i] == '*': workout.append(y[i]) deleteX = False elif y[i] == '*': workout.append(x[i]) ...
Python
nomic_cornstack_python_v1
function Display num begin for i in range 1 num + 1 1 begin for j in range 1 num + 1 1 begin print j end=string end print end end function function main begin set no = integer input string Enter a number call Display no end function if __name__ == string __main__ begin call main end
def Display(num): for i in range(1,num+1,1): for j in range(1,num+1,1): print(j,end=' ') print() def main(): no=int(input("Enter a number")) Display(no) if(__name__=="__main__"): main()
Python
zaydzuhri_stack_edu_python
function turn self begin pass end function
def turn(self): pass
Python
nomic_cornstack_python_v1
import sys set stdin = open string input.txt set T = 10 for _ in range 1 T + 1 begin set tc = integer input comment 16 * 16 미로 set miro = list comprehension list map int input for _ in range 16 comment print(miro) comment 델타 set dr = list - 1 1 0 0 set dc = list 0 0 - 1 1 set queue = list set visited = list set res =...
import sys sys.stdin = open("input.txt") T = 10 for _ in range(1, T+1): tc = int(input()) # 16 * 16 미로 miro = [list(map(int, input())) for _ in range(16)] # print(miro) # 델타 dr = [-1, 1, 0, 0] dc = [0, 0, -1, 1] queue = [] visited = [] res = 0 # 2를 찾자 for i in range(...
Python
zaydzuhri_stack_edu_python
function predict self Xtest nn_list begin comment calculate distances first call dist_calc Xtest set ypred = list for nn in nn_list begin set neigh_ind = ind at tuple slice : : slice 0 : nn : if weights == string uniform begin set p = mean np ytrain at neigh_ind axis=1 end else if weights == string distance begin ...
def predict(self,Xtest,nn_list): #calculate distances first self.dist_calc(Xtest) ypred = [] for nn in nn_list: neigh_ind = self.ind[:,0:nn] if self.weights == 'uniform': p = np.mean(self.ytrain[neigh_ind], axis=1) elif self.weig...
Python
nomic_cornstack_python_v1
function __int__ self begin set key_val = call _ValueOrPrimary key if not is instance key_val tuple int long begin comment We should not truncate floating point numbers. comment Nor turn strings of numbers into an integer. raise call ValueError string The primary key is not an integral number. end return key_val end fu...
def __int__(self): key_val = self._ValueOrPrimary(self.key) if not isinstance(key_val, (int, long)): # We should not truncate floating point numbers. # Nor turn strings of numbers into an integer. raise ValueError('The primary key is not an integral number.') return key_val
Python
nomic_cornstack_python_v1
comment Nathan Hinton comment This is the file for the platforms import pygame class Platform begin function __init__ self display pos width height color begin set display = display set tuple x y = pos set width = width set height = height set color = color set rect = call Rect x y width height end function function ru...
##Nathan Hinton ##This is the file for the platforms import pygame class Platform: def __init__(self, display, pos, width, height, color): self.display = display self.x, self.y = pos self.width = width self.height = height self.color = color self.rect = pygame.Rect(...
Python
zaydzuhri_stack_edu_python
function provide self cls begin string Provides an instance of the given class. Args: cls: a class (not an instance) Returns: an instance of cls Raises: Error: an instance of cls is not providable call verify_class_type cls string cls if not call _is_injectable_fn cls begin set provide_loc = call get_back_frame_loc rai...
def provide(self, cls): """Provides an instance of the given class. Args: cls: a class (not an instance) Returns: an instance of cls Raises: Error: an instance of cls is not providable """ support.verify_class_type(cls, 'cls') if not...
Python
jtatman_500k
function test_cv_gradients_gaussian_circuit self G O gaussian_dev tol begin set tol = 1e-05 set par = list 0.4 function circuit x begin set args = list 0.3 * num_params set args at 0 = x call Displacement 0.5 0 wires=0 call G *args wires=range num_wires call Beamsplitter 1.3 - 2.3 wires=list 0 1 call Displacement - 0.5...
def test_cv_gradients_gaussian_circuit(self, G, O, gaussian_dev, tol): tol = 1e-5 par = [0.4] def circuit(x): args = [0.3] * G.num_params args[0] = x qml.Displacement(0.5, 0, wires=0) G(*args, wires=range(G.num_wires)) qml.Beamsplitte...
Python
nomic_cornstack_python_v1