code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
for i in range n begin set tuple a b = map int split input append arr list b a end sort arr set now = 0 for a in arr begin if now + a at 1 > a at 0 begin print string No exit end set now = now + a at 1 end print string Yes
for i in range(n): a,b = map(int,input().split()) arr.append([b,a]) arr.sort() now = 0 for a in arr: if now + a[1] > a[0]: print("No") exit() now += a[1] print("Yes")
Python
zaydzuhri_stack_edu_python
import unittest from plantpi_waterer import read_amount_string class TestReadAmountString extends TestCase begin function test_empty self begin with assert raises ValueError begin call read_amount_string string end end function function test_invalid_type self begin with assert raises TypeError begin call read_amount_st...
import unittest from plantpi_waterer import read_amount_string class TestReadAmountString(unittest.TestCase): def test_empty(self): with self.assertRaises(ValueError): read_amount_string('') def test_invalid_type(self): with self.assertRaises(TypeError): read_amount_s...
Python
zaydzuhri_stack_edu_python
function calculate_fizzbuzz fizz_num buzz_num start end interval begin string Ensure that the end number gets included even if negative. set end_num_fix = if expression interval < 0 then - 1 else 1 string Print numbers and replace with fizz and buzz where applicable for num in range start end + end_num_fix interval beg...
def calculate_fizzbuzz(fizz_num, buzz_num, start, end, interval): """Ensure that the end number gets included even if negative.""" end_num_fix = -1 if interval < 0 else 1 """ Print numbers and replace with fizz and buzz where applicable """ for num in range(start, end + end_num_fix, interval): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 string Module of read_file function. function read_file filename=string begin string Function that reads a text file (UTF8) and prints it to stdout: with open filename encoding=string utf-8 as myfile begin while true begin set line = read line myfile if line == string begin break end print fo...
#!/usr/bin/python3 """Module of read_file function.""" def read_file(filename=""): """Function that reads a text file (UTF8) and prints it to stdout:""" with open(filename, encoding='utf-8') as myfile: while True: line = myfile.readline() if line == "": brea...
Python
zaydzuhri_stack_edu_python
function fit self X y=none begin call validate_params call get_params _hyperparameters call check_array X allow_nd=true set _is_fitted = true return self end function
def fit(self, X, y=None): validate_params(self.get_params(), self._hyperparameters) check_array(X, allow_nd=True) self._is_fitted = True return self
Python
nomic_cornstack_python_v1
function get_var self field begin for tup in vars begin if field == tup at 1 begin return squeeze np data at tup at 0 at 0 at tup at 1 at 0 end end end function
def get_var(self, field): for tup in self.vars: if field == tup[1]: return np.squeeze(self.data[tup[0]][0][tup[1]][0])
Python
nomic_cornstack_python_v1
function g_spread self begin return __g_spread end function
def g_spread(self) -> AssetScreenerRequestFilterLimits: return self.__g_spread
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment # Behaviorial Cloning Project comment ## Project Writeup comment #### Author: Salman Ali Shaukat. comment The steps of this project are the following: comment #### 1. Import all the stuff which is needed for this project. comment #### 2. Gather Data. comment #### 3. Pre-process Data for ac...
# coding: utf-8 # # Behaviorial Cloning Project # # ## Project Writeup # #### Author: Salman Ali Shaukat. # The steps of this project are the following: # # #### 1. Import all the stuff which is needed for this project. # #### 2. Gather Data. # #### 3. Pre-process Data for achiving Guassian Distribution. # a. I...
Python
zaydzuhri_stack_edu_python
function load_actions_config actionsfile begin with open actionsfile as f begin set config = load yaml f end assert string gamepads in config assert string games in config for game in config at string games begin assert string gamepad in config at string games at game assert string actions in config at string games at ...
def load_actions_config(actionsfile): with open(actionsfile) as f: config = yaml.load(f) assert "gamepads" in config assert "games" in config for game in config["games"]: assert "gamepad" in config["games"][game] assert "actions" in config["games"][game] return config
Python
nomic_cornstack_python_v1
function check_taxa self ds begin set ret_val = list function match_taxa_standard_names standard_name_string begin string Match variables which are standard_names related to taxa, but are not the taxon identifiers or LSIDs themselves. return standard_name_string is not none and string taxon in standard_name_string and...
def check_taxa(self, ds: Dataset): ret_val = [] def match_taxa_standard_names(standard_name_string): """ Match variables which are standard_names related to taxa, but are not the taxon identifiers or LSIDs themselves. """ return ( ...
Python
nomic_cornstack_python_v1
function uifft2 inarray begin return call uifftn inarray 2 end function
def uifft2(inarray): return uifftn(inarray, 2)
Python
nomic_cornstack_python_v1
function from_warc warc_record begin set html = string read raw_stream set url = call get_header string WARC-Target-URI set article = call from_html html url return article end function
def from_warc(warc_record): html = str(warc_record.raw_stream.read()) url = warc_record.rec_headers.get_header('WARC-Target-URI') article = NewsPlease.from_html(html, url) return article
Python
nomic_cornstack_python_v1
function _get_blocked_statuses self begin return list false * length case_names end function
def _get_blocked_statuses(self): return [False] * len(self.case_names)
Python
nomic_cornstack_python_v1
function palindromePairs lst begin set results = list for tuple i e1 in enumerate lst begin for tuple j e2 in enumerate lst begin if i != j begin if call isPalindrome e1 + e2 begin append results tuple i j end end end end return results end function
def palindromePairs(lst): results = [] for i, e1 in enumerate(lst): for j, e2 in enumerate(lst): if i != j: if isPalindrome(e1+e2): results.append((i, j)) return results
Python
nomic_cornstack_python_v1
string Created on May 20, 2017 @author: Gregory from incanGold.agent.Agent import Agent from incanGold.GameState import TURN_BACK , GO_FORWARD class CollectNAgent extends Agent begin string classdocs function __init__ self minRoundValue begin string Constructor call __init__ minRoundValue set minRoundValue = minRoundVa...
''' Created on May 20, 2017 @author: Gregory ''' from incanGold.agent.Agent import Agent from incanGold.GameState import TURN_BACK, GO_FORWARD class CollectNAgent(Agent): ''' classdocs ''' def __init__(self, minRoundValue): ''' Constructor ''' super(CollectNAgent, sel...
Python
zaydzuhri_stack_edu_python
function ok a b c d begin return a + b == c + d or a - b == c - d or absolute a - c + absolute b - d <= 3 end function comment 最大三手で必ずいける if r1 == r2 and c1 == c2 begin print 0 end else if r1 + c1 == r2 + c2 or r1 - c1 == r2 - c2 or absolute r1 - r2 + absolute c1 - c2 <= 3 begin print 1 end else if r1 + r2 + c1 + c2 % ...
def ok(a, b, c, d): return a+b == c+d or a-b == c-d or abs(a-c) + abs(b-d) <= 3 # 最大三手で必ずいける if r1==r2 and c1==c2: print(0) elif r1+c1 == r2+c2 or r1-c1 == r2-c2 or abs(r1-r2) + abs(c1-c2) <= 3: print(1) elif (r1+r2+c1+c2)%2 == 0\ or abs(r1-r2) + abs(c1-c2) <= 6\ or r2-r1+3 >= c2-c1 and r2-r1-3 <= ...
Python
zaydzuhri_stack_edu_python
import unittest from bigquerytest.testcase import BigQueryTestCase from mock import patch class BigQueryTestCaseDummy extends BigQueryTestCase begin set project = string my-project set dataset = string my_dataset function __init__ self begin call __init__ methodName=string __class__ end function end class class BigQuer...
import unittest from bigquerytest.testcase import BigQueryTestCase from mock import patch class BigQueryTestCaseDummy(BigQueryTestCase): project = 'my-project' dataset = 'my_dataset' def __init__(self): super(BigQueryTestCaseDummy, self).__init__(methodName='__class__') class BigQueryTestCaseLeg...
Python
zaydzuhri_stack_edu_python
function get_binary_labels label_list t_dic begin set label_df = call DataFrame label_list set selected_category = keys t_dic set label_df = label_df at selected_category for tuple key value in call iteritems begin set label_df at key = where label_df at key < value 0 1 end return label_df end function
def get_binary_labels(label_list, t_dic): label_df = pd.DataFrame(label_list) selected_category = t_dic.keys() label_df = label_df[selected_category] for key, value in t_dic.iteritems(): label_df[key] = np.where(label_df[key] < value, 0, 1) return(label_df)
Python
nomic_cornstack_python_v1
function getAllLogs begin set dir = list directory absolute path path curdir + string \Usables\Log\ set list = list for file in dir begin set tuple filename file_extention = call splitext file if file_extention == string .xes begin append list file end end return list end function
def getAllLogs(): dir = os.listdir(os.path.abspath(os.curdir) + "\\Usables\\Log\\") list = [] for file in dir: filename, file_extention = os.path.splitext(file) if(file_extention == ".xes"): list.append(file) return list
Python
nomic_cornstack_python_v1
function _request self method endpoint params=none begin set params = if expression params then params else dict debug string Making request for endpoint { endpoint } and parameters: { params } try begin set resp = call request method endpoint params=params timeout=timeout debug string Received response - status: { st...
def _request( self, method: str, endpoint: str, params: Optional[dict] = None ) -> dict: params = params if params else {} logging.debug( f"Making request for endpoint {endpoint} and parameters: {params}" ) try: resp = requests.request( ...
Python
nomic_cornstack_python_v1
comment STRETCH: implement Linear Search function linear_search arr target begin for i in range 0 length arr begin if arr at i == target begin return i end end return - 1 end function comment STRETCH: write an iterative implementation of Binary Search function binary_search arr target begin if length arr == 0 begin com...
# STRETCH: implement Linear Search def linear_search(arr, target): for i in range(0, len(arr)): if arr[i] == target: return i return -1 # STRETCH: write an iterative implementation of Binary Search def binary_search(arr, target): if len(arr) == 0: return -1 # array emp...
Python
zaydzuhri_stack_edu_python
function display_metrics2 self begin call showinfo string Original Image Metrics raw_metrics end function
def display_metrics2(self): messagebox.showinfo("Original Image Metrics", self.raw_metrics)
Python
nomic_cornstack_python_v1
function initNodes self size begin if layerType == string output begin for i in call xrange 1 size + 1 begin call addNode i end end else begin for i in call xrange 0 size + 1 begin call addNode i end end end function
def initNodes(self, size): if self.layerType == 'output': for i in xrange(1, size + 1): self.addNode(i) else: for i in xrange(0, size + 1): self.addNode(i)
Python
nomic_cornstack_python_v1
function compute_mask self inputs mask=none begin return length inputs + 1 * list none end function
def compute_mask(self, inputs, mask=None): return (len(inputs) + 1) * [None]
Python
nomic_cornstack_python_v1
import flake8.api.legacy as flake8 set style_guide = call get_style_guide set report = call check_files list string example.py comment Format output call format_statistics comment Count errors set error_count = call get_statistics string E print string Error count: { length error_count } comment 1. Added output formatt...
import flake8.api.legacy as flake8 style_guide = flake8.get_style_guide() report = style_guide.check_files(['example.py']) # Format output report.format_statistics() # Count errors error_count = report.get_statistics('E') print(f'Error count: {len(error_count)}') # 1. Added output formatting. # 2. Included error co...
Python
flytech_python_25k
function get_active_space_integrals self active_space_start active_space_stop=none begin comment Get integrals. set tuple one_body_integrals two_body_integrals = call get_integrals set n_orbitals = shape at 0 if active_space_stop is none begin set active_space_stop = n_orbitals end comment Determine core constant set c...
def get_active_space_integrals(self, active_space_start, active_space_stop=None): # Get integrals. one_body_integrals, two_body_integrals = self.get_integrals() n_orbitals = one_body_integrals.shape[0] if active_space_stop is None: active_sp...
Python
nomic_cornstack_python_v1
function test_complex_expression self begin call assertAlmostEqual call evaluator dict dict string (2^2+1.0)/sqrt(5e0)*5-1 10.18 delta=0.001 call assertAlmostEqual call evaluator dict dict string 1+1/(1+1/(1+1/(1+1))) 1.6 delta=0.001 call assertAlmostEqual call evaluator dict dict string 10||sin(7+5) - 0.567 delt...
def test_complex_expression(self): self.assertAlmostEqual( calc.evaluator({}, {}, "(2^2+1.0)/sqrt(5e0)*5-1"), 10.180, delta=1e-3 ) self.assertAlmostEqual( calc.evaluator({}, {}, "1+1/(1+1/(1+1/(1+1)))"), 1.6, delt...
Python
nomic_cornstack_python_v1
function determinant self begin set A = copy self if m != n begin raise call MatrixException string Non-Square Matrix! end else if n == 1 begin return values at 0 at 0 end else begin set det = 0 for j in range 1 n + 1 begin set w1 = - 1 ^ 1 + j comment account for zero-indexing set w2 = values at 0 at j - 1 set w3 = ca...
def determinant(self): A = self.copy() if A.m != A.n: raise MatrixException("Non-Square Matrix!") elif A.n == 1: return A.values[0][0] else: det = 0 for j in range(1, A.n + 1): w1 = (-1) ** (1 + j) w2 = A.val...
Python
nomic_cornstack_python_v1
function __init__ self begin call __init__ string /run/dmg/system/cleanup/* string cleanup set machinename = call FormattedParameter string {} none set verbose = call FormattedParameter string --verbose false end function
def __init__(self): super().__init__("/run/dmg/system/cleanup/*", "cleanup") self.machinename = FormattedParameter("{}", None) self.verbose = FormattedParameter("--verbose", False)
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup , Tag function extract_attributes html begin set attributes = dict function extract tag begin if is instance tag Tag begin for tuple key value in items attrs begin set attributes at key = value end for child in children begin extract child end end end function set soup = call BeautifulSou...
from bs4 import BeautifulSoup, Tag def extract_attributes(html): attributes = {} def extract(tag): if isinstance(tag, Tag): for key, value in tag.attrs.items(): attributes[key] = value for child in tag.children: extract(child) soup = Beautif...
Python
jtatman_500k
comment !/usr/bin/env python3 import sys from BST import TreeNode from BST import insertNode from BST import inOrderTraversal from BST import preOrderTraversal comment Symmetric Binary Tree comment https://www.interviewbit.com/problems/symmetric-binary-tree/ comment Given a binary tree, check whether it is a mirror of ...
#!/usr/bin/env python3 import sys from BST import TreeNode from BST import insertNode from BST import inOrderTraversal from BST import preOrderTraversal # Symmetric Binary Tree # https://www.interviewbit.com/problems/symmetric-binary-tree/ # # Given a binary tree, check whether it is a mirror of itself (ie, symmetric ...
Python
zaydzuhri_stack_edu_python
function test_adjust_inv_sigmoid_cutoff_half begin set image = reshape array range 0 255 4 uint8 tuple 8 8 set expected = array list list 253 253 252 252 251 251 250 249 list 249 248 247 245 244 242 240 238 list 235 232 229 225 220 215 210 204 list 197 190 182 174 165 155 146 136 list 126 116 106 96 87 78 70 62 list 55...
def test_adjust_inv_sigmoid_cutoff_half(): image = np.arange(0, 255, 4, np.uint8).reshape((8, 8)) expected = np.array([ [253, 253, 252, 252, 251, 251, 250, 249], [249, 248, 247, 245, 244, 242, 240, 238], [235, 232, 229, 225, 220, 215, 210, 204], [197, 190, 182, 174, 165, 155, 146...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment Filename: Lesson07.py import linkbot import math set robot = call Linkbot comment The "track length" is the distance between the two set tracklength = 3.6975 comment wheels comment The wheel diameter set wheel_diameter = 3.5 comment Calculate the wheel radius based on diameter set ...
#!/usr/bin/env python3 # Filename: Lesson07.py import linkbot import math robot = linkbot.Linkbot() tracklength = 3.6975 # The "track length" is the distance between the two # wheels wheel_diameter = 3.5 # The wheel diameter wheel_radius = wheel_diameter/2 # Calculate the wheel radius...
Python
zaydzuhri_stack_edu_python
import os set author = string Deart Ivan comment Задача-1: comment Напишите небольшую консольную утилиту, comment позволяющую работать с папками текущей директории. comment Утилита должна иметь меню выбора действия, в котором будут пункты: comment 1. Перейти в папку comment 2. Просмотреть содержимое текущей папки comme...
import os author = "Deart Ivan" # Задача-1: # Напишите небольшую консольную утилиту, # позволяющую работать с папками текущей директории. # Утилита должна иметь меню выбора действия, в котором будут пункты: # 1. Перейти в папку # 2. Просмотреть содержимое текущей папки # 3. Удалить папку # 4. Создать папку # При выбо...
Python
zaydzuhri_stack_edu_python
import datetime from typing import List , Dict from functional import seq from sqlalchemy import Column , Integer , DateTime , func , and_ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session from crawler.politician import Politician set Base = call declarative_base class Job exten...
import datetime from typing import List, Dict from functional import seq from sqlalchemy import Column, Integer, DateTime, func, and_ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import Session from crawler.politician import Politician Base = declarative_base() class Job(Base): #...
Python
zaydzuhri_stack_edu_python
comment split set letters = string A,B,C,D print split letters string , print split letters string , 2 comment joining comment join set letters_list = list string A string B string C string D print join string , letters_list print join string , list comprehension string i for i in range 10 comment partition splits a st...
# split letters = "A,B,C,D" print(letters.split(",")) print(letters.split(",", 2)) # joining # join letters_list = ['A', 'B', 'C', 'D'] print(','.join(letters_list)) print(','.join([str(i) for i in range(10)])) # partition splits a string into a tuple of three strings based on the method's seperator argument # the...
Python
zaydzuhri_stack_edu_python
function attach self filt view=none begin string Attach a Filter to this visual Each filter modifies the appearance or behavior of the visual. Parameters ---------- filt : object The filter to attach. view : instance of VisualView | None The view to use. if view is none begin append filters filt for view in keys views ...
def attach(self, filt, view=None): """Attach a Filter to this visual Each filter modifies the appearance or behavior of the visual. Parameters ---------- filt : object The filter to attach. view : instance of VisualView | None The view to use. ...
Python
jtatman_500k
import numpy as np function svd_diag sigma m n begin set sigma = call diag sigma if m < n begin set sigma = c_ at tuple sigma zeros tuple m n - m end else if m > n begin set sigma = r_ at tuple sigma zeros tuple m - n n end return sigma end function function is_equal_array_over_eps a b ep=1e-08 begin comment Relative C...
import numpy as np def svd_diag(sigma, m, n): sigma = np.diag(sigma) if m < n: sigma = np.c_[sigma, np.zeros((m, n - m))] elif m > n: sigma = np.r_[sigma, np.zeros((m - n, n))] return sigma def is_equal_array_over_eps(a, b, ep=1e-8): # Relative Comparision diff = abs(a - b) ...
Python
zaydzuhri_stack_edu_python
function gen_unique_id begin comment Workaround for http://bugs.python.org/issue4607 if ctypes and _uuid_generate_random begin set buffer = call create_string_buffer 16 call _uuid_generate_random buffer return string uuid bytes=raw end return string uuid 4 end function
def gen_unique_id(): # Workaround for http://bugs.python.org/issue4607 if ctypes and _uuid_generate_random: buffer = ctypes.create_string_buffer(16) _uuid_generate_random(buffer) return str(UUID(bytes=buffer.raw)) return str(uuid4())
Python
nomic_cornstack_python_v1
function legendre_symbol a p begin set ls = power a p - 1 / 2 p return if expression ls == p - 1 then - 1 else ls end function
def legendre_symbol(a, p): ls = pow(a, (p - 1) / 2, p) return -1 if ls == p - 1 else ls
Python
nomic_cornstack_python_v1
comment importing libraries from sklearn import tree import numpy as np comment preparing the data comment features set features = list list 140 1 list 130 1 list 150 0 list 170 0 comment target set target = list string apple string apple string orange string orange comment training the classifier set clf = call Decisi...
#importing libraries from sklearn import tree import numpy as np # preparing the data # features features = [[140,1],[130,1],[150,0],[170,0]] # target target = ['apple','apple','orange','orange'] # training the classifier clf = tree.DecisionTreeClassifier() clf = clf.fit(features, target) # testing the classifier t...
Python
jtatman_500k
function test_max_flow default_plugin_resolver begin set dpr = default_plugin_resolver set source_node = 0 set target_node = 7 set ebunch = list tuple 0 1 9 tuple 0 3 10 tuple 1 4 3 tuple 2 7 6 tuple 3 1 2 tuple 3 4 8 tuple 4 5 7 tuple 4 2 4 tuple 5 2 5 tuple 5 6 1 tuple 6 2 11 set nx_graph = call DiGraph call add_weig...
def test_max_flow(default_plugin_resolver): dpr = default_plugin_resolver source_node = 0 target_node = 7 ebunch = [ (0, 1, 9), (0, 3, 10), (1, 4, 3), (2, 7, 6), (3, 1, 2), (3, 4, 8), (4, 5, 7), (4, 2, 4), (5, 2, 5), (5, 6, ...
Python
nomic_cornstack_python_v1
from typing import Counter import pandas as pd import stemming import os import sys append path string food_dashboard/ import requests import Percentage import Interest_by_date import Data comment paths set paths = list string raw_dataset/cleaned_menu_links.csv string raw_dataset/cleaned_packaged_foods.csv string raw_d...
from typing import Counter import pandas as pd import stemming import os import sys sys.path.append('food_dashboard/') import requests import Percentage import Interest_by_date import Data #paths paths=['raw_dataset/cleaned_menu_links.csv','raw_dataset/cleaned_packaged_foods.csv','raw_dataset/cleaned_receipe.csv'] de...
Python
zaydzuhri_stack_edu_python
string retrieve the articles from the rss wayback links. import requests from bs4 import BeautifulSoup import time comment first, open the file of rss links. set skipto = 7000 set upto = 8000 set ctr = 0 with open string ./rss_wayback_links.txt as f begin for link in f begin set ctr = ctr + 1 if skipto and ctr < skipto...
''' retrieve the articles from the rss wayback links. ''' import requests from bs4 import BeautifulSoup import time #first, open the file of rss links. skipto = 7000 upto = 8000 ctr = 0 with open('./rss_wayback_links.txt') as f: for link in f: ctr += 1 if skipto and (ctr < skipto): co...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python2 import numpy as np from scipy.linalg import sqrtm function kmatrix N begin return array list comprehension list comprehension if expression j <= i then 1 else 0 for j in range N for i in range N end function function optKMatrix N begin set K = call kmatrix N return dot call inv call sqrtm dot ...
#!/usr/bin/python2 import numpy as np from scipy.linalg import sqrtm def kmatrix(N): return np.array([ [ 1 if j<=i else 0 for j in range(N) ] for i in range(N) ]) def optKMatrix(N): K = kmatrix(N) return K.T.dot(np.linalg.inv(sqrtm(K.dot(K.T)))) if __name__ == '__main__': import drawnet as dn controllerSizes =...
Python
zaydzuhri_stack_edu_python
function _on_sphinx_thread_error_msg self error_msg begin string Display error message on Sphinx rich text failure wait _sphinx_thread call setChecked true set sphinx_ver = call get_module_version string sphinx critical self call _ string Help call _ string The following error occured when calling <b>Sphinx %s</b>. <br...
def _on_sphinx_thread_error_msg(self, error_msg): """ Display error message on Sphinx rich text failure""" self._sphinx_thread.wait() self.plain_text_action.setChecked(True) sphinx_ver = programs.get_module_version('sphinx') QMessageBox.critical(self, _(...
Python
jtatman_500k
import re from optparse import OptionParser function create_options_for_option_parser option_parser begin call add_option string -c string --count action=string store_true dest=string counter help=string display the total number of requests call add_option string -t string --time action=string store_true dest=string ti...
import re from optparse import OptionParser def create_options_for_option_parser(option_parser: OptionParser): option_parser.add_option("-c", "--count", action="store_true", dest='counter', help="display the total number of requests") option_parser.add_option("-t", "--time", action="store_true", dest='time', ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment [Using Machine Learning to Find the 8 Types of Players in the NBA](https://fastbreakdata.com/classifying-the-modern-nba-player-with-machine-learning-539da03bb824 "fastbreakdata") comment Import necessary libraries comment In[1]: import numpy as np import warnin...
#!/usr/bin/env python # coding: utf-8 # [Using Machine Learning to Find the 8 Types of Players in the NBA](https://fastbreakdata.com/classifying-the-modern-nba-player-with-machine-learning-539da03bb824 "fastbreakdata") # Import necessary libraries # In[1]: import numpy as np import warnings warnings.simplefilter("...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import random function random_list n begin set re_list = range n shuffle random re_list return re_list end function function swap L left right begin string Zamiana miejscami dwóch elementów. comment L[left], L[right] = L[right], L[left] set item = L at left set L at left = L at right set L...
# -*- coding: utf-8 -*- import random def random_list(n): re_list = range(n) random.shuffle(re_list) return re_list def swap(L, left, right): """Zamiana miejscami dwóch elementów.""" # L[left], L[right] = L[right], L[left] item = L[left] L[left] = L[right] L[right] = item def quick...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Fri Apr 21 15:17:02 2017 @author: yaosheng import re import crawlerlog import requests import codecs import os import threading set session = call Session function getHTML url begin set headers = dict string Accept-Encoding string gzip ; string User-Agent string Mozilla/5...
# -*- coding: utf-8 -*- """ Created on Fri Apr 21 15:17:02 2017 @author: yaosheng """ import re import crawlerlog import requests import codecs import os import threading session=requests.Session() def getHTML(url): headers = { "Accept-Encoding":"gzip", "User-Age...
Python
zaydzuhri_stack_edu_python
function command_shell self begin return _command_shell end function
def command_shell(self): return self._command_shell
Python
nomic_cornstack_python_v1
function value_calculator_cluster clusters_info begin set clusters_info_sorted_by_area = sorted clusters_info key=lambda item -> item at string area reverse=true set length = length clusters_info_sorted_by_area for info in clusters_info_sorted_by_area begin set info at string value = 1 end if length > 5 begin set clust...
def value_calculator_cluster(clusters_info): clusters_info_sorted_by_area = sorted(clusters_info, key=lambda item: item['area'], reverse=True) length = len(clusters_info_sorted_by_area) for info in clusters_info_sorted_by_area: info['value'] = 1 if length > 5: clusters_info_sorted_by_are...
Python
nomic_cornstack_python_v1
comment 출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges comment 코딩테스트 연습 > 연습문제 > 짝수와 홀수 comment 사용언어 Python3 comment 내 답안 function solution num begin if num % 2 == 0 begin set answer = string Even end else begin set answer = string Odd end return answer end function
# 출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges # 코딩테스트 연습 > 연습문제 > 짝수와 홀수 # 사용언어 Python3 #내 답안 def solution(num): if num%2 == 0 : answer = "Even" else : answer = "Odd" return answer
Python
zaydzuhri_stack_edu_python
function insert self word begin set current_node = root for i in range length word begin if word at i not in keys sons begin set sons at word at i = call Node end set current_node = sons at word at i end set sons at string end = string end end function
def insert(self, word): current_node = self.root for i in range(len(word)): if word[i] not in current_node.sons.keys(): current_node.sons[word[i]] = Node() current_node = current_node.sons[word[i]] current_node.sons["end"] = "end"
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment Wifi Connection Status comment Kevin Hinds http://www.kevinhinds.com comment License: GPL 2.0 import json import includes.data as data import includes.settings as settings class Wifi begin string Wifi connection status as class to persist as JSON information to file set jsonFile = strin...
#!/usr/bin/python # Wifi Connection Status # Kevin Hinds http://www.kevinhinds.com # License: GPL 2.0 import json import includes.data as data import includes.settings as settings class Wifi: '''Wifi connection status as class to persist as JSON information to file''' jsonFile = '' isConnected = 'no' ...
Python
zaydzuhri_stack_edu_python
comment hot_dog_cookout_Wood comment this program will calculate the leftovers from a cookout comment Programmer: Christopher Wood comment date 2/14/18 comment file name hot_dog_cookout_Wood.py comment pseudocode comment Get the number of attendees comment Get the number of hot dogs for each person comment Calculate th...
# hot_dog_cookout_Wood # this program will calculate the leftovers from a cookout # Programmer: Christopher Wood # date 2/14/18 # file name hot_dog_cookout_Wood.py # pseudocode # Get the number of attendees # Get the number of hot dogs for each person # Calculate the total number of hot dogs required # Number ...
Python
zaydzuhri_stack_edu_python
function _setup_logger name log_levels=none begin set log_levels = call opt_dict_param log_levels string log_levels comment py27 compat class TestLogger extends Logger begin pass end class set logger = call TestLogger name set captured_results = list comment pylint:disable=unused-argument function log_fn msg *args **k...
def _setup_logger(name, log_levels=None): log_levels = check.opt_dict_param(log_levels, "log_levels") class TestLogger(logging.Logger): # py27 compat pass logger = TestLogger(name) captured_results = [] def log_fn(msg, *args, **kwargs): # pylint:disable=unused-argument captured...
Python
nomic_cornstack_python_v1
import requests from time import sleep set API_ENDPOINT = string https://api.example.com/users set TOKEN_ENDPOINT = string https://auth.example.com/token set REFRESH_ENDPOINT = string https://auth.example.com/refresh comment OAuth2.0 configuration set CLIENT_ID = string your_client_id set CLIENT_SECRET = string your_cl...
import requests from time import sleep API_ENDPOINT = 'https://api.example.com/users' TOKEN_ENDPOINT = 'https://auth.example.com/token' REFRESH_ENDPOINT = 'https://auth.example.com/refresh' # OAuth2.0 configuration CLIENT_ID = 'your_client_id' CLIENT_SECRET = 'your_client_secret' USERNAME = 'your_username' PASSWORD =...
Python
jtatman_500k
function generate self begin set graph_repl = graph_repl end function
def generate(self): self.graph_repl = self.master.graph_repl
Python
nomic_cornstack_python_v1
function test_family self begin set barghest = call fromMonster MONSTERS at 144 set actual = sorted call pluck families string label set expected = sorted list string Outsider string Evil string Extraplanar string Lawful string Shapechanger assert equal actual expected set babau = call fromId 165 set actual = sorted ca...
def test_family(self): barghest = statblock.Statblock.fromMonster(MONSTERS[144]) actual = sorted(pluck(barghest.families, 'label')) expected = sorted([u'Outsider', u'Evil', u'Extraplanar', u'Lawful', u'Shapechanger']) self.assertEqual(actual, expected) babau = statbl...
Python
nomic_cornstack_python_v1
comment Ej. Crear un variable nombre y una variable EDAD comment Con sus Nombres y edades y despues imprimir comment Hola, me llamo ----- y tengo----- anos set nombre = string Ruben set Edad = 28 print string hola mi nombre es nombre string y tengo Edad set Profesion = string electrcista set ciudad = string caaguazu co...
#Ej. Crear un variable nombre y una variable EDAD # Con sus Nombres y edades y despues imprimir #Hola, me llamo ----- y tengo----- anos nombre = "Ruben" Edad = 28 print("hola mi nombre es",nombre, "y tengo",Edad) Profesion = "electrcista" ciudad = "caaguazu" #Ej. Crear una lista datos que en en primer lugar este tu no...
Python
zaydzuhri_stack_edu_python
from telegram.ext import Updater , MessageHandler , Filters set updater = call Updater token=string 832662397:AAFfKUi8HQqzhOJVgKOEp2L8InKl6cWaFpI set dispatcher = dispatcher call start_polling function handler bot update begin set text = text set chat_id = chat_id if string die in text begin call send_message chat_id=c...
from telegram.ext import Updater, MessageHandler, Filters updater = Updater(token='832662397:AAFfKUi8HQqzhOJVgKOEp2L8InKl6cWaFpI') dispatcher = updater.dispatcher updater.start_polling() def handler(bot, update): text = update.message.text chat_id = update.message.chat_id if 'die' in text: bot.se...
Python
zaydzuhri_stack_edu_python
class AreaCalculator extends object begin decorator staticmethod function find_area width length begin set area_of_rectangle = width * length print string area_of_rectangle : area_of_rectangle end function end class class Main begin call find_area 10 20 end class
class AreaCalculator(object): @staticmethod def find_area(width, length): area_of_rectangle = width * length print("area_of_rectangle : ", area_of_rectangle) class Main: AreaCalculator.find_area(10, 20)
Python
zaydzuhri_stack_edu_python
import string function get_length string begin comment Remove punctuation marks set string = call translate call maketrans string string punctuation comment Remove whitespace characters set string = replace string string string comment Count alphanumeric characters set count = sum generator expression is alphanumeri...
import string def get_length(string): # Remove punctuation marks string = string.translate(str.maketrans('', '', string.punctuation)) # Remove whitespace characters string = string.replace(" ", "") # Count alphanumeric characters count = sum(char.isalnum() for char in string) ...
Python
greatdarklord_python_dataset
function get_velocity self begin comment rad/s return call _I85_msg_from_device phys / 10 end function
def get_velocity(self): return (self._I85_msg_from_device(self.node.sdo[0x606c].phys)) / 10 # rad/s
Python
nomic_cornstack_python_v1
function factorial_while_loop n begin if not is instance n int begin return string Error: Invalid input. Please enter a valid integer. end else if n < 0 begin return string Error: Factorial is undefined for negative numbers. end else begin set result = 1 while n > 0 begin set result = result * n set n = n - 1 end retur...
def factorial_while_loop(n): if not isinstance(n, int): return "Error: Invalid input. Please enter a valid integer." elif n < 0: return "Error: Factorial is undefined for negative numbers." else: result = 1 while n > 0: result *= n n -= 1 retur...
Python
jtatman_500k
function stat_filter2d input_img size perc begin comment M is height, N is width set tuple M N = shape comment m is height, n is width set tuple m n = size comment size of neighborhood set tuple a b = tuple m / 2 n / 2 function get_percentile x y begin comment z = np.zeros(n * m) # pad with zeros set z = list comment ...
def stat_filter2d(input_img, size, perc): M, N = input_img.shape # M is height, N is width m, n = size # m is height, n is width a, b = m / 2, n / 2 # size of neighborhood def get_percentile(x, y): # z = np.zeros(n * m) # pad with zeros z = [] # fill in available neighborhoo...
Python
nomic_cornstack_python_v1
import os comment 通过python脚本修改打包后的apk名字 for file in list directory string . begin if is file path file begin set extension = call splitext file at 1 at slice 1 : : end end
import os #通过python脚本修改打包后的apk名字 for file in os.listdir('.'): if os.path.isfile(file): extension = os.path.splitext(file)[1][1:]
Python
zaydzuhri_stack_edu_python
function test_deliverable self begin comment create a test product only deliverable to Ireland comment and add it to the bag set product = product name=string Create a Test price=1 euro_shipping=false save set session = session set session at string bag = dict id 1 save comment user is registed with a default delivery ...
def test_deliverable(self): # create a test product only deliverable to Ireland # and add it to the bag product = Product(name="Create a Test", price=1, euro_shipping=False) product.save() session = self.client.session session['bag'] = {product.id: 1} session.save...
Python
nomic_cornstack_python_v1
async function public_bulk_inc_user_stat_item_async body=none namespace=none x_additional_headers=none **kwargs begin if namespace is none begin set tuple namespace error = call get_services_namespace if error begin return tuple none error end end set request = call create body=body namespace=namespace return await cal...
async def public_bulk_inc_user_stat_item_async( body: Optional[List[BulkUserStatItemInc]] = None, namespace: Optional[str] = None, x_additional_headers: Optional[Dict[str, str]] = None, **kwargs ): if namespace is None: namespace, error = get_services_namespace() if error: ...
Python
nomic_cornstack_python_v1
function write branch=none branch_track=none inner=true connect_to=none begin global _tracks glyphs if inner begin set result = string end else if branch == string start begin set result = glyphs at string > end else if branch == string end begin set result = glyphs at string < end else begin set result = glyphs at st...
def write(branch=None, branch_track=None, inner=True, connect_to=None): global _tracks, glyphs if inner: result = " " else: if branch == 'start': result = glyphs[">"] elif branch == 'end': result = glyphs["<"] else: result = glyphs["-"] ...
Python
nomic_cornstack_python_v1
comment -------------------------------------------------------------------------- comment This prog. optimizes a function using the greedy optimization method by [Deco et al. 2014] comment see: comment G. Deco, A. Ponce-Alvarez, P. Hagmann, G.L. Romani, D. Mantini, M. Corbetta comment How local excitation-inhibition r...
# -------------------------------------------------------------------------- # # This prog. optimizes a function using the greedy optimization method by [Deco et al. 2014] # see: # G. Deco, A. Ponce-Alvarez, P. Hagmann, G.L. Romani, D. Mantini, M. Corbetta # How local excitation-inhibition ratio impacts the whole...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import random from __future__ import division function design_matrix order x begin set A = zeros list length x order for i in range order begin set A at tuple slice : : i = x ^ i end return A end function function regularization x b order lamb begin set order = orde...
import matplotlib.pyplot as plt import numpy as np import random from __future__ import division def design_matrix(order, x): A= np.zeros([len(x), order]) for i in range(order): A[:,i] = x**i return A def regularization(x, b, order, lamb): order += 1 A = design_matrix(order, x) w = ...
Python
zaydzuhri_stack_edu_python
import face_recognition import json from flask import Flask from flask import request import base64 from PIL import Image from io import BytesIO comment self-written functions from func import get_face set app = call Flask __name__ decorator call route string / methods=list string GET comment api activity test function...
import face_recognition import json from flask import Flask from flask import request import base64 from PIL import Image from io import BytesIO # self-written functions from func import get_face app = Flask(__name__) # api activity test @app.route('/', methods=['GET']) def hello(): return "Halo, the API is al...
Python
zaydzuhri_stack_edu_python
from trello import TrelloClient class TrelloHelper begin function __init__ self api_key token begin set client = call TrelloClient api_key=api_key token=token end function function create_organization self organization_name begin set post_args = dict string displayName organization_name set obj = call fetch_json string...
from trello import TrelloClient class TrelloHelper(): def __init__(self, api_key, token): self.client = TrelloClient(api_key=api_key, token=token) def create_organization(self, organization_name): post_args = {'displayName': organization_name} obj = self.client.fetch_json( ...
Python
zaydzuhri_stack_edu_python
comment 4672. 수진이의 팰린드롬 set T = integer input for test_case in range 1 T + 1 begin set str_list = input set res = 0 set char_count = dict for char in str_list begin if char in char_count begin set char_count at char = char_count at char + 1 end else begin set char_count at char = 1 end end for key in char_count begin ...
#4672. 수진이의 팰린드롬 T = int(input()) for test_case in range(1, T+1): str_list = input() res = 0 char_count = {} for char in str_list: if char in char_count: char_count[char] +=1 else: char_count[char] = 1 for key in char_count: value = char_...
Python
zaydzuhri_stack_edu_python
function __init__ self epsilon=1e-07 begin call __init__ set epsilon = epsilon end function
def __init__(self, epsilon=1e-7): super().__init__() self.epsilon = epsilon
Python
nomic_cornstack_python_v1
for x in reversed L begin comment 3 1 7 9 5 print x end comment L2 = [1 3 5 7 9] set L2 = sorted L call python3中常用的列表方法 method
for x in reversed(L): print(x) #3 1 7 9 5 L2 = sorted(L) #L2 = [1 3 5 7 9] python3中常用的列表方法(method)
Python
zaydzuhri_stack_edu_python
function init_db begin with call app_context begin comment db = get_db() comment with app.open_resource('base.sql', mode='r') as f: comment db.cursor().executescript(f.read()) comment db.commit() set db = call get_db for j in range length joueurs / 2 begin set cur = execute db string update matchs set j1=' + string jou...
def init_db(): with app.app_context(): #db = get_db() #with app.open_resource('base.sql', mode='r') as f: # db.cursor().executescript(f.read()) #db.commit() db = get_db() for j in range(len(joueurs)/2): cur = db.execute("update matchs set j1='" + str(jo...
Python
nomic_cornstack_python_v1
function allow_running_jobs_to_complete_past_operation_window self flag begin if is instance flag bool begin set settings = dict string allowRunningJobsToCompletePastOperationWindow flag call set_general_settings settings end else begin raise call SDKException string Job string 108 end end function
def allow_running_jobs_to_complete_past_operation_window(self, flag): if isinstance(flag, bool): settings = { "allowRunningJobsToCompletePastOperationWindow": flag } self.set_general_settings(settings) else: raise SDKException('Job',...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment required to make HTTP requests import requests function main begin comment api goes here comment example: set api = string https://pokeapi.co/api/v2/pokemon/pikachu comment api = "http://" # <--- you have to fill in this! comment sent HTTP GET and create resp, a response object set res...
#!/usr/bin/python3 # required to make HTTP requests import requests def main(): # api goes here # example: api = "https://pokeapi.co/api/v2/pokemon/pikachu" #api = "http://" # <--- you have to fill in this! # sent HTTP GET and create resp, a response object resp = requests.get(api) # ...
Python
zaydzuhri_stack_edu_python
comment load all images in a directory and save as pixel values from os import listdir from PIL import Image from numpy import asarray comment import cv2 import os import io from matplotlib import pyplot function readAllPixels num_of_dirs dir_names begin set pixels_all = list set m = 0 for i in range num_of_dirs begin ...
# load all images in a directory and save as pixel values from os import listdir from PIL import Image from numpy import asarray # import cv2 import os import io from matplotlib import pyplot def readAllPixels(num_of_dirs,dir_names): pixels_all = list() m = 0 for i in range(num_of_dirs): pixels...
Python
zaydzuhri_stack_edu_python
function domain_emails emails begin set domain_dict = dict for email in emails begin set domain = split email string @ at 1 if domain not in domain_dict begin set domain_dict at domain = list end append domain_dict at domain email end for domain in domain_dict begin sort domain_dict at domain key=len reverse=true end...
def domain_emails(emails): domain_dict = {} for email in emails: domain = email.split('@')[1] if domain not in domain_dict: domain_dict[domain] = [] domain_dict[domain].append(email) for domain in domain_dict: domain_dict[domain].sort(key=len, reverse=Tr...
Python
greatdarklord_python_dataset
comment coding = 'utf-8' string 模块功能:sqlite3数据库操作模块 作者:Li Yu 创建时间:2019/05/02 创建地点:武汉大学,湖北,武汉 作者邮箱:2014301610173@whu.edu.cn from tkinter import * from tkinter import messagebox , filedialog import sqlite3 , os from datetime import * comment 创建sqlite数据库 function createDB sp_ins dbname curdir begin if dbname == string be...
#coding = 'utf-8' ''' 模块功能:sqlite3数据库操作模块 作者:Li Yu 创建时间:2019/05/02 创建地点:武汉大学,湖北,武汉 作者邮箱:2014301610173@whu.edu.cn ''' from tkinter import * from tkinter import messagebox,filedialog import sqlite3,os from datetime import * # 创建sqlite数据库 def createDB(sp_ins,dbname,curdir): if(dbname == ''): print(dbname) messagebo...
Python
zaydzuhri_stack_edu_python
comment This is not a real password generator comment Printing password to terminal, not great comment Not using secrets.systemrandom, not great comment Storing symbols, letters, and numbers in list in memory is also bad comment Just the exercise which reqs allowing choosing letters, numbers, and symbols import random ...
## This is not a real password generator ## Printing password to terminal, not great ## Not using secrets.systemrandom, not great ## Storing symbols, letters, and numbers in list in memory is also bad ## Just the exercise which reqs allowing choosing letters, numbers, and symbols import random import secrets import st...
Python
zaydzuhri_stack_edu_python
function dEuclideanLoss YPredict YTrue begin if shape != shape begin set YTrue = reshape YTrue shape end return YPredict - YTrue end function
def dEuclideanLoss(YPredict, YTrue): if YPredict.shape != YTrue.shape: YTrue = YTrue.reshape(YPredict.shape) return YPredict - YTrue
Python
nomic_cornstack_python_v1
function answer l begin string Args: l (list of ints): list of ascending intergers Return: Count (int): number of 'Triples' comment initialize count of Triples set count = 0 comment the plan here is for every index i in l, comment look to see if there is an index ahead of it j for which l[j] is divisible by l[i] commen...
def answer(l): ''' Args: l (list of ints): list of ascending intergers Return: Count (int): number of 'Triples' ''' #initialize count of Triples count=0 #the plan here is for every index i in l, #look to see if there is an index ahead of it j for which l[j] is div...
Python
zaydzuhri_stack_edu_python
import RPi.GPIO as GPIO call setmode BCM set BUZZER = 21 set G_LED = 16 set IR = 12 set R_LED = 20 setup GPIO IR IN pull_up_down=PUD_DOWN import time while 1 begin print input IR if input IR == 0 begin print string obstacle detect end else begin print string No obstacle end sleep 0.3 end
import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) BUZZER=21 G_LED=16 IR=12 R_LED=20 GPIO.setup(IR,GPIO.IN,pull_up_down=GPIO.PUD_DOWN) import time while 1: print(GPIO.input(IR)) if(GPIO.input(IR)==0): print('obstacle detect') else: print('No obstacle') time.sleep(.3)
Python
zaydzuhri_stack_edu_python
function _got_chunk self chunk timestamp begin debug string _got_chunk: chunk=%s chunk call _extract_sample D1000TemperatureDataParticle call regex_compiled chunk timestamp end function
def _got_chunk(self, chunk, timestamp): log.debug("_got_chunk: chunk=%s", chunk) self._extract_sample(D1000TemperatureDataParticle, D1000TemperatureDataParticle.regex_compiled(), chunk, timestamp)
Python
nomic_cornstack_python_v1
function validate self begin string Validate that the FoldCountContextField is correctly representable. if not is instance fold_scope_location FoldScopeLocation begin raise call TypeError format string Expected FoldScopeLocation fold_scope_location, got: {} {} type fold_scope_location fold_scope_location end if field !...
def validate(self): """Validate that the FoldCountContextField is correctly representable.""" if not isinstance(self.fold_scope_location, FoldScopeLocation): raise TypeError(u'Expected FoldScopeLocation fold_scope_location, got: {} {}'.format( type(self.fold_scope_location), ...
Python
jtatman_500k
class Publisher begin function __init__ self begin set subscribers = dictionary end function function subscribe self who callback=none begin if callback is none begin set callback = get attribute who string update end set subscribers at who = callback end function function unsubscribe self who begin del subscribers at ...
class Publisher(): def __init__(self): self.subscribers = dict() def subscribe(self, who, callback=None): if callback is None: callback = getattr(who, 'update') self.subscribers[who] = callback def unsubscribe(self, who): del self.subscribers[who] def ...
Python
zaydzuhri_stack_edu_python
function draw_focused_block self begin if target_block begin set tuple x y z = target_block call glPushAttrib GL_ENABLE_BIT comment glLineStipple(1, 0x17AF) comment glEnable(GL_LINE_STIPPLE) set vertex_data = call cube_vertices x y z 0.51 call glColor3d 0 0 0 call glPolygonMode GL_FRONT_AND_BACK GL_LINE call draw 24 GL...
def draw_focused_block(self): if self.master.target_block: x, y, z = self.master.target_block glPushAttrib(GL_ENABLE_BIT) # glLineStipple(1, 0x17AF) # glEnable(GL_LINE_STIPPLE) vertex_data = cube_vertices(x, y, z, 0.51) glColor3d(0, 0, 0) ...
Python
nomic_cornstack_python_v1
while n != 0 begin set tuple origin_x origin_y = map int split input for i in range n begin set tuple x y = map int split input if x == origin_x or y == origin_y begin print string divisa end else if x > origin_x and y > origin_y begin print string NE end else if x > origin_x and y < origin_y begin print string SE end ...
while n != 0: origin_x, origin_y = map(int, input().split()) for i in range(n): x, y = map(int, input().split()) if x == origin_x or y == origin_y: print("divisa") elif x > origin_x and y > origin_y: print("NE") elif x > origin_x and y < origin_y: print("SE") elif x < origin_x and y > or...
Python
zaydzuhri_stack_edu_python
function point_from_angle_and_distance self angle distance method=string GEODESCIC begin return call _binary_op_geo name=string point_from_angle_and_distance left=data keyword dict string angle angle ; string distance distance ; string method method end function
def point_from_angle_and_distance(self, angle, distance, method='GEODESCIC'): return _binary_op_geo(name='point_from_angle_and_distance', left=self.data, **{'angle' : angle, 'distance' : distance, ...
Python
nomic_cornstack_python_v1
function _inherit_from context uri calling_uri begin if uri is none begin return none end set template = call _lookup_template context uri calling_uri set self_ns = context at string self set ih = self_ns while inherits is not none begin set ih = inherits end set lclcontext = call locals_ dict string next ih set inheri...
def _inherit_from(context, uri, calling_uri): if uri is None: return None template = _lookup_template(context, uri, calling_uri) self_ns = context['self'] ih = self_ns while ih.inherits is not None: ih = ih.inherits lclcontext = context.locals_({'next':ih}) ih.inheri...
Python
nomic_cornstack_python_v1
function my_widgets begin set widgets = list set user = none try begin set user_email = get session string user_email set user = call find_by_email user_email if user is none begin error string widget.py::my_widgets string ERROR: invalid state - no user record for user_email: + user_email call flash string Please sign...
def my_widgets(): widgets = [] user = None try: user_email = session.get('user_email') user = db_users.find_by_email(user_email) if user is None: log.error('widget.py::my_widgets', 'ERROR: invalid state - no user record for user_email: ' + user_email) fla...
Python
nomic_cornstack_python_v1
function func begin pass end function
def func(): pass
Python
nomic_cornstack_python_v1
function can_be_deployed self can_be_deployed begin set _can_be_deployed = can_be_deployed end function
def can_be_deployed(self, can_be_deployed): self._can_be_deployed = can_be_deployed
Python
nomic_cornstack_python_v1
function reset self num_batches num_samples begin pass end function
def reset(self, num_batches: int, num_samples: int) -> None: pass
Python
nomic_cornstack_python_v1
function test_invalid_serializer_with_pk self begin set record = get Policy uuid set serializer = call PolicySerializer record assert equal call valid uuid false end function
def test_invalid_serializer_with_pk(self): record = Policy.get(self.uuid) serializer = PolicySerializer(record) self.assertEqual(serializer.valid(self.uuid), False)
Python
nomic_cornstack_python_v1