code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function main begin set client = call build string shopping SHOPPING_API_VERSION developerKey=DEVELOPER_KEY set resource = call products set request = list source=string public country=string US set response = execute request call pprint response end function
def main(): client = build("shopping", SHOPPING_API_VERSION, developerKey=DEVELOPER_KEY) resource = client.products() request = resource.list(source="public", country="US") response = request.execute() pprint.pprint(response)
Python
nomic_cornstack_python_v1
function new_client clockspeed img_height img_width ip_port_file_name=DEFAULT_IP_PORT_FILE_NAME mode=string WINDOWED_DISPLAY use_locker=true lock_client=none begin if use_locker begin call print_with_pid string DEBUG: new_client: waiting for lock... acquire lock_client call print_with_pid string DEBUG: new_client: lock...
def new_client(clockspeed, img_height, img_width, ip_port_file_name=DEFAULT_IP_PORT_FILE_NAME, mode='WINDOWED_DISPLAY', use_locker=True, lock_client=None): if use_locker: print_with_pid("DEBUG: new_client: waiting for lock...") lock_client.acquire() print_with_pid("DEBUG: new_client: lock ac...
Python
nomic_cornstack_python_v1
import y2022.shared as shared from dataclasses import dataclass , field from typing import Union , List from collections import deque comment Data set raw = call read_file string day10.txt set test = call read_file string day10-test.txt decorator dataclass comment Functions class Signal begin set instructions : List at...
import y2022.shared as shared from dataclasses import dataclass, field from typing import Union, List from collections import deque ## Data raw = shared.read_file("day10.txt") test = shared.read_file("day10-test.txt") ## Functions @dataclass class Signal: instructions: List[str] queue: deque = None regist...
Python
zaydzuhri_stack_edu_python
function _build_regexes begin comment Define a regex that matches ASCII text. set encoding_regexes = dict string ascii compile string ^[-]*$ for encoding in CHARMAP_ENCODINGS begin comment Make a sequence of characters that bytes \x80 to \xFF decode to comment in each encoding, as well as byte \x1A, which is used to ...
def _build_regexes(): # Define a regex that matches ASCII text. encoding_regexes = {u'ascii': re.compile('^[\x00-\x7f]*$')} for encoding in CHARMAP_ENCODINGS: # Make a sequence of characters that bytes \x80 to \xFF decode to # in each encoding, as well as byte \x1A, which is used to represe...
Python
nomic_cornstack_python_v1
from microbit import * set test0 = string 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 set test1 = string 2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 set test2 = string 4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 set test3 = string 8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 set test4 = string 16 17 18 19 20 21 22 23 24 25 26 27 2...
from microbit import * test0 = '1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 ' test1 = '2 3 6 7 10 11 14 15 18 19 22 23 26 27 30 ' test2 = '4 5 6 7 12 13 14 15 20 21 22 23 28 29 30 ' test3 = '8 9 10 11 12 13 14 15 24 25 26 27 28 29 30 ' test4 = '16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ' answer = 0 #0 display.scroll(...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import json import argparse set parser = call ArgumentParser description=string Make a map call add_argument string input type=str help=string Input default=string Json file function make_map values mini=none maxi=none title=string delim=none begin if mini == ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import argparse parser = argparse.ArgumentParser(description='Make a map') parser.add_argument('input', type=str, help='Input', default="Json file") def make_map(values, mini=None, maxi=None, title="", delim=None): if mini == None: mini = min(valu...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 import random set number = random integer - 10 10 if number > 0 begin print string {:d} is positive number end else if number == 0 begin print string {:d} is zero number end else if number < 0 begin print string {:d} is negative number end
#!/usr/bin/python3 import random number = random.randint(-10, 10) if (number > 0): print("{:d} is positive", number) elif (number == 0): print("{:d} is zero", number) elif (number < 0): print("{:d} is negative", number)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding=utf-8 string a customize class. python 未知bug, 在__str__函数里调用父类的函数,同时定义了__repr__ = __str__函数, 调用str()内建函数就会出错,好是是一个无穷递归所造成的。 class NumStr extends object begin function __init__ self num=0 string=string begin set __num = num set __string = string end function comment define for ...
#!/usr/bin/env python # coding=utf-8 """ a customize class. python 未知bug, 在__str__函数里调用父类的函数,同时定义了__repr__ = __str__函数, 调用str()内建函数就会出错,好是是一个无穷递归所造成的。 """ class NumStr(object): def __init__(self, num=0, string=''): self.__num = num self.__string = string def __str__(self): # define for str()...
Python
zaydzuhri_stack_edu_python
function add_photo_to_observation observation_id photo access_token user_agent=none begin set response = post url=format string {base_url}/observation_photos base_url=INAT_BASE_URL access_token=access_token data=dict string observation_photo[observation_id] observation_id files=dict string file call ensure_file_obj pho...
def add_photo_to_observation( observation_id: int, photo: FileOrPath, access_token: str, user_agent: str = None, ): response = post( url="{base_url}/observation_photos".format(base_url=INAT_BASE_URL), access_token=access_token, data={"observation_photo[observation_id]": obser...
Python
nomic_cornstack_python_v1
function get_reco_entries_as_ndarray self *args **kwargs begin return call get_entries_as_ndarray *args keyword kwargs end function
def get_reco_entries_as_ndarray(self, *args, **kwargs): return self.reco_binning.get_entries_as_ndarray(*args, **kwargs)
Python
nomic_cornstack_python_v1
function create self request **kwargs begin comment this is full name actually set fullname = CLEANED at string fullname set email = CLEANED at string email set password = CLEANED at string password set username = CLEANED at string username comment Prevent repeatly create user with the SAME email if exists filter email...
def create(self, request, **kwargs): fullname = request.CLEANED['fullname'] #this is full name actually email = request.CLEANED['email'] password = request.CLEANED['password'] username = request.CLEANED['username'] # Prevent repeatly create user with the SAME email if Use...
Python
nomic_cornstack_python_v1
from typing import Generator , List , Dict from contextlib import closing from urllib.request import urlopen from lxml import etree import os.path import gzip import re set _DEFAULT_DB = join path directory name path __file__ string jm.db set _DEFAULT_URL = string http://ftp.monash.edu.au/pub/nihongo/JMdict_e.gz class ...
from typing import Generator, List, Dict from contextlib import closing from urllib.request import urlopen from lxml import etree import os.path import gzip import re _DEFAULT_DB = os.path.join(os.path.dirname(__file__), 'jm.db') _DEFAULT_URL = 'http://ftp.monash.edu.au/pub/nihongo/JMdict_e.gz' class JmDBError(Excep...
Python
zaydzuhri_stack_edu_python
string You are welcome to use any part of the Python Standard Library in addition to Flask. from flask import Flask , render_template , abort , request , make_response import base64 from http.cookies import SimpleCookie import sys append path string .. import grader import json set app = call Flask __name__ decorator c...
"""You are welcome to use any part of the Python Standard Library in addition to Flask.""" from flask import Flask, render_template, abort, request, make_response import base64 from http.cookies import SimpleCookie import sys sys.path.append("..") import grader import json app = Flask(__name__) @app.route('/xss/<vuln...
Python
zaydzuhri_stack_edu_python
comment -*-coding:Utf-8 -* string Implements a reader of VCF files. from Generators.SfsGenerator import SfsGenerator from VariantCallSet.IndividualCallValue import IndividualCallValue , Genotype from VariantCallSet.VariantCall import VariantCall from VariantCallSet.VariantCallSet import VariantCallSet from datetime imp...
# -*-coding:Utf-8 -* """ Implements a reader of VCF files. """ from Generators.SfsGenerator import SfsGenerator from VariantCallSet.IndividualCallValue import IndividualCallValue, Genotype from VariantCallSet.VariantCall import VariantCall from VariantCallSet.VariantCallSet import VariantCallSet from datetime impo...
Python
zaydzuhri_stack_edu_python
from PIL import Image set img = open string D:pict\1.jpg set left = 50 set top = 200 set width = 1700 set height = 2200 set box = tuple left top width height set resized_img = call crop box save string D:\pict_recize\2.jpg set res_img = open string D:\pict_recize\2.jpg set watermark = open string D:\watermark\watermark...
from PIL import Image img = Image.open(r"D:pict\1.jpg") left=50 top=200 width=1700 height=2200 box=(left,top,width,height) resized_img=img.crop((box)) resized_img.save(r"D:\pict_recize\2.jpg") res_img=Image.open(r"D:\pict_recize\2.jpg") watermark=Image.open (r"D:\watermark\watermark.png") width_w=500 heig...
Python
zaydzuhri_stack_edu_python
function prepare_url_to_request url begin return url comment get server url from database set cursor = call cursor execute cursor string SELECT url, id FROM servers ORDER BY used_at ASC LIMIT 1 set row = call fetchone set server_url = row at 0 set identity = row at 1 comment update server usage time in database execute...
def prepare_url_to_request(url): return url # get server url from database cursor = Database.cursor() cursor.execute("SELECT url, id FROM servers ORDER BY used_at ASC LIMIT 1") row = cursor.fetchone() server_url = row[0] identity = row[1] # update server u...
Python
nomic_cornstack_python_v1
function find_classes self Y begin set classes = list set Y if length classes != 2 begin raise exception string this does not seem to be a 2-class problem end set positive_class = classes at 0 set negative_class = classes at 1 end function
def find_classes(self, Y): classes = list(set(Y)) if len(classes) != 2: raise Exception("this does not seem to be a 2-class problem") self.positive_class = classes[0] self.negative_class = classes[1]
Python
nomic_cornstack_python_v1
set ta = eval input string Enter the temperature in Fahrenheit between -58 and 41: set v = eval input string Enter the wind speed in miles per hour: set twc = 35.74 + 0.6215 * ta - 35.75 * v ^ 0.16 + 0.4275 * ta * v ^ 0.16 print string The wind chill index is string %.5f % twc
ta = eval(input("Enter the temperature in Fahrenheit between -58 and 41: ")) v = eval(input("Enter the wind speed in miles per hour: ")) twc = 35.74 + 0.6215*ta - 35.75 * v**0.16 + 0.4275 * ta * v**0.16 print("The wind chill index is ", "%.5f"%twc)
Python
zaydzuhri_stack_edu_python
comment Faça um programa que leia um númer de 0 a 9999 e mostre na tela cada um dos digitos separados set num = integer input string Digite um número entre '1' e '9999': set m = num // 1000 % 10 set c = num // 100 % 10 set d = num // 10 % 10 set u = num // 1 % 10 print string Analisando o número { num } print string Mi...
# Faça um programa que leia um númer de 0 a 9999 e mostre na tela cada um dos digitos separados num = int(input("Digite um número entre '1' e '9999': ")) m = num // 1000 % 10 c = num // 100 % 10 d = num // 10 % 10 u = num // 1 % 10 print(f'Analisando o número {num}') print(f'Milhar: {m}') print(f'Centena:...
Python
zaydzuhri_stack_edu_python
import sys import requests import re from bs4 import BeautifulSoup comment getting the encoding of the site through meta tag function get_encoding_by_tag soup begin if soup and meta begin set encod = get meta string charset if encod == none begin set encod = get meta string content-type if encod == none begin set conte...
import sys import requests import re from bs4 import BeautifulSoup #getting the encoding of the site through meta tag def get_encoding_by_tag(soup): if soup and soup.meta: encod = soup.meta.get('charset') if encod == None: encod = soup.meta.get('content-type') if encod == No...
Python
zaydzuhri_stack_edu_python
comment solve quadratic equation import cmath set a = decimal input string enter a: set b = decimal input string enter b: set c = decimal input string enter c: set d = b ^ 2 - 4 * a * c set sol1 = - b - square root d / 2 * a set sol2 = - b + square root d / 2 * a print string the solution of given equation is : sol1 so...
# solve quadratic equation import cmath a=float(input("enter a:")) b=float(input("enter b:")) c=float(input("enter c:")) d=(b**2)-(4*a*c) sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print("the solution of given equation is :",sol1,sol2)
Python
zaydzuhri_stack_edu_python
function test_healthy_only_works_for_list_of_functions self begin set actors = list comprehension call remote i for i in range 4 set manager = call FaultTolerantActorManager actors=actors comment Mark first and second actor as unhealthy. call set_actor_state 1 false call set_actor_state 2 false function f id _ begin re...
def test_healthy_only_works_for_list_of_functions(self): actors = [Actor.remote(i) for i in range(4)] manager = FaultTolerantActorManager(actors=actors) # Mark first and second actor as unhealthy. manager.set_actor_state(1, False) manager.set_actor_state(2, False) def f...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import copy import random set supported_theorem_provers = list string problog set default_theorem_prover = string problog set variables = list string X comment In the original RuleTaker dataset, variables were represented using the following NL. comment These are used to check if an argumen...
#!/usr/bin/env python import copy import random supported_theorem_provers = ["problog"] default_theorem_prover = "problog" variables = ["X"] # In the original RuleTaker dataset, variables were represented using the following NL. # These are used to check if an argument is a variable when we are loading/processing # ...
Python
zaydzuhri_stack_edu_python
comment l=[x for x in range(11)] #1 comment #print (l) comment e=o=0 comment for x in l: comment if x == 0: continue comment elif x % 2 == 0: e+=1 comment else: o+=1 comment print("e= ",e,"o= ",o) comment print(input("enter string")[::-1]) #2 comment dic={"a":1,"b":2} #3 comment print( (input("enter a key to find: ") i...
# l=[x for x in range(11)] #1 # #print (l) # e=o=0 # for x in l: # if x == 0: continue # elif x % 2 == 0: e+=1 # else: o+=1 # print("e= ",e,"o= ",o) # print(input("enter string")[::-1]) #2 # dic={"a":1,"b":2} #3 # print( (input("enter a key to find: ") in dic.keys()) and 'already in' or ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import pytest import ib import ejercicio import pdb from decimal import Decimal comment Tests de los módulos function test_is_compatible begin string Test para la función _is_compatible de BinaryEvent. set A = call BinaryEvent set B = call BinaryEvent set C = call BinaryEvent set X = call ...
#-*- coding: utf-8 -*- import pytest import ib import ejercicio import pdb from decimal import Decimal # Tests de los módulos def test_is_compatible(): "Test para la función _is_compatible de BinaryEvent." A = ib.BinaryEvent() B = ib.BinaryEvent() C = ib.BinaryEvent() X = ib.BinaryEvent({A: 1, B: ...
Python
zaydzuhri_stack_edu_python
function alphabet_position letter begin set alpha = string abcdefghijklmnopqrstuvwxyz set letter = lower letter return index alpha letter end function function rotate_character char rot begin comment ignore char that are NOT letters if is alpha char begin comment new rotated position set rotat_posit = call alphabet_pos...
def alphabet_position(letter): alpha = 'abcdefghijklmnopqrstuvwxyz' letter = letter.lower() return alpha.index(letter) def rotate_character(char, rot): if char.isalpha(): #ignore char that are NOT letters rotat_posit = (alphabet_position(char) + rot) % 26 #new rotated position posit...
Python
zaydzuhri_stack_edu_python
string VISDRONE Dataset Classes Original author: Francisco Massa https://github.com/fmassa/vision/blob/voc_dataset/torchvision/datasets/voc.py Updated by: Ellis Brown, Max deGroot Modified for the VisDrone dataset by Evgeny Markin from config import HOME import os.path as osp import sys import torch import torch.utils....
"""VISDRONE Dataset Classes Original author: Francisco Massa https://github.com/fmassa/vision/blob/voc_dataset/torchvision/datasets/voc.py Updated by: Ellis Brown, Max deGroot Modified for the VisDrone dataset by Evgeny Markin """ from .config import HOME import os.path as osp import sys import torch import torch.ut...
Python
zaydzuhri_stack_edu_python
function load_XML self filename begin if is instance zip ZipFile begin try begin extract zip filename path end except KeyError begin warn format string Excel file does not contain {0} filename return self end end if has attribute etree string parse begin set xml = parse etree join path path filename set xmls at filenam...
def load_XML(self, filename): if isinstance(self.zip, ZipFile): try: self.zip.extract(filename, self.path) except KeyError: log.warn('Excel file does not contain {0}'.format(filename)) return self if hasattr(etree, 'parse'): ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment @Time : 2018/8/8 14:27 comment @Author : melon string 垃圾邮件过滤之特征工程 import re import matplotlib as mpl import pandas as pd if __name__ == string __main__ begin comment 设置字符集,防止中文乱码 set rcParams at string font.sans-serif = list string simHei set rcParams at string axes.unicode_minus =...
# -*- coding: utf-8 -*- # @Time : 2018/8/8 14:27 # @Author : melon '''垃圾邮件过滤之特征工程''' import re import matplotlib as mpl import pandas as pd if __name__ == '__main__': # 设置字符集,防止中文乱码 mpl.rcParams['font.sans-serif'] = [u'simHei'] mpl.rcParams['axes.unicode_minus'] = False # 1. 文件数据读取 df = pd...
Python
zaydzuhri_stack_edu_python
function ylabelbox ax text color bgcolor=none size=6 boxsize=0.1 pad=0.05 **kwargs begin set boxsize = string boxsize * 100 + string % set divider = call make_axes_locatable ax set cax = call append_axes string left size=boxsize pad=pad call set_visible false call set_visible false call set_visible true call set_visibl...
def ylabelbox(ax, text, color, bgcolor=None, size=6, boxsize=0.1, pad=0.05, **kwargs): boxsize=str(boxsize * 100) + '%' divider = make_axes_locatable(ax) cax = divider.append_axes("left", size=boxsize, pad=pad) cax.get_xaxis().set_visible(False) cax.get_yaxis().set_visible(False) cax.spines["to...
Python
nomic_cornstack_python_v1
function getRejectSchema self begin pass end function
def getRejectSchema(self): pass
Python
nomic_cornstack_python_v1
function call *popenargs **kwargs begin comment workaround: subprocess.Popen(cmd, stdout=sys.stdout) fails comment see http://bugs.python.org/issue1531862 if string stdout in kwargs begin set fileno = call fileno del kwargs at string stdout return wait popen *popenargs stdout=call dup fileno keyword kwargs end return w...
def call(*popenargs, **kwargs): # workaround: subprocess.Popen(cmd, stdout=sys.stdout) fails # see http://bugs.python.org/issue1531862 if "stdout" in kwargs: fileno = kwargs.get("stdout").fileno() del kwargs['stdout'] return Popen(stdout=os.dup(fileno), ...
Python
nomic_cornstack_python_v1
from turtle import RawTurtle , TurtleScreen class DrawableTurtle extends RawTurtle begin function __init__ self cv begin set ts = call TurtleScreen cv call __init__ self ts comment self.turtleRef = turt set ts = ts call listen set isDrawing = false call penup call speed 0 set canvas = cv call bind string <Button-1> onD...
from turtle import RawTurtle, TurtleScreen class DrawableTurtle(RawTurtle): def __init__(self, cv): ts = TurtleScreen(cv) RawTurtle.__init__(self, ts) # self.turtleRef = turt self.ts = ts ts.listen() self.isDrawing = False self.penup() self.speed(0) ...
Python
zaydzuhri_stack_edu_python
function writeRnaDotBracketNotation self sequence pairedBases outputFileName begin set stack = dict for i in range 0 length sequence begin if i in pairedBases begin set stack at i = string ( set stack at pairedBases at i = string ) end else if not i in stack begin set stack at i = string . end end set fileToWrite = op...
def writeRnaDotBracketNotation(self, sequence, pairedBases, outputFileName): stack = {} for i in range (0, len(sequence)): if i in pairedBases: stack[i] = "(" stack[pairedBases[i]] = ")" else: if not i in stack: ...
Python
nomic_cornstack_python_v1
import keras from keras import backend as K from keras.models import Sequential , load_model , model_from_json from keras.layers import Activation from keras.layers.core import Dense comment 1 load all: architecture, weights, training config (loss, optimizer), state of optimizer set model = call load_model string saveA...
import keras from keras import backend as K from keras.models import Sequential, load_model, model_from_json from keras.layers import Activation from keras.layers.core import Dense #1 load all: architecture, weights, training config (loss, optimizer), state of optimizer model = load_model("saveAll.h5") model.summary()...
Python
zaydzuhri_stack_edu_python
string This topological sort implementation takes an adjacency list of an acyclic graph and returns an array with the indexes of the nodes in a (non unique) topological order which tells you how to process the nodes in the graph. More precisely from wiki: A topological ordering is a linear ordering of its vertices such...
''' This topological sort implementation takes an adjacency list of an acyclic graph and returns an array with the indexes of the nodes in a (non unique) topological order which tells you how to process the nodes in the graph. More precisely from wiki: A topological ordering is a linear ordering of its vertices such th...
Python
zaydzuhri_stack_edu_python
from zope.interface import Interface class ICompleteness extends Interface begin string Provides methods to check completeness. function isComplete begin string Checks whether the data of an object is complete. end function end class class IType extends Interface begin string Provides methods to get type informations. ...
from zope.interface import Interface class ICompleteness(Interface): """Provides methods to check completeness. """ def isComplete(): """Checks whether the data of an object is complete. """ class IType(Interface): """Provides methods to get type informations. """ ...
Python
zaydzuhri_stack_edu_python
function f x y z begin if z > y > x begin print z string e o maior. end end function f dist 2 3 4 print string EXERCICIO 2 function somando lista begin set l = lista return l end function set l = call somando list 11 10 10 set soma = 0 for i in range length l begin set soma = soma + l at i end print soma print string E...
def f(x,y,z): if z>y>x : print (z, " e o maior.") f(2,3,4) print("EXERCICIO 2") def somando(lista): l = lista return l l = somando([11,10,10]) soma = 0 for i in range(len(l)): soma += l[i] print(soma) print("EXERCICIO 3") def multiplica(lista2): l = lista2 return l l = multipli...
Python
zaydzuhri_stack_edu_python
function extract_subtype_information input_json begin try begin set subtype = input_json at string subtypeText end except any begin print string Subtype data not found end return subtype end function
def extract_subtype_information(input_json): try: subtype = input_json['subtypeText'] except: print("Subtype data not found") return subtype
Python
zaydzuhri_stack_edu_python
from VoiceUtils.voice2word import * from VoiceUtils.recorder import Recorder from playsound import playsound string 我用windows+python,所以在playsound里的winCommand里添加下面的代码 while True: if winCommand('status', alias, 'mode').decode() == 'stopped': winCommand('close', alias) break 一定在“winCommand('play', alias, 'from 0 to', dura...
from VoiceUtils.voice2word import * from VoiceUtils.recorder import Recorder from playsound import playsound """ 我用windows+python,所以在playsound里的winCommand里添加下面的代码 while True: if winCommand('status', alias, 'mode').decode() == 'stopped': winCommand('close', alias) break 一定在“winCommand('play', alias,...
Python
zaydzuhri_stack_edu_python
from random import randrange as rnd , choice from tkinter import * import math import time set root = call Tk set fr = call Frame root call geometry string 800x600 set canv = call Canvas root bg=string white call pack fill=BOTH expand=1 class Ball begin function __init__ self x=40 y=450 begin set x = x set y = y set r ...
from random import randrange as rnd, choice from tkinter import * import math import time root = Tk() fr = Frame(root) root.geometry('800x600') canv = Canvas(root, bg='white') canv.pack(fill=BOTH, expand=1) class Ball(): def __init__(self, x=40, y=450): self.x = x self.y = y self.r ...
Python
zaydzuhri_stack_edu_python
function _get_kwargs op begin set kwargs = args remove kwargs string self return kwargs end function
def _get_kwargs(op): kwargs = inspect.getfullargspec(op).args kwargs.remove("self") return kwargs
Python
nomic_cornstack_python_v1
function __eq__ self other begin if not is instance other DestinyItemStatBlockDefinition begin return false end return __dict__ == __dict__ end function
def __eq__(self, other): if not isinstance(other, DestinyItemStatBlockDefinition): return False return self.__dict__ == other.__dict__
Python
nomic_cornstack_python_v1
function _backward self x begin set T = length x set beta = zeros tuple T hidden_states comment Explicitly set up beta[T-1, :] = log1 = 0 set beta at tuple - 1 slice : : = zeros hidden_states set work_buffer = zeros hidden_states for this_t in reversed range T - 1 begin set next_obs = x at this_t + 1 for this_s_prev...
def _backward(self, x) -> np.ndarray: T = len(x) beta = np.zeros((T, self.hidden_states)) # Explicitly set up beta[T-1, :] = log1 = 0 beta[-1, :] = np.zeros(self.hidden_states) work_buffer = np.zeros(self.hidden_states) for this_t in reversed(range(T-1)): nex...
Python
nomic_cornstack_python_v1
function main begin comment will print 4 print search range 1 21 2 9 comment will print -1 print search range 1 21 2 0 end function
def main(): print(search(range(1, 21, 2), 9)) # will print 4 print(search(range(1, 21, 2), 0)) # will print -1
Python
nomic_cornstack_python_v1
function transition self begin for node in call nodes begin if node not in evidence begin call update_node node end end end function
def transition(self): for node in self.net.nodes(): if node not in self.evidence: self.update_node(node)
Python
nomic_cornstack_python_v1
function initialsamples self begin pass end function
def initialsamples(self): pass
Python
nomic_cornstack_python_v1
function as_ref_datetime timespec begin try begin set dt = call as_datetime timespec tz=REF_TZ set hms_dt = call astimezone REF_TZ return hms_dt end except Exception begin raise call DatetimeCoercionFailure timespec=timespec timezone=REF_TZ end end function
def as_ref_datetime(timespec): try: dt = as_datetime(timespec, tz=REF_TZ) hms_dt = dt.astimezone(REF_TZ) return hms_dt except Exception: raise DatetimeCoercionFailure(timespec=timespec, timezone=REF_TZ)
Python
nomic_cornstack_python_v1
function fusion_api_get_deployment_manager self uri=none param=string api=none headers=none begin return get dep_mgr uri=uri api=api headers=headers param=param end function
def fusion_api_get_deployment_manager(self, uri=None, param='', api=None, headers=None): return self.dep_mgr.get(uri=uri, api=api, headers=headers, param=param)
Python
nomic_cornstack_python_v1
function get_passports inputs begin string Converts input into whole passports set passports = list set p = string for line in inputs begin if line == string begin append passports p set p = string end else begin set p = p + replace line string string end end comment Catch the last block append passports p return ...
def get_passports(inputs): """Converts input into whole passports""" passports = [] p = '' for line in inputs: if line == '\n': passports.append(p) p = '' else: p += line.replace('\n', ' ') passports.append(p) # Catch the last block return pas...
Python
zaydzuhri_stack_edu_python
from collections import Counter from math import log2 from os.path import getsize set filename = input string Дайте будь-ласка назву файлу (без txt) + string .txt set filesize = get size filename set file = open filename string r encoding=string utf-8 set text = read file close file set count = counter text set enthrop...
from collections import Counter from math import log2 from os.path import getsize filename = input("Дайте будь-ласка назву файлу (без txt) ") + ".txt" filesize = getsize(filename) file = open(filename, "r", encoding="utf-8") text = file.read() file.close() count = Counter(text) enthrop = 0 for k in count.keys(): p...
Python
zaydzuhri_stack_edu_python
function sample_scaled self shape begin string sample_scaled(shape) -> bounding_box Yields an iterator that iterates over all sampled bounding boxes in the given (scaled) image shape. **Parameters:** ``shape`` : (int, int) or (int, int, int) The (current) shape of the (scaled) image **Yields:** ``bounding_box`` : :py:c...
def sample_scaled(self, shape): """sample_scaled(shape) -> bounding_box Yields an iterator that iterates over all sampled bounding boxes in the given (scaled) image shape. **Parameters:** ``shape`` : (int, int) or (int, int, int) The (current) shape of the (scaled) image **Yields:** `...
Python
jtatman_500k
function verify_tor_connection begin set content = read url open string https://check.torproject.org/ comment <h1 class="off"> - not using tor comment <h1 class="not"> - using tor without torbrowser comment <h1 class="on"> - using tor with torbrowser return find content b'class="off"' == - 1 end function
def verify_tor_connection(): content = urlopen('https://check.torproject.org/').read() # <h1 class="off"> - not using tor # <h1 class="not"> - using tor without torbrowser # <h1 class="on"> - using tor with torbrowser return content.find(b'class="off"')==-1
Python
nomic_cornstack_python_v1
function getConferenceSessionsByType self request begin set sessions = call _getConferenceSessionsByType request comment Return individual SessionForm object per Session return call SessionForms items=list comprehension call _copySessionToForm session for session in sessions end function
def getConferenceSessionsByType(self, request): sessions = self._getConferenceSessionsByType(request) # Return individual SessionForm object per Session return SessionForms( items=[self._copySessionToForm(session) for session in sessions] )
Python
nomic_cornstack_python_v1
function _get_child_text parent name begin return call _get_text call _get_first_child_named parent name end function
def _get_child_text(parent, name): return _get_text(_get_first_child_named(parent, name))
Python
nomic_cornstack_python_v1
comment given an array of integers, return indicies of the two numbers so they add up to a specific targe. comment assume each input has one solution comment you may not use same element twice comment Given numbers = 2, 7, 11, 15 comment target is 9 comment 2 + 7 is 9 and the indicies are 0 and 1 comment return 0, 1 co...
#given an array of integers, return indicies of the two numbers so they add up to a specific targe. # assume each input has one solution # you may not use same element twice # Given numbers = 2, 7, 11, 15 # target is 9 # 2 + 7 is 9 and the indicies are 0 and 1 # return 0, 1 #using a hashmap #key is value of ...
Python
zaydzuhri_stack_edu_python
function __read_file self begin raise NotImplementedError end function
def __read_file(self): raise NotImplementedError
Python
nomic_cornstack_python_v1
function foo begin set i = 0 while i < 5 begin if i > 2 begin break end print i set i = i + 1 end while else begin print string broken end end function call foo comment out: 0 comment out: 1 comment out: 2 function bar begin set i = 3 while i < 5 begin print i set i = i + 1 end while else begin print string success end...
def foo(): i = 0 while i < 5: if i > 2: break print(i) i += 1 else: print("broken") foo() #out: 0 #out: 1 #out: 2 def bar(): i = 3 while i < 5: print(i) i += 1 else: print("success") bar() #out: 3 #out: 4 #out: success
Python
zaydzuhri_stack_edu_python
function version only_number=false begin if only_number begin call tsecho VERSION end else begin call tsecho string MocaTwitterUtils ( { VERSION } ) end end function
def version(only_number: bool = False) -> None: if only_number: mzk.tsecho(core.VERSION) else: mzk.tsecho(f'MocaTwitterUtils ({core.VERSION})')
Python
nomic_cornstack_python_v1
function adjoint self add mod dat begin if shape at 0 != __nm or shape at 0 != __nd begin raise exception string lint adjoint: input shapes do not match those passed to constructor end if add == false begin set mod at slice : : = 0.0 end call adjoint_lint __om __dm __nm __nd __crd mod dat end function
def adjoint(self,add,mod,dat): if(mod.shape[0] != self.__nm or dat.shape[0] != self.__nd): raise Exception("lint adjoint: input shapes do not match those passed to constructor") if(add == False): mod[:] = 0.0 adjoint_lint(self.__om,self.__dm,self.__nm,self.__nd,self.__crd,mod,dat)
Python
nomic_cornstack_python_v1
function mark_recommendation_failed self request=none name=none state_metadata=none etag=none retry=DEFAULT timeout=DEFAULT metadata=tuple begin comment Create or coerce a protobuf request object. comment Quick check: If we got a request object, we should *not* have comment gotten any keyword arguments that map to the ...
def mark_recommendation_failed( self, request: Optional[ Union[recommender_service.MarkRecommendationFailedRequest, dict] ] = None, *, name: Optional[str] = None, state_metadata: Optional[MutableMapping[str, str]] = None, etag: Optional[str] = None, ...
Python
nomic_cornstack_python_v1
function ids_bystate state cfgdict=coaps_config begin set data = call stationinfo_bystate state cfgdict=cfgdict try begin set coopid = data at string COOP_ID end except ValueError begin set coopid = data at string COOPID end return dictionary zip data at string STATION_NAME as type coopid int end function
def ids_bystate(state, cfgdict=coaps_config): data = stationinfo_bystate(state, cfgdict=cfgdict) try: coopid = data['COOP_ID'] except ValueError: coopid = data['COOPID'] return dict(zip(data['STATION_NAME'], coopid.astype(int)))
Python
nomic_cornstack_python_v1
from src import QLK from src.Date import Date function Add lst begin if length lst == 6 begin set tuple name quantity price day month year = lst if name != string and quantity != string and price != string and day != string and month != string and year != string begin append dsKho call QLK name integer quantity i...
from src import QLK from src.Date import Date def Add(lst): if len(lst) == 6: name, quantity, price, day, month, year = lst if ( name != "" and quantity != "" and price != "" and day != "" and month != "" and year != "" ...
Python
zaydzuhri_stack_edu_python
function send_msg msg dpid begin debug format string Installing rule on switch {} dpid debug show call sendToDPID dpid msg end function
def send_msg(msg, dpid): log.debug("Installing rule on switch {}".format(dpid)) log.debug(msg.show()) core.openflow.sendToDPID(dpid, msg)
Python
nomic_cornstack_python_v1
comment tabledresser - a reddit bot that turns AMAs into tables comment Copyright (C) 2012-2015 Yann Kaiser comment This program is free software: you can redistribute it and/or modify comment it under the terms of the GNU General Public License as published by comment the Free Software Foundation, either version 3 of ...
# tabledresser - a reddit bot that turns AMAs into tables # Copyright (C) 2012-2015 Yann Kaiser # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your ...
Python
zaydzuhri_stack_edu_python
from turtle import * import turtle set bg = call Screen call bgcolor string black call speed 0 call color string white call shape string turtle function coolAnimation levels inc c begin set colors = list string black string white if levels == 0 begin return string done end call forward inc call right 55 call circle inc...
from turtle import * import turtle bg = turtle.Screen() bg.bgcolor("black") speed(0) color("white") shape("turtle") def coolAnimation(levels,inc,c): colors = ["black", "white"] if (levels == 0): return "done" forward(inc) right(55) circle(inc) forward(inc) circle(inc) left(...
Python
zaydzuhri_stack_edu_python
function test_without_lambdas_stop_if_invalid_does_not_prevent_errors_report self begin class MyModel begin set name = string Foo end class class DangerValidator extends Validator begin function get_rules self begin return list call TypeRule data string data MyModel stop_if_invalid=true call FullStringRule name string ...
def test_without_lambdas_stop_if_invalid_does_not_prevent_errors_report(self): class MyModel: name = 'Foo' class DangerValidator(Validator): def get_rules(self) -> list: return [ TypeRule(self.data, 'data', MyModel, stop_if_invalid=True), ...
Python
nomic_cornstack_python_v1
function main begin print string mpdtimeline.py::main - Begin. set outputMode = string log set hostUrl = none if string -o in argv begin set outputMode = argv at index argv string -o + 1 end if string -host in argv begin set hostUrl = argv at index argv string -host + 1 end if string -f in argv begin set mpdFilename = ...
def main(): print("mpdtimeline.py::main - Begin.") outputMode = "log" hostUrl = None if '-o' in sys.argv: outputMode = sys.argv[sys.argv.index('-o')+1] if '-host' in sys.argv: hostUrl = sys.argv[sys.argv.index('-host')+1] if '-f' in sys.argv: mpdFilename = sys.argv[sy...
Python
nomic_cornstack_python_v1
function display_ephemeris_header self begin set end_index = where ephemeris == string $$SOE at 0 at 0 - 2 print ephemeris at slice 0 : end_index : end function
def display_ephemeris_header(self): end_index = np.where(self.ephemeris == '$$SOE')[0][0] - 2 print(self.ephemeris[0:end_index])
Python
nomic_cornstack_python_v1
from flask import Flask , request , render_template , redirect import cgi set app = call Flask __name__ set config at string DEBUG = true decorator call route string /join function index begin return call render_template string signin.html username=string username_error=string password=string pass_error=string veri...
from flask import Flask, request, render_template, redirect import cgi app = Flask(__name__) app.config['DEBUG'] = True @app.route('/join') def index(): return render_template("signin.html",username='', username_error='', password='', pass_error='', verify_password='', pass_v_error='', email='', email_error='',s...
Python
zaydzuhri_stack_edu_python
function _next_pos self begin if starts with animation string linear begin set x = x + speed set y = y + speed if x + dim at 0 > height begin set x = 0 end if y > width - dim at 1 begin set y = 0 set end = true end end else if starts with animation string fall begin if x + dim at 0 >= height begin set x = 1 end comment...
def _next_pos(self): if self.animation.startswith("linear"): self.x += self.speed self.y += self.speed if self.x + self.dim[0] > self.height: self.x = 0 if self.y > self.width - self.dim[1]: self.y = 0 self.end = Tru...
Python
nomic_cornstack_python_v1
import json from pygal.maps.world import World from country_codes import get_country_code comment Loads data into a list. set filename = string gpd.json with open filename as f begin set gdp_data = load json f end comment Build a dictionary of GDP data. set values = dict for gdp_dict in gdp_data begin if gdp_dict at s...
import json from pygal.maps.world import World from country_codes import get_country_code # Loads data into a list. filename = 'gpd.json' with open(filename) as f: gdp_data = json.load(f) # Build a dictionary of GDP data. values = {} for gdp_dict in gdp_data: if gdp_dict['Year'] == 2016: country_name ...
Python
zaydzuhri_stack_edu_python
function __ne__ self other begin return not self == other end function
def __ne__(self, other): return not self == other
Python
nomic_cornstack_python_v1
function total_actual_memory self begin return _total_actual_memory end function
def total_actual_memory(self): return self._total_actual_memory
Python
nomic_cornstack_python_v1
import cv2 import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans set img_path = string C:\Users\user\Desktop\parrot.jpg set img = call imread img_path set a = copy np img at tuple slice : : slice : : 0 set img at tuple slice : : slice : : 0 = img at tuple slice : : slice ...
import cv2 import matplotlib.pyplot as plt import numpy as np from sklearn.cluster import KMeans img_path="C:\\Users\\user\\Desktop\\parrot.jpg" img=cv2.imread(img_path) a=np.copy(img[:,:,0]) img[:,:,0]=img[:,:,2] img[:,:,2]=a l=[] l=img.shape img=img.reshape((l[0]*l[1]),l[2]) k=KMeans() d=k.fit(img) out=d.predict(img)...
Python
zaydzuhri_stack_edu_python
string if-elif-else 개념.py elif : else if의 줄임말 if 조건 : 실행문1 elif 조건 : 실행문 1 elif 조건 : 실행문2 elif 조건 : 실행문3 else : 실행문4 Q. 입력받은 점수를 (수우미양가) 로 평가하는 프로그램 수 : 90이상 100 미만 우 : 80이상 90 미만 미 : 70이상 80 미만 양 : 60이상 70 미만 가 : 60미만 if 조건에서 조건이 2개일때 2개다 참일때 실행 - 교집합(and) 1개만 참이어도 실행 - 합집합(or) set score = integer input string 당신의 점수는...
""" if-elif-else 개념.py elif : else if의 줄임말 if 조건 : 실행문1 elif 조건 : 실행문 1 elif 조건 : 실행문2 elif 조건 : 실행문3 else : 실행문4 Q. 입력받은 점수를 (수우미양가) 로 평가하는 프로그램 수 : 90이상 100 미만 우 : 80이상 90 미만 미 : 70이상 80 미만 양 : 60이상 70 미만 가 : 60미만 if 조건에서 조건이 2개일때 2개다 참일때 실행 - 교집합(and) 1개만 참이어도 실행 - 합집합(or) "...
Python
zaydzuhri_stack_edu_python
import os import shutil function barCode inputFolder outputFolder begin comment make a path for the folder set path1 = string %s/ % inputFolder comment list all things in path1 set fList1 = list directory path1 comment change to path1 change directory path1 comment temp folder name set folderName2 = string data2 commen...
import os import shutil def barCode(inputFolder, outputFolder): #make a path for the folder path1 = "%s/" % inputFolder #list all things in path1 fList1 = os.listdir(path1) #change to path1 os.chdir(path1) #temp folder name folderName2 = 'data2' #path for temp folder path2 = "%s/test1.txt" % folderName2 ...
Python
zaydzuhri_stack_edu_python
function is_duplicate arr begin return length arr != length set arr end function comment returns True call is_duplicate arr
def is_duplicate(arr): return len(arr) != len(set(arr)) is_duplicate(arr) # returns True
Python
jtatman_500k
function draw self surface begin if sprite is not none and rect is not none and call isAlive begin if _drawable is none begin set _drawable = call RenderPlain sprite end call draw surface end end function
def draw(self, surface: pygame.Surface) -> None: if self.sprite is not None and self.sprite.rect is not None and self.isAlive(): if self._drawable is None: self._drawable = pygame.sprite.RenderPlain(self.sprite) self._drawable.draw(surface)
Python
nomic_cornstack_python_v1
function test_pseudo_subtitle begin assert parse parser string Subtitle## == string <p>Subtitle## </p> end function
def test_pseudo_subtitle(): assert parser.parse("Subtitle## ") == "<p>Subtitle## </p>"
Python
nomic_cornstack_python_v1
function walk_through_floors instructions begin set floor = 0 set position = 0 set enter_basement_at = 0 for instruction in instructions begin set position = position + 1 if instruction == string ( begin set floor = floor + 1 end else begin set floor = floor - 1 end if floor == - 1 and enter_basement_at == 0 begin set ...
def walk_through_floors(instructions): floor = 0 position = 0 enter_basement_at = 0 for instruction in instructions: position += 1 if instruction == '(': floor += 1 else: floor -= 1 if floor == -1 and enter_basement_at == 0: enter_basem...
Python
nomic_cornstack_python_v1
function fea_rank_write path fn feature_order_list exc_fun_label fidx begin set num_fea = 0 if length feature_order_list > 0 begin set num_fea = length feature_order_list at 0 end set new_path = path + format string /n{0}/ num_fea call create_path new_path with open feature_ranking_file_path string a+ as f begin if new...
def fea_rank_write(path, fn, \ feature_order_list, exc_fun_label, fidx): num_fea = 0 if len(feature_order_list) > 0: num_fea = len(feature_order_list[0]) new_path = path + "/n{0}/".format(num_fea) create_path(new_path) with open(feature_ranking_file_path, "a+") as f: ...
Python
nomic_cornstack_python_v1
function _bake_from_request arguments begin set request = split shlex request try begin call bake_from_request request output_directory force=force end except ValueError begin print string Request "{arguments.request}" contains one-or-more missing Rez packages. file=stderr exit CANNOT_BAKE_FROM_REQUEST end end function
def _bake_from_request(arguments): request = shlex.split(arguments.request) try: linker.bake_from_request( request, arguments.output_directory, force=arguments.force ) except ValueError: print( 'Request "{arguments.request}" contains one-or-more missing Rez p...
Python
nomic_cornstack_python_v1
function gluUnProject4 baseFunction winX winY winZ clipW model=none proj=none view=none near=0.0 far=1.0 begin if model is none begin set model = call glGetDoublev GL_MODELVIEW_MATRIX end if proj is none begin set proj = call glGetDoublev GL_PROJECTION_MATRIX end if view is none begin set view = call glGetIntegerv GL_V...
def gluUnProject4( baseFunction, winX, winY, winZ, clipW, model=None, proj=None, view=None, near=0.0, far=1.0 ): if model is None: model = GL.glGetDoublev( GL.GL_MODELVIEW_MATRIX ) if proj is None: proj = GL.glGetDoublev( GL.GL_PROJECTION_MATRIX ) if view is None: v...
Python
nomic_cornstack_python_v1
from collections import deque from queue import Queue comment Definition for a binary tree node. class TreeNode begin function __init__ self val=0 left=none right=none begin set val = val set left = left set right = right end function end class function createBinaryTreeFrom bin_tree_array begin return call ___createBin...
from collections import deque from queue import Queue # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def createBinaryTreeFrom(bin_tree_array: []) -> TreeNode: return ___createBi...
Python
zaydzuhri_stack_edu_python
function lockable self begin raise call NotImplementedError string Core Designator is not lockable. Override .lockable() in subclasses and make it so that there's only *one* locker instead of a new one every call. For locking to the exact same Python-object, use the LockingDesignator end function
def lockable(self): raise NotImplementedError("Core Designator is not lockable. Override .lockable() in subclasses and " "make it so that there's only *one* locker instead of a new one every call." " For locking to the exact same Python-object,...
Python
nomic_cornstack_python_v1
class Solution begin function peakIndexInMountainArray self arr begin comment binary search comment 1. mid largest -> move left comment 2. l largest -> move right comment 3. r largest -> move left comment Time O(logn), space O(1) set tuple left right = tuple 0 length arr - 1 while left + 1 < right begin set mid = left ...
class Solution: def peakIndexInMountainArray(self, arr: List[int]) -> int: # binary search # 1. mid largest -> move left # 2. l largest -> move right # 3. r largest -> move left # Time O(logn), space O(1) left, right = 0, len(arr) - 1 while left + 1 < right: ...
Python
zaydzuhri_stack_edu_python
function system_annotations self begin return call SystemAnnotationDict self end function
def system_annotations(self): return attributes.SystemAnnotationDict(self)
Python
nomic_cornstack_python_v1
import time set N = 600851475143
import time N = 600851475143
Python
zaydzuhri_stack_edu_python
function _best_em_loop self X begin set init_seeds = call get_seeds n_seeds=n_init random_state=random_state comment lower bounds for each initialization set init_loss_vals = list for i in range n_init begin if verbosity >= 1 begin set time = string format time now string %H:%M:%S print format string Beginning initial...
def _best_em_loop(self, X): init_seeds = get_seeds(n_seeds=self.n_init, random_state=self.random_state) # lower bounds for each initialization init_loss_vals = [] for i in range(self.n_init): if self.verbosity >= 1: time = da...
Python
nomic_cornstack_python_v1
function set_labels self labels begin if string , in labels begin set labels_qpts = split labels string , end else if string in labels begin set labels_qpts = split labels string end else begin set labels_qpts = labels end end function
def set_labels(self,labels): if ',' in labels: self.labels_qpts = labels.split(',') elif ' ' in labels: self.labels_qpts = labels.split(' ') else: self.labels_qpts = labels
Python
nomic_cornstack_python_v1
function getKeyBytes keyPath size l2r=none offset=none waste=false begin set keySize = get size path keyPath if offset is not none and offset > keySize begin print string key is smaller than key offset file=stderr exit 102 end set keyConfig = load yaml open keyPath + string .yaml string r if offset is none and waste is...
def getKeyBytes(keyPath, size, l2r=None, offset=None, waste=False): keySize = os.path.getsize(keyPath) if offset is not None and offset > keySize: print("key is smaller than key offset", file=sys.stderr) sys.exit(102) keyConfig = yaml.load(open(keyPath+".yaml", 'r')) if offset is None...
Python
nomic_cornstack_python_v1
function transform self input_data is_fit_pipeline_stage begin set features = features if is_fit_pipeline_stage begin comment For fit stage - filter data set mask = inlier_mask_ set inner_features = features at mask comment Update data set modified_input_data = call _update_data input_data mask end else begin comment F...
def transform(self, input_data, is_fit_pipeline_stage: bool): features = input_data.features if is_fit_pipeline_stage: # For fit stage - filter data mask = self.operation.inlier_mask_ inner_features = features[mask] # Update data modified_inp...
Python
nomic_cornstack_python_v1
function GetEnforceConnectivity self begin return call itkSLICImageFilterVISS3IULL3_GetEnforceConnectivity self end function
def GetEnforceConnectivity(self) -> "bool": return _itkSLICImageFilterPython.itkSLICImageFilterVISS3IULL3_GetEnforceConnectivity(self)
Python
nomic_cornstack_python_v1
function set_default_init_cli_cmds self begin set init_cli_cmds = list append init_cli_cmds string set --retcode true append init_cli_cmds string echo off append init_cli_cmds string set --vt100 off comment set dut name as variable append init_cli_cmds string set dut " + name + string " append init_cli_cmds list strin...
def set_default_init_cli_cmds(self): init_cli_cmds = [] init_cli_cmds.append("set --retcode true") init_cli_cmds.append("echo off") init_cli_cmds.append("set --vt100 off") #set dut name as variable init_cli_cmds.append('set dut "'+self.name+'"') init_cli_cmds.app...
Python
nomic_cornstack_python_v1
string Created on Sun Oct 21 2018 @author: Kimin Lee from __future__ import print_function import torch import numpy as np import torch.nn.functional as F from torch.autograd import Variable set features = list function get_features_hook self input output begin global features set features = list output end function f...
""" Created on Sun Oct 21 2018 @author: Kimin Lee """ from __future__ import print_function import torch import numpy as np import torch.nn.functional as F from torch.autograd import Variable features = [] def get_features_hook(self, input, output): global features features = [output] def get_feature_list(...
Python
zaydzuhri_stack_edu_python
function unhashify obj cache key begin if is instance obj at 1 tuple Exception Iterator begin return call pop cache key at 1 end return call obj at 1 end function
def unhashify(obj: Tuple[Callable[[S], T], S], cache: Dict[KeyType, T], key: KeyType) -> T: if isinstance(obj[1], (Exception, Iterator)): return obj[0](cache.pop(key)[1]) return obj[0](obj[1])
Python
nomic_cornstack_python_v1
import pandas as pd import datetime as dt import v20 import configparser import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pylab comment new_hist.py set config = config parser read config string pyalgo.cfg set access_token = config at string oanda_v20 at string access_token comment v20.con...
import pandas as pd import datetime as dt import v20 import configparser import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pylab #new_hist.py config = configparser.ConfigParser() config.read('pyalgo.cfg') access_token = config['oanda_v20']['access_token'] #v20.context ctx = v20.Conte...
Python
zaydzuhri_stack_edu_python
from week4.matplotlib_scatterPlot.scatterPlot_utility.utility_demo import validate_num , list_created import matplotlib.pyplot as plt import numpy as np comment class to perform graphical representation of data using matplotlib pie chart class CompareWeightsAndHeights begin set choice = 0 function scatter_plots self be...
from week4.matplotlib_scatterPlot.scatterPlot_utility.utility_demo import validate_num, list_created import matplotlib.pyplot as plt import numpy as np # class to perform graphical representation of data using matplotlib pie chart class CompareWeightsAndHeights: choice = 0 def scatter_plots(self): pr...
Python
zaydzuhri_stack_edu_python
function check_statement statement begin comment Split the statement into words set words = split statement comment Check each word for validity for word in words begin if not is alpha word begin return false end end comment Check the sentence structure if length words != 3 begin return false end if words at 1 != strin...
def check_statement(statement): # Split the statement into words words = statement.split() # Check each word for validity for word in words: if not word.isalpha(): return False # Check the sentence structure if len(words) != 3: return False if words...
Python
jtatman_500k