code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function xform_ang_axs self thetaRad k begin call xform_homog call homog_ang_axs thetaRad k list 0 0 0 end function
def xform_ang_axs( self , thetaRad , k ): self.xform_homog( homog_ang_axs( thetaRad , k , [ 0 , 0 , 0 ] ) )
Python
nomic_cornstack_python_v1
from tools.VecMath import Vec2D from tools.utils import Drawable class Player extends Drawable begin set PLAYERSPEED = 10 set PLAYERSIZE = call Vec2D 150 10 comment Constructor function __init__ self size=none begin from tools.Debug import Debug if call isVec size begin call __init__ self none size end else begin call ...
from tools.VecMath import Vec2D from tools.utils import Drawable class Player(Drawable): PLAYERSPEED = 10 PLAYERSIZE = Vec2D(150, 10) # Constructor def __init__(self, size=None): from tools.Debug import Debug if Vec2D.isVec(size): Drawable.__init__(self,None, s...
Python
zaydzuhri_stack_edu_python
function getFeatures self gameState action begin set features = counter set height = height set width = width set walls = walls if red begin set longitude = width / 2 + 1 end else begin set longitude = width / 2 end set border_positions = list comprehension tuple longitude i for i in range height if not walls at longit...
def getFeatures(self, gameState, action): features = util.Counter() height = gameState.data.layout.height width = gameState.data.layout.width walls = gameState.data.layout.walls if self.red: longitude = width/2 + 1 else: longitude = width/2 border_positions = [(longitude, ...
Python
nomic_cornstack_python_v1
function cache_invalidator func=none method=false args=none kwargs=none generic=true begin if func is not none begin if is instance func tuple list tuple set begin set func = tuple func end else begin set func = tuple func end end if args is not none begin if is instance args tuple list tuple set begin set args = set a...
def cache_invalidator(*, func=None, method=False, args=None, kwargs=None, generic=True): if func is not None: if isinstance(func, (list, tuple, set)): func = tuple(func) else: func = (func,) if args is not None: if isinstance(args, (list, tuple, set)): ...
Python
nomic_cornstack_python_v1
for num in range num num1 + 1 begin if num % 2 != 0 begin print string Impar { num } end end
for num in range(num, num1+1): if num%2!=0: print(f"Impar {num}")
Python
zaydzuhri_stack_edu_python
import os , shutil import socket import sys comment import struct comment import ctypes function main begin comment Get IP adddress and Host Name call ip_address comment make target files, source files change directory string . set target_folder = string C:\Users\Jenny McCyber\Documents\JoKEr_Virus\new.txt set source_f...
import os, shutil import socket import sys #import struct #import ctypes def main(): #Get IP adddress and Host Name ip_address() #make target files, source files os.chdir('.') target_folder = r'C:\Users\Jenny McCyber\Documents\JoKEr_Virus\new.txt' source_folder = r'C:\Users\...
Python
zaydzuhri_stack_edu_python
function list_arg self list_name string begin return list comprehension x for tuple x y in enumerate list_name if y == string at 0 end function
def list_arg(self, list_name, string): return [x for x, y in enumerate(list_name) if y == string][0]
Python
nomic_cornstack_python_v1
function outputs self begin return _outputs end function
def outputs(self): return self._outputs
Python
nomic_cornstack_python_v1
class Solution begin function twoSum self nums target begin set mapper = dict for i in range length nums begin if target - nums at i == nums at i begin for j in range i + 1 length nums begin if nums at j == nums at i begin return list i j end end end set mapper at string target - nums at i = i end for j in range lengt...
class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: mapper = {} for i in range(len(nums)): if target - nums[i] == nums[i]: for j in range(i+1,len(nums)): if nums[j] == nums[i]: return [i,j] ...
Python
zaydzuhri_stack_edu_python
function compress data compression width height depth version=1 begin string Compress raw data. :param data: raw data bytes to write. :param compression: compression type, see :py:class:`.Compression`. :param width: width. :param height: height. :param depth: bit depth of the pixel. :param version: psd file version. :r...
def compress(data, compression, width, height, depth, version=1): """Compress raw data. :param data: raw data bytes to write. :param compression: compression type, see :py:class:`.Compression`. :param width: width. :param height: height. :param depth: bit depth of the pixel. :param version:...
Python
jtatman_500k
comment create object "5 movies" - create movielist - print stoixeia twn tainiwn from Lesson5.model.Car import Car from Lesson5.model.Movie import Movie comment nissan 350z toyota supra mitsubishi evo 4 doors set nissan = call Car string nissan string 350z string 2000 string 2 set toyota = call Car string toyota string...
# create object "5 movies" - create movielist - print stoixeia twn tainiwn from Lesson5.model.Car import Car from Lesson5.model.Movie import Movie # nissan 350z toyota supra mitsubishi evo 4 doors nissan = Car("nissan", "350z", "2000", "2") toyota = Car("toyota", "supra", "1992", "2") evo = Car("mitsubishi", "evo", "...
Python
zaydzuhri_stack_edu_python
comment out dated by filterisofroms.py import sys import csv import re from Bio import SeqIO from Bio.SeqIO import FastaIO set inFast = argv at 1 set outFast = argv at 2 set speciesAccession = list set NAJNAcheck = dict set HYDUCRcheck = dict set PROFLcheck = dict set outputrecord = list comment open the read in f...
#out dated by filterisofroms.py import sys import csv import re from Bio import SeqIO from Bio.SeqIO import FastaIO inFast = sys.argv[1] outFast = sys.argv[2] speciesAccession =[] NAJNAcheck ={} HYDUCRcheck = {} PROFLcheck ={} outputrecord =[] #open the read in fasta file and read in HYDCUR, NAJNA, or PROFL entrie...
Python
zaydzuhri_stack_edu_python
import random if __name__ == string __main__ begin set length = 50000 set numbers = list comprehension call randrange 65565 for i in range length set temp = 0 for i in range length begin for j in range length - 1 begin if numbers at j < numbers at j + 1 begin set temp = numbers at j set numbers at j = numbers at j + 1 ...
import random if __name__ == '__main__': length = 50000 numbers = [random.randrange(65565) for i in range(length)] temp = 0 for i in range(length): for j in range(length - 1): if numbers[j] < numbers[j+1]: temp = numbers[j] numbers[j] = numbers[j+1] ...
Python
zaydzuhri_stack_edu_python
from datetime import datetime from flask import Flask , render_template , request , redirect from flask_sqlalchemy import SQLAlchemy from datetime import date set app = call Flask __name__ comment <<<""for database"">>> set config at string SQLALCHEMY_DATABASE_URI = string sqlite:///todo.db comment <to handle a warning...
from datetime import datetime from flask import Flask, render_template, request, redirect from flask_sqlalchemy import SQLAlchemy from datetime import date app = Flask(__name__) #<<<""for database"">>> app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:///todo.db" #<to handle a warning> app.config['SQLALCHEMY_TRACK_MODI...
Python
zaydzuhri_stack_edu_python
import torch from torch.utils.data import Dataset from torchvision.transforms import ToTensor from pycocotools.coco import COCO from PIL import Image from typing import Any , Callable , Optional , Tuple , List import os class COCODataset extends Dataset begin function __init__ self is_train data_type image_size=448 num...
import torch from torch.utils.data import Dataset from torchvision.transforms import ToTensor from pycocotools.coco import COCO from PIL import Image from typing import Any, Callable, Optional, Tuple, List import os class COCODataset(Dataset): def __init__(self, is_train: str, ...
Python
zaydzuhri_stack_edu_python
for row in range 1 max_ + 1 begin for column in range 1 max_ + 1 begin print row * column end=string end print end set max_ = 14 for row in range 1 max_ + 1 begin for column in range 1 max_ + 1 begin print row * column end=string end print end
for row in range(1, max_ + 1): for column in range(1, max_ + 1): print(row * column, end='\t') print() max_ = 14 for row in range(1, max_ + 1): for column in range(1, max_ + 1): print(row * column, end='\t') print()
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import sys import os import shutil import deform_conv set f1 = open string output-resnet-size.txt string a function conv3x3 in_planes out_planes stride=1 begin return conv 2d in_planes out_planes kernel_size=3 stride=...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import sys import os import shutil import deform_conv f1 = open("output-resnet-size.txt", "a") def conv3x3(in_planes, out_planes, stride=1): return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride...
Python
zaydzuhri_stack_edu_python
function check_output *popenargs **kwargs begin set process = popen *popenargs stdout=PIPE keyword kwargs set tuple output unused_err = communicate process set retcode = poll process if retcode begin set cmd = get kwargs string args if cmd is none begin set cmd = popenargs at 0 end set error = call CalledProcessError r...
def check_output(*popenargs, **kwargs): process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] error = subproc...
Python
nomic_cornstack_python_v1
function write self data begin write audio data end function
def write(self, data): self.audio.write(data)
Python
nomic_cornstack_python_v1
comment l : 노드 길이, s : 점수 합 function dfs l s t begin global res if t > m begin return end if l == n begin print l s t res if s > res begin set res = s end print string res : res return res end else begin call dfs l + 1 s + scores at l t + times at l call dfs l + 1 s t end end function set tuple n m = map int split inpu...
def dfs(l,s,t) : # l : 노드 길이, s : 점수 합 global res if t > m : return if l == n : print(l, s, t, res) if s > res : res = s print("res : ",res) return res else : dfs(l+1, s+scores[l],t+times[l]) dfs(l+1, s, t) n,m = map(int,input().split...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 import turtle call shape string turtle call speed 0 call delay 0 call penup call goto 0 - 100 call pendown set n = 200 call begin_fill for i in range n begin call color string black string yellow call forward 5 call left 360 / n end call end_fill set k = 40 call penup call goto - 60 100 call p...
#!/usr/bin/python3 import turtle turtle.shape('turtle') turtle.speed(0) turtle.delay(0) turtle.penup() turtle.goto(0,-100) turtle.pendown() n = 200 turtle.begin_fill() for i in range(n): turtle.color('black', 'yellow') turtle.forward(5) turtle.left(360/n) turtle.end_fill() k=40 turtle.penup() turtle....
Python
zaydzuhri_stack_edu_python
import struct import sys
import struct import sys
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python string Return the children of the given SVN path. import pysvn import cgi import json import os.path function main begin string Get the CGI "path" field and return a list of its children as a JSON object. set form = call FieldStorage set path = value set client = call Client set contents = call...
#!/usr/bin/python """ Return the children of the given SVN path. """ import pysvn import cgi import json import os.path def main(): """ Get the CGI "path" field and return a list of its children as a JSON object. """ form = cgi.FieldStorage() path = form['path'].value client = pysvn.Clien...
Python
zaydzuhri_stack_edu_python
function unzip_dataset dataset begin set output_dir = call Path stem make directory output_dir with zip file dataset as archive begin extract all archive path=output_dir end comment members = archive.infolist() comment for zipinfo in members: comment archive.extract(zipinfo, output_dir) call unlink dataset end function
def unzip_dataset(dataset): output_dir = Path(dataset.stem) output_dir.mkdir() with zipfile.ZipFile(dataset) as archive: archive.extractall(path=output_dir) # members = archive.infolist() # for zipinfo in members: # archive.extract(zipinfo, output_dir) os.unlink(data...
Python
nomic_cornstack_python_v1
string Created on Nov 12, 2017 @author: Ale from RepositoryException import * from Assignment0507.domain.Discipline import * class DisciplineList begin function __init__ self begin set disciplinesList = list end function function add self discipline begin string Adds a discipline to the list input: the discipline we wa...
''' Created on Nov 12, 2017 @author: Ale ''' from RepositoryException import * from Assignment0507.domain.Discipline import * class DisciplineList: def __init__(self): self.disciplinesList = list() def add(self, discipline): """ Adds a discipline to the list input: the...
Python
zaydzuhri_stack_edu_python
function get_env_variable var_name prefix=VARIABLE_PREFIX as_bool=false begin if prefix is not none begin set var_name = prefix + var_name end try begin set value = environ at var_name if as_bool begin set value = lower value == string true end return value end except KeyError begin raise call ImproperlyConfigured stri...
def get_env_variable(var_name, prefix=VARIABLE_PREFIX, as_bool=False): if prefix is not None: var_name = prefix + var_name try: value = os.environ[var_name] if as_bool: value = value.lower() == 'true' return value except KeyError: raise ImproperlyConfigur...
Python
nomic_cornstack_python_v1
import unittest from hotel_book import HotelBook class BookHotelTest extends TestCase begin function test_book_regular_week_success self begin set book = call HotelBook assert equal call find_best_hotel_options string Regular: 16Mar2020(mon), 17Mar2020(tues), 18Mar2020(wed) string Parque das flores end function functio...
import unittest from hotel_book import HotelBook class BookHotelTest(unittest.TestCase): def test_book_regular_week_success(self): book = HotelBook() self.assertEqual(book.find_best_hotel_options("Regular: 16Mar2020(mon), 17Mar2020(tues), 18Mar2020(wed)"), "Parque das flores") de...
Python
zaydzuhri_stack_edu_python
function collect_paths self package begin set args = list dpkg_query string --no-pager string --listfiles package set tuple rc out err = call run_command args if rc != 0 begin error string dpkg-query failed err call fail_json msg=string dpkg-query failed rc=rc err=err end set paths = set for path in call splitlines beg...
def collect_paths(self, package): args = [self.dpkg_query, '--no-pager', '--listfiles', package] rc, out, err = self.module.run_command(args) if rc != 0: log.error('dpkg-query failed', err) self.module.fail_json(msg='dpkg-query failed', rc=rc, err=err) paths = set...
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd import cv2 import argparse set SIZE_FACE = 48 set EMOTIONS = list string angry string happy string sad string surprised string neutral set CASC_PATH = string ./haarcascade_files/haarcascade_frontalface_default.xml set cascade_classifier = call CascadeClassifier CASC_PATH set READ_...
import numpy as np import pandas as pd import cv2 import argparse SIZE_FACE = 48 EMOTIONS = ['angry', 'happy', 'sad', 'surprised', 'neutral'] CASC_PATH = './haarcascade_files/haarcascade_frontalface_default.xml' cascade_classifier = cv2.CascadeClassifier(CASC_PATH) READ_CSV_AT = { "train": "./data/train.csv", ...
Python
zaydzuhri_stack_edu_python
for i in range n begin remove card input end for i in card begin print i end
for i in range(n): card.remove(input()) for i in card: print(i)
Python
zaydzuhri_stack_edu_python
function test_query_handler begin return call QueryHandler end function
def test_query_handler(): return QueryHandler()
Python
nomic_cornstack_python_v1
function build_predict self Xnew task_ind begin set tuple Fmean Fvar = tuple 0 0 for i in array range rank begin for j in array range num_latent_list at i begin set lat_id = sum num_latent_list at slice : i : dtype=int64 + j comment need to compute fmean and fvar by the weights if whiten_list at lat_id begin set tupl...
def build_predict(self,Xnew,task_ind): Fmean,Fvar = 0,0 for i in np.arange(self.rank): for j in np.arange(self.num_latent_list[i]): lat_id = np.sum(self.num_latent_list[:i],dtype = np.int64) + j if self.whiten_list[lat_id]: # need to compu...
Python
nomic_cornstack_python_v1
import sys import json from receiver import Receiver from typing import List , Dict , Any , Optional class Writer begin function __init__ self begin set _help : Optional at str = none set _input : Optional at str = none set _prompt : Optional at str = none set _hide_combi_lines : Optional at bool = none set _exit_by_ca...
import sys import json from receiver import Receiver from typing import List, Dict, Any, Optional class Writer: def __init__(self): self._help: Optional[str] = None self._input: Optional[str] = None self._prompt: Optional[str] = None self._hide_combi_lines: Optional[bool] = None ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- comment @author Maxime Hutinet import random import hashlib function DisplayValuesKeys m p g a A begin print format string Message : {} Prime number p = {} Generator g = {} A = g^a % p : {} Public Key (p, g, A) = ({}, {}, {}) Private Key a = {} m p g A p g A a...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @author Maxime Hutinet import random import hashlib def DisplayValuesKeys(m, p, g, a, A): print("Message : {}\nPrime number p = {}\nGenerator g = {}\nA = g^a % p : {}\n\nPublic Key (p, g, A) = ({}, " "{}, {})\nPrivate Key a = {}".format(m, p, g, A, p, g,...
Python
zaydzuhri_stack_edu_python
function GetDataFromURL self url begin try begin set deftimeout = call getdefaulttimeout call setdefaulttimeout 1 try begin debug string Slide fetching data from %s % url set u = url open url set data = read u return data end except any begin exception string Uh oh! return none end end finally begin call setdefaulttime...
def GetDataFromURL(self, url): try: deftimeout = socket.getdefaulttimeout() socket.setdefaulttimeout(1) try: logging.debug('Slide fetching data from %s' % url) u = urllib.urlopen(url) data = u.read() return data except: logging.exception('Uh oh!') ...
Python
nomic_cornstack_python_v1
function authenticateToSharedNote self guid noteKey begin pass end function
def authenticateToSharedNote(self, guid, noteKey): pass
Python
nomic_cornstack_python_v1
from typing import Union class AlgoUtils begin string Class container for algorithm utility functions. decorator staticmethod function Encode data encoding=string utf-8 begin string Encode to bytes. Args: data (str or bytes): Data encoding (str) : Encoding type Returns: bytes: String encoded to bytes Raises: TypeError:...
from typing import Union class AlgoUtils: """ Class container for algorithm utility functions. """ @staticmethod def Encode(data: Union[bytes, str], encoding: str = "utf-8") -> bytes: """ Encode to bytes. Args: data (str or bytes): Data encoding (st...
Python
zaydzuhri_stack_edu_python
import socket set sock = call socket print string Socket created comment Reserve a port number set port = 2345 comment Bind to port. call bind tuple string port print string Socket bound to port %s % port comment Put socket into listening mode call listen 5 print string Socket listening comment Create a loop to run un...
import socket sock = socket.socket() print("Socket created") # Reserve a port number port = 2345 # Bind to port. sock.bind(('', port)) print("Socket bound to port %s" %(port) ) # Put socket into listening mode sock.listen(5) print("Socket listening") # Create a loop to run until exit or error. while True: # E...
Python
zaydzuhri_stack_edu_python
function get_underline_thickness self font fontsize dpi begin raise call NotImplementedError end function
def get_underline_thickness(self, font, fontsize, dpi): raise NotImplementedError()
Python
nomic_cornstack_python_v1
function BubbleSort ulist begin comment This variable is used to break the loop when sorting is done set done = 0 while not done begin set done = 1 for i in range length ulist - 1 begin if ulist at i > ulist at i + 1 begin set tuple ulist at i ulist at i + 1 = tuple ulist at i + 1 ulist at i set done = 0 end end end en...
def BubbleSort(ulist): done = 0 #This variable is used to break the loop when sorting is done while not done: done = 1 for i in range(len(ulist) - 1): if ulist[i] > ulist[i+1]: ulist[i], ulist[i+1] = ulist[i+1], ulist[i] done = 0
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup import urllib2 , re import xlwt import requests from xlrd import open_workbook comment Open the excel sheet to write the data set book = call Workbook encoding=string utf-8 set sheet1 = call add_sheet string Costs set i = 0 write sheet1 i 0 string SR Number write sheet1 i 1 string College ...
from bs4 import BeautifulSoup import urllib2, re import xlwt import requests from xlrd import open_workbook # Open the excel sheet to write the data book = xlwt.Workbook(encoding="utf-8") sheet1 = book.add_sheet('Costs') i = 0 sheet1.write(i,0,"SR Number") sheet1.write(i,1,"College Name") sheet1.write(i,2,"Net Price...
Python
zaydzuhri_stack_edu_python
function random_number_generator lhs rhs begin string This function generates a random number between given range (lhs, rhs) import random return random integer lhs rhs end function
def random_number_generator(lhs, rhs): '''This function generates a random number between given range (lhs, rhs)''' import random return random.randint(lhs, rhs)
Python
jtatman_500k
function find_peak list_of_integers begin set table = list_of_integers set value = 0 if table begin for i in range length table begin if i == 1 begin if table at i > table at i + 1 begin set value = table at i end end else if i == length table - 1 begin if table at i > table at i - 1 begin set value = table at i end en...
def find_peak(list_of_integers): table = list_of_integers value = 0 if table: for i in range(len(table)): if i == 1: if table[i] > table[i + 1]: value = table[i] elif i == len(table) - 1: if table[i] > table[i - 1]: ...
Python
nomic_cornstack_python_v1
comment Leia 2 valores de ponto flutuante de dupla precisão A e B, que correspondem a comment 2 notas de um aluno. A seguir, calcule a média do aluno, sabendo que a nota A comment tem peso 3.5 e a nota B tem peso 7.5 (A soma dos pesos portanto é 11). Assuma comment que cada nota pode ir de 0 até 10.0, sempre com uma ca...
# Leia 2 valores de ponto flutuante de dupla precisão A e B, que correspondem a # 2 notas de um aluno. A seguir, calcule a média do aluno, sabendo que a nota A # tem peso 3.5 e a nota B tem peso 7.5 (A soma dos pesos portanto é 11). Assuma # que cada nota pode ir de 0 até 10.0, sempre com uma casa decimal. a = floa...
Python
zaydzuhri_stack_edu_python
function get_arr_edge_indices arr res=string 4x5 extra_points_point_on_edge=none verbose=true debug=false begin if verbose begin print tuple string get_arr_edge_indices for arr of shape: shape end comment initialise variables set tuple lon_c lat_c NIU = call get_latlonalt4res res=res centre=true set tuple lon_e lat_e N...
def get_arr_edge_indices(arr, res='4x5', extra_points_point_on_edge=None, verbose=True, debug=False): if verbose: print(('get_arr_edge_indices for arr of shape: ', arr.shape)) # initialise variables lon_c, lat_c, NIU = get_latlonalt4res(res=res, centre=True) lon_e, lat_...
Python
nomic_cornstack_python_v1
function JS_S_T3P_SDIST Dataframe HNAME_List Raceday begin set Feature_DF = loc at tuple slice : : list string HNAME string SNAME set SNAME_List = string ( + string call tolist at slice 1 : - 1 : + string ) set Distance = values at 0 set Extraction = call Extraction_Database format string Select SNAME, Num_Races, T...
def JS_S_T3P_SDIST(Dataframe, HNAME_List, Raceday): Feature_DF = Dataframe.loc[:,['HNAME','SNAME']] SNAME_List = '('+str(Dataframe.loc[:,'SNAME'].tolist())[1:-1]+')' Distance = Dataframe.loc[:,'RADIS'].values[0] Extraction = Extraction_Database(""" Select SNAME, Nu...
Python
nomic_cornstack_python_v1
function calcWei RX RY RA RB RV begin comment calculate the weight matrix between the vertices using information of the coordinates of the vertices and some other comment relevant factors, in this case, speed set n = length RX set wei = zeros tuple n n dtype=float set m = length RA for i in range m begin set xa = RX at...
def calcWei(RX,RY,RA,RB,RV): # calculate the weight matrix between the vertices using information of the coordinates of the vertices and some other # relevant factors, in this case, speed n = len(RX) wei = np.zeros((n,n),dtype=float) m = len(RA) for i in range(m): xa = RX[RA[i]-1]...
Python
zaydzuhri_stack_edu_python
import math from pygame import image , Color , joystick set myChars = list set myDirs = list tuple 0 1 tuple - 1 1 tuple - 1 0 tuple - 1 - 1 tuple 0 - 1 tuple 1 - 1 tuple 1 0 tuple 1 1 set collisionmap = load image string images/collisionmap.png call init set joyin0 = false set joyin1 = false if call get_count > 0 beg...
import math from pygame import image, Color, joystick myChars = [] myDirs = [(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1), (1,0),(1,1)] collisionmap = image.load('images/collisionmap.png') joystick.init() joyin0 = joyin1 = False if(joystick.get_count() > 0): joyin0 = joystick.Joystick(0) joyin0.init() if(joystick.get_co...
Python
zaydzuhri_stack_edu_python
function get_num_takeouts add begin set name = call get_zipcode_names add set engine = call get_sql_engine set number_takeouts = call text string SELECT COUNT("NAME") as num_takeouts FROM chinese_takeout WHERE "ZIP" = :name set resp = call fetchone return resp at string num_takeouts end function
def get_num_takeouts(add): name=get_zipcode_names(add) engine = get_sql_engine() number_takeouts = text( """ SELECT COUNT("NAME") as num_takeouts FROM chinese_takeout WHERE "ZIP" = :name """ ) resp = engine.execute(number_takeouts, name=name).fetchon...
Python
nomic_cornstack_python_v1
import requests import json from common.Log import MyLog as Log class RunMain begin function send_Post self url data begin set result = json post url=url data=data set res = dumps result ensure_ascii=false sort_keys=true indent=2 return res end function function send_Get self url data begin set result = json get reques...
import requests import json from common.Log import MyLog as Log class RunMain(): def send_Post(self,url,data): result = requests.post(url= url,data= data).json() res = json.dumps(result ,ensure_ascii= False , sort_keys= True , indent= 2) return res def send_Get(self,url,data): ...
Python
zaydzuhri_stack_edu_python
function delete_meal_plan plan_id session=call Depends generate_session begin delete session plan_id return error string Mealplan Deleted end function
def delete_meal_plan(plan_id, session: Session = Depends(generate_session)): MealPlan.delete(session, plan_id) return SnackResponse.error("Mealplan Deleted")
Python
nomic_cornstack_python_v1
comment ************************** Necessary Imports *************************************** import matplotlib.pyplot as plt import numpy as np comment These are functions and libraries necessary to run the network you are bringing in import torch import torch.nn as nn import torch.nn.functional as F comment Once you'v...
# ************************** Necessary Imports *************************************** import matplotlib.pyplot as plt import numpy as np # These are functions and libraries necessary to run the network you are bringing in import torch import torch.nn as nn import torch.nn.functional as F # Once you've define the net...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver import time from pythonbot.secret1.pw import email , password import pandas as pd class Instabot begin function __init__ self user password begin set data = dict set user = user set password = password set driver = call Chrome get driver string https://www.instagram.com/ sleep 2 set user...
from selenium import webdriver import time from pythonbot.secret1.pw import email, password import pandas as pd class Instabot: def __init__(self, user, password): self.data = {} self.user = user self.password = password self.driver = webdriver.Chrome() self.driver.get('htt...
Python
zaydzuhri_stack_edu_python
function __str__ self begin set this_str = string Stack: Top of stack [ set n = length top for tuple i current in enumerate top begin set this_str = this_str + string current if i + 1 < n begin set this_str = this_str + string -> end end set this_str = this_str + format string ] Bottom of stack; length = {} length top ...
def __str__(self): this_str = "Stack: Top of stack [" n = len(self.top) for i, current in enumerate(self.top): this_str += str(current) if i + 1 < n: this_str += " -> " this_str += "] Bottom of stack; length = {}".format(len(self.top)) retu...
Python
nomic_cornstack_python_v1
function create_DOM_node_from_dict d name parent_node begin string Dumps dict data to an ``xml.etree.ElementTree.SubElement`` DOM subtree object and attaches it to the specified DOM parent node. The created subtree object is named after the specified name. If the supplied dict is ``None`` no DOM node is created for it ...
def create_DOM_node_from_dict(d, name, parent_node): """ Dumps dict data to an ``xml.etree.ElementTree.SubElement`` DOM subtree object and attaches it to the specified DOM parent node. The created subtree object is named after the specified name. If the supplied dict is ``None`` no DOM node is creat...
Python
jtatman_500k
import urllib.request import urllib.error import logging function DownloadFile url filename reporthook=none begin set log = call getLogger __name__ info format string Sending request to {} url try begin with url open url as response ; open filename string wb as out_file begin comment In case download isn't possible if ...
import urllib.request import urllib.error import logging def DownloadFile(url, filename, reporthook=None): log = logging.getLogger(__name__) log.info('Sending request to {}'.format(url)) try: with urllib.request.urlopen(url) as response, open(filename, 'wb') as out_file: #In case downlo...
Python
zaydzuhri_stack_edu_python
function getBackup self begin set query = string set conn = call get_connection set headers = dict string Content-type string application/json ; string Authorization string A10 %s % sessionid call request string GET call get_path + string / + query headers=headers set response = call getresponse set expected_status = ...
def getBackup(self): query = '' conn = self.get_connection() headers = { 'Content-type' : 'application/json', 'Authorization' : 'A10 %s' %self.sessionid} conn.request('GET', self.get_path() + '/' + query, headers=headers) response = conn.getresponse() expected_status = 200 errors = {500: 'An unexpected ru...
Python
nomic_cornstack_python_v1
from fractions import gcd function isPrime p begin if p > 1 begin for i in range 2 p begin if p % i == 0 begin return false end end for else begin return true end end else begin return false end end function function ETF n begin set relatively_prime = 0 for i in range n begin if call gcd i n == 1 begin set relatively_p...
from fractions import gcd def isPrime(p): if p > 1: for i in range(2,p): if (p % i) == 0: return False else: return True else: return False def ETF(n): relatively_prime = 0 for i in range(n): if gcd(i,n) == 1: ...
Python
zaydzuhri_stack_edu_python
import sys , time from PyQt5 import QtGui from PyQt5 import QtCore from PyQt5 import QtWidgets , uic from PyQt5.QtCore import QCoreApplication import socket from threading import Thread from socketserver import ThreadingMixIn set sock = none set wind = none class Window extends QDialog begin function __init__ self begi...
import sys,time from PyQt5 import QtGui from PyQt5 import QtCore from PyQt5 import QtWidgets, uic from PyQt5.QtCore import QCoreApplication import socket from threading import Thread from socketserver import ThreadingMixIn sock=None wind=None class Window(QtWidgets.QDialog): def __init__(self): super()....
Python
zaydzuhri_stack_edu_python
from itertools import permutations set N = input set arr = list set a = list permutations N length N set a = list set a sort a for i in range length a begin set st = string for j in range length a at i begin set st = st + a at i at j end append arr integer st end set b = index arr integer N set c = b + 1 if c < lengt...
from itertools import permutations N = input() arr = [] a = list(permutations(N, len(N))) a = list(set(a)) a.sort() for i in range(len(a)): st = '' for j in range(len(a[i])): st += a[i][j] arr.append(int(st)) b = arr.index(int(N)) c = b + 1 if c < len(arr): print(arr[c]) else: print(0)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- from collections import OrderedDict class Node begin function __init__ self key begin set id = key set connectedTo = ordered dictionary set status = string unvisited end function end class class Graph begin function __init__ self begin set nodes = ordered dictionary end function function a...
# -*- coding: utf-8 -*- from collections import OrderedDict class Node: def __init__(self, key): self.id = key self.connectedTo = OrderedDict() self.status = 'unvisited' class Graph: def __init__(self): self.nodes = OrderedDict() def addNode(self, ke...
Python
zaydzuhri_stack_edu_python
function get_named_policy self ptype begin return call get_policy string p ptype end function
def get_named_policy(self, ptype): return self.model.get_policy("p", ptype)
Python
nomic_cornstack_python_v1
function _load_data self input_file begin set seqs = transform call FastaToSeq normalize=false input_file return seqs end function
def _load_data(self, input_file): seqs = FastaToSeq(normalize=False).transform(input_file) return seqs
Python
nomic_cornstack_python_v1
import sys import math function IL begin return map int split right strip read line stdin end function function Main begin set tuple a b n = call IL set x = min b - 1 n print floor a * x / b - a * floor x / b return end function if __name__ == string __main__ begin call Main end
import sys import math def IL(): return map(int,sys.stdin.readline().rstrip().split()) def Main(): a,b,n = IL() x = min(b-1,n) print(math.floor(a*x/b)-a*math.floor(x/b)) return if __name__=='__main__': Main()
Python
zaydzuhri_stack_edu_python
string Erdos Number Class import graph import copy function main begin comment le o input do usuario set qtdInput = integer input set no_teste = 1 comment cria uma estrutura para armazenar todos os testes set gp = dict comment le novos inputs até digitar um 0 while qtdInput != 0 begin comment grafo para o novo teste s...
''' Erdos Number Class ''' import graph import copy def main(): qtdInput = int(input()) # le o input do usuario no_teste = 1 gp = {} # cria uma estrutura para armazenar todos os testes while(qtdInput != 0): # le novos inputs até digitar um 0 gp[no_teste] = graph.Graph(directed=True) ...
Python
zaydzuhri_stack_edu_python
import cv2 import imutils import matplotlib.pyplot as plt import numpy as np import time import os function colorFeat img bbox begin string Probability map of object likelihood based on color histogram Input: img - HSV image bbox - ROI of object Output: dst - Probability map of object location comment select object reg...
import cv2 import imutils import matplotlib.pyplot as plt import numpy as np import time import os def colorFeat(img, bbox): """ Probability map of object likelihood based on color histogram Input: img - HSV image bbox - ROI of object Output: dst - Probability map of object location ...
Python
zaydzuhri_stack_edu_python
if length set s == 1 begin print length s * k // 2 exit end set ss = s + s set shoko = 0 set prev = string set cnt = 0 for i in range length s begin if s at i == prev begin set cnt = cnt + 1 end else begin set shoko = shoko + cnt // 2 set cnt = 1 end set prev = s at i end set shoko = shoko + cnt // 2 set kosa = 0 set ...
if len(set(s)) == 1: print((len(s)*k)//2) exit() ss = s + s shoko = 0 prev = '' cnt = 0 for i in range(len(s)): if s[i] == prev: cnt += 1 else: shoko += cnt // 2 cnt = 1 prev = s[i] shoko += cnt // 2 kosa = 0 prev = '' cnt = 0 for i in range(len(ss)): if ss[i] == prev:...
Python
zaydzuhri_stack_edu_python
function manejador event begin set current_path = get current directory set file_path = join path current_path string TareaPythonPlus set tuple boton json_name = split replace event string - string string , with open join path file_path string ArchivosCSV string vgsales.csv string r encoding=string UTF-8 as archivo beg...
def manejador(event): current_path = os.getcwd() file_path = os.path.join(current_path,'TareaPythonPlus') boton,json_name = event.replace('-','').split(',') with open(os.path.join(file_path,'ArchivosCSV','vgsales.csv'),'r',encoding='UTF-8') as archivo: datos = csv.reader(archivo,delimiter=',') ...
Python
nomic_cornstack_python_v1
function indexes_equal a b begin string Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) return string a == string b end function
def indexes_equal(a: Index, b: Index) -> bool: """ Are two indexes equal? Checks by comparing ``str()`` versions of them. (AM UNSURE IF THIS IS ENOUGH.) """ return str(a) == str(b)
Python
jtatman_500k
function stationsLijst begin comment Inlog gegevens als variable set inlogegevens = tuple string sam.zandee@gmail.com string PR15gnkYhlxUuWrjXFnZ_yBHswBfR-clw1oYMkbMW7eeeNLD0sGd5A comment Aanroepen van het ns stations xml set stationsVanAPI = string http://webservices.ns.nl/ns-api-stations-v2 set responseStationLijst =...
def stationsLijst(): # Inlog gegevens als variable inlogegevens = ('sam.zandee@gmail.com', 'PR15gnkYhlxUuWrjXFnZ_yBHswBfR-clw1oYMkbMW7eeeNLD0sGd5A') # Aanroepen van het ns stations xml stationsVanAPI = 'http://webservices.ns.nl/ns-api-stations-v2' responseStationLijst = requests.get(stationsVanAPI,...
Python
nomic_cornstack_python_v1
from objet import ObjetRamassable class SacCouchage extends ObjetRamassable begin string Représente un sac de couchage permettant de se reposer quelques heures function utiliser self joueur begin call gagnerEnergie 50 end function function description self begin return string Sac de couchage end function end class
from objet import ObjetRamassable class SacCouchage(ObjetRamassable): """ Représente un sac de couchage permettant de se reposer quelques heures """ def utiliser(self, joueur): joueur.gagnerEnergie(50) def description(self): return "Sac de couchage"
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment coding: utf-8 comment File: preprocessing.py comment Author: lxw comment Date: 12/20/17 8:10 AM comment import matplotlib.pyplot as plt import numpy as np import pandas as pd comment import seaborn as sns import time from keras.preprocessing import sequence from collections import ...
#!/usr/bin/env python3 # coding: utf-8 # File: preprocessing.py # Author: lxw # Date: 12/20/17 8:10 AM # import matplotlib.pyplot as plt import numpy as np import pandas as pd # import seaborn as sns import time from keras.preprocessing import sequence from collections import Counter from pyfasttext import FastText ...
Python
zaydzuhri_stack_edu_python
function mode self begin return MODE_STORAGE end function
def mode(self) -> str: return MODE_STORAGE
Python
nomic_cornstack_python_v1
function __len__ self begin return length photos end function
def __len__(self): return len(self.photos)
Python
nomic_cornstack_python_v1
string 给定一个非负整数num。对于0 ≤ i ≤ num 范围中的每个数字i,计算其二进制数中的 1 的数目并将它们作为数组返回。 示例 1: 输入: 2 输出: [0,1,1] 示例2: 输入: 5 输出: [0,1,1,2,1,2] 进阶: 给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗? 要求算法的空间复杂度为O(n)。 你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的__builtin_popcount)来执行此操作。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/pro...
""" 给定一个非负整数num。对于0 ≤ i ≤ num 范围中的每个数字i,计算其二进制数中的 1 的数目并将它们作为数组返回。 示例 1: 输入: 2 输出: [0,1,1] 示例2: 输入: 5 输出: [0,1,1,2,1,2] 进阶: 给出时间复杂度为O(n*sizeof(integer))的解答非常容易。但你可以在线性时间O(n)内用一趟扫描做到吗? 要求算法的空间复杂度为O(n)。 你能进一步完善解法吗?要求在C++或任何其他语言中不使用任何内置函数(如 C++ 中的__builtin_popcount)来执行此操作。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/...
Python
zaydzuhri_stack_edu_python
function grad_potential self position beta check_numerics=true begin with call name_scope string grad_potential begin if call executing_eagerly begin set tfe = eager set grad_fn = call gradients_function potential_energy params=list string position set grad = call grad_fn position beta at 0 end else begin set grad = ca...
def grad_potential(self, position, beta, check_numerics=True): with tf.name_scope('grad_potential'): if tf.executing_eagerly(): tfe = tf.contrib.eager grad_fn = tfe.gradients_function(self.potential_energy, params=["pos...
Python
nomic_cornstack_python_v1
comment commandline argument is fs, dssp, 3A, 4A, or 5A. need 2 import numpy as np import pickle as pkl from pprint import pprint from sys import argv import matplotlib.pyplot as plt set tuple script m n = argv set nrpdb_dict = load pkl open string nrPDB_sasa.pkl string rb comment for plotting set megadict = dict strin...
# commandline argument is fs, dssp, 3A, 4A, or 5A. need 2 import numpy as np import pickle as pkl from pprint import pprint from sys import argv import matplotlib.pyplot as plt script, m, n = argv nrpdb_dict=pkl.load(open('nrPDB_sasa.pkl','rb')) megadict = {'3A': [], '4A': [], '5A': [], 'dssp':[], 'fs':[]} # for plo...
Python
zaydzuhri_stack_edu_python
function cached_reader reader sampled_rate cache_path cached_id begin seed cached_id set cache_path = join path cache_path string cached_id debug format string read data from: {} cache_path function s_reader begin if is directory path cache_path begin for file_name in open join path cache_path string list begin yield l...
def cached_reader(reader, sampled_rate, cache_path, cached_id): np.random.seed(cached_id) cache_path = os.path.join(cache_path, str(cached_id)) _logger.debug('read data from: {}'.format(cache_path)) def s_reader(): if os.path.isdir(cache_path): for file_name in open(os.path.join(cac...
Python
nomic_cornstack_python_v1
function fiveislands begin set fiveisyn = title strip input string Are you sure that you'd like to begin this side quest?(Y/N) if fiveisyn == string N begin input string You turn back. end else comment this depends on where we put the entrance. if fiveisyn == string Y begin call fiveis end else begin print string I'm s...
def fiveislands(): fiveisyn = input("Are you sure that you'd like to begin this side quest?(Y/N)").strip().title() if fiveisyn == ("N"): input("You turn back.") #this depends on where we put the entrance. elif fiveisyn == ("Y"): fiveis() else: print ("I'm sorry, I'm not s...
Python
zaydzuhri_stack_edu_python
function calculate_train_accuracy self begin set accuracy = list for pred in model_predictions begin append accuracy call accuracy_score y_train pred end return accuracy end function
def calculate_train_accuracy(self): accuracy = [] for pred in self.model_predictions: accuracy.append(accuracy_score(self.data_loader.y_train, pred)) return accuracy
Python
nomic_cornstack_python_v1
function colored_print msg colorname end=string begin print call color msg colorname end=end end function
def colored_print(msg: Any, colorname: str, end='\n') -> NoReturn: print(color(msg, colorname), end=end)
Python
nomic_cornstack_python_v1
function test_adaptive_iter_plot self begin call soft_avg 1 call noise 0 call set_sweep_functions list x y z call set_adaptive_function_parameters dict string adaptive_function nelder_mead ; string x0 list - 50 - 50 - 50 ; string initial_step list 2.5 2.5 2.5 call noise 0.5 call set_detector_function parabola run strin...
def test_adaptive_iter_plot(self): self.MC.soft_avg(1) self.mock_parabola.noise(0) self.MC.set_sweep_functions( [self.mock_parabola.x, self.mock_parabola.y, self.mock_parabola.z] ) self.MC.set_adaptive_function_parameters( { "adaptive_funct...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np set aruco = aruco set cap = call VideoCapture 0 comment C920の最大解像度を指定する width = 2304 height = 1536 fps = 2 set CAP_PROP_FPS 2 set CAP_PROP_FRAME_HEIGHT 1536 set CAP_PROP_FRAME_WIDTH 2304 comment 実際に利用できている解像度を取得する set tuple ret frame = read cap set tuple height width channels = shape at sl...
import cv2 import numpy as np aruco = cv2.aruco cap = cv2.VideoCapture(0) ## C920の最大解像度を指定する width = 2304 height = 1536 fps = 2 cap.set(cv2.CAP_PROP_FPS, 2) cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1536) cap.set(cv2.CAP_PROP_FRAME_WIDTH, 2304) # 実際に利用できている解像度を取得する ret, frame = cap.read() height, width, channels = frame....
Python
zaydzuhri_stack_edu_python
string - Attempt #3 Last Approach: • Sort the intervals by duration (ie: with respect to their end points) • Traverse through all intervals, if we get two overlapping intervals, then choose interval with lower end point since, to ensure that we don't overlap with any other interval. • Apply the same method to all the i...
''' - Attempt #3 Last Approach: • Sort the intervals by duration (ie: with respect to their end points) • Traverse through all intervals, if we get two overlapping intervals, then choose interval with lower end point since, to ensure that we don't overlap with any other interval. • Apply the same method to all the in...
Python
zaydzuhri_stack_edu_python
from DHeap import DHeap class PriorityQueue extends object begin function __init__ self reverse=false begin set heap = call DHeap minHeap=not reverse end function function __len__ self begin return length heap end function function enqueue self val begin insert heap val end function function dequeue self begin return p...
from DHeap import DHeap class PriorityQueue(object): def __init__(self, reverse=False): self.heap = DHeap(minHeap=not reverse) def __len__(self): return len(self.heap) def enqueue(self, val): self.heap.insert(val) def dequeue(self): return self.heap.pop() def fr...
Python
zaydzuhri_stack_edu_python
function exempted_members self begin return get pulumi self string exempted_members end function
def exempted_members(self) -> Sequence[str]: return pulumi.get(self, "exempted_members")
Python
nomic_cornstack_python_v1
function multiply arg1 arg2 begin if is instance arg1 Vector and is instance arg2 tuple int float begin set vector = list for i in range length vector begin append vector vector at i * arg2 end return call Vector name vector end else if is instance arg2 Vector and is instance arg1 tuple int float begin set vector = li...
def multiply(arg1, arg2): if isinstance(arg1, Vector) and isinstance(arg2, (int, float)): vector = [] for i in range(len(arg1.vector)): vector.append(arg1.vector[i] * arg2) return Vector(arg1.name, vector) elif isinstance(arg2, Vector) and isinstance(a...
Python
nomic_cornstack_python_v1
string The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? import itertools import math function prime begin yield 2 for i in count itertools 3 1 begin set sentinel = square root i for p in call prime begin if p > sentinel begin yield i break end if i % p == 0 b...
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ import itertools import math def prime(): yield 2 for i in itertools.count(3, 1): sentinel = math.sqrt(i) for p in prime(): if p > sentinel: yield i ...
Python
zaydzuhri_stack_edu_python
function binarySearch L low high begin string Recusive adaped binary search algorithm that returns true or false if there is a number in the range of lower and upper bound Parameters: L is a list, low and high are integers comment Base case if the length of the list is if length L < 1 begin comment empty then it hasn't...
def binarySearch(L,low,high): '''Recusive adaped binary search algorithm that returns true or false if there is a number in the range of lower and upper bound Parameters: L is a list, low and high are integers ''' if len(L) <1: #Base case if the length of the list is ...
Python
zaydzuhri_stack_edu_python
function check_signature signature message pub_port begin try begin comment get the public key of the port set pub_key = call get_pub_key pub_port comment verify the signature with the message call verify signature message call PSS mgf=call MGF1 algorithm=sha256 salt_length=MAX_LENGTH sha256 return true end except any ...
def check_signature(signature, message, pub_port): try: # get the public key of the port pub_key = ke.get_pub_key(pub_port) # verify the signature with the message pub_key.verify( signature, message, padding.PSS( mgf=padding.MGF1(a...
Python
nomic_cornstack_python_v1
function return_index self idx begin return tuple timeseries at idx ch_amount freq at idx ch_name at idx units at idx end function
def return_index(self, idx): return ( self.timeseries[idx], self.ch_amount, self.freq[idx], self.ch_name[idx], self.units[idx], )
Python
nomic_cornstack_python_v1
import math function is_753 s begin if string 0 in s begin return false end else if string 1 in s begin return false end else if string 2 in s begin return false end else if string 4 in s begin return false end else if string 6 in s begin return false end else if string 8 in s begin return false end else if string 9 in...
import math def is_753(s) : if ("0" in s) : return False elif ("1" in s) : return False elif ("2" in s) : return False elif ("4" in s) : return False elif ("6" in s) : return False elif ("8" in s) : return False elif ("9" in s) : return False if ("7" in s and "5" in s and "3"...
Python
zaydzuhri_stack_edu_python
from lib.JsonUtils import JsonUtils class FBFormat extends object begin function getQuickRepliesSuggestions res begin return dict string speech string ; string messages list dict string type 2 ; string platform string facebook ; string title string Below are the List of Suggestions? ; string replies res at string keyw...
from lib.JsonUtils import JsonUtils class FBFormat(object): def getQuickRepliesSuggestions(res): return { "speech": "", "messages": [ {"type": 2, "platform": "facebook", "title": "Below are the List of Suggestions?", ...
Python
zaydzuhri_stack_edu_python
comment Prints a table of contents for this project from re import search with open string Readme.md as f begin set hdrs = list comprehension strip l for l in read lines f if search string # l is not none end for h in hdrs begin comment headers should consist of several hash signs `#`, followed by a comment space, foll...
## Prints a table of contents for this project from re import search with open('Readme.md') as f: hdrs = [l.strip() for l in f.readlines() if search(r'#', l) is not None] for h in hdrs: # headers should consist of several hash signs `#`, followed by a # space, followed by a title ix = h.find(' ') ...
Python
zaydzuhri_stack_edu_python
from multiprocessing.connection import Listener import traceback comment writing an echo server function echo_client conn begin try begin while true begin set msg = call recv call send msg end end except EOFError begin print string Connection closed end end function function echo_server address authkey begin set serv =...
from multiprocessing.connection import Listener import traceback # writing an echo server def echo_client(conn): try: while True: msg = conn.recv() conn.send(msg) except EOFError: print('Connection closed') def echo_server(address, authkey): serv = Listener(address,...
Python
zaydzuhri_stack_edu_python
from time import sleep set n = 1 set evaluation_list = list 0 0 0 set slep_time = 2 function eval_person li begin if string person in li begin return 1 end else begin return 0 end end function function eval_cup li begin if string cup in li or string wine glass in li or string bottle in li begin return 1 end else begin ...
from time import sleep n=1; evaluation_list=[0,0,0] slep_time=2; def eval_person(li): if 'person' in li: return 1 else: return 0 def eval_cup(li): if 'cup' in li or 'wine glass' in li or 'bottle' in li: return 1 else: return 0 def eval_etc(li): if 'mouse' in li ...
Python
zaydzuhri_stack_edu_python
comment !c:/Python/python.exe comment -*- coding: utf-8 -*- set a = tuple string a 1 2 3 1.5 string c print a at slice : : comment print ("La Tupla elegida es: {} " . format(a[5])) for n in a begin print n end
#!c:/Python/python.exe # -*- coding: utf-8 -*- a = ("a",1,2,3,1.5,"c") print(a[:]) #print ("La Tupla elegida es: {} " . format(a[5])) for n in a: print(n)
Python
zaydzuhri_stack_edu_python
function increment_int t seconds begin set t_int = call time_to_int t set new_t_int = t_int + seconds set new_t = call int_to_time new_t_int comment For the pure functional version, could just return new_t. comment If we want to modify the time passed in, we need something different comment t = new_t won't work, becaus...
def increment_int(t, seconds): t_int = time_to_int(t) new_t_int = t_int + seconds new_t = int_to_time(new_t_int) # For the pure functional version, could just return new_t. # If we want to modify the time passed in, we need something different # t = new_t won't work, because that just makes our ...
Python
nomic_cornstack_python_v1
print 123 set name = input string plz key in your name: print name set int = 123 set float = 2.3 set str = string jack set bool = true print int float str bool
print(123) name = input("plz key in your name: ") print(name) int = 123 float = 2.3 str = 'jack' bool = True print(int, float, str, bool)
Python
zaydzuhri_stack_edu_python
function create_model_group self flow_limit **kwargs begin comment resources allocated to traffic demands, suc, spec, core_out, core_in set cnk_resource = dictionary comprehension u : list - 1 - 1 - 1 - 1 for u in traffic_pairs set cnk_group_suc = list set cnk_group_fail = list set obj_ = 0 set obj_connections_ = 0 s...
def create_model_group(self, flow_limit, **kwargs): # resources allocated to traffic demands, suc, spec, core_out, core_in self.cnk_resource = {u:[-1,-1,-1,-1] for u in self.traffic_pairs} self.cnk_group_suc = [] self.cnk_group_fail = [] self.obj_ = 0 self.obj_connections...
Python
nomic_cornstack_python_v1