code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function getEdges self fromVol begin string Return the edges available from fromVol. return list comprehension diff toDict d for d in call getEdges call vol fromVol end function
def getEdges(self, fromVol): """ Return the edges available from fromVol. """ return [self.toDict.diff(d) for d in self.butterStore.getEdges(self.toObj.vol(fromVol))]
Python
jtatman_500k
comment Problem No.: 1948 comment Solver: Jinmin Goh comment Date: 20220713 comment URL: https://www.acmicpc.net/problem/1948 import sys function main begin set n = integer right strip read line stdin set m = integer right strip read line stdin set graph = list comprehension list for _ in range n + 1 set degree = list...
# Problem No.: 1948 # Solver: Jinmin Goh # Date: 20220713 # URL: https://www.acmicpc.net/problem/1948 import sys def main(): n = int(sys.stdin.readline().rstrip()) m = int(sys.stdin.readline().rstrip()) graph = [[] for _ in range(n + 1)] degree = [0 for _ in range(n + 1)] f...
Python
zaydzuhri_stack_edu_python
function number_of_lines filename=string begin set count = 0 with open filename mode=string r encoding=string utf-8 as reading begin for lines in reading begin set count = count + 1 end end return count end function
def number_of_lines(filename=""): count = 0 with open(filename, mode='r', encoding='utf-8') as reading: for lines in reading: count += 1 return count
Python
nomic_cornstack_python_v1
function assign_project_to_client self project=none client_id=none begin set is_project = type project is Project set one_not_set = project is none or client_id is none set client_exists = client_id in list comprehension client_id for c in client_list set client_is_self = client_id == client_id comment cancel, if eithe...
def assign_project_to_client(self, project=None, client_id=None): is_project = type(project) is Project one_not_set = project is None or client_id is None client_exists = client_id in [c.client_id for c in self.client_list] client_is_self = client_id == project.client_id # cance...
Python
nomic_cornstack_python_v1
function get_absolute_weeks_url self begin return reverse string bowling_entry_league_weeks args=list pk end function
def get_absolute_weeks_url(self): return reverse('bowling_entry_league_weeks', args=[self.pk])
Python
nomic_cornstack_python_v1
comment Problem C of ENME 337 Final Project comment Failure Probability Analysis from random import normalvariate import PartA from matplotlib import pyplot as plt comment All given values from the table,these are used in the final function## comment Do = 88.9 #pipe outer diameter, [mm] comment t =11.1252 #pipe thickne...
#Problem C of ENME 337 Final Project #Failure Probability Analysis from random import normalvariate import PartA from matplotlib import pyplot as plt ##All given values from the table,these are used in the final function## ##Do = 88.9 #pipe outer diameter, [mm] ##t =11.1252 #pipe thickness, [mm] ##a ...
Python
zaydzuhri_stack_edu_python
import ScriptSetup import Main.config as config import Internals.Utils.wlogger as wlogger import HardwareControl.Eyes.wcontroller as wcontroller import time print string Calibrating comment Set the logger up. call setup_loggers log_directory set myController = call Controller comment Turn current calibration off before...
import ScriptSetup import Main.config as config import Internals.Utils.wlogger as wlogger import HardwareControl.Eyes.wcontroller as wcontroller import time print("Calibrating") # Set the logger up. wlogger.setup_loggers(config.log_directory) myController = wcontroller.Controller() # Turn current calibration off b...
Python
zaydzuhri_stack_edu_python
function encryptionShift text index begin set s = text set transformedChar = string set transformedChar = ordinal s at index + 1 if transformedChar > 90 begin set transformedChar = character ordinal s at index + 1 - 26 end else begin set transformedChar = character transformedChar end print string Single Shift Encrypt...
def encryptionShift(text, index): s=text transformedChar="" transformedChar = ord(s[index]) + 1 if(transformedChar > 90): transformedChar=chr(ord(s[index]) + 1 - 26) else: transformedChar = chr(transformedChar) print("Single Shift Encrypted text: ") return s[:index] + trans...
Python
nomic_cornstack_python_v1
class Vector begin function __init__ self x y begin set x = x set y = y end function function length self begin return x ^ 2 + y ^ 2 ^ 1 / 2 end function function add self other begin return call Vector x + x y + y end function function subtract self other begin return call Vector x - x y - y end function end class
class Vector: def __init__(self, x, y): self.x = x self.y = y def length(self): return (self.x**2 + self.y**2)**(1/2) def add(self, other): return Vector(self.x + other.x, self.y + other.y) def subtract(self, other): return Vector(self.x - other.x, self.y - oth...
Python
flytech_python_25k
import numpy as np from sklearn import datasets from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge , LinearRegression from sklearn.linear_model import Lasso import random function change_reg_in_liste reg begin set w_LinearRegrassion...
import numpy as np from sklearn import datasets from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split from sklearn.linear_model import Ridge, LinearRegression from sklearn.linear_model import Lasso import random def change_reg_in_liste(reg): w_LinearRegrassion = [] ...
Python
zaydzuhri_stack_edu_python
from graphics import * import collections import math import re class State begin comment The key of neighbors is the transtition value, the value on the "edge" comment And teh neighbors[key] is actually the State to which it points set key = none set final = 0 set initial = 0 comment neighbors={} NEVEEEEEEEEERRRRRRRRR...
from graphics import * import collections import math import re class State: #The key of neighbors is the transtition value, the value on the "edge" #And teh neighbors[key] is actually the State to which it points key=None final=0 initial=0 #neighbors={} NEVEEEEEEEEERRRRRRRRR neighbors=None...
Python
zaydzuhri_stack_edu_python
import sys function in_order_digits num begin comment make sure digits are in descending order set prev_digit = 9 while num > 0 begin set digit = num % 10 if digit > prev_digit begin return false end set num = num // 10 set prev_digit = digit end return true end function function exist_adjacent_digits num begin comment...
import sys def in_order_digits(num: int): # make sure digits are in descending order prev_digit = 9 while (num > 0): digit = num % 10 if digit > prev_digit: return False num = num // 10 prev_digit = digit return True def exist_adjacent_digits(num: int): ...
Python
zaydzuhri_stack_edu_python
comment Classes du programme "grille" import pygame from pygame.locals import * call init from constantes10x10_2 import * comment =============================================================================== comment AFFICHAGE DES GRILLES DE JEU comment =================================================================...
# Classes du programme "grille" import pygame from pygame.locals import * pygame.init() from constantes10x10_2 import * #=============================================================================== # AFFICHAGE DES GRILLES DE JEU #===============================================================...
Python
zaydzuhri_stack_edu_python
function extract_sum inp dimensions offset begin set tmp = call VectorInt list call extract_sum inp tmp dimensions at 1 dimensions at 2 dimensions at 0 offset debug string Extract sum: Extracted with offset + string offset + string and dimensions + string dimensions if debug_mode begin debug string Extracted U starts w...
def extract_sum(inp, dimensions, offset): tmp = minionn.VectorInt([]) minionn.extract_sum(inp, tmp, dimensions[1], dimensions[2], dimensions[0], offset) logger.debug("Extract sum: Extracted with offset " + str(offset)+ " and dimensions " + str(dimensions)) if config.debug_mode...
Python
nomic_cornstack_python_v1
function create_widget self parent tree begin return call QRadioButton parent end function
def create_widget(self, parent, tree): return QRadioButton(parent)
Python
nomic_cornstack_python_v1
function recovery_source_protection_container_name self begin return get pulumi self string recovery_source_protection_container_name end function
def recovery_source_protection_container_name(self) -> pulumi.Output[str]: return pulumi.get(self, "recovery_source_protection_container_name")
Python
nomic_cornstack_python_v1
function force_balanced_LP self begin string Force balanced lamination parameters The lamination parameters `\xi_{A2}` and `\xi_{A4}` are set to null to force a balanced laminate. set tuple dummy xiA1 xiA2 xiA3 xiA4 = xiA set xiA = array list 1 xiA1 0 xiA3 0 dtype=float64 call calc_ABDE_from_lamination_parameters end f...
def force_balanced_LP(self): r"""Force balanced lamination parameters The lamination parameters `\xi_{A2}` and `\xi_{A4}` are set to null to force a balanced laminate. """ dummy, xiA1, xiA2, xiA3, xiA4 = self.xiA self.xiA = np.array([1, xiA1, 0, xiA3, 0], dtype=np.float...
Python
jtatman_500k
import PySimpleGUI as sg import os.path from model import ColorizationNet from utils import * import torch set img_size = tuple 350 350 set img_box_size = tuple 800 350 set image_orig_str = string -IMAGE_ORIG- set image_pred_str = string -IMAGE-PRED- set layout = list list call Text string Automatic Image Colorization ...
import PySimpleGUI as sg import os.path from model import ColorizationNet from utils import * import torch img_size = (350, 350) img_box_size = (800, 350) image_orig_str = "-IMAGE_ORIG-" image_pred_str = "-IMAGE-PRED-" layout = [[sg.Text("Automatic Image Colorization")]] file_list_column = [ [ ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import os from PIL import Image , ImageDraw import numpy as np from math import ceil , floor string # dir_data = './data_generated' dir_images = dir_data + '/images' dir_contents = dir_data + '/contents' # function getFilesInDirect path str_dot_ext begin set file_list = list for file in l...
# -*- coding: utf-8 -*- import os from PIL import Image,ImageDraw import numpy as np from math import ceil, floor ''' # dir_data = './data_generated' dir_images = dir_data + '/images' dir_contents = dir_data + '/contents' # ''' # def getFilesInDirect(path, str_dot_ext): file_list = [] ...
Python
zaydzuhri_stack_edu_python
function game_of_life board begin set output = list comprehension list comprehension string _ for a in range length board at 0 for b in range length board set output_string = string for i in range length board begin for j in range length board at i begin set neighbors = 0 for k in range max 0 i - 1 min length board i ...
def game_of_life(board): output = [['_' for a in range(len(board[0]))] for b in range(len(board))] output_string = '' for i in range(len(board)): for j in range(len(board[i])): neighbors = 0 for k in range(max(0, i - 1), min(len(board), i + 2)): for l in range...
Python
zaydzuhri_stack_edu_python
comment https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Digit-by-digit_calculation comment current value set c = 0 comment part of the root found so far set p = 0 comment x is the greatest digit such that x(20p + x) <= c comment y = x(20p + x) set digit_sum = 0 for non_square in list comprehension x for...
# https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Digit-by-digit_calculation # current value c = 0 # part of the root found so far p = 0 # x is the greatest digit such that x(20p + x) <= c # y = x(20p + x) digit_sum = 0 for non_square in [x for x in range(1,100) if x not in map(lambda y: y*y, r...
Python
zaydzuhri_stack_edu_python
string -Medium- *Bit Manipulation* You are given an integer array pref of size n. Find and return the array arr of size n that satisfies: pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]. Note that ^ denotes the bitwise-xor operation. It can be proven that the answer is unique. Example 1: Input: pref = [5,2,0,3,1] Output: [5,7...
''' -Medium- *Bit Manipulation* You are given an integer array pref of size n. Find and return the array arr of size n that satisfies: pref[i] = arr[0] ^ arr[1] ^ ... ^ arr[i]. Note that ^ denotes the bitwise-xor operation. It can be proven that the answer is unique. Example 1: Input: pref = [5,2,0,3,1] Output...
Python
zaydzuhri_stack_edu_python
function _process_files self begin call _process_files_defaults call _process_files_requirements end function
def _process_files(self): self._process_files_defaults() self._process_files_requirements()
Python
nomic_cornstack_python_v1
function print_reverse lst begin if expression is instance lst list then list comprehension call print_reverse item for item in lst at slice : : - 1 else print lst end function call print_reverse colors
def print_reverse(lst): [print_reverse(item) for item in lst[::-1]] if isinstance(lst, list) else print(lst) print_reverse(colors)
Python
jtatman_500k
function checkout event context begin debug string Received event: %s event set checkout_event = loads event at string body set amount = checkout_event at string payment at string amount debug string Publishing checkout event with amount: %s amount call publish Message=dumps checkout_event MessageAttributes=dict string...
def checkout(event, context): LOG.debug('Received event: %s', event) checkout_event = json.loads(event['body']) amount = checkout_event['payment']['amount'] LOG.debug('Publishing checkout event with amount: %s', amount) TOPIC.publish( Message=json.dumps(checkout_event), MessageAttr...
Python
nomic_cornstack_python_v1
function test_add_file_to_list self begin pass end function
def test_add_file_to_list(self): pass
Python
nomic_cornstack_python_v1
function main begin try begin set http_server = call WSGIServer tuple string 0.0.0.0 8080 app log=logging error_log=logging call serve_forever end except Exception as exc begin error message exception call format_exc end finally begin comment get last entry and insert build appended if not completed comment Do somethin...
def main(): try: http_server = WSGIServer(('0.0.0.0', 8080), app, log=logging, error_log=logging) http_server.serve_forever() except Exception as exc: logger.error(exc.message) log...
Python
nomic_cornstack_python_v1
from ik.tree.ds import TreeNode function build_binary_search_tree preorder begin set inorder = sorted preorder set index_map = dict for i in range length inorder begin set index_map at inorder at i = i end function helper inorder i_start i_end preorder p_start p_end begin comment base case if i_start > i_end begin ret...
from ik.tree.ds import TreeNode def build_binary_search_tree(preorder): inorder = sorted(preorder) index_map = {} for i in range(len(inorder)): index_map[inorder[i]] = i def helper(inorder, i_start, i_end, preorder, p_start, p_end): # base case if i_start > i_end: ...
Python
zaydzuhri_stack_edu_python
function is_valid_match match begin set valid_qids = call get_valid_queue_ids if match at string queue_id in valid_qids begin return true end else begin return false end end function
def is_valid_match(match): valid_qids = dc.get_valid_queue_ids() if match['queue_id'] in valid_qids: return(True) else: return(False)
Python
nomic_cornstack_python_v1
comment Write a function, zeta1(n), that takes a positive integer, n, and comment returns the value 1 + 1/2 + 1/3 + 1/4 + ⋯ + 1/n. function zetal n begin set sum = 0 for i in range 1 n + 1 begin set sum = sum + 1 / i end return sum end function comment Write a function, product(a), that takes an array, a, of numbers an...
################################################################### # Write a function, zeta1(n), that takes a positive integer, n, and # returns the value 1 + 1/2 + 1/3 + 1/4 + ⋯ + 1/n. ################################################################### def zetal(n): sum = 0 for i in range(1,n+1): s...
Python
zaydzuhri_stack_edu_python
function tokenize header foldCase=true begin set tokens = http_tokens set ctls = http_ctls set string = join string , header set start = 0 set cur = 0 set quoted = false set qpair = false set inSpaces = - 1 set qstring = none for x in string begin if quoted begin if qpair begin set qpair = false set qstring = qstring +...
def tokenize(header, foldCase=True): tokens = http_tokens ctls = http_ctls string = ",".join(header) start = 0 cur = 0 quoted = False qpair = False inSpaces = -1 qstring = None for x in string: if quoted: if qpair: qpair = False ...
Python
nomic_cornstack_python_v1
function options self begin if not _options begin call update_options end comment type: ignore return _options end function
def options(self) -> Options: if not self._options: self.update_options() return self._options # type: ignore
Python
nomic_cornstack_python_v1
function make_data self ncvariables begin set datas = list comprehension name for name in keys ncvariables if find name string Data == 0 for d in datas begin set data_type = split d string . at 1 set self at data_type = list end for data_type in keys self begin set keys = list comprehension split name string . at - 1 ...
def make_data(self, ncvariables): datas = [name for name in ncvariables.keys() if name.find('Data') == 0] for d in datas: data_type = d.split('.')[1] self[data_type] = [] for data_type in self.keys(): keys = [name.split('.')[-1] for name in ncvariables.keys() ...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string ! Descripción de Léxemas ? Clase con métodos que retornan una descripción detallada dependiendo el lexema dado @author Gabriel @date 2020/07/19 @version 0.1 class LexemeDesc begin function __init__ self begin set countlexem = 0 end function comment Obtiene la descripción de los iden...
# -*- coding: utf-8 -*- """ ! Descripción de Léxemas ? Clase con métodos que retornan una descripción detallada dependiendo el lexema dado @author Gabriel @date 2020/07/19 @version 0.1 """ class LexemeDesc: def __init__(self): self.countlexem = 0 #Obtiene la descripción de los i...
Python
zaydzuhri_stack_edu_python
function _OnGstMessage self bus message begin set t = type if t == MESSAGE_EOS begin call set_state STATE_NULL release lock end else if t == MESSAGE_ERROR begin call set_state STATE_NULL release lock end end function comment NOTE(damonkohler): Ignoring errors for now.
def _OnGstMessage(self, bus, message): t = message.type if t == gst.MESSAGE_EOS: self.pipe.set_state(gst.STATE_NULL) self.lock.release() elif t == gst.MESSAGE_ERROR: self.pipe.set_state(gst.STATE_NULL) self.lock.release() # NOTE(damonkohler): Ignoring errors for now.
Python
nomic_cornstack_python_v1
function printinfo arg1 *vartuple begin print string Output is: print arg1 for var in vartuple begin print var end return end function
def printinfo( arg1, *vartuple ): print('Output is: ') print(arg1) for var in vartuple: print(var) return
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment librerie import math comment Variabili comment Kg set m = 1.6 comment m/s^2 set g = 9.81 comment gradi set angle_alpha = 22 comment calcolo seno e coseno comment converto l'angolo da gradi a radianti set cos_alpha = cos call radians angle_alpha comment converto l'angolo da gradi a radia...
#!/usr/bin/python #librerie import math #Variabili m = 1.6 #Kg g = 9.81 #m/s^2 angle_alpha = 22 #gradi #calcolo seno e coseno cos_alpha = math.cos(math.radians(angle_alpha)) #converto l'angolo da gradi a radianti sin_alpha = math.sin(math.radians(angle_alpha)) #converto l'angolo da gradi a radianti print(cos_alpha...
Python
zaydzuhri_stack_edu_python
comment Print the first letter of the following string set school = string McHenry County College comment print the length of the school string print length school comment Use a while loop to print each character (including spaces) in the school variable set index = 0 while index < length school begin set letter = scho...
# Print the first letter of the following string school = "McHenry County College" # print the length of the school string print(len(school)) # Use a while loop to print each character (including spaces) in the school variable index = 0 while index < len(school): letter = school[index]
Python
zaydzuhri_stack_edu_python
function __get__ self instance owner begin set resource_meta = instance return self end function
def __get__(self, instance, owner): self.resource_meta = instance return self
Python
nomic_cornstack_python_v1
function is_authenticated self begin return pk is not none end function
def is_authenticated(self): return self.pk is not None
Python
nomic_cornstack_python_v1
function bitwise_add_multiply a b c begin comment Step 1: Add the two integers using bitwise operators while b != 0 begin set carry = a ? b set a = a ? b set b = carry ? 1 end comment Step 2: Multiply the result by the third integer using bitwise operators set result = 0 for _ in range c begin set result = result + a e...
def bitwise_add_multiply(a, b, c): # Step 1: Add the two integers using bitwise operators while b != 0: carry = a & b a = a ^ b b = carry << 1 # Step 2: Multiply the result by the third integer using bitwise operators result = 0 for _ in range(c): result += a re...
Python
jtatman_500k
import re import string import unicodedata from mrjob.job import MRJob from mrjob.protocol import TextProtocol , ReprProtocol set pattern = compile string [a-zA-Z]+ function split_with_re line re_compiler=pattern begin set translator = call maketrans punctuation string * length punctuation return find all call transla...
import re import string import unicodedata from mrjob.job import MRJob from mrjob.protocol import TextProtocol, ReprProtocol pattern = re.compile(r"[a-zA-Z]+") def split_with_re(line, re_compiler=pattern): translator = str.maketrans(string.punctuation, ' '*len(string.punctuation)) return re_compiler....
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string Author: Dennis/JIAJIE LIANG Created: 10/30/2015 FileName: Data Analytics_SVM.py comment sklearn library from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model.logistic import LogisticRegression from sklearn.svm import SVC from sklearn.pipeline import Pi...
#!/usr/bin/env python """ Author: Dennis/JIAJIE LIANG Created: 10/30/2015 FileName: Data Analytics_SVM.py """ # sklearn library from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model.logistic import LogisticRegression from sklearn.svm import SVC from sklearn.pipeline import Pipeline fro...
Python
zaydzuhri_stack_edu_python
function gcopy to_layer from_layer begin return list tuple to_layer from_layer string u tuple to_layer to_layer string d end function
def gcopy(to_layer, from_layer): return [(to_layer,from_layer,'u'), (to_layer,to_layer,'d')]
Python
nomic_cornstack_python_v1
function _validate_service_account prop value begin if not value begin return none end call validate_service_account _name value return value end function
def _validate_service_account(prop, value): if not value: return None validate_service_account(prop._name, value) return value
Python
nomic_cornstack_python_v1
function get_X self x begin set X0 = stack tuple ones length x x axis=1 comment Number of covariate signals set p = length columns - 3 comment Didn't implement if p > 0 return X0 end function
def get_X(self, x): X0 = np.stack((np.ones(len(x)), x), axis=1) p = len(self.df.columns) - 3 # Number of covariate signals # Didn't implement if p > 0 return X0
Python
nomic_cornstack_python_v1
comment This is a sample Python script. comment Press Maj+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 csv from django.contrib.gis.geos import fromstr import os comment Press the green button in the gutter...
# This is a sample Python script. # Press Maj+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 csv from django.contrib.gis.geos import fromstr import os # Press the green button in the gutter to run the script. d...
Python
zaydzuhri_stack_edu_python
async function swagger_handler request begin return call json_response app at string _swagger_config end function
async def swagger_handler(request): return web.json_response(app["_swagger_config"])
Python
nomic_cornstack_python_v1
from menus.base_menu import BaseMenu from utils import raise_exception , get_option_input from exceptions import ExitFromMenuException from utils_for_db import select_all_recipes import json class RecipeList extends BaseMenu begin set header = string *****Recipe List***** set options = string [1] Exit set next_menus = ...
from menus.base_menu import BaseMenu from utils import raise_exception, get_option_input from exceptions import ExitFromMenuException from utils_for_db import select_all_recipes import json class RecipeList(BaseMenu): header = "*****Recipe List*****" options = "[1] Exit" next_menus = {'1': lambda *_...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import math set dataset = read csv string H:/Software/Machine learning/Dataset/Logistice Regression/net.csv set x = drop dataset list string User ID string Purchased axis=1 set y = dataset at string Purchased set x = array x set...
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import math dataset = pd.read_csv('H:/Software/Machine learning/Dataset/Logistice Regression/net.csv') x = dataset.drop(['User ID' , 'Purchased'] , axis = 1) y = dataset['Purchased'] x = np.array(x) y = np.array(y) x = (x ...
Python
zaydzuhri_stack_edu_python
function find_flagging_summary_dir diagnostics begin if not diagnostics and exists path diagnostics begin return none end set potential_flag_dir = list diagnostics + string /Flagging_Summaries diagnostics for flag_dir in potential_flag_dir begin if exists path flag_dir begin set summaries = glob glob flag_dir + string ...
def find_flagging_summary_dir(diagnostics): if not (diagnostics and os.path.exists(diagnostics)): return None potential_flag_dir = [diagnostics+'/Flagging_Summaries', diagnostics] for flag_dir in potential_flag_dir: if os.path.exists(flag_dir): summaries = glob.glob(flag_dir...
Python
nomic_cornstack_python_v1
function add_labels_to_issue self installation_id repo_owner repo_name issue_num predictions begin comment take an action if the prediction is confident enough if predictions at string labels begin set tuple label_names label_probabilities = call filter_specified_labels repo_owner repo_name predictions end else begin s...
def add_labels_to_issue(self, installation_id, repo_owner, repo_name, issue_num, predictions): # take an action if the prediction is confident enough if predictions['labels']: label_names, label_probabilities = self.filter_specified_labels(repo_owner, ...
Python
nomic_cornstack_python_v1
function Kcross self theta begin assert length theta == n_hyperparameters msg string dimensions do not match return zeros tuple n n_cross end function
def Kcross(self,theta): assert len(theta)==self.n_hyperparameters, 'dimensions do not match' return SP.zeros((self.n,self.n_cross))
Python
nomic_cornstack_python_v1
function get_selected_params self begin return dict string gamma best_gamma ; string best_alpha best_alpha end function
def get_selected_params(self) -> dict: return { 'gamma': self.best_gamma, 'best_alpha': self.best_alpha, }
Python
nomic_cornstack_python_v1
function size self begin if _size is none begin comment Default size to a ulong. set _size = call c_ulong end return call pointer _size end function
def size(self): if self._size is None: # Default size to a ulong. self._size = c_ulong() return pointer(self._size)
Python
nomic_cornstack_python_v1
function change_sound link_to begin with open directory name path absolute path path __file__ + string \data.json string r as test begin set f = load json test end set f at string stop_sound = link_to with open directory name path absolute path path __file__ + string \data.json string w as test begin dump f test indent...
def change_sound(link_to:str): with open(os.path.dirname(os.path.abspath(__file__))+'\\data.json', 'r') as test: f = json.load(test) f['stop_sound'] = link_to with open(os.path.dirname(os.path.abspath(__file__))+'\\data.json', 'w') as test: json.dump(f, test, indent=2)
Python
nomic_cornstack_python_v1
comment Hashmap.delete function delete self entry begin delete comment remove the entry from the hashmap set list = contentHash at hexdigest set newlist = list for e in list begin if e != entry begin append newlist e end end comment if there are no more entries for this hashval, remove comment it from the dictionary m...
def delete(self, entry): # Hashmap.delete entry.delete() # remove the entry from the hashmap list=self.contentHash[entry.hexdigest] newlist = [] for e in list: if e != entry: newlist.append(e) # if there are no more entrie...
Python
nomic_cornstack_python_v1
function adjusted_rand_score labels_true labels_pred begin set ct = call from_labels labels_true labels_pred return call adjusted_rand_index end function
def adjusted_rand_score(labels_true, labels_pred): ct = ClusteringMetrics.from_labels(labels_true, labels_pred) return ct.adjusted_rand_index()
Python
nomic_cornstack_python_v1
comment Inspired from https://github.com/ozgur/python-linkedin comment LinkedIn app configuration comment https://localhost:8080/auth/linkedin/callback comment Insert key and secret set KEY = string KEY set SECRET = string SECRET comment Credentials you get from registering a new application set client_id = KEY set cli...
#Inspired from https://github.com/ozgur/python-linkedin #LinkedIn app configuration #https://localhost:8080/auth/linkedin/callback #Insert key and secret KEY="KEY" SECRET="SECRET" # Credentials you get from registering a new application client_id = KEY client_secret = SECRET # OAuth endpoints given in the LinkedIn AP...
Python
zaydzuhri_stack_edu_python
function build self x begin set type = call _check_input x if type == string st begin set x = x + next call _terminalSymbolsGenerator call _build x end if type == string gst begin call _build_generalized x end end function
def build(self, x): type = self._check_input(x) if type == 'st': x += next(self._terminalSymbolsGenerator()) self._build(x) if type == 'gst': self._build_generalized(x)
Python
nomic_cornstack_python_v1
function isOnSaleSoon ticket begin return start_time > now end function
def isOnSaleSoon(ticket): return ticket.start_time > timezone.now()
Python
nomic_cornstack_python_v1
function address self begin return dict at string fhdhr at string address end function
def address(self): return self.config.dict["fhdhr"]["address"]
Python
nomic_cornstack_python_v1
comment https://atcoder.jp/contests/typical-algorithm/submissions/20050573 set N = integer input comment 終了日でソートするため、[ 終了日, 開始日 ]の順に格納する set BA = list for i in range N begin set tuple a b = list map int split input append BA list b a end sort BA set ans = 0 set last = 0 for tuple b a in BA begin if last < a begin set ...
# https://atcoder.jp/contests/typical-algorithm/submissions/20050573 N = int(input()) # 終了日でソートするため、[ 終了日, 開始日 ]の順に格納する BA = [] for i in range(N): a, b = list(map(int, input().split())) BA.append([b, a]) BA.sort() ans = 0 last = 0 for b, a in BA: if last < a: ans += 1 last = b print(ans)
Python
zaydzuhri_stack_edu_python
if alien_color == string green begin print string You got 5 points! end set alien_color = string red if alien_color == string green begin print string You got 5 points! end else begin print string You got 10 points! end set alien_color = string red if alien_color == string green begin set point = 5 end else if alien_co...
if alien_color == 'green': print("\nYou got 5 points!") alien_color = 'red' if alien_color == 'green': print('\nYou got 5 points!') else: print('\nYou got 10 points!') alien_color = 'red' if alien_color =='green': point = 5 elif alien_color == 'yellow': point = 10 else: point = 15 print('\nY...
Python
zaydzuhri_stack_edu_python
class Solution begin function firstMissingPositive self nums begin set small = 1 for i in nums begin if i == small begin set small = small + 1 end if small in nums begin set small = small + 1 end end return small end function end class
class Solution: def firstMissingPositive(self, nums: List[int]) -> int: small = 1 for i in nums: if i == small: small += 1 if small in nums: small += 1 return small
Python
zaydzuhri_stack_edu_python
function check_all_conditions begin set x = call check_size if x begin return x end set x = call check_color if x begin return x end set x = call check_tone if x begin return x end set x = call check_flavor if x begin return x end return none end function
def check_all_conditions(): x = check_size() if x: return x x = check_color() if x: return x x = check_tone() if x: return x x = check_flavor() if x: return x return None
Python
jtatman_500k
comment 普通程序员的简单生活 comment 计算一个程序员的基本工资收入(纯整数运算) set salary = 25000 set sa_total = 0 set sa_year = 0 for i in range 40 begin set sa_year = salary * 12 set sa_total = sa_total + sa_year print format str string 第 {0:2} 年,月工资 {1:6} ,年收入 {2:10} 元 i salary sa_year end print string ------------------------------- print forma...
#普通程序员的简单生活 #计算一个程序员的基本工资收入(纯整数运算) salary = 25000 sa_total = 0 sa_year = 0 for i in range(40): sa_year = salary * 12 sa_total = sa_total + sa_year print(str.format('第 {0:2} 年,月工资 {1:6} ,年收入 {2:10} 元',i,salary,sa_year)) print('-------------------------------') print(str.format('一生工资总收入 ...
Python
zaydzuhri_stack_edu_python
function setData self data role=UserRole exclusive=false begin set datadict at call __int__ = data if call __int__ == call __int__ and exclusive == false begin set datadict at call __int__ = data end if call __int__ == call __int__ and exclusive == false begin set datadict at call __int__ = data end call emitDataChange...
def setData(self, data, role=QtCore.Qt.UserRole, exclusive=False): self.datadict[role.__int__()] = data if role.__int__() == QtCore.Qt.DisplayRole.__int__() and exclusive==False: self.datadict[QtCore.Qt.EditRole.__int__()] = data if role.__int__() == QtCore.Qt.EditRole.__int__() and ...
Python
nomic_cornstack_python_v1
function main begin pass return none end function
def main(): pass return None
Python
nomic_cornstack_python_v1
function squash self message=none author=none begin call _check_connection set result = post call _squash_url headers=dict string user-agent string terminusdb-client-python/ { __version__ } json=dict string commit_info call _generate_commit message author auth=call _auth return loads call _finish_response result end fu...
def squash( self, message: Optional[str] = None, author: Optional[str] = None ) -> dict: self._check_connection() result = requests.post( self._squash_url(), headers={"user-agent": f"terminusdb-client-python/{__version__}"}, json={"commit_info": self._gen...
Python
nomic_cornstack_python_v1
function sorted_dim cube coord=string longitude begin set coord_to_sort = call coord coord assert ndim == 1 msg string Coord should be 1-dimensional. set tuple dim = call coord_dims coord_to_sort set index = list call slice none * ndim set index at dim = call argsort points set cube = cube at tuple index set coord = ca...
def sorted_dim(cube, coord="longitude"): coord_to_sort = cube.coord(coord) assert coord_to_sort.ndim == 1, "Coord should be 1-dimensional." (dim, ) = cube.coord_dims(coord_to_sort) index = [slice(None)] * cube.ndim index[dim] = np.argsort(coord_to_sort.points) cube = cube...
Python
nomic_cornstack_python_v1
comment Python GUI Tutorial - 9 - creating drop down menus from tkinter import * set root = call Tk function donothing begin set filewin = call Toplevel root set button = call Button filewin text=string Do nothing button call pack end function comment 1: create instance of Menu class set main_menu = call Menu root comm...
# Python GUI Tutorial - 9 - creating drop down menus from tkinter import * root = Tk() def donothing(): filewin = Toplevel(root) button = Button(filewin, text="Do nothing button") button.pack() #1: create instance of Menu class main_menu = Menu(root) #====================================================...
Python
zaydzuhri_stack_edu_python
function test_diff_numofparam_stmt self begin set input = string Function: main Body: printStrLn(); EndBody. set expect = string call TypeMismatchInStatement call CallStmt call Id string printStrLn list assert true call test input expect 416 end function
def test_diff_numofparam_stmt(self): input = """Function: main Body: printStrLn(); EndBody.""" expect = str(TypeMismatchInStatement(CallStmt(Id("printStrLn"), []))) self.assertTrue(TestChecker.test(input, expect, 416))
Python
nomic_cornstack_python_v1
import numpy as np from state import State class TicTacToe begin string Represents a TicTacToe game. function __init__ self player1 player2 begin set state = call State set turn = - 1 set players = call permutation list player1 player2 end function function switch_turn self begin set turn = turn * - 1 end function func...
import numpy as np from state import State class TicTacToe: """Represents a TicTacToe game.""" def __init__(self, player1, player2): self.state = State() self.turn = -1 self.players = np.random.permutation([player1, player2]) def switch_turn(self): self.turn *= -1 def handle_move(self, x, y):...
Python
zaydzuhri_stack_edu_python
function parse_add_person_to_group cls request begin if KEY_PERSON_ID in data and KEY_PROJECT_ID in data begin return dict KEY_PERSON_ID data at KEY_PERSON_ID ; KEY_PROJECT_ID data at KEY_PROJECT_ID end else begin return none end end function
def parse_add_person_to_group(cls, request): if KEY_PERSON_ID in request.data and KEY_PROJECT_ID in request.data: return { KEY_PERSON_ID: request.data[KEY_PERSON_ID], KEY_PROJECT_ID: request.data[KEY_PROJECT_ID], } else: return None
Python
nomic_cornstack_python_v1
from time import time from sklearn.ensemble import AdaBoostClassifier from sklearn import datasets , metrics from sklearn.model_selection import train_test_split import numpy as np comment Wczytywanie danych set test = call loadtxt string test.txt delimiter=string , set X = test at tuple slice : : slice 0 : 13 : se...
from time import time from sklearn.ensemble import AdaBoostClassifier from sklearn import datasets, metrics from sklearn.model_selection import train_test_split import numpy as np # Wczytywanie danych test = np.loadtxt('test.txt', delimiter=",") X = test[:, 0:13] train = np.loadtxt('train.txt', delimiter=",...
Python
zaydzuhri_stack_edu_python
function eat food is_healthy begin if is_healthy begin set ending = string because my body is a temple. end else begin set ending = string because YOLO! end return string I'm eating { food } { ending } end function function nap num_hours begin if num_hours >= 2 begin return string No! I overslept! I didn't mean to nap ...
def eat(food, is_healthy): if is_healthy: ending = "because my body is a temple." else: ending = "because YOLO!" return f"I'm eating {food} {ending}" def nap(num_hours): if num_hours >= 2: return f"No! I overslept! I didn't mean to nap for {num_hours} hours!" return f"I feel refreshed...
Python
zaydzuhri_stack_edu_python
comment ラムダ print string ********************************************* print string (1) comment 前提:先頭が大文字(capital)出なければならいルールの文字列 comment 以下の文章は小文字が混ざっている set l = list string Mon string tue string Wed string Thu string fri string sat string Sun function change_words words func begin for word in words begin print call f...
# ラムダ # print('*********************************************') print('(1)') # 前提:先頭が大文字(capital)出なければならいルールの文字列 ## 以下の文章は小文字が混ざっている l = ['Mon', 'tue', 'Wed', 'Thu', 'fri', 'sat', 'Sun'] def change_words(words, func): for word in words: print(func(word)) def sample_func(word): return word.capitalize()...
Python
zaydzuhri_stack_edu_python
string ---------------------------------------- AppendLastNToFirst ------------------------------------------ You have been given a singly linked list of integers along with an integer 'N'. Write a function to append the last 'N' nodes towards the front of the singly linked list and returns the new head to the list. ##...
""" ---------------------------------------- AppendLastNToFirst ------------------------------------------ You have been given a singly linked list of integers along with an integer 'N'. Write a function to append the last 'N' nodes towards the front of the singly linked list and returns the new head to the list. #...
Python
zaydzuhri_stack_edu_python
function __init__ self init_dict=dict date_fmt=string %Y-%m-%dT%H:%M:%SZ begin set data = dict update data init_dict set date_fmt = date_fmt end function
def __init__(self, init_dict={}, date_fmt='%Y-%m-%dT%H:%M:%SZ'): self.data = {} self.data.update(init_dict) self.date_fmt = date_fmt
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup import requests import time import unicodedata function getContractStats teamName begin set url = string https://www.basketball-reference.com/contracts/ { teamName } .html set page = get requests url set firstdiv = string div_contracts set headerRow = 1 comment Create a beautifulSoup objec...
from bs4 import BeautifulSoup import requests import time import unicodedata def getContractStats(teamName): url = f'https://www.basketball-reference.com/contracts/{teamName}.html' page = requests.get(url) firstdiv = 'div_contracts' headerRow = 1 # Create a beautifulSoup object soup = Beautifu...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt set days = list 1 2 3 4 5 set sleeping = list 7 8 6 11 7 set eating = list 2 3 4 3 2 set working = list 7 8 7 2 2 set playing = list 8 5 7 8 13 plot list list color=string m label=string Sleeping linewidth=5 plot list list color=string c label=string Eating linewidth=5 plot list lis...
import matplotlib.pyplot as plt days = [1,2,3,4,5] sleeping = [7,8,6,11,7] eating = [2,3,4,3,2] working = [7,8,7,2,2] playing = [8,5,7,8,13] plt.plot([],[],color='m',label='Sleeping',linewidth=5) plt.plot([],[],color='c',label='Eating',linewidth=5) plt.plot([],[],color='r',label='Working',linewidth=5) plt.plot([],[]...
Python
zaydzuhri_stack_edu_python
function wasb connection_name path_from path_to is_file check_path raise_errors sync_fw begin call _download connection_name=connection_name connection_kind=WASB path_from=path_from path_to=path_to is_file=is_file raise_errors=raise_errors sync_fw=sync_fw check_path=check_path end function
def wasb( connection_name, path_from, path_to, is_file, check_path, raise_errors, sync_fw ): _download( connection_name=connection_name, connection_kind=V1ConnectionKind.WASB, path_from=path_from, path_to=path_to, is_file=is_file, raise_errors=raise_errors, ...
Python
nomic_cornstack_python_v1
function _check_value self filename value begin if call _match_value value begin if _values begin call verbose filename value string is in call repr _values end end else begin raise call ValueError string Value + string call PP value + string is not one of + string call PP _values end if call _not_match_value value beg...
def _check_value(self, filename, value): if self._match_value(value): if self._values: self.verbose(filename, value, "is in", repr(self._values)) else: raise ValueError("Value " + str(log.PP(value)) + " is not one of " + str(log.PP(sel...
Python
nomic_cornstack_python_v1
function _parse_pb_prune matches begin if length matches != 2 begin return matches end set tuple pb1 pb2 = matches comment Break a tie between reflection request/response by just "guessing" it is comment a response. if is instance pb1 REFLECTION_REQUEST and is instance pb2 REFLECTION_RESPONSE begin return list pb2 end ...
def _parse_pb_prune(matches): if len(matches) != 2: return matches pb1, pb2 = matches # Break a tie between reflection request/response by just "guessing" it is # a response. if isinstance(pb1, REFLECTION_REQUEST) and isinstance( pb2, REFLECTION_RESPONSE ): return [pb2] ...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import pandas as pd import numpy as np import plotly.graph_objs as go from PIL import Image from typing import NoReturn , List , Tuple function trace_fix trajectory colour_str begin string :param trajectory: :param colour_str: :return: set size_list = list 6 * shape at 0 set size_list at...
import matplotlib.pyplot as plt import pandas as pd import numpy as np import plotly.graph_objs as go from PIL import Image from typing import NoReturn, List, Tuple def trace_fix(trajectory: np.ndarray, colour_str: str) -> Tuple[List, ...]: """ :param trajectory: :param colour_str: :return: """...
Python
zaydzuhri_stack_edu_python
function planarity eigenvalues begin return eigenvalues at 1 - eigenvalues at 2 / eigenvalues at 0 end function
def planarity(eigenvalues): return (eigenvalues[1] - eigenvalues[2]) / eigenvalues[0]
Python
nomic_cornstack_python_v1
function get begin try begin with open string /tmp/mimic_daemon as f begin set uri = read f end end except IOError begin raise call MimicError string Mimic not running, please start. end set daemon = call getProxyForURI uri try begin call test_connection end except ProtocolError begin raise call MimicError string Mimic...
def get(): try: with open("/tmp/mimic_daemon") as f: uri = f.read() except IOError: raise MimicError("Mimic not running, please start.") daemon = Pyro.core.getProxyForURI(uri) try: daemon.test_connection() except Pyro.errors.ProtocolError: raise MimicErr...
Python
nomic_cornstack_python_v1
function print_faculty begin try begin with open string faculty_record.pkl string rb as f begin set l = load pickle f set i = 0 while true begin try begin call display_faculty l at i set i = i + 1 end except any begin break end end end end except any begin print string No Record Found! end end function
def print_faculty(): try: with open("faculty_record.pkl","rb") as f: l=pickle.load(f) i=0 while True: try: display_faculty(l[i]) i+=1 except: break except: print("N...
Python
nomic_cornstack_python_v1
comment Write a Python program to display the examination schedule. (extract the date from exam_st_date). set exam_st_date = tuple 11 12 2014 print string The examination will start from : %i / %i / %i % exam_st_date
#Write a Python program to display the examination schedule. (extract the date from exam_st_date). exam_st_date = (11,12,2014) print( "The examination will start from : %i / %i / %i"%exam_st_date)
Python
zaydzuhri_stack_edu_python
import re class WpInstance begin function __init__ self key name wp_path host user begin set key = key set name = name set wp_path = wp_path set host = host set user = user end function function check_version self begin string Get the Wordpress version installed in the given path. try begin set content = call get_conte...
import re class WpInstance(): def __init__(self, key, name, wp_path, host, user): self.key = key self.name = name self.wp_path = wp_path self.host = host self.user = user def check_version(self): """ Get the Wordpress version installed in the given path...
Python
zaydzuhri_stack_edu_python
comment Find all possible combinations of k numbers that add up to a number n, comment given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. class Solution extends object begin function combinationSum3 self k n begin string :type k: int :type n: int :rtype: List[List[in...
#Find all possible combinations of k numbers that add up to a number n, #given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. class Solution(object): def combinationSum3(self, k, n): """ :type k: int :type n: int :rtype: List[List[...
Python
zaydzuhri_stack_edu_python
async function count_server_async namespace=none x_additional_headers=none **kwargs begin if namespace is none begin set tuple namespace error = call get_services_namespace if error begin return tuple none error end end set request = call create namespace=namespace return await call run_request_async request additional...
async def count_server_async( namespace: Optional[str] = None, x_additional_headers: Optional[Dict[str, str]] = None, **kwargs ): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = CountServer.create( namespace...
Python
nomic_cornstack_python_v1
function __init__ self begin set root = ROOT set content_type = CONTENT_TYPE end function
def __init__(self): self.root = ROOT self.content_type = CONTENT_TYPE
Python
nomic_cornstack_python_v1
import maya.cmds as mc import OptionsWindowBaseClass class scaleHelperTool extends OptionsWindow begin function __init__ self begin call __init__ self comment rename the tool set title = string Scale Helper Tool comment rename action button set actionName = string Create Scale Ruler comment rename apply name set applyN...
import maya.cmds as mc import OptionsWindowBaseClass class scaleHelperTool(OptionsWindowBaseClass.OptionsWindow): def __init__(self): OptionsWindowBaseClass.OptionsWindow.__init__(self) self.title="Scale Helper Tool" # rename the tool self.actionName="Create Scale Ruler" # rena...
Python
zaydzuhri_stack_edu_python
for i in range v begin print s at i i end
for i in range(v): print(s[i],i)
Python
zaydzuhri_stack_edu_python
function _split_classes_and_methods folds begin string Split out classes and methods into two separate lists. Parameters ---------- folds : list of :class:`FoldScopeHelper` The result of :func:`_get_fold_levels`. Returns ------- classes, functions: list of :class:`FoldScopeHelper` Two separate lists of :class:`FoldScop...
def _split_classes_and_methods(folds): """ Split out classes and methods into two separate lists. Parameters ---------- folds : list of :class:`FoldScopeHelper` The result of :func:`_get_fold_levels`. Returns ------- classes, functions: list of :class:`FoldScopeHelper` ...
Python
jtatman_500k
function __init__ self name num_levels padding_idx term_weights begin set name = name set num_levels = num_levels set padding_idx = padding_idx set term_weights : List = term_weights end function
def __init__( self, name: str, num_levels: int, padding_idx: int, term_weights: List[Tensor], ) -> None: self.name = name self.num_levels = num_levels self.padding_idx = padding_idx self.term_weights: List = term_weights
Python
nomic_cornstack_python_v1
import heapq from collections import deque import pdb import sys import Queue as Q import logging string NOTE: THIS PROGRAM IS DEVELOPED UNDER PYTHON 2.7 In python 3.0, the notation for queue is different than ver. < 3.0 class ProcessQueue extends object begin string abstract class for process queue function __init__ s...
import heapq from collections import deque import pdb import sys import Queue as Q import logging """ NOTE: THIS PROGRAM IS DEVELOPED UNDER PYTHON 2.7 In python 3.0, the notation for queue is different than ver. < 3.0 """ class ProcessQueue(object): """ abstract class for process queue """ def _...
Python
zaydzuhri_stack_edu_python
function __init__ self max_inst=2 max_tips=2 begin set max_inst = max_inst set max_tips = max_tips set _graph = none set _im = none end function
def __init__(self, max_inst=2, max_tips=2): self.max_inst = max_inst self.max_tips = max_tips self._graph = None self._im = None
Python
nomic_cornstack_python_v1