code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function scansion self meter=none conscious=false begin string Print out the parses and their violations in scansion format. set meter = call get_meter meter call scansion_prepare meter=meter conscious=conscious end function
def scansion(self,meter=None,conscious=False): """Print out the parses and their violations in scansion format.""" meter=self.get_meter(meter) self.scansion_prepare(meter=meter,conscious=conscious)
Python
jtatman_500k
from Bio import SeqIO for i in parse SeqIO string arquivo.fasta string fasta begin print id print seq print length i end comment Fizemos a leitura dos dados do arquivo: "arquivo.fasta" e imprimos algumas informações.
from Bio import SeqIO for i in SeqIO.parse("arquivo.fasta","fasta"): print(i.id) print(i.seq) print(len(i)) # Fizemos a leitura dos dados do arquivo: "arquivo.fasta" e imprimos algumas informações.
Python
zaydzuhri_stack_edu_python
function soma x y begin print x + y end function call soma 10 5 set soma = lambda x y -> x + y
def soma(x, y): print(x + y) soma(10, 5) soma = lambda x, y: x + y
Python
zaydzuhri_stack_edu_python
function test_rmat_edgelist scale mg begin if mg and _is_single_gpu begin skip string skipping MG testing on Single GPU system end set num_edges = 2 ^ scale * 4 comment Returns the edgelist from RMAT set create_using = none set df = call _call_rmat scale num_edges create_using mg if mg begin assert npartitions == lengt...
def test_rmat_edgelist(scale, mg): if mg and _is_single_gpu: pytest.skip("skipping MG testing on Single GPU system") num_edges = (2**scale)*4 create_using = None # Returns the edgelist from RMAT df = _call_rmat(scale, num_edges, create_using, mg) if mg: assert df.npartitions == l...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 import numpy as np comment for black image zeros tuple 400 300 comment for white image call full tuple 400 300 255 comment gan library for face recognition call system string pip3 install opencv-contrib-python import cv2 comment only for collab comment import matplotli...
#!/usr/bin/env python # coding: utf-8 import numpy as np np.zeros((400,300))# for black image np.full((400,300),255)#for white image #gan library for face recognition get_ipython().system('pip3 install opencv-contrib-python') import cv2 #only for collab #import matplotlib.pyplot as plt print(cv2.__version__) ...
Python
zaydzuhri_stack_edu_python
function compute_ppmi a begin call fill_diagonal a 0 set a = call my_scale_sim_mat a set tuple p q = call shape a set col = sum a axis=0 set col at col == 0 = 1 set ppmi = log decimal p * a / col at tuple none slice : : set idx_nan = call isnan ppmi set ppmi at idx_nan = 0 set ppmi at ppmi < 0 = 0 return ppmi end fun...
def compute_ppmi(a): np.fill_diagonal(a, 0) a = my_scale_sim_mat(a) (p, q) = np.shape(a) col = np.sum(a, axis=0) col[col == 0] = 1 ppmi = np.log((float(p)*a)/col[None, :]) idx_nan = np.isnan(ppmi) ppmi[idx_nan] = 0 ppmi[ppmi < 0] = 0 return ppmi
Python
nomic_cornstack_python_v1
function normalise_addr self addr begin if string - in addr begin set tuple a1 a2 = split addr string - set o1 = split strip a1 string . set o2 = split strip a2 string . return string %s-%s % tuple join string . list comprehension string integer i for i in o1 join string . list comprehension string integer i for i in o...
def normalise_addr(self, addr): if '-' in addr: (a1, a2) = addr.split('-') o1 = a1.strip().split('.') o2 = a2.strip().split('.') return '%s-%s' % ('.'.join([str(int(i)) for i in o1]), '.'.join([str(int(i)) for i in o2])) ...
Python
nomic_cornstack_python_v1
function trim_req req begin set reqfirst = next iterate req if string . in reqfirst begin return dict split reqfirst string . at 0 req at reqfirst end return req end function
def trim_req(req): reqfirst = next(iter(req)) if "." in reqfirst: return {reqfirst.split(".")[0]: req[reqfirst]} return req
Python
nomic_cornstack_python_v1
comment import unittest module import unittest comment import all classes we used from aungierRental import Car , DieselCar , ElectricCar , HybridCar , PetrolCar , AungierRental comment test class, inherits from unittest module class TestAungierCar extends TestCase begin comment set up instances for use in testing func...
#import unittest module import unittest #import all classes we used from aungierRental import Car, DieselCar, ElectricCar, HybridCar, PetrolCar, AungierRental #test class, inherits from unittest module class TestAungierCar(unittest.TestCase): #set up instances for use in testing def setUp(self): ...
Python
zaydzuhri_stack_edu_python
from grammars import yacc import cmd class dbms extends Cmd begin function __init__ self begin call __init__ self set prompt = string DBMS > end function function onecmd self line begin parse yacc line end function end class if __name__ == string __main__ begin print string 基于Python的小型dbms print string 学号:17030130021 姓...
from grammars import yacc import cmd class dbms(cmd.Cmd): def __init__(self): cmd.Cmd.__init__(self) self.prompt = 'DBMS > ' def onecmd(self, line): yacc.parse(line) if __name__ == '__main__': print("基于Python的小型dbms") print("学号:17030130021 姓名:张维越") dbms().cmdloop()
Python
zaydzuhri_stack_edu_python
function test_background begin comment Create a Background instance set test_background = call Background comment Create a VTK Render Window to display the video capture set renWin = call vtkRenderWindow comment Set Window Size with the camera actual resolution call SetSize *test_background.size comment Link the Render...
def test_background(): # Create a Background instance test_background = Background() # Create a VTK Render Window to display the video capture renWin = vtk.vtkRenderWindow() # Set Window Size with the camera actual resolution renWin.SetSize(*test_background.size) # Link the Render to the...
Python
nomic_cornstack_python_v1
string Created on Sun Nov 24 14:09:49 2019 @author: jakei import random as rand import time as time set Deck = list 0 0 0 0 2 2 2 2 3 3 3 3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7 8 8 8 8 9 9 9 9 10 10 10 10 11 11 11 11 12 12 12 12 13 13 - 1 - 1 set PlayerCards = list set PlayerKnownCards = list set PlayerUnknownCards = list...
""" Created on Sun Nov 24 14:09:49 2019 @author: jakei """ import random as rand import time as time Deck = [0,0,0,0,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,-1,-1] PlayerCards = [] PlayerKnownCards = [] PlayerUnknownCards = [] Scores ...
Python
zaydzuhri_stack_edu_python
function forget_dead_hosts self begin for s in servers begin set deaduntil = 0 end end function
def forget_dead_hosts(self): for s in self.servers: s.deaduntil = 0
Python
nomic_cornstack_python_v1
function extract_epub_info self begin set soup = call parse_page url call find_volume_name_number soup call find_author_illustrator soup call find_introduction soup call find_cover_url soup set chapters_links = call find_chapter_links soup end function
def extract_epub_info(self): soup = self.parse_page(self.url) self.find_volume_name_number(soup) self.find_author_illustrator(soup) self.find_introduction(soup) self.find_cover_url(soup) self.chapters_links = self.find_chapter_links(soup)
Python
nomic_cornstack_python_v1
import pygame import time call init set bgcolor = tuple 147 166 180 set button_color = tuple 255 255 255 set hover_color = tuple 216 216 216 set press_color = tuple 192 192 192 set logo = load image string logo.png set pattern = load image string line.png set title_font = call SysFont string Courier 40 set small_font =...
import pygame import time pygame.init() bgcolor = (147,166,180) button_color = (255,255,255) hover_color = (216,216,216) press_color = (192,192,192) logo = pygame.image.load("logo.png") pattern = pygame.image.load("line.png") title_font = pygame.font.SysFont('Courier', 40) small_font = pygame.font.SysFont('Courier',18...
Python
zaydzuhri_stack_edu_python
function num_deriv_exterior cal cpar dpos dang pos begin set var = list x0 y0 z0 omega phi kappa set x_ders = zeros 6 set y_ders = zeros 6 set ext_par = call rotation_matrix ext_par set tuple xs ys = call img_coord pos cal mm for pd in range 6 begin set step = if expression pd > 2 then dang else dpos set var at pd = va...
def num_deriv_exterior( cal: Calibration, cpar: ControlPar, dpos: float, dang: float, pos: vec3d ): var = [ cal.ext_par.x0, cal.ext_par.y0, cal.ext_par.z0, cal.ext_par.omega, cal.ext_par.phi, cal.ext_par.kappa, ] x_ders = np.zeros(6) y_ders = np.zeros(...
Python
nomic_cornstack_python_v1
function prime n begin if n == 2 begin return true end if n % 2 == 0 or n <= 1 begin return false end end function set eqlCounter = 0 set octals = list set smallest = 99 with open string D:\matura\Matura2017\Dane_PR2\liczby.txt string r as f begin for x in f begin set lines = read line f set splited = split lines comm...
def prime(n): if n == 2: return True if n % 2 == 0 or n <= 1: return False eqlCounter = 0 octals = [] smallest = 99 with open("D:\matura\Matura2017\Dane_PR2\liczby.txt", "r") as f: for x in f: lines = f.readline() splited = lines.split() toInt = int(splite...
Python
zaydzuhri_stack_edu_python
function _represent_ZGate self basis **options begin set _format = get options string format string sympy set n = 1 set definite_state = 0 for it in reversed qubit_values begin set definite_state = definite_state + n * it set n = n * 2 end set result = list 0 * 2 ^ dimension set result at integer definite_state = 1 if ...
def _represent_ZGate(self, basis, **options): _format = options.get('format', 'sympy') n = 1 definite_state = 0 for it in reversed(self.qubit_values): definite_state += n*it n = n*2 result = [0]*(2**self.dimension) result[int(definite_state)] = 1 ...
Python
nomic_cornstack_python_v1
async function test_unsigned_two_word_register hass mock_hub begin set register_config = dict CONF_COUNT 2 ; CONF_DATA_TYPE DATA_TYPE_UINT ; CONF_SCALE 1 ; CONF_OFFSET 0 ; CONF_PRECISION 0 await call run_test hass mock_hub register_config SENSOR_DOMAIN register_words=list 35243 52719 expected=string 2309737967 end func...
async def test_unsigned_two_word_register(hass, mock_hub): register_config = { CONF_COUNT: 2, CONF_DATA_TYPE: DATA_TYPE_UINT, CONF_SCALE: 1, CONF_OFFSET: 0, CONF_PRECISION: 0, } await run_test( hass, mock_hub, register_config, SENSOR_DO...
Python
nomic_cornstack_python_v1
comment Python 52 - Constructor---------- class Student begin set name = string set class1 = string set roll = string set gpa = string comment Using Constructor----- function __init__ self name class1 roll gpa begin set name = name set class1 = class1 set roll = roll set gpa = gpa end function function display self...
#Python 52 - Constructor---------- class Student: name = "" class1 = "" roll = "" gpa = "" #Using Constructor----- def __init__(self, name, class1, roll, gpa): self.name = name self.class1 = class1 self.roll = roll self.gpa = gpa def display(self...
Python
zaydzuhri_stack_edu_python
import src.utils as utils import pandas as pd async function send_stats client result channel logging begin info string converting dictionary to table set str_to_fmt = await call dict_to_table call stat_totals logging set str_to_fmt = string ``` + str_to_fmt + string + string number of games analyzed: { num_games } ``...
import src.utils as utils import pandas as pd async def send_stats(client, result, channel, logging): logging.info('converting dictionary to table') str_to_fmt = await utils.dict_to_table(result.stat_totals(), logging) str_to_fmt = "```" + str_to_fmt + "\n" + f"number of games analyzed: {result.num_games}`...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sun Jul 28 18:15:38 2019 Methods to delete non-complete abstracts (abstracts that do not have P and I and O tags) 2. to save them is format that can be used to train the sentence classification @author: lena schmidt set pathOrigTrain = string PICO_train.txt set pathOrigDe...
# -*- coding: utf-8 -*- """ Created on Sun Jul 28 18:15:38 2019 Methods to delete non-complete abstracts (abstracts that do not have P and I and O tags) 2. to save them is format that can be used to train the sentence classification @author: lena schmidt """ pathOrigTrain='PICO_train.txt' pathOrigDev='PICO_dev.txt...
Python
zaydzuhri_stack_edu_python
string A left rotation shifts each element in the array 1 unit to the left. Given an array of a of n integers, and a number d, perform d left rotations on the array. Return the updated array printed as single line of space-separated integers. import math import os import random import re import sys comment Complete the...
""" A left rotation shifts each element in the array 1 unit to the left. Given an array of a of n integers, and a number d, perform d left rotations on the array. Return the updated array printed as single line of space-separated integers. """ import math import os import random import re import sys # Complete the r...
Python
zaydzuhri_stack_edu_python
set distancia = integer input set combustivel = decimal input print format string {:.3f} km/l decimal distancia / combustivel
distancia = int(input()); combustivel = float(input()); print('{:.3f} km/l'.format(float(distancia / combustivel)));
Python
zaydzuhri_stack_edu_python
function apply_model pfi_fitted_models x begin set model_params = load pickle open pfi_fitted_models string rb set model = call MLPClassifier call set_params keyword model_params set y = predict model x call predict_proba x return y end function
def apply_model(pfi_fitted_models, x): model_params = pickle.load(open(pfi_fitted_models, 'rb')) model = MLPClassifier() model.set_params(**model_params) y = model.predict(x) model.predict_proba(x) return y
Python
nomic_cornstack_python_v1
function mainloop self *args **kwargs begin if call in_idle begin return end call mainloop *args keyword kwargs end function
def mainloop(self, *args, **kwargs): if in_idle(): return self.top.mainloop(*args, **kwargs)
Python
nomic_cornstack_python_v1
function initialise_framework self options begin set proxy_mode = options at string ProxyMode info string Loading framework please wait.. call initialisation_phase_3 options call initialise_plugin_handler_and_params options comment No processing required, just list available modules. if options at string list_plugins b...
def initialise_framework(self, options): self.proxy_mode = options["ProxyMode"] logging.info("Loading framework please wait..") ComponentInitialiser.initialisation_phase_3(options) self.initialise_plugin_handler_and_params(options) # No processing required, just list available mo...
Python
nomic_cornstack_python_v1
import textract import re set text = process string C://Users//admin//Desktop//New folder//resume.pdf set txt = string text set match = find all string [\w\.-]+@[\w\.-]+ txt for i in match begin comment mail ids print i end for j in find all string [\+\(]?[1-9][0-9 .\-\(\)]{8,}[0-9] txt begin comment phone numbers prin...
import textract import re text = textract.process('C://Users//admin//Desktop//New folder//resume.pdf') txt=str(text) match = re.findall(r'[\w\.-]+@[\w\.-]+', txt) for i in match: print(i)# mail ids for j in re.findall(r'[\+\(]?[1-9][0-9 .\-\(\)]{8,}[0-9]', txt): print (j)# phone numbers t...
Python
zaydzuhri_stack_edu_python
function interrogator corpus search query=string any show=string w exclude=false excludemode=string any searchmode=string all dep_type=string collapsed-ccprocessed-dependencies case_sensitive=false save=false just_speakers=false preserve_case=false lemmatag=false files_as_subcorpora=false only_unique=false random=false...
def interrogator(corpus, search, query='any', show='w', exclude=False, excludemode='any', searchmode='all', dep_type='collapsed-ccprocessed-dependencies', case_sensitive=False, ...
Python
nomic_cornstack_python_v1
import constants class Enemy begin function __init__ self difficulty begin set difficulty = difficulty set health = difficulty * 5 set damage = difficulty * 2 set enemyType = call InitEnemyType set sprite = call InitSprite end function function InitEnemyType self begin comment Initializes the enemy based on the difficu...
import constants class Enemy: def __init__(self, difficulty): self.difficulty = difficulty self.health = difficulty * 5 self.damage = difficulty * 2 self.enemyType = self.InitEnemyType() self.sprite = self.InitSprite() def InitEnemyType(self): # Initializes the ...
Python
zaydzuhri_stack_edu_python
comment CTI-110 comment P3HW1 - Age Classifier comment Marcus Merritt comment 4/30/2018 set age = integer input string Please enter a person's age. if age <= 1 begin print string You are an infant. end else if age > 1 and age < 13 begin print string You are a child end else if age >= 13 and age < 20 begin print string ...
# CTI-110 # P3HW1 - Age Classifier # Marcus Merritt # 4/30/2018 # age = int(input("Please enter a person's age.")) if age <= 1: print("You are an infant.") elif age > 1 and age < 13: print("You are a child") elif age >= 13 and age < 20: print("You are a teenager.") else: print("...
Python
zaydzuhri_stack_edu_python
import sys function test did_pass begin string Print the result of a test. comment Get the caller's line number. set linenum = f_lineno if did_pass begin set msg = format string Test at line {0} ok. linenum end else begin set msg = format string Test at line {0} FAILIED. linenum end print msg end function function test...
import sys def test(did_pass): """ Print the result of a test. """ linenum = sys._getframe(1).f_lineno # Get the caller's line number. if did_pass: msg = "Test at line {0} ok.".format(linenum) else: msg = ("Test at line {0} FAILIED.".format(linenum)) print(msg) def test_suite(): ...
Python
zaydzuhri_stack_edu_python
function _determine_current_relay_speed self begin set w1 = get states _relay_w1 if not w1 begin warning string W1 entity { _relay_w1 } not found, cannot determine { _name } LUNOS speed. return none end set w2 = get states _relay_w2 if not w2 begin warning string W2 entity { _relay_w2 } not found, cannot determine { _n...
def _determine_current_relay_speed(self): w1 = self.hass.states.get(self._relay_w1) if not w1: LOG.warning( f"W1 entity {self._relay_w1} not found, cannot determine {self._name} LUNOS speed." ) return None w2 = self.hass.states.get(self._relay...
Python
nomic_cornstack_python_v1
function priorsampling self nsample query evidence begin set closedquery = list comprehension tuple qt qt for qt in query set closedevidence = evidence set openevidence = list comprehension a for tuple a b in evidence set tuple querynodes evidencenodesgiven orderednodes evidencenodes = call expandNode query evidence se...
def priorsampling(self,nsample,query,evidence): closedquery=[(qt,qt) for qt in query] closedevidence=evidence openevidence=[a for (a,b) in evidence] querynodes,evidencenodesgiven,orderednodes,evidencenodes=self.expandNode(query,evidence) query=self.querytovector(orderednodes,quer...
Python
nomic_cornstack_python_v1
function _hard_negative_mining self conf_loss pos begin set tuple batch_size num_boxes = size pos comment set pos boxes = 0, the rest are neg conf_loss set conf_loss at pos = 0 comment [N,8732] set conf_loss = view conf_loss batch_size - 1 comment sort by neg conf_loss set tuple _ idx = sort conf_loss 1 descending=true...
def _hard_negative_mining(self, conf_loss, pos): batch_size, num_boxes = pos.size() conf_loss[pos] = 0 # set pos boxes = 0, the rest are neg conf_loss conf_loss = conf_loss.view(batch_size, -1) # [N,8732] _, idx = conf_loss.sort(1, descending=True) # sort by neg conf_loss _,...
Python
nomic_cornstack_python_v1
function save_form self request form change begin return save commit=false user=user end function
def save_form(self, request, form, change): return form.save(commit=False, user=request.user)
Python
nomic_cornstack_python_v1
function certificateError self listener=none begin set event_name = string Security.certificateError if listener is none begin set future = call create_future function _listener event=none begin call set_result event end function call once event_name _listener return future end call on event_name listener return lambda...
def certificateError( self, listener: Optional[Callable[[Dict[str, Any]], Any]] = None ) -> Any: event_name = "Security.certificateError" if listener is None: future = self.client.loop.create_future() def _listener(event: Optional[Dict] = None) -> None: ...
Python
nomic_cornstack_python_v1
import pymongo class CreateCollections begin comment Database connection function __init__ self begin set myclients = call MongoClient string mongodb+srv://mahmut:123@cluster0.3ycuu.mongodb.net/PorteDB?retryWrites=true&w=majority set mydb = myclients at string PorteDB call input_collection set document_count = call cou...
import pymongo class CreateCollections: # Database connection def __init__(self): self.myclients = pymongo.MongoClient("mongodb+srv://mahmut:123@cluster0.3ycuu.mongodb.net/PorteDB?retryWrites=true&w=majority") self.mydb = self.myclients["PorteDB"] self.input_collection() sel...
Python
zaydzuhri_stack_edu_python
comment delwin class FoodExpert begin function init self begin set goodFood = list end function function addGoodFood self food begin call appdend food end function function likes self x begin return x in goodFood end function function prefers self x y begin set x_rating = index goodFood x set y_rating = index goodFood...
# delwin class FoodExpert: def init(self): self.goodFood = [] def addGoodFood(self,food): self.goodFood.appdend(food) def likes(self,x): return x in self.goodFood def prefers(self,x,y): x_rating = self.goodFood.index(x) y_rating = self.goodFood.index(y) ...
Python
zaydzuhri_stack_edu_python
import math function IntcodeExecute fullInput begin set currentExecutePointer = 0 set exitCode = 0 while exitCode == 0 begin if length fullInput - currentExecutePointer > 0 begin if fullInput at currentExecutePointer == 1 begin if length fullInput - currentExecutePointer - 3 < 1 begin set exitCode = 3 break end set inp...
import math; def IntcodeExecute(fullInput): currentExecutePointer = 0; exitCode = 0; while exitCode == 0: if ((len(fullInput) - currentExecutePointer) > 0): if fullInput[currentExecutePointer] == 1: if ((len(fullInput) - currentExecutePointer - 3) < 1): ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from scipy import integrate set pi = pi set x = array range - pi pi pi / 1000 comment 係数 function bk k begin set tmpb = 4 / k ^ 2 * cos k * pi return tmpb end function comment Sn(x)の計算 function Sn n b x begin set y = zeros n set sin_list = array list comprehension cos ...
import numpy as np import matplotlib.pyplot as plt from scipy import integrate pi = np.pi x = np.arange(-pi, pi, pi/1000) #係数 def bk(k): tmpb = (4/k**2)*np.cos(k*pi) return tmpb #Sn(x)の計算 def Sn(n,b,x): y = np.zeros((n)) sin_list = np.array([np.cos((k+1)*x) for k in range(n)]) sn = sin_list*b ...
Python
zaydzuhri_stack_edu_python
comment This code was originally done within Jupyter notebooks and has been copied across into a .py file comment This is to allow me to upload the code to Github to showcase comment This is because Juypter notbookes has a proprietary format import pandas as pd import numpy as np from matplotlib import pyplot as plt se...
# This code was originally done within Jupyter notebooks and has been copied across into a .py file # This is to allow me to upload the code to Github to showcase # This is because Juypter notbookes has a proprietary format import pandas as pd import numpy as np from matplotlib import pyplot as plt country_da...
Python
zaydzuhri_stack_edu_python
string A series of Python functions for the creation and analysis of FAST-related files. AUTHOR: Jenni Rinker, Duke University CONTACT: jennifer.rinker@duke.edu NOTES: Currently only tested for FAST v7 TODO: - Proper handling of tower gage/blade gage nodes (currently only tested with none) - Porper handling of DISCON c...
""" A series of Python functions for the creation and analysis of FAST-related files. AUTHOR: Jenni Rinker, Duke University CONTACT: jennifer.rinker@duke.edu NOTES: Currently only tested for FAST v7 TODO: - Proper handling of tower gage/blade gage nodes (currently only tested with none) - Porper handli...
Python
zaydzuhri_stack_edu_python
import argparse from trolldetector.KNN import knn from trolldetector.MLP import mlp from trolldetector.NB import nb from trolldetector.SVM import svm from trolldetector.all import all from trolldetector.tree import tree from trolldetector.parsing.commonarguments import CommonArguments from trolldetector.parsing import ...
import argparse from trolldetector.KNN import knn from trolldetector.MLP import mlp from trolldetector.NB import nb from trolldetector.SVM import svm from trolldetector.all import all from trolldetector.tree import tree from trolldetector.parsing.commonarguments import CommonArguments from trolldetector.parsing import ...
Python
zaydzuhri_stack_edu_python
function subarrive request user begin set u = call getuser user set arrivesub = true save end function
def subarrive(request, user): u = getuser(user) u.arrivesub = True u.save()
Python
nomic_cornstack_python_v1
function play_recursive_game player1_cards player2_cards begin set previous_rounds = set call play_recursive_game0 player1_cards player2_cards previous_rounds return call compute_winner_score player1_cards player2_cards end function
def play_recursive_game(player1_cards, player2_cards): previous_rounds = set() play_recursive_game0(player1_cards, player2_cards, previous_rounds) return compute_winner_score(player1_cards, player2_cards)
Python
nomic_cornstack_python_v1
function load_ini_file ini_file_path begin set config = config parser read config ini_file_path set cfg = dict comment Load hyperparameters set cfg at string hyperparameters = dict set cfg at string hyperparameters at string gpu_id = call getint string hyperparameters string gpu_id set cfg at string hyperparameters a...
def load_ini_file(ini_file_path): config = configparser.ConfigParser() config.read(ini_file_path) cfg = {} # Load hyperparameters cfg["hyperparameters"] = {} cfg["hyperparameters"]["gpu_id"] = config.getint("hyperparameters", "gpu_id") cfg["hyperparamete...
Python
nomic_cornstack_python_v1
string 矩形模块 function girth width height begin string 功能:计算周长 参数:width(宽度)、height(高) return width + height * 2 end function function area width height begin string 功能:计算面积 参数:width(宽度)、height(高) return width * height end function if __name__ == string __main__ begin print call area 10 20 end
'''矩形模块''' def girth(width,height): '''功能:计算周长 参数:width(宽度)、height(高) ''' return (width + height)*2 def area(width,height): '''功能:计算面积 参数:width(宽度)、height(高) ''' return width * height if __name__ == '__main__': print(area(10,20))
Python
zaydzuhri_stack_edu_python
import sys import controller from DISClib.ADT import list as lt assert cf from DISClib.ADT import map as mp call setrecursionlimit 1000000 class text begin set BOLD = string  set UNDERLINE = string  set PURPLE = string  set CYAN = string  set RED = string  set BLUE = string  set YELLOW = str...
import sys import controller from DISClib.ADT import list as lt assert cf from DISClib.ADT import map as mp sys.setrecursionlimit(1000000) class text: BOLD = '\033[1m' UNDERLINE = '\033[4m' PURPLE = '\033[95m' CYAN = '\033[96m' RED = '\033[91m' BLUE = '\033[34m' YELLOW = '\033[93m' GREEN...
Python
zaydzuhri_stack_edu_python
function delete_group_type_group_specs_property self group_type prop begin set group_type = call _get_resource GroupType group_type return call delete_group_specs_property self prop end function
def delete_group_type_group_specs_property(self, group_type, prop): group_type = self._get_resource(_group_type.GroupType, group_type) return group_type.delete_group_specs_property(self, prop)
Python
nomic_cornstack_python_v1
function make_album album_name artist_name begin set album = dict string Album album_name ; string Artist artist_name return album end function
def make_album(album_name, artist_name): album = {'Album':album_name, 'Artist':artist_name} return album
Python
nomic_cornstack_python_v1
comment Print out even numbers from the given list for num in list begin if num % 2 == 0 begin print num end end
#Print out even numbers from the given list for num in list: if (num % 2 == 0): print(num)
Python
flytech_python_25k
function update_watchers self begin set watchers = list set plugins = list comment trying to list the watchers try begin set connected = true set watchers = yield call Task send_message string list set watchers = watchers at string watchers for watcher in watchers begin if watcher in tuple string circusd-stats string...
def update_watchers(self): self.watchers = [] self.plugins = [] # trying to list the watchers try: self.connected = True watchers = yield gen.Task(self.send_message, 'list') watchers = watchers['watchers'] for watcher in watchers: ...
Python
nomic_cornstack_python_v1
function detect self contour begin comment Initialize the shape name and get the shape perimeter. set shape = string unidentified set perimeter = call arcLength contour true comment Approximate the contour to 'smooth' the shape. Perimeter of appoximation can be up to 4% different. set approx = call approxPolyDP contour...
def detect(self, contour): # Initialize the shape name and get the shape perimeter. shape = "unidentified" perimeter = cv2.arcLength(contour, True) # Approximate the contour to 'smooth' the shape. Perimeter of appoximation can be up to 4% different. approx = cv2.approxPolyDP(con...
Python
nomic_cornstack_python_v1
function apply_layer self text_index begin set footnotes = list for label in keys layer begin if call is_contained_in label text_index begin set footnotes = footnotes + list comprehension x at string footnote_data for x in layer at label if string footnote_data in x end end return tuple string footnotes sorted footnot...
def apply_layer(self, text_index): footnotes = [] for label in self.layer.keys(): if is_contained_in(label, text_index): footnotes += [x['footnote_data'] for x in self.layer[label] if 'footnote_data' in x] re...
Python
nomic_cornstack_python_v1
function test_add_manual_latest_price rotkehlchen_api_server begin call add_manual_latest_price from_asset=A_ETH to_asset=A_EUR price=call Price call FVal 100 set response = post call api_url_for rotkehlchen_api_server string latestassetspriceresource json=dict string target_asset identifier ; string assets list identi...
def test_add_manual_latest_price(rotkehlchen_api_server): GlobalDBHandler().add_manual_latest_price( from_asset=A_ETH, to_asset=A_EUR, price=Price(FVal(100)), ) response = requests.post( api_url_for( rotkehlchen_api_server, 'latestassetspriceresource',...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import sys import argparse import gzip import time set des = string Parse base station/hour statistics file to generate base station stat set parser = call ArgumentParser description=des call add_argument string -bsthstat metavar=string bsth_stat_file help=string input file with base station/ho...
#!/usr/bin/python import sys import argparse import gzip import time des='Parse base station/hour statistics file to generate base station stat' parser = argparse.ArgumentParser(description=des) parser.add_argument('-bsthstat', metavar='bsth_stat_file', help='input file with base station/hour statistics (gziped)', r...
Python
zaydzuhri_stack_edu_python
function Path_Folder directory begin if not exists path directory begin make directories directory end end function
def Path_Folder(directory): if not os.path.exists(directory): os.makedirs(directory)
Python
nomic_cornstack_python_v1
import flask from flask import Flask from lecture_code.testing.wrap_around_counter.wraparoundcounter import WrapAroundCounter set app = call Flask __name__ set debug = true set wac = call WrapAroundCounter 10 decorator call route string / function hello_world begin return string Hello, World!! end function decorator ca...
import flask from flask import Flask from lecture_code.testing.wrap_around_counter.wraparoundcounter import WrapAroundCounter app = Flask(__name__) app.debug = True wac = WrapAroundCounter(10) @app.route('/') def hello_world(): return 'Hello, World!!' @app.route('/counter/<argument>') def counter(argument): ...
Python
zaydzuhri_stack_edu_python
for letter in string MIS407 begin if letter == string 4 begin break end print letter end
for letter in "MIS407": if letter == '4': break print(letter)
Python
zaydzuhri_stack_edu_python
function _validate_numax self numax begin if numax is none begin try begin return numax end except AttributeError begin raise call AttributeError string You need to call `Seismology.estimate_numax()` first. end end return numax end function
def _validate_numax(self, numax): if numax is None: try: return self.numax except AttributeError: raise AttributeError("You need to call `Seismology.estimate_numax()` first.") return numax
Python
nomic_cornstack_python_v1
function clear self begin del db at key end function
def clear(self): del self.db[self.key]
Python
nomic_cornstack_python_v1
function get_repo_root path begin set norm_path = call normpath path set norm_path_exists = exists path norm_path if not norm_path_exists begin return none end if call is_repo_root norm_path begin return norm_path end set parent_path = directory name path norm_path comment Check if we're in the root folder already. if ...
def get_repo_root(path): norm_path = os.path.normpath(path) norm_path_exists = os.path.exists(norm_path) if not norm_path_exists: return None if is_repo_root(norm_path): return norm_path parent_path = os.path.dirname(norm_path) # Check if we're in the root folder already. if parent_path == norm...
Python
nomic_cornstack_python_v1
import os from playsound import playsound import datetime set extracted_time = open string C:\Users\Hari\Destny the ai\Data.txt string rt set time = read extracted_time set Time = string time set delete_time = open string C:\Users\Hari\Destny the ai\Data.txt string r+ call truncate 0 close delete_time function RingerNo...
import os from playsound import playsound import datetime extracted_time = open('C:\\Users\\Hari\\Destny the ai\\Data.txt','rt') time = extracted_time.read() Time = str(time) delete_time = open("C:\\Users\\Hari\\Destny the ai\\Data.txt",'r+') delete_time.truncate(0) delete_time.close() def RingerNow(tim...
Python
zaydzuhri_stack_edu_python
import re from datetime import datetime , time comment funkcja eksportująca listę do pliku function to_file list_for_export output_path begin string Writes list into a file of given file path Parameters: list (list), path (string) Returns: file of seperated list items with open output_path string w as f begin for eleme...
import re from datetime import datetime, time # funkcja eksportująca listę do pliku def to_file(list_for_export, output_path): """ Writes list into a file of given file path Parameters: list (list), path (string) Returns: file of \n seperated list items """ with open(output_path, "w") as f: ...
Python
zaydzuhri_stack_edu_python
function __init__ self **kwargs begin call __init__ self call __init__ self keyword kwargs end function
def __init__(self, **kwargs): nn.Module.__init__(self) BaseEstimator.__init__(self, **kwargs)
Python
nomic_cornstack_python_v1
function solve_8_puzzle initial_state begin comment Create goal state set goal_state = list 1 2 3 8 0 4 7 6 5 comment Dictionary to maintain visited states set visited_states = dict set state_list = list append state_list initial_state set visited_states at tuple initial_state = true comment Create the nodes that nee...
def solve_8_puzzle(initial_state): # Create goal state goal_state = [1, 2, 3, 8, 0, 4, 7, 6, 5] # Dictionary to maintain visited states visited_states = {} state_list = [] state_list.append(initial_state) visited_states[tuple(initial_state)] = True # Create the nodes t...
Python
jtatman_500k
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import numpy as np import os as os import csv import classification function collect_data num_classes_limit=none begin string Preprocessing step: Collect information about the dataset and build train and test set. The files of the dataset should be splitted in...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np import os as os import csv import classification def collect_data(num_classes_limit=None): """ Preprocessing step: Collect information about the dataset and build train and test set. The files of the dataset should be splitted in train a...
Python
zaydzuhri_stack_edu_python
from src.afnd import * from src.minimiza import * from src.determiniza import * from src.auxi import * set afd = dict set alfabeto = list set gramatica = list comment faz a leitura dos tokens do arquivo e chama função para gerar afnd while true begin try begin set token = input if not token begin break end call gera...
from src.afnd import * from src.minimiza import * from src.determiniza import * from src.auxi import * afd = {} alfabeto = [] gramatica = [] while True:#faz a leitura dos tokens do arquivo e chama função para gerar afnd try: token = input() if not token: break gerarAfndToken(af...
Python
zaydzuhri_stack_edu_python
class Solution begin function subarraySum self nums k begin string Brute force method to find the total number of continuous subarrays whose sum equals to k. Run time complexity is O(n ^ 3), where n is the number of elements. Parameters ---------- nums : List[int] List of (signed) integers k : int Target integer for su...
class Solution: def subarraySum(self, nums: List[int], k: int) -> int: """ Brute force method to find the total number of continuous subarrays whose sum equals to k. Run time complexity is O(n ^ 3), where n is the number of elements. Parameters ---------- ...
Python
zaydzuhri_stack_edu_python
function test_createElement begin assert not call failed assert call failed assert call failed end function
def test_createElement(): assert not _do_test_raw(""" var x = "foo"; x.createElement(); x.createElement("foo"); """).failed() assert _do_test_raw(""" var x = "foo"; x.createElement("script"); """).failed() assert _do_test_raw(""" var x = "foo"; x.createElement(bar); ...
Python
nomic_cornstack_python_v1
function get_meraki_api_data api_uri begin set url = API_URL + api_uri set a_response = get requests url headers=api_headers verify=false if status_code == 200 begin set data = loads text info string Meraki GET operation suceeded : %s api_uri end else begin set data = dict info string Meraki GET Operation failed : %s ...
def get_meraki_api_data(api_uri): url = API_URL + api_uri a_response = requests.get(url, headers=api_headers, verify=False) if a_response.status_code == 200: data = json.loads(a_response.text) logger.info("Meraki GET operation suceeded : %s ", api_uri) else: data = {} log...
Python
nomic_cornstack_python_v1
from sklearn import linear_model import numpy as np import pdb from preprocessing import load_paws from analyze_model import get_swapping_pos function transform_loader dataloader include_absolute_distance=false begin comment convert raw data from dataloader to swapping distance input set tuple input_array label_array =...
from sklearn import linear_model import numpy as np import pdb from preprocessing import load_paws from analyze_model import get_swapping_pos def transform_loader(dataloader, include_absolute_distance=False): # convert raw data from dataloader to swapping distance input input_array, label_array = [], [] ...
Python
zaydzuhri_stack_edu_python
import numpy as num comment import matplotlib.pyplot as plt comment import pylab as lab comment from scipy import constants import scipy as sci comment import pandas as pan import os comment from collections import OrderedDict comment from scipy.optimize import curve_fit import sys import re function DumpExtractor file...
import numpy as num #import matplotlib.pyplot as plt #import pylab as lab #from scipy import constants import scipy as sci #import pandas as pan import os #from collections import OrderedDict #from scipy.optimize import curve_fit import sys import re def DumpExtractor(filename,frames,atomNumber,atomPlate): ...
Python
zaydzuhri_stack_edu_python
from heapq import heapify , heappop , heappush call heapify min_plane call heapify max_plane set ans_min = 0 set ans_max = 0 for i in range n begin set temp = call heappop min_plane set ans_min = ans_min + temp if temp - 1 != 0 begin call heappush min_plane temp - 1 end set temp = absolute call heappop max_plane set an...
from heapq import heapify, heappop, heappush heapify(min_plane) heapify(max_plane) ans_min = 0 ans_max = 0 for i in range(n): temp = heappop(min_plane) ans_min += temp if temp-1 != 0: heappush(min_plane, temp-1) temp = abs(heappop(max_plane)) ans_max += temp if temp-1 != 0: heappush(max_plane, ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string Smart parser for IceWM's address bar feature Included (somewhat slapdash but fairly comprehensive) test suite may be run with `nosetests <name of this file>`. --snip-- Run without arguments for usage. @todo: Refactor to allow cleaner, more thorough unit ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Smart parser for IceWM's address bar feature Included (somewhat slapdash but fairly comprehensive) test suite may be run with `nosetests <name of this file>`. --snip-- Run without arguments for usage. @todo: Refactor to allow cleaner, more thorough unit tests. @todo:...
Python
zaydzuhri_stack_edu_python
function getScorecard self **kwargs begin set lstPlayers = list for tuple n score in enumerate _players begin set dct = dict string player doc set dct at string in = dct_points at string in set dct at string out = dct_points at string out set dct at string total = dct_points at string total set dct at string holes = d...
def getScorecard(self, **kwargs): lstPlayers = [] for n,score in enumerate(self._players): dct = {'player': score.doc } dct['in'] = score.dct_points['in'] dct['out'] = score.dct_points['out'] dct['total'] = score.dct_points['total'] dct['holes'] = score.dct_points['holes'] # ...
Python
nomic_cornstack_python_v1
function gen_malicious num_per_dga=10000 begin set domains = list set labels = list comment We use some arbitrary seeds to create domains with banjori set banjori_seeds = list string somestring string firetruck string bulldozer string airplane string racecar string apartment string laptop string laptopcomp string mal...
def gen_malicious(num_per_dga=10000): domains = [] labels = [] # We use some arbitrary seeds to create domains with banjori banjori_seeds = ['somestring', 'firetruck', 'bulldozer', 'airplane', 'racecar', 'apartment', 'laptop', 'laptopcomp', 'malwareisbad', 'crazytrain', ...
Python
nomic_cornstack_python_v1
import os import math import matplotlib.pyplot as plt import numpy as np import parse function plot_latency_cpu d errorbar=false begin set tuple fig ax1 = call subplots dpi=100 figsize=tuple 16 9 tight_layout=true set ax2 = call twinx for tuple k v in items d begin set tuple avg err = v if errorbar begin call errorbar ...
import os import math import matplotlib.pyplot as plt import numpy as np import parse def plot_latency_cpu(d, errorbar=False): fig, ax1 = plt.subplots(dpi=100, figsize=(16, 9), tight_layout=True) ax2 = ax1.twinx() for k, v in d.items(): avg, err = v if errorbar: ax1.errorbar(...
Python
zaydzuhri_stack_edu_python
function load_shortlist self fname begin load shortlist join path model_dir fname + string .shortlist.indices load sim join path model_dir fname + string .shortlist.sim end function
def load_shortlist(self, fname): self.shortlist.load(os.path.join( self.model_dir, fname+'.shortlist.indices')) self.sim.load(os.path.join( self.model_dir, fname+'.shortlist.sim'))
Python
nomic_cornstack_python_v1
function construct_worker_config self worker_name begin set config = deep copy get config string defaults dict update config get config worker_name dict return config end function
def construct_worker_config(self, worker_name): config = deepcopy(self.config.get('defaults', {})) config.update(self.config.get(worker_name, {})) return config
Python
nomic_cornstack_python_v1
function event_switch_2_off self ioname iovalue begin if main_state and door_2_state begin set door_2_state = false call config bg=string #EAEAEA fg=string black call config bg=string light grey text=string Closed call config bg=string #00C1FF fg=string white set door_count = door_count + 1 call config text=string # do...
def event_switch_2_off(self, ioname, iovalue): if self.main_state and self.door_2_state: self.door_2_state = False self.btn_door_2_open.config(bg='#EAEAEA', fg='black') self.lbl_state_door_2.config(bg='light grey', text="Closed") self.btn_door_2_close.config(bg='#...
Python
nomic_cornstack_python_v1
function _closeClickedSlot self begin if call _proceedWithUnsavedChanges begin save close self end end function
def _closeClickedSlot(self): if self._proceedWithUnsavedChanges(): self.__storedSearchesController.model.save() self.close()
Python
nomic_cornstack_python_v1
function setTextChanged self begin call stop start timer 3000 end function
def setTextChanged(self): self.timer.stop() self.timer.start(3000)
Python
nomic_cornstack_python_v1
function test_solve_numberadder begin import numpy as np from crpm.ffn_bodyplan import read_bodyplan from crpm.ffn_bodyplan import init_ffn from crpm.dataset import load_dataset from crpm.gradientdecent import gradientdecent comment create shallow bodyplan with 5 inputs and 1 output for numebr adder data set bodyplan =...
def test_solve_numberadder(): import numpy as np from crpm.ffn_bodyplan import read_bodyplan from crpm.ffn_bodyplan import init_ffn from crpm.dataset import load_dataset from crpm.gradientdecent import gradientdecent #create shallow bodyplan with 5 inputs and 1 output for numebr adder data ...
Python
nomic_cornstack_python_v1
function get_closest_waypoint self pose begin set tuple distance wp_closest = query tree pose return wp_closest end function
def get_closest_waypoint(self, pose): distance, wp_closest = self.tree.query(pose) return wp_closest
Python
nomic_cornstack_python_v1
string This program helps other developers to guess numbers. from random import randint from time import sleep function get_user_guess begin set user_guess = integer call raw_input string Guess a number: return user_guess end function function roll_dice number_of_sides begin set first_roll = random integer 1 number_of_...
"""This program helps other developers to guess numbers.""" from random import randint from time import sleep def get_user_guess(): user_guess = int(raw_input("Guess a number: ")) return user_guess def roll_dice(number_of_sides): first_roll = randint(1, number_of_sides) second_roll = randint(1, number_of_sid...
Python
zaydzuhri_stack_edu_python
function h5_dsets_data self begin set _h5_dsets_data = none if is instance _h5_dsets tuple list tuple begin set _h5_dsets_data = dict for dset in _h5_dsets begin if dset in datasets begin set _h5_dsets_data at dset = gen at dset end end end else if is instance _h5_dsets dict begin set _h5_dsets_data = _h5_dsets end el...
def h5_dsets_data(self): _h5_dsets_data = None if isinstance(self._h5_dsets, (list, tuple)): _h5_dsets_data = {} for dset in self._h5_dsets: if dset in self.gen.datasets: _h5_dsets_data[dset] = self.gen[dset] elif isinstance(self._h5...
Python
nomic_cornstack_python_v1
function train_final_model model_name ivectors labels params verbose=false begin set trainer_type = MODEL_CHOICE at model_name at 1 set model_params = dictionary comprehension key : params at key for key in PARAM_CHOICE at model_name set trainer = call trainer_type keyword model_params set final_model = call train_fina...
def train_final_model( model_name: str, ivectors: ndarray, labels: ndarray, params: Dict, verbose: bool = False, ) -> Union[LogisticRegression, SVC, FeedForward]: trainer_type = MODEL_CHOICE[model_name][1] model_params = {key: params[key] for key in PARAM_CHOICE[model_name]} trainer = tr...
Python
nomic_cornstack_python_v1
function Associate self request_iterator timeout metadata=none with_call=false protocol_options=none begin raise call NotImplementedError end function
def Associate(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None): raise NotImplementedError()
Python
nomic_cornstack_python_v1
function __getitem__ self i begin set image = call convert string RGB set target = call convert string L if transform is not none begin set tuple image target = transform self image target end return tuple image target end function
def __getitem__(self, i): image = Image.open(self.images[i]).convert('RGB') target = Image.open(self.targets[i]).convert('L') if self.transform is not None: image, target = self.transform(image, target) return image, target
Python
nomic_cornstack_python_v1
comment Challenge - Print multiplication table of 14 for i in range 1 11 begin print string 14 * { i } = { 14 * i } end
#Challenge - Print multiplication table of 14 for i in range(1,11): print(f"14 * {i} = {14*i}")
Python
zaydzuhri_stack_edu_python
import requests import re function extra_link begin set url = string http://www.xinshipu.com/caipu/17844 set base_url = string http://xinshipu.com set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36 set r = get r...
import requests import re def extra_link(): url = 'http://www.xinshipu.com/caipu/17844' base_url = 'http://xinshipu.com' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'} r = requests.get(url, header...
Python
zaydzuhri_stack_edu_python
function initialize begin set blue_gem_positions = list tuple 3 0 tuple 6 0 tuple 1 2 tuple 5 2 tuple 4 4 tuple 7 4 tuple 2 6 tuple 6 6 tuple 3 8 tuple 5 8 set blue_gems = list for pos in blue_gem_positions begin set blue_gem = call BlueGem call register blue_gem call set_el pos at 0 pos at 1 blue_gem append blue_gems...
def initialize(): blue_gem_positions = [ (3,0), (6,0), (1,2), (5,2), (4,4), (7,4), (2,6), (6,6), (3,8), (5,8) ] blue_gems = [] for pos in blue_gem_positions: blue_gem = BlueGem() GAME_BOARD.register(bl...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding:utf-8 -*- from pylab import * from matplotlib.dates import DateFormatter , WeekdayLocator , HourLocator , DayLocator , MONDAY from matplotlib.finance import quotes_historical_yahoo , candlestick , plot_day_summary , candlestick2 comment 定义起始、终止日期和股票代码 set date1 = tuple 20...
#!/usr/bin/env python # -*- coding:utf-8 -*- from pylab import * from matplotlib.dates import DateFormatter, WeekdayLocator, HourLocator, \ DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo, candlestick,\ plot_day_summary, candlestick2 # 定义起始、终止日期和股票代码 date1 = ( 2012, 12, 25 ) date2 = ( 2013, 6,...
Python
zaydzuhri_stack_edu_python
function keras_session model input_tensor_names output_tensor_names **kwargs begin assert VERSION > string 2.1.0 msg string keras model need tensorflow version > 2.1.0.... from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 if not is instance model Model begin set model = call...
def keras_session(model, input_tensor_names, output_tensor_names, **kwargs): assert tf.version.VERSION > '2.1.0', 'keras model need tensorflow version > 2.1.0....' from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 if not isinstance(model, tf.keras.Model): ...
Python
nomic_cornstack_python_v1
function test_ab_reject self begin set fixture_file = string fixtures/simple/ab_reject.json set events = call run_and_get_events fixture_file set expected_events = list tuple string on_b_dial dict string caller string SIP/150010001-00000008 ; string targets list string SIP/150010002-00000009 tuple string on_hangup dict...
def test_ab_reject(self): fixture_file = 'fixtures/simple/ab_reject.json' events = self.run_and_get_events(fixture_file) expected_events = [ ('on_b_dial', { 'caller': 'SIP/150010001-00000008', 'targets': ['SIP/150010002-00000009'], }), ...
Python
nomic_cornstack_python_v1
function session_ended_request_handler handler_input begin comment type: (HandlerInput) -> Response return response end function
def session_ended_request_handler(handler_input): # type: (HandlerInput) -> Response return handler_input.response_builder.response
Python
nomic_cornstack_python_v1
comment Mon Chef-d’Oeuvre comment My Program draws the perspective of someone looking at the front of a ball pit! comment Created by Jasper Quan comment July 6, 2017 import turtle as t import random as r function ball numberofBalls begin for count in range numberofBalls begin call pu set x_pos = random integer - 340 ...
#Mon Chef-d’Oeuvre #My Program draws the perspective of someone looking at the front of a ball pit! #Created by Jasper Quan #July 6, 2017 import turtle as t import random as r def ball(numberofBalls): for count in range(numberofBalls): t.pu() x_pos = r.randint(-340,340) y_p...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf from bert.modeling import BertConfig , get_shape_list class LSTMConfig begin function __init__ self num_units max_seq_length model bert_config begin set num_units = num_units set max_seq_length = max_seq_length set bert_config = bert_config assert model == string lstm set model = model end funct...
import tensorflow as tf from bert.modeling import BertConfig, get_shape_list class LSTMConfig: def __init__(self, num_units, max_seq_length, model, bert_config): self.num_units = num_units self.max_seq_length = max_seq_length self.bert_config = bert_config assert model == 'lstm' ...
Python
zaydzuhri_stack_edu_python