code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment -*- coding: utf-8 -*- string Created on Wed May 26 20:23:22 2021 @author: calle Alejandro Calderon will work on this script import pandas as pd import time comment Read tables as dataframes comment file = os.path.join("..", "data", "Data Model Generated Network-13.xlsm") function read_data_rfep folder_path dict...
# -*- coding: utf-8 -*- """ Created on Wed May 26 20:23:22 2021 @author: calle Alejandro Calderon will work on this script """ import pandas as pd import time #Read tables as dataframes #file = os.path.join("..", "data", "Data Model Generated Network-13.xlsm") def read_data_rfep(folder_path, dict_tables_name, is_to_g...
Python
zaydzuhri_stack_edu_python
function evaluate_model model X_test Y_test label_names begin set Y_pred = predict model X_test comment Calculate classification report set metrics = call classification_report Y_test Y_pred target_names=label_names output_dict=true comment Create dataframe, tanspose it set metrics_df = T print metrics_df end function
def evaluate_model(model, X_test, Y_test, label_names): Y_pred = model.predict(X_test) # Calculate classification report metrics = classification_report( Y_test, Y_pred, target_names=label_names, output_dict=True, ) # Create data...
Python
nomic_cornstack_python_v1
function remove self idxs begin import utool as ut set keep_idxs = call index_complement idxs length self return call take keep_idxs end function
def remove(self, idxs): import utool as ut keep_idxs = ut.index_complement(idxs, len(self)) return self.take(keep_idxs)
Python
nomic_cornstack_python_v1
set list = list 1 6 2 8 4 9 set max_index = index list max list comment Output: 4 print max_index
list = [1, 6, 2, 8, 4, 9] max_index = list.index(max(list)) print(max_index) # Output: 4
Python
flytech_python_25k
string AUTHOR: Micah Braun PROJECT NAME: test_run.py (for waterregulation modules) DATE CREATED: 10/19/2018 LAST-UPDATED: 10/29/2018 PURPOSE: Lesson 6 DESCRIPTION: Unittests for Pump, Sensor, Controller, and Decider classes and their modules to check for proper functionality. import unittest from unittest.mock import M...
""" AUTHOR: Micah Braun PROJECT NAME: test_run.py (for waterregulation modules) DATE CREATED: 10/19/2018 LAST-UPDATED: 10/29/2018 PURPOSE: Lesson 6 DESCRIPTION: Unittests for Pump, Sensor, Controller, and Decider classes and their modules to check for proper functionality. """ import unittest from unittest.mock import ...
Python
zaydzuhri_stack_edu_python
string Starter code for logistic regression model to solve OCR task with MNIST in TensorFlow MNIST dataset: yann.lecun.com/exdb/mnist/ import os set environ at string TF_CPP_MIN_LOG_LEVEL = string 2 import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data import time comment...
""" Starter code for logistic regression model to solve OCR task with MNIST in TensorFlow MNIST dataset: yann.lecun.com/exdb/mnist/ """ import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data import time # Def...
Python
zaydzuhri_stack_edu_python
import numpy as np from scipy.spatial.distance import pdist string 马氏距离python实现 function mashi_distance_by_python x y begin string 纯python实现 comment 马氏距离要求样本数要大于维数,否则无法求协方差矩阵 comment 此处进行转置,表示10个样本,每个样本2维 set X = vertical stack list x y set XT = T comment 两个维度之间协方差矩阵 set S = call cov X comment 协方差矩阵的逆矩阵 set SI = call i...
import numpy as np from scipy.spatial.distance import pdist """ 马氏距离python实现 """ def mashi_distance_by_python(x, y): """ 纯python实现 """ # 马氏距离要求样本数要大于维数,否则无法求协方差矩阵 # 此处进行转置,表示10个样本,每个样本2维 X = np.vstack([x, y]) XT = X.T S = np.cov(X) # 两个维度之间协方差矩阵 SI = np.linalg.inv(S) # 协方差矩阵的逆矩阵...
Python
zaydzuhri_stack_edu_python
function bool2int x begin set y = 0 for tuple i j in enumerate x begin set y = y + j ? i end return y end function
def bool2int(x): y = 0 for i,j in enumerate(x): y += j<<i return y
Python
nomic_cornstack_python_v1
from django.db import models comment Create your models here. string Documentation for this module: This module of django contains all tables of the databse . class user extends Model begin string user data of the people interacting with the bot set mobile = call CharField max_length=250 default=string NULL set fbid = ...
from django.db import models # Create your models here. """ Documentation for this module: This module of django contains all tables of the databse . """ class user(models.Model): """user data of the people interacting with the bot """ mobile = models.CharField(max_length = 250 , default = 'NULL') fbi...
Python
zaydzuhri_stack_edu_python
function striding_windows arr batch_num=200 begin set batches = list for di in range length arr - batch_num + 1 begin set window = arr at slice di : di + batch_num : print di window append batches window end return array batches end function
def striding_windows(arr: list, batch_num=200) -> np.array: batches = [] for di in range(len(arr) - batch_num + 1): window = arr[di:di + batch_num] print(di, window) batches.append(window) return np.array(batches)
Python
nomic_cornstack_python_v1
comment Helper for some tests import sys import fileinput from insurance import Data set dataset = data load dataset stdin comment Find customers that chose a weirdo product set n = 0 for customer in values customers begin if not did_choose_browsed_plan begin print customer_id set n = n + 1 end end print print string %...
# Helper for some tests import sys import fileinput from insurance import Data dataset = Data() dataset.load(sys.stdin) # Find customers that chose a weirdo product n = 0 for customer in dataset.customers.values(): if not customer.did_choose_browsed_plan: print(customer.customer_id) n += 1 print() print("%d...
Python
zaydzuhri_stack_edu_python
string This program mediates between the AI instructions and the game itself through stdin and stdout import sys import subprocess class Manager begin set ai = string set game_name = string set best = 0 function __init__ self game ai gens=50 begin set gens = gens set game_name = game end function function openAI self...
""" This program mediates between the AI instructions and the game itself through stdin and stdout """ import sys import subprocess class Manager: ai = "" game_name = "" best = 0 def __init__(self, game, ai, gens=50): self.gens = gens self.game_name = game def openAI(self): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 from tkinter.filedialog import asksaveasfilename from tkinter.filedialog import askopenfilename from tkinter import * import alsaaudio , wave , threading class PiAudio extends Tk begin function __init__ self begin call __init__ self set nom_carte = string sysdefault:CARD=U0x46d0x825 set fi...
#!/usr/bin/env python3 from tkinter.filedialog import asksaveasfilename from tkinter.filedialog import askopenfilename from tkinter import * import alsaaudio, wave, threading class PiAudio(Tk): def __init__(self): Tk.__init__(self) self.nom_carte = 'sysdefault:CARD=U0x46d0x825' self.fichier...
Python
zaydzuhri_stack_edu_python
from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener import socket import sys import json comment Twitter consumer key, consumer secret, access token, access secret set ACCESS_TOKEN = string 741468980-hirgAI1iuJr8RyLlWS4zX86YsFVTsvnH84cNw4ND set ACCESS_SECRET = string Fc...
from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener import socket import sys import json # Twitter consumer key, consumer secret, access token, access secret ACCESS_TOKEN = '741468980-hirgAI1iuJr8RyLlWS4zX86YsFVTsvnH84cNw4ND' ACCESS_SECRET = 'FcUyRls8TBRQkloHTiWMqxzt1...
Python
zaydzuhri_stack_edu_python
comment CS B551 Fall 2017, Assignment #3 comment (Based on skeleton code by D. Crandall) string Title: To find POS tags of every word of a given sentence using hidden Markov model. We have implemented this using three techniques viz. a. Simple Naive Bayes Algorithm b. Variable Elimination (Forward-Backward algorithm) c...
################################### # CS B551 Fall 2017, Assignment #3 # # # (Based on skeleton code by D. Crandall) # # #### """ Title: To find POS tags of every word of a given sentence using hidden Markov model. We have implemented this using three techniques viz. a. Simple Naive Bayes Algorithm b. Variable Elimin...
Python
zaydzuhri_stack_edu_python
set tuple m n = split input set tuple m n = tuple integer m integer n set m = m ? n set n = m ? n set m = m ? n print m n
m,n=input().split() m,n=int(m),int(n) m=m^n n=m^n m=m^n print(m,n)
Python
zaydzuhri_stack_edu_python
class MaxStack begin function __init__ self begin set __stack = list end function function push self x begin append __stack x end function function pop self begin if length __stack != 0 begin pop __stack end end function function getMax self begin if length __stack == 0 begin return - 1 end return max __stack end func...
class MaxStack: def __init__(self): self.__stack=[] def push(self, x: int): self.__stack.append(x) def pop(self) -> None: if len(self.__stack)!=0: self.__stack.pop() def getMax(self): if len(self.__stack)==0: return -1 ...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf function dice_loss prediction label class_num begin comment softmax processing set softmax_prediction = softmax logits=prediction set ground_truth = call one_hot indices=label depth=class_num set loss = 0 comment unique = len(tf.unique(label)) for i in range class_num begin set i_prediction = so...
import tensorflow as tf def dice_loss(prediction, label, class_num): # softmax processing softmax_prediction = tf.nn.softmax(logits=prediction) ground_truth = tf.one_hot(indices=label, depth=class_num) loss = 0 # unique = len(tf.unique(label)) for i in range(class_num): i_prediction = ...
Python
zaydzuhri_stack_edu_python
from queue import PriorityQueue as pq from copy import deepcopy class Node begin function __init__ self mat move height parent=none begin set mat = mat set move = move set parent = parent set height = height end function comment makes nodes comparable function __lt__ self other begin return 0 end function function zero...
from queue import PriorityQueue as pq from copy import deepcopy class Node(): def __init__(self, mat, move,height,parent=None): self.mat = mat self.move = move self.parent = parent self.height=height def __lt__(self,other): #makes nodes comparable return 0 de...
Python
zaydzuhri_stack_edu_python
import unittest from model.model import to_uppercase from unittest import TestCase class ModelTest extends TestCase begin function test_uppercase self begin assert equal call to_uppercase string abc string ABC end function end class if __name__ == string __main__ begin call main end
import unittest from ..model.model import to_uppercase from unittest import TestCase class ModelTest(TestCase): def test_uppercase(self): self.assertEqual(to_uppercase('abc'), 'ABC') if __name__ == '__main__': unittest.main()
Python
zaydzuhri_stack_edu_python
function has_negatives a begin string YOUR CODE HERE comment Dictionary for values set vals = dict comment Iterate through numbers in a for num in a begin comment Check if the absolute value of num is in vals if absolute num in vals begin comment Increment the value associated with abs(a) set vals at absolute num = va...
def has_negatives(a): """ YOUR CODE HERE """ # Dictionary for values vals = {} # Iterate through numbers in a for num in a: # Check if the absolute value of num is in vals if abs(num) in vals: # Increment the value associated with abs(a) vals[abs(num)...
Python
zaydzuhri_stack_edu_python
import numpy as np from numpy import array from keras.models import Sequential , Model from keras.layers import Dense , LSTM , Input function split_sequence sequence n_steps begin set tuple x y = tuple list list comment 10 for i in range length sequence begin comment 0+4=4/// 6+4 set end_ix = i + n_steps if end_ix > le...
import numpy as np from numpy import array from keras.models import Sequential,Model from keras.layers import Dense, LSTM, Input def split_sequence(sequence, n_steps): x,y = list(), list() for i in range(len(sequence)): #10 end_ix = i + n_steps #0+4=4/// 6+4 if end_ix > len(sequence)-1...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn import torch.nn.functional as F class LSTMNet extends Module begin string model built with 2 lstm layers function __init__ self params device begin call __init__ comment ! https://pytorch.org/docs/stable/nn.html#torch.nn.LSTM comment initilize h0, c0 (num_layers * num_directions, batc...
import torch import torch.nn as nn import torch.nn.functional as F class LSTMNet(nn.Module): """ model built with 2 lstm layers """ def __init__(self, params, device): super(LSTMNet, self).__init__() #! https://pytorch.org/docs/stable/nn.html#torch.nn.LSTM # initilize h0, c...
Python
zaydzuhri_stack_edu_python
function test_reset_channel backend begin set original_backend = call get_backend call set_backend backend set initial_rho = call random_density_matrix 3 set c = call Circuit 3 density_matrix=true add c call ResetChannel 0 p0=0.2 p1=0.2 set final_rho = call c copy np initial_rho set dtype = dtype set collapsed_rho = re...
def test_reset_channel(backend): original_backend = qibo.get_backend() qibo.set_backend(backend) initial_rho = utils.random_density_matrix(3) c = models.Circuit(3, density_matrix=True) c.add(gates.ResetChannel(0, p0=0.2, p1=0.2)) final_rho = c(np.copy(initial_rho)) dtype = initial_r...
Python
nomic_cornstack_python_v1
from gsapi import * from gsapi.MathUtils import PatternMarkov import random import copy import logging set markovLog = call getLogger string gsapi.GSStyle.GSMarkovStyle class GSMarkovStyle extends GSStyle begin string compute sa style based on markov chains Args: order: order used for markov computation numSteps: numbe...
from gsapi import * from gsapi.MathUtils import PatternMarkov import random import copy import logging markovLog = logging.getLogger('gsapi.GSStyle.GSMarkovStyle') class GSMarkovStyle(GSStyle): """ compute sa style based on markov chains Args: order: order used for markov computation numSteps: number of steps...
Python
zaydzuhri_stack_edu_python
function recreatedb begin call drop_all call create_all end function
def recreatedb(): db.drop_all() db.create_all()
Python
nomic_cornstack_python_v1
function delete_asset self asset_id asset_type begin return call asset asset_id asset_type=asset_type action=string DELETE end function
def delete_asset(self, asset_id, asset_type): return self.asset(asset_id, asset_type=asset_type, action='DELETE')
Python
nomic_cornstack_python_v1
function send_email date result begin set message = call MIMEMultipart string alternative none list call MIMEText result string html set message at string Subject = string net_syslog for { date } set message at string From = FROM set message at string To = TO with call SMTP SERVER as server begin call sendmail FROM TO ...
def send_email(date, result): message = MIMEMultipart("alternative", None, [MIMEText(result, 'html')]) message['Subject'] = f"net_syslog for {date}" message['From'] = FROM message['To'] = TO with smtplib.SMTP(SERVER) as server: server.sendmail(FROM, TO, message.as_string())
Python
nomic_cornstack_python_v1
from datetime import datetime set d = input set a = string parse time d string %dth %b %Y print strip string a string 00:00:00
from datetime import datetime d=input() a=datetime.strptime(d,"%dth %b %Y") print(str(a).strip('00:00:00'))
Python
zaydzuhri_stack_edu_python
import unittest from transparencia_api.crawler.remuneracao_camara.remuneracao_camara_model import RemuneracaoCamaraModel class RemuneracaoCamaraModelTest extends TestCase begin function setUp self begin set remuneracaoModel = call RemuneracaoCamaraModel set dado = list string ABEL YOSHINOBU TAIRA string ANALISTA TEC.LE...
import unittest from transparencia_api.crawler.remuneracao_camara.remuneracao_camara_model import RemuneracaoCamaraModel class RemuneracaoCamaraModelTest(unittest.TestCase): def setUp(self): self.remuneracaoModel = RemuneracaoCamaraModel() self.dado = ["ABEL YOSHINOBU TAIRA", "ANALISTA TEC.LEG-DE...
Python
zaydzuhri_stack_edu_python
function get_function_path_and_options function begin comment Try to pop the options off whatever they passed in. set options = get attribute function string _async_options none return tuple call reference_to_path function options end function
def get_function_path_and_options(function): # Try to pop the options off whatever they passed in. options = getattr(function, '_async_options', None) return reference_to_path(function), options
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup import requests function get_repos uri begin set r = get requests uri set soup = call BeautifulSoup text string html.parser set table = table for row in find all table string tr at slice 1 : : begin set column = find all row string td at 0 yield string %s%s % tuple uri a at string href e...
from bs4 import BeautifulSoup import requests def get_repos(uri): r = requests.get(uri) soup = BeautifulSoup(r.text, "html.parser") table = soup.table for row in table.find_all('tr')[1:]: column = row.find_all('td')[0] yield "%s%s" % (uri, column.a['href'])
Python
zaydzuhri_stack_edu_python
function delete_all_refresh_tokens self user_id begin set keys = keys redis_db string * { user_id } * if keys begin delete *keys end end function
def delete_all_refresh_tokens(self, user_id: str): keys = redis_db.keys(f"*{user_id}*") if keys: redis_db.delete(*keys)
Python
nomic_cornstack_python_v1
function find_max_consecutive_vowels s max_count=0 max_substrings=list count=0 substring=string begin if s == string begin if count > max_count begin set max_count = count set max_substrings = list substring end else if count == max_count and count > 0 begin append max_substrings substring end return tuple max_count ...
def find_max_consecutive_vowels(s, max_count=0, max_substrings=[], count=0, substring=""): if s == "": if count > max_count: max_count = count max_substrings = [substring] elif count == max_count and count > 0: max_substrings.append(substring) return max_c...
Python
greatdarklord_python_dataset
import datetime function print_human_readable_date begin set days = list string Monday string Tuesday string Wednesday string Thursday string Friday string Saturday string Sunday set months = list string January string February string March string April string May string June string July string August string September ...
import datetime def print_human_readable_date(): days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] today = datetime.date.today() ...
Python
jtatman_500k
import pandas as pd , numpy as np , copy from sklearn.feature_selection import SelectKBest , f_classif from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split , GridSearchCV from sklearn.pipeline import Pipeline from sklearn.ensemble import RandomForestClassifier from sklearn...
import pandas as pd, numpy as np, copy from sklearn.feature_selection import SelectKBest, f_classif from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.pipeline import Pipeline from sklearn.ensemble import RandomForestClassifier from sklearn imp...
Python
zaydzuhri_stack_edu_python
function make_plots self indices=none hardcopy=false hardcopydir=string . hardcopyprefix=string hardcopytype=string png begin for tuple i E in enumerate experiments begin if indices == none or i in indices begin call show_plot hardcopy hardcopydir hardcopyprefix hardcopytype end end end function
def make_plots(self,indices=None,hardcopy=False,hardcopydir='.',hardcopyprefix='',hardcopytype='png'): for (i,E) in enumerate(self.experiments): if(indices==None) or (i in indices): E.show_plot(hardcopy,hardcopydir,hardcopyprefix,hardcopytype)
Python
nomic_cornstack_python_v1
set protein1 = string msrslllrfllfllllpplp set protein2 = string MSRSLLLRFLLFLLLLPPLP set protein3 = string MSRSLLLRFLLFLLLLPPLP set list1 = list string L
protein1 = "msrslllrfllfllllpplp" protein2 = "MSRSLLLRFLLFLLLLPPLP" protein3 = "MSRSLLLRFLLFLLLLPPLP" list1=["L"]
Python
zaydzuhri_stack_edu_python
comment contoh penggunaan modul getpass import getpass set password = call getpass
# contoh penggunaan modul getpass import getpass password = getpass.getpass()
Python
zaydzuhri_stack_edu_python
function assays self begin return _assay_queryset end function
def assays(self): return self._assay_queryset
Python
nomic_cornstack_python_v1
string Replay each URL on a list through the replay proxy, and gather results. import argparse import threading import time from pyvirtualdisplay import Display from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import UnexpectedAlertPresentException f...
"""Replay each URL on a list through the replay proxy, and gather results.""" import argparse import threading import time from pyvirtualdisplay import Display from selenium import webdriver from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import UnexpectedAlertPresentException ...
Python
zaydzuhri_stack_edu_python
function serialize self writer begin if not writer begin raise call TypeError string writer cannot be null. end call serialize writer call write_object_value string emailSettings email_settings call write_int_value string workflowScheduleIntervalInHours workflow_schedule_interval_in_hours end function
def serialize(self,writer: SerializationWriter) -> None: if not writer: raise TypeError("writer cannot be null.") super().serialize(writer) writer.write_object_value("emailSettings", self.email_settings) writer.write_int_value("workflowScheduleIntervalInHours", self.workflow_...
Python
nomic_cornstack_python_v1
function IPban message begin if lower call GetArg 0 == string list begin if not ipbans begin call Reply string Nobody is currently IP banned end else begin call Reply string List of currently banned IPs: + join string , ipbans end end else if call GetArg 1 begin set action = lower call GetArg 0 if action == string remo...
def IPban(message): if message.GetArg(0).lower() == "list": if not ipbans: message.Reply("Nobody is currently IP banned") else: message.Reply("List of currently banned IPs: " + ", ".join(ipbans)) elif message.GetArg(1): action = message.GetArg(0).lower() if action == "remove": ipbans.discard(message....
Python
nomic_cornstack_python_v1
function get_bullet self paragraph begin try begin set pPr = next call iterfind call qn string w:pPr set numPr = next call iterfind call qn string w:numPr set numId = attrib at call qn string w:val set ilvl = attrib at call qn string w:val try begin set numFmt = numId2numFmts at string numId at integer ilvl end except ...
def get_bullet(self, paragraph: EtreeElement) -> str: try: pPr = next(paragraph.iterfind(qn("w:pPr"))) numPr = next(pPr.iterfind(qn("w:numPr"))) numId = next(numPr.iterfind(qn("w:numId"))).attrib[qn("w:val")] ilvl = next(numPr.iterfind(qn("w:ilvl"))).attrib[qn("w:...
Python
nomic_cornstack_python_v1
function scatter self *args **kwargs begin set cls = call _make_class ScatterVisual _default_marker=pop kwargs string marker none return call _add_item cls *args keyword kwargs end function
def scatter(self, *args, **kwargs): cls = _make_class(ScatterVisual, _default_marker=kwargs.pop('marker', None), ) return self._add_item(cls, *args, **kwargs)
Python
nomic_cornstack_python_v1
function fix_bulkrename self begin set bulkrename_cls = call get_command string bulkrename if not bulkrename_cls begin return end set editor = call getenv string EDITOR if not editor begin set editor = string nvim end set code = call dedent get source execute set code = replace code string def execute string def bulkre...
def fix_bulkrename(self): bulkrename_cls = self.commands.get_command('bulkrename') if not bulkrename_cls: return editor = os.getenv('EDITOR') if not editor: editor = 'nvim' code = textwrap.dedent(inspect.getsource(bulkrename_cls.execute)) code = ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Sep 26 21:49:19 2018 @author: Rafiya import numpy as np import scipy as sp comment one option for a 2D convolution library import scipy.signal import cv2 import matplotlib.pyplot as plt from os import path import seam_carving as sc comment img = cv2.imread("sample_ima...
# -*- coding: utf-8 -*- """ Created on Wed Sep 26 21:49:19 2018 @author: Rafiya """ import numpy as np import scipy as sp import scipy.signal # one option for a 2D convolution library import cv2 import matplotlib.pyplot as plt from os import path import seam_carving as sc ### img = cv2.imread("sample_image.png",...
Python
zaydzuhri_stack_edu_python
function rget dict_object path_list begin try begin return reduce lambda d k -> d at k path_list dict_object end except KeyError begin return dict_object end end function
def rget(dict_object, path_list): try: return reduce(lambda d, k: d[k], path_list, dict_object) except KeyError: return dict_object
Python
nomic_cornstack_python_v1
string 개요: continue문 작성자: 진상영 작성일: 2021.03.22 내용: continue문은 반복문의 시작 지점으로 제어의 흐름 변경 - while문 : 조건식 이동 실행 - for문 : 반복가능객체 이동 나머지 실행 comment fruits = ['사과', '감귤'] comment count = 3 comment while count > 0: comment fruit = input('어떤 과일을 저장할까요?>>> ') comment if fruit in fruits: comment print('동일한 과일이 있습니다.') comment contin...
''' 개요: continue문 작성자: 진상영 작성일: 2021.03.22 내용: continue문은 반복문의 시작 지점으로 제어의 흐름 변경 - while문 : 조건식 이동 실행 - for문 : 반복가능객체 이동 나머지 실행 ''' # fruits = ['사과', '감귤'] # count = 3 # # while count > 0: # fruit = input('어떤 과일을 저장할까요?>>> ') # if fruit in fruits: # print('동일한 과일이 있습니다.') # continue # fruit...
Python
zaydzuhri_stack_edu_python
for i in range integer input begin set n = integer input set l = list map int split input while length l != 2 begin set r = sorted l remove l r at 1 remove r r at 1 end print string l at 0 + string + string l at 1 end
for i in range(int(input())): n = int(input()) l = list(map(int,input().split())) while len(l) != 2: r = sorted(l) l.remove(r[1]) r.remove(r[1]) print(str(l[0]) + " " + str(l[1]))
Python
zaydzuhri_stack_edu_python
import re set text = string Hello, my cell is (770) 555-1234 set phoneNumRegex = compile string (\(\d\d\d\)) (\d\d\d-\d\d\d\d) set match = search text print match print call group 0 print call group 1 print call group 2 print call group
import re text = "Hello, my cell is (770) 555-1234" phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)') match = phoneNumRegex.search(text) print(match) print(match.group(0)) print(match.group(1)) print(match.group(2)) print(match.group())
Python
zaydzuhri_stack_edu_python
function SqueezeNet include_top=true input_shape=none weights=string imagenet input_tensor=none pooling=none classes=1000 **kwargs begin if weights not in set literal string imagenet none begin raise call ValueError string The `weights` argument should be either `None` (random initialization) or `imagenet` (pre-trainin...
def SqueezeNet(include_top=True, input_shape=None, weights='imagenet', input_tensor=None, pooling=None, classes=1000, **kwargs): if weights not in {'imagenet', None}: raise ValueError('The `weights` argument should be...
Python
nomic_cornstack_python_v1
function get_param_groups core selection=string kep begin if selection == string all begin set selection = string kep_binary_gr_pm_spin_pos_noise_dm_chrom_dmx_fd end set kep_pars = list string PB string PBDOT string T0 string A1 string OM string E string ECC string EPS1 string EPS2 string EPS1DOT string EPS2DOT string ...
def get_param_groups(core, selection="kep"): if selection == "all": selection = "kep_binary_gr_pm_spin_pos_noise_dm_chrom_dmx_fd" kep_pars = [ "PB", "PBDOT", "T0", "A1", "OM", "E", "ECC", "EPS1", "EPS2", "EPS1DOT", "...
Python
nomic_cornstack_python_v1
function typecheck values nans=list begin set types = list for v in values begin if v == none begin append types TYPE_EMPTY end else begin try begin set test = integer v append types TYPE_INTEGER end except any begin try begin set test = decimal lower v append types TYPE_FLOAT end except any begin append types TYPE_ST...
def typecheck(values, nans=[]): types = [] for v in values: if v == None: types.append(TYPE_EMPTY) else: try: test = int(v) types.append(TYPE_INTEGER) except: try: test = float(v.lower()) ...
Python
nomic_cornstack_python_v1
string Save models to saved_models folder function save_model model model_name begin set model_json = to json model with open string saved_models\ + model_name + string .json string w as json_file begin write json_file model_json end comment serialize weights to HDF5 call save_weights string saved_models\ + model_name ...
""" Save models to saved_models folder """ def save_model(model, model_name): model_json = model.to_json() with open("saved_models\\" + model_name + ".json", "w") as json_file: json_file.write(model_json) # serialize weights to HDF5 model.save_weights("saved_models\\" + model_name+ ".h5") pr...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np from datetime import datetime import pytz from math import ceil import matplotlib.pyplot as plt from matplotlib import cm import seaborn as sns call set_style string white function get_data_from_csv begin return read csv string ../data/USvideos.csv end function function delete_dup...
import pandas as pd import numpy as np from datetime import datetime import pytz from math import ceil import matplotlib.pyplot as plt from matplotlib import cm import seaborn as sns sns.set_style("white") def get_data_from_csv(): return pd.read_csv("../data/USvideos.csv") def delete_duplicates(df): df = ...
Python
zaydzuhri_stack_edu_python
function cast obj begin return call itkAdaptiveHistogramEqualizationImageFilterISS2_cast obj end function
def cast(obj: 'itkLightObject') -> "itkAdaptiveHistogramEqualizationImageFilterISS2 *": return _itkAdaptiveHistogramEqualizationImageFilterPython.itkAdaptiveHistogramEqualizationImageFilterISS2_cast(obj)
Python
nomic_cornstack_python_v1
import math import torch from torch.nn import functional as F from networks import eta_to_gamma , get_eta_scale function unsqueeze_x_as_y x y begin if ndim == ndim begin return x end assert size x 0 == size y 0 return view x - 1 *[1] * (y.ndim - 1) end function class GaussianDiffusion begin function __init__ self num_t...
import math import torch from torch.nn import functional as F from networks import eta_to_gamma, get_eta_scale def unsqueeze_x_as_y(x, y): if x.ndim == y.ndim: return x assert x.size(0) == y.size(0) return x.view(-1, *([1, ] * (y.ndim-1)) ) class GaussianDiffusion: def __init__( sel...
Python
zaydzuhri_stack_edu_python
comment bot.py import os import datetime comment from datetime import datetime import discord from dotenv import load_dotenv from discord.ext import commands import json import asyncio from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from...
# bot.py import os import datetime #from datetime import datetime import discord from dotenv import load_dotenv from discord.ext import commands import json import asyncio from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.web...
Python
zaydzuhri_stack_edu_python
comment -*- coding=UTF-8 -*- string author:hamioo date:2018/1/23 describle:循环遍历 describle:循环遍历 for i in range 1 20 3 begin if i == 16 begin break end end
# -*- coding=UTF-8 -*- """ author:hamioo date:2018/1/23 describle:循环遍历 describle:循环遍历 """ for i in range(1, 20, 3): if i== 16: break
Python
zaydzuhri_stack_edu_python
function analyze_build_main bin_dir from_build_command begin set parser = call create_parser from_build_command set args = call parse_args call validate parser args from_build_command comment setup logging call initialize_logging verbose debug string Parsed arguments: %s args with call report_directory output keep_empt...
def analyze_build_main(bin_dir, from_build_command): parser = create_parser(from_build_command) args = parser.parse_args() validate(parser, args, from_build_command) # setup logging initialize_logging(args.verbose) logging.debug('Parsed arguments: %s', args) with report_directory(args.out...
Python
nomic_cornstack_python_v1
comment 주어진 튜플 (1,2,3,4,5,6,7,8,9,10)의 앞 항목 절반과 뒤 항목 절반을 출력하는 프로그램을 작성하십시오. set tu = tuple 1 2 3 4 5 6 7 8 9 10 print tu at slice 0 : 5 : print tu at slice 5 : 11 :
# 주어진 튜플 (1,2,3,4,5,6,7,8,9,10)의 앞 항목 절반과 뒤 항목 절반을 출력하는 프로그램을 작성하십시오. tu = (1,2,3,4,5,6,7,8,9,10) print(tu[0:5]) print(tu[5:11])
Python
zaydzuhri_stack_edu_python
function query_api term location begin set bearer_token = call obtain_bearer_token API_HOST TOKEN_PATH set response = search bearer_token term location set businesses = get response string businesses if not businesses begin print format string No businesses for {0} in {1} found. term location return end set business_id...
def query_api(term, location): bearer_token = obtain_bearer_token(API_HOST, TOKEN_PATH) response = search(bearer_token, term, location) businesses = response.get('businesses') if not businesses: print(u'No businesses for {0} in {1} found.'.format(term, location)) return business_...
Python
nomic_cornstack_python_v1
from collections import Counter set tuple N M = map int split input set primes = list set d = 2 while d ^ 2 <= M begin if M % d == 0 begin set M = M // d append primes d end else begin set d = d + 1 end end if M != 1 begin append primes M end set cnt = counter primes function choose n k begin import math return call f...
from collections import Counter N,M = map(int,input().split()) primes = [] d = 2 while d**2<=M: if M % d == 0: M //= d primes.append(d) else: d += 1 if M != 1: primes.append(M) cnt = Counter(primes) def choose(n,k): import math return math.factorial(n)//(math.factorial(n-k...
Python
zaydzuhri_stack_edu_python
function swt X wtf=string d4 nlevels=string conservative RetainVJ=false begin comment Get a valid wavelet transform filter coefficients struct. set wtf_s = call wtfilter wtf set wtfname = Name set gt = g set ht = h set L = L comment ensure X is a numpy array set X = array X if length shape > 1 begin raise call ValueErr...
def swt(X, wtf='d4', nlevels='conservative', RetainVJ=False): # Get a valid wavelet transform filter coefficients struct. wtf_s = wtfilter(wtf) wtfname = wtf_s.Name gt = wtf_s.g ht = wtf_s.h L = wtf_s.L # ensure X is a numpy array X = np.array(X) if len(X.shape)>1: rais...
Python
nomic_cornstack_python_v1
function test_post_apost self begin set url = string http://blog/postcreate/ set data = dict string title string new idea ; string text string Notre Dame Cathedral rebuilt in 5 years set request = post url data call force_authenticate request user=user token=token set response = call call as_view request assert status_...
def test_post_apost(self): url = 'http://blog/postcreate/' data = {'title': 'new idea', 'text':'Notre Dame Cathedral rebuilt in 5 years'} request = self.factory.post(url, data) force_authenticate(request, user=self.user, token=self.token) response = PostCreation.as_view()(request...
Python
nomic_cornstack_python_v1
function _apply_replacement error found_file file_lines begin set fixed_lines = file_lines set fixed_lines at line - 1 = replacement set concatenated_fixed_lines = join string fixed_lines comment Only fix one error at a time seek found_file 0 write found_file concatenated_fixed_lines call truncate end function
def _apply_replacement(error, found_file, file_lines): fixed_lines = file_lines fixed_lines[error[1].line - 1] = error[1].replacement concatenated_fixed_lines = "".join(fixed_lines) # Only fix one error at a time found_file.seek(0) found_file.write(concatenated_fixed_lines) found_file.trunc...
Python
nomic_cornstack_python_v1
for n in nums begin if n > 4 begin append twice n * 2 end end set twice = list comprehension n * 2 for n in nums if n > 4
for n in nums: if n > 4: twice.append(n * 2) twice = [n * 2 for n in nums if n > 4]
Python
zaydzuhri_stack_edu_python
set name = string alice wonderland comment 문자열의 수를 알려줌. length name comment name[-10]과 같음. print name at 6 comment 문자열은 immutable하기 때문에 변형이 안됨. set name at 0 = string A comment 6번째 열부터 12열전까지 출력-'wonder'문자열이 출력됨. name at slice 6 : 12 : comment 위와 같으 결과가 나옴. name at slice - 10 : 12 : comment 계산방향이 왼쪽부터 오른쪽 순서이기 때문에 왼쪽...
name='alice wonderland' len(name)# 문자열의 수를 알려줌. print(name[6]) #name[-10]과 같음. name[0]='A'#문자열은 immutable하기 때문에 변형이 안됨. name[6:12] #6번째 열부터 12열전까지 출력-'wonder'문자열이 출력됨. name[-10:12] #위와 같으 결과가 나옴. name[12:9]# 계산방향이 왼쪽부터 오른쪽 순서이기 때문에 왼쪽이 오른쪽보다 작아야함. name[ : 5] #숫자칸이 비어있으면 0으로 계산. name[12 : ] #생략된 부분이 len(name)이라고 생각.(문자열...
Python
zaydzuhri_stack_edu_python
function left self begin return integer round _box at 0 end function
def left(self): return int(round(self._box[0]))
Python
nomic_cornstack_python_v1
for i in range e begin set arr = list map int split right strip input append G at arr at 0 arr at 1 append GR at arr at 1 arr at 0 end for i in G begin sort i end for i in GR begin sort i end class prop begin function __init__ self u begin set u = u set flag = false set t1 = - 1 set t2 = - 1 end function end class clas...
for i in range(e): arr=list(map(int,input().rstrip().split())) G[arr[0]].append(arr[1]) GR[arr[1]].append(arr[0]) for i in G: i.sort() for i in GR: i.sort() class prop: def __init__(self,u): self.u=u self.flag=False self.t1=-1 self.t2=-1 class DFS: def __init__(self,G): self.graph=[] for i in G: s...
Python
zaydzuhri_stack_edu_python
import pandas as pd import os set DATA_DIRECTORY = string Data + sep set GI = read csv string Dataset S2 - Averaged E-MAP one allele per gene.csv header=none set GS = read csv string Dataset S3 - S.pombe Similarity Scores.csv header=none set output_name_GI = string gene_interactions set output_name_GS = string gene_sim...
import pandas as pd import os DATA_DIRECTORY = "Data" + os.sep GI = pd.read_csv("Dataset S2 - Averaged E-MAP one allele per gene.csv", header=None) GS = pd.read_csv("Dataset S3 - S.pombe Similarity Scores.csv", header=None) output_name_GI = "gene_interactions" output_name_GS = "gene_similarity" output_name_combined ...
Python
zaydzuhri_stack_edu_python
import csv import matplotlib.pyplot as plt import requests import pandas as pd from config2 import api_key from pprint import pprint function make_df city_list begin comment We will be making a list of dictionaries that we will eventually turn into our dataframe set dict_list = list comment Loops through every city in...
import csv import matplotlib.pyplot as plt import requests import pandas as pd from config2 import api_key from pprint import pprint def make_df(city_list): #We will be making a list of dictionaries that we will eventually turn into our dataframe dict_list = [] #Loops through every city in the p...
Python
zaydzuhri_stack_edu_python
function get_session_keys conn pairing_data begin set headers = dict string Content-Type string application/pairing+tlv8 comment Step #1 ios --> accessory (send verify start Request) (page 47) set ios_key = call Key25519 set request_tlv = call encode_list list tuple kTLVType_State M1 tuple kTLVType_PublicKey pubkey cal...
def get_session_keys(conn, pairing_data): headers = { 'Content-Type': 'application/pairing+tlv8' } # # Step #1 ios --> accessory (send verify start Request) (page 47) # ios_key = py25519.Key25519() request_tlv = TLV.encode_list([ (TLV.kTLVType_State, TLV.M1), (TLV.k...
Python
nomic_cornstack_python_v1
function test_thin begin set s = call SED string 1 wave_type=string nm flux_type=string fphotons set bp = call Bandpass join path datapath string LSST_r.dat string nm set flux = call calculateFlux bp print string Original number of bandpass samples = length wave_list for err in list 0.01 0.001 0.0001 1e-05 begin print ...
def test_thin(): s = galsim.SED('1', wave_type='nm', flux_type='fphotons') bp = galsim.Bandpass(os.path.join(datapath, 'LSST_r.dat'), 'nm') flux = s.calculateFlux(bp) print("Original number of bandpass samples = ",len(bp.wave_list)) for err in [1.e-2, 1.e-3, 1.e-4, 1.e-5]: print("Test err = ...
Python
nomic_cornstack_python_v1
function __create_preference_file begin try begin comment creates file set pref_file = open call get_preference_file string w comment creates the data structure set data = dict set data at string cache_manager_cache_path = string set data at string cache_manager_model_group = string set data at string cache_manager_...
def __create_preference_file(): try: # creates file pref_file = open(get_preference_file(), "w") # creates the data structure data = {} data["cache_manager_cache_path"] = "" data["cache_manager_model_group"] = "" data["cache_manager_unload_rigs"] = 1 ...
Python
nomic_cornstack_python_v1
function load_image self image_id begin comment Load image set image = call imread image_info at image_id at string path comment If grayscale. Convert to RGB for consistency. if ndim != 3 begin set image = call gray2rgb as type image / 65535 * 255 uint8 end comment If has an alpha channel, remove it for consistency if ...
def load_image(self, image_id): # Load image image = skimage.io.imread(self.image_info[image_id]['path']) # If grayscale. Convert to RGB for consistency. if image.ndim != 3: image = skimage.color.gray2rgb((image / 65535 * 255).astype(np.uint8)) # If has an alpha chann...
Python
nomic_cornstack_python_v1
function get_exchangeable_nodes self n begin set parent = parent_node set tuple a b = random sample call child_nodes 2 if parent_node is none begin if rooted begin set tuple c d = random sample call child_nodes 2 end else begin set tuple c d = random sample call sister_nodes 2 end end else begin set c = random choice c...
def get_exchangeable_nodes(self, n): parent = n.parent_node a, b = random.sample(n.child_nodes(), 2) if parent.parent_node is None: if self.tree.rooted: c, d = random.sample(n.sister_nodes()[0].child_nodes(), 2) else: c, d = random.sample(n...
Python
nomic_cornstack_python_v1
function access_token self begin return get attribute top string _assist_access_token none end function
def access_token(self): return getattr(_app_ctx_stack.top, "_assist_access_token", None)
Python
nomic_cornstack_python_v1
import torch import numpy as np import matplotlib.pyplot as plt from model import Generator if __name__ == string __main__ begin string Load generator checkpoint, then generate a single image set generator = call Generator load state dict generator load torch string generator.pth set device = if expression call is_avai...
import torch import numpy as np import matplotlib.pyplot as plt from model import Generator if __name__ == '__main__': """ Load generator checkpoint, then generate a single image """ generator = Generator() generator.load_state_dict(torch.load('generator.pth')) device = torch.device('cuda') ...
Python
zaydzuhri_stack_edu_python
from django.test import TestCase from datetime import datetime from errors.models import Error from errors.forms import ErrorForm from projects.models import Project class ErrorFormTestCase extends TestCase begin function test_error_form_should_use_error_model self begin string ErrorForm should use Error model for form...
from django.test import TestCase from datetime import datetime from errors.models import Error from errors.forms import ErrorForm from projects.models import Project class ErrorFormTestCase(TestCase): def test_error_form_should_use_error_model(self): ''' ErrorForm should use Error model for form ...
Python
zaydzuhri_stack_edu_python
function append self val begin if vals and vals at - 1 at 0 == val at 0 begin if vals at - 1 at 2 == val at 1 and vals at - 1 at 4 == val at 3 begin set res = tuple vals at - 1 at 0 vals at - 1 at 1 val at 2 vals at - 1 at 3 val at 4 set vals = vals at slice : - 1 : end else begin raise call ValueError string Element...
def append(self, val): if self.vals and self.vals[-1][0] == val[0]: if self.vals[-1][2] == val[1] and self.vals[-1][4] == val[3]: res = (self.vals[-1][0], self.vals[-1][1], val[2], self.vals[-1][3], val[4]) self.vals = self.vals[:-1] ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Tue Feb 13 13:52:25 2018 @author: Data Scientist 1 import os import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime , date , time , timedelta import pandas as pd import numpy as np import ConfigParser from scipy.interpolate im...
# -*- coding: utf-8 -*- """ Created on Tue Feb 13 13:52:25 2018 @author: Data Scientist 1 """ import os import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime, date, time, timedelta import pandas as pd import numpy as np import ConfigParser from scipy.interpolate import U...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string https://leetcode.com/problems/redundant-connection/description/ In this problem, a tree is an *undirected graph* that is connected and has no cycles. The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), wit...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ https://leetcode.com/problems/redundant-connection/description/ In this problem, a tree is an *undirected graph* that is connected and has no cycles. The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one additi...
Python
zaydzuhri_stack_edu_python
function is_develop self spec begin return name in dev_specs end function
def is_develop(self, spec): return spec.name in self.dev_specs
Python
nomic_cornstack_python_v1
import random import disjointSet import matplotlib.pyplot as plt class BiGraph begin string An undirected binomial random graph function __init__ self begin string Graph constructor set graph = dict end function function Binomial self n p begin string Generate and return an instance of a binomial random graph set L = ...
import random import disjointSet import matplotlib.pyplot as plt class BiGraph: '''An undirected binomial random graph''' def __init__(self): '''Graph constructor''' self.graph={} def Binomial(self, n, p): '''Generate and return an instance of a binomial random graph''' L=[] for i in range(n): for...
Python
zaydzuhri_stack_edu_python
import os function file_merger dir begin set files = list directory dir set full_text = string print length files for file in files begin with open format string {}/{} dir file as f begin set full_text = full_text + join string read lines f end end with open format string {}_merge.txt dir string w as f begin write f ...
import os def file_merger(dir): files = os.listdir(dir) full_text = '' print(len(files)) for file in files: with open('{}/{}'.format(dir,file)) as f: full_text += ''.join(f.readlines()) with open('{}_merge.txt'.format(dir), 'w') as f: f.write(full_text) return f...
Python
zaydzuhri_stack_edu_python
function Get self interface prop begin set my_prop = call __getattribute__ prop return my_prop end function
def Get(self, interface, prop): my_prop = self.__getattribute__(prop) return my_prop
Python
nomic_cornstack_python_v1
class DomainSearch begin function __init__ self begin string This still needs a bit of modifications :param phagesProteins: protein function and sequences, as provided in NCBI. Each phage ID has every protein represented with a dicionary with keys as protein IDs :param phageDomains: for each phage and each of it's prot...
class DomainSearch: def __init__(self): ''' This still needs a bit of modifications :param phagesProteins: protein function and sequences, as provided in NCBI. Each phage ID has every protein represented with a dicionary with keys as protein IDs :param phageDomains: for each phage and each of it's proteins, a...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from mpl_toolkits.mplot3d import Axes3D from sklearn.ensemble import IsolationForest from visualize.helper import plot_hyperplane , plot_subplots if __name__ == string __main__ begin set fig = figure set gs = call GridSpec 3 8 fig from sklearn.dat...
import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec from mpl_toolkits.mplot3d import Axes3D from sklearn.ensemble import IsolationForest from visualize.helper import plot_hyperplane, plot_subplots if __name__ == '__main__': fig = plt.figure() gs = GridSpec(3, 8, fig) from sklearn.dat...
Python
zaydzuhri_stack_edu_python
class Estudiante extends object begin set db = none decorator classmethod comment Crear estudiante function create cls apellido nombre fecha_nac localidad_id nivel_id domicilio genero_id escuela_id tipo_doc_id numero tel barrio_id lugar_nac responsable begin set sql = string INSERT INTO `estudiante`(`apellido`, `nombre...
class Estudiante(object): db = None #Crear estudiante @classmethod def create(cls, apellido, nombre, fecha_nac, localidad_id, nivel_id, domicilio, genero_id, escuela_id, tipo_doc_id, numero, tel, barrio_id, lugar_nac, responsable): sql = """ INSERT INTO `estudiante`(`apellido`, `nombre...
Python
zaydzuhri_stack_edu_python
function empty self begin return not call qsize end function
def empty(self): return not self.qsize()
Python
nomic_cornstack_python_v1
function cb_toggled self cb begin set config at string Setup at check_boxes at call objectName = string call isChecked comment TODO: When initially loading config, clear certain checkbox values in it write config end function
def cb_toggled(self, cb): GLB.config['Setup'][self.check_boxes[cb.objectName()]] = str(cb.isChecked()) GLB.config.write() # TODO: When initially loading config, clear certain checkbox values in it
Python
nomic_cornstack_python_v1
comment How To Read Global Variables From Local function spam begin print eggs end function set eggs = 42 call spam print eggs print string eggs needed: set eggs = input call spam
#How To Read Global Variables From Local def spam(): print(eggs) eggs = 42 spam() print(eggs) print("eggs needed:") eggs = input() spam()
Python
zaydzuhri_stack_edu_python
function solve s begin set split_arr = list set split_str = string for ch in s begin if ch in string aeiou begin append split_arr split_str set split_str = string end else begin set split_str = split_str + ch end end return max map lambda item -> sum generator expression ordinal ch - 96 for ch in item split_arr end ...
def solve(s): split_arr = [] split_str = '' for ch in s: if ch in 'aeiou': split_arr.append(split_str) split_str = '' else: split_str += ch return max(map(lambda item: sum(ord(ch) - 96 for ch in item), split_arr))
Python
zaydzuhri_stack_edu_python
function look vertices viewpoints direction=none up=none begin assert ndim == 3 if direction is none begin set direction = call as_tensor list 0 0 1 dtype=float32 end if up is none begin set up = call as_tensor list 0 1 0 dtype=float32 end if is instance viewpoints list or is instance viewpoints tuple begin set viewpoi...
def look(vertices, viewpoints, direction=None, up=None): assert (vertices.ndim == 3) if direction is None: direction = torch.as_tensor([0, 0, 1], dtype=torch.float32) if up is None: up = torch.as_tensor([0, 1, 0], dtype=torch.float32) if isinstance(viewpoints, list) or isinstance(viewp...
Python
nomic_cornstack_python_v1
comment 讀取檔案 set data = list set count = 0 with open string reviews.txt string r as f begin for line in f begin append data line set count = count + 1 if count % 100000 == 0 begin print length data end end end print string 檔案讀取完了,總共有 length data string 筆資料 comment 文字記數 comment word_count 字典 set wc = dict for d in dat...
# 讀取檔案 data = [] count = 0 with open('reviews.txt', 'r') as f: for line in f: data.append(line) count += 1 if count % 100000 == 0: print(len(data)) print('檔案讀取完了,總共有', len(data), '筆資料') # 文字記數 wc = {} # word_count 字典 for d in data: words = d.split() for word in words: if word in wc: wc[word] += 1 e...
Python
zaydzuhri_stack_edu_python
function calendar request username=none year=none month=none begin set context = dict set tuple is_owner user = call check_access user username set year = if expression year then integer year else year set month = if expression month then integer month else month set tuple current_workout schedule = call get_current_w...
def calendar(request, username=None, year=None, month=None): context = {} is_owner, user = check_access(request.user, username) year = int(year) if year else datetime.date.today().year month = int(month) if month else datetime.date.today().month (current_workout, schedule) = Schedule.objects.get_cu...
Python
nomic_cornstack_python_v1
import cv2 import sys import logging as log import datetime as dt from time import sleep import PIL from PIL import Image from Predict import PredictClass set cascPath = string haarcascade_frontalface_default.xml set faceCascade = call CascadeClassifier cascPath call basicConfig filename=string webcam.log level=INFO se...
import cv2 import sys import logging as log import datetime as dt from time import sleep import PIL from PIL import Image from Predict import PredictClass cascPath = "haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) log.basicConfig(filename='webcam.log', level=log.INFO) video_capture...
Python
zaydzuhri_stack_edu_python
function show_deaths self db_session begin set deaths = call _get_current_deaths db_session set total_deaths = call _get_total_deaths db_session call _add_to_chat_queue format string Current Boss Deaths: {}, Total Deaths: {} deaths total_deaths end function
def show_deaths(self, db_session): deaths = self._get_current_deaths(db_session) total_deaths = self._get_total_deaths(db_session) self._add_to_chat_queue("Current Boss Deaths: {}, Total Deaths: {}".format(deaths, total_deaths))
Python
nomic_cornstack_python_v1