code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function test_is_extendable self begin class OtherXFrameOptionsMiddleware extends XFrameOptionsMiddleware begin comment This is just an example for testing purposes... function get_xframe_options_value self request response begin if get attribute request string sameorigin false begin return string SAMEORIGIN end if get...
def test_is_extendable(self): class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware): # This is just an example for testing purposes... def get_xframe_options_value(self, request, response): if getattr(request, 'sameorigin', False): return 'SAMEOR...
Python
nomic_cornstack_python_v1
function pricing_save request simulation begin comment Retrieve the formset from the POST data. set formset = call PolicyFormSet POST if call is_valid begin comment Save the formset (updated values and newly created objects). save set has_changed = true save end else begin comment Redirect to a page with the errors. se...
def pricing_save(request, simulation): # Retrieve the formset from the POST data. formset = PolicyFormSet(request.POST) if formset.is_valid(): # Save the formset (updated values and newly created objects). formset.save() simulation.has_changed = True simulation.save() els...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from os import path import rospy import rospkg from std_msgs.msg import Bool import airsim from ast import literal_eval from utils import reset_objects_id , set_objects_id function prepare_start client begin call reset_objects_id client call set_objects_id client comment Async methods retur...
#!/usr/bin/env python from os import path import rospy import rospkg from std_msgs.msg import Bool import airsim from ast import literal_eval from utils import reset_objects_id, set_objects_id def prepare_start(client): reset_objects_id(client) set_objects_id(client) # Async methods returns Future. C...
Python
zaydzuhri_stack_edu_python
comment real signature unknown function __sizeof__ self *args **kwargs begin pass end function
def __sizeof__(self, *args, **kwargs): # real signature unknown pass
Python
nomic_cornstack_python_v1
comment Put Your Back Into It by Omar Aziz (u7205952@anu.edu.au) comment Using Whitney Houston's Greatest Love of All, either replaces the word 'love' with 'butt' comment or reverses the spelling of each line in the lyric. comment Partially inspired by Cloud to Butt extension for Chrome comment opening .txt with read m...
# Put Your Back Into It by Omar Aziz (u7205952@anu.edu.au) # Using Whitney Houston's Greatest Love of All, either replaces the word 'love' with 'butt' # or reverses the spelling of each line in the lyric. # Partially inspired by Cloud to Butt extension for Chrome # opening .txt with read mode because we don't want to...
Python
zaydzuhri_stack_edu_python
function _exec_entrypoint self logs_path begin with open logs_path string w as logs_file begin set child_process = popen _entrypoint shell=true start_new_session=true stdout=logs_file stderr=STDOUT preexec_fn=lambda -> if expression platform != string win32 and get environ string RAY_JOB_STOP_SIGNAL == string SIGINT t...
def _exec_entrypoint(self, logs_path: str) -> subprocess.Popen: with open(logs_path, "w") as logs_file: child_process = subprocess.Popen( self._entrypoint, shell=True, start_new_session=True, stdout=logs_file, stderr=sub...
Python
nomic_cornstack_python_v1
function test_handle_create_lookup_error self begin set test_user = call User string userid set permissions_level = admin set github_username = string githubuser set return_value = test_user set return_value = string team_id set inputstring = string team create b-s --name 'B S' set side_effect = LookupError call assert...
def test_handle_create_lookup_error(self): test_user = User("userid") test_user.permissions_level = Permissions.admin test_user.github_username = "githubuser" self.db.retrieve.return_value = test_user self.gh.org_create_team.return_value = "team_id" inputstring = "team cr...
Python
nomic_cornstack_python_v1
function npod_uuid self begin return __npod_uuid end function
def npod_uuid(self) -> UUIDFilter: return self.__npod_uuid
Python
nomic_cornstack_python_v1
if __name__ == string __main__ begin set b = list comprehension 0 for i in range 3 set b at 0 = 1 set len = 0 set a = list map int split input for i in range 3 begin for k in range 0 i begin set len = max b at slice 0 : k + 1 : if a at i > a at k begin set b at i = len + 1 end end end print max b end comment xxxxxxxxx
if __name__=="__main__": b=[0 for i in range(3)] b[0]=1 len=0 a=list(map(int,input().split())) for i in range(3): for k in range(0,i): len=max(b[0:k+1]) if a[i]>a[k]: b[i]=len+1 print(max(b)) # xxxxxxxxx
Python
zaydzuhri_stack_edu_python
comment question1 comment exception occcured is ZeroDivisionError try begin set a = 3 set a = a / a - 3 end except ZeroDivisionError begin print string error end try else begin print a end finally begin print string handeled end comment question 2 comment IndexError try begin set l = list 1 2 3 set a = l at 3 end excep...
#question1 #exception occcured is ZeroDivisionError try: a=3 a=a/(a-3) except ZeroDivisionError: print("error") else: print(a) finally: print("handeled") #question 2 #IndexError try: l=[1,2,3] a=l[3] except IndexError: print("list index is out of bounds") els...
Python
zaydzuhri_stack_edu_python
import random import string function randomPswd begin set password = list for i in range 6 begin set alpha = random choice ascii_letters set digits = random choice digits comment password.append(alpha) append password digits end set pwd = join string generator expression string x for x in password print pwd end funct...
import random import string def randomPswd(): password = [] for i in range(6): alpha = random.choice(string.ascii_letters) digits = random.choice(string.digits) #password.append(alpha) password.append(digits) pwd=''.join(str(x) for x in password) print(pwd) ...
Python
zaydzuhri_stack_edu_python
function get_signup_csrf_token begin set response = get session string https://www.udemy.com/join/signup-popup set match = search string name='csrfmiddlewaretoken' value='(.*)' text return call group 1 end function
def get_signup_csrf_token(): response = session.get('https://www.udemy.com/join/signup-popup') match = re.search("name=\'csrfmiddlewaretoken\' value=\'(.*)\'", response.text) return match.group(1)
Python
nomic_cornstack_python_v1
async function _async_update_data self begin try begin return await call async_get_my_user_profile end except any begin raise UpdateFailed end end function
async def _async_update_data(self) -> Dict[str, Any]: try: return await self._api.async_get_my_user_profile() except: raise UpdateFailed
Python
nomic_cornstack_python_v1
comment Import required packages and modules import tkinter as tk from tkinter.filedialog import asksaveasfilename , askopenfilename from tkinter.simpledialog import askinteger , askstring from algorithms.vigenere import vigenere_decrypt , vigenere_encrypt , vigenere_key_gen from algorithms.des import des_encrypt , des...
# Import required packages and modules import tkinter as tk from tkinter.filedialog import asksaveasfilename, askopenfilename from tkinter.simpledialog import askinteger, askstring from algorithms.vigenere import vigenere_decrypt, vigenere_encrypt, vigenere_key_gen from algorithms.des import des_encrypt, des_decrypt, ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import matplotlib.pyplot as plt import numpy as np set rdf = read json string risk_data.json set filteredrdf = rdf at rdf at string maxDeployRad == 300 comment more options can be specified also with call option_context string display.max_rows none string display.max_columns none begin print filtere...
import pandas as pd import matplotlib.pyplot as plt import numpy as np rdf = pd.read_json('risk_data.json') filteredrdf = rdf[(rdf['maxDeployRad']==300)] with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also print(filteredrdf) # table of results fo...
Python
zaydzuhri_stack_edu_python
comment TASK:To print the data before and after updation and deletion comment Program By:Ayush Pandey comment Email Id:1805290@kiit.ac.in comment DATE:24-Sept-2021 comment Python Version:3.7 comment CAVEATS:None comment LICENSE:None from flask import Flask from flask import render_template from flask import jsonify fro...
# TASK:To print the data before and after updation and deletion # Program By:Ayush Pandey # Email Id:1805290@kiit.ac.in # DATE:24-Sept-2021 # Python Version:3.7 # CAVEATS:None # LICENSE:None from flask import Flask from flask import render_template from flask import jsonify from flask_sqlalchemy import SQ...
Python
zaydzuhri_stack_edu_python
set n = integer input string Digite um número inteiro: set suc = n + 1 set ant = n - 1 print format string O sucessor desse número, no conjunto dos inteiros, é {}, suc print format string e seu antecessor é {}. ant
n=int(input('Digite um número inteiro: ')) suc=n+1 ant=n-1 print('O sucessor desse número, no conjunto dos inteiros, é {},'.format(suc)) print('e seu antecessor é {}.'.format(ant))
Python
zaydzuhri_stack_edu_python
function process_data cur filepath func begin comment get all files matching extension from directory set all_files = list for tuple root dirs files in walk filepath begin set files = glob glob join path root string *.json for f in files begin append all_files absolute path path f end end comment get total number of f...
def process_data(cur, filepath, func): # get all files matching extension from directory all_files = [] for root, dirs, files in os.walk(filepath): files = glob.glob(os.path.join(root, '*.json')) for f in files: all_files.append(os.path.abspath(f)) # get total number of file...
Python
nomic_cornstack_python_v1
comment Remove Duplicates from Sorted List comment Question: Given a sorted linked list, delete all duplicates such that each element appear only once. comment For example: comment Given 1->1->2, return 1->2. comment Given 1->1->2->3->3, return 1->2->3. comment Solutions: class ListNode begin function __init__ self x b...
# Remove Duplicates from Sorted List # Question: Given a sorted linked list, delete all duplicates such that each element appear only once. # For example: # Given 1->1->2, return 1->2. # Given 1->1->2->3->3, return 1->2->3. # Solutions: class ListNode: def __init__(self, x): self.val = x self.next...
Python
zaydzuhri_stack_edu_python
while c < 6 begin set a = integer input string Primeiro número: set b = integer input string Segundo número: set rc = a + b set res = integer input string Quanto é { a } + { b } ? if res == rc begin print string Acertou! { a } + { b } = { rc } set ac = ac + 1 end else begin print string Errou, mas não desista! { a } + ...
while c < 6: a = int(input('Primeiro número: ')) b = int(input('Segundo número: ')) rc = a + b res = int(input(f'Quanto é {a} + {b}? ')) if res == rc: print(f'Acertou! {a} + {b} = {rc}') ac += 1 else: print(f'Errou, mas não desista! {a} + {b} = {rc}') ...
Python
zaydzuhri_stack_edu_python
function __init__ self accepting_change_of_payor_patients=none accepting_medicaid_patients=none accepting_medicare_patients=none accepting_private_patients=none accepting_referral_patients=none city=none email=none gender=none first_name=none hios_ids=none id=none last_name=none latitude=none longitude=none middle_name...
def __init__(self, accepting_change_of_payor_patients=None, accepting_medicaid_patients=None, accepting_medicare_patients=None, accepting_private_patients=None, accepting_referral_patients=None, city=None, email=None, gender=None, first_name=None, hios_ids=None, id=None, last_name=None, latitude=None, longitude=None, m...
Python
nomic_cornstack_python_v1
class Solution begin function isSelfDividingNumber self number begin set digits = set set temp = number while temp > 0 begin add digits temp % 10 set temp = temp // 10 end if 0 in digits begin return false end for digit in digits begin if number % digit begin return false end end return true end function function selfD...
class Solution: def isSelfDividingNumber(self, number): digits = set() temp = number while temp > 0: digits.add(temp % 10) temp //= 10 if 0 in digits: return False for digit in digits: if number % digi...
Python
zaydzuhri_stack_edu_python
function play_random_video self begin function random_video_logic begin string Gets a random video without any flags comment Store all videos set _all_videos = all_videos comment Get a random video set _random_video = random choice _all_videos comment Loop while video has flag while flag begin if length _all_videos > 1...
def play_random_video(self): def random_video_logic(): """Gets a random video without any flags""" _all_videos = self.all_videos # Store all videos _random_video = random.choice(_all_videos) # Get a random video ...
Python
nomic_cornstack_python_v1
import sys set read = read set readlines = readlines from collections import deque function main begin set tuple n *a = map int split read set a = deque a set r = 1 set flag = false set muki = 0 set n1 = call popleft while a begin set n2 = call popleft if flag begin if n1 < n2 and muki begin set n1 = n2 end else if n1 ...
import sys read = sys.stdin.read readlines = sys.stdin.readlines from collections import deque def main(): n, *a = map(int, read().split()) a = deque(a) r = 1 flag = False muki = 0 n1 = a.popleft() while a: n2 = a.popleft() if flag: if n1 < n2 and muki: ...
Python
zaydzuhri_stack_edu_python
function __init__ self name classification=string parent_id=none founding_date=string dissolution_date=string image=string chamber=none begin call __init__ set name = name set classification = classification set founding_date = founding_date set dissolution_date = dissolution_date set parent_id = call pseudo_organi...
def __init__( self, name, *, classification="", parent_id=None, founding_date="", dissolution_date="", image="", chamber=None ): super(Organization, self).__init__() self.name = name self.classification = classification ...
Python
nomic_cornstack_python_v1
import time import terminalio from adafruit_magtag.magtag import MagTag set months = list string January string February string March string April string May string June string July string August string September string October string November string December set USE_24HR_TIME = false comment Set up data location and f...
import time import terminalio from adafruit_magtag.magtag import MagTag months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] USE_24HR_TIME = False # Set up data location and fields DATA_SOURCE = "http://192.168.0.25:18...
Python
zaydzuhri_stack_edu_python
import timeClasses class Associate begin function __init__ self name station startTime endTime begin set name = name set station = station set startTime = time startTime set endTime = time endTime end function function getName self begin return name end function function getStation self begin return station end functio...
import timeClasses class Associate(): def __init__(self, name, station, startTime, endTime): self.name = name self.station = station self.startTime = timeClasses.Time( startTime ) self.endTime = timeClasses.Time( endTime ) def getName( self ): return self.name def ...
Python
zaydzuhri_stack_edu_python
import cv2 from datetime import datetime , timedelta from pytz import timezone import keyboard comment from pynput.keyboard import Key, Listener import keyboard while true begin set x = read keyboard 1000 timeout=0 if length x begin print x end end comment def on_press(key): comment try: comment print('alphanumeric key...
import cv2 from datetime import datetime, timedelta from pytz import timezone import keyboard # from pynput.keyboard import Key, Listener import keyboard while True: x = keyboard.read(1000,timeout=0) if len(x): print(x) # def on_press(key): # try: # print('alphanumeric key {0} pressed'.form...
Python
zaydzuhri_stack_edu_python
function name self begin return get pulumi self string name end function
def name(self) -> pulumi.Input[str]: return pulumi.get(self, "name")
Python
nomic_cornstack_python_v1
for k in range K begin set B = list 0 * N + 1 for tuple i a in enumerate A begin set l = max 0 i - a set r = min i + a + 1 N set B at l = B at l + 1 set B at r = B at r - 1 end for i in range 1 N + 1 begin set B at i = B at i + B at i - 1 end pop B if A == B begin break end set A = B end for a in A begin print a end=st...
for k in range(K): B = [0] * (N+1) for i, a in enumerate(A): l = max(0, i-a) r = min(i+a+1, N) B[l] += 1 B[r] -= 1 for i in range(1, N+1): B[i] += B[i-1] B.pop() if (A==B): break A = B for a in A: print(a, end=' ') print()
Python
zaydzuhri_stack_edu_python
function join self begin join _thread end function
def join(self): self._thread.join()
Python
nomic_cornstack_python_v1
function E_0_t x_r x_r_prime w_n_1 candidate d_prev begin set temp = 1.0 / SIGMA_V ^ 2.0 * w_n_1 at x_r_prime * norm candidate - d_prev at x_r_prime ^ 2.0 return temp end function
def E_0_t(x_r, x_r_prime, w_n_1, candidate, d_prev): temp = (1. / SIGMA_V ** 2.) * \ w_n_1[x_r_prime] * \ linalg.norm(candidate - d_prev[x_r_prime]) ** 2. return temp
Python
nomic_cornstack_python_v1
function _update_status self new_status begin set old_status = _status set _status = new_status for listener in _listeners begin comment Calling user-defined callback. call submit call on_status_change self value value end end function
def _update_status(self, new_status): old_status = self._status self._status = new_status for listener in self._listeners: # Calling user-defined callback. self._thread_pool.submit( listener.on_status_change( self, new_status.val...
Python
nomic_cornstack_python_v1
function endpoint self begin return string deployments/ { id } /statuses end function
def endpoint(self): return f"deployments/{self.parent.id}/statuses"
Python
nomic_cornstack_python_v1
comment invoer set aantal_mol = decimal input string Aantal deeltjes in zwavel? comment berekening set aantal_deeltjes = aantal_mol * avogadro set massa = molaire_massa_zwavel * aantal_mol comment uitvoer print massa print aantal_deeltjes
#invoer aantal_mol = float(input('Aantal deeltjes in zwavel? ')) #berekening aantal_deeltjes = aantal_mol*avogadro massa = molaire_massa_zwavel*aantal_mol #uitvoer print(massa) print(aantal_deeltjes)
Python
zaydzuhri_stack_edu_python
function test_temporal_smoothing_how perfectModelEnsemble_initialized_control_1d_ym_cftime begin set pm = perfectModelEnsemble_initialized_control_1d_ym_cftime set pm_smoothed_mean = call smooth dict string lead 4 how=string mean set pm_smoothed_sum = call smooth dict string lead 4 how=string sum assert mean call get_i...
def test_temporal_smoothing_how(perfectModelEnsemble_initialized_control_1d_ym_cftime): pm = perfectModelEnsemble_initialized_control_1d_ym_cftime pm_smoothed_mean = pm.smooth({"lead": 4}, how="mean") pm_smoothed_sum = pm.smooth({"lead": 4}, how="sum") assert ( pm_smoothed_sum.get_initializ...
Python
nomic_cornstack_python_v1
function test_ambiguous_pattern_install self begin call pkgsend_bulk rurl foo10 call image_create rurl call pkg string install foo call pkgsend_bulk rurl anotherfoo11 call pkg string refresh call pkg string update -v exit=4 end function
def test_ambiguous_pattern_install(self): self.pkgsend_bulk(self.rurl, self.foo10) self.image_create(self.rurl) self.pkg("install foo") self.pkgsend_bulk(self.rurl, self.anotherfoo11) self.pkg("refresh") self.pkg("update ...
Python
nomic_cornstack_python_v1
comment <<-------------------- Excersice 3 --------------------->> string poem.txt Contains famous poem "Road not taken" by poet Robert Frost. You have to read this file in python and print every word and its count as show below. Think about the best data structure that you can use to solve this problem and figure out ...
# <<-------------------- Excersice 3 --------------------->> """ poem.txt Contains famous poem "Road not taken" by poet Robert Frost. You have to read this file in python and print every word and its count as show below. Think about the best data structure that you can use to solve this problem and figure out why you ...
Python
zaydzuhri_stack_edu_python
function test_block_nonlabel_do_construct begin comment pylint: disable=invalid-name set tcls = Block_Nonlabel_Do_Construct set obj = call tcls call get_reader string do i=1,10 a = 1 end do assert is instance obj tcls msg call repr obj assert string obj == string DO i = 1, 10 a = 1 END DO set obj = call tcls call get_r...
def test_block_nonlabel_do_construct(): # pylint: disable=invalid-name tcls = Block_Nonlabel_Do_Construct obj = tcls( get_reader( """\ do i=1,10 a = 1 end do """ ) ) assert isinstance(obj, tcls), repr(obj) assert str(obj) == "DO i = 1, 10\n a...
Python
nomic_cornstack_python_v1
function paint_ball ball surface begin if call is_visible begin call circle surface call get_bg_color call get_center integer call get_diameter / 2 set ball_center = call get_center set tuple txt_width txt_height = size call get_txt_font get text call get_operation set txt_position = tuple integer ball_center at 0 - tx...
def paint_ball(ball, surface): if ball.is_visible(): pygame.draw.circle(surface, ball.get_bg_color(), ball.get_center(), int(ball.get_diameter() / 2)) ball_center = ball.get_center() txt_width, txt_height = ball.get_txt_font().size(ball.get_operation(). ...
Python
nomic_cornstack_python_v1
if hs > 40 begin set pay = 40 * rt + hs - 40 * 1.5 * rt end else begin set pay = hs * rt end print pay
if hs>40: pay=40*rt+(hs-40)*1.5*rt else: pay=hs*rt print(pay)
Python
zaydzuhri_stack_edu_python
import piexif from PIL import Image import os comment Read image comment Bild importieren set a = input string Geben Sie Bildname: set img = open a comment print out all image's information set exif_dict = load piexif info at string exif print exif_dict set altitude = exif_dict at string GPS at GPSAltitude print altitu...
import piexif from PIL import Image import os # Read image # Bild importieren a = input('Geben Sie Bildname: ') img = Image.open(a) exif_dict = piexif.load(img.info['exif']) # print out all image's information print(exif_dict) altitude = exif_dict['GPS'][piexif.GPSIFD.GPSAltitude] print(altitude) b...
Python
zaydzuhri_stack_edu_python
import logging import time import os function log begin comment 获取当前时间 set nowDay = string format time time string %Y-%m-%d comment 拼接文件路径 set filePath = string /var/log/python-%s % nowDay comment 判断当前路径是否存在 if not exists path filePath begin comment 不存在则创建 make directories filePath end comment 切换操作目录 change directory f...
import logging import time import os def log(): # 获取当前时间 nowDay = time.strftime('%Y-%m-%d') # 拼接文件路径 filePath = '/var/log/python-%s' % (nowDay) # 判断当前路径是否存在 if not os.path.exists(filePath): # 不存在则创建 os.makedirs(filePath) # 切换操作目录 os.chdir(filePath) # 日志格式 loggin...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/python comment Final comment Project No. 03 comment File Name: Salary.py comment Programmer: Karina Elias comment Date: Dec. 14, 2019 from Employee import Employee class Salary extends Employee begin function __init__ self firstName lastName employeeID salary begin call __init__ self firstName lastNa...
#! /usr/bin/python # # Final # Project No. 03 # File Name: Salary.py # Programmer: Karina Elias # Date: Dec. 14, 2019 from Employee import Employee class Salary(Employee): def __init__(self, firstName, lastName, employeeID, salary): Employee.__init__(self, firstName, lastName, employeeID) ...
Python
zaydzuhri_stack_edu_python
function update self irc msg args channel isAre url begin set isAre = lower isAre if isAre == string is begin set add = setIs end else if isAre == string are begin set add = setAre end set count = 0 try begin set fd = call getUrlFd url end except Error begin try begin set fd = call file url end except EnvironmentError ...
def update(self, irc, msg, args, channel, isAre, url): isAre = isAre.lower() if isAre == 'is': add = self.db.setIs elif isAre == 'are': add = self.db.setAre count = 0 try: fd = utils.web.getUrlFd(url) except utils.web.Error: ...
Python
nomic_cornstack_python_v1
function naive_forecast x return_sequences=true feature_idx=0 begin set x_shape = call get_shape comment If shape of x is (batch, sequence) if length x_shape == 2 begin if return_sequences begin return x end return x at tuple slice : : - 1 end comment If shape of x is (batch, sequence, features) if length x_shape ==...
def naive_forecast(x: tf.Tensor, return_sequences: bool=True, feature_idx: int=0): x_shape = x.get_shape() # If shape of x is (batch, sequence) if len(x_shape) == 2: if return_sequences: return x return x[:, -1] # If shape of x is (batch, sequence, features) if len(x_sh...
Python
nomic_cornstack_python_v1
function get_target_tags self begin raise call NotImplementedError string end function
def get_target_tags(self): raise NotImplementedError("")
Python
nomic_cornstack_python_v1
function test_output_toxicity begin set output = call text_quality text=x assert toxicity at 0 >= 0.06 and toxicity at 0 <= 0.09 end function
def test_output_toxicity(): output = text_quality(text=x) assert output.toxicity[0]>=0.06 and output.toxicity[0]<=0.09
Python
nomic_cornstack_python_v1
for i in range n begin if l at i % 2 == 0 begin if l at i < 0 begin append e1 l at i end else if l at i > 0 begin append e2 l at i end end else if l at i > 0 begin append o2 l at i end else if l at i < 0 begin append o1 l at i end end comment print(o1,o2,e1,e2) if length o2 == 0 begin print max o1 + sum e2 end else if ...
for i in range(n): if l[i]%2==0: if l[i]<0: e1.append(l[i]) elif l[i]>0: e2.append(l[i]) else: if l[i]>0: o2.append(l[i]) elif l[i]<0: o1.append(l[i]) #print(o1,o2,e1,e2) if len(o2)==0: print(max(o1)+sum(e2)) else: if len(o2...
Python
jtatman_500k
function get_license_data begin set output = check output list string pip-licenses string --format string json return loads output end function
def get_license_data() -> List[Mapping[str, str]]: output = subprocess.check_output(["pip-licenses", "--format", "json"]) return json.loads(output)
Python
nomic_cornstack_python_v1
function date_time name=none begin string Creates the grammar for a date and time field, which is a combination of the Date (D) and Time or Duration field (T). This field requires first a Date, and then a Time, without any space in between. :param name: name for the field :return: grammar for a Date and Time field if n...
def date_time(name=None): """ Creates the grammar for a date and time field, which is a combination of the Date (D) and Time or Duration field (T). This field requires first a Date, and then a Time, without any space in between. :param name: name for the field :return: grammar for a Date a...
Python
jtatman_500k
print string Hello! by filling out a simple form to continue using the site. set anketa = open string anketa.txt string w set name = input string What is your name? set surname = input string What is your surname? set age = integer input string How old are you? set town = input string Where do you live? set name_surnam...
print ("Hello! by filling out a simple form to continue using the site.") anketa = open("anketa.txt", "w") name = input ("What is your name?") surname = input ("What is your surname?") age = int(input ("How old are you?")) town = input ("Where do you live?") name_surname = name + ' ' + surname letter = "Thank you %s...
Python
zaydzuhri_stack_edu_python
import unittest from dataclasses import dataclass from remove_dups.remove_dups import remove_duplicates decorator dataclass class TestObject begin set one : str set two : str end class class RemoveDuplicateTest extends TestCase begin function test_remove_duplicates self begin set no_duplicates = call remove_duplicates ...
import unittest from dataclasses import dataclass from remove_dups.remove_dups import remove_duplicates @dataclass class TestObject: one: str two: str class RemoveDuplicateTest(unittest.TestCase): def test_remove_duplicates(self): no_duplicates = remove_duplicates([1, 2, 2, 2, 3, 4, 5]) ...
Python
zaydzuhri_stack_edu_python
function configure_optimizers self begin return adam parameters self end function
def configure_optimizers(self) -> Optimizer: return Adam(self.parameters())
Python
nomic_cornstack_python_v1
function setup_local_site self begin comment create Tenant, App, EPG on site 1 set site1 = call Session SITE1_URL SITE1_LOGIN SITE1_PASSWORD set resp = call login assert true ok set tenant = call Tenant string intersite-testsuite set app = call AppProfile string app tenant set epg = call EPG string epg app set mac = st...
def setup_local_site(self): # create Tenant, App, EPG on site 1 site1 = Session(SITE1_URL, SITE1_LOGIN, SITE1_PASSWORD) resp = site1.login() self.assertTrue(resp.ok) tenant = Tenant('intersite-testsuite') app = AppProfile('app', tenant) epg = EPG('epg', app) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string Retrieve the maximum timestamp for the data present in the given top level path. Usage: getMaxTimeForPath.py --basepath ${PATH} set __author__ = string Daniel Zhang (張道博) set __copyright__ = string Copyright (c) 2014, University of Hawaii Smart Energy Pr...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Retrieve the maximum timestamp for the data present in the given top level path. Usage: getMaxTimeForPath.py --basepath ${PATH} """ __author__ = 'Daniel Zhang (張道博)' __copyright__ = 'Copyright (c) 2014, University of Hawaii Smart Energy Project' __license__ = '...
Python
zaydzuhri_stack_edu_python
string column aggregates df.column_name.command() built in commands that are included in Pandas mean, std, median, min, max, count, nunique, unique Command Description mean Average of all values in column std Standard deviation median Median max Maximum value in column min Minimum value in column count Number of values...
"""column aggregates df.column_name.command() built in commands that are included in Pandas mean, std, median, min, max, count, nunique, unique Command Description mean Average of all values in column std Standard deviation median Median max Maximum value in column min Minimum value in column count Number of values ...
Python
zaydzuhri_stack_edu_python
function prime_range m n begin set primes = list for num in range m n + 1 begin for i in range 2 num begin if num % i == 0 begin break end end for else begin append primes num end end return primes end function comment [11, 13, 17, 19] call prime_range 10 20
def prime_range(m, n): primes = [] for num in range(m, n+1): for i in range(2, num): if (num % i) == 0: break else: primes.append(num) return primes prime_range(10, 20) # [11, 13, 17, 19]
Python
flytech_python_25k
import matplotlib.pyplot as plt import numpy as np from sklearn import metrics from sklearn.grid_search import GridSearchCV from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.cross_validation import cross_val_predict from sklearn.preprocessing import binarize function benchmark clfs X_...
import matplotlib.pyplot as plt import numpy as np from sklearn import metrics from sklearn.grid_search import GridSearchCV from sklearn.decomposition import PCA from sklearn.manifold import TSNE from sklearn.cross_validation import cross_val_predict from sklearn.preprocessing import binarize def benchmark(clfs, X_tra...
Python
zaydzuhri_stack_edu_python
import os import time import errno class FileLockException extends Exception begin pass end class class FileLock extends object begin function __init__ self file_name timeout=60 delay=0.1 begin set _delay = delay set _fd = none set _lockfile = join path get current directory file_name set _timeout = timeout end functio...
import os import time import errno class FileLockException(Exception): pass class FileLock(object): def __init__(self, file_name, timeout=60, delay=.1): self._delay = delay self._fd = None self._lockfile = os.path.join(os.getcwd(), file_name) self._timeout = timeout def...
Python
zaydzuhri_stack_edu_python
function add_dependents self dependents start=none end=none begin call add_dependents dependents=dependents dp=dependents frame_valid=valid start_frame=start end_frame=end subtract=false end function
def add_dependents(self, dependents, start=None, end=None): frames_numba_functions.add_dependents( dependents=self.dependents, dp=dependents, frame_valid=self.valid, start_frame=start, end_frame=end, subtract=False)
Python
nomic_cornstack_python_v1
class player begin string Класс описывающий игрока NBA function __init__ self height wingspan avg_points avg_takes avg_passes begin string Конструктор класса игрока NBA set height = height set wingspan = wingspan set avg_points = avg_points set avg_takes = avg_takes set avg_passes = avg_passes end function function get...
class player: """ Класс описывающий игрока NBA """ def __init__(self, height, wingspan, avg_points, avg_takes, avg_passes): """Конструктор класса игрока NBA""" self.height = height self.wingspan = wingspan self.avg_points = avg_points self.avg_takes = avg_takes ...
Python
zaydzuhri_stack_edu_python
import time function Primes a begin set sieve = list true * a + 1 set sieve at slice : 2 : = list false false set sqrt = integer a ^ 0.5 + 1 for x in range 2 sqrt begin if sieve at x begin set sieve at slice 2 * x : : x = list false * a / x - 1 end end return sieve end function set p = call Primes 10 ^ 3 set primes ...
import time def Primes(a): sieve=[True]*(a+1) sieve[:2]=[False, False] sqrt=int(a**.5)+1 for x in range(2, sqrt): if sieve[x]: sieve[2*x::x]=[False]*(a/x-1) return sieve p = Primes(10**3) primes = [x for x in range(10**3) if p[x]] connected=set([2]) def isConnected1(a,b): if...
Python
zaydzuhri_stack_edu_python
function test_list_time_white_space_nistxml_sv_iv_list_time_white_space_1_3 mode save_output output_format begin call assert_bindings schema=string nistData/list/time/Schema+Instance/NISTSchema-SV-IV-list-time-whiteSpace-1.xsd instance=string nistData/list/time/Schema+Instance/NISTXML-SV-IV-list-time-whiteSpace-1-3.xml...
def test_list_time_white_space_nistxml_sv_iv_list_time_white_space_1_3(mode, save_output, output_format): assert_bindings( schema="nistData/list/time/Schema+Instance/NISTSchema-SV-IV-list-time-whiteSpace-1.xsd", instance="nistData/list/time/Schema+Instance/NISTXML-SV-IV-list-time-whiteSpace-1-3.xml"...
Python
nomic_cornstack_python_v1
comment 3 function getvartypelist self subj vartype begin set num_ = none if num_ is none begin set num_ = length subj end else if num_ != length subj begin raise call IndexError string Inconsistent length of array subj end if num_ is none begin set num_ = 0 end if subj is none begin raise call TypeError string Invalid...
def getvartypelist(self,subj,vartype): # 3 num_ = None if num_ is None: num_ = len(subj) elif num_ != len(subj): raise IndexError("Inconsistent length of array subj") if num_ is None: num_ = 0 if subj is None: raise TypeError("Invalid type for argument subj") if subj ...
Python
nomic_cornstack_python_v1
function build self begin set topo_sort = list call toposort call _build_dependency_dict for i in range 0 length topo_sort begin set _topo_sort at i = topo_sort at i end comment if a bw op has the same order with a fw op, comment then remove the bw op call _clean_bw_ops comment if there are non-bw ops in the bw phase, ...
def build(self): topo_sort = list(toposort.toposort(self._build_dependency_dict())) for i in range(0, len(topo_sort)): self._topo_sort[i] = topo_sort[i] # if a bw op has the same order with a fw op, # then remove the bw op self._clean_bw_ops() # if there are...
Python
nomic_cornstack_python_v1
function __Forward self image begin set tuple h w _ = shape set img = call cvtColor image COLOR_BGR2RGB set img = call Resize img tuple 112 112 set img = img / 255.0 set img = transpose numpy img list 2 0 1 set img = call expand_dims img axis=0 set img = as type img float32 set output = run none dict __input_name img a...
def __Forward(self, image): h, w, _ = image.shape img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) img = Resize(img, (112, 112)) img = img / 255.0 img = numpy.transpose(img, [2, 0, 1]) img = numpy.expand_dims(img, axis=0) img = img.astype(numpy.float32) outpu...
Python
nomic_cornstack_python_v1
function perspective_run_oob params begin set output = call RunOob params at 0 params at 1 params at 2 params at 3 if output begin set result = call LoadJson output end else begin set result = none end return result end function
def perspective_run_oob(params): output = backend.RunOob(params[0], params[1], params[2], params[3]) if output: result = serializer.LoadJson(output) else: result = None return result
Python
nomic_cornstack_python_v1
class GameManager begin set _instance = none function __init__ self begin set _w = none set _player = none end function function remove_actor self actor begin call remove_actor actor end function function remove_boss self actor begin from game.ui_manager.modes import EndGame as eg from game.ui_manager.ui_manager import...
class GameManager: _instance = None def __init__(self): self._w = None self._player = None def remove_actor(self, actor): self._w.remove_actor(actor) def remove_boss(self, actor): from game.ui_manager.modes import EndGame as eg from game.ui_manager.ui_manager i...
Python
zaydzuhri_stack_edu_python
string test_slaxmlparser verifies the processes that convert XML nodes containing spell-like abilities into formed XML structures. import inspect from xml.dom import minidom from twisted.trial import unittest from playtools.parser import slaxmlparser as sxp from playtools.test.pttestutil import DiffTestCaseMixin class ...
""" test_slaxmlparser verifies the processes that convert XML nodes containing spell-like abilities into formed XML structures. """ import inspect from xml.dom import minidom from twisted.trial import unittest from playtools.parser import slaxmlparser as sxp from playtools.test.pttestutil import DiffTestCaseMixin cl...
Python
zaydzuhri_stack_edu_python
from base64 import b64decode import io import json from math import sqrt import random import time from PIL import Image class Point begin function __init__ self coordinates begin set coordinates = coordinates end function end class class Cluster begin function __init__ self center points begin set center = center set ...
from base64 import b64decode import io import json from math import sqrt import random import time from PIL import Image class Point: def __init__(self, coordinates): self.coordinates = coordinates class Cluster: def __init__(self, center, points): self.center = center self.points...
Python
zaydzuhri_stack_edu_python
function init self *pargs **kwargs begin call init *pargs keyword kwargs set invites_list = call DAList set auto_gather = false set populated = false end function
def init(self, *pargs, **kwargs): super().init(*pargs, **kwargs) self.invites_list = DAList() self.invites_list.auto_gather = False self.populated = False
Python
nomic_cornstack_python_v1
function Patch self request global_params=none begin set config = call GetMethodConfig string Patch return call _RunMethod config request global_params=global_params end function
def Patch(self, request, global_params=None): config = self.GetMethodConfig('Patch') return self._RunMethod( config, request, global_params=global_params)
Python
nomic_cornstack_python_v1
function ppf self x begin set ppfValue = call inverseCdf x random return ppfValue end function
def ppf(self,x): ppfValue = self._distribution.inverseCdf(x,random()) return ppfValue
Python
nomic_cornstack_python_v1
function flatten_array arr begin comment Base case: if the input array is empty or only contains empty arrays, return an empty list if not arr or all generator expression not a for a in arr begin return list end set flattened = list for item in arr begin comment If the item is a list or dictionary, recursively flatte...
def flatten_array(arr): # Base case: if the input array is empty or only contains empty arrays, return an empty list if not arr or all(not a for a in arr): return [] flattened = [] for item in arr: # If the item is a list or dictionary, recursively flatten it and add its elements to the...
Python
jtatman_500k
from SignAnimation import SignAnimation import random from Effects.GoToColorEffect import GoToColorEffect from Effects.AlwaysOnEffect import AlwaysOnEffect from Colors import Colors class HueSignAnimation extends SignAnimation begin string Slowly running on the hue circle hue_speed: [0-1] change in hue for one beat hue...
from SignAnimation import SignAnimation import random from Effects.GoToColorEffect import GoToColorEffect from Effects.AlwaysOnEffect import AlwaysOnEffect from Colors import Colors class HueSignAnimation(SignAnimation): """ Slowly running on the hue circle hue_speed: [0-1] change in hue for one beat h...
Python
zaydzuhri_stack_edu_python
if __name__ == string __main__ begin set tuple n p = map int split input set aws = 1 while true begin set min_number = aws * 2 ^ 0 + p if min_number > n begin set aws = - 1 break end else if min_number == n begin break end else if count binary n - aws * p string 1 <= aws begin break end set aws = aws + 1 end print aws ...
if __name__ == '__main__': n, p = map(int, input().split()) aws = 1 while True: min_number = aws * ((2**0) + p) if min_number > n: aws = -1 break elif min_number == n: break elif bin((n - aws * p)).count('1') <= aws: break ...
Python
jtatman_500k
function get_definitions cls scope plugin=none app_name=none user_modifiable=false begin call _check_scope scope set defs = call _get_defs plugin app_name set ret = dictionary comprehension k : v for tuple k v in items defs if string scope in v and v at string scope == scope and not user_modifiable or string user_modif...
def get_definitions( cls, scope, plugin=None, app_name=None, user_modifiable=False, ): cls._check_scope(scope) defs = cls._get_defs(plugin, app_name) ret = { k: v for k, v in defs.items() if ( 'scope'...
Python
nomic_cornstack_python_v1
function make_relationship self relator direction=BIDIRECTIONAL begin string Create a relationship object for this attribute from the given relator and relationship direction. comment pylint:disable=E1101 if call providedBy relator begin set rel = call DomainRelationship relator self direction=direction end else commen...
def make_relationship(self, relator, direction= RELATIONSHIP_DIRECTIONS.BIDIRECTIONAL): """ Create a relationship object for this attribute from the given relator and relationship direction. """ if IEntity.providedBy(relator):...
Python
jtatman_500k
function input_shape self begin return list none 32 32 1 end function
def input_shape(self): return [None, 32, 32, 1]
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit as cf from numpy import genfromtxt comment Please Check made.py to check how this csv file is made from the RAW available on Pantheon site set pth = string made.csv set mn = call genfromtxt pth delimiter=string ,...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit as cf from numpy import genfromtxt pth = 'made.csv' #Please Check made.py to check how this csv file is made from the RAW available on Pantheon site mn= genfromtxt(pth, delimiter=',') pr...
Python
zaydzuhri_stack_edu_python
function tune_num_estimators metric label params strat_folds train begin set eval_hist = call cv dtrain=call DMatrix train label=label early_stopping_rounds=50 folds=strat_folds metrics=metric num_boost_round=10000 params=params verbose_eval=true set num_trees = shape at 0 set best_score = values at tuple num_trees - 1...
def tune_num_estimators(metric: str, label: np.ndarray, params: dict, strat_folds: StratifiedKFold, train) -> Tuple[int, float]: eval_hist = xgb.cv( dtrain=xgb.DMatrix(train, label=label), early_stopping_...
Python
nomic_cornstack_python_v1
string This is a database-schema from sqlalchemy import Column , Integer , Text , UniqueConstraint from sqlalchemy.orm import relationship from meta import Base class Application extends Base begin string This is definition of class Application. Application is the core of Experiment-Server. Application-class represents...
""" This is a database-schema """ from sqlalchemy import ( Column, Integer, Text, UniqueConstraint ) from sqlalchemy.orm import relationship from .meta import Base class Application(Base): """ This is definition of class Application. Application is the core of Experiment-Server. Applicati...
Python
zaydzuhri_stack_edu_python
function add_test_dates df start=string 2016-09-13 00:00:00 end=string 2016-09-20 23:00:00 begin set h_range = call date_range start end freq=string 1H set test_dates = call DataFrame dict string date h_range set test_dates at string type = string test set df = merge test_dates on=list string date string type how=strin...
def add_test_dates(df, start='2016-09-13 00:00:00', end='2016-09-20 23:00:00'): h_range = pd.date_range(start, end, freq='1H') test_dates = pd.DataFrame({'date': h_range}) test_dates['type'] = 'test' df = df.merge(test_dates, on=['date', 'type'], how='outer', sort=True) return df
Python
nomic_cornstack_python_v1
comment The input() function set your_name = input string Please enter your name: print string Hello + upper your_name + string ! set number = input string Please enter your number: print string Your number: + number print string Type of + string number + string is + string type number print string Give me any two numb...
# The input() function your_name = input("Please enter your name: ") print("Hello " + your_name.upper() + '!') number = input("Please enter your number: ") print("Your number: " + number) print("Type of " + str(number) + " is " + str(type(number))) print("Give me any two number and I'll multiply them together.") num...
Python
zaydzuhri_stack_edu_python
import time import pandas as pd import numpy as np set CITY_DATA = dict string chicago string chicago.csv ; string new york city string new_york_city.csv ; string washington string washington.csv set months = list string january string jebruary string jarch string april string may string june string all set days = list...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } months = ['january', 'jebruary', 'jarch', 'april', 'may', 'june', 'all'] days = ['monday', 'tuesday', 'wednesday', 'thursday', '...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Tue Jul 24 15:52:21 2018 @author: edwin function main begin import trialDivision set total = 0 set ticks = 0 set i = 10 while ticks < 11 begin if call main i begin set forwardString = string i set backwardString = forwardString set successFla...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 24 15:52:21 2018 @author: edwin """ def main(): import trialDivision total = 0 ticks = 0 i = 10 while (ticks < 11): if (trialDivision.main(i)): forwardString = str(i) backwardString = forwardStrin...
Python
zaydzuhri_stack_edu_python
function compute_tails ddf by=none begin set empty = iloc at slice 0 : 0 : if by is none begin return call prefix_reduction most_recent_tail ddf empty end else begin set kwargs = dict string by by return call prefix_reduction most_recent_tail_summary ddf empty keyword kwargs end end function
def compute_tails(ddf, by=None): empty = ddf._meta.iloc[0:0] if by is None: return prefix_reduction(most_recent_tail, ddf, empty) else: kwargs = {"by": by} return prefix_reduction(most_recent_tail_summary, ddf, empty, **kwargs)
Python
nomic_cornstack_python_v1
comment 03_nempyEx01.py import numpy as np set data = array list list 10 20 list 30 40 print data print string - * 30 comment sum : 모든 요소의 합을 구함 set result = sum data print result print string - * 30 comment axis=0 : 행을 따라가면서, 열 단위 합산 set result = sum data axis=0 print result print string - * 30 comment axis=1 : 열을 따라가...
# 03_nempyEx01.py import numpy as np data = np.array([[10,20], [30,40]]) print(data) print('-' * 30) result = np.sum(data) # sum : 모든 요소의 합을 구함 print(result) print('-' * 30) result = np.sum(data, axis=0) # axis=0 : 행을 따라가면서, 열 단위 합산 print(result) print('-' * 30) result = n...
Python
zaydzuhri_stack_edu_python
function play_song self somelist begin if not somelist begin return end call on_key_press somelist at 0 0 sleep 0.19 return call play_song self somelist at slice 1 : : end function
def play_song(self,somelist): if not somelist: return on_key_press(somelist[0],0) time.sleep(.19) return play_song(self,somelist[1:])
Python
nomic_cornstack_python_v1
function configure_input_size cfg input_size_config=DEFAULT model_ckpt=none begin set input_size = call get_configured_input_size input_size_config model_ckpt if input_size is none begin return end comment segmentation models have different input size in train and val data pipeline set base_input_size = dict string tra...
def configure_input_size( cfg, input_size_config: InputSizePreset = InputSizePreset.DEFAULT, model_ckpt: Optional[str] = None ): input_size = get_configured_input_size(input_size_config, model_ckpt) if input_size is None: return # segmentation models have different input...
Python
nomic_cornstack_python_v1
function make data samples begin string reads in .loci and builds alleles from case characters comment read in loci file set outfile = open join path outfiles name + string .alleles string w set lines = open join path outfiles name + string .loci string r comment Get the longest sample name for pretty printing set long...
def make(data, samples): """ reads in .loci and builds alleles from case characters """ #read in loci file outfile = open(os.path.join(data.dirs.outfiles, data.name+".alleles"), 'w') lines = open(os.path.join(data.dirs.outfiles, data.name+".loci"), 'r') ## Get the longest sample name for prett...
Python
jtatman_500k
comment program to check if a year is a leap year or not comment Mick Perring comment 8 March 2014 comment lets user input a year set year = eval input string Enter a year: comment checks if year is divisible by 4 if year % 4 == 0 begin comment checks if year is divisible by 100 if year % 100 == 0 begin comment checks ...
# program to check if a year is a leap year or not # Mick Perring # 8 March 2014 # lets user input a year year = eval(input("Enter a year:""\n")) if (year % 4) == 0: # checks if year is divisible by 4 if (year % 100) == 0: # checks if year is divisible b...
Python
zaydzuhri_stack_edu_python
function backwards string begin set new = join string reversed string return new end function
def backwards(string): new = ''.join(reversed(string)) return new
Python
zaydzuhri_stack_edu_python
function day self begin return get pulumi self string day end function
def day(self) -> pulumi.Input['WeeklyMaintenanceWindowDay']: return pulumi.get(self, "day")
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_squared_error as rmse from sklearn.model_selection import train_test_split comment Read all data and join the data set data_features = read csv string ../../Data/Refined/features_dataset_refined.csv se...
import pandas as pd import numpy as np from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_squared_error as rmse from sklearn.model_selection import train_test_split # Read all data and join the data data_features = pd.read_csv('../../Data/Refined/features_dataset_refined.csv') data_featu...
Python
zaydzuhri_stack_edu_python
function infix fmt begin function decorator fn begin function pp t begin return fmt % t end function set pp = pp return fn end function return decorator end function function conditional fn begin set conditional = true return fn end function decorator call infix string %s + %s function add a b begin return a + b end fu...
def infix(fmt): def decorator(fn): def pp(t): return fmt % t fn.pp = pp return fn return decorator def conditional(fn): fn.conditional = True return fn @infix("%s + %s") def add(a, b): return a + b @infix("%s - %s") def sub(a, b): return a - b @infix("%s & %s") def andl(a, b): return a & b @infix(...
Python
zaydzuhri_stack_edu_python
function dthandler obj begin if has attribute obj string isoformat begin return call isoformat end else begin raise call TypeError string Object can not be isoformatted. end end function
def dthandler(obj): if hasattr(obj, "isoformat"): return obj.isoformat() else: raise TypeError("Object can not be isoformatted.")
Python
nomic_cornstack_python_v1
function __init__ self main_window begin set parent_window = window set app_view = main_window set box = call Edit_Box call connect_signals call setup_signals call set_transient_for parent_window comment Width and Height of the parent window. set tuple width height = call get_size call set_size_request width / 2 height...
def __init__(self,main_window): self.parent_window = main_window.window self.app_view = main_window self.box = Edit_Box() self.box.interface.connect_signals(self.setup_signals()) self.box.dialog.set_transient_for(self.parent_window) ## Width and Height of the p...
Python
nomic_cornstack_python_v1
function switch next begin global _current set _current = next if firstrun begin set firstrun = false call switch *next.args keyword kwargs end else begin call switch end end function
def switch(next): global _current _current = next if next.firstrun: next.firstrun = False next.greenlet.switch(*next.args, **next.kwargs) else: next.greenlet.switch()
Python
nomic_cornstack_python_v1