code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment 0 1 1 2 3 5 ... set rng = integer input string Enter your range for fib ser : if rng == 0 begin print string Invalid input end else if rng == 1 begin print 0 end else begin set tuple n1 n2 = tuple 0 1 for i in range rng begin print n1 set nth = n1 set n1 = n2 set n2 = nth + n2 end end
# 0 1 1 2 3 5 ... rng = int(input("Enter your range for fib ser : ")) if rng == 0: print("Invalid input") elif rng == 1: print(0) else: n1,n2 = 0,1 for i in range(rng): print(n1) nth = n1 n1 = n2 n2= nth +n2
Python
zaydzuhri_stack_edu_python
function _handleChaturaseetiSamaDasaGraphicsItemTextEnabledFlagResetButtonClicked self begin set value = defaultChaturaseetiSamaDasaGraphicsItemTextEnabledFlag if value == true begin call setCheckState Checked end else begin call setCheckState Unchecked end end function
def _handleChaturaseetiSamaDasaGraphicsItemTextEnabledFlagResetButtonClicked(self): value = \ PriceBarChartSettings.\ defaultChaturaseetiSamaDasaGraphicsItemTextEnabledFlag if value == True: self.chaturaseetiSamaDasaGraphicsItemTextEnabledFlagCheckBox.\ ...
Python
nomic_cornstack_python_v1
class QualityMetrics begin decorator staticmethod function MLogLoss actual predicted eps=1e-15 begin set actual = array actual set actual = call ravel set predicted = array predicted set predicted = call ravel set predicted at predicted < eps = eps set predicted at predicted > 1 - eps = 1 - eps return mean - 1 / shape ...
class QualityMetrics: @staticmethod def MLogLoss(actual, predicted, eps=1e-15): actual = np.array(actual) actual = actual.ravel() predicted = np.array(predicted) predicted = predicted.ravel() predicted[predicted < eps] = eps predicted[predicted > 1 - e...
Python
zaydzuhri_stack_edu_python
function enable_user request begin set post = dictionary comment TODO not implemented return call HttpResponse end function
def enable_user(request): post = request.POST.dict() # TODO not implemented return HttpResponse()
Python
nomic_cornstack_python_v1
import logging from amanuensis.backend import lexiq , userq , charq from amanuensis.db import DbContext , Character from helpers import add_argument set COMMAND_NAME = string char set COMMAND_HELP = string Interact with characters. set LOG = call getLogger __name__ decorator call add_argument string --lexicon required=...
import logging from amanuensis.backend import lexiq, userq, charq from amanuensis.db import DbContext, Character from .helpers import add_argument COMMAND_NAME = "char" COMMAND_HELP = "Interact with characters." LOG = logging.getLogger(__name__) @add_argument("--lexicon", required=True) @add_argument("--user", r...
Python
zaydzuhri_stack_edu_python
function lambertw x begin set eps = 1e-08 set w = x while true begin set ew = exp w set w_new = w - w * ew - x / w * ew + ew if absolute w - w_new <= eps begin break end set w = w_new end return w end function
def lambertw(x): eps = 1e-8 w = x while True: ew = math.exp(w) w_new = w - (w * ew - x) / (w * ew + ew) if abs(w - w_new) <= eps: break w = w_new return w
Python
nomic_cornstack_python_v1
function _MakeGceNetworkName self net_type=none cidr=none uri=none begin comment Return user managed network name if defined. if gce_network_name begin return gce_network_name end set net_type = net_type or net_type set cidr = cidr or cidr set uri = uri or run_uri comment Assume the default network naming. set name = s...
def _MakeGceNetworkName(self, net_type=None, cidr=None, uri=None): if FLAGS.gce_network_name: # Return user managed network name if defined. return FLAGS.gce_network_name net_type = net_type or self.net_type cidr = cidr or self.cidr uri = uri or FLAGS.run_uri name = 'pkb-network-%s' % uri ...
Python
nomic_cornstack_python_v1
function func begin set emptyCells = list append emptyCells list 1 1 return list true emptyCells end function set v = call func if v at 0 begin set lst = list v at 1 end
def func(): emptyCells = [] emptyCells.append([1,1]) return [True, emptyCells] v = func() if v[0]: lst = list(v[1])
Python
zaydzuhri_stack_edu_python
string Constant : replaces the message in a packet with a fixed message only works for udp from slick.Element import Element from dpkt import ethernet from dpkt import ip from dpkt import udp import dumbnet class Constant extends Element begin function __init__ self shim ed begin call __init__ self shim ed set message ...
""" Constant : replaces the message in a packet with a fixed message only works for udp """ from slick.Element import Element from dpkt import ethernet from dpkt import ip from dpkt import udp import dumbnet class Constant(Element): def __init__( self, shim, ed ): Element.__init__( self, shim, ed )...
Python
zaydzuhri_stack_edu_python
function delete_log_entry self log_entry_id begin string Deletes a ``LogEntry``. arg: log_entry_id (osid.id.Id): the ``Id`` of the ``log_entry_id`` to remove raise: NotFound - ``log_entry_id`` not found raise: NullArgument - ``log_entry_id`` is ``null`` raise: OperationFailed - unable to complete request raise: Permiss...
def delete_log_entry(self, log_entry_id): """Deletes a ``LogEntry``. arg: log_entry_id (osid.id.Id): the ``Id`` of the ``log_entry_id`` to remove raise: NotFound - ``log_entry_id`` not found raise: NullArgument - ``log_entry_id`` is ``null`` raise: Operatio...
Python
jtatman_500k
class Solution begin function setZeroes self matrix begin string Example: Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] A first attempt at a solution would be to have row and column marker lists. A first pass over the matrix would take note of all rows and columns that a 0 is in...
class Solution: def setZeroes(self, matrix): """ Example: Input: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] Output: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] A first attempt at a solution would be to have row and column marker lists. A first pass over the matrix...
Python
zaydzuhri_stack_edu_python
function SetReplaceValue self _arg begin return call itkIsolatedConnectedImageFilterISS3ISS3_SetReplaceValue self _arg end function
def SetReplaceValue(self, _arg: 'short const') -> "void": return _itkIsolatedConnectedImageFilterPython.itkIsolatedConnectedImageFilterISS3ISS3_SetReplaceValue(self, _arg)
Python
nomic_cornstack_python_v1
function read_csv_data filename credentials=none verbose=true **kwargs begin comment if on GS split bucket name from file location as first directory if call file_is_on_gs filename begin set df = call read_csv_from_bucket filename credentials=credentials verbose=verbose keyword kwargs end else begin if verbose begin pr...
def read_csv_data(filename, credentials=None, verbose=True, **kwargs): # if on GS split bucket name from file location as first directory if file_is_on_gs(filename): df = read_csv_from_bucket(filename, credentials=credentials, verbose=verbose, **kwargs) else: if verbose: prin...
Python
nomic_cornstack_python_v1
from helpers import LoadImage class Location begin function __init__ self Name begin set name = Name return end function function setRedLight self xy begin set redlocation = xy return end function function setGreenLight self xy begin set grnlocation = xy return end function function setCurrentBracket self xy begin set ...
from helpers import LoadImage class Location(): def __init__(self,Name): self.name = Name return def setRedLight(self,xy): self.redlocation = xy return def setGreenLight(self,xy): self.grnlocation = xy return def setCurrentBracket(self,xy): ...
Python
zaydzuhri_stack_edu_python
function transfer_single_archive_to_job wcl files2get jobfiles dest begin if call fwdebug_check 3 string PFWRUNJOB_DEBUG begin call fwdebug_print string BEG end set archive_info = wcl at string %s_archive_info % lower dest set res = none set transinfo = call get_file_archive_info wcl files2get jobfiles archive_info if ...
def transfer_single_archive_to_job(wcl, files2get, jobfiles, dest): if miscutils.fwdebug_check(3, "PFWRUNJOB_DEBUG"): miscutils.fwdebug_print("BEG") archive_info = wcl['%s_archive_info' % dest.lower()] res = None transinfo = get_file_archive_info(wcl, files2get, jobfiles, ...
Python
nomic_cornstack_python_v1
from z3 import * comment Rename this to die.py function GetStep begin set current_s = integer string current_s set probability = call Real string probability set dice_value = integer string dice_value set next_s = integer string next_s set ranges = call And call And 0 <= current_s current_s <= 7 call And 0 <= next_s ne...
from z3 import * #Rename this to die.py def GetStep(): current_s = Int("current_s") probability = Real("probability") dice_value = Int("dice_value") next_s = Int("next_s") ranges = And(And(0 <= current_s, current_s <= 7), And(0 <= next_s, next_s <= 7), And(0 <= dice_value, dice_value <= 6), And(0 ...
Python
zaydzuhri_stack_edu_python
function update_contacts self contact_list begin set updated_contacts = 0 set request_list = list comment stale_contacts contains all old contacts at first, all current comment contacts get then removed so that the remaining can get deleted set stale_contacts = set contacts for contact in contact_list begin set c = get...
def update_contacts(self, contact_list): updated_contacts = 0 request_list = list() # stale_contacts contains all old contacts at first, all current # contacts get then removed so that the remaining can get deleted stale_contacts = set(self.contacts) for contact in cont...
Python
nomic_cornstack_python_v1
function fact n begin if n < 0 begin print string wrong input end else if n == 0 begin return 1 end else if n == 1 begin return 1 end else begin return n * call fact n - 1 end end function print call fact 5
def fact(n): if n<0: print('wrong input') elif n==0: return 1 elif n==1: return 1 else: return n*fact(n-1) print(fact(5))
Python
zaydzuhri_stack_edu_python
function load_cli_plugins cli config_dir=none begin string Load all plugins and attach them to a CLI object. from config import load_master_config set config = call load_master_config config_dir=config_dir set plugins = call discover_plugins dirs for plugin in plugins begin comment pragma: no cover if not has attribute...
def load_cli_plugins(cli, config_dir=None): """Load all plugins and attach them to a CLI object.""" from .config import load_master_config config = load_master_config(config_dir=config_dir) plugins = discover_plugins(config.Plugins.dirs) for plugin in plugins: if not hasattr(plugin, 'attac...
Python
jtatman_500k
function gameOver self begin comment this function is called when the game ends comment add a restart button set restartButton = call MyButton text=string Press to Restart, your score was + string rapperScore end function
def gameOver(self): # this function is called when the game ends #add a restart button restartButton = MyButton(text='Press to Restart, your score was ' + str(self.rapperScore))
Python
nomic_cornstack_python_v1
function create_image node_id name profile description=none **libcloud_kwargs begin set conn = call _get_driver profile=profile set libcloud_kwargs = call clean_kwargs keyword libcloud_kwargs set node = call _get_by_id call list_nodes node_id return call _simple_image call create_image node name description=description...
def create_image(node_id, name, profile, description=None, **libcloud_kwargs): conn = _get_driver(profile=profile) libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs) node = _get_by_id(conn.list_nodes(), node_id) return _simple_image( conn.create_image(node, name, description=descr...
Python
nomic_cornstack_python_v1
function table_move_indi begin if default_values_dict at string settings at string table_is_moving begin call setStyleSheet string background: rgb(255,0,0); border-radius: 25px; border: 1px solid black; border-radius: 5px end else begin call setStyleSheet string background: rgb(105,105,105); border-radius: 25px; border...
def table_move_indi(): if self.variables.default_values_dict["settings"]["table_is_moving"]: self.table_move_ui.table_ind.setStyleSheet( "background: rgb(255,0,0); border-radius: 25px; border: 1px solid black; border-radius: 5px" ) else: ...
Python
nomic_cornstack_python_v1
string Module defining deep learning pipeline for cardiac MRI images. import asyncio import logging class Pipeline begin string Class implementing deep learning pipeline for cardiac MRI images. function __init__ self dataset max_num_batches=10 loop=none begin string Initialize the pipeline with the given dataset. :para...
"""Module defining deep learning pipeline for cardiac MRI images.""" import asyncio import logging class Pipeline: """Class implementing deep learning pipeline for cardiac MRI images.""" def __init__(self, dataset, max_num_batches=10, loop=None): """Initialize the pipeline with the given dataset. :param...
Python
zaydzuhri_stack_edu_python
from tkinter import * from tkinter import messagebox import tkinter set top = call Tk title top string New Application call geometry string 350x200 set frm = call LabelFrame top text=string Login Form padx=10 pady=10 set name = call Label frm text=string UserName call place x=18 y=20 set entername = call Entry frm call...
from tkinter import * from tkinter import messagebox import tkinter top=Tk() top.title("New Application") top.geometry("350x200") frm=LabelFrame(top,text="Login Form",padx=10,pady=10) name=Label(frm,text="UserName") name.place(x=18,y=20) entername=Entry(frm) entername.place(x=90,y=20) name=Label(frm,text="Password") na...
Python
zaydzuhri_stack_edu_python
comment This is the file where you must work. Write code in the functions, create new functions, comment so they work according to the specification comment Displays the inventory. function display_inventory inventory begin print string Inventory: for i in keys inventory begin print format string {} : {} i inventory at...
# This is the file where you must work. Write code in the functions, create new functions, # so they work according to the specification # Displays the inventory. def display_inventory(inventory): print("\nInventory:") for i in inventory.keys(): print("{} : {}".format(i, inventory[i])) print("\nTot...
Python
zaydzuhri_stack_edu_python
async function test_async_test_connection_valid mock_device hass begin set mock_instance = call AsyncMock set has_returned_state = true set return_value = mock_instance set device = await call async_test_connection dict CONF_DEVICE_ID string deviceid ; CONF_LOCAL_KEY string localkey ; CONF_HOST string hostname hass ass...
async def test_async_test_connection_valid(mock_device, hass): mock_instance = AsyncMock() mock_instance.has_returned_state = True mock_device.return_value = mock_instance device = await config_flow.async_test_connection( { CONF_DEVICE_ID: "deviceid", CONF_LOCAL_KE...
Python
nomic_cornstack_python_v1
from collections import deque import numpy as np import cv2 import pyautogui as pt set FAILSAFE = false set handCascade = call CascadeClassifier string hand.xml comment initialize the list of tracked points, the frame counter, comment and the coordinate deltas comment 32 set DEQUE_MAX_LEN = 32 set pts = deque maxlen=DE...
from collections import deque import numpy as np import cv2 import pyautogui as pt pt.FAILSAFE = False handCascade = cv2.CascadeClassifier("hand.xml") # initialize the list of tracked points, the frame counter, # and the coordinate deltas DEQUE_MAX_LEN =32 #32 pts = deque(maxlen=DEQUE_MAX_LEN) counter = 0 (dX, dY) = ...
Python
zaydzuhri_stack_edu_python
import time import serial import struct set STX1 = 85 set STX2 = 170 set DEVID = 1 set CMD_OPEN = 1 set CMD_CLOSE = 2 set CMD_CHANGEBAUDRATE = 4 set CMD_LED = 18 set CMD_GET_ENROLL_COUNT = 32 set CMD_ENROLL_START = 34 set CMD_ENROLL_1 = 35 set CMD_ENROLL_2 = 36 set CMD_ENROLL_3 = 37 set CMD_IS_FINGER_PRESSED = 38 set C...
import time import serial import struct STX1 = 0x55 STX2 = 0xAA DEVID = 0x01 CMD_OPEN = 0x01 CMD_CLOSE = 0x02 CMD_CHANGEBAUDRATE = 0x04 CMD_LED = 0x12 CMD_GET_ENROLL_COUNT = 0x20 CMD_ENROLL_START = 0x22 CMD_ENROLL_1 = 0x23 CMD_ENROLL_2 = 0x24 CMD_ENROLL_3 = 0x25 CMD_IS_FINGER_PRESSED = 0x26 CMD_DELETE_ALL = 0x41 CMD_...
Python
zaydzuhri_stack_edu_python
function areacon Listmapspatch prefix escala_frag_con dirout prepareBIODIM calcStatistics removeTrash begin if prepareBIODIM begin set tuple esc met = call escala_con Listmapspatch at 0 escala_frag_con comment maps clean set lista_maps_pid_clean = call empty tuple length Listmapspatch length esc dtype=call dtype string...
def areacon(Listmapspatch, prefix,escala_frag_con,dirout,prepareBIODIM,calcStatistics,removeTrash): if prepareBIODIM: esc, met = escala_con(Listmapspatch[0], escala_frag_con) # maps clean lista_maps_pid_clean = np.empty((len(Listmapspatch), len(esc)), dtype=np.dtype('a200')) lista_maps_area_clean = n...
Python
nomic_cornstack_python_v1
function welcome begin return string Available Routes:<br/>/api/precipitation<br/>/api/stations<br/>/api/temperature<br/>/api/start<br/>/api/start/end<br/> end function
def welcome(): return ( f"Available Routes:<br/>" f"/api/precipitation<br/>" f"/api/stations<br/>" f"/api/temperature<br/>" f"/api/start<br/>" f"/api/start/end<br/>" )
Python
nomic_cornstack_python_v1
function backup_file file_path begin set src = string file_path set dst = string { file_path } .backup. { call isoformat } print string Backing Up: { src } -> { dst } copy src dst end function
def backup_file(file_path: Path): src = str(file_path) dst = f"{file_path}.backup.{datetime.now().isoformat()}" print(f"Backing Up: {src} -> {dst}") copy(src, dst)
Python
nomic_cornstack_python_v1
async function on_message self message begin set gh_match = search content set gl_match = search content if gh_match or gl_match and not bot begin for gh in call finditer content begin set d = call groupdict set headers = dict if string GITHUB_TOKEN in environ begin set headers at string Authorization = string token {...
async def on_message(self, message): gh_match = GITHUB_RE.search(message.content) gl_match = GITLAB_RE.search(message.content) if (gh_match or gl_match) and not message.author.bot: for gh in GITHUB_RE.finditer(message.content): d = gh.groupdict() hea...
Python
nomic_cornstack_python_v1
function __init__ self *args **kwargs begin comment Set any passed arg to true. for arg in args begin if not is instance arg str begin raise call TypeError string Only strings are allowed as arguments. end else begin set self at arg = true end end comment Set any keyword arg with keyword as key and value as value. upda...
def __init__(self, *args, **kwargs): # Set any passed arg to true. for arg in args: if not isinstance(arg, str): raise TypeError('Only strings are allowed as arguments.') else: self[arg] = True # Set any keyword arg with keyword as key and...
Python
nomic_cornstack_python_v1
function runSlicer self begin comment DEBUG: call printSlicerVars set num_iters = get num_slices_entry if not num_iters begin set num_iters = num_imgs end else begin set num_iters = integer num_iters end set slicer = call Slicer in_dir=get curr_dir_lbl out_dir=get out_dir_lbl img_ext=img_ext mode=get mode reverse=get r...
def runSlicer(self): # DEBUG: self.printSlicerVars() num_iters = self.num_slices_entry.get() if not num_iters: num_iters = self.num_imgs else: num_iters = int(num_iters) slicer = Slicer( in_dir = self.curr_dir_lbl.get(), ...
Python
nomic_cornstack_python_v1
function __init__ self subreddit begin set subreddit = subreddit end function
def __init__(self, subreddit): self.subreddit = subreddit
Python
nomic_cornstack_python_v1
function minkowski dict1 dict2 r begin set dist = 0 for tuple k v1 in items dict1 begin set v2 = get dict2 k if v2 is not none begin set dist = dist + absolute v1 - v2 ^ r end end return dist ^ 1.0 / r end function function manhatten_distance dict1 dict2 begin return call minkowski dict1 dict2 1 end function function e...
def minkowski(dict1, dict2, r): dist = 0 for k, v1 in dict1.items(): v2 = dict2.get(k) if v2 is not None: dist += abs(v1 - v2) ** r return dist ** (1./r) def manhatten_distance(dict1, dict2): return minkowski(dict1, dict2, 1) def euclidean_distance(dict1, dict2): return minkowski(dict1, dict...
Python
zaydzuhri_stack_edu_python
function params path_to_config begin set template = call load_asset string phy/params.py set config = call load_yaml path_to_config set timestamp = string format time now string %B %-d, %Y at %H:%M set dat_path = join path config at string data at string root_folder config at string data at string recordings set n_chan...
def params(path_to_config): template = load_asset('phy/params.py') config = load_yaml(path_to_config) timestamp = datetime.now().strftime('%B %-d, %Y at %H:%M') dat_path = path.join(config['data']['root_folder'], config['data']['recordings']) n_channels_dat = config['record...
Python
nomic_cornstack_python_v1
function get_run fname full=false begin set basename = base name path fname set run = string if string GA_ in basename begin if string _S_ in basename begin comment example: GA_za05to35_8_1743990to1745989_S_wr_2.root if string _S_ in basename begin set run = split basename string _ at 3 end else begin comment GA_M1_za...
def get_run(fname, full=False): basename = path.basename(fname) run = "" if "GA_" in basename: if "_S_" in basename: # example: GA_za05to35_8_1743990to1745989_S_wr_2.root if "_S_" in basename: run = basename.split("_")[3] # GA_M1_za35to50_8_1740993...
Python
nomic_cornstack_python_v1
import datetime as dt from pytz import timezone from learning_record.settings import TIME_ZONE from django.db import models class Item extends Model begin string learning item set id = call AutoField primary_key=true set name = call CharField max_length=50 verbose_name=string Name set description = call CharField max_l...
import datetime as dt from pytz import timezone from learning_record.settings import TIME_ZONE from django.db import models class Item(models.Model): """ learning item """ id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, verbose_name='Name') description = models.CharField...
Python
zaydzuhri_stack_edu_python
function test_follow_request_accept self broadcast_mock *_ begin set manually_approves_followers = true save broadcast=false update_fields=list string manually_approves_followers set request = call create user_subject=remote_user user_object=local_user remote_id=string https://www.hi.com/ call accept set activity = loa...
def test_follow_request_accept(self, broadcast_mock, *_): self.local_user.manually_approves_followers = True self.local_user.save( broadcast=False, update_fields=["manually_approves_followers"] ) request = models.UserFollowRequest.objects.create( user_subject=sel...
Python
nomic_cornstack_python_v1
function user_input begin while true begin try begin set user_input = integer input string Please enter a positive odd integer: if user_input < 0 begin print string Enter a positive odd integer, try again continue end else if user_input % 2 != 1 begin print string Enter an odd integer continue end else if user_input % ...
def user_input(): while True: try: user_input = int(input("\nPlease enter a positive odd integer: ")) if user_input < 0: print("Enter a positive odd integer, try again") continue elif user_input%2 != 1: print("Enter an od...
Python
nomic_cornstack_python_v1
function check_encapsulated obj_type first_obj second_obj db begin if obj_type == string network begin comment the indexing is to get the list of networks out of the tuple[1] and comment list[0] returned by get_nets set first = call get_nets list first_obj db at 0 at 1 set second = call get_nets list second_obj db at 0...
def check_encapsulated(obj_type, first_obj, second_obj, db): if obj_type == 'network': # the indexing is to get the list of networks out of the tuple[1] and # list[0] returned by get_nets first = get_nets([first_obj], db)[0][1] second = get_nets([second_obj], db)[0][1] elif obj_type == 'service': ...
Python
nomic_cornstack_python_v1
function get_metadata_field self field_name begin set logger = get call Logger debug string start get_metadata_field for field: { field_name } if string metadata not in call list_collection_names or call count_documents dict == 0 begin error string Metadata has not been initialized. return none end try begin set metada...
def get_metadata_field(self, field_name): logger = Logger().get() logger.debug(f"start get_metadata_field for field:{field_name}") if "metadata" not in self.__db.list_collection_names() or self.__metadata_collection.count_documents({}) == 0: logger.error("Metadata ha...
Python
nomic_cornstack_python_v1
import openpyxl comment 新建Excel文件 set wb = call Workbook comment 创建工作表,参数为位置和名称 call create_sheet index=2 title=string PS comment 第二个工作表 call create_sheet index=1 title=string SH comment 获取第一个工作表 set sheet = worksheets at 0 comment 给工作表命名 set title = string PATAC comment 删除指定名称工作表 del wb at string SH comment 为指定单元格输入值 ...
import openpyxl wb = openpyxl.Workbook() #新建Excel文件 wb.create_sheet(index=2, title='PS') #创建工作表,参数为位置和名称 wb.create_sheet(index=1, title='SH') #第二个工作表 sheet = wb.worksheets[0] #获取第一个工作表 sheet.title = 'PATAC' #给工作表命名 del wb['SH'...
Python
zaydzuhri_stack_edu_python
import asyncio import inspect import os from pathlib import Path from collections import namedtuple from dataclasses import dataclass from datetime import datetime , timedelta from functools import partial from typing import Optional , Union , Awaitable , Callable import discord from discord.ext import commands from ba...
import asyncio import inspect import os from pathlib import Path from collections import namedtuple from dataclasses import dataclass from datetime import datetime, timedelta from functools import partial from typing import Optional, Union, Awaitable, Callable import discord from discord.ext import commands...
Python
zaydzuhri_stack_edu_python
function jumlah x y begin return x + y end function function kurang x y begin return x - y end function function kali x y begin return x * y end function function bagi x y begin return x / y end function print string Berikut pilihan fungsi : print string 1. Penjumlahan print string 2. pengurangan print string 3. perkal...
def jumlah(x,y): return x + y def kurang(x,y): return x - y def kali(x,y): return x * y def bagi(x,y): return x / y print ("Berikut pilihan fungsi :") print ("1. Penjumlahan") print ("2. pengurangan") print ("3. perkalian") print ("4. pembagian") pilihan = input ("pilih fungsi 1, 2, 3, atau 4 : ") angka1 = i...
Python
zaydzuhri_stack_edu_python
comment Sort Characters By Frequency comment Given a string, sort it in decreasing order based on the frequency of characters. class Solution begin function frequencySort self s begin comment converting the string to list set ls = list s set dic = counter ls comment sorting the counter by value, This method returns a t...
# Sort Characters By Frequency # Given a string, sort it in decreasing order based on the frequency of characters. class Solution: def frequencySort(self, s: str) -> str: ls = list(s) # converting the string to list dic = collections.Counter(ls) t = dic.most_common() # sorting the coun...
Python
zaydzuhri_stack_edu_python
import sys import json import difflib comment Input argument is the filename of the JSON ascii file from the Twitter API set filename = argv at 1 set filtered_file = argv at 2 comment We will store the text of every tweet in this list set tweets_text = list comment Location of every tweet (free text field - not always...
import sys import json import difflib # Input argument is the filename of the JSON ascii file from the Twitter API filename = sys.argv[1] filtered_file = sys.argv[2] tweets_text = [] # We will store the text of every tweet in this list tweets_location = [] # Location of every tweet (free text field - not always accu...
Python
zaydzuhri_stack_edu_python
function get_followers self to_user profile=false from_user_request=none begin set followers = list if profile begin for friendship in call select_related string from_user begin set obj = get objects user=from_user if from_user_request is not none begin comment set following property of profile to true if the current ...
def get_followers(self, to_user, profile=False, from_user_request=None): followers = [] if profile: for friendship in self.filter(to_user=to_user).select_related('from_user'): obj = Profile.objects.get(user=friendship.from_user) if from_user_request is not Non...
Python
nomic_cornstack_python_v1
function test_alt_service_perfdata self aggregator begin set log_file = named temporary file set perfdata_file = named temporary file comment Get the config set tuple config _ = call get_config format string service_perfdata_file={} service_perfdata_file_template={} name NAGIOS_TEST_ALT_SVC_TEMPLATE service_perf=true c...
def test_alt_service_perfdata(self, aggregator): self.log_file = tempfile.NamedTemporaryFile() perfdata_file = tempfile.NamedTemporaryFile() # Get the config config, _ = get_config( "service_perfdata_file={}\n" "service_perfdata_file_template={}".format(perfdata_...
Python
nomic_cornstack_python_v1
string A tuple is an immutable sequence of values of any type. Tuple elements are indexed by sequential integers, starting with zero. Tuples are constructed by the comma operator, with or without enclosing parentheses. An empty tuple must have the enclosing parentheses. A single item tuple must have a trailing comma. c...
''' A tuple is an immutable sequence of values of any type. Tuple elements are indexed by sequential integers, starting with zero. Tuples are constructed by the comma operator, with or without enclosing parentheses. An empty tuple must have the enclosing parentheses. A single item tuple must have a trailing comma. ''' ...
Python
zaydzuhri_stack_edu_python
async function logout self begin set url = url join base_url string j_acegi_logout_elcustrap async_with get session url raise_for_status=true as response begin await call _flush_response response end end function
async def logout(self) -> None: url = urljoin(self.base_url, "j_acegi_logout_elcustrap") async with self.session.get(url, raise_for_status=True) as response: await _flush_response(response)
Python
nomic_cornstack_python_v1
from sklearn.preprocessing import MinMaxScaler , StandardScaler import numpy as np set data = call loadtxt string /Users/catalinadiaz/Documents/ML_fall2021/auto-mpg_removed_missing_values.data usecols=tuple 0 1 2 3 4 5 6 7 set scaler = min max scaler fit scaler data set data = transform scaler data set k = 10 shuffle r...
from sklearn.preprocessing import MinMaxScaler, StandardScaler import numpy as np data = np.loadtxt("/Users/catalinadiaz/Documents/ML_fall2021/auto-mpg_removed_missing_values.data", usecols=(0,1,2,3,4,5,6,7)) scaler = MinMaxScaler() scaler.fit(data) data = scaler.transform(data) k = 10 np.random.shuffle(data) split...
Python
zaydzuhri_stack_edu_python
function search self street number=none predir=none suffix=none postdir=none city=none state=none zipcode=none strict_number=false begin set filters = dict string street upper street set sided_filters = list if predir begin set filters at string predir = upper predir end if suffix begin set filters at string suffix = ...
def search(self, street, number=None, predir=None, suffix=None, postdir=None, city=None, state=None, zipcode=None, strict_number=False): filters = {'street': street.upper()} sided_filters = [] if predir: filters['predir'] = predir.upper() if suffix: filters[...
Python
nomic_cornstack_python_v1
function _bytes_feature value begin if is instance value type call constant 0 begin comment BytesList won't unpack a string from an EagerTensor. set value = call numpy end return call Feature bytes_list=call BytesList value=list value end function
def _bytes_feature(value): if isinstance(value, type(tf.constant(0))): value = value.numpy() # BytesList won't unpack a string from an EagerTensor. return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
Python
nomic_cornstack_python_v1
function GC_Content self begin set GC_content = lambda dna -> count dna string G + count dna string C / length return round call GC_content sequence 4 end function
def GC_Content(self): GC_content = lambda dna: (dna.count('G')+dna.count('C'))\ /self.length return round(GC_content(self.sequence),4)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import gspread from oauth2client.service_account import ServiceAccountCredentials import random import string function main begin set input_password = input string inputyournamepassword: set password_first = list string XyQVBy?2i string +sUD2fdF string 6UX?Dd38 string D+H?fd7w string Tq+6k...
#!/usr/bin/env python3 import gspread from oauth2client.service_account import ServiceAccountCredentials import random import string def main(): input_password = input("inputyournamepassword: " ) password_first = ['XyQVBy?2i','+sUD2fdF','6UX?Dd38','D+H?fd7w','Tq+6ky&K','6Vfs#y!&'] password_sec ...
Python
zaydzuhri_stack_edu_python
function disable_swap begin comment unmount unused tmpfs filesystems before swap comment (tmpfs can be swapped and you can get a deadlock) call run_quiet string /bin/umount string -at string tmpfs info call _ string Deactivating swap space call run_quiet string /sbin/swapoff string -a end function
def disable_swap(): # unmount unused tmpfs filesystems before swap # (tmpfs can be swapped and you can get a deadlock) run_quiet("/bin/umount", "-at", "tmpfs") UI.info(_("Deactivating swap space")) run_quiet("/sbin/swapoff", "-a")
Python
nomic_cornstack_python_v1
import datetime from metadata_load import get_metadata import petl as etl function get_data begin string import points data from .csv, and reformat set data_rows = call fromcsv string data_sources/Load_history_ver2.csv set data_rows_map = dict string zone_id int ; string year int ; string month int ; string day int upd...
import datetime from metadata_load import get_metadata import petl as etl def get_data (): ''' import points data from .csv, and reformat ''' data_rows = etl.fromcsv('data_sources/Load_history_ver2.csv') data_rows_map = { 'zone_id': int, 'year': int, 'month': int, ...
Python
zaydzuhri_stack_edu_python
function generate_appointments days=14 begin set start = today set end = start + time delta days=days set subs = filter call Q end__gte=now ? call Q end__isnull=true for sub in subs begin for milestone in all begin set milestone_date = call date + time delta days=offset comment Create appointment(s) for this subscripti...
def generate_appointments(days=14): start = datetime.date.today() end = start + datetime.timedelta(days=days) subs = TimelineSubscription.objects.filter(Q(end__gte=now()) | Q(end__isnull=True)) for sub in subs: for milestone in sub.timeline.milestones.all(): milestone_date = sub.st...
Python
nomic_cornstack_python_v1
function make_topwall scrn_width begin set loc = list defx defy set size = list scrn_width defhei set new_wall = call Wall loc size return new_wall end function
def make_topwall(scrn_width): loc = [defx, defy] size = [scrn_width, defhei] new_wall = Wall(loc, size) return new_wall
Python
nomic_cornstack_python_v1
function solve_geodesic self g likeness begin set worldline_likeness = dict string timelike - 1 ; string spacelike 1 ; string null 1 set epsilon = worldline_likeness at likeness set g_inv = call invert_metric g=g set Gamma = call calculate_Christoffel g=g g_inv=g_inv simplify=true set t = call Function index_dict at 0 ...
def solve_geodesic(self, g, likeness): worldline_likeness = {'timelike':-1, 'spacelike':1, 'null':1} epsilon = worldline_likeness[likeness] g_inv = self.invert_metric(g=g) Gamma = self.calculate_Christoffel(g=g, g_inv=g_inv, simplify=True) t = sp.Function(g.index_d...
Python
nomic_cornstack_python_v1
function check_requirements confirmed_events unconfirmed_events num_challenges num_bitbytes begin set req_statuses = call fromkeys keys req_list false set req_remaining = copy req_list for tuple req_type minimum in items req_list begin if req_type == BITBYTE_ACTIVITY begin set num_confirmed = num_bitbytes end else begi...
def check_requirements(confirmed_events, unconfirmed_events, num_challenges, num_bitbytes): req_statuses = dict.fromkeys(req_list.keys(), False) req_remaining = req_list.copy() for req_type, minimum in req_list.items(): if req_type == settings.BITBYTE_ACTIVITY: num_confirmed = num_bitby...
Python
nomic_cornstack_python_v1
import json import jsonpickle from DiGraph import DiGraph from GraphAlgo import GraphAlgo function check begin string Graph: |V|=4 , |E|=5 {0: 0: |edges out| 1 |edges in| 1, 1: 1: |edges out| 3 |edges in| 1, 2: 2: |edges out| 1 |edges in| 1, 3: 3: |edges out| 0 |edges in| 2} {0: 1} {0: 1.1, 2: 1.3, 3: 10} (3.4, [0, 1, ...
import json import jsonpickle from DiGraph import DiGraph from GraphAlgo import GraphAlgo def check(): """ Graph: |V|=4 , |E|=5 {0: 0: |edges out| 1 |edges in| 1, 1: 1: |edges out| 3 |edges in| 1, 2: 2: |edges out| 1 |edges in| 1, 3: 3: |edges out| 0 |edges in| 2} {0: 1} {0: 1.1, 2: 1.3, 3: 10} ...
Python
zaydzuhri_stack_edu_python
function timeEditorComposition *args active=true allCompositions=true createTrack=true delete=true duplicateFrom=string rename=none tracksNode=true q=true query=true e=true edit=true **kwargs begin pass end function
def timeEditorComposition(*args, active: bool=True, allCompositions: bool=True, createTrack: bool=True, delete: bool=True, duplicateFrom: AnyStr="", rename: List[AnyStr, AnyStr]=None, tracksNode: bool=True, q=True, query=True, e=True, edit=Tr...
Python
nomic_cornstack_python_v1
function merge_sorted_arrays arr1 arr2 begin set merged_arr = list set i = 0 set j = 0 while i < length arr1 and j < length arr2 begin if arr1 at i < arr2 at j begin append merged_arr arr1 at i set i = i + 1 end else begin append merged_arr arr2 at j set j = j + 1 end end while i < length arr1 begin append merged_arr ...
def merge_sorted_arrays(arr1, arr2): merged_arr = [] i = 0 j = 0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: merged_arr.append(arr1[i]) i += 1 else: merged_arr.append(arr2[j]) j += 1 while i < len(arr1): ...
Python
greatdarklord_python_dataset
comment Sonic Python Lecture 2017.03.04 comment -*- coding: utf-8 -*- string 플러그 인이 너무 많을 때에는 package.json처럼 리스트를 관리할 수 있다. 설치된 패키지 목록을 파일로 얻기 pip freeze > requirements.txt 설치가 필요한 프로젝트 목록을 통한 프로젝트 설치 pip install -r requirements.txt 로컬호스트에서 shell을 대체할 수 있는 notebook pip install 'ipython[notebook]' 로컬 파일을 에디팅 할 수 있다. 한글을...
# Sonic Python Lecture 2017.03.04 # -*- coding: utf-8 -*- ''' 플러그 인이 너무 많을 때에는 package.json처럼 리스트를 관리할 수 있다. 설치된 패키지 목록을 파일로 얻기 pip freeze > requirements.txt 설치가 필요한 프로젝트 목록을 통한 프로젝트 설치 pip install -r requirements.txt 로컬호스트에서 shell을 대체할 수 있는 notebook pip install 'ipython[notebook]' 로...
Python
zaydzuhri_stack_edu_python
import torch import torch.nn as nn import torchvision import torchvision.datasets as dsets import torchvision.transforms as transforms import torchvision.utils as vutils import torch.optim as optim import numpy as np import matplotlib.pyplot as plt from PIL import Image comment hyperparameters comment could also use tw...
import torch import torch.nn as nn import torchvision import torchvision.datasets as dsets import torchvision.transforms as transforms import torchvision.utils as vutils import torch.optim as optim import numpy as np import matplotlib.pyplot as plt from PIL import Image #hyperparameters lr = 2e-4 # could ...
Python
zaydzuhri_stack_edu_python
comment x = 0 comment y = input("How many times do I have to teel you? ") comment for x in range(int(y)): comment print("CLEAN UP YOUR ROOM") comment NUMBERS for num in range 1 21 begin if num == 4 or num == 13 begin print num string is UNLUCKY end else if num % 2 == 0 begin print num string is even end else begin prin...
# x = 0 # y = input("How many times do I have to teel you? ") # for x in range(int(y)): # print("CLEAN UP YOUR ROOM") # NUMBERS for num in range(1, 21): if num == 4 or num == 13: print(num, "is UNLUCKY") elif num % 2 == 0: print(num, "is even") else: print(num, "is odd")
Python
zaydzuhri_stack_edu_python
function build self begin return self end function
def build(self) -> "Storage": return self
Python
nomic_cornstack_python_v1
import csv import cv2 import numpy as np from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Flatten , Dense , Lambda , Cropping2D , Dropout from keras.layers import Conv2D from keras.layers.pooling import MaxPooling2D from ...
import csv import cv2 import numpy as np from sklearn.utils import shuffle from sklearn.model_selection import train_test_split from keras.models import Sequential from keras.layers import Flatten, Dense, Lambda, Cropping2D, Dropout from keras.layers import Conv2D from keras.layers.pooling import MaxPooling2D from ker...
Python
zaydzuhri_stack_edu_python
import os from flask import Flask , jsonify , request set app = call Flask __name__ set person2 = dict string id 2 ; string name string Jane ; string lastname string Doe ; string age 38 ; string gender string female ; string lucky_numbers list 2 4 6 8 set person1 = dict string id 1 ; string name string John ; string la...
import os from flask import Flask, jsonify, request app = Flask(__name__) person2 = { "id": 2, "name": "Jane", "lastname": "Doe", "age": 38, "gender": "female", "lucky_numbers": [ 2, 4, 6, 8] } person1 = { "id": 1, "name": "John", "lastname": "Doe", "age": 35, "gender": "male", "lucky_numbers...
Python
zaydzuhri_stack_edu_python
function StaClrPerl lines begin set if_n = true for i in lines begin if starts with i string perl begin if string latest in i begin set start = index lines i end end end while if_n begin for i in lines at slice start : : begin if i == string begin set if_n = false set end = index lines at slice start : : i end end...
def StaClrPerl(lines): if_n = True for i in lines: if i.startswith("perl"): if "latest" in i: start = lines.index(i) while if_n: for i in lines[start:]: if i == "\n": if_n = False end = lines[start:].index(i) for ...
Python
nomic_cornstack_python_v1
comment ! /usr/bin/python import subprocess import os.path import timeit set numberOftestsOk = 0 set numberOftestsNok = 0 function main begin set start = call default_timer set databaseName = string test_hsphonebook.pb end function comment It should clean a previous database if found
#! /usr/bin/python import subprocess; import os.path import timeit numberOftestsOk = 0 numberOftestsNok = 0 def main(): start = timeit.default_timer() databaseName = 'test_hsphonebook.pb' # It should clean a previous database if found
Python
zaydzuhri_stack_edu_python
function open_file path begin with open path string r as fin begin return read lines fin end end function function make_list_from_string string separator=false integer=false begin set result = list if separator begin set result = split string separator end else begin set result = split string string end if integer beg...
def open_file(path): with open(path, 'r') as fin: return fin.readlines() def make_list_from_string(string, separator=False, integer=False): result = [] if separator: result = string.split(separator) else: result = string.split(' ') if integer: return [int(i) for i i...
Python
zaydzuhri_stack_edu_python
function relation_factory relation_name begin string Get the RelationFactory for the given relation name. Looks for a RelationFactory in the first file matching: ``$CHARM_DIR/hooks/relations/{interface}/{provides,requires,peer}.py`` set tuple role interface = call relation_to_role_and_interface relation_name if not rol...
def relation_factory(relation_name): """Get the RelationFactory for the given relation name. Looks for a RelationFactory in the first file matching: ``$CHARM_DIR/hooks/relations/{interface}/{provides,requires,peer}.py`` """ role, interface = hookenv.relation_to_role_and_interface(relation_name) ...
Python
jtatman_500k
comment 키를 중심으로 내림차순 정렬 comment 몸무게 max값 갱신 할 때 마다 count += 1 set n = integer input set arr = list comprehension list map int split input for _ in range n sort arr reverse=true key=lambda x -> x at 0 set max_height = 0 set count = 0 for tuple height weight in arr begin if weight > max_height begin set count = count + 1...
# 키를 중심으로 내림차순 정렬 # 몸무게 max값 갱신 할 때 마다 count += 1 n = int(input()) arr = [list(map(int,input().split())) for _ in range(n)] arr.sort(reverse=True, key=lambda x:x[0]) max_height = 0 count = 0 for height , weight in arr: if weight>max_height: count +=1 max_height=weight print(count)
Python
zaydzuhri_stack_edu_python
for i in range 0 n * 2 2 begin append points list li at i li at i + 1 end set tuple x0 y0 = points at 0 comment Other points set points = list comprehension tuple x y for tuple x y in points if x != x0 or y != y0 comment None for vertical Line set slopes = list comprehension if expression x != x0 then y - y0 / x - x0 e...
for i in range(0,n*2,2): points.append([li[i],li[i+1]]) x0,y0 = points[0] points = [ (x,y) for x,y in points if x != x0 or y != y0 ] # Other points slopes = [ (y-y0)/(x-x0) if x!=x0 else None for x,y in points ] # None for vertical Line res = all( s == slopes[0] for s in slopes) if(res == True): ...
Python
zaydzuhri_stack_edu_python
import os from typing import * class TextProcessingUnit begin function __init__ self path_in path_out max_docs=none begin string Initialize a text processing unit. Args: path_in: path to corpus, can be file or directory path_out: path to output directory set path_in = path_in set path_out = path_out set _max_docs = max...
import os from typing import * class TextProcessingUnit: def __init__(self, path_in: str, path_out: str, max_docs: Union[int, None] = None ) -> None: """Initialize a text processing unit. Args: path_in: path to corpus...
Python
zaydzuhri_stack_edu_python
async function test_start_async_send_stop_switch_instance event_loop hyperion_fixture begin set tuple rw hc = tuple rw hc set start_in = dict string command string instance ; string subcommand string startInstance ; string instance 1 await call add_flow list tuple string write start_in assert await call async_send_star...
async def test_start_async_send_stop_switch_instance( event_loop: asyncio.AbstractEventLoop, hyperion_fixture: HyperionFixture, ) -> None: (rw, hc) = hyperion_fixture.rw, hyperion_fixture.hc start_in = {"command": "instance", "subcommand": "startInstance", "instance": 1} await rw.add_flow([("write"...
Python
nomic_cornstack_python_v1
function svn_exists url begin try begin call svn_info url return true end except RuntimeError as e begin return false end end function
def svn_exists(url): try: svn_info(url) return True except RuntimeError as e: return False
Python
nomic_cornstack_python_v1
class BadRequestError extends Exception begin function __init__ self message=string Bad request made begin set message = message end function end class class NonExistentError extends Exception begin function __init__ self message=string Data does not exists begin set message = message end function end class class Unaut...
class BadRequestError(Exception): def __init__(self, message ="Bad request made"): self.message = message class NonExistentError(Exception): def __init__(self, message ="Data does not exists"): self.message = message class UnauthorisedError(Exception): def __init__(self, message ="User una...
Python
zaydzuhri_stack_edu_python
function Energy Walkers begin set E = 0.0 comment given in units of k_B set J = 4.0 comment Simplest Ising model assumption: interaction only between nearest neighbors. comment Energy of such assumption: E(s) = -J*sum(si*sj), summing over all nn pairs for walker in Walkers begin set E = E + call site_Energy Walkers wal...
def Energy(Walkers): E = 0.0 J = 4.0 # given in units of k_B # Simplest Ising model assumption: interaction only between nearest neighbors. # Energy of such assumption: E(s) = -J*sum(si*sj), summing over all nn pairs for walker in Walkers: E += site_Energy(Walkers,walker) # Every nn-pai...
Python
nomic_cornstack_python_v1
comment pip install mysql-connector-python import mysql.connector set mydb = call connect host=string 192.168.0.6 user=string root passwd=string root@123 database=string EmployeeDB set mycursor = call cursor comment # create table comment mycursor.execute("CREATE TABLE Employee (name VARCHAR(255), email VARCHAR(255))")...
import mysql.connector # pip install mysql-connector-python mydb = mysql.connector.connect ( host="192.168.0.6", user="root", passwd="root@123", database="EmployeeDB" ) mycursor = mydb.cursor() # # create table # mycursor.execute("CREATE TABLE Employee (name VARCHAR(255), email VARCHAR(255))") # pri...
Python
zaydzuhri_stack_edu_python
function reap_stale_submissions begin print string Reaping stale submissions comment Find and update stale submissions update filter last_updated < now - time delta minutes=60 processed == false state != string regrading dict string processed true ; string state string Reaped after timeout false comment Commit any chan...
def reap_stale_submissions(): print("Reaping stale submissions") # Find and update stale submissions Submission.query.filter( Submission.last_updated < datetime.now() - timedelta(minutes=60), Submission.processed == False, Submission.state != 'regrading', ).update({ 'pr...
Python
nomic_cornstack_python_v1
function save self begin for tuple name param in items components begin set param_path = join path model_path string %s.mat % name if has attribute param string params begin set param_values = dictionary comprehension name : call get_value for p in params end else begin set param_values = dict name call get_value end c...
def save(self): for name, param in self.components.items(): param_path = os.path.join(self.model_path, "%s.mat" % name) if hasattr(param, 'params'): param_values = {p.name: p.get_value() for p in param.params} else: param_values = {name: param....
Python
nomic_cornstack_python_v1
function is_complete self include_reboot begin if state == COMPLETE begin return true end if not include_reboot and state == COMMITTED begin return true end return false end function
def is_complete(self, include_reboot): if self.state == self.states.COMPLETE: return True if not include_reboot and self.state == self.states.COMMITTED: return True return False
Python
nomic_cornstack_python_v1
comment -*- coding: UTF-8 -*- import collections set d = default dictionary lambda -> 1 function init filename=string SogouLabDic.dic begin set f = open filename string r set total = 0 while true begin set line = read line f if not line begin break end set tuple word freq = split line string at slice 0 : 2 : comment ...
# -*- coding: UTF-8 -*- import collections d=collections.defaultdict(lambda:1) def init(filename='SogouLabDic.dic'): f=open(filename,'r') total=0 while True: line=f.readline() if not line: break word, freq = line.split('\t')[0:2] total+=int(freq)+1#smooth try: ...
Python
zaydzuhri_stack_edu_python
comment Guessing Game import random from number_game_logo import logo print logo print string Welcome to the Number Guessing Game! I am thinking of a number between 1 and 50. set difficulty = lower input string Choose a difficulty. Type 'easy' or 'hard': set number = integer random choice range 1 51 if difficulty == st...
#Guessing Game import random from number_game_logo import logo print(logo) print("Welcome to the Number Guessing Game!\n" " I am thinking of a number between 1 and 50.") difficulty = (input("Choose a difficulty. Type 'easy' or 'hard': ").lower()) number = int(random.choice(range(1,51))) if diffi...
Python
zaydzuhri_stack_edu_python
class Instructor begin comment class attribute set degree = string PhD (Magic) function __init__ self name begin set name = name end function function lecture self topic begin print string Today we're learning about + topic end function end class set dumbledore = call Instructor string Doumbledore class Student begin s...
class Instructor: degree = "PhD (Magic)" # class attribute def __init__(self, name): self.name = name def lecture(self, topic): print("Today we're learning about " + topic) dumbledore = Instructor("Doumbledore") class Student: instructor = dumbledore def __init__(sel...
Python
zaydzuhri_stack_edu_python
function icon self icon begin set _icon = icon end function
def icon(self, icon): self._icon = icon
Python
nomic_cornstack_python_v1
function loadHyp pFileName printHyp=false begin comment Load Parameters from disk with open pFileName as data_file begin set hyp = load json data_file end comment Task hyper parameters set task = call Task games at hyp at string task paramOnly=true set hyp at string ann_nInput = nInput set hyp at string ann_nOutput = n...
def loadHyp(pFileName, printHyp=False): # Load Parameters from disk with open(pFileName) as data_file: hyp = json.load(data_file) # Task hyper parameters task = Task(games[hyp['task']],paramOnly=True) hyp['ann_nInput'] = task.nInput hyp['ann_nOutput'] = task.nOutput hyp['ann_initAct'] = task.activations[...
Python
nomic_cornstack_python_v1
function max_in_range self x y low high begin set data = vertical stack tuple x y set y_values = data at 1 at call logical_and low < data at 0 data at 0 < high set x_values = data at 0 at call logical_and low < data at 0 data at 0 < high set index_max_y = argument maximum set max_y = y_values at index_max_y set max_x =...
def max_in_range(self, x, y, low, high): data = np.vstack((x,y)) y_values = data[1][np.logical_and(low < data[0], data[0] < high)] x_values = data[0][np.logical_and(low < data[0], data[0] < high)] index_max_y = y_values.argmax() ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python set answer = string Pig Latin function print_word begin print answer end function call print_word
#!/usr/bin/env python answer = 'Pig Latin' def print_word(): print(answer) print_word()
Python
zaydzuhri_stack_edu_python
class Solution begin function hasPathSum self root sum begin if not root begin return false end if root and not left and not right and val == sum begin return true end return call hasPathSum left sum - val or call hasPathSum right sum - val end function function hasPathSum self root sum begin set stack = list tuple roo...
class Solution: def hasPathSum(self, root, sum): if not root: return False if root and not root.left and not roo.right and root.val == sum: return True return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val) def hasPathSum(self, root, sum): stack = [(root, sum)] whi...
Python
zaydzuhri_stack_edu_python
string __author__ = 'jaxon' __time__ = '2020/12/19 下午2:26' __desc__ = '' import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait function test_login begin set opt = call Ch...
""" __author__ = 'jaxon' __time__ = '2020/12/19 下午2:26' __desc__ = '' """ import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait def test_login(): opt = webdriver.C...
Python
zaydzuhri_stack_edu_python
function standardize_features_to_array df scalers=none begin set df = apply df lambda x -> replace x list nan mean x at ? call isin list nan inf - inf axis=0 set df = apply df lambda x -> replace x list inf max axis=0 set df = apply df lambda x -> replace x list - inf min axis=0 set df = apply df lambda x -> replace x ...
def standardize_features_to_array(df, scalers = None): df = df.apply(lambda x: x.replace([np.nan], x[~x.isin([np.nan, np.inf, -np.inf])].mean()), axis=0) df = df.apply(lambda x: x.replace([np.inf], x[~x.isin([np.nan, np.inf, -np.inf])].max()), axis=0) df = df.apply(lambda x: x.replace([-np.inf], x[~x.isin([...
Python
nomic_cornstack_python_v1
function print_cv_preamble ridges cluster locality folds inputs outputs **solve_kwargs begin comment compute relative sizes of datasets set sizes = call get_sizes inputs set n_training = sum generator expression size for tuple training _ in folds / length folds set n_validation = sum generator expression size for tuple...
def print_cv_preamble(ridges, cluster, locality, folds, inputs, outputs, **solve_kwargs): # compute relative sizes of datasets sizes = ridge.get_sizes(inputs) n_training = sum(training.size for training, _ in folds) / len(folds) n_validation = sum(validation.size for _, validation ...
Python
nomic_cornstack_python_v1
comment pylint: disable=function-redefined, redefined-builtin function pub cli_ctx keyid filename format begin try begin set keyid = integer keyid 16 log string Getting ECC Public Key from KeyID = 0x%08X % keyid call session_open cli_ctx set get_object = get session set status = call func_timeout TIME_OUT get_key tuple...
def pub(cli_ctx, keyid, filename, format): # pylint: disable=function-redefined, redefined-builtin try: keyid = int(keyid, 16) cli_ctx.log("Getting ECC Public Key from KeyID = 0x%08X" % keyid) session_open(cli_ctx) get_object = Get(cli_ctx.session) status = func_timeout.func...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python set dictonary = dict function find alist begin for i in call xrange length alist begin if alist at i not in keys dictonary begin set dictonary at alist at i = 1 end else begin set dictonary at alist at i = dictonary at alist at i + 1 end end set output = list for i in keys dictonary begin...
#!/usr/bin/env python dictonary ={} def find(alist): for i in xrange(len(alist)): if alist[i] not in dictonary.keys(): dictonary[alist[i]] = 1 else: dictonary[alist[i]] +=1 output =[] for i in dictonary.keys(): temp = [i]*dictonary[i] output.extend(temp)
Python
zaydzuhri_stack_edu_python