code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function decrease_brightness img begin set step = 10 set width = call getWidth set height = call getHeight for x in range width begin for y in range height begin set tuple r g b = call getPixel x y set r_new = r - step set g_new = g - step set b_new = b - step set tuple r2 g2 b2 = call fix_rgb r_new g_new b_new call se...
def decrease_brightness(img): step = 10 width = img.getWidth() height = img.getHeight() for x in range(width): for y in range(height): r,g,b = img.getPixel(x,y) r_new = (r - step) g_new = (g - step) b_new = (b - step) r2,g2,b2 = fix_rgb...
Python
nomic_cornstack_python_v1
function bias_variable shape name=none begin return call Variable call constant 0.01 shape=shape name=name end function
def bias_variable(shape, name=None): return tf.Variable(tf.constant(0.01, shape=shape), name=name)
Python
nomic_cornstack_python_v1
string Tests for executing database commands import pytest function test_create_tables setup_person_query begin set tuple ctx block = call setup_person_query set expected = string CREATE TABLE IF NOT EXISTS person ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER ); assert call create_tables == expected end function com...
""" Tests for executing database commands """ import pytest def test_create_tables(setup_person_query): ctx, block = setup_person_query() expected = """\ CREATE TABLE IF NOT EXISTS person ( id INTEGER PRIMARY KEY, name TEXT, age INTEGER );""" assert ctx.create_tables() == expected # TODO: assert sche...
Python
zaydzuhri_stack_edu_python
function token_to_sentence text begin set regex_of_sentence = find all TEXT_TO_SENTENCES_REGEX text set text_sentences = list comprehension strip x for x in regex_of_sentence if x is not string return text_sentences end function
def token_to_sentence(text): regex_of_sentence = re.findall(TEXT_TO_SENTENCES_REGEX, text) text_sentences = [x.strip() for x in regex_of_sentence if x is not ''] return text_sentences
Python
nomic_cornstack_python_v1
from PIL import Image set image_beach = open string images/beach.jpg comment print(image_beach.size) comment print(image_beach.format) set image_combined = call new string RGB size set tuple width height = size print string Width: { width } print string Height: { height } set pixels_beach = load image_beach comment pri...
from PIL import Image image_beach = Image.open('images/beach.jpg') # print(image_beach.size) # print(image_beach.format) image_combined = Image.new('RGB', image_beach.size) (width, height) = image_beach.size print(f'Width: {width}') print(f'Height: {height}') pixels_beach = image_beach.load() # print(pixels_beach[...
Python
zaydzuhri_stack_edu_python
import rhinoscriptsyntax as rs set ptt = call GetPoint string Pick starting point function createColoredCylinder x y z r g b begin set currentColor = list r g b call AddPoint x y z set pt = tuple x y z set cr = call AddCylinder pt x + y / 4 5 call ObjectColor cr currentColor end function call EnableRedraw false set ste...
import rhinoscriptsyntax as rs ptt = rs.GetPoint("Pick starting point") def createColoredCylinder(x,y,z,r,g,b): currentColor = [r,g,b] rs.AddPoint(x,y,z) pt = (x,y,z) cr = rs.AddCylinder(pt, (x + y) / 4, 5) rs.ObjectColor(cr, currentColor) rs.EnableRedraw(False) step = 10 ...
Python
zaydzuhri_stack_edu_python
import string import random set game_board = none set visible_board = none set num_mines = 10 set width = 10 set height = 10 function letters begin=string A end=string Z begin set begin_ord = ordinal begin set end_ord = ordinal end for number in call xrange begin_ord end_ord + 1 begin yield character number end end fun...
import string import random game_board = None visible_board = None num_mines = 10 width = 10 height = 10 def letters(begin='A', end='Z'): begin_ord = ord(begin) end_ord = ord(end) for number in xrange(begin_ord, end_ord+1): yield chr(number) def generate_boards(): global visible_board glo...
Python
zaydzuhri_stack_edu_python
function sum_elements X begin set sums = 0 for i in range length X begin for j in range length X at i begin set sums = sums + X at i at j end end return sums end function print call sum_elements X
def sum_elements(X): sums = 0 for i in range(len(X)): for j in range(len(X[i])): sums+=X[i][j] return sums print(sum_elements(X))
Python
jtatman_500k
import numpy as np function generate_bin length lev g_bin begin if lev == 0 begin call generate_bin length lev + 1 list 1 end else if lev < length - 1 begin append g_bin 0 call generate_bin length lev + 1 g_bin pop g_bin append g_bin 1 call generate_bin length lev + 1 g_bin pop g_bin end else begin append g_bin 1 for i...
import numpy as np def generate_bin(length, lev, g_bin) : if lev==0 : generate_bin(length, lev+1, [1]) elif lev<length-1 : g_bin.append(0) generate_bin(length, lev+1, g_bin) g_bin.pop() g_bin.append(1) generate_bin(length, lev+1, g_bin) g_bin.pop() else : g_bin.append(1) for i in range(...
Python
zaydzuhri_stack_edu_python
function get_vertical_order_tree begin set root = call TreeNode 0 set left = call TreeNode 8 set right = call TreeNode 1 set left = call TreeNode 3 set right = call TreeNode 4 set right = call TreeNode 7 set right = call TreeNode 2 set left = call TreeNode 5 set left = call TreeNode 6 return root end function
def get_vertical_order_tree(): root = TreeNode(0) root.left = TreeNode(8) root.right = TreeNode(1) root.right.left = TreeNode(3) root.right.left.right = TreeNode(4) root.right.left.right.right = TreeNode(7) root.right.right = TreeNode(2) root.right.right.left = TreeNode(5) root.rig...
Python
nomic_cornstack_python_v1
function generate_counts_subparser subparsers begin string Adds a sub-command parser to `subparsers` to make a counts query. set parser = call add_parser string counts description=COUNTS_DESCRIPTION epilog=COUNTS_EPILOG formatter_class=ParagraphFormatter help=COUNTS_HELP call set_defaults func=ngram_counts call add_com...
def generate_counts_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make a counts query.""" parser = subparsers.add_parser( 'counts', description=constants.COUNTS_DESCRIPTION, epilog=constants.COUNTS_EPILOG, formatter_class=ParagraphFormatter, help=constants.CO...
Python
jtatman_500k
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import cv2 import numpy as np function draw_hud img color=tuple 0 0 255 begin assert img is not none set tuple h w channels = shape call line img tuple integer w / 2 0 tuple integer w / 2 h color 1 call line img tuple 0 integer h / 2 tuple w integer h / 2 colo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import numpy as np def draw_hud ( img , color = (0,0,255) ) : assert img is not None h,w,channels = img.shape cv2.line (img , ( int(w/2),0 ) , (int(w/2),h) , color , 1 ) cv2.line (img , ( 0,int(h/2) ) , (w,int(h/2)) , color , 1 ) return img de...
Python
zaydzuhri_stack_edu_python
class MathOperations begin decorator staticmethod function get_sum a b begin comment Iterate until b becomes 0 while b != 0 begin comment Carry contains common set bits of a and b set carry = a ? b comment Sum of bits of a and b where at least one of the bits is not set set a = a ? b comment Carry is shifted by one so ...
class MathOperations: @staticmethod def get_sum(a, b): # Iterate until b becomes 0 while b != 0: # Carry contains common set bits of a and b carry = a & b # Sum of bits of a and b where at least one of the bits is not set a = a ^ b # ...
Python
jtatman_500k
import pandas as pd set data = call read_excel string catering_dish_profit.xls index_col=string 菜品名 set data = copy data at string 盈利 comment 排序 sort values data ascending=false import matplotlib.pyplot as plt set rcParams at string font.sans-serif = list string SimHei set rcParams at string axes.unicode_minus = false ...
import pandas as pd data = pd.read_excel('catering_dish_profit.xls', index_col=u'菜品名') data = data[u'盈利'].copy() data.sort_values(ascending=False) # 排序 import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.figure() data.plot(kind='bar') plt.ylab...
Python
zaydzuhri_stack_edu_python
function update self instance oldValue newValue subKey begin set histogram = call __get__ instance none set histogram at subKey = histogram at subKey + newValue - oldValue end function
def update(self, instance, oldValue, newValue, subKey): histogram = self.__get__(instance, None) histogram[subKey] += newValue - oldValue
Python
nomic_cornstack_python_v1
import numpy as np import tensorflow as tf set num_points = 5 set x_batch = call placeholder float32 set y_batch = call Variable call random_uniform list num_points - 1 1 set allLosses = call square x_batch - y_batch set loss = call reduce_mean allLosses set set1 = list for i in call xrange num_points begin set x = ra...
import numpy as np import tensorflow as tf num_points = 5 x_batch = tf.placeholder(tf.float32) y_batch = tf.Variable(tf.random_uniform([num_points],-1,1)) allLosses = tf.square(x_batch - y_batch) loss = tf.reduce_mean(allLosses) set1 = [] for i in xrange(num_points): x = np.random.randint(0,10) set1.append...
Python
zaydzuhri_stack_edu_python
function main rootdir version version_short is_release verbose mock_run begin if not version begin call secho string No version info provided fg=string red exit end set updater = call VersionUpdater rootdir=rootdir version=version version_short=version_short is_release=is_release verbose=verbose mock_run=mock_run call ...
def main(rootdir, version, version_short, is_release, verbose, mock_run): if not version: click.secho("No version info provided", fg="red") exit() updater = VersionUpdater( rootdir=rootdir, version=version, version_short=version_short, is_release=is_release, ...
Python
nomic_cornstack_python_v1
function _reset self begin call _reset call _reset end function
def _reset(self): self._model._reset() super(RDPAnalyzer, self)._reset()
Python
nomic_cornstack_python_v1
function make_pipeline context begin string Create our pipeline. comment Filter for primary share equities. IsPrimaryShare is a built-in filter. set primary_share = call IsPrimaryShare comment Equities listed as common stock (as opposed to, say, preferred stock). comment 'ST00000001' indicates common stock. set common_...
def make_pipeline(context): """ Create our pipeline. """ # Filter for primary share equities. IsPrimaryShare is a built-in filter. primary_share = IsPrimaryShare() # Equities listed as common stock (as opposed to, say, preferred stock). # 'ST00000001' indicates common stock. common_sto...
Python
jtatman_500k
function nnPredict w1 w2 data begin set labels = array list comment create bias row set bias_row = ones tuple size np data 0 1 comment concatenate bias with data matrix set data = concatenate tuple data bias_row axis=1 comment Calculate input to hidden layer set intput_hidden_layer = dot data transpose w1 comment Calcu...
def nnPredict(w1,w2,data): labels = np.array([]) # create bias row bias_row =np.ones((np.size(data,0),1)) # concatenate bias with data matrix data=np.concatenate((data,bias_row),axis=1) #Calculate input to hidden layer intput_hidden_layer= np.dot(data,w1.transpose()) ...
Python
nomic_cornstack_python_v1
function parse_name lexer begin string Convert a name lex token into a name parse node. set token = call expect_token lexer NAME return call NameNode value=value loc=loc lexer token end function
def parse_name(lexer: Lexer) -> NameNode: """Convert a name lex token into a name parse node.""" token = expect_token(lexer, TokenKind.NAME) return NameNode(value=token.value, loc=loc(lexer, token))
Python
jtatman_500k
function alpha l begin set c = ordinal l - 96 return c end function set w = split call raw_input set w1 = length w at 0 set w2 = length w at 1 set r = 0 set w3 = min w1 w2 set w4 = max w1 w2 for i in range w3 begin set m = absolute call alpha w at 0 at i - call alpha w at 1 at i set r = r + m end if w1 > w2 begin for i...
def alpha(l): c=(ord(l)-96) return(c) w=(raw_input()).split() w1=len(w[0]) w2=len(w[1]) r=0 w3=min(w1,w2) w4=max(w1,w2) for i in range(w3): m=abs(alpha(w[0][i])-alpha(w[1][i])) r+=m if(w1>w2): for i in range(w3,w1): x=alpha(w[0][i]) r+=x elif(w2>w1): for i in range(w3,w2): y=alpha(w[1][i]) r...
Python
zaydzuhri_stack_edu_python
function read_json_file file_path begin if not exists gfile file_path begin raise call IOError string Path { file_path } does not exist. end try begin with call GFile file_path as json_file begin return load json json_file end end except Exception as e begin raise call ValueError string Failed loading file { file_path ...
def read_json_file(file_path: str): if not tf.io.gfile.exists(file_path): raise IOError(f"Path {file_path!r} does not exist.") try: with tf.io.gfile.GFile(file_path) as json_file: return json.load(json_file) except Exception as e: raise ValueError(f"Failed loading file {...
Python
nomic_cornstack_python_v1
function updateUserDrawnThresholds self event begin if not call LeftIsDown begin return end set tuple x y = call GetPosition set y = scatterHeight - y set x = x - xoffset set x = x - call GetWidth + 2 * emptySpace set x = min x 255 set y = min y 255 set x = max x 0 set y = max y 0 set actionend = tuple x y set tuple x1...
def updateUserDrawnThresholds(self, event): if not event.LeftIsDown(): return x, y = event.GetPosition() y = self.scatterHeight - y x -= self.xoffset x -= (self.verticalLegend.GetWidth() + 2 * self.emptySpace) x = min(x, 255) y = min(y, 255) x = max(x, 0) y = max(y, 0) self.actionend = (x...
Python
nomic_cornstack_python_v1
function test_post_api_no_preferred_laboratories_201 self begin set url = reverse string mobile:prescription-list comment Creates a prescription for this user set data = dict string patient dict string user_id id ; string preferred_laboratories_id list id ; string picture_id_front string R0lGODlhAQABAIAAAAUEBAAAACwAAAA...
def test_post_api_no_preferred_laboratories_201(self): url = reverse('mobile:prescription-list') # Creates a prescription for this user data = { "patient": { "user_id": self.patient.user.id, "preferred_laboratories_id": [self.laboratory.id], ...
Python
nomic_cornstack_python_v1
function test_compare_frozensets self begin set fset = frozenset_type set i = call Instance fset _ctx set j = call Instance fset _ctx call assertIs none call cmp_rel _ctx EQ i j end function
def test_compare_frozensets(self): fset = self._convert.frozenset_type i = abstract.Instance(fset, self._ctx) j = abstract.Instance(fset, self._ctx) self.assertIs(None, compare.cmp_rel(self._ctx, slots.EQ, i, j))
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[1]: set test_0 = string DIP= Digital Image Processing set test_1 = string Goruntu Isleme comment In[2]: print test_0 comment In[3]: set var_0 = 10 set var_1 = 100 comment In[4]: var_1 comment In[5]: var_1 + var_0 comment In[6]: set myList = list 0 1 string 2 print myList comment In[7]: ...
# coding: utf-8 # In[1]: test_0="DIP= Digital Image Processing" test_1="Goruntu Isleme" # In[2]: print(test_0) # In[3]: var_0=10 var_1=100 # In[4]: var_1 # In[5]: var_1+var_0 # In[6]: myList=[0,1,"2"] print(myList) # In[7]: myList # In[8]: myList[1] myList[2] # In[9]: myList[1] # In[10]: my...
Python
zaydzuhri_stack_edu_python
comment remove duplicates from list comment use hash if no space constraint is given (not implemeted) comment else do loop for each node and check the data for dups and change the next pointers from ll import * function linked_list_remove_duplicates ll begin if head == none begin return ll end set cur = head while cur ...
#remove duplicates from list #use hash if no space constraint is given (not implemeted) #else do loop for each node and check the data for dups and change the next pointers from ll import * def linked_list_remove_duplicates(ll): if ll.head == None: return ll cur = ll.head while cur: ...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import non_maximum_suppuration_file from imageio import imread , imsave from scipy import signal from scipy.ndimage.filters import convolve from scipy.signal import convolve2d from skimage import color function read_image filename representation=2 begin string reads a ...
import matplotlib.pyplot as plt import numpy as np import non_maximum_suppuration_file from imageio import imread , imsave from scipy import signal from scipy.ndimage.filters import convolve from scipy.signal import convolve2d from skimage import color def read_image(filename, representation=2): """ reads a i...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- string @author: Frank Brehm @contact: frank.brehm@profitbricks.com @copyright: © 2010 - 2016 by Frank Brehm, ProfitBricks GmbH, Berlin @summary: The module for a base application object. It provides methods for commandline parsing, initialising the logging mech...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: Frank Brehm @contact: frank.brehm@profitbricks.com @copyright: © 2010 - 2016 by Frank Brehm, ProfitBricks GmbH, Berlin @summary: The module for a base application object. It provides methods for commandline parsing, initialising the logging ...
Python
zaydzuhri_stack_edu_python
import csv import datetime import os function parse_occurrences occ begin set s = string { occ at 0 at 0 } | { occ at 0 at 1 } for o in occ at slice 1 : : begin set s = s + string ; { o at 0 } | { o at 1 } end return s end function function create_directory date begin set directory_path = string /home/marco/Scrivania...
import csv import datetime import os def parse_occurrences(occ): s = f"{occ[0][0]}|{occ[0][1]}" for o in occ[1:]: s += f";{o[0]}|{o[1]}" return s def create_directory(date): directory_path = f"/home/marco/Scrivania/tirocinio-unicredit/graphdb/relations/{date}/" if not os.path.exists(dire...
Python
zaydzuhri_stack_edu_python
import unittest from unittest.mock import MagicMock from fitness_repo import FitnessRepository from workout import Workout class test_save_workout_route extends TestCase begin set mock_conn = type string Connection tuple object dict string cursor string method ; string commit string otherMethod set mock_cursor = type s...
import unittest from unittest.mock import MagicMock from fitness_repo import FitnessRepository from workout import Workout class test_save_workout_route(unittest.TestCase): mock_conn = type('Connection', (object,), { "cursor": "method", "commit": "otherMethod" }) mock_cursor = type('Cursor', (object,), { "exe...
Python
zaydzuhri_stack_edu_python
function hoggar_indices begin return list product list 0 1 repeat=6 end function
def hoggar_indices(): return list(product([0,1], repeat=6))
Python
nomic_cornstack_python_v1
from requests import get comment Функция возвращает начальную ссылку function get_start_link topic begin set link = string https://ru.wikipedia.org/wiki/ { capitalize topic } return link end function comment Функция возвращает ссылку на сопутствующую страницу function get_link wiki_link begin set link = string https://...
from requests import get # Функция возвращает начальную ссылку def get_start_link(topic): link = f'https://ru.wikipedia.org/wiki/{topic.capitalize()}' return link # Функция возвращает ссылку на сопутствующую страницу def get_link(wiki_link): link = f'https://ru.wikipedia.org{wiki_link}' return link ...
Python
zaydzuhri_stack_edu_python
function test_phase self begin append self string a string a set tuple rev node0 = commit client string first addremove=true assert equal list tuple 0 string draft call phase node0 set ctx = client at rev assert equal string draft call phase end function
def test_phase(self): self.append('a', 'a') rev, node0 = self.client.commit('first', addremove=True) self.assertEqual([(0, 'draft')], self.client.phase(node0)) ctx = self.client[rev] self.assertEqual('draft', ctx.phase())
Python
nomic_cornstack_python_v1
function sanitize instring begin return encode instring string ascii string replace end function
def sanitize(instring): return instring.encode('ascii','replace')
Python
nomic_cornstack_python_v1
import pygame import pygame.locals import sys from time import sleep from lib.infuse import Infuse from lib.signalgenerator import OscillatingSignal from keymap import keymap class Controller extends object begin function __init__ self begin set key_map = false set joysticks = false set joysticks_map = false set button...
import pygame import pygame.locals import sys from time import sleep from lib.infuse import Infuse from lib.signalgenerator import OscillatingSignal from .keymap import keymap class Controller(object): def __init__(self): self.key_map = False self.joysticks = False self.joysticks_map = False self.bu...
Python
zaydzuhri_stack_edu_python
function test_json_schema_must_have_type_present self begin set invalid_schema = call ConfigContextSchema name=string invalid slug=string invalid data_schema=dict string properties dict string a dict string type string string with assert raises ValidationError begin call full_clean end end function
def test_json_schema_must_have_type_present(self): invalid_schema = ConfigContextSchema( name="invalid", slug="invalid", data_schema={"properties": {"a": {"type": "string"}}} ) with self.assertRaises(ValidationError): invalid_schema.full_clean()
Python
nomic_cornstack_python_v1
function winning_move macroboard begin set moves = available_moves for tuple px py in moves begin call make_move px py if has_a_winner begin return tuple px py end call undo_last_move end return none end function
def winning_move(macroboard): moves = macroboard.available_moves for px, py in moves: macroboard.make_move(px, py) if macroboard.has_a_winner: return (px, py) macroboard.undo_last_move() return None
Python
nomic_cornstack_python_v1
function show self eq value=none begin if eq in list string f string x begin set key = string unamex end else if eq in list string g string y begin set key = string unamey end if value begin set value = list value end else begin set value = list __dict__ at eq end set out = string for tuple name val idx in zip __dict_...
def show(self, eq, value=None): if eq in ['f', 'x']: key = 'unamex' elif eq in ['g', 'y']: key = 'unamey' if value: value = list(value) else: value = list(self.__dict__[eq]) out = '' for name, val, idx in zip(self.system.V...
Python
nomic_cornstack_python_v1
function meteors n ar br begin set differ = list set used = dict set pr = list for i in range n begin if ar at i != br at i begin append pr - 1 append differ tuple i ar at i br at i end else begin append pr ar at i set used at ar at i = i end end set unused = call find_unused n used if length differ == 1 begin set p...
def meteors(n, ar, br): differ = [] used = {} pr = [] for i in range(n): if ar[i] != br[i]: pr.append(-1) differ.append((i, ar[i], br[i])) else: pr.append(ar[i]) used[ar[i]] = i unused = find_unused(n, used) if len(differ) == 1: ...
Python
zaydzuhri_stack_edu_python
function _motion_scroll_event self widget event begin if not call is_image_loaded begin return end if direction == UP begin call zoom_in end else if direction == DOWN begin call zoom_out end end function
def _motion_scroll_event(self, widget, event): if not self.is_image_loaded(): return if event.direction == Gdk.ScrollDirection.UP: self.zoom_in() elif event.direction == Gdk.ScrollDirection.DOWN: self.zoom_out()
Python
nomic_cornstack_python_v1
function test_app_settings_reset_bool self mock_exit mock_write_error mock_write_success begin comment Boolean Custom Setting set mock_args_bool = call MagicMock app=string test_app setting=string enable_feature assert raises SystemExit app_settings_reset_command mock_args_bool call assert_not_called call assert_called...
def test_app_settings_reset_bool( self, mock_exit, mock_write_error, mock_write_success ): # Boolean Custom Setting mock_args_bool = mock.MagicMock( app="test_app", setting="enable_feature", ) self.assertRaises( SystemExit, cli...
Python
nomic_cornstack_python_v1
import itertools import os import random import numpy as np class NeuralNetwork begin function __init__ self layers learning_rate epochs begin set fitted_ = false set biases_ = list comprehension randn a 1 for a in layers at slice 1 : : set weights_ = list comprehension randn a b for tuple b a in zip layers at slice ...
import itertools import os import random import numpy as np class NeuralNetwork: def __init__(self, layers, learning_rate, epochs): self.fitted_ = False self.biases_ = [np.random.randn(a, 1) for a in layers[1:]] self.weights_ = [np.random.randn(a, b) for b, a in zip(layers[:-1], layers[1:...
Python
zaydzuhri_stack_edu_python
function variation_count self begin raise call NotImplementedError string 'variation_count' must be defined and return an int. end function
def variation_count(self) -> int: raise NotImplementedError( "'variation_count' must be defined and return an int.")
Python
nomic_cornstack_python_v1
import cv2 import numpy as np from matplotlib import pyplot as plt set img = call imread string C:/Users/wang/Desktop/square_images/1-10-1.jpg set hsv = call cvtColor img COLOR_BGR2HSV set hist = call calcHist list hsv list 1 none list 256 list 0 256 comment print (hist[3][35]) comment plt.imshow(hist,interpolation = '...
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread('C:/Users/wang/Desktop/square_images/1-10-1.jpg') hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV) hist = cv2.calcHist([hsv],[1],None,[256],[0,256]) # print (hist[3][35]) # plt.imshow(hist,interpolation = 'nearest') plt.plot(hist,c...
Python
zaydzuhri_stack_edu_python
function intensityRatioSave self outFile=0 begin if not outFile begin set outFile = IntensityRatio at string filename print string saving ratio to filename = %s % outFile end if has attribute self string IntensityRatio begin set temperature = IntensityRatio at string temperature set eDensity = IntensityRatio at string ...
def intensityRatioSave(self,outFile=0): if not outFile: outFile = self.IntensityRatio['filename'] print(' saving ratio to filename = %s'%(outFile)) if hasattr(self, 'IntensityRatio'): temperature=self.IntensityRatio['temperature'] eDensity=self.IntensityRa...
Python
nomic_cornstack_python_v1
function get_learning_rate optim groups=none begin set state_dict = state dict optim set param_groups = state_dict at string param_groups if groups is none begin return list comprehension pg at string lr for pg in param_groups end else if is instance groups int begin return param_groups at groups at string lr end else ...
def get_learning_rate(optim, groups=None): state_dict = optim.state_dict() param_groups = state_dict["param_groups"] if groups is None: return [pg["lr"] for pg in param_groups] elif isinstance(groups, int): return param_groups[groups]["lr"] elif isinstance(groups, list): retu...
Python
nomic_cornstack_python_v1
set __author__ = string computer set a = 0 set b1 = 0 set b = list insert b 0 b1 insert b 0 a print b
__author__ = 'computer' a = 0 b1 = 0 b =[] b.insert(0,b1) b.insert(0,a) print(b)
Python
zaydzuhri_stack_edu_python
function run_individual_node self index number=10 repeat=1 min_repeat_ms=0 limit_zero_time_iterations=100 cooldown_interval_ms=0 repeats_to_cooldown=1 begin comment Results are returned as serialized strings which we deserialize set res = call _run_individual_node index number repeat min_repeat_ms limit_zero_time_itera...
def run_individual_node( self, index, number=10, repeat=1, min_repeat_ms=0, limit_zero_time_iterations=100, cooldown_interval_ms=0, repeats_to_cooldown=1, ): # Results are returned as serialized strings which we deserialize res = self._...
Python
nomic_cornstack_python_v1
function createTriangleColor p1 p2 p3 r g b begin comment Extend set p1 = call __vertexUnpack3 p1 set p2 = call __vertexUnpack3 p2 set p3 = call __vertexUnpack3 p3 comment Dissamble vertices set tuple x1 y1 z1 = p1 set tuple x2 y2 z2 = p2 set tuple x3 y3 z3 = p3 comment Defining locations and color set vertices = list ...
def createTriangleColor(p1, p2, p3, r, g, b): # Extend p1 = __vertexUnpack3(p1) p2 = __vertexUnpack3(p2) p3 = __vertexUnpack3(p3) # Dissamble vertices x1, y1, z1 = p1 x2, y2, z2 = p2 x3, y3, z3 = p3 # Defining locations and color vertices = [ # X, Y, Z, R, G, B, ...
Python
nomic_cornstack_python_v1
import json from http import HTTPStatus from my_app.users.models import User function test_get_all_users session client begin string Test getting all users set user_a = call User email=string user-a@example.com set user_b = call User email=string user-b@example.com add session user_a add session user_b commit session s...
import json from http import HTTPStatus from my_app.users.models import User def test_get_all_users(session, client): """Test getting all users""" user_a = User(email='user-a@example.com') user_b = User(email='user-b@example.com') session.add(user_a) session.add(user_b) session.commit() ...
Python
zaydzuhri_stack_edu_python
function dnasequence_reader file_name begin with open file_name as f begin return right strip read line f end end function
def dnasequence_reader(file_name): with open(file_name) as f: return f.readline().rstrip()
Python
nomic_cornstack_python_v1
function seminar_list_teachers self seminars begin set params = dict string seminar seminars debug string [LIST] Get list of teachers in the course's seminaries with params: { params } return call _create_resource string seminar-cvicici-seznam params cls=SeminarTeachers end function
def seminar_list_teachers(self, seminars: List[str]) -> entities.SeminarTeachers: params = {'seminar': seminars} log.debug(f"[LIST] Get list of teachers in the course's seminaries with params: {params}") return self._create_resource('seminar-cvicici-seznam', params, ...
Python
nomic_cornstack_python_v1
function __init__ self proportion=1.0 n_neighbors=5 n_jobs=1 begin call __init__ call check_greater_or_equal proportion string proportion 0 call check_greater_or_equal n_neighbors string n_neighbors 1 call check_n_jobs n_jobs string n_jobs set proportion = proportion set n_neighbors = n_neighbors set n_jobs = n_jobs en...
def __init__(self, proportion= 1.0, n_neighbors= 5, n_jobs= 1): super().__init__() self.check_greater_or_equal(proportion, "proportion", 0) self.check_greater_or_equal(n_neighbors, "n_neighbors", 1) self.check_n_jobs(n_jobs, 'n_jobs') self.proportion= proportion...
Python
nomic_cornstack_python_v1
function evaluate self state begin set score = call get_pimped_score WEIGHT_TOWER_FIVE_PLAYER1 WEIGHT_TOWER_FIVE_PLAYER2 WEIGHT_TOWER__PLAYER1 WEIGHT_TOWER__PLAYER2 WEIGHT_TOWER_FOUR_PLAYER1 WEIGHT_TOWER_FOUR_PLAYER2 WEIGHT_CAST_AWAY_PLAYER1 WEIGHT_CAST_AWAY_PLAYER2 WEIGHT_DONT_DO_THAT return score end function
def evaluate(self, state): score = state[0].get_pimped_score(self.WEIGHT_TOWER_FIVE_PLAYER1, self.WEIGHT_TOWER_FIVE_PLAYER2, self.WEIGHT_TOWER__PLAYER1, self.WEIGHT_TOWER__PLAYER2, self.WEIGHT_TOWER_FOUR_PLAYER1, ...
Python
nomic_cornstack_python_v1
function exists self username begin set query = query session where username == username return call scalar end function
def exists(self, username: str) -> bool: query = self.session.query(sql.exists().where( User.username == username)) return query.scalar()
Python
nomic_cornstack_python_v1
function main begin set tuple _ money = map int split input set prices = sorted map int split input set answer = 0 for price in prices begin if price > money begin break end set money = money - price set answer = answer + 1 end print answer end function if __name__ == string __main__ begin call main end
def main(): _, money = map(int, input().split()) prices = sorted(map(int, input().split())) answer = 0 for price in prices: if price > money: break money -= price answer += 1 print(answer) if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
for i in range 1 stL begin if st at i == prev begin set cnt = cnt + 1 end else begin set cnt = 1 end if cnt == 7 begin set y = true break end set prev = st at i end
for i in range(1, stL): if st[i] == prev: cnt += 1 else: cnt = 1 if cnt == 7: y = True break prev = st[i]
Python
zaydzuhri_stack_edu_python
function test_is_valid_submission_upvote_notification self begin set submission_vote_mock = call MagicMock is_upvote=true author=1 submission=call MagicMock author=2 assert true call is_valid_submission_upvote_notification submission_vote_mock end function
def test_is_valid_submission_upvote_notification(self): submission_vote_mock = MagicMock(is_upvote=True, author=1, submission=MagicMock(author=2)) self.assertTrue(Notification.is_valid_submission_upvote_notification(submission_vote_mock))
Python
nomic_cornstack_python_v1
function format_pooling_echo_pick_list vol_sample max_vol_per_well=60000 dest_plate_shape=list 16 24 begin set contents = list string Source Plate Name,Source Plate Type,Source Well,Concentration,Transfer Volume,Destination Plate Name,Destination Well comment Write the sample transfer volumes set tuple rows cols = shap...
def format_pooling_echo_pick_list(vol_sample, max_vol_per_well=60000, dest_plate_shape=[16,24]): contents = ['Source Plate Name,Source Plate Type,Source Well,' 'Concentration,Transfer Volume,Destination Plate Name,' ...
Python
nomic_cornstack_python_v1
function peek self begin with lock begin return event_list at integer onset_idx at 0 at 1 end end function
def peek(self) -> Event: with self.lock: return self.event_list[int(self.onset_idx[0][1])]
Python
nomic_cornstack_python_v1
function convert_to_list data begin return list comprehension integer i for i in split data string ; end function function convert_to_str data begin return join string ; list comprehension string i for i in data end function function weight_by_type courier_type begin if courier_type == string foot begin return 10 end e...
def convert_to_list(data) -> list: return [int(i) for i in data.split(';')] def convert_to_str(data) -> str: return ';'.join([str(i) for i in data]) def weight_by_type(courier_type) -> int: if courier_type == "foot": return 10 elif courier_type == "bike": return 15 elif courier_t...
Python
zaydzuhri_stack_edu_python
function _join self begin if thread and is alive thread begin join thread end end function
def _join(self): if self.thread and self.thread.is_alive(): self.thread.join()
Python
nomic_cornstack_python_v1
function geo2sph bod sph geo begin set tuple R f = args yield while true begin call setshape R f set tuple lat_d lon_d alt_d = reqs set tuple lat_c lon_c rad_c = call datum2center lat_d lon_d alt_d set pros = tuple lat_c lon_c rad_c yield tuple call outs tuple true end end function
def geo2sph(bod, sph, geo): R, f = bod.args yield while True: libgeoid.setshape(R, f) lat_d, lon_d, alt_d = geo.reqs lat_c, lon_c, rad_c = libgeoid.datum2center(lat_d, lon_d, alt_d) sph.pros = lat_c, lon_c, rad_c yield (sph.outs((True,)),)
Python
nomic_cornstack_python_v1
function create_dataset self begin comment define how text and label will be processed set inputs = call Field lower=true tokenize=string spacy batch_first=true set labels = call Field sequential=false batch_first=true unk_token=none comment create datasets set tuple train dev test = call splits inputs labels root=data...
def create_dataset(self): # define how text and label will be processed self.inputs = data.Field(lower=True, tokenize='spacy', batch_first=True) self.labels = data.Field(sequential=False, batch_first=True, unk_token=None) # create datasets train, dev, test = datasets.SNLI.splits...
Python
nomic_cornstack_python_v1
function _handle_clock_gettime self mu clk_id tp_ptr begin if clk_id == CLOCK_REALTIME begin set ns = call time_ns set seconds = integer time set ns = ns - seconds * 1000000000 call mem_write tp_ptr + 0 call to_bytes 4 byteorder=string little call mem_write tp_ptr + 4 call to_bytes 4 byteorder=string little return 0 en...
def _handle_clock_gettime(self, mu, clk_id, tp_ptr): if clk_id == CLOCK_REALTIME: ns = time.time_ns() seconds = int(time.time()) ns = ns - seconds * 1000000000 mu.mem_write(tp_ptr + 0, seconds.to_bytes(4, byteorder='little')) mu.mem_write(tp_ptr + 4...
Python
nomic_cornstack_python_v1
if u > 1 begin for i in range 2 u begin if u % i == 0 begin print string no break end end for else begin print string yes end end else begin print string no end
if u>1: for i in range(2,u): if u%i == 0: print("no") break else: print("yes") else: print("no")
Python
zaydzuhri_stack_edu_python
comment 全体をインポート import pizza comment 全モジュールインポート →ドットを使ってモジュールと関数指定しなくていい。 comment 直接関数を呼び出せる。しかし、同名関数があったら問題発生なので非推奨 comment from module_name import * comment モジュール内の、関数指定でインポート comment from module_name import function_0, function_1, function_2 comment インポートして、関数のエイリアスを定義 comment from pizza import make_pizza as mp co...
# 全体をインポート import pizza # 全モジュールインポート →ドットを使ってモジュールと関数指定しなくていい。 # 直接関数を呼び出せる。しかし、同名関数があったら問題発生なので非推奨 # from module_name import * # モジュール内の、関数指定でインポート # from module_name import function_0, function_1, function_2 # インポートして、関数のエイリアスを定義 # from pizza import make_pizza as mp # インポートして、モジュールレベルでエイリアスを定義 # im...
Python
zaydzuhri_stack_edu_python
string programmers 12905. 가장 큰 정사각형 찾기 url: https://programmers.co.kr/learn/courses/30/lessons/12905 writer: Harim Kang Language: Python3 Date: 2021.02.09 Status: Success, Runtime: 28 ms, Memory Usage: 14.6 MB function solution board begin comment Write your code here set answer = 0 comment check all zeros for i in ran...
""" programmers 12905. 가장 큰 정사각형 찾기 url: https://programmers.co.kr/learn/courses/30/lessons/12905 writer: Harim Kang Language: Python3 Date: 2021.02.09 Status: Success, Runtime: 28 ms, Memory Usage: 14.6 MB """ def solution(board): # Write your code here answer = 0 # check all zeros for i in range(len...
Python
zaydzuhri_stack_edu_python
from functools import reduce try begin from math import gcd end except any begin from fractions import gcd end class LCM begin function __init__ self arg begin if type arg in list list tuple begin set arr = arg end set lcm = call lcm_list arr end function function lcm_base self x y begin return x * y // call gcd x y en...
from functools import reduce try: from math import gcd except: from fractions import gcd class LCM: def __init__(self,arg): if type(arg) in [list,tuple]: self.arr=arg self.lcm=self.lcm_list(self.arr) def lcm_base(self,x,y): return (x*y)//gcd(x,y) ...
Python
zaydzuhri_stack_edu_python
from rouge import Rouge set rouge = call Rouge set result = list string 我 是 谁 , 这是 在 哪里 呢 ? string 希望 你是 一个 好 孩子 。 set gold = list string 我 喜欢 你 , 在 哪里 ? string 明天 会 更好 的 ,小 孩子 。 set rouge_score = call get_scores result gold print rouge_score at 0 at string rouge-1 print rouge_score at 0 at string rouge-2 print rouge_s...
from rouge import Rouge rouge = Rouge() result=['我 是 谁 , 这是 在 哪里 呢 ?','希望 你是 一个 好 孩子 。'] gold=['我 喜欢 你 , 在 哪里 ?','明天 会 更好 的 ,小 孩子 。'] rouge_score = rouge.get_scores(result, gold) print(rouge_score[0]["rouge-1"]) print(rouge_score[0]["rouge-2"]) print(rouge_score[0]["rouge-l"]) #result # {'f': 0.6249999950781252, 'p': 0...
Python
zaydzuhri_stack_edu_python
from projecteuler.utils import get_input function names_scores names_raw begin set names = split replace names_raw string " string string , sort names set alphabetical_values = list comprehension sum list comprehension ordinal letter - ordinal string A + 1 for letter in name for name in names return sum generator expre...
from projecteuler.utils import get_input def names_scores(names_raw: str) -> int: names = names_raw.replace('"', '').split(',') names.sort() alphabetical_values = [sum([ord(letter) - ord('A') + 1 for letter in name]) for name in names] return sum(value * (index + 1) for index, value in enumerate(alphab...
Python
zaydzuhri_stack_edu_python
import turtle set mypen = call Turtle call color string red string yellow call begin_fill for _ in range 6 begin call circle 60 steps=5 call left 60 end call end_fill call done
import turtle mypen = turtle.Turtle() mypen.color("red", "yellow") mypen.begin_fill() for _ in range(6): mypen.circle(60, steps=5) mypen.left(60) mypen.end_fill() turtle.done()
Python
zaydzuhri_stack_edu_python
function get_ids data N_max begin set id_data = copy data at list string molecule_name string id comment write molecules into one line set id_data = apply group by id_data string molecule_name lambda x -> reshape values - 1 comment pad with nans set id_list = list for i in range length id_data begin set n = N_max * 2 ...
def get_ids(data, N_max): id_data = data[['molecule_name', 'id']].copy() # write molecules into one line id_data = id_data.groupby('molecule_name').apply(lambda x: x.values.reshape(-1)) # pad with nans id_list = [] for i in range(len(id_dat...
Python
nomic_cornstack_python_v1
from turtle import * set pantalla = call Screen setup pantalla 425 225 call screensize 400 200 set tortuga = call Turtle call left 90 comment Tortuga con forma de tortuga. call shape string turtle comment Sello de la tortuga en el punto (0,0) call stamp for i in range 12 begin call penup call forward 50 call stamp back...
from turtle import * pantalla = Screen() pantalla.setup(425,225) pantalla.screensize(400,200) tortuga = Turtle() tortuga.left(90) tortuga.shape("turtle") # Tortuga con forma de tortuga. tortuga.stamp() # Sello de la tortuga en el punto (0,0) for i in range(12): tortuga.penup() tortuga.forward(50) tortuga...
Python
zaydzuhri_stack_edu_python
function encode_cards cards_str begin set plane = zeros 54 dtype=int set joker_counter = 0 for card_str in cards_str begin if card_str == string 0 and joker_counter == 0 begin comment handle the first joker situation set joker_counter = 1 set index = card_encoding_dict at string 01 set plane at index = 1 end else if ca...
def encode_cards(cards_str): plane = np.zeros(54, dtype=int) joker_counter = 0 for card_str in cards_str: if card_str == '0' and joker_counter == 0: # handle the first joker situation joker_counter = 1 index = card_encoding_dict['01'] plane[index] = 1 ...
Python
nomic_cornstack_python_v1
function HasTexture self begin return false end function
def HasTexture(self): return False
Python
nomic_cornstack_python_v1
function multiplicationTable a b begin for i in range 1 b + 1 begin print format string {} x {} = {} a i a * i end end function comment prints a multiplication table for 9 and 10 call multiplicationTable 9 10
def multiplicationTable(a, b): for i in range(1, b+1): print("{} x {} = {}".format(a, i, a * i)) multiplicationTable(9, 10) #prints a multiplication table for 9 and 10
Python
jtatman_500k
from PredictionAlgorithms.SentimentAnalysis.SentimentAnalysis import SentimentAnalysis from PredictionAlgorithms.SentimentAnalysis.TextProcessing import TextProcessing from PredictionAlgorithms.PredictiveConstants import PredictiveConstants as pc from PredictionAlgorithms.PredictiveUtilities import PredictiveUtilities ...
from PredictionAlgorithms.SentimentAnalysis.SentimentAnalysis import SentimentAnalysis from PredictionAlgorithms.SentimentAnalysis.TextProcessing import TextProcessing from PredictionAlgorithms.PredictiveConstants import PredictiveConstants as pc from PredictionAlgorithms.PredictiveUtilities import PredictiveUtilities ...
Python
zaydzuhri_stack_edu_python
comment get lines to array set file = open string 07/input1.txt string r set Lines = call splitlines set Rules = list class Rule begin function __init__ self rule=string begin set rule = rule set bag = string set contents = list set quantitys = list set bag = call Bag split rule string bags contain at 0 if string n...
# get lines to array file = open('07/input1.txt', 'r') Lines = file.read().splitlines() Rules = [] class Rule(): def __init__(self, rule=""): self.rule = rule self.bag = "" self.contents = [] self.quantitys = [] self.bag = Bag(rule.split(" bags contain ")[0]) if "...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from PIL import Image from ydmapi import * class AttackYdm extends object begin function __init__ self begin set browser = call Chrome set url = string http://www.yundama.com/ end function comment 1. 获取网站首页截图 function get_index_shot self begin get browser url call save_screenshot string i...
from selenium import webdriver from PIL import Image from ydmapi import * class AttackYdm(object): def __init__(self): self.browser = webdriver.Chrome() self.url = 'http://www.yundama.com/' # 1. 获取网站首页截图 def get_index_shot(self): self.browser.get(self.url) self.browser.save_screenshot('index.png...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict set tuple n m = map int split input set yp = list for i in range m begin set tuple p y = map int split input append yp tuple y p i end set yp = sorted yp set code = list 0 * m set ctr = default dictionary int for i in range m begin set ctr at yp at i at 1 = ctr at yp at i at 1 + 1 s...
from collections import defaultdict n, m = map(int, input().split()) yp = [] for i in range(m): p, y = map(int, input().split()) yp.append((y, p, i)) yp = sorted(yp) code = [0] * m ctr = defaultdict(int) for i in range(m): ctr[yp[i][1]] += 1 x = ctr[yp[i][1]] code[yp[i][2]] = '{:06}{...
Python
zaydzuhri_stack_edu_python
function las_headers self begin comment FIXME laspy breaks with a large number of files return list comprehension header for las_obj in _las_objects end function
def las_headers(self): #FIXME laspy breaks with a large number of files return [las_obj.header for las_obj in self._las_objects]
Python
nomic_cornstack_python_v1
import re function append_lines string lines indent begin set line_list = split lines string for line in line_list begin set string = string + string * indent * 4 + line + string end return string end function function relate_stream_ports component stream_ports begin set component at string stream_input_ports = list ...
import re def append_lines(string, lines, indent): line_list = lines.split('\n') for line in line_list: string = string + (" " * indent * 4) + line + "\n" return string def relate_stream_ports(component, stream_ports): component["stream_input_ports"] = [] component["stream_output_ports"]...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 from random import randint set myList = list set length = 0 string " This class contains all of the sorting methods used by " the main class in sorting. I could have put all of the " code into one file, but I wanted to learn how to call " methods from different files. class C begin string...
#!/usr/bin/env python3 from random import randint myList = [] length = 0; """ " This class contains all of the sorting methods used by " the main class in sorting. I could have put all of the " code into one file, but I wanted to learn how to call " methods from different files. """ class C: """ ...
Python
zaydzuhri_stack_edu_python
function default_clean self begin call remove_outliers call _resample resampleRate=string H aggFun=string mean comment HACK: Remove this since keep index works? needs testing set modifiedData = drop missing modifiedData call add_degree_hours call _resample aggFun=string sum call add_time_columns call data_slice end fun...
def default_clean(self): self.remove_outliers() self._resample(resampleRate='H', aggFun='mean') # HACK: Remove this since keep index works? needs testing self.modifiedData = self.modifiedData.dropna() self.add_degree_hours() self._resample(aggFun='sum') self.add...
Python
nomic_cornstack_python_v1
function __init__ self level_dir begin set game_settings = game_settings call init call set_caption string Neural Network Evolution set width = game_settings at string width set height = game_settings at string height set screen = call set_mode tuple width height DOUBLEBUF set background = call convert set clock = call...
def __init__(self, level_dir): self.game_settings = game_settings pygame.init() pygame.display.set_caption("Neural Network Evolution") self.width = self.game_settings['width'] self.height = self.game_settings['height'] self.screen = pygame.display.set_mode((self.width, se...
Python
nomic_cornstack_python_v1
comment Author: Mohammadreza Hajy Heydary comment ================================================================================================================= comment This script contains all the necessary modules for predicting the property value for a given user input comment ====================================...
# Author: Mohammadreza Hajy Heydary # ================================================================================================================= # This script contains all the necessary modules for predicting the property value for a given user input # ============================================================...
Python
zaydzuhri_stack_edu_python
comment inf = open (r'C:\Users\79851\PycharmProjects\Alex\venv\GitHub\stepic_study\dataset_3363_3.txt','r') comment a = inf.read().replace('\n', ' ').lower().split() comment inf.close() comment a.sort() set b = dict set c = list set g = 0 comment проверям в ключах значение for i in a begin if i not in keys b begin co...
#inf = open (r'C:\Users\79851\PycharmProjects\Alex\venv\GitHub\stepic_study\dataset_3363_3.txt','r') #a = inf.read().replace('\n', ' ').lower().split() #inf.close() #a.sort() b = {} c = [] g = 0 for i in a:#проверям в ключах значение if i not in b.keys(): b[i] = len(i)#если нет, то добавляем g = max(b.values())...
Python
zaydzuhri_stack_edu_python
function rolling_window array window axis=0 stride=1 begin if is instance array Tensor begin assert axis == 0 msg string time axis must be 0 for torch tensors set arr = call unfold axis window stride set arange = array range length shape if length arange > 2 begin return permute arr 0 arange at - 1 *arange[1:-1] end re...
def rolling_window(array, window, axis=0, stride=1): if isinstance(array, torch.Tensor): assert axis==0, "time axis must be 0 for torch tensors" arr = array.unfold(axis, window, stride) arange = torch.arange(len(arr.shape)) if len(arange) > 2: return arr.permute(0,arange[...
Python
nomic_cornstack_python_v1
function split_train_val data begin comment idx = ((data['geolocation_id'] == 4) | (data['geolocation_id'] == 1)) & (data['segment_id'] % 6 == 0) set idx = data at string segment_id % 6 == 0 set training_x = data at string iq_sweep_burst at call logical_not idx set training_y = data at string target_type at call logica...
def split_train_val(data): # idx = ((data['geolocation_id'] == 4) | (data['geolocation_id'] == 1)) & (data['segment_id'] % 6 == 0) idx = (data['segment_id'] % 6 == 0) training_x = data['iq_sweep_burst'][np.logical_not(idx)] training_y = data['target_type'][np.logical_not(idx)] validation_x = data['iq_sweep_burst'...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import os , sys append path pardir from dataset.mnist import load_mnist from PIL import Image import numpy as np import pickle import perceptionFunc function loadMnist begin set tuple tuple x_train t_train tuple x_test t_test = call load_mnist flatten=true normalize=false print shape print...
# -*- coding: utf-8 -*- import os, sys sys.path.append(os.pardir) from dataset.mnist import load_mnist from PIL import Image import numpy as np import pickle import perceptionFunc def loadMnist(): (x_train, t_train), (x_test, t_test) = load_mnist(flatten=True, normalize=False) print(x_train.shape) print(t...
Python
zaydzuhri_stack_edu_python
while true begin set num = call raw_input string Enter a number: if num == string done begin break end end
while True: num= raw_input("Enter a number: ") if num == "done": break
Python
zaydzuhri_stack_edu_python
function cos data begin return cos data end function
def cos(data): return _make.cos(data)
Python
nomic_cornstack_python_v1
from datetime import datetime , timedelta comment There was an Run Time Error from the call below: comment tdelta = timedelta(days=0, seconds=tdelta.seconds) comment I ended up correcting that with help from: comment https://github.com/rvrheenen/OpenKattis/blob/master/Python/natrij/natrij.py comment I have anxiety whic...
from datetime import datetime, timedelta # There was an Run Time Error from the call below: # tdelta = timedelta(days=0, seconds=tdelta.seconds) # I ended up correcting that with help from: # https://github.com/rvrheenen/OpenKattis/blob/master/Python/natrij/natrij.py # I have anxiety which causes me to focus on one pa...
Python
zaydzuhri_stack_edu_python
function __isub__ self *args begin return call Point3D___isub__ self *args end function
def __isub__(self, *args): return _fife.Point3D___isub__(self, *args)
Python
nomic_cornstack_python_v1
import smtplib from email.message import EmailMessage from string import Template from pathlib import Path from sms import send_sms function send_email begin set html = call Template call read_text set email = call EmailMessage set email at string from = string Ayush set email at string to = string *****@gmail.com set ...
import smtplib from email.message import EmailMessage from string import Template from pathlib import Path from sms import send_sms def send_email(): html = Template(Path('Template/index.html').read_text()) email = EmailMessage() email['from'] = 'Ayush' email['to'] = '*****@gmail.com' email['subj...
Python
zaydzuhri_stack_edu_python
function has_resource_provider self begin return string provider in spec end function
def has_resource_provider(self) -> bool: return 'provider' in self.spec
Python
nomic_cornstack_python_v1
string Section 8 Challenge - Input and Output (I/O) Write a program to append the times tables to our jabberwocky poem in sample.txt. We want the tables from 2 to 12 (similar to the output from the For loops part 2 lecture in section 6). The first column of numbers should be right justified. As an example, the 2 times ...
""" Section 8 Challenge - Input and Output (I/O) Write a program to append the times tables to our jabberwocky poem in sample.txt. We want the tables from 2 to 12 (similar to the output from the For loops part 2 lecture in section 6). The first column of numbers should be right justified. As an example, the 2 times ta...
Python
zaydzuhri_stack_edu_python