code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function truncate self num_rows begin return call truncate num_rows end function
def truncate(self, num_rows): return self.ll_table.truncate(num_rows)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import sys , string , re string --------------- Instruction Set for MM -------------- 000000 hlt Halt 01rmmm ldr Load register r with contents of address mmm. 02rmmm sto Store the contents of register r at address mmm. 03rnnn ldn Load register r with the number nnn. 04r00s lfm Load register r w...
#!/usr/bin/python import sys, string, re """ --------------- Instruction Set for MM -------------- 000000 hlt Halt 01rmmm ldr Load register r with contents of address mmm. 02rmmm sto Store the contents of register r at address mmm. 03rnnn ldn Load register r with the number nnn. 04r00s lfm Lo...
Python
zaydzuhri_stack_edu_python
function __init__ self *args **kwargs begin call JPEGHandler_swiginit self call new_JPEGHandler *args keyword kwargs end function
def __init__(self, *args, **kwargs): _core_.JPEGHandler_swiginit(self,_core_.new_JPEGHandler(*args, **kwargs))
Python
nomic_cornstack_python_v1
comment coding: utf-8 from collections import Counter import Levenshtein from django.contrib.auth import get_user_model set __all__ = list string get_user_email_domains string replace_user_email_domains string find_similar_email_domains function get_user_email_domains count=256 begin string Renvoyer tous les noms de do...
# coding: utf-8 from collections import Counter import Levenshtein from django.contrib.auth import get_user_model __all__ = ['get_user_email_domains', 'replace_user_email_domains', 'find_similar_email_domains'] def get_user_email_domains(count=256): """ Renvoyer tous les noms de domaine utilisés pour les em...
Python
zaydzuhri_stack_edu_python
function auto_assign_permission sender instance created **kwargs begin if created begin call assign_perm string change_post owner instance call assign_perm string delete_post owner instance end end function
def auto_assign_permission(sender, instance, created, **kwargs): if created: assign_perm('change_post', instance.owner, instance) assign_perm('delete_post', instance.owner, instance)
Python
nomic_cornstack_python_v1
comment some tools for fomatting markdown files # import sys import os import commenttools function py_to_md pyfilename pyfiledir mdfilename mdfiledir begin comment convert a .py file to a corresponding .md file based on the comments in it set pyfilepath = join path pyfiledir pyfilename comment check extensions and exi...
########################################### # some tools for fomatting markdown files # ########################################### import sys import os import commenttools def py_to_md( pyfilename, pyfiledir, mdfilename, mdfiledir ): ### convert a .py file to a corresponding .md file based on the comments in it ...
Python
zaydzuhri_stack_edu_python
function showtopscores self begin set top_scores = call gettopscorerslist CURRENT_GAME_LEVEL set level_string = string if CURRENT_GAME_LEVEL == ExpertLevel begin set level_string = string Expert level end else if CURRENT_GAME_LEVEL == BeginnerLevel begin set level_string = string Beginner level end else begin set leve...
def showtopscores(self): top_scores = LeaderBoard.gettopscorerslist(CURRENT_GAME_LEVEL) level_string = "" if CURRENT_GAME_LEVEL == DifficultyLevel.ExpertLevel: level_string = "Expert level" elif CURRENT_GAME_LEVEL == DifficultyLevel.BeginnerLevel: level_string = "...
Python
nomic_cornstack_python_v1
from typing import List import heapq class Solution begin function __init__ self begin set distance = list end function function smallestDistancePair self nums k begin set k = k set i = 0 set L = length nums while i < L - 1 begin set j = i + 1 while j < L begin set d = nums at i - nums at j if length distance < k begi...
from typing import List import heapq class Solution: def __init__(self): self.distance = [] def smallestDistancePair(self, nums: List[int], k: int) -> int: self.k = k i = 0 L = len(nums) while i < L-1: j = i+1 while j < L: d = nu...
Python
zaydzuhri_stack_edu_python
if valor > 0 begin print string positivo end else begin print string negativo end
if valor > 0: print ('positivo') else: print ('negativo')
Python
zaydzuhri_stack_edu_python
from hypothesis.strategies import characters , integers from hypothesis.strategies import composite , lists from custom.label.comments import label from custom.verify.comments import verify function build_comment_str item begin return item at string inputs end function decorator composite comment XXX: #! type of commen...
from hypothesis.strategies import characters, integers from hypothesis.strategies import composite, lists from custom.label.comments import label from custom.verify.comments import verify def build_comment_str(item): return item["inputs"] # XXX: #! type of comment is not implemented yet @composite def comment_it...
Python
zaydzuhri_stack_edu_python
function __init__ self riemann_solver=none claw_package=none begin set dimensional_split = true set transverse_waves = trans_inc set num_dim = 2 set aux1 = none set aux2 = none set aux3 = none set work = none call __init__ riemann_solver claw_package end function
def __init__(self,riemann_solver=None, claw_package=None): self.dimensional_split = True self.transverse_waves = self.trans_inc self.num_dim = 2 self.aux1 = None self.aux2 = None self.aux3 = None self.work = None super(ClawSolver2D,self)._...
Python
nomic_cornstack_python_v1
class Solution begin function findDuplicates self nums begin set output = list set lookin = set for i in nums begin if i not in lookin begin add lookin i end else begin append output i end end return output end function end class
class Solution: def findDuplicates(self, nums): output=[] lookin=set() for i in nums: if i not in lookin: lookin.add(i) else: output.append(i) return output
Python
zaydzuhri_stack_edu_python
function test_infrastructure_usage_difficulty_can_be_changed self begin set change_url = reverse string admin:infrastructure_infrastructureusagedifficultylevel_change args=list pk set response = post change_url dict string label string Easy assert equal status_code 302 assert equal label string Easy assert equal url st...
def test_infrastructure_usage_difficulty_can_be_changed(self): change_url = reverse('admin:infrastructure_infrastructureusagedifficultylevel_change', args=[self.level.pk]) response = self.client.post(change_url, {'label': 'Easy'}) self.assertEqual(response.status_code, 302) self.assertEq...
Python
nomic_cornstack_python_v1
function load_data fname begin set f = open fname string rb set data = load pickle f encoding=string bytes close f set X = list set Y = list for d in data begin append X d at slice : 784 : append Y d at 784 end return tuple array X array Y end function
def load_data(fname): f = open(fname, 'rb') data = pickle.load(f, encoding='bytes') f.close() X = [] Y = [] for d in data: X.append(d[:784]) Y.append(d[784]) return np.array(X), np.array(Y)
Python
nomic_cornstack_python_v1
import numpy as np from decision_tree_learning import * class EmotionPredictor extends object begin function __init__ self begin set attributes = array list comprehension i for i in range 45 set emotions = list comprehension i + 1 for i in range 6 comment List of trees containing one tree for each emotion set trees = l...
import numpy as np from decision_tree_learning import * class EmotionPredictor(object): def __init__(self): self.attributes = np.array([i for i in range(45)]) self.emotions = [i + 1 for i in range(6)] # List of trees containing one tree for each emotion self.trees = [] def tra...
Python
zaydzuhri_stack_edu_python
string Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger library or convert th...
''' Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. Note: The length of both num1 and num2 is < 5100. Both num1 and num2 contains only digits 0-9. Both num1 and num2 does not contain any leading zero. You must not use any built-in BigInteger librar...
Python
zaydzuhri_stack_edu_python
function SetInput self histogram begin return call itkHistogramToIntensityImageFilterHDIF3_Superclass_SetInput self histogram end function
def SetInput(self, histogram: 'itkHistogramD') -> "void": return _itkHistogramToIntensityImageFilterPython.itkHistogramToIntensityImageFilterHDIF3_Superclass_SetInput(self, histogram)
Python
nomic_cornstack_python_v1
function exception_changer function *args **kwargs begin try begin call function *args keyword kwargs end except Exception as ex begin comment Re-raise exception as ValueError with modified message and same comment traceback as original exception. raise call with_traceback call exc_info at 2 end end function
def exception_changer(function, *args, **kwargs): try: function(*args, **kwargs) except Exception as ex: # Re-raise exception as ValueError with modified message and same # traceback as original exception. raise WeirdException("Modified message:" + ex.message + "!").with_tracebac...
Python
nomic_cornstack_python_v1
function was_modified self begin set recorded = get recorded_mtimes string ensemble set last = st_mtime return recorded != last end function
def was_modified(self) -> bool: recorded = self.recorded_mtimes.get("ensemble") last = self.pred_path().stat().st_mtime return recorded != last
Python
nomic_cornstack_python_v1
import csv import random import os try begin from config import StartingDataDirectory end except any begin from config import StartingDataDirectory end function randomZ z_max begin comment TODO: introduce some sort of smoothing over this, maybe a perlin noise? return random integer 0 z_max end function function generat...
import csv import random import os try: from ..config import StartingDataDirectory except: from config import StartingDataDirectory def randomZ(z_max): #TODO: introduce some sort of smoothing over this, maybe a perlin noise? return random.randint(0, z_max) def generateStartingElevation(name, x_width=2...
Python
zaydzuhri_stack_edu_python
comment import some dependencies import numpy as np import matplotlib.pyplot as plt try begin import seaborn as sns set end except ImportError begin pass end import torch from torch.autograd import Variable import pyro import pyro.infer import pyro.optim import pyro.distributions as dist import numpy as np call manual_...
# import some dependencies import numpy as np import matplotlib.pyplot as plt try: import seaborn as sns sns.set() except ImportError: pass import torch from torch.autograd import Variable import pyro import pyro.infer import pyro.optim import pyro.distributions as dist import numpy as np torch.manual_s...
Python
zaydzuhri_stack_edu_python
function process_docs self docs min_cf=1 min_df=1 max_docs=none begin comment current word index, across all documents set ii = 0 comment current document index set jj = 0 set x = zeros num_pos dtype=string int set j = zeros num_pos dtype=string int set new_docs = list if max_docs is none begin set max_docs = length d...
def process_docs(self, docs, min_cf=1, min_df=1, max_docs=None): ii = 0 # current word index, across all documents jj = 0 # current document index x = np.zeros(self.vocab.num_pos, dtype='int') j = np.zeros(self.vocab.num_pos, dtype='int') new_docs = [] if max_d...
Python
nomic_cornstack_python_v1
function predict self inputs begin set model_inputs = generator expression call preprocess ex for ex in inputs set outputs = predict wrapped model_inputs return generator expression call remap_dict mo FIELD_RENAMES for mo in outputs end function
def predict(self, inputs): model_inputs = (self.preprocess(ex) for ex in inputs) outputs = self.wrapped.predict(model_inputs) return (utils.remap_dict(mo, self.FIELD_RENAMES) for mo in outputs)
Python
nomic_cornstack_python_v1
function scroll_backward_vertically self steps=10 *args **selectors begin string Perform scroll backward (vertically)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. See `Scroll Forward Vertically` for more details. return backward vert steps=steps end function
def scroll_backward_vertically(self, steps=10, *args, **selectors): """ Perform scroll backward (vertically)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. See `Scroll Forward Vertically` for more details. """ retur...
Python
jtatman_500k
function update_config self config begin comment add follower public folder to the CKAN's list of public folders set here = directory name path __file__ set public_dir = join path here string public if get config string extra_public_paths begin set config at string extra_public_paths = config at string extra_public_pat...
def update_config(self, config): # add follower public folder to the CKAN's list of public folders here = os.path.dirname(__file__) public_dir = os.path.join(here, 'public') if config.get('extra_public_paths'): config['extra_public_paths'] += ',' + public_dir else: ...
Python
nomic_cornstack_python_v1
import pickle import numpy as np import pandas as pd set dataset = read csv string train.csv encoding=string latin-1 set x = values set y = values import nltk , re call download string stopwords from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer set cleaned_tweets_list = list for i in range 0...
import pickle import numpy as np import pandas as pd dataset = pd.read_csv("train.csv",encoding='latin-1') x = dataset.iloc[:,2].values y = dataset.iloc[:,1].values import nltk,re nltk.download('stopwords') from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer cleaned_tweets_list = ...
Python
zaydzuhri_stack_edu_python
function get_res token nums begin try begin set res = pop nums end except any begin print format str string Error: Operator ”{0}" without operand(s) found. token exit 0 end if token == string + begin for n in nums begin set res = res + n end set nums at slice : : = list end else if token == string * begin for n in ...
def get_res(token, nums): try: res = nums.pop() except: print(str.format('Error: Operator ”{0}" without operand(s) found.', token)) sys.exit(0) if token == '+': for n in nums: res = res + n nums[:] = [] elif token == '*': for n in nums: ...
Python
zaydzuhri_stack_edu_python
function register_task cls begin if not is instance cls type and is subclass cls Task begin raise call TypeError string @register_task needs to be used with a subclass of Task, not %s % call repr cls end set task_name = call get_task_name set _task_classes at task_name = cls function run celery_task *args **kwargs begi...
def register_task(cls): if not(isinstance(cls, type) and issubclass(cls, Task)): raise TypeError( '@register_task needs to be used with a subclass of Task, not %s' % repr(cls)) task_name = cls.get_task_name() _task_classes[task_name] = cls def run(celery_task, *args, **...
Python
nomic_cornstack_python_v1
function queryxml self dbsalias userinput q_start=string q_end=string begin set dbsapi = call getapi dbsalias set dbsxml = call executeQuery userinput begin=q_start end=q_end type=string query return dbsxml end function
def queryxml(self, dbsalias, userinput, q_start = "", q_end = ""): dbsapi = self.getapi(dbsalias) dbsxml = dbsapi.executeQuery(userinput, begin = q_start, end = q_end, type="query") return dbsxml
Python
nomic_cornstack_python_v1
comment def print_models(unprinted_designs, completed_models): comment """ comment 模拟打印每个设计,直到没有未打印的设计为止 comment 打印每个设计后,都将其移到completed_models中 comment """ comment while unprinted_designs: comment current_desing = unprinted_designs.pop() comment 模拟根据设计制作3D打印模型的过程 comment print('Printing model: ' + current_desing) comme...
#def print_models(unprinted_designs, completed_models): #""" #模拟打印每个设计,直到没有未打印的设计为止 #打印每个设计后,都将其移到completed_models中 #""" #while unprinted_designs: #current_desing = unprinted_designs.pop() ##模拟根据设计制作3D打印模型的过程 #print('Printing model: ' + current_desing) #completed_models.append(current_desing) #def show...
Python
zaydzuhri_stack_edu_python
import math class Solution extends object begin function countPrimeSetBits self L R begin string 给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。 (注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。) --- 输入: L = 6, R = 10 输出: 4 解释: 6 -> 110 (2 个计算置位,2 是质数) 7 -> 111 (3 个计算置位,3 是质数) 9 -> 1001 (2 个计算置位,2 是质数) 10-> 1...
import math class Solution(object): def countPrimeSetBits(self, L, R): """ 给定两个整数 L 和 R ,找到闭区间 [L, R] 范围内,计算置位位数为质数的整数个数。 (注意,计算置位代表二进制表示中1的个数。例如 21 的二进制表示 10101 有 3 个计算置位。还有,1 不是质数。) --- 输入: L = 6, R = 10 输出: 4 解释: 6 -> 110 (2 个计算置位,2 是质数) 7 -> 111 (3 个计算置位,3 是质数) 9 -> 1001 (2 个计算置位,2 是质数) 10-> ...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python import cv2 as cv import numpy as np import matplotlib.pyplot as plt import imutils set vid = call VideoCapture string front.mp4 comment Color Ranges set light_orange = tuple 5 120 120 set dark_orange = tuple 40 255 255 set light_white = tuple 30 255 255 set dark_white = tuple 40 255 255 if...
#! /usr/bin/env python import cv2 as cv import numpy as np import matplotlib.pyplot as plt import imutils vid = cv.VideoCapture('front.mp4') #Color Ranges light_orange = (5, 120, 120) dark_orange = (40, 255, 255) light_white = (30, 255, 255) dark_white = (40, 255, 255) if(vid.isOpened() == False): print("Error ...
Python
zaydzuhri_stack_edu_python
function empty self begin warn string Emptying asset of children. extra=dictionary asset=id comment "only" here is an optimization to speed up signal delivery delete _from_doc_delete=true return self end function
def empty(self): log.warn("Emptying asset of children.", extra=dict(asset=self.id)) # "only" here is an optimization to speed up signal delivery self.children.only('id').delete(_from_doc_delete=True) return self
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np from lightgbm import LGBMClassifier from sklearn.preprocessing import MinMaxScaler if __name__ == string __main__ begin set X_train = read csv string ../203_biol/data/train.csv set X_test = read csv string ../203_biol/data/test.csv set y_train = X_train at string Activity drop X_t...
import pandas as pd import numpy as np from lightgbm import LGBMClassifier from sklearn.preprocessing import MinMaxScaler if __name__ == "__main__": X_train = pd.read_csv("../203_biol/data/train.csv") X_test = pd.read_csv("../203_biol/data/test.csv") y_train = X_train["Activity"] X_train...
Python
zaydzuhri_stack_edu_python
function invcdf p k theta begin with call extradps 5 begin set p = call _validate_p p if p == 0 begin return ninf end if p == 1 begin return inf end set tuple k theta = call _validate_k_theta k theta set tuple x0 x1 = call _find_bracket lambda t -> call cdf t k theta p - inf inf set root = call findroot lambda t -> cal...
def invcdf(p, k, theta): with mp.extradps(5): p = _validate_p(p) if p == 0: return mp.ninf if p == 1: return mp.inf k, theta = _validate_k_theta(k, theta) x0, x1 = _find_bracket(lambda t: cdf(t, k, theta), p, -mp.inf, mp.inf) root = mp.findroot...
Python
nomic_cornstack_python_v1
function path self begin return get pulumi self string path end function
def path(self) -> pulumi.Input[str]: return pulumi.get(self, "path")
Python
nomic_cornstack_python_v1
function create_comission_plan request begin set serializer = call ComissionPlanSerializer data=data if call is_valid begin set data = save set response = dict string id id return call Response response status=HTTP_201_CREATED end return call Response errors status=HTTP_400_BAD_REQUEST end function
def create_comission_plan(request): serializer = ComissionPlanSerializer(data=request.data) if serializer.is_valid(): data = serializer.save() response = { "id": data.id } return Response(response, status=status.HTTP_201_CREATED) return Response(serializer.errors,...
Python
nomic_cornstack_python_v1
function eps_nn X eps=1.0 begin from utils.fast_distance import euclidean_distance if size np X == shape at 0 begin set X = reshape np X tuple size np X 1 end try begin set eps = decimal eps end except any begin string eps cannot be cast to a float end if call isnan eps begin raise call ValueError string eps is nan end...
def eps_nn(X, eps=1.): from ..utils.fast_distance import euclidean_distance if np.size(X) == X.shape[0]: X = np.reshape(X, (np.size(X), 1)) try: eps = float(eps) except: "eps cannot be cast to a float" if np.isnan(eps): raise ValueError('eps is nan') if np.isinf(e...
Python
nomic_cornstack_python_v1
function __generate_number_boleto_fake self begin set numbers = string 0123456789 return join string generator expression random choice numbers for character in range 48 end function
def __generate_number_boleto_fake(self): numbers = "0123456789" return "".join(random.choice(numbers) for character in range(48))
Python
nomic_cornstack_python_v1
function append self val begin concat call Linked val end function
def append(self, val: T) -> None: self.concat(Linked(val))
Python
nomic_cornstack_python_v1
import warnings filter warnings string ignore import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from pydataset import data import acquire as aq import prepare as pr from sklearn.model_selection import train_test_split from sklearn.impute import SimpleImputer import scipy.stats...
import warnings warnings.filterwarnings("ignore") import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from pydataset import data import acquire as aq import prepare as pr from sklearn.model_selection import train_test_split from sklearn.impute import SimpleImputer import scipy....
Python
zaydzuhri_stack_edu_python
function compare_dicts first second begin set diff : Diff = list for tuple key _ in sorted items first begin if key not in second begin append diff tuple key first at key none end end for tuple key _ in sorted items second begin if key not in first begin append diff tuple key none second at key end end set all_keys : ...
def compare_dicts(first: Dict[str, str], second: Dict[str, str]) -> Diff: diff: Diff = [] for key, _ in sorted(first.items()): if key not in second: diff.append((key, first[key], None)) for key, _ in sorted(second.items()): if key not in first: diff.append((key, None...
Python
nomic_cornstack_python_v1
function save_model outcode_regex boilerplate_text begin call save_to_s3 string outcode_regex.txt outcode_regex call save_to_s3 string boilerplate_text.txt boilerplate_text end function
def save_model(outcode_regex, boilerplate_text): save_to_s3('outcode_regex.txt', outcode_regex) save_to_s3('boilerplate_text.txt', boilerplate_text)
Python
nomic_cornstack_python_v1
function test_get_context_dict self begin set context_dict = call get_context_dict set test_dict = dict string maven:formula string sprinter.formula.unpack ; string maven:specific_version string 2.10 ; string ant:formula string sprinter.formula.unpack ; string mysql:formula string sprinter.formula.package ; string sub:...
def test_get_context_dict(self): context_dict = self.old_manifest.get_context_dict() test_dict = { "maven:formula": "sprinter.formula.unpack", "maven:specific_version": "2.10", "ant:formula": "sprinter.formula.unpack", "mysql:formula": "sprinter.formula.pa...
Python
nomic_cornstack_python_v1
import calendar as c from datetime import * print call month 2021 2 set d = today print string Date format : d print string Year : year print string Month : month print string Hour : hour print string Minute : minute print string Second : second
import calendar as c from datetime import * print(c.month(2021,2)) d=datetime.today() print("Date format :",d) print("Year :",d.year) print("Month :",d.month) print("Hour :",d.hour) print("Minute :",d.minute) print("Second :",d.second)
Python
zaydzuhri_stack_edu_python
function repository_integration hacs begin set repository_obj = call HacsIntegrationRepository hacs string test/test yield call dummy_repository_base hacs repository_obj end function
def repository_integration(hacs): repository_obj = HacsIntegrationRepository(hacs, "test/test") yield dummy_repository_base(hacs, repository_obj)
Python
nomic_cornstack_python_v1
from PIL import Image import random import numpy as np import cv2 class ad extends object begin function __init__ self gender item pattern color link begin set gender = gender set item = item set pattern = pattern set color = color set link = link end function function get_image self begin set image = call imread strin...
from PIL import Image import random import numpy as np import cv2 class ad(object): def __init__(self, gender, item, pattern, color, link): self.gender = gender self.item = item self.pattern = pattern self.color = color self.link = link def get_image(self): image = cv2.imread('./ad_retrieval/' + self.li...
Python
zaydzuhri_stack_edu_python
function test_compute_perfect_model_da1d_not_nan_crpss_quadratic PM_da_initialized_1d PM_da_control_1d begin set actual = any assert not actual end function
def test_compute_perfect_model_da1d_not_nan_crpss_quadratic( PM_da_initialized_1d, PM_da_control_1d ): actual = ( compute_perfect_model( PM_da_initialized_1d.isel(lead=[0]), PM_da_control_1d, comparison='m2c', metric='crpss', gaussian=False, ...
Python
nomic_cornstack_python_v1
from multilayer_feed_forward_network import MultilayerFeedForwardNetwork as Network set layers = list 2 3 2 comment Input layer, 3 neurons comment First hidden layer, 5 neurons comment Second hidden layer, 4 neurons comment 7, # Third hidden layer, 7 neurons comment 2 # Output layer, 2 neurons set network = call Networ...
from multilayer_feed_forward_network import MultilayerFeedForwardNetwork as Network layers = [ 2, # Input layer, 3 neurons 3, # First hidden layer, 5 neurons 2, # Second hidden layer, 4 neurons # 7, # Third hidden layer, 7 neurons # 2 # Output layer, 2 neurons ] network = Network(layers) input_1 ...
Python
zaydzuhri_stack_edu_python
comment $NON-NLS-1$ function getAtomEntry self editLink begin set atomRequest = call _createGetEntryRequest editLink call _sendAtomRequest atomRequest set rval = call getEntry del atomRequest return rval end function
def getAtomEntry(self, editLink): #$NON-NLS-1$ atomRequest = self._createGetEntryRequest(editLink) self._sendAtomRequest(atomRequest) rval = atomRequest.getEntry() del atomRequest return rval
Python
nomic_cornstack_python_v1
function get_damage self amount begin set health = health - amount end function
def get_damage(self, amount: float) -> None: self.health = self.health - amount
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 string Unittest for max_integer([..]) import unittest set max_integer = max_integer class TestMaxInteger extends TestCase begin string max_integer unittest function test_max_integer self begin string test_max_integer function assert equal call max_integer list 1 2 3 4 4 assert equal call max_i...
#!/usr/bin/python3 """Unittest for max_integer([..]) """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): """ max_integer unittest""" def test_max_integer(self): """ test_max_integer function """ self.assertEqual(max_integer([1, 2, ...
Python
zaydzuhri_stack_edu_python
async function write_error name url error_type begin async_with open string error_locations.csv string a as f begin await write f string { name } , { url } , { error_type } end end function
async def write_error(name, url, error_type): async with aiofiles.open(f"error_locations.csv", "a") as f: await f.write(f"{name},{url},{error_type}\n")
Python
nomic_cornstack_python_v1
function SetNormalFont self font begin set _normal_font = font end function
def SetNormalFont(self, font): self._normal_font = font
Python
nomic_cornstack_python_v1
comment comment: comment f2 sub.py
#comment: # f2 sub.py
Python
zaydzuhri_stack_edu_python
function by_ids self task_ids begin return all end function
def by_ids(self, task_ids): return self.restrict().filter(Task.task_id.in_(task_ids)).all()
Python
nomic_cornstack_python_v1
function show_popup self data begin set store = call get_store set rows = 1 + get store string Nbtimecompound at string value comment the first µEOF call add_widget call CEToolBoxLabel text=call add_color string µEOF : string FFFFFF set value = format string {:.2E} get store string MicroEOF at string value set value = ...
def show_popup(self, data): store = get_store() self.ids.inlayout.rows = 1 + store.get('Nbtimecompound')["value"] #the first µEOF self.ids.inlayout.add_widget(CEToolBoxLabel(text=add_color("µEOF :","FFFFFF"))) value = "{:.2E}".format(store.get('MicroEOF')["value"]) ...
Python
nomic_cornstack_python_v1
function from_serializable cls contents begin return call cls keyword contents end function
def from_serializable(cls, contents): return cls(**contents)
Python
nomic_cornstack_python_v1
import pickle , base64 from django_redis import get_redis_connection function merge_cart_cookie_to_redis request user response begin string 登录时购物车的cookie合并到redis comment 获取cookie中的购物车数据 set cookie_cart_str = get COOKIES string cart if not cookie_cart_str or cookie_cart_str == string begin return response end set cooki...
import pickle, base64 from django_redis import get_redis_connection def merge_cart_cookie_to_redis(request, user, response): """登录时购物车的cookie合并到redis""" # 获取cookie中的购物车数据 cookie_cart_str = request.COOKIES.get('cart') if not cookie_cart_str or cookie_cart_str == '': return response cookie_...
Python
zaydzuhri_stack_edu_python
comment *=======================================================* comment -*- coding:utf-8 -*- comment * time : 2020-03-18 15:34 comment * author : lichengyi comment *=======================================================* comment concordance data string 1、首先把一个日期文件内的所有压缩文件全部解压缩存放格式为shared1 2、扫描所有解压缩的文件,发现一个交易所的名称就产生一...
# *=======================================================* # -*- coding:utf-8 -*- # * time : 2020-03-18 15:34 # * author : lichengyi # *=======================================================* # concordance data ''' 1、首先把一个日期文件内的所有压缩文件全部解压缩存放格式为shared1 2、扫描所有解压缩的文件,发现一个交易所的名称就产生一个对应的文件夹, 同时把此时的文件存放进去对应的文件夹,按照在cp进去的...
Python
zaydzuhri_stack_edu_python
function check_item self begin set itemNumber = integer item_number_text try begin comment get item info set tuple name price amount = call get_item_details itemNumber end except InvalidItemNumberException begin return end try begin comment try to buy item set tuple change item = call pay_for_item itemNumber for c in c...
def check_item(self) -> None: itemNumber = int(self.item_number_text) try: #get item info name, price, amount = self.automat.get_item_details(itemNumber) except at.InvalidItemNumberException: return try: #try to buy item change,...
Python
nomic_cornstack_python_v1
import math import heapq import sys import string import random import time import pdb comment CS 4780/5780 k-Nearest Neighbor implementation example code comment by Joshua L. Moore, August/September 2012 comment To run the experiment over all users for a particular parameter setting, run comment python knn_cf.py exp n...
import math import heapq import sys import string import random import time import pdb; # CS 4780/5780 k-Nearest Neighbor implementation example code # by Joshua L. Moore, August/September 2012 # # To run the experiment over all users for a particular parameter setting, run # python knn_cf.py exp nnk (list of integer ...
Python
zaydzuhri_stack_edu_python
function get_authserver self domainid serverid begin string Get an Authentication server return call api_call ENDPOINTS at string authservers at string get dictionary domainid=domainid serverid=serverid end function
def get_authserver(self, domainid, serverid): """Get an Authentication server""" return self.api_call( ENDPOINTS['authservers']['get'], dict(domainid=domainid, serverid=serverid))
Python
jtatman_500k
function test_last_chapter self begin set url = string http://www.mangapanda.com/naruto/700 set expected = dict string next_chapter_url none call _test_chapter self site url expected end function
def test_last_chapter(self): url = 'http://www.mangapanda.com/naruto/700' expected = { 'next_chapter_url': None, } _test_chapter(self, site, url, expected)
Python
nomic_cornstack_python_v1
function do_spline x_values y_values begin comment ATTENTION: current implementation of spline does not work for comment the samples CVchapita05Videm.txt and CVchapita08V.txt comment The underlying Fortran rutine fails with no further information. comment spline parameters comment smoothness parameter set s = 3.0 comme...
def do_spline(x_values, y_values): # ATTENTION: current implementation of spline does not work for # the samples CVchapita05Videm.txt and CVchapita08V.txt # The underlying Fortran rutine fails with no further information. # spline parameters s=3.0 # smoothness parameter k=3 # spline order ...
Python
nomic_cornstack_python_v1
from matplotlib import pyplot as plt import numpy as np import cv2 as cv from skimage import exposure function image_histogram_equalization image number_bins=256 begin comment get image histogram set tuple image_histogram bins = call histogram flatten image number_bins density=true comment cumulative distribution funct...
from matplotlib import pyplot as plt import numpy as np import cv2 as cv from skimage import exposure def image_histogram_equalization(image, number_bins=256): # get image histogram image_histogram, bins = np.histogram(image.flatten(), number_bins, density=True) cdf = image_histogram.cumsum() # cumulative ...
Python
zaydzuhri_stack_edu_python
import sys with open argv at 1 as f begin next for tuple case_number case in enumerate f 1 begin set tuple farm_cost farm_boost goal = map float split strip case set time = 0 set farms = 0 while true begin set next_farm = farm_cost / 2 + farm_boost * farms set goal_time = goal / 2 + farm_boost * farms set goal_time_wit...
import sys with open(sys.argv[1]) as f: f.next() for case_number, case in enumerate(f, 1): farm_cost, farm_boost, goal = map(float, case.strip().split()) time = 0 farms = 0 while(True): next_farm = farm_cost / (2 + farm_boost * farms) goal_time = goal / (2 + farm_boost * farms) goal_time_with_farm =...
Python
zaydzuhri_stack_edu_python
function main d_sr f_max_src begin comment integer that sorts of the saved folders in the results dir. set case = 1 comment sound speed, float (m.s-1). set c = 340.0 comment air density, float (kg.m-3). set rho = 1.2 comment T_delay + 2T_sim = simulation duration, float (s). set T = 1.0 / 50 + 2 * 1.0 / 50.0 comment ~ ...
def main(d_sr, f_max_src): case = 1 # integer that sorts of the saved folders in the results dir. c = 340. # sound speed, float (m.s-1). rho = 1.2 # air density, float (kg.m-3). T = 1./50 + 2 * 1./50. # T_delay + 2T_sim = simulation duration, float (s). # ~ T = 2.0 * 10 ** -2 s = 20 ms, ...
Python
nomic_cornstack_python_v1
function test_webp_animated index begin comment gif2webp frames.u1.gif -kmin 1 -kmax 1 -o frames.webp set decode = webp_decode comment TODO: test animation with partial frames set data = call readfile string frames.webp assert call webp_check data set decoded = decode data index=index set expected = call image_data str...
def test_webp_animated(index): # gif2webp frames.u1.gif -kmin 1 -kmax 1 -o frames.webp decode = imagecodecs.webp_decode # TODO: test animation with partial frames data = readfile('frames.webp') assert imagecodecs.webp_check(data) decoded = decode(data, index=index) expected = image_data('gra...
Python
nomic_cornstack_python_v1
function sequences self begin string Sequence declaration lines. set lines = call Lines add lines 0 string @cython.final add lines 0 string cdef class Sequences(object): for subseqs in sequences begin add lines 1 string cdef public %s %s % tuple call classname subseqs name end if get attribute sequences string states n...
def sequences(self): """Sequence declaration lines.""" lines = Lines() lines.add(0, '@cython.final') lines.add(0, 'cdef class Sequences(object):') for subseqs in self.model.sequences: lines.add(1, 'cdef public %s %s' % (objecttools.classname(s...
Python
jtatman_500k
from math import fabs set a = decimal input string Digite o primeiro comprimento: set b = decimal input string Digite o segundo comprimento: set c = decimal input string Digite o terceiro comprimento: set cores = dict string sem string  ; string azul string  comment Outra forma de calcular: comment a < b + c ...
from math import fabs a = float(input('Digite o primeiro comprimento: ')) b = float(input('Digite o segundo comprimento: ')) c = float(input('Digite o terceiro comprimento: ')) cores = {'sem':'\033[m', 'azul':'\033[36;1m'} # Outra forma de calcular: # a < b + c and b < a + c and c < a + b if (fabs(b - c) < a <...
Python
zaydzuhri_stack_edu_python
function get_partial_sampler mode class_weights begin if mode is not none begin set sampler = partial frequency_weighted_sampler class_weights=class_weights mode=lower mode end else begin set sampler = none end return sampler end function
def get_partial_sampler(mode, class_weights): if mode is not None: sampler = partial( data.utils.frequency_weighted_sampler, class_weights=class_weights, mode=mode.lower(), ) else: sampler = None return sampler
Python
nomic_cornstack_python_v1
function SarsaLambda env gamma lam alpha X num_episode begin comment openai gym environment comment discount factor comment decay rate comment step size function epsilon_greedy_policy s done w epsilon=0.05 begin set nA = n set Q = list comprehension dot w call X s done a for a in range nA if call rand < epsilon begin r...
def SarsaLambda( env, # openai gym environment gamma:float, # discount factor lam:float, # decay rate alpha:float, # step size X:StateActionFeatureVectorWithTile, num_episode:int, ) -> np.array: def epsilon_greedy_policy(s, done, w, epsilon=0.05): nA = env.action_space.n Q ...
Python
nomic_cornstack_python_v1
import itertools import socket import json import time from payload import payload function chunks iterable size begin set it = iterate iterable while true begin set chunk = tuple iterator slice it size if not chunk begin break end yield chunk end end function class Client begin function __init__ self server_host serve...
import itertools import socket import json import time from payload import payload def chunks(iterable, size): it = iter(iterable) while True: chunk = tuple(itertools.islice(it, size)) if not chunk: break yield chunk class Client: def __init__(self, server_host: str, ...
Python
zaydzuhri_stack_edu_python
function test_atomic_byte_enumeration_2_nistxml_sv_iv_atomic_byte_enumeration_3_5 mode save_output output_format begin call assert_bindings schema=string nistData/atomic/byte/Schema+Instance/NISTSchema-SV-IV-atomic-byte-enumeration-3.xsd instance=string nistData/atomic/byte/Schema+Instance/NISTXML-SV-IV-atomic-byte-enu...
def test_atomic_byte_enumeration_2_nistxml_sv_iv_atomic_byte_enumeration_3_5(mode, save_output, output_format): assert_bindings( schema="nistData/atomic/byte/Schema+Instance/NISTSchema-SV-IV-atomic-byte-enumeration-3.xsd", instance="nistData/atomic/byte/Schema+Instance/NISTXML-SV-IV-atomic-byte-enum...
Python
nomic_cornstack_python_v1
from sklearn.naive_bayes import MultinomialNB import numpy as np comment [é gordinho, tem perna curta, faz auaua] set porco1 = list 1 1 0 set porco2 = list 1 1 0 set porco3 = list 1 1 0 set cachorro4 = list 1 1 1 set cachorro5 = list 0 1 1 set cachorro6 = list 0 1 1 set dados = list porco1 porco2 porco3 cachorro4 cacho...
from sklearn.naive_bayes import MultinomialNB import numpy as np # [é gordinho, tem perna curta, faz auaua] porco1 = [1, 1, 0] porco2 = [1, 1, 0] porco3 = [1, 1, 0] cachorro4 = [1, 1, 1] cachorro5 = [0, 1, 1] cachorro6 = [0, 1, 1] dados = [porco1, porco2, porco3, cachorro4, cachorro5, cachorro6] # 1 é porco e -1 é c...
Python
zaydzuhri_stack_edu_python
function test_newlinesBeforeLineBreaking self begin comment Because MAX_COMMAND_LENGTH includes framing characters, this long comment line is slightly longer than half the permissible message size. set longline = string o * MAX_COMMAND_LENGTH // 2 call msg string foo longline + string + longline assert equal lines lis...
def test_newlinesBeforeLineBreaking(self): # Because MAX_COMMAND_LENGTH includes framing characters, this long # line is slightly longer than half the permissible message size. longline = "o" * (irc.MAX_COMMAND_LENGTH // 2) self.client.msg("foo", longline + "\n" + longline) self...
Python
nomic_cornstack_python_v1
function name self begin return call Sigma2qg2LEDqg_name self end function
def name(self): return _pythia8.Sigma2qg2LEDqg_name(self)
Python
nomic_cornstack_python_v1
function test_derivatives prior_type scale begin if prior_type in list string uniform string parameterScaleUniform begin set prior_parameters = list - 1 1 end else begin set prior_parameters = list 1 1 end set prior_dict = call get_parameter_prior_dict 0 prior_type prior_parameters scale comment use this x0, since it i...
def test_derivatives(prior_type, scale): if prior_type in ['uniform', 'parameterScaleUniform']: prior_parameters = [-1, 1] else: prior_parameters = [1, 1] prior_dict = get_parameter_prior_dict( 0, prior_type, prior_parameters, scale) # use this x0, since it is a moderate value...
Python
nomic_cornstack_python_v1
function save self *args **kwargs begin if not data begin call set_link_data end save *args keyword kwargs end function
def save(self, *args, **kwargs): if not self.data: self.set_link_data() super(Link, self).save(*args, **kwargs)
Python
nomic_cornstack_python_v1
function process_request self request operation_type **kwargs begin try begin set tuple runner_view __ = call _get_producer operation_type end except ValueError begin return call redirect string home end return call runner_view request operation_type=operation_type keyword kwargs end function
def process_request( self, request: http.HttpRequest, operation_type: int, **kwargs ) -> http.HttpResponse: try: runner_view, __ = self._get_producer(operation_type) except ValueError: return redirect('home') return run...
Python
nomic_cornstack_python_v1
function port self begin return port end function
def port(self) -> 'Returns the Port Number of server(int)': return self._parameters.port
Python
nomic_cornstack_python_v1
function EnableUnresBandwidth self begin if force_auto_sync begin get self string EnableUnresBandwidth end return _EnableUnresBandwidth end function
def EnableUnresBandwidth(self): if self.force_auto_sync: self.get('EnableUnresBandwidth') return self._EnableUnresBandwidth
Python
nomic_cornstack_python_v1
comment 0과 1은 더하는게 더 크다 function find_max_plus_or_multiply array begin set result = 0 for i in array begin if i <= 1 or result <= 1 begin set result = result + i end else begin set result = result * i end end return result end function set result = call find_max_plus_or_multiply input print result
#0과 1은 더하는게 더 크다 def find_max_plus_or_multiply(array): result = 0 for i in array: if (i <= 1) or result <= 1: result = result + i else: result = result * i return result result = find_max_plus_or_multiply(input) print(result)
Python
zaydzuhri_stack_edu_python
import math import os import datetime import pickle function load_solution path begin if not exists path path begin return false end with open path string rb as f begin return load pickle f end end function function export_solution path obj name=none begin if not exists path path begin return false end if name is none ...
import math import os import datetime import pickle def load_solution(path): if not os.path.exists(path): return False with open(path, 'rb') as f: return pickle.load(f) def export_solution(path, obj, name=None): if not os.path.exists(path): return False if name is None: ...
Python
zaydzuhri_stack_edu_python
function bagOfWords text words begin set sentenceWords = call clean text set bag = list 0 * length words for s in sentenceWords begin for tuple i w in enumerate words begin if w == s begin set bag at i = 1 end end end return array bag end function
def bagOfWords(text: str, words: List[str]): sentenceWords = clean(text) bag = [0]*len(words) for s in sentenceWords: for i,w in enumerate(words): if w == s: bag[i] = 1 return(numpy.array(bag))
Python
nomic_cornstack_python_v1
import _thread from slidingPuzzle_values import slidingPuzzle_value class Algorithms begin set solved = false set maxNodeExplored = 0 set maxNodeExpanded = 0 set answerDepth = 0 function find self board x begin for i in range 0 3 begin for j in range 0 3 begin if board at i at j == x begin return tuple i j end end end ...
import _thread from slidingPuzzle_values import slidingPuzzle_value class Algorithms: solved = False maxNodeExplored = 0 maxNodeExpanded = 0 answerDepth = 0 def find(self, board, x): for i in range(0, 3): for j in range(0, 3): if (board[i][j] == x): ...
Python
zaydzuhri_stack_edu_python
function mod_agreement_index self j=1 begin set a = absolute predicted - true ^ j set b = absolute predicted - mean np true set c = absolute true - mean np true set e = b + c ^ j return decimal 1 - sum a / sum e end function
def mod_agreement_index(self, j=1) -> float: a = (np.abs(self.predicted - self.true)) ** j b = np.abs(self.predicted - np.mean(self.true)) c = np.abs(self.true - np.mean(self.true)) e = (b + c) ** j return float(1 - (np.sum(a) / np.sum(e)))
Python
nomic_cornstack_python_v1
function get_registered_outcomes self begin return tuple _outcomes end function
def get_registered_outcomes(self): return tuple(self._outcomes)
Python
nomic_cornstack_python_v1
import calendar as cld comment print(cld.month(2021,3)) comment print(cld.month(1998,8)) print call calendar 2021
import calendar as cld #print(cld.month(2021,3)) #print(cld.month(1998,8)) print(cld.calendar(2021))
Python
zaydzuhri_stack_edu_python
function get_cameras_and_zones config begin set cameras_zones = set for camera in keys get config string cameras dict begin add cameras_zones camera for zone in keys get config at string cameras at camera string zones dict begin add cameras_zones zone end end return cameras_zones end function
def get_cameras_and_zones(config: dict[str, Any]) -> set[str]: cameras_zones = set() for camera in config.get("cameras", {}).keys(): cameras_zones.add(camera) for zone in config["cameras"][camera].get("zones", {}).keys(): cameras_zones.add(zone) return cameras_zones
Python
nomic_cornstack_python_v1
for i in range primeiro_termo decimo + razao razao begin print i end=string end
for i in range(primeiro_termo, decimo + razao, razao): print(i, end=" ")
Python
zaydzuhri_stack_edu_python
function up_array arr begin if length arr != 0 begin for tuple i char in enumerate arr begin if arr at i >= 10 begin return none end else begin set arr at i = string arr at i end end end try begin set num = list string integer join string arr + 1 for tuple i char in enumerate num begin set num at i = integer num at i ...
def up_array(arr): if len(arr) != 0: for i, char in enumerate(arr): if arr[i] >= 10: return None else: arr[i] = str(arr[i]) try: num = list(str(int("".join(arr)) + 1)) for i, char in enumerate(num): num[i] = int(num[i]) return num except ValueError: return None return None
Python
zaydzuhri_stack_edu_python
function report LOGDIR epoch e_dict saver sess fh_log begin comment print loss print string Epoch: %i; Loss: %f; KLd: %f; CE %f % tuple epoch e_dict at string loss at - 1 e_dict at string KLd at - 1 e_dict at string CE at - 1 write fh_log string %i %0.5e %0.5e %0.5e % tuple epoch e_dict at string loss at - 1 e_dict at ...
def report(LOGDIR, epoch, e_dict, saver, sess, fh_log): # print loss print ("Epoch: %i; Loss: %f; KLd: %f; CE %f" % (epoch, e_dict["loss"][-1], e_dict["KLd"][-1], e_dict["CE"][-1])) fh_log.write("%i\t%0.5e\t%0.5e\t%0.5e\n" % (epoch, e_dict["loss"][-1], e_dict["KLd"][-1], e_dict["CE"][-1]))
Python
nomic_cornstack_python_v1
function run_pandoc text=string args=none pandoc_path=none begin if args is none begin set args = list end if pandoc_path is none begin comment initialize the global PANDOC_PATH if PANDOC_PATH is none begin set temp = which string pandoc if temp is none begin raise call OSError string Path to pandoc executable does n...
def run_pandoc(text='', args=None, pandoc_path=None): if args is None: args = [] if pandoc_path is None: # initialize the global PANDOC_PATH if PANDOC_PATH is None: temp = which('pandoc') if temp is None: raise OSError("Path to pandoc executable do...
Python
nomic_cornstack_python_v1
comment Time Complexity : O(M * N) where M = # of rows, N = # of columns comment Space Complexity : O(M * N) where M = # of rows, N = # of columns comment Did this code successfully run on Leetcode : No comment Any problem you faced while coding this : I was the getting 1 more than the actual answer for the given test ...
# Time Complexity : O(M * N) where M = # of rows, N = # of columns # Space Complexity : O(M * N) where M = # of rows, N = # of columns # Did this code successfully run on Leetcode : No # Any problem you faced while coding this : I was the getting 1 more than the actual answer for the given test case class Solution: ...
Python
zaydzuhri_stack_edu_python
comment These are Monitors print string ___________________ |*\_/*|___________ | _____________ | ||_/-\_|_________ | print string | | | | | | | | | | 0 0 | | | | 0 0 | | print string | | - | | | | - | | | | \___/ | | | | \___/ | | print string | |___ ___| | | |______________| | |______ |\_/| ______| |__________________...
# These are Monitors print(" ___________________\t\t\t\t\t|*\_/*|___________\n| _____________ |\t\t\t\t ||_/-\_|_________ |") print("| |\t\t\t | |\t\t\t\t | |\t\t\t\t| |\n| |\t0\t0\t | |\t\t\t\t | |\t 0 0\t| |") print("| |\t - \t | |\t\t\t\t | |\t - \t| |\n| |\t\___/\t | |\t\t\t\t | |\t...
Python
zaydzuhri_stack_edu_python
function startup self override_args=none begin set _app_name = argv at 0 if override_args begin set my_args = list _app_name set my_args = my_args + override_args end else begin set my_args = argv at slice : : end if length my_args != 2 begin print format string Usage: {0} sitl run with built-in SITL simulator {0} r...
def startup(self, override_args=None): self._app_name = sys.argv[0] if override_args: my_args = [self._app_name] my_args = my_args + override_args else: my_args = sys.argv[:] if len(my_args) != 2: print("""Usage: {0} sitl run with b...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import os if is file path string usercreds.txt begin with open string usercreds.txt as f begin for line in f begin if string username in line begin set username = split line string = at 1 end else begin set password = split line string = at 1 end end print password end end else begin with o...
#!/usr/bin/env python import os if os.path.isfile('usercreds.txt'): with open("usercreds.txt") as f: for line in f: if 'username' in line: username=line.split('=')[1] else: password=line.split('=')[1] print(password) else: with open("user...
Python
zaydzuhri_stack_edu_python
function choose_torch_device gpus begin if call is_available and length gpus > 0 begin assert call device_count >= length gpus set device = device string cuda:0 print string Using device: { call get_device_name device } unit { gpus at 0 } . end else begin print string Using CPU device. set device = device string cpu en...
def choose_torch_device(gpus: list): if torch.cuda.is_available() and len(gpus) > 0: assert torch.cuda.device_count() >= len(gpus) device = torch.device("cuda:0") print(f"Using device: {torch.cuda.get_device_name(device)} unit {gpus[0]}.") else: print(f"Using CPU device.") ...
Python
nomic_cornstack_python_v1