code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function average_slope_intercept frame line_segments begin set lane_lines = list if line_segments is none begin info string No line_segment segments detected return lane_lines end set tuple height width _ = shape set left_fit = list set right_fit = list set boundary = 1 / 2 comment left lane line segment should be o...
def average_slope_intercept(frame, line_segments): lane_lines = [] if line_segments is None: logging.info('No line_segment segments detected') return lane_lines height, width, _ = frame.shape left_fit = [] right_fit = [] boundary = 1 / 2 left_region_boundary = width * (1 - b...
Python
nomic_cornstack_python_v1
from django import forms from models import PhoneBook class QuestionForm extends Form begin set first_name = call CharField widget=call TextInput attrs=dict string size string 50 set last_name = call CharField widget=call TextInput attrs=dict string size string 50 set phone_number = call CharField widget=call TextInput...
from django import forms from .models import PhoneBook class QuestionForm(forms.Form): first_name = forms.CharField(widget = forms.TextInput(attrs={'size': '50'})) last_name = forms.CharField(widget = forms.TextInput(attrs={'size': '50'})) phone_number = forms.CharField(widget = forms.TextInput(attrs={'siz...
Python
zaydzuhri_stack_edu_python
from ligo.gracedb.rest import GraceDbBasic , HTTPError import argparse function parseargs begin set parser = call ArgumentParser description=string Submit event to GraceDB call add_argument string group default=string test help=string MOU group responsible call add_argument string grace_id default=string EVENTNAME help...
from ligo.gracedb.rest import GraceDbBasic, HTTPError import argparse def parseargs(): parser = argparse.ArgumentParser(description='Submit event to GraceDB') parser.add_argument('group', default = 'test', help = 'MOU group responsible') parser.add_argument('grace_id',default = 'EVENTNAME', help ='Identif...
Python
zaydzuhri_stack_edu_python
function parse_libxc_docs path begin string Parse libxc_docs.txt file, return dictionary with mapping: libxc_id --> info_dict end function
def parse_libxc_docs(path): """ Parse libxc_docs.txt file, return dictionary with mapping: libxc_id --> info_dict """
Python
jtatman_500k
comment !/usr/bin/env python3 import pandas as pd import numpy as np function missing_value_types begin set countries = list string United Kingdom string Finland string USA string Sweden string Germany string Russia set year_of_inpedence = list none 1917 1776 1523 none 1992 set presidents = list none string Niinistö st...
#!/usr/bin/env python3 import pandas as pd import numpy as np def missing_value_types(): countries = ['United Kingdom', 'Finland', 'USA', 'Sweden', 'Germany', 'Russia'] year_of_inpedence = [None, 1917, 1776,1523,None,1992] presidents = [None, 'Niinistö', 'Trump', None, 'Steinmeier', 'Putin'] df =...
Python
zaydzuhri_stack_edu_python
from django.shortcuts import render from django.http import JsonResponse from models import Profile import json comment Create your views here. function index request begin set payload = dict string message string Hello World! set response = call JsonResponse payload return response end function function signup request...
from django.shortcuts import render from django.http import JsonResponse from .models import Profile import json # Create your views here. def index(request): payload={'message': 'Hello World!'} response = JsonResponse(payload) return response def signup (request): if request.method == "POST": ...
Python
zaydzuhri_stack_edu_python
from cv2 import cv2 import numpy as np set image1 = call imread string 1.jpg set image2 = call imread string 2.jpg set image3 = call imread string PP4A6535_20200301.jpg set image4 = call imread string PP4A6535_20200316.jpg set difference1 = call subtract image1 image2 set result1 = not any difference1 set difference2 =...
from cv2 import cv2 import numpy as np image1 = cv2.imread("1.jpg") image2 = cv2.imread("2.jpg") image3 = cv2.imread("PP4A6535_20200301.jpg") image4 = cv2.imread("PP4A6535_20200316.jpg") difference1 = cv2.subtract(image1, image2) result1 = not np.any(difference1) difference2 = cv2.subtract(image3, image4) result2 ...
Python
zaydzuhri_stack_edu_python
function make_symmetric_matrix n a b begin set B = zeros shape=tuple n n for i in range n begin for j in range i n begin set r = random integer a b set B at tuple i j = r set B at tuple j i = r end end return as type B int end function
def make_symmetric_matrix(n, a, b): B = np.zeros(shape=(n,n)) for i in range(n): for j in range(i, n): r = random.randint(a, b) B[i, j] = r B[j, i] = r return B.astype(int)
Python
nomic_cornstack_python_v1
function display self begin pass end function
def display(self): pass
Python
nomic_cornstack_python_v1
import os from builtins import print from demo.second.nester import print_lol import pickle change directory string E:\python_workspace set man = list set other = list try begin string w 写的模式 打开指定的文件,假如没有没有,之间创建一个文件 有则打开文件并清空里边的内容 w+ 打开一个文件进行写和读 不清除文件的内容; r 读的模式(默认) set data = open string first.txt for each_line in d...
import os from builtins import print from demo.second.nester import print_lol import pickle os.chdir("E:\python_workspace") man = [] other = [] try: """w 写的模式 打开指定的文件,假如没有没有,之间创建一个文件 有则打开文件并清空里边的内容 w+ 打开一个文件进行写和读 不清除文件的内容; r 读的模式(默认)""" data = open("first.txt") for each_line in data: ...
Python
zaydzuhri_stack_edu_python
function temp_converter begin set degreeC = input string What degree in C do you want to convert to F? set degreeF = integer degreeC * 9 / 5 + 32 print string Robbie says: print string I converted %s C in to %s F! % tuple degreeC degreeF end function
def temp_converter(): degreeC = input("What degree in C do you want to convert to F? ") degreeF = int(degreeC) * 9 / 5 + 32 print("\nRobbie says:\n") print("I converted %s C in to %s F!" % (degreeC, degreeF))
Python
nomic_cornstack_python_v1
function generate_document_vector self doc mode=string tfidf begin string Returns a representation of the specified document as a feature vector weighted according the mode specified (by default tf-dif). A custom weighting function can also be passed which receives the hashedindex instance, the selected term and docume...
def generate_document_vector(self, doc, mode='tfidf'): """ Returns a representation of the specified document as a feature vector weighted according the mode specified (by default tf-dif). A custom weighting function can also be passed which receives the hashedindex instance, th...
Python
jtatman_500k
import argparse import re import statistics import subprocess import time import graphviz as gv import NB.instance.instance as instance from NB import util from NB.construction_heuristic import construction_heuristic from NB.instance.instance import * from NB.neighbourhoods.CustomerInsertionIntra import CustomerInserti...
import argparse import re import statistics import subprocess import time import graphviz as gv import NB.instance.instance as instance from NB import util from NB.construction_heuristic import construction_heuristic from NB.instance.instance import * from NB.neighbourhoods.CustomerInsertionIntra import CustomerInser...
Python
zaydzuhri_stack_edu_python
function filter self value model=none context=none begin string Filter Performs value filtering and returns filtered result. :param value: input value :param model: parent model being validated :param context: object, filtering context :return: filtered value set value = string value return upper value end function
def filter(self, value, model=None, context=None): """ Filter Performs value filtering and returns filtered result. :param value: input value :param model: parent model being validated :param context: object, filtering context ...
Python
jtatman_500k
function stop_composite self test_item begin set msg = call StopComposite test_id=identifier call _request msg end function
def stop_composite(self, test_item): msg = messages.StopComposite(test_id=test_item.identifier) self._request(msg)
Python
nomic_cornstack_python_v1
function processLocalization host tator_api project_id section_name media localization localization_types_df attribute_types_info image_folder disable_thumbnails thumbnail_filename_pattern begin comment Get the media's pixel width to convert the relative width/height and position info set width = width set height = hei...
def processLocalization( host: str, tator_api: tator.api, project_id: int, section_name: str, media: tator.models.Media, localization: tator.models.Localization, localization_types_df: pd.DataFrame, attribute_types_info: dict, image_folder: str, ...
Python
nomic_cornstack_python_v1
function do_editor self editor begin set editor = editor print string Editor set: %s % editor end function
def do_editor(self, editor): self.editor = editor print("Editor set: %s" % self.editor)
Python
nomic_cornstack_python_v1
import cards_tools while true begin call cards_menu set selection = input string 请输入您要执行的选项: if selection in list string 1 string 2 string 3 begin print string - * 50 comment 新增名片,查看名片,查找名片 if selection == string 1 begin call action_1 end else if selection == string 2 begin call action_2 end else begin call action_3 en...
import cards_tools while True: cards_tools.cards_menu() selection = input("请输入您要执行的选项: ") if selection in ["1", "2", "3"]: print("-" * 50) # 新增名片,查看名片,查找名片 if selection == "1": cards_tools.action_1() elif selection == "2": cards_tools...
Python
zaydzuhri_stack_edu_python
function get_prompt self begin set prompt_pattern = call get_prompt_pattern prompt=string class_prompt=comms_prompt_pattern call _send_return set output = b'' while true begin set output = output + call _read_chunk if comms_ansi begin set output = call strip_ansi output=output end set channel_match = search pattern=pr...
def get_prompt(self) -> str: prompt_pattern = get_prompt_pattern(prompt="", class_prompt=self.comms_prompt_pattern) self._send_return() output = b"" while True: output += self._read_chunk() if self.comms_ansi: output = strip_ansi(output=output) ...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt import sklearn.linear_model from DeepLearning.CourseOne.planar_utils import plot_decision_boundary , sigmoid , load_planar_dataset , load_extra_datasets comment 定义神经网络的结构 function layer_sizes X Y begin comment size of input layer set n_x = shape at 0 comment size of ou...
import numpy as np import matplotlib.pyplot as plt import sklearn.linear_model from DeepLearning.CourseOne.planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets # 定义神经网络的结构 def layer_sizes(X, Y): n_x = X.shape[0] # size of input layer n_y = Y.shape[0] # size of output...
Python
zaydzuhri_stack_edu_python
import datetime from itertools import product , chain from collections import ChainMap import pandas as pd import numpy as np from scipy.interpolate import interp1d , Akima1DInterpolator , PchipInterpolator from tqdm import tqdm import pickle comment import matplotlib.pyplot as plt comment %matplotlib inline set p_list...
import datetime from itertools import product, chain from collections import ChainMap import pandas as pd import numpy as np from scipy.interpolate import interp1d, Akima1DInterpolator, PchipInterpolator from tqdm import tqdm import pickle # import matplotlib.pyplot as plt # %matplotlib inline p_list = [ 0.04, 0....
Python
zaydzuhri_stack_edu_python
function list_stacks region stack_ref all output field w watch begin call check_credentials region set stack_refs = call get_stack_refs stack_ref for _ in call watching w watch begin set rows = list for stack in call get_stacks stack_refs region all=all begin append rows dict string stack_name name ; string version ve...
def list_stacks(region, stack_ref, all, output, field, w, watch): check_credentials(region) stack_refs = get_stack_refs(stack_ref) for _ in watching(w, watch): rows = [] for stack in get_stacks(stack_refs, region, all=all): rows.append( { "s...
Python
nomic_cornstack_python_v1
from telethon import TelegramClient import socks import logging from config import API_HASH , API_ID , PROXY function proxy data begin string If you need proxy, example data = '123.456.789:1234:login:pass' if not data begin return none end set data = split data string : if length data == 4 begin set tuple host port log...
from telethon import TelegramClient import socks import logging from config import API_HASH, API_ID, PROXY def proxy(data: str): """ If you need proxy, example data = '123.456.789:1234:login:pass' """ if not data: return None data = data.split(":") if len(data) == 4: host, port...
Python
zaydzuhri_stack_edu_python
set guests = list string patel string shikhar string shah comment example 3-4 print string hey u r invited to dinner + string guests at 0 print string hey u r invited to dinner + string guests at 1 print string hey u r invited to dinner + string guests at 2 comment example 3-5 print string guests at 2 + string would no...
guests = ["patel","shikhar","shah"] print("hey u r invited to dinner " + str(guests[0])) # example 3-4 print("hey u r invited to dinner " + str(guests[1])) print("hey u r invited to dinner " + str(guests[2])) print(str(guests[2]) + " would not be able to come! " ) # example 3-5 guests[2]="bonde" print(...
Python
zaydzuhri_stack_edu_python
function get self request id_post begin set comments = filter post__pk=id_post set serialaizer = call CommentSerializer comments many=true return call Response dict string post pk id_post ; string comments data end function
def get(self, request, id_post): comments = Comment.objects.filter(post__pk=id_post) serialaizer = CommentSerializer(comments, many=True) return Response({"post pk": id_post, "comments": serialaizer.data})
Python
nomic_cornstack_python_v1
function describe_restaurant self begin print string The name of the restaurant is { name } , and they offer { type } food. end function
def describe_restaurant(self): print(f"The name of the restaurant is {self.name}, and they offer {self. type} food.")
Python
nomic_cornstack_python_v1
function generate_quadratic_heatmap batch_parameters img_height=DEFAULT_HEIGHT img_width=DEFAULT_WIDTH return_params=false begin comment if batch_parameters is None: comment centre_x, centre_y = get_initialization(img_height, img_width) set batch_size = shape at 0 set centre_x = call expand batch_size img_height img_wi...
def generate_quadratic_heatmap(batch_parameters, img_height=DEFAULT_HEIGHT, img_width=DEFAULT_WIDTH, return_params=False): # if batch_parameters is None: # centre_x, centre_y = get_initialization(img_height, img_width) batch_size = batch_parameters.shape[0] centre_x = batch_parameters[:, 0].unsquee...
Python
nomic_cornstack_python_v1
string Utilities used for all files import os import tqdm import heapq import networkx as nx import numpy as np import matplotlib.pyplot as plt import pylab import scipy.stats as stats import codecs import HTMLParser set parser = call HTMLParser set FILE_DIR = directory name path real path path __file__ set DEFAULT_PRO...
""" Utilities used for all files """ import os import tqdm import heapq import networkx as nx import numpy as np import matplotlib.pyplot as plt import pylab import scipy.stats as stats import codecs import HTMLParser parser = HTMLParser.HTMLParser() FILE_DIR = os.path.dirname(os.path.realpath(__file__)) DEFAULT...
Python
zaydzuhri_stack_edu_python
function test_dweet_for_without_a_key self begin try begin call dweet_for my_thing_id test_data end except DweepyError as e begin assert equal args at 0 string this thing is locked and requires a key end try else begin call fail string shouldn't ever get called end end function
def test_dweet_for_without_a_key(self): try: dweepy.dweet_for(self.my_thing_id, test_data) except dweepy.DweepyError as e: self.assertEqual(e.args[0], 'this thing is locked and requires a key') else: self.fail("shouldn't ever get called")
Python
nomic_cornstack_python_v1
from tkinter import * from winsound import * import pygame call init set root = call Tk function one begin load music string no-1.wav call play wait event end function function two begin load music string no-2.wav call play wait event end function function three begin load music string no-3.wav call play wait event end...
from tkinter import * from winsound import * import pygame pygame.init() root=Tk() def one(): pygame.mixer.music.load("no-1.wav") pygame.mixer.music.play() pygame.event.wait() def two(): pygame.mixer.music.load("no-2.wav") pygame.mixer.music.play() pygame.event.wait() def th...
Python
zaydzuhri_stack_edu_python
function hull_reduction hull begin if hull == string standard metal begin return 20 end else if hull == string hardened metal begin return 40 end else if hull == string almost but not quite cheater hull begin return 90 end else if hull == string almost cheater hull begin return 99 end else if hull == string cheater hul...
def hull_reduction(hull): if hull == 'standard metal': return 20 elif hull == "hardened metal": return 40 elif hull == 'almost but not quite cheater hull': return 90 elif hull == 'almost cheater hull': return 99 elif hull == 'cheater hull': return 100 '...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn import torch.nn.functional as F class StateBasedQNetwork extends Module begin function __init__ self state_size action_size seed begin call __init__ set seed = call manual_seed seed set fc1 = linear state_size 512 set fc2 = linear 512 256 set fc3 = linear 256 128 set fc4 = linear 128 ...
import torch import torch.nn as nn import torch.nn.functional as F class StateBasedQNetwork(nn.Module): def __init__(self, state_size, action_size, seed): super(StateBasedQNetwork, self).__init__() self.seed = torch.manual_seed(seed) self.fc1 = nn.Linear(state_size, 512) self.fc2 =...
Python
zaydzuhri_stack_edu_python
import AllesAnzeigen import NeueNote from tkinter import * class Application extends Frame begin function __init__ self master=none begin call __init__ master call pack call main end function function main self begin set t = call Label self text=string HI call pack set menu = call Menu master call config menu=menu set ...
import AllesAnzeigen import NeueNote from tkinter import * class Application(Frame): def __init__(self, master=None): super().__init__(master) self.pack() self.main() def main (self): self.t = Label(self, text="HI") self.t.pack() m...
Python
zaydzuhri_stack_edu_python
from typing import * from argparse import ArgumentParser from time import time from datetime import datetime as dt import os import tensorflow as tf import numpy as np from generator import GeneratorModel , generator_loss from discriminator import DiscriminatorModel , discriminator_loss from image_utils import generate...
from typing import * from argparse import ArgumentParser from time import time from datetime import datetime as dt import os import tensorflow as tf import numpy as np from generator import GeneratorModel, generator_loss from discriminator import DiscriminatorModel, discriminator_loss from image_utils import generate...
Python
zaydzuhri_stack_edu_python
import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import confusion_matrix set df = read csv string insurance_data.csv print head df scatter plt age bought_insurance marker=string + color=string red show from sklearn.model_selection import train_test_split set tuple x_train x_test y_train y_t...
import pandas as pd from matplotlib import pyplot as plt from sklearn.metrics import confusion_matrix df=pd.read_csv("insurance_data.csv") print(df.head()) plt.scatter(df.age,df.bought_insurance,marker="+",color="red") plt.show() from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test =...
Python
zaydzuhri_stack_edu_python
import random seed set fin = open string training.csv string r set fout = open string shuffled_training.csv string w set lst = read lines fin set tot = length lst for i in call xrange tot - 1 begin set rand = random integer i tot - 1 set tuple lst at i lst at rand = tuple lst at rand lst at i end for str in lst begin w...
import random random.seed() fin = open("training.csv", "r") fout = open("shuffled_training.csv", "w") lst = fin.readlines() tot = len(lst) for i in xrange(tot - 1): rand = random.randint(i, tot-1) lst[i], lst[rand] = lst[rand], lst[i] for str in lst: fout.write(str) fin.close() fout.close()
Python
zaydzuhri_stack_edu_python
string This script was used to create the figures for http://jrsmith3.github.io/sample-logs-the-secret-to-managing-multi-person-projects.html from a PDF file containing some old CMU sample logs. import PyPDF2 from polyglot.detect import Detector from wand.color import Color from wand.image import Image import io functi...
""" This script was used to create the figures for http://jrsmith3.github.io/sample-logs-the-secret-to-managing-multi-person-projects.html from a PDF file containing some old CMU sample logs. """ import PyPDF2 from polyglot.detect import Detector from wand.color import Color from wand.image import Image import io def...
Python
zaydzuhri_stack_edu_python
comment !/usr/local/bin/python3 comment coding=utf-8 comment 正则表达式通常被用来检索、替换那些符合某个模式的文本 comment 贪婪模式: import re set div_content = string 其它元素<div><span>用户:<span/><span>张三<span/></div> <br /><div><span>密码:<span/><span>123456<span/></div> 其它元素 set pattern = compile string <div>.*</div> set match = find all div_content pr...
#!/usr/local/bin/python3 #coding=utf-8 # 正则表达式通常被用来检索、替换那些符合某个模式的文本 # 贪婪模式: import re div_content = "其它元素<div><span>用户:<span/><span>张三<span/></div> <br /><div><span>密码:<span/><span>123456<span/></div> 其它元素" pattern = re.compile(r'<div>.*</div>') match = pattern.findall(div_content) print(match) """ 返回:['<div><span>用户...
Python
zaydzuhri_stack_edu_python
from django.http import HttpResponse from django.shortcuts import render function index request begin return call render request string index.html end function function about request begin set djtext = get POST string text string default set djtext1 = djtext set checkbox_input = get POST string removepunc string off se...
from django.http import HttpResponse from django.shortcuts import render def index(request): return render(request,'index.html') def about(request): djtext=request.POST.get('text','default') djtext1=djtext checkbox_input=request.POST.get('removepunc','off') extra_Space=request.POST.get('extraSpace...
Python
zaydzuhri_stack_edu_python
comment Utitlities function remove_prefix text prefix begin if starts with text prefix begin return text at slice length prefix : : end return text end function function remove_suffix text suffix begin return text at slice : - length suffix : end function function comment_suffix text begin if ends with text string ...
# Utitlities def remove_prefix(text, prefix): if text.startswith(prefix): return text[len(prefix):] return text def remove_suffix(text, suffix): return text[:-(len(suffix))] def comment_suffix(text): if text.endswith('s'): return remove_suffix(text, 'comments') else: re...
Python
zaydzuhri_stack_edu_python
import numpy as np set a = call loadtxt string matrixA.txt set b = call loadtxt string matrixB.txt set c = reshape dot b list 1 - 1 sort c set count = 1 with open string ./ans_one.txt string wt as f begin for x in call nditer c begin write f format string {} {} count integer x set count = count + 1 end end
import numpy as np a = np.loadtxt('matrixA.txt') b = np.loadtxt('matrixB.txt') c = a.dot(b).reshape([1, -1]) c.sort() count = 1 with open('./ans_one.txt', 'wt') as f: for x in np.nditer(c): f.write('{} {}\n'.format(count, int(x))) count += 1
Python
zaydzuhri_stack_edu_python
function increase_voltage self begin set function_string = string INCV + output return call scpi_comm function_string end function
def increase_voltage(self): function_string = 'INCV' + self.output return self.scpi_comm(function_string)
Python
nomic_cornstack_python_v1
import requests import xml.etree.ElementTree as ET import json import os import re set DBLP_URL = string https://dblp.uni-trier.de/pers/xx/ set PROFESSOR_DLPB_IDS = list string l/Laviolette:Fran=ccedil=ois string m/Marchand:Mario string l/Lamontagne:Luc string k/Khoury:Richard string c/Corbeil:Jacques string d/Durand:A...
import requests import xml.etree.ElementTree as ET import json import os import re DBLP_URL = 'https://dblp.uni-trier.de/pers/xx/' PROFESSOR_DLPB_IDS = [ "l/Laviolette:Fran=ccedil=ois", "m/Marchand:Mario", "l/Lamontagne:Luc", "k/Khoury:Richard", "c/Corbeil:Jacques", "d/Durand:Audrey", "g/...
Python
zaydzuhri_stack_edu_python
from bs4 import BeautifulSoup from urllib.request import urlopen import csv set my_url = string https://www.newegg.com/global/in-en/p/pl?d=graphic+card comment open a connection and get page set uClient = url open my_url comment grab the html set page_html = read uClient comment close a connection close uClient set pag...
from bs4 import BeautifulSoup from urllib.request import urlopen import csv my_url = 'https://www.newegg.com/global/in-en/p/pl?d=graphic+card' # open a connection and get page uClient = urlopen(my_url) # grab the html page_html = uClient.read() # close a connection uClient.close() page_soup = BeautifulSoup(page_html...
Python
zaydzuhri_stack_edu_python
function parse_time timestring begin set timestring = strip string timestring for tuple regex pattern in TIME_FORMATS begin if match timestring begin set found = call groupdict set dt = string parse time found at string time pattern set dt = call combine today time if string fraction in found and found at string fracti...
def parse_time(timestring): timestring = str(timestring).strip() for regex, pattern in TIME_FORMATS: if regex.match(timestring): found = regex.search(timestring).groupdict() dt = datetime.utcnow().strptime(found['time'], pattern) dt = datetime.combine(date.today(), ...
Python
nomic_cornstack_python_v1
if x < 10 begin print string Huh. I thought you'd choose something bigger end else if x >= 10 begin print string I knew you would choose that end
if x < 10: print('Huh. I thought you\'d choose something bigger') elif x >= 10: print('I knew you would choose that')
Python
zaydzuhri_stack_edu_python
function _update_center_position self position center begin set r1 = call generate_uniform_random_number set new_position = position + r1 * center - position return new_position end function
def _update_center_position(self, position: np.ndarray, center: np.ndarray) -> None: r1 = r.generate_uniform_random_number() new_position = position + r1 * (center - position) return new_position
Python
nomic_cornstack_python_v1
function node_info self begin set location_str = string { location at 0 } , { string location at 1 } , { string location at 2 } return dict string id key ; string pos location_str end function
def node_info(self) -> dict: location_str = f"{self.location[0]},{str(self.location[1])},{str(self.location[2])}" return {"id": self.key, "pos": location_str}
Python
nomic_cornstack_python_v1
function _convertKey self key begin if is instance key str begin if lower key in _STR_TO_QT begin set ascii = ordinal key set key = _STR_TO_QT at lower key return tuple key ascii end else begin raise call ValueError string Invalid key: %s % key end end else begin set ascii = ordinal get _QT_TO_STR key string return t...
def _convertKey(self, key): if isinstance(key, str): if key.lower() in _STR_TO_QT: ascii = ord(key) key = _STR_TO_QT[key.lower()] return key, ascii else: raise ValueError('Invalid key: %s' % key) else: as...
Python
nomic_cornstack_python_v1
from itertools import permutations function translate_string_to_list beer list_of_likes begin set translated_list = list for index in range 0 integer beer begin append translated_list list end for i in range 0 length list_of_likes begin for j in range 0 integer beer begin if list_of_likes at i at j == string Y begin i...
from itertools import permutations def translate_string_to_list(beer, list_of_likes): translated_list = [] for index in range(0, int(beer)): translated_list.append(list()) for i in range(0, len(list_of_likes)): for j in range(0, int(beer)): if list_of_likes[i][j] == "Y": ...
Python
zaydzuhri_stack_edu_python
function delete self item_id **params begin queue string delete item_id=item_id keyword params end function
def delete(self, item_id, **params): self.queue('delete', item_id=item_id, **params)
Python
nomic_cornstack_python_v1
import time class printer begin function gen_timestr self begin set tstr = string format time time string %Y/%m/%d %H:%M:%S call localtime time return tstr end function function gen_center_str self content len=42 frame=string ||| begin if type content == str begin set content = split content string end comment content ...
import time class printer(): def gen_timestr(self): tstr = time.strftime('%Y/%m/%d %H:%M:%S',time.localtime(time.time())) return tstr def gen_center_str(self, content, len=42, frame="|||"): if type(content)==str: content = content.split("\n") # content = [conten...
Python
zaydzuhri_stack_edu_python
function compSciArticles document begin set document = open document string r set document = read document set documentList = split document set docLength = length documentList set bagOfWords = list set outputLabel = dict set artScore = 0 comment Stop words taken from a site that google recommended to find stop words...
def compSciArticles(document): document = open(document, "r") document = document.read() documentList = document.split() docLength = len(documentList) bagOfWords = [ ] outputLabel = {} artScore = 0 #Stop words taken from a site that google recommended to find stop words for text mining ...
Python
zaydzuhri_stack_edu_python
function calc_listed_fitnesses self begin for tuple i p in enumerate populations begin for c in chromosomes begin set v = call list_values_replace i values c set fitness = call fitness_functions v at i end call sort_population end end function
def calc_listed_fitnesses(self): for i, p in enumerate(self.populations): for c in p.chromosomes: v = self.list_values_replace(i, c.values() ) c.fitness = self.fitness_functions(v)[i] p.sort_population()
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python comment -*- encoding: UTF-8 -*- import time from Modules.module import ModuleBaseClass from Applications.Survey import Survey import os import paramiko from scp import SCPClient class SurveyModule extends ModuleBaseClass begin string A survey module function __init__ self app name pepper_i...
#! /usr/bin/env python # -*- encoding: UTF-8 -*- import time from Modules.module import ModuleBaseClass from Applications.Survey import Survey import os import paramiko from scp import SCPClient class SurveyModule(ModuleBaseClass): """ A survey module """ def __init__(self, app, name, pepper_ip): ...
Python
zaydzuhri_stack_edu_python
comment 8. Escreva um programa que leia um valor qualquer e informe se ele é múltiplo de 5 (Use comment o operador %). comment Para um número natural ser múltiplo comment É preciso realizar a multiplicação de determinado número comment Por qualquer número do conjunto dos números naturais comment O resultado dos produto...
#8. Escreva um programa que leia um valor qualquer e informe se ele é múltiplo de 5 (Use #o operador %). # Para um número natural ser múltiplo # É preciso realizar a multiplicação de determinado número # Por qualquer número do conjunto dos números naturais # O resultado dos produtos da operação serão considerados múlt...
Python
zaydzuhri_stack_edu_python
with open string text_about_england.txt encoding=string utf-8 as f begin for line in f begin if string Category in line begin print line end=string end end print string end
with open("text_about_england.txt", encoding="utf-8") as f: for line in f: if "Category" in line: print(line, end="") print("")
Python
zaydzuhri_stack_edu_python
from flask import Flask , request , Blueprint from json import dumps import jwt import hashlib from Error import * from token_check import * from channel_check import * from data import * function channel_messages token channel_id start begin global data set data = call getData if call token_check token == false begin ...
from flask import Flask, request, Blueprint from json import dumps import jwt import hashlib from Error import * from token_check import * from channel_check import * from data import * def channel_messages(token, channel_id, start): global data data = getData() if token_check(token) == False: ...
Python
zaydzuhri_stack_edu_python
function parse_record raw_record is_training=true dtype=float32 begin set tuple image_buffer label bbox = call _parse_example_proto raw_record set image = call preprocess_image image_buffer=image_buffer bbox=bbox output_height=DEFAULT_IMAGE_SIZE output_width=DEFAULT_IMAGE_SIZE num_channels=NUM_CHANNELS is_training=is_t...
def parse_record(raw_record, is_training=True, dtype=tf.float32): image_buffer, label, bbox = _parse_example_proto(raw_record) image = imagenet_preprocessing.preprocess_image( image_buffer=image_buffer, bbox=bbox, output_height=DEFAULT_IMAGE_SIZE, output_width=DEFAULT_IMAGE_SIZE...
Python
nomic_cornstack_python_v1
function get_all_related_companies self include_self=false begin string Return all parents and subsidiaries of the company Include the company if include_self = True set parents = call get_all_parents set subsidiaries = call get_all_children set related_companies = parents ? subsidiaries if include_self is true begin s...
def get_all_related_companies(self, include_self=False): """ Return all parents and subsidiaries of the company Include the company if include_self = True """ parents = self.get_all_parents() subsidiaries = self.get_all_children() related_companies = parents | sub...
Python
jtatman_500k
function read_gbasis basis_lines fname begin string Reads gbasis-formatted file data and converts it to a dictionary with the usual BSE fields Note that the gbasis format does not store all the fields we have, so some fields are left blank set skipchars = string !# set basis_lines = list comprehension l for l in basis_...
def read_gbasis(basis_lines, fname): '''Reads gbasis-formatted file data and converts it to a dictionary with the usual BSE fields Note that the gbasis format does not store all the fields we have, so some fields are left blank ''' skipchars = '!#' basis_lines = [l for l in basis_...
Python
jtatman_500k
function recv self size timeout=0 begin set data = none wait psh_event timeout comment check if empty if length ingress_buffer != 0 begin if length ingress_buffer <= size begin set length = length ingress_buffer comment take chunk set data = ingress_buffer at slice : length : set ingress_buffer = ingress_buffer at sl...
def recv(self, size, timeout=0): data = None self.rtcp.psh_event.wait(timeout) if len(self.rtcp.ingress_buffer) != 0: # check if empty if len(self.rtcp.ingress_buffer) <= size: # length = len(self.rtcp.ingress_buffer) data = self.rtcp.ingress_buffer[...
Python
nomic_cornstack_python_v1
function always_together self pattern_dict singletons_dict begin title top string species that are always together in samples set scroll = call Scrollbar frame orient=VERTICAL grid row=0 column=3 sticky=N + S set text = call Text frame width=100 grid row=0 column=0 columnspan=3 set txt = string for tuple idx species_l...
def always_together(self, pattern_dict, singletons_dict): self.top.title('species that are always together in samples') scroll = Scrollbar(self.frame, orient=VERTICAL) scroll.grid(row=0, column=3, sticky=N+S) self.text = Text(self.frame, width=100) self.text.grid(row=0, ...
Python
nomic_cornstack_python_v1
function appendInStep self stepName assignments begin pass end function
def appendInStep(self, stepName: str, assignments: SymbolicConstant): pass
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt comment Load Data set x_MISO_MPC = call loadtxt string x_MISO_MPC.txt set u_MISO_MPC = call loadtxt string u_MISO_MPC.txt set x_MISO_DDPG_MPC = call loadtxt string x_MISO_DDPG_MPC.txt set u_MISO_DDPG_MPC = call loadtxt string u_MISO_DDPG_MPC.txt comment x_MIMO_DDPG_RL ...
import numpy as np import matplotlib.pyplot as plt # Load Data x_MISO_MPC = np.loadtxt('x_MISO_MPC.txt') u_MISO_MPC = np.loadtxt('u_MISO_MPC.txt') x_MISO_DDPG_MPC = np.loadtxt('x_MISO_DDPG_MPC.txt') u_MISO_DDPG_MPC = np.loadtxt('u_MISO_DDPG_MPC.txt') # # x_MIMO_DDPG_RL = np.loadtxt('x_MIMO_DDPG_RL.txt') # u_MIMO_DDPG...
Python
zaydzuhri_stack_edu_python
function serialize self root begin comment 前序遍历 set stack = list set preorder = string set cur = root append stack root while cur or stack begin set cur = pop stack if cur begin set preorder = preorder + string val + string , end else begin set preorder = preorder + string null + string , end if cur begin append stac...
def serialize(self, root): # 前序遍历 stack = [] preorder = "" cur = root stack.append(root) while cur or stack: cur = stack.pop() if cur: preorder += str(cur.val) + "," else: preorder += "null" + "," ...
Python
nomic_cornstack_python_v1
function main begin comment connect socket to server set sock = call connect comment login your user call login sock comment show all the options set options_message = string ----------------------------- for option in CLIENT_OPTIONS begin set options_message = options_message + string { option } - { index CLIENT_OPTIO...
def main(): # connect socket to server sock = connect() # login your user login(sock) # show all the options options_message = "-----------------------------" for option in CLIENT_OPTIONS: options_message += f'\n{option} - {CLIENT_OPTIONS.index(option) + 1}' print(options_messa...
Python
nomic_cornstack_python_v1
function get_stream_time_characteristic self begin set j_characteristic = call getStreamTimeCharacteristic return call _from_j_time_characteristic j_characteristic end function
def get_stream_time_characteristic(self) -> 'TimeCharacteristic': j_characteristic = self._j_stream_execution_environment.getStreamTimeCharacteristic() return TimeCharacteristic._from_j_time_characteristic(j_characteristic)
Python
nomic_cornstack_python_v1
function jsonData_to_dataset_in_timedifference_us data begin set the_cols = list string x string y string z string timestamp string label string hand string annotator set the_data = list for value in data begin set the_raws = list set the_indxs = list set idx = 0 set raw_time_us = 0 for raw in value at string raws b...
def jsonData_to_dataset_in_timedifference_us(data): the_cols = ['x', 'y', 'z', 'timestamp', 'label', 'hand', 'annotator'] the_data = [] for value in data: the_raws = [] the_indxs = [] idx = 0 raw_time_us = 0 for raw in value['raws']: raw_time_us += int(r...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment author: tzeng.yuxio@gmail.com comment usage: cat file.input | ./qround-problem-a.py > file.output import sys set strs = list function short s begin set rs = string set counts = list set cc = 0 for c in s begin if length rs == 0 begin set rs = rs + c set cc = 1 end else if c != rs at ...
#!/usr/bin/python # # author: tzeng.yuxio@gmail.com # usage: cat file.input | ./qround-problem-a.py > file.output import sys strs = [] def short(s): rs = "" counts = [] cc = 0 for c in s: if len(rs) == 0: rs += c cc = 1 elif c != rs[-1]: counts.appe...
Python
zaydzuhri_stack_edu_python
function histogram_by title df df_column sort_by height columns begin set paragraph = call add_paragraph string style=string Body Text set underline = true set alignment = CENTER figure histogram figsize=tuple 6.4 height by=df at sort_by bins=linear space 1 5 9 layout=tuple columns 2 sharey=true sharex=true xrot=90 ca...
def histogram_by(title, df, df_column, sort_by, height, columns): paragraph = document.add_paragraph('', style='Body Text') paragraph.add_run(title).underline = True paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER plt.figure() df[df_column].hist( figsize=(6.4, height), by=df[sort_by]...
Python
nomic_cornstack_python_v1
function get_washing_regex begin string Return a washing regex list. global _washing_regex if length _washing_regex begin return _washing_regex end set washing_regex = list tuple compile string (\snon)[- ](\w+) string \1\2 tuple compile string (\santi)[- ](\w+) string \1\2 tuple compile string \s\d- string tuple compi...
def get_washing_regex(): """Return a washing regex list.""" global _washing_regex if len(_washing_regex): return _washing_regex washing_regex = [ # Replace non and anti with non- and anti-. This allows a better # detection of keywords such as nonabelian. (re.compile(r"(\...
Python
jtatman_500k
string 类和对象 class A begin comment 一般都是需要的,存储代码,复用时绝大多情况下,数据是变化的,变化的数据提取为参数, comment 在类里面变化的参数放在初始化函数里, comment 需要对整个类传参数时,才用__init__,需要有变化的数据,通过不同的方法使用 function __init__ self param1 param2 begin pass end function function run self begin pass end function end class class B extends A begin function run_abc self begin pas...
"""类和对象""" class A: #一般都是需要的,存储代码,复用时绝大多情况下,数据是变化的,变化的数据提取为参数, # 在类里面变化的参数放在初始化函数里, # 需要对整个类传参数时,才用__init__,需要有变化的数据,通过不同的方法使用 def __init__(self,param1,param2): pass def run(self): pass class B(A): def run_abc(self): pass # 怎么得到对象:实例化 a = A('a','b') a.run() b = A()
Python
zaydzuhri_stack_edu_python
import requests set MAX_RETRIES = 3 function make_api_call begin set retries = 0 while retries < MAX_RETRIES begin try begin comment Retry mechanism for API call set response = get requests string https://api.example.com call raise_for_status comment Process API response break end except ConnectionError as ce begin pri...
import requests MAX_RETRIES = 3 def make_api_call(): retries = 0 while retries < MAX_RETRIES: try: # Retry mechanism for API call response = requests.get("https://api.example.com") response.raise_for_status() # Process API response break ...
Python
jtatman_500k
from json.decoder import JSONDecodeError import unittest from main import get_data , extract_schema class TestJSONtoSchema extends TestCase begin string Tests the various functions used in the converson of data from JSOn format to the python dict and back to JSON function test_getdata self begin assert equal type call ...
from json.decoder import JSONDecodeError import unittest from main import get_data, extract_schema class TestJSONtoSchema(unittest.TestCase): ''' Tests the various functions used in the converson of data from JSOn format to the python dict and back to JSON ''' def test_getdata(self): s...
Python
zaydzuhri_stack_edu_python
function get_chat begin set full_chat = list with open filename as file begin for line in file begin append full_chat dict string message right strip line string end end return full_chat end function function add_message name message begin with open filename string a as file begin write file string <b class="name"> + ...
def get_chat(): full_chat = [] with open(filename) as file: for line in file: full_chat.append({"message": line.rstrip("\n\r")}) return full_chat def add_message(name, message): with open(filename, "a") as file: file.write("<b class=\"name\">" + name + "</b>: ") ...
Python
zaydzuhri_stack_edu_python
string Do not change the input and output format. If our script cannot run your code or the format is improper, your code will not be graded. import sys import json import numpy as np function load_vocab filename_vocab begin string Loads and returns the mapping of word index to actual word string in the vocabulary. Arg...
""" Do not change the input and output format. If our script cannot run your code or the format is improper, your code will not be graded. """ import sys import json import numpy as np def load_vocab(filename_vocab): """Loads and returns the mapping of word index to actual word string in the vocabular...
Python
zaydzuhri_stack_edu_python
from __future__ import with_statement from accepts_block import accepts_block decorator accepts_block function bmap arr block begin return map block arr end function with call bmap list 1 2 3 as zootrope begin function foo x begin return decimal x + 1 / 2 end function end
from __future__ import with_statement from accepts_block import accepts_block @accepts_block def bmap(arr, block): return map(block, arr) with bmap([1,2,3]) as zootrope: def foo(x): return (float(x) + 1) / 2
Python
zaydzuhri_stack_edu_python
function _create_dir self begin debug string Creating directory %s for %s destination_dir name make directories destination_dir exist_ok=true end function
def _create_dir(self): logger.debug( "Creating directory %s for %s", self.destination_dir, self.name ) os.makedirs(self.destination_dir, exist_ok=True)
Python
nomic_cornstack_python_v1
if s == u begin set a = a - 1 end else if t == u begin set b = b - 1 end print a b
if (s == u): a -= 1 elif(t == u): b -= 1 print(a,b)
Python
zaydzuhri_stack_edu_python
function encrypt self filepath begin comment TODO(b/170396289): handle wildcards and recursive copies comment file type validation; can't handle directories or FIFOs if is directory path filepath begin call error_and_exit string cannot encrypt a directory end else if call S_ISFIFO st_mode begin call error_and_exit stri...
def encrypt(self, filepath): # TODO(b/170396289): handle wildcards and recursive copies # file type validation; can't handle directories or FIFOs if os.path.isdir(filepath): error_and_exit('cannot encrypt a directory') elif stat.S_ISFIFO(os.stat(filepath).st_mode): error_and_exit('cannot en...
Python
nomic_cornstack_python_v1
comment -*- coding:utf8 -*- comment 生成九九乘法表 comment 初始化表格为空 set table = string for i in range 1 10 begin for j in range 1 10 begin if i < j begin continue end set table = table + format string {} * {} = {} j i i * j comment 边界情况下换行 if i == j begin set table = table + string end end end print table
# -*- coding:utf8 -*- # 生成九九乘法表 # 初始化表格为空 table = '' for i in range(1, 10): for j in range(1, 10): if i < j: continue table += '{} * {} = {}\t'.format(j, i, i * j) # 边界情况下换行 if i == j: table += '\n' print(table)
Python
zaydzuhri_stack_edu_python
import os import argparse from wav_steganography.wav_file import WAVFile from pathlib import Path set audiofiles = list set filenames = list set parser = call ArgumentParser description=string start the encode script call add_argument string encode type=str help=string name of the encode txt-file call add_argument st...
import os import argparse from wav_steganography.wav_file import WAVFile from pathlib import Path audiofiles = [] filenames = [] parser = argparse.ArgumentParser(description="start the encode script") parser.add_argument("encode", type=str, help="name of the encode txt-file") parser.add_argument("--single", action="...
Python
zaydzuhri_stack_edu_python
comment -*- coding: UTF-8 -*- import sys import re from collections import Counter import multiprocessing as mp set rNUM = compile string (-|\+)?\d+((\.|·)\d+)?%? set rENG = compile string [A-Za-z_.]+ set hashtags = list string ## string () string ** string [] string () string 【】 string "" string “” string () string ()...
# -*- coding: UTF-8 -*- import sys import re from collections import Counter import multiprocessing as mp rNUM = re.compile(u'(-|\+)?\d+((\.|·)\d+)?%?') rENG = re.compile(u'[A-Za-z_.]+') hashtags = [u'##', u'()', u'**', u'[]', u'()', u'【】', u'\"\"', u'“”', u'()', u'()', u'【】'] patterns = [re.compile(u"\%s.*?\%s"%(ht[...
Python
zaydzuhri_stack_edu_python
import os function rename_files begin comment 1 get name of files from the folder set file_names = list directory string /Users/jinzegu/Downloads/prank end function
import os def rename_files(): #1 get name of files from the folder file_names = os.listdir(r'/Users/jinzegu/Downloads/prank')
Python
zaydzuhri_stack_edu_python
function gradient self x begin return where x < 0 alpha 1 end function
def gradient(self, x): return M.where(x < 0, self.alpha, 1)
Python
nomic_cornstack_python_v1
function SetupAndDispatch callback begin call SetInstance call SendGridEmailManager comment Try not to disturb production usage while checking and repairing the database. call ThrottleUsage set client = call Instance comment Dispatch command-line options. yield call Task Dispatch client call callback end function
def SetupAndDispatch(callback): EmailManager.SetInstance(SendGridEmailManager()) # Try not to disturb production usage while checking and repairing the database. ThrottleUsage() client = db_client.DBClient.Instance() # Dispatch command-line options. yield gen.Task(Dispatch, client) callback()
Python
nomic_cornstack_python_v1
comment pylint: disable=unused-import comment pylint: disable=import-error comment pylint: disable=wrong-import-position import functools import math import multiprocessing as mp import os import re import string import sys import time from collections import Counter , deque import heapq from enum import IntEnum from s...
# pylint: disable=unused-import # pylint: disable=import-error # pylint: disable=wrong-import-position import functools import math import multiprocessing as mp import os import re import string import sys import time from collections import Counter, deque import heapq from enum import IntEnum from struct import pack ...
Python
zaydzuhri_stack_edu_python
comment 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。 comment 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。 comment 此外,你可以假设该网格的四条边均被水包围。 comment 示例 1: comment 输入: comment 11110 comment 11010 comment 11000 comment 00000 comment 输出: 1 comment 示例 2: comment 输入: comment 11000 comment 11000 comment 00100 comment 00011 comment 输出:...
# 给你一个由 '1'(陆地)和 '0'(水)组成的的二维网格,请你计算网格中岛屿的数量。 # # 岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。 # # 此外,你可以假设该网格的四条边均被水包围。 # # 示例 1: # # 输入: # 11110 # 11010 # 11000 # 00000 # 输出: 1 # 示例 2: # # 输入: # 11000 # 11000 # 00100 # 00011 # 输出: 3 # 解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。 from typing import List from exercise.myUtils import t...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 function reverse_integer x begin if x < 0 begin return - call reverse_integer - x end set res = 0 while x begin set res = res * 10 + x % 10 set x = x // 10 end return if expression res <= 2147483647 then res else 0 end function set ret = call reverse_integer 12000 print ret
# coding: utf-8 def reverse_integer(x: int) -> int: if x < 0: return -reverse_integer(-x) res = 0 while x: res = res * 10 + x % 10 x //= 10 return res if res <= 0x7fffffff else 0 ret = reverse_integer(12000) print(ret)
Python
zaydzuhri_stack_edu_python
string Created on 2017 7 29 @author: zhengchenzhang import matplotlib.pyplot as plt import matplotlib.finance as plotf import matplotlib.ticker as mticker import matplotlib.dates as mdates import pylab import numpy as np import sys class PlotClass extends object begin function drawData self date openp closep highp lowp...
''' Created on 2017 7 29 @author: zhengchenzhang ''' import matplotlib.pyplot as plt import matplotlib.finance as plotf import matplotlib.ticker as mticker import matplotlib.dates as mdates import pylab import numpy as np import sys class PlotClass(object): def drawData(self, date, openp, closep, highp, lowp, vol...
Python
zaydzuhri_stack_edu_python
import serial import numpy as np from matplotlib import pyplot as plt import json from cmdlapp import CmdlApp class BME280Plot extends CmdlApp begin function __init__ self begin call __init__ self call configure main_fct=plot use_cfgfile=false tool_name=string bme280plot tool_version=string 0.0-dev set num_points = 500...
import serial import numpy as np from matplotlib import pyplot as plt import json from cmdlapp import CmdlApp class BME280Plot(CmdlApp): def __init__(self): CmdlApp.__init__(self) self.configure( main_fct=self.plot, use_cfgfile=False, tool_name='bme...
Python
zaydzuhri_stack_edu_python
from solutions.core.evaluation.rmsle_evaluation import RootMeanSquaredLogarithmError as rmsle import unittest import random class TestRootMeanSquaredLogarithmError extends TestCase begin function test_rmsle self begin seed 1000 set N = 550000 set max_error = list 0.005 0.01 0.1 0.3 0.5 set results = list 0.0 0.01 0.1 0...
from solutions.core.evaluation.rmsle_evaluation import RootMeanSquaredLogarithmError as rmsle import unittest import random class TestRootMeanSquaredLogarithmError(unittest.TestCase): def test_rmsle(self): random.seed(1000) N = 550000 max_error = [0.005, 0.01, 0.1, 0.3, 0.5] resu...
Python
zaydzuhri_stack_edu_python
function encripter begin set useroutput = string set number = integer input string quante lettere ci sono? print string inserire la parola lettera per lettera for i in range number + 1 begin set userinput = input string set useroutputbackup = useroutput if userinput == string a begin set useroutput = useroutputbackup ...
def encripter(): useroutput = (" ") number = int (input("quante lettere ci sono?")) print ("inserire la parola lettera per lettera") for i in range (number + 1): userinput = input ("") useroutputbackup = useroutput if userinput == ("a"): useroutput = (useroutp...
Python
zaydzuhri_stack_edu_python
function _load_tests self begin set tests = dict string enabled default dictionary list ; string disabled default dictionary list for tuple test_path test_type test in call iter_tests begin set enabled = not call disabled if not include_https and environment at string protocol == string https begin set enabled = false ...
def _load_tests(self): tests = {"enabled":defaultdict(list), "disabled":defaultdict(list)} for test_path, test_type, test in self.iter_tests(): enabled = not test.disabled() if not self.include_https and test.environment["protocol"] == "https": e...
Python
nomic_cornstack_python_v1
import requests set SHEETY_PRICE_ENDPOINT = string https://api.sheety.co/281b7b354b6373ee95bc3bc916c24399/flightDeals/prices set SHEETY_USER_ENDPOINT = string https://api.sheety.co/281b7b354b6373ee95bc3bc916c24399/flightDeals/users class DataManager begin string This class is responsible for talking to the Google Sheet...
import requests SHEETY_PRICE_ENDPOINT = "https://api.sheety.co/281b7b354b6373ee95bc3bc916c24399/flightDeals/prices" SHEETY_USER_ENDPOINT = "https://api.sheety.co/281b7b354b6373ee95bc3bc916c24399/flightDeals/users" class DataManager: """This class is responsible for talking to the Google Sheet.""" def __init...
Python
zaydzuhri_stack_edu_python
function state self begin return _state end function
def state(self): return self._state
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Dec 6 14:58:53 2018 @author: asus import csv import math comment packet class class packet extends object begin set url = string set val = 0 set score = 0 comment The class "constructor" - It's actually an initializer function __init__ self begin set rep = string se...
# -*- coding: utf-8 -*- """ Created on Thu Dec 6 14:58:53 2018 @author: asus """ import csv import math #packet class class packet(object): url = "" val = 0 score = 0 # The class "constructor" - It's actually an initializer def __init__(self): self.rep = "" ...
Python
zaydzuhri_stack_edu_python
function create_list_of_ships ship param_horzntal_battleField param_vertical_battleField begin set list_of_ships = list comment Horizontal check first: for line in range 0 10 begin if ship in param_horzntal_battleField at line begin set offset = 0 comment we will start our search at this index (covers case where > 1 s...
def create_list_of_ships(ship, param_horzntal_battleField, param_vertical_battleField): list_of_ships = [] # Horizontal check first: for line in range(0,10): if ship in param_horzntal_battleField[line]: offset = 0 start_offset = 0 # we will start our search at this i...
Python
zaydzuhri_stack_edu_python
function manual_go_terms_parser manual_go begin set manual_go_map = dict set manual_annotation = reader open manual_go string r delimiter=string for row in manual_annotation begin set manual_go_map at row at 1 = list comprehension term for term in split row at 2 string ; end return manual_go_map end function
def manual_go_terms_parser(manual_go): manual_go_map = {} manual_annotation = csv.reader(open(manual_go, "r"), delimiter = "\t") for row in manual_annotation: manual_go_map[row[1]] = [term for term in row[2].split("; ")] return manual_go_map
Python
nomic_cornstack_python_v1