code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment %% import import cv2 from PIL import Image import numpy as np comment %% load original image set img = open string ../../ImageProcessing100Wen/Question_21_30/imori.jpg set img_arr = array img print shape comment %% function interpolate img ratio=1.5 method=string nearest begin set d_size = tuple integer shape a...
# %% import import cv2 from PIL import Image import numpy as np # %% load original image img = Image.open("../../ImageProcessing100Wen/Question_21_30/imori.jpg") img_arr = np.array(img) print(img_arr.shape) # %% def interpolate(img, ratio=1.5, method="nearest"): d_size = (int(img.shape[0] * ratio), int(img.shape...
Python
zaydzuhri_stack_edu_python
function strip_indentation_whitespace text begin set stripped_lines = list comprehension left strip line for line in split text b'\n' return join b'\n' stripped_lines end function
def strip_indentation_whitespace(text): stripped_lines = [line.lstrip() for line in text.split(b"\n")] return b"\n".join(stripped_lines)
Python
nomic_cornstack_python_v1
function decimalToBinary decimal begin set binary = 0 set i = 1 while decimal != 0 begin set remainder = decimal % 2 set binary = binary + remainder * i set i = i * 10 set decimal = decimal // 2 end return binary end function function isPrime n begin if n == 1 or n == 0 begin return false end else begin set c = 0 for i...
def decimalToBinary(decimal): binary=0 i=1 while decimal!=0: remainder=decimal%2 binary=binary+remainder*i i=i*10 decimal=decimal//2 return binary def isPrime(n): if n==1 or n==0: return False else: c=0 for i in range(2,n+1): if n%i==0: c+=1 if c==1: return True else: return False ...
Python
zaydzuhri_stack_edu_python
import json from haversine import haversine as h import argparse function load_data filepath begin with open filepath string r encoding=string utf8 as file begin return load json file end end function function get_biggest_bar bars begin return max bars key=lambda x -> x at string properties at string Attributes at stri...
import json from haversine import haversine as h import argparse def load_data(filepath): with open(filepath, 'r', encoding='utf8') as file: return json.load(file) def get_biggest_bar(bars): return max(bars, key=lambda x: x['properties']['Attributes']['SeatsCount']) def get_smallest_bar(bars): ...
Python
zaydzuhri_stack_edu_python
function testSingleton self begin assert equal call id res_mgr call id call ReservationManager end function
def testSingleton(self): self.assertEqual(id(self.res_mgr), id(ReservationManager()))
Python
nomic_cornstack_python_v1
function main begin call init_node string ik_pick_and_place_demo comment meters set hover_distance = 0.1 comment Define offset - original table sdf was 0.82 for base(0.04) + column(0.04) + surface(0.74) set off = 0.095 comment Start Pose for left arm set left_pose = call Pose set x = 0.589679836383 set y = 0.1833117697...
def main(): rospy.init_node("ik_pick_and_place_demo") hover_distance = 0.1 # meters # Define offset - original table sdf was 0.82 for base(0.04) + column(0.04) + surface(0.74) off = 0.095 # Start Pose for left arm left_pose = Pose() left_pose.position.x = 0.589679836383 left_pose.posi...
Python
nomic_cornstack_python_v1
import random , math function je_v_mejah x y xmax ymax begin return x >= 0 and y >= 0 and x < xmax and y < ymax end function function preveri_okoli xne yne x y begin for i in range yne - 1 yne + 2 begin for j in range xne - 1 xne + 2 begin if y == i and x == j begin return true end end end return false end function cla...
import random, math def je_v_mejah(x, y, xmax, ymax): return x >= 0 and y >= 0 and x < xmax and y < ymax def preveri_okoli(xne, yne, x, y): for i in range (yne - 1, yne + 2): for j in range(xne - 1, xne + 2): if (y == i and x == j): return True return False class P...
Python
zaydzuhri_stack_edu_python
import logging import utilities.custom_logger as cl from base.selenium_driver import SeleniumDriver from base.basepage import BasePage class Login_page extends BasePage begin string All these locators and log is a class property ,it wont change with every page,(until we want to do),so making it s a class property.(stat...
import logging import utilities.custom_logger as cl from base.selenium_driver import SeleniumDriver from base.basepage import BasePage class Login_page(BasePage): ''' All these locators and log is a class property ,it wont change with every page,(until we want to do),so making it s a class property.(stat...
Python
zaydzuhri_stack_edu_python
import pickle , gzip , numpy , urllib.request , json , sagemaker , os from sagemaker import KMeans comment constants comment TODO Input Bucket Name set BUCKET = string set OUTPUT_PATH = format string s3://{}/hands-on/mnist-kmeans/output BUCKET comment TODO Input IAM Role set ROLE = string set ENDPOINT_NAME = string m...
import pickle, gzip, numpy, urllib.request, json, sagemaker, os from sagemaker import KMeans # constants BUCKET = "" # TODO Input Bucket Name OUTPUT_PATH = "s3://{}/hands-on/mnist-kmeans/output".format(BUCKET) ROLE = "" # TODO Input IAM Role ENDPOINT_NAME = "mnist-kmeans-ec2-jhy" def show_image(arr): pixels = arr.r...
Python
zaydzuhri_stack_edu_python
function canonical_url self begin set url = call text if find url string ? > - 1 begin return url at slice : find url string ? : end else begin return url end end function
def canonical_url(self): url = self.element.children('link[type="html"]').text() if url.find('?') > -1: return url[:url.find('?')] else: return url
Python
nomic_cornstack_python_v1
function procExists self procname begin acquire semaphore comment refresh process data if necessary call _checkCache comment count number of occurrences of 'procname' set count = 0 for i in list begin set command = comdname if command == procname or procname == procname begin set count = count + 1 end end release semap...
def procExists(self, procname): self.semaphore.acquire() self._checkCache() # refresh process data if necessary count = 0 # count number of occurrences of 'procname' for i in self.list: command = i.comdname if command == procname or i.procn...
Python
nomic_cornstack_python_v1
function __init__ self init=none data=none dq=none err=none dq_def=none **kwargs begin call __init__ init=init data=data dq=dq err=err dq_def=dq_def keyword kwargs comment Data type is last frame. set reftype = string LASTFRAME set model_type = call get_my_model_type __name__ if model_type is not none begin set model_t...
def __init__(self, init=None, data=None, dq=None, err=None, dq_def=None, **kwargs): super(MiriLastFrameModel, self).__init__(init=init, data=data, dq=dq, err=err, dq_def=dq_def, **kwargs) ...
Python
nomic_cornstack_python_v1
set l = eval input string Enter list: print l append l eval input string Enter a value to add in the list: print string After adding the list is: l remove l eval input string Enter a value to remove from the list: print string After removing the list is: l print string The largest number is: max l print string The smal...
l=eval(input('Enter list:')) print(l) l.append(eval(input('Enter a value to add in the list:'))) print('After adding the list is:',l) l.remove(eval(input('Enter a value to remove from the list:'))) print('After removing the list is:',l) print('The largest number is:',max(l)) print('The smallest number is:',min(l...
Python
zaydzuhri_stack_edu_python
function twos_comp val bits begin comment if sign bit is set e.g., 8bit: 128-255 if val ? 1 ? bits - 1 != 0 begin comment compute negative value set val = val - 1 ? bits end comment return positive value as is return val end function
def twos_comp(val, bits): if (val & (1 << (bits - 1))) != 0: # if sign bit is set e.g., 8bit: 128-255 val = val - (1 << bits) # compute negative value return val # return positive value as is
Python
nomic_cornstack_python_v1
function getBuildNumber self requestContext begin return call build or string end function
def getBuildNumber(self, requestContext): return self.service.build() or ""
Python
nomic_cornstack_python_v1
comment Python program to demonstrate working comment of map. comment Return double of n function addition n begin return n + n end function comment We double all numbers using map() set numbers = tuple 1 2 3 4 set result = map addition numbers print list result comment Double all numbers using map and lambda set numbe...
# Python program to demonstrate working # of map. # Return double of n def addition(n): return n + n # We double all numbers using map() numbers = (1, 2, 3, 4) result = map(addition, numbers) print(list(result)) # Double all numbers using map and lambda numbers = (1, 2, 3, 4) result = map(lambda ...
Python
zaydzuhri_stack_edu_python
function getAllocated self begin set raw = get schema at string allocated self return call convert raw end function
def getAllocated(self): raw = self.schema['allocated'].get(self) return self.convert(raw)
Python
nomic_cornstack_python_v1
if hungry == string yes or string Yes or string Y or string y begin print string Eat something end else begin print string Do your homework end
if hungry=="yes" or "Yes" or 'Y' or 'y': print("Eat something") else: print("Do your homework")
Python
zaydzuhri_stack_edu_python
function test_script_path_components self begin set tuple dirname fname = call script_path_components string /test/test_file.py assert equal dirname string /test assert equal fname string test_file.py end function
def test_script_path_components(self): dirname, fname=script_path_components('/test/test_file.py') self.assertEqual(dirname,'/test') self.assertEqual(fname,'test_file.py')
Python
nomic_cornstack_python_v1
import time import http.client import json import concurrent.futures import logging set connection = call HTTPSConnection string swapi.dev class ListItem extends object begin string Custom class for the required display parameters function __init__ self character begin set name = character at string name set gender = c...
import time import http.client import json import concurrent.futures import logging connection = http.client.HTTPSConnection("swapi.dev") class ListItem(object): """ Custom class for the required display parameters """ def __init__(self, character): self.name = character["name"] self.g...
Python
zaydzuhri_stack_edu_python
function aap_to_bp ant1 ant2 pol begin string Create a basepol from antenna numbers and a CASA polarization code. if ant1 < 0 begin raise call ValueError string first antenna is below 0: %s % ant1 end if ant2 < ant1 begin raise call ValueError string second antenna is below first: %s % ant2 end if pol < 1 or pol > 12 b...
def aap_to_bp (ant1, ant2, pol): """Create a basepol from antenna numbers and a CASA polarization code.""" if ant1 < 0: raise ValueError ('first antenna is below 0: %s' % ant1) if ant2 < ant1: raise ValueError ('second antenna is below first: %s' % ant2) if pol < 1 or pol > 12: ...
Python
jtatman_500k
function _convert_to_seconds self time begin return 3600 * time at 0 + 60 * time at 1 + time at 0 end function
def _convert_to_seconds(self, time): return 3600*time[0] + 60*time[1] + time[0]
Python
nomic_cornstack_python_v1
from unittest import main , mock , TestCase from os import urandom function simple_urandom length begin return string f * length end function class TestRandom extends TestCase begin decorator patch string __main__.urandom side_effect=simple_urandom function test_urandom self urandom_function begin assert call urandom 5...
from unittest import main, mock, TestCase from os import urandom def simple_urandom(length): return 'f' * length class TestRandom(TestCase): @mock.patch('__main__.urandom', side_effect=simple_urandom) def test_urandom(self, urandom_function): assert urandom(5) == 'fffff' @mock.patch('__main__.ura...
Python
zaydzuhri_stack_edu_python
function log_uniform low high begin set log_low = log low set log_high = log high set log_rval = uniform log_low log_high set rval = decimal exp log_rval return rval end function
def log_uniform(low, high): log_low = np.log(low) log_high = np.log(high) log_rval = np.random.uniform(log_low, log_high) rval = float(np.exp(log_rval)) return rval
Python
nomic_cornstack_python_v1
import string comment Open the file in read mode set text = open string What is Python.txt string r comment Create an empty dictionary set dictionary_of_all_words = dictionary comment Loop through each line of the file for line in text begin comment Remove the leading spaces and newline character set line = strip line ...
import string # Open the file in read mode text = open("What is Python.txt", "r") # Create an empty dictionary dictionary_of_all_words = dict() # Loop through each line of the file for line in text: # Remove the leading spaces and newline character line = line.strip() # Convert the characters in ...
Python
zaydzuhri_stack_edu_python
comment Feature selection step code import time , datetime as dt import numpy as np , pandas as pd from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_selection import SelectFromModel from sklearn.m...
# Feature selection step code import time, datetime as dt import numpy as np, pandas as pd from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_selection import SelectFromModel from sklearn....
Python
zaydzuhri_stack_edu_python
comment This is a sample Python script. comment Press Umschalt+F10 to execute it or replace it with your code. comment Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import cv2 import pytesseract comment after the installation you have to set the path directly to the ex...
# This is a sample Python script. # Press Umschalt+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import cv2 import pytesseract # after the installation you have to set the path directly to the executable (Windows) py...
Python
zaydzuhri_stack_edu_python
class Node begin function __init__ self data begin set data = data set left = none set right = none end function end class comment https://www.techseries.dev/products/coderpro/categories/1831147/posts/6231427 comment Time: O(n) comment Space: O(n) function check_binary_search_tree_ root begin function check_binary_sear...
class Node: def __init__(self, data): self.data = data self.left = None self.right = None # https://www.techseries.dev/products/coderpro/categories/1831147/posts/6231427 # Time: O(n) # Space: O(n) def check_binary_search_tree_(root): def check_binary_search_tree(node, lower, upper): ...
Python
zaydzuhri_stack_edu_python
function post_state begin if not call get_json begin return call make_response call jsonify dict string error string Not a JSON 400 end if string name not in call get_json begin return call make_response call jsonify dict string error string Missing name 400 end set state = call State keyword call get_json save return ...
def post_state(): if not request.get_json(): return make_response(jsonify({'error': 'Not a JSON'}), 400) if 'name' not in request.get_json(): return make_response(jsonify({'error': 'Missing name'}), 400) state = State(**request.get_json()) state.save() return make_response(jsonify(st...
Python
nomic_cornstack_python_v1
function _pad_image self img pad_width=10 begin set padded_img = zeros tuple shape at 0 + pad_width * 2 shape at 1 + pad_width * 2 set padded_img at tuple slice pad_width : - pad_width : slice pad_width : - pad_width : = img return padded_img end function
def _pad_image(self, img: ndarray, pad_width: int = 10) -> ndarray: self.padded_img = np.zeros( (img.shape[0] + pad_width*2, img.shape[1]+pad_width*2)) self.padded_img[pad_width:-pad_width, pad_width:-pad_width] = img return self.padded_img
Python
nomic_cornstack_python_v1
class MethodCall extends object begin set method_name : str set arguments : list function __init__ self method_name arguments begin set method_name = method_name set arguments = arguments end function function to_dict self begin set _dict = dict string method_name method_name set _dict_arguments = list for argument in...
class MethodCall(object): method_name: str arguments: list def __init__(self, method_name: str, arguments: list): self.method_name = method_name self.arguments = arguments def to_dict(self): _dict = {'method_name': self.method_name} _dict_arguments = [] for argu...
Python
zaydzuhri_stack_edu_python
function test_is_select_query begin set client = call Client assert call _is_select_query string select 1 assert call _is_select_query string SELECT 1 assert call _is_select_query string SELECT `insert`, `update`, from nothing end function
def test_is_select_query(): client = Client() assert client._is_select_query('select 1') assert client._is_select_query(' SELECT 1') assert client._is_select_query('SELECT `insert`, `update`, from nothing')
Python
nomic_cornstack_python_v1
function _set_lettercase string begin return if expression boolean any generator expression is lower c for c in string then lower string else upper string end function
def _set_lettercase(string: str) -> str: return ( string.lower() if bool(any(c.islower() for c in string)) else string.upper() )
Python
nomic_cornstack_python_v1
function number_of_subscribers subreddit begin set url_rsubs = format string https://api.reddit.com/r/{}/about subreddit set headers = dict string User-Agent string Python3 set response = get requests url_rsubs headers=headers allow_redirects=false if string response != string <Response [200]> begin return 0 end set r_...
def number_of_subscribers(subreddit): url_rsubs = "https://api.reddit.com/r/{}/about".format(subreddit) headers = {'User-Agent': 'Python3'} response = requests.get(url_rsubs, headers=headers, allow_redirects=False) if str(response) != "<Response [200]>": return 0 ...
Python
nomic_cornstack_python_v1
function annotate self begin set annotations = dict set text_keys = list string fontsize string family set text_config = filter keys=text_keys prefix=string text_ comment suptitle set suptitle = get config string suptitle if suptitle is not none begin set suptitle_config = filter prefix=string suptitle_ update suptitl...
def annotate(self): annotations = {} text_keys = ['fontsize', 'family'] text_config = self.config.filter(keys=text_keys, prefix='text_') # suptitle suptitle = self.config.get('suptitle') if suptitle is not None: suptitle_config = self.config.filter(prefix='s...
Python
nomic_cornstack_python_v1
function text_visual texts scores img_h=400 img_w=600 threshold=0.0 font_path=string ./doc/simfang.ttf begin if scores is not none begin assert length texts == length scores msg string The number of txts and corresponding scores must match end function create_blank_img begin set blank_img = ones shape=list img_h img_w ...
def text_visual(texts, scores, img_h=400, img_w=600, threshold=0., font_path="./doc/simfang.ttf"): if scores is not None: assert len(texts) == len( scores), "The number of txts and corresponding scores must match" ...
Python
nomic_cornstack_python_v1
from urllib.request import urlopen from bs4 import BeautifulSoup set html = url open string https://vip.mk.co.kr/newSt/rate/item_all.php print html set bs = call BeautifulSoup html string html.parser set tds = select bs string .st2 for td in tds begin set s_code = get find td list string a string title set s_name = tex...
from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen("https://vip.mk.co.kr/newSt/rate/item_all.php") print(html) bs = BeautifulSoup(html, "html.parser") tds = bs.select(".st2") for td in tds: s_code = td.find(["a"]).get("title") s_name = td.text s_price = td.parent.select("...
Python
zaydzuhri_stack_edu_python
comment code learning practiced by desmond comment date 2019.11.16 string 输入 一 行字 符, 分别统计出其中英文字母 、 空格、数字和其他字符的个数 set string = string input string plz input ur string print string set space = 0 set letters = 0 set else_str = 0 for i in string begin if i == string begin set space = space + 1 end else if i >= string A an...
# code learning practiced by desmond # date 2019.11.16 ''' 输入 一 行字 符, 分别统计出其中英文字母 、 空格、数字和其他字符的个数 ''' string = str(input("plz input ur string")) print(string) space = 0 letters = 0 else_str = 0 for i in string: if i == " ": space = space +1 elif i >= "A" and i <= "Z" or i >= "a" and i <= "z": ...
Python
zaydzuhri_stack_edu_python
function check_input_matches_expected_output in_ out begin Ellipsis end function
def check_input_matches_expected_output(in_, out): ...
Python
nomic_cornstack_python_v1
import boto3 , os , json , sys , math , cv2 , pprint from pathlib import Path set client = call client string rekognition set FILE_NAME = string /tmp/rekogwebcam.png function get_image begin set camera = call VideoCapture 0 call raw_input string Press Enter to capture picture... comment 30 frames are discarded to let t...
import boto3, os, json, sys, math, cv2, pprint from pathlib import Path client = boto3.client('rekognition') FILE_NAME = "/tmp/rekogwebcam.png" def get_image(): camera = cv2.VideoCapture(0) raw_input("Press Enter to capture picture...") # 30 frames are discarded to let the camera adjust brightness ...
Python
zaydzuhri_stack_edu_python
from decimal import Decimal as _Decimal from datetime import datetime import registry class TypeBase extends object begin function __init__ self default=none begin set default = default end function function validate self value begin raise call NotImplementedError end function function parse self xml begin raise call N...
from decimal import Decimal as _Decimal from datetime import datetime import registry class TypeBase(object): def __init__(self, default=None): self.default = default def validate(self, value): raise NotImplementedError() def parse(self, xml): raise NotImplementedError() def default_value(self): try:...
Python
zaydzuhri_stack_edu_python
class Element begin function __init__ self value begin set value = value set next = none end function end class class DLL begin function __init__ self head=none begin set head = head end function function append self value begin set element = call Element value if head is none begin set head = element end else begin se...
class Element(): def __init__(self, value): self.value = value self.next = None class DLL(): def __init__(self, head=None): self.head = head def append(self, value): element = Element(value) if self.head is None: self.head = element else: ...
Python
zaydzuhri_stack_edu_python
function print_pos self byte_offset=- 1 begin if _debug_level > 3 begin if has attribute self string ensemble begin set k = k end else begin set k = 0 end print string pos: %d, pos_: %d, nbyte: %d, k: %d, byte_offset: %d % tuple tell f _pos _nbyte k byte_offset end end function
def print_pos(self, byte_offset=-1): if self._debug_level > 3: if hasattr(self, 'ensemble'): k = self.ensemble.k else: k = 0 print(' pos: %d, pos_: %d, nbyte: %d, k: %d, byte_offset: %d' % (self.f.tell(), self._pos, self._nby...
Python
nomic_cornstack_python_v1
class A begin function do_something self begin print string Method defined in: A end function end class class B extends A begin function do_something self begin print string Method defined in: B call do_something end function end class class C extends A begin function do_something self begin print string Method defined...
class A: def do_something(self): print("Method defined in: A") class B(A): def do_something(self): print("Method defined in: B") super().do_something() class C(A): def do_something(self): print("Method defined in: C") class D(B,C): def do_something(self): print("Method defined in: ...
Python
zaydzuhri_stack_edu_python
while 1 begin set line1 = read line input1 set line2 = read line input2 if not line1 or not line2 begin break end set line1 = strip line1 string set line2 = strip line2 string set line1 = strip line1 string set line2 = strip line2 string if length line1 > 0 or length line2 > 0 begin set token_count = token_count + 1 en...
while 1: line1 = input1.readline() line2 = input2.readline() if not line1 or not line2: break line1 = line1.strip('\n') line2 = line2.strip('\n') line1 = line1.strip(' ') line2 = line2.strip(' ') if len(line1) > 0 or len(line2) > 0: token_count = token_count + 1
Python
zaydzuhri_stack_edu_python
function delete path auth=false accepted_status_codes=false begin if auth begin call authenticate set headers = dict string X-HuutoApiToken call token end else begin set headers = dict end comment Avoiding the "mutable dict/list funtion argument" issue by not defining the default in the function def if not accepted_st...
def delete(path, auth=False, accepted_status_codes=False): if auth: authenticate() headers = {'X-HuutoApiToken': token()} else: headers = {} # Avoiding the "mutable dict/list funtion argument" issue by not defining the default in the function def if not accepted_status_codes: ...
Python
nomic_cornstack_python_v1
function pc_noutput_items_var self begin return call atsc_fpll_sptr_pc_noutput_items_var self end function
def pc_noutput_items_var(self): return _atsc_swig.atsc_fpll_sptr_pc_noutput_items_var(self)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import pandas as pd set df = read csv string new.csv encoding=string gbk comment 只使用2016年之后的数据 set df = df at df at string tradeTime > string 2015-12-31 set df = drop df list string ladderRatio string price string url string id string Cid string tradeTime string DOM string followers string...
# -*- coding: utf-8 -*- import pandas as pd df = pd.read_csv('new.csv', encoding='gbk') df = df[df['tradeTime']>'2015-12-31'] # 只使用2016年之后的数据 df = df.drop(['ladderRatio','price','url', 'id', 'Cid', 'tradeTime', 'DOM','followers','district','communityAverage'], axis = 1) df = df.dropna(axis = 0) # floor 高 中 低 底 顶 fl...
Python
zaydzuhri_stack_edu_python
string # Name: expense_manager.py # Aim: To implement functions for the Expense Manager project. This will be used in main_ui.py # Start date: 14.June 2021 # End date: --- # Library/Frameworks used: PyQt5, Pandas, Matplotlib import sys from PyQt5 import QtGui , QtCore from PyQt5.QtWidgets import QWidget , QApplication ...
''' # Name: expense_manager.py # Aim: To implement functions for the Expense Manager project. This will be used in main_ui.py # Start date: 14.June 2021 # End date: --- # Library/Frameworks used: PyQt5, Pandas, Matplotlib ''' import sys from PyQt5 import QtGui, QtCore from PyQt5.QtWidgets import QWidget, QApplication, ...
Python
zaydzuhri_stack_edu_python
function set_value self attribute_name value classifier=none begin if is_deleted begin raise call CException string can't set value ' { attribute_name } ' on deleted { call _get_kind_str } end call set_var_value self class_path attribute_values attribute_name value ATTRIBUTE_VALUE classifier end function
def set_value(self, attribute_name, value, classifier=None): if self.is_deleted: raise CException(f"can't set value '{attribute_name!s}' on deleted {self._get_kind_str()!s}") set_var_value(self, self.classifier.class_path, self.attribute_values, attribute_name, value, V...
Python
nomic_cornstack_python_v1
import cv2 import numpy as np from Transform import Undistort function highlight_cubes image begin set image = call rot90 image 2 return call cvtColor image COLOR_BGR2YCrCb at tuple slice : : slice : : 2 end function class USB extends object begin function __init__ self port calibration_path begin set film = call...
import cv2 import numpy as np from Transform import Undistort def highlight_cubes(image): image = np.rot90(image, 2) return cv2.cvtColor(image, cv2.COLOR_BGR2YCrCb)[:,:,2] class USB(object): def __init__(self, port, calibration_path): self.film = cv2.VideoCapture(port) self.film.set(3, 192...
Python
zaydzuhri_stack_edu_python
import re class ExtractHRef extends object begin function __init__ self f=string begin set filename = f set data_preped = false end function function set_filename self f begin set filename = f end function function prep_data self begin set data_preped = true set fHandle = open filename set pattern = string (http[s]?://...
import re class ExtractHRef(object): def __init__(self, f=""): self.filename=f self.data_preped=False def set_filename(self, f): self.filename=f def prep_data(self): self.data_preped = True fHandle = open(self.filename) pattern = r'(http[s]?://[^\s\)\]\"]+)...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 import numpy as np import pandas as pd import os import time set MAIN_FILE = string Data_Entry_2017.csv set SAVED_FILE = string Data_Entry_Training.csv seed 1234 comment columns for each desease set pathology_list = list string Cardiomegaly string Emphysema string Effusion string Hernia string Nod...
# coding: utf-8 import numpy as np import pandas as pd import os import time MAIN_FILE='Data_Entry_2017.csv' SAVED_FILE='Data_Entry_Training.csv' np.random.seed(1234) #columns for each desease pathology_list = ['Cardiomegaly','Emphysema','Effusion','Hernia','Nodule','Pneumothorax','Atelectasis','Pleural_Thickenin...
Python
zaydzuhri_stack_edu_python
function _load_default_environments self tools begin import acre set environ at string PLATFORM = lower call system set tools_env = call get_tools tools set pype_paths_env = dictionary for tuple key value in items dictionary environ begin if starts with key string PYPE_ begin set pype_paths_env at key = value end end s...
def _load_default_environments(self, tools): import acre os.environ['PLATFORM'] = platform.system().lower() tools_env = acre.get_tools(tools) pype_paths_env = dict() for key, value in dict(os.environ).items(): if key.startswith('PYPE_'): pype_paths_env...
Python
nomic_cornstack_python_v1
import re , time from selenium.webdriver import Chrome , ChromeOptions comment Get your chromedriver at https://sites.google.com/a/chromium.org/chromedriver/ set subs_file = string subscription_manager.xml comment Set your profile that you want to use, visit "chrome://version" and check Profile Path set chrome_profile ...
import re, time from selenium.webdriver import Chrome, ChromeOptions ## Get your chromedriver at https://sites.google.com/a/chromium.org/chromedriver/ subs_file = "subscription_manager.xml" chrome_profile = "Profile 1" # Set your profile that you want to use, visit "chrome://version" and check Profile Path chrome_us...
Python
zaydzuhri_stack_edu_python
function get_hikedetails_by_id hike_id begin return get query hike_id end function
def get_hikedetails_by_id(hike_id): return Hike.query.get(hike_id)
Python
nomic_cornstack_python_v1
function ideal_gas_law T Vm begin comment L*atm/K/mol set R = 0.08205 return R * T / Vm end function
def ideal_gas_law(T, Vm): R = 0.08205 #L*atm/K/mol return R * T / Vm
Python
nomic_cornstack_python_v1
function add_bounding_box self bounding_box fill_auto_fields=true timestamp=none begin append bounding_boxes bounding_box if fill_auto_fields begin call fill_auto_fields bounding_box end if timestamp begin set timestamp = timestamp end end function
def add_bounding_box(self, bounding_box, fill_auto_fields=True, timestamp=None): self.bounding_boxes.append(bounding_box) if fill_auto_fields: self.fill_auto_fields(bounding_box) if timestamp: bounding_box.timestamp = timestamp
Python
nomic_cornstack_python_v1
function describe cls pre_models begin info string analyzing given pre models... if not pre_models begin return tuple none none none end set existing_entities = list set new_entities = list set to_be_remapped_entities = list set invalids = list for obj in pre_models begin comment validity must be checked first so t...
def describe(cls, pre_models): logger.info("analyzing given pre models...") if not pre_models: return None, None, None existing_entities = [] new_entities = [] to_be_remapped_entities = [] invalids = [] for obj in pre_models: if not obj.is_...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env /Library/Frameworks/Python.framework/Versions/2.5/bin/python comment encoding: utf-8 string sfaopdq.py Created by Tom Quackenbush on 2009-06-24. import sys import os import random import time import pygame from pygame.locals import * from ship import Ship from shot import Shot from alien import Al...
#!/usr/bin/env /Library/Frameworks/Python.framework/Versions/2.5/bin/python # encoding: utf-8 """ sfaopdq.py Created by Tom Quackenbush on 2009-06-24. """ import sys import os import random import time import pygame from pygame.locals import * from ship import Ship from shot import Shot from alien import Alien from s...
Python
zaydzuhri_stack_edu_python
import csv import sqlite3 function trim lst begin return list comprehension strip string for string in lst if string not in tuple none string end function function find_by_name lst name begin return next generator expression obj for obj in lst if lower obj at string name == lower name none end function if __name__ == ...
import csv import sqlite3 def trim(lst): return [string.strip() for string in lst if string not in (None, '')] def find_by_name(lst, name): return next((obj for obj in lst if obj['name'].lower() == name.lower()), None) if __name__ == '__main__': with open('items.csv') as f: reader = csv.DictRe...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import os from settings import logging import settings import sqlite3 import json function is_new_db begin return not exists path DB_FILE_NAME end function function create_db conn begin info string Creating database set create_schema = string CREATE TABLE song_requests ( id NUMERIC PRIMARY...
# -*- coding: utf-8 -*- import os from settings import logging import settings import sqlite3 import json def is_new_db(): return not os.path.exists(settings.DB_FILE_NAME) def create_db(conn): logging.info("Creating database") create_schema = """ CREATE TABLE song_requests ( id NUMERIC P...
Python
zaydzuhri_stack_edu_python
comment The average number of comments on the last 50 posts on NASA's official Instagram account from urllib.parse import urljoin import os import requests set DOMAIN = string https://api.instagram.com/ set USERNAME = string nasa set ITEM_COUNT = 50 comment note: I've specified INSTAGRAM_TOKEN in my ~/.bash_profile set...
# The average number of comments on the last 50 posts on NASA's official Instagram account from urllib.parse import urljoin import os import requests DOMAIN = 'https://api.instagram.com/' USERNAME = 'nasa' ITEM_COUNT = 50 # note: I've specified INSTAGRAM_TOKEN in my ~/.bash_profile atts = {'access_token': os.environ.ge...
Python
zaydzuhri_stack_edu_python
function calculate_daily_statistics m_bal price update_stats begin global STATS set today = dict string mBal m_bal ; string price price if STATS is none begin if update_stats and time > time begin set STATS = call Stats integer string format time today string %Y%j today call persist_statistics end return today end if u...
def calculate_daily_statistics(m_bal: float, price: float, update_stats: bool): global STATS today = {'mBal': m_bal, 'price': price} if STATS is None: if update_stats and datetime.datetime.utcnow().time() > datetime.datetime(2012, 1, 17, 12, 1).time(): STATS = Stats(int(datetime.date.to...
Python
nomic_cornstack_python_v1
class Solution begin function exist self board word begin set visit = set function dfs i j idx begin if idx >= length word begin return true end if i >= length board or j >= length board at 0 or i < 0 or j < 0 begin return false end if tuple i j in visit begin return false end if board at i at j == word at idx begin ad...
class Solution: def exist(self, board: list, word: str) -> bool: visit = set() def dfs(i, j, idx) -> bool: if idx >= len(word): return True if i >= len(board) or j >= len(board[0]) or i < 0 or j < 0: return False if (i, j) in visit:...
Python
zaydzuhri_stack_edu_python
function getTicket begin global loadedTicket try begin set loadedTicket = call fetchTicket integer get ticketidVar end except ValueError begin call incrementRequestsSentCount return call showerror string Error string Ticket ID is not a number end call incrementRequestsSentCount if status != string closed begin call con...
def getTicket(): global loadedTicket try: loadedTicket = backend.fetchTicket(int(ticketidVar.get())) except ValueError: incrementRequestsSentCount() return messagebox.showerror("Error", "Ticket ID is not a number") incrementRequestsSentCount() if loadedTicket.status != "close...
Python
nomic_cornstack_python_v1
function classify_tweets tweets begin set classified_tweets = list end function
def classify_tweets(tweets): classified_tweets = []
Python
jtatman_500k
function get_section_names self **options begin return list keys _configs end function
def get_section_names(self, **options): return list(self._configs.keys())
Python
nomic_cornstack_python_v1
comment import sys comment sys.setrecursionlimit(10 ** 6) comment from decorator import stop_watch comment @stop_watch function solve H begin set ans = 0 set monster = 1 while true begin set ans = ans + monster if H == 1 begin break end set H = H // 2 set monster = monster * 2 end print ans end function if __name__ == ...
# import sys # sys.setrecursionlimit(10 ** 6) # from decorator import stop_watch # # # @stop_watch def solve(H): ans = 0 monster = 1 while True: ans += monster if H == 1: break H = H // 2 monster *= 2 print(ans) if __name__ == '__main__': H = int(input()...
Python
zaydzuhri_stack_edu_python
function get_most_probable_labels proba begin comment patch for pandas<=1.1.5 if not size begin return call Series list dtype=string O end return call idxmax axis=string columns end function
def get_most_probable_labels(proba: pd.DataFrame) -> pd.Series: # patch for pandas<=1.1.5 if not proba.size: return pd.Series([], dtype='O') return proba.idxmax(axis='columns')
Python
nomic_cornstack_python_v1
function privmsg self target message begin string Sends a PRIVMSG to someone. Required arguments: * target - Who to send the message to. * message - Message to send. with lock begin call send string PRIVMSG + target + string : + message if call readable begin set msg = call _recv expected_replies=tuple string 301 if ms...
def privmsg(self, target, message): """ Sends a PRIVMSG to someone. Required arguments: * target - Who to send the message to. * message - Message to send. """ with self.lock: self.send('PRIVMSG ' + target + ' :' + message) if self.readable...
Python
jtatman_500k
import sys import meta_features as mf import numpy as np import os from sklearn.externals import joblib class MotionPrimitive begin set SIGNALS = dict string STARTED 1 ; string CLOSED 0 ; string EMPTY - 1 function __init__ self init_time threshold=0.03 begin set buffer = list set threshold = threshold set current_stat...
import sys import meta_features as mf import numpy as np import os from sklearn.externals import joblib class MotionPrimitive(): SIGNALS = {'STARTED': 1, 'CLOSED': 0, 'EMPTY': -1} def __init__(self, init_time, threshold=0.03): self.buffer = [] self.threshold = threshold self.current_s...
Python
zaydzuhri_stack_edu_python
input set A = list map int split input set B = list map int split input print sum generator expression all generator expression x % a == 0 for a in A and all generator expression b % x == 0 for b in B for x in range 1 max A + B + 1
input() A=list(map(int,input().split())) B=list(map(int,input().split())) print(sum(all(x%a==0 for a in A) and all(b%x==0 for b in B) for x in range(1, max(A+B)+1)))
Python
zaydzuhri_stack_edu_python
from pandas import * from numpy import * from random import * import datetime from matplotlib.pyplot import * import sys set TRAIN_ON_EVERYTHING = true comment Read dates function readdate s begin return string parse time s string %d/%m/%Y end function comment Read in file set data = read csv string FIFA0212.csv parse_...
from pandas import * from numpy import * from random import * import datetime from matplotlib.pyplot import * import sys TRAIN_ON_EVERYTHING = True #Read dates def readdate(s): return datetime.datetime.strptime(s, '%d/%m/%Y') #Read in file data = read_csv('FIFA0212.csv',parse_dates=True) #Throw away unplayed ma...
Python
zaydzuhri_stack_edu_python
function _to_northern_grid_location self scalararray weights_in=none weights_out=none begin set average = lambda xarr -> call shift y=- 1 + xarr / 2.0 if weights_in is none begin set out = call average scalararray end else begin if weights_out is none begin set weights_out = call average weights_in end set out = call a...
def _to_northern_grid_location(self,scalararray, weights_in=None,weights_out=None): average = lambda xarr:( xarr.shift(y=-1) + xarr ) / 2. if weights_in is None: out = average(scalararray) else: if weights_out is None: wei...
Python
nomic_cornstack_python_v1
import GuessGame import MemoryGame import CurrencyRouletteGame function welcome name begin return string Hello %s and welcome to the World of Games (WoG). Here you can find many cool games to play. % name end function function CheckChoice choice begin if choice in range 1 4 begin return true end else begin return false...
import GuessGame import MemoryGame import CurrencyRouletteGame def welcome(name): return "Hello %s and welcome to the World of Games (WoG). \ Here you can find many cool games to play." % name def CheckChoice(choice): if choice in range(1,4): return True else: return False def...
Python
zaydzuhri_stack_edu_python
function setcolumns self columns begin comment Store the column titles ("raw" format) comment This is a list of white-space separated strings set __columns = columns comment Create table_column objects for col in split columns begin call addcolumn col end comment Attempt to populate the column objects if __data begin c...
def setcolumns(self, columns): # Store the column titles ("raw" format) # This is a list of white-space separated strings self.__columns = columns # Create table_column objects for col in columns.split(): self.addcolumn(col) # Attempt to populate the column o...
Python
nomic_cornstack_python_v1
function GetColumnHeaders self begin string Call IUIAutomationTablePattern::GetCurrentColumnHeaders. Return list, a list of `Control` subclasses, representing all the column headers in a table.. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclient-iuiautomationtablepattern...
def GetColumnHeaders(self) -> list: """ Call IUIAutomationTablePattern::GetCurrentColumnHeaders. Return list, a list of `Control` subclasses, representing all the column headers in a table.. Refer https://docs.microsoft.com/en-us/windows/desktop/api/uiautomationclient/nf-uiautomationclie...
Python
jtatman_500k
function post self request begin if exists filter username=data at string username begin return call Response dict string msg string A user with the same name already exists. status=202 end else begin set user = call create username=data at string username call set_password data at string password save return call Resp...
def post(self, request): if User.objects.filter(username=request.data['username']).exists(): return Response({'msg': 'A user with the same name already exists.'}, status=202) else: user = User.objects.create(username=request.data['username']) user.set_password(request.data['password']) user.save() re...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import sys function motif_count seq_name seq motif begin set count = 0 for i in range length seq begin if starts with seq at slice i : : motif begin set count = count + 1 end end end function
#!/usr/bin/env python import sys def motif_count(seq_name, seq, motif): count = 0 for i in range(len(seq)): if seq[i:].startswith(motif): count += 1
Python
zaydzuhri_stack_edu_python
comment Eric Einhaus comment Computer Algorithms comment Nondeterinistic Finite Automata comment L(MNFA1): {w | w contains all 'a's (including 0) or alternating 'ab' segments} function MNFA1 test begin comment Defining required variables and methods comment our incrementor variable set i = 0 comment Pointer boolean val...
#Eric Einhaus #Computer Algorithms #Nondeterinistic Finite Automata #L(MNFA1): {w | w contains all 'a's (including 0) or alternating 'ab' segments} def MNFA1(test): #Defining required variables and methods ################################################################################################...
Python
zaydzuhri_stack_edu_python
comment For layout function print_new_section section_no section_name begin print string -------------------- print format string #{} {} section_no section_name print string -------------------- end function comment 1 function print_list_enum list1 begin string Prints two elemnt tuples of the list1 list elements in the...
#For layout def print_new_section(section_no, section_name): print("--------------------") print("#{} {}".format(section_no, section_name)) print("--------------------") #1 def print_list_enum(list1): '''Prints two elemnt tuples of the list1 list elements in the order which they appear w...
Python
zaydzuhri_stack_edu_python
for row in range 0 length x at 0 begin set ans = list for i in x begin append ans i at row end append trans ans end print trans
for row in range(0,len(x[0])): ans = [] for i in x: ans.append(i[row]) trans.append(ans) print(trans)
Python
zaydzuhri_stack_edu_python
from sys import argv from PIL import Image set picture = open argv at 1 comment Get the size of the image set tuple width height = size comment Process every pixel for x in range width begin for y in range height begin set current_color = call getpixel tuple x y comment print(current_color) for mapping in map begin if ...
from sys import argv from PIL import Image picture = Image.open(argv[1]) # Get the size of the image width, height = picture.size # Process every pixel for x in range(width): for y in range(height): current_color = picture.getpixel( (x,y) ) # print(current_color) for mapping in map: ...
Python
zaydzuhri_stack_edu_python
function condicionesIniciales V_dada begin set condiciones_0 = dict set R = call calcularR comment Se agregan las condiciones triviales set condiciones_0 at string Yn = 0 set condiciones_0 at string Vxn = 0 comment Se agregan las condiciones no triviales set condiciones_0 at string Xn = call posicionInicialX if V_dada...
def condicionesIniciales(V_dada): condiciones_0 = {} R = calcularR() #Se agregan las condiciones triviales condiciones_0['Yn'] = 0 condiciones_0['Vxn'] = 0 #Se agregan las condiciones no triviales condiciones_0['Xn'] = posicionInicialX() if V_dada is 0: condiciones_0['Vyn'] = velocidadInicial(R) else:...
Python
nomic_cornstack_python_v1
function min_enclosing_rectangle radius x y begin if radius >= 0 begin return tuple x - radius y - radius end end function
def min_enclosing_rectangle(radius, x, y): if radius >= 0: return(x-radius, y-radius)
Python
nomic_cornstack_python_v1
function bottoms panels begin string Finds bottom lines of all panels :param panels: :return: sorted by row list of tuples representing lines (col, row , col + len, row) set bottom_lines = list comprehension tuple p at string col p at string row + p at string size_y p at string col + p at string size_x p at string row ...
def bottoms(panels): """ Finds bottom lines of all panels :param panels: :return: sorted by row list of tuples representing lines (col, row , col + len, row) """ bottom_lines = [(p['col'], p['row'] + p['size_y'], p['col'] + p['size_x'], p['row'] + p['size_y']) for p in panels] return sorted(...
Python
jtatman_500k
comment 主成分分解 comment fit_transfrom()用来降维,属于PCA对象 comment 要导入sklearn.decomposition import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn.decomposition import PCA from sklearn.decomposition import PCA set iris = call load_iris set x = data at tuple slice : : ...
##主成分分解 #fit_transfrom()用来降维,属于PCA对象 #要导入sklearn.decomposition import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import datasets from sklearn.decomposition import PCA from sklearn.decomposition import PCA iris=datasets.load_iris() x=iris.data[:,1] y=iris.data[:,2] s...
Python
zaydzuhri_stack_edu_python
function chooseAction self gameState begin set actions = call getLegalActions index string You should change this in your own agent. return random choice actions end function
def chooseAction(self, gameState): actions = gameState.getLegalActions(self.index) ''' You should change this in your own agent. ''' return random.choice(actions)
Python
nomic_cornstack_python_v1
with open string reviews.txt string r as f begin for line in f begin append data line set datalen = datalen + length line if length line < 100 begin append datashort line end if string good in line begin append datagood line end end end print length data print datalen / length data print string 小於100的留言 length datashor...
with open('reviews.txt','r') as f: for line in f: data.append(line) datalen += len(line) if len(line)<100: datashort.append(line) if 'good' in line: datagood.append(line) print(len(data)) print(datalen/len(data)) print('小於100的留言', len(datashort)) print('提到good的留言', len(datagood))
Python
zaydzuhri_stack_edu_python
string Persons and Teams model using MongoDB. Tobias Thelen, 2016 Public Domain, no rights reserved, CC-0 The model defines two classes: Persons and Teams. Usage: # create a new person p = Person(firstname="Tobias", lastname="Thelen", email="tthelen@uos.de", hobbies=["singen", "tanzen", "fröhlichsein"]) # change an att...
"""Persons and Teams model using MongoDB. Tobias Thelen, 2016 Public Domain, no rights reserved, CC-0 The model defines two classes: Persons and Teams. Usage: # create a new person p = Person(firstname="Tobias", lastname="Thelen", email="tthelen@uos.de", hobbies=["singen", "tanzen", "fröhlichsein"]) # change an att...
Python
zaydzuhri_stack_edu_python
async function list_secret_parameters_with_options_async self tmp_req runtime begin call validate_model tmp_req set request = call ListSecretParametersShrinkRequest call convert tmp_req request if not call is_unset tags begin set tags_shrink = call array_to_string_with_specified_style tags string Tags string json end s...
async def list_secret_parameters_with_options_async( self, tmp_req: oos_20190601_models.ListSecretParametersRequest, runtime: util_models.RuntimeOptions, ) -> oos_20190601_models.ListSecretParametersResponse: UtilClient.validate_model(tmp_req) request = oos_20190601_models.Li...
Python
nomic_cornstack_python_v1
comment Exploring why 4x4 grids have a spike of patterns with stroke length 11 comment Will display all 4x4 grids of stroke length 11 in 4x4_data.csv comment D.E.Budzitowski 150876 import Image , csv with open string ./analysis/3x3/3x3_data.csv as csvfile begin set reader = dict reader csvfile set savepath = string ./a...
### ## Exploring why 4x4 grids have a spike of patterns with stroke length 11 ## Will display all 4x4 grids of stroke length 11 in 4x4_data.csv ## ## D.E.Budzitowski 150876 ### import Image, csv with open("./analysis/3x3/3x3_data.csv") as csvfile: reader = csv.DictReader(csvfile) savepath = "./analysis/3x3_st...
Python
zaydzuhri_stack_edu_python
comment A simple implementation of Priority Queue comment using Queue. class PriorityQueue extends object begin function __init__ self begin set queue = list end function function __str__ self begin return join string list comprehension string i for i in queue end function comment for checking if the queue is empty f...
# A simple implementation of Priority Queue # using Queue. class PriorityQueue(object): def __init__(self): self.queue = [] def __str__(self): return ' '.join([str(i) for i in self.queue]) # for checking if the queue is empty def isEmpty(self): return len(self.queue) == 0 def __add__(self,other): ...
Python
zaydzuhri_stack_edu_python
function _PasswordFromFile password_file begin try begin with open password_file string r as pf begin for line in read lines pf begin if not starts with line string # begin return strip line end end end end except IOError as why begin exception why return none end end function
def _PasswordFromFile(password_file): try: with open(password_file, 'r') as pf: for line in pf.readlines(): if not line.startswith('#'): return line.strip() except IOError as why: logging.exception(why) return None
Python
nomic_cornstack_python_v1
string słowa try możemy postawić przed jakimkolwiek kawałkiem kodu to jest coś takiego jak blok if ale działa dla całego bloku kodu jak to wygląda w praktyce? comment tutaj mamy kawałek kodu z porzedniego tutorialu import csv with open string plik.csv as csvfile begin set readCSV = reader csvfile delimiter=string , set...
''' słowa try możemy postawić przed jakimkolwiek kawałkiem kodu to jest coś takiego jak blok if ale działa dla całego bloku kodu jak to wygląda w praktyce? ''' # tutaj mamy kawałek kodu z porzedniego tutorialu import csv with open('plik.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter = ',') daty = [...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf8 -*- import theano.tensor as T import numpy as np function accuracy_measure true_frame pred_frame begin comment Checked w/ test_value -> ok comment true_frame must be a binary vector set true_positive = sum pred_frame * true_frame axis=1 set false_negative = sum 1 - ...
#!/usr/bin/env python # -*- coding: utf8 -*- import theano.tensor as T import numpy as np def accuracy_measure(true_frame, pred_frame): # Checked w/ test_value -> ok # true_frame must be a binary vector true_positive = T.sum(pred_frame * true_frame, axis=1) false_negative = T.sum((1 - pred_frame) * t...
Python
zaydzuhri_stack_edu_python
function get_version_from_executable cls bin_path cwd=none env=none begin set output = decode check output list string bin_path string -version cwd=cwd env=env set match = search VERSION_OUTPUT_REGEX output if not match begin return none end return call parse_version_string output end function
def get_version_from_executable( cls, bin_path: Union[Path, str], *, cwd: Optional[Union[Path, str]] = None, env: Optional[Dict[str, str]] = None, ) -> Optional[Version]: output = subprocess.check_output( [str(bin_path), "-version"], cwd=cwd, env=env ...
Python
nomic_cornstack_python_v1
function optimize_actions actions begin set result = dict function donothing oid index_oid action1 action2 begin del result at tuple oid index_oid end function function doadd oid index_oid action1 action2 begin set result at tuple oid index_oid = action1 end function function dochange oid index_oid action1 action2 beg...
def optimize_actions(actions): result = {} def donothing(oid, index_oid, action1, action2): del result[(oid, index_oid)] def doadd(oid, index_oid, action1, action2): result[(oid, index_oid)] = action1 def dochange(oid, index_oid, action1, action2): result[(oid, index...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import seaborn as sns set set colors = list string #9b59b6 string #3498db string #95a5a6 string #e74c3c string #34495e string #2ecc71 call palplot call color_palette colors function line_xy x y **kwargs begin return call lineplot x y keyword kwargs end function function scatter_xy data x...
import matplotlib.pyplot as plt import seaborn as sns sns.set() colors = ["#9b59b6", "#3498db", "#95a5a6", "#e74c3c", "#34495e", "#2ecc71"] sns.palplot(sns.color_palette(colors)) def line_xy(x, y, **kwargs): return sns.lineplot(x, y, **kwargs) def scatter_xy(data, x: str, y: str, axis=None, position=None, **kw...
Python
zaydzuhri_stack_edu_python