code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment -*- coding: utf-8 -*- import sys import csv from log import setup_logger from db import GyazaiDB from paths import DirPaths , DataFilePaths from normalizer import EngTextNormalizer function main begin set logger = call setup_logger string normalize_card_text.log try begin info string Start normalizing card text...
# -*- coding: utf-8 -*- import sys import csv from log import setup_logger from db import GyazaiDB from paths import DirPaths, DataFilePaths from normalizer import EngTextNormalizer def main(): logger = setup_logger('normalize_card_text.log') try: logger.info('Start normalizing card text') #...
Python
zaydzuhri_stack_edu_python
function GetWCSSys self *args begin return call send dict string cmd string GetWCSSys ; string args args end function
def GetWCSSys(self, *args): return self.send({"cmd": "GetWCSSys", "args": args})
Python
nomic_cornstack_python_v1
import requests from urllib.parse import urlencode from requests.exceptions import RequestException import json from bs4 import BeautifulSoup import re import os from hashlib import md5 from json.decoder import JSONDecodeError from config import * from multiprocessing import Pool function get_page_index offset keyword ...
import requests from urllib.parse import urlencode from requests.exceptions import RequestException import json from bs4 import BeautifulSoup import re import os from hashlib import md5 from json.decoder import JSONDecodeError from config import * from multiprocessing import Pool def get_page_index(offset, keyword): ...
Python
zaydzuhri_stack_edu_python
import RPi.GPIO as GPIO import time import datetime import os call setmode BOARD set PIR = 26 setup GPIO PIR IN set first_turned_off = false
import RPi.GPIO as GPIO import time import datetime import os GPIO.setmode(GPIO.BOARD) PIR = 26 GPIO.setup(PIR, GPIO.IN) first_turned_off = False
Python
zaydzuhri_stack_edu_python
function reset begin global _categories _get_funds _df set _categories = none set _get_funds = _all_funds set _df = _orig_df end function
def reset(): global _categories, _get_funds, _df _categories = None _get_funds = _all_funds _df = _orig_df
Python
nomic_cornstack_python_v1
import constants import pandas as pd import numpy as np from sklearn import preprocessing function add_dummy_indicator data_frame indicator begin comment item_list = data_frame[indicator].unique() comment print(item_list) for item in nominal_feature_mapping at indicator at slice 0 : - 1 : begin set dummy_ind_name = st...
import constants import pandas as pd import numpy as np from sklearn import preprocessing def add_dummy_indicator(data_frame, indicator): # item_list = data_frame[indicator].unique() # print(item_list) for item in constants.nominal_feature_mapping[indicator][0:-1]: dummy_ind_name = str(indicator) ...
Python
zaydzuhri_stack_edu_python
comment exercise 6.1.2 from loadingdata import * from matplotlib.pyplot import figure , plot , xlabel , ylabel , legend , show , boxplot from scipy.io import loadmat from sklearn import model_selection , tree import numpy as np comment Load Matlab data file and extract variables of interest set mu = mean np X 0 set sig...
# exercise 6.1.2 from loadingdata import * from matplotlib.pyplot import figure, plot, xlabel, ylabel, legend, show, boxplot from scipy.io import loadmat from sklearn import model_selection, tree import numpy as np # Load Matlab data file and extract variables of interest mu = np.mean(X, 0) sigma = np.std...
Python
zaydzuhri_stack_edu_python
comment from data_structures_and_algorithms.challenges.array_shift import insertShiftArray from data_structures_and_algorithms.challenges.array_shift.array_shift import insertShiftArray function test_type_of_list begin set actual = call insertShiftArray 5 4 set expected = string Invalid Input assert actual == expected ...
# from data_structures_and_algorithms.challenges.array_shift import insertShiftArray from data_structures_and_algorithms.challenges.array_shift.array_shift import insertShiftArray def test_type_of_list(): actual= insertShiftArray(5,4) expected= 'Invalid Input' assert actual==expected def test_type_of_n...
Python
zaydzuhri_stack_edu_python
import sys , os append path directory name path directory name path real path path __file__ import requests from util.blind_signatures import validate_signature , modulo_multiplicative_inverse import pprint import uuid import datetime import json from Crypto.Cipher import AES from Crypto import Random import hashlib fr...
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import requests from util.blind_signatures import validate_signature, modulo_multiplicative_inverse import pprint import uuid import datetime import json from Crypto.Cipher import AES from Crypto import Random import hashlib f...
Python
zaydzuhri_stack_edu_python
function getweigths begin set ls = list for i_lay in range 1 length layers begin append ls layers at i_lay at string weigths end return ls end function
def getweigths(): ls = [] for i_lay in range(1, len(layers)): ls.append(layers[i_lay]["weigths"]) return ls
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- from numpy import * import random import math string class Document(object): def __init__(self,polarity,words): self.polarity=polarity self.words=words comment 读文件 function readFromFile path polarity begin set input = open path string rb set docs = list set labelClass = list set alllines...
#-*- coding: utf-8 -*- from numpy import * import random import math ''' class Document(object): def __init__(self,polarity,words): self.polarity=polarity self.words=words ''' #读文件 def readFromFile(path,polarity): input=open(path,'rb') docs=[] labelClass=[] alllines=input.readlines() for line in alllines...
Python
zaydzuhri_stack_edu_python
from piece import Piece from game_rules import can_move import os class Rook extends Piece begin function __init__ self color name begin set sprite_dir = color + string Rook.png set name = name call __init__ color name end function function get_possible_moves self coord matrix begin set list_aux = call can_move color m...
from .piece import Piece from game_rules import can_move import os class Rook(Piece): def __init__(self, color, name): self.sprite_dir = color + "Rook.png" self.name = name super(Rook,self).__init__(color,name) def get_possible_moves(self, coord, matrix): list_aux = ca...
Python
zaydzuhri_stack_edu_python
string We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left ...
""" We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from lef...
Python
zaydzuhri_stack_edu_python
import pygame , sys , random , time from pygame.locals import * set win = tuple 800 600 set black = tuple 0 0 0 set red = tuple 255 0 0 set green = tuple 0 255 0 set cyan = tuple 0 255 255 set purple = tuple 150 0 150 set yellow = tuple 255 255 0 set p_pos = list 370 500 set e_pos = list random integer 0 740 0 set enem...
import pygame, sys, random, time from pygame.locals import * win = (800, 600) black = (0, 0, 0) red = (255, 0, 0) green = (0, 255, 0) cyan = (0, 255, 255) purple = (150, 0, 150) yellow = (255, 255, 0) p_pos = [370, 500] e_pos =[random.randint(0, 740), 0] enemy_l = [e_pos] speed = 10 speed_e = 5 fps = 60 game_over = Fal...
Python
zaydzuhri_stack_edu_python
import numpy as np import sqlite3 as sql from matplotlib import pyplot as plt from sklearn.svm import SVR from fetch_data import fetch_data as fd from random_dark_colors import random_dark_colors as rdc set kernel = input string Which kernel to use, polynomial or linear ([p]/l)? if length kernel > 0 and kernel at 0 == ...
import numpy as np import sqlite3 as sql from matplotlib import pyplot as plt from sklearn.svm import SVR from fetch_data import fetch_data as fd from random_dark_colors import random_dark_colors as rdc kernel = input('Which kernel to use, polynomial or linear ([p]/l)? ') if len(kernel)>0 and kernel[0]=='l': ke...
Python
zaydzuhri_stack_edu_python
comment We define the possible winning combination of the game set WINNING_COMBINATION = dict string rock string scissors ; string paper string rock ; string scissors string paper function playRockPaperScissors begin comment Player 1's turn set player1_choice = input string Player 1: Choose rock, paper or scissors: com...
# We define the possible winning combination of the game WINNING_COMBINATION = { "rock": "scissors", "paper": "rock", "scissors": "paper" } def playRockPaperScissors(): # Player 1's turn player1_choice = input("Player 1: Choose rock, paper or scissors: ") # Player 2's turn player2_choice = input("Player ...
Python
iamtarun_python_18k_alpaca
function egglayingModel1 t stateVar params begin set num_strains = length stateVar / 3 set diffs = list for i in range 0 num_strains begin set dE = value * stateVar at 1 + 3 * i * stateVar at 3 * i set dS = - dE set dO = value - value * stateVar at 1 + 3 * i - dE append diffs list dS dO dE end end function
def egglayingModel1(t,stateVar,params): num_strains = len(stateVar) / 3 diffs = [] for i in range(0,num_strains) : dE = params['kf'].value*stateVar[1+3*i]*stateVar[3*i] dS = -dE dO = params['ko'].value - params['kc'].value*stateVar[1+3*i] - dE ...
Python
nomic_cornstack_python_v1
function delete_min self begin if _length == 0 begin return none end set min = _heap at 0 set tuple _heap at 0 _heap at _length - 1 = tuple _heap at _length - 1 _heap at 0 set _length = _length - 1 call _move_down 0 return min end function
def delete_min(self): if self._length == 0: return None min = self._heap[0] self._heap[0], self._heap[self._length - 1] = self._heap[self._length - 1], self._heap[0] self._length -= 1 self._move_down(0) return min
Python
nomic_cornstack_python_v1
import unittest from domain.course import Course from errors import CourseError from repository.course_repository import CourseRepository from service.course_controller import CourseController class TestCourseController extends TestCase begin function setUp self begin set courses = call CourseRepository set course1 = c...
import unittest from domain.course import Course from errors import CourseError from repository.course_repository import CourseRepository from service.course_controller import CourseController class TestCourseController(unittest.TestCase): def setUp(self): courses = CourseRepository() self.course...
Python
zaydzuhri_stack_edu_python
import numpy as np from calculation_cost import * function stocashtic_gradient_descent X y theta learning_rate=0.01 iterations=10 begin string X = matrix of X with added bias unit y = Vector of y theta = vector of theta np.random.randn(j,1) learning_rate iterations = no of iterations Returns the final theta vector and ...
import numpy as np from calculation_cost import * def stocashtic_gradient_descent(X,y,theta,learning_rate=0.01,iterations=10): ''' X = matrix of X with added bias unit y = Vector of y theta = vector of theta np.random.randn(j,1) learning_rate iterations = no of iterations Returns the final theta vector and...
Python
zaydzuhri_stack_edu_python
function insertion_sort arr compare begin set comparisons = 0 for i in range 1 length arr begin set key = arr at i set j = i - 1 while j >= 0 and call compare arr at j key begin set comparisons = comparisons + 1 set arr at j + 1 = arr at j set j = j - 1 end set arr at j + 1 = key end return comparisons end function fun...
def insertion_sort(arr, compare): comparisons = 0 for i in range(1, len(arr)): key = arr[i] j = i - 1 while j >= 0 and compare(arr[j], key): comparisons += 1 arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return comparisons def descending_com...
Python
jtatman_500k
function classImplementsFirst cls iface begin set spec = call implementedBy cls call _classImplements_ordered spec tuple iface tuple end function
def classImplementsFirst(cls, iface): spec = implementedBy(cls) _classImplements_ordered(spec, (iface,), ())
Python
nomic_cornstack_python_v1
from flask_restful import Resource , reqparse from flask_jwt import JWT , jwt_required from models.item import ItemModel from models.brand import BrandModel comment Api works with resources, which are classes that inherits from Resource comment In this case Item is the resource. class Item extends Resource begin decora...
from flask_restful import Resource, reqparse from flask_jwt import JWT, jwt_required from models.item import ItemModel from models.brand import BrandModel # Api works with resources, which are classes that inherits from Resource # In this case Item is the resource. class Item(Resource): # decorator, means we have...
Python
zaydzuhri_stack_edu_python
function test_unique_constraint_with_unset_caseversion self begin set new = call CaseStep with assert raises ValidationError begin call full_clean end end function
def test_unique_constraint_with_unset_caseversion(self): new = self.model.CaseStep() with self.assertRaises(ValidationError): new.full_clean()
Python
nomic_cornstack_python_v1
set Ratio = eval input string What is the ratio of the solution? set RP = Ratio * 100 set Volume = integer input string What is the current volume? set Percent = decimal input string What is the current percent? set Solution = Volume * Percent / RP print Solution
Ratio =eval(input("What is the ratio of the solution?")) RP= (Ratio*100) Volume=int(input("What is the current volume?")) Percent=float(input("What is the current percent?")) Solution=(Volume*Percent)/(RP) print (Solution)
Python
zaydzuhri_stack_edu_python
function extract_songs self begin set original_url = url try begin set url = call _get_ytmusic_url original_url call _create_mix end except DownloadError begin set url = original_url call _extract_fallback end end function
def extract_songs(self): original_url = self.url try: self.url = self._get_ytmusic_url(original_url) self._create_mix() except DownloadError: self.url = original_url self._extract_fallback()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import re import sys if __name__ == string __main__ begin set expr = compile string .*(\W|[0-9])\S.* with open string consigna3 as f begin while r := read line f begin set found = match r if not found begin continue end print call group end end end
#!/usr/bin/env python3 import re import sys if __name__ == "__main__": expr = re.compile(".*(\W|[0-9])\S.*") with open("consigna3") as f: while r := f.readline(): found = expr.match(r) if not found: continue print(found.group())
Python
zaydzuhri_stack_edu_python
function dft x begin set N = length x comment array for results set X = zeros N dtype=complex comment define exponent factor set W = exp - 1j * 2 * pi / N for k in range N begin set X at k = sum list comprehension x at n * W ^ k * n for n in range N end return X end function
def dft(x): N = len(x) # array for results X = np.zeros(N, dtype=complex) # define exponent factor W = np.exp(-1j * (2*np.pi / N)) for k in range(N): X[k] = sum([x[n]*(W**(k*n)) for n in range(N)]) return X
Python
nomic_cornstack_python_v1
function main begin comment placing actual main action in a 'helper'script so can call that easily comment with a distinguishing name in Jupyter notebooks, where `main()` may get comment assigned multiple times depending how many scripts imported/pasted in. set kwargs = dict comment kwargs['return_df'] = False #probab...
def main(): # placing actual main action in a 'helper'script so can call that easily # with a distinguishing name in Jupyter notebooks, where `main()` may get # assigned multiple times depending how many scripts imported/pasted in. kwargs = {} #kwargs['return_df'] = False #probably don't want dataf...
Python
nomic_cornstack_python_v1
function test_sktime_save_model_raises_invalid_serialization_format auto_arima_model model_path begin with raises MlflowException match=string Unrecognized serialization format: begin call save_model sktime_model=auto_arima_model path=model_path serialization_format=string json end end function
def test_sktime_save_model_raises_invalid_serialization_format(auto_arima_model, model_path): with pytest.raises(MlflowException, match="Unrecognized serialization format: "): flavor.save_model( sktime_model=auto_arima_model, path=model_path, serialization_format="json" )
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python import re function stringToBinary st begin return join string generator expression format ordinal x string b for x in st end function comment input: argument in string format with space inbetween function binaryToString bn begin set bn = split bn string set bn_ascii = list map lambda i -> ...
#!/usr/bin/env python import re def stringToBinary(st): return ' '.join(format(ord(x), 'b') for x in st) # input: argument in string format with space inbetween def binaryToString(bn): bn = bn.split(' ') bn_ascii = list(map(lambda i: int(i, 2), bn)) text = ''.join(chr(i) for i in bn_ascii) retu...
Python
zaydzuhri_stack_edu_python
import warnings from pandas import Series import pandas as pd from pandas import read_csv from statsmodels.tsa.arima_model import ARIMA from sklearn.metrics import mean_absolute_error import matplotlib from math import sqrt set pr = list function evaluate_arima_model X arima_order begin set X = as type X string float32...
import warnings from pandas import Series import pandas as pd from pandas import read_csv from statsmodels.tsa.arima_model import ARIMA from sklearn.metrics import mean_absolute_error import matplotlib from math import sqrt pr=list() def evaluate_arima_model(X, arima_order): X = X.astype('float32') train_size = int(...
Python
zaydzuhri_stack_edu_python
function test_index_view_with_no_questions self begin set response = get client reverse string polls:index assert equal status_code 200 call assertContains response string No polls are available. call assertQuerysetEqual context at string latest_questions_list list end function
def test_index_view_with_no_questions(self): response = self.client.get(reverse("polls:index")) self.assertEqual(response.status_code, 200) self.assertContains(response, "No polls are available.") self.assertQuerysetEqual(response.context['latest_questions_list'], [])
Python
nomic_cornstack_python_v1
function __repr__ self begin return call to_str end function
def __repr__(self): return self.to_str()
Python
nomic_cornstack_python_v1
function join_tables database query begin set table_names = query at string from if string * in table_names begin set table_names = list database end set result_table = database at table_names at 0 for table in table_names at slice 1 : : begin set other_table = database at table set result_table = call cartesian_prod...
def join_tables(database, query): table_names = query["from"] if "*" in table_names: table_names = list(database) result_table = database[table_names[0]] for table in table_names[1:]: other_table = database[table] result_table = cartesian_product(result_table...
Python
nomic_cornstack_python_v1
import tensorflow as tf class Train begin function __init__ self output=none ground_truth=none loss=string sparse_crossentropy optimizer=string Adam opt_params=list begin set output = output set ground_truth = ground_truth set loss = loss set optimizer = optimizer set opt_params = opt_params set learning_rate = opt_par...
import tensorflow as tf class Train(): def __init__(self, output=None,ground_truth=None,loss='sparse_crossentropy', optimizer='Adam', opt_params=[]): self.output = output self.ground_truth = ground_truth self.loss = loss self.optimizer = optimizer self.opt_params = opt_para...
Python
zaydzuhri_stack_edu_python
function search self word begin set node = root for chars in word begin set node = get data chars if not node begin return false end end return is_word end function
def search(self, word): node = self.root for chars in word: node = node.data.get(chars) if not node: return False return node.is_word
Python
nomic_cornstack_python_v1
function close_gripper self distance=0.0 force_threshold=none begin set gripper_goal = call GripperGoal set grip_distance = distance set force_threshold = if expression force_threshold is none then decimal string nan else force_threshold call send_goal gripper_goal end function
def close_gripper(self, distance=0.0, force_threshold=None): gripper_goal = GripperGoal() gripper_goal.grip_distance = distance gripper_goal.force_threshold = float("nan") if force_threshold is None else force_threshold self.gripper_action.send_goal(gripper_goal)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment coding=utf-8 comment 2013 Kyle Fitzsimmons import time import sys import urllib import csv from BeautifulSoup import BeautifulSoup from unidecode import unidecode comment Custom file imports import FuzzyString as fuzzy from Browser import Browser import TableParser from MontrealAddressP...
#!/usr/bin/python # coding=utf-8 # 2013 Kyle Fitzsimmons import time import sys import urllib import csv from BeautifulSoup import BeautifulSoup from unidecode import unidecode # Custom file imports import FuzzyString as fuzzy from Browser import Browser import TableParser from MontrealAddressParser import AddressPars...
Python
zaydzuhri_stack_edu_python
function _merge_pdfs output_path *args begin set merger = call PdfFileMerger for path in args begin if path is not none begin append merger path end end write merger output_path end function
def _merge_pdfs(output_path, *args): merger = PdfFileMerger() for path in args: if path is not None: merger.append(path) merger.write(output_path)
Python
nomic_cornstack_python_v1
comment Definition for singly-linked list. comment class ListNode: comment def __init__(self, val=0, next=None): comment self.val = val comment self.next = next class Solution begin function sortList self head begin from queue import PriorityQueue set ptr = head set p_queue = call PriorityQueue while ptr != none begin ...
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def sortList(self, head: ListNode) -> ListNode: from queue import PriorityQueue ptr = head p_queue = PriorityQueue() ...
Python
zaydzuhri_stack_edu_python
async function unwhitelist self ctx guild_id begin if guild_id not in await call whitelist begin await call send string This server is not in the whitelist. return end async_with call whitelist as w begin set index = index w guild_id pop w index end await call tick end function
async def unwhitelist(self, ctx: commands.Context, guild_id: int): if guild_id not in await self.config.whitelist(): await ctx.send("This server is not in the whitelist.") return async with self.config.whitelist() as w: index = w.index(guild_id) w.pop(inde...
Python
nomic_cornstack_python_v1
class Solution extends object begin function fizzBuzz self n begin string :type n: int :rtype: List[str] set finalArray = list set number = 1 while number <= n begin if number % 3 == 0 and number % 5 == 0 begin append finalArray string FizzBuzz set number = number + 1 end else if number % 3 == 0 begin append finalArra...
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ finalArray = [] number = 1 while number <= n: if number % 3 == 0 and number % 5 == 0: finalArray.append("FizzBuzz") number+=1 ...
Python
zaydzuhri_stack_edu_python
function convert_single_example tokenizer example max_seq_length=256 begin if is instance example PaddingInputExample begin set input_ids = list 0 * max_seq_length set input_mask = list 0 * max_seq_length set segment_ids = list 0 * max_seq_length set label = 0 return tuple input_ids input_mask segment_ids label end set...
def convert_single_example(tokenizer, example, max_seq_length=256): if isinstance(example, PaddingInputExample): input_ids = [0] * max_seq_length input_mask = [0] * max_seq_length segment_ids = [0] * max_seq_length label = 0 return input_ids, input_mask, segment_ids, label ...
Python
nomic_cornstack_python_v1
function email_additional_text self begin return get pulumi self string email_additional_text end function
def email_additional_text(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "email_additional_text")
Python
nomic_cornstack_python_v1
function get_context self begin return string end function
def get_context(self) -> str: return ""
Python
nomic_cornstack_python_v1
function find_frames self ftype calib_ID=none index=false begin if string framebit not in keys self begin error string Frame types are not set. First run get_frame_types. end if ftype == string None begin return self at string framebit == 0 end comment Select frames set indx = call flagged self at string framebit ftype...
def find_frames(self, ftype, calib_ID=None, index=False): if 'framebit' not in self.keys(): msgs.error('Frame types are not set. First run get_frame_types.') if ftype == 'None': return self['framebit'] == 0 # Select frames indx = self.type_bitmask.flagged(self['f...
Python
nomic_cornstack_python_v1
function Hello full_name ID language email begin return format string Hello World, this is {} with HNGi7 ID {} using {} for stage 2 task {} full_name ID language email end function if __name__ == string __main__ begin set full_name = string Paul Ogolla set ID = string HNG-00150 set language = string Python set email = ...
def Hello(full_name, ID, language, email): return "Hello World, this is {} with HNGi7 ID {} using {} for stage 2 task {}".format(full_name, ID, language,email) if __name__ == '__main__': full_name = "Paul Ogolla" ID = "HNG-00150" language = "Python" email = "paulotieno2@gmail.com" print(Hello(f...
Python
zaydzuhri_stack_edu_python
import numpy as np import librosa import librosa.display import os from os.path import isdir , join , dirname from pathlib import Path import re import hashlib from tqdm import tqdm comment ~134M set MAX_NUM_WAVS_PER_CLASS = 2 ^ 27 - 1 function which_set filename validation_percentage testing_percentage begin string De...
import numpy as np import librosa import librosa.display import os from os.path import isdir, join, dirname from pathlib import Path import re import hashlib from tqdm import tqdm MAX_NUM_WAVS_PER_CLASS = 2**27 - 1 # ~134M def which_set(filename, validation_percentage, testing_percentage): """Determines which d...
Python
zaydzuhri_stack_edu_python
function dataset_preprocessed self begin set df = read csv string data/houses_clean.csv drop df string Unnamed: 0 axis=1 inplace=true return df end function
def dataset_preprocessed(self): df = pd.read_csv("data/houses_clean.csv") df.drop('Unnamed: 0',axis = 1,inplace = True) return df
Python
nomic_cornstack_python_v1
function __init__ self next_ files=none begin call __init__ self next_ set params = dict if files is none begin set file_from_cl = call get_value string config if file_from_cl begin set files = tuple file_from_cl end else begin set files = tuple CONFIG_FILE_NAME string ~/ + CONFIG_FILE_NAME end end for f in files begi...
def __init__(self, next_, files=None): ChainedConfig.__init__(self, next_) self.params = {} if files is None: file_from_cl = CommandLineConfig.get_value("config") if file_from_cl: files = (file_from_cl,) else: files = (CONFIG_F...
Python
nomic_cornstack_python_v1
import sqlite3 import os set GALLERY_DIR = string gallery set db = call connect string storage.db function init_db begin set cursor = call cursor execute cursor string CREATE TABLE IF NOT EXISTS images ( id INTEGER PRIMARY KEY, reddit_id TEXT, title TEXT, width INTEGER, height INTEGER, file_size INTEGER, file_type TEXT...
import sqlite3 import os GALLERY_DIR = 'gallery' db = sqlite3.connect('storage.db') def init_db(): cursor = db.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS images ( id INTEGER PRIMARY KEY, reddit_id TEXT, title TEXT, width INTEGER, ...
Python
zaydzuhri_stack_edu_python
class ListNode extends object begin function __init__ self val=0 next=none begin set val = val set next = next end function end class class Solution begin function print_linkedlist self head begin while next != none begin set head = next print val end end function end class
class ListNode(object): def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def print_linkedlist(self, head): while head.next != None: head = head.next print(head.val)
Python
iamtarun_python_18k_alpaca
comment !/bin/python from __future__ import print_function function ppsd_event data begin if string 25 in data at string course begin set course = string S end else begin set course = string L end return format string ({0}) {event:17} course keyword data end function function ppsd_time row begin return format string {0...
#!/bin/python from __future__ import print_function def ppsd_event(data): if '25' in data['course']: course = 'S' else: course = 'L' return "({0}) {event:17}".format(course, **data) def ppsd_time(row): return "{0}".format(row['time'].strftime("%M:%S.%f")[:-4]) def ppsd_date(row): ...
Python
zaydzuhri_stack_edu_python
function _add_meta_dict_to_xml self doc parent meta_dict begin if not meta_dict begin return end set key_list = list keys meta_dict sort key_list for key in key_list begin set el_list = call _index_list_of_values meta_dict key for el in el_list begin call _add_meta_value_to_xml_doc doc parent el end end end function
def _add_meta_dict_to_xml(self, doc, parent, meta_dict): if not meta_dict: return key_list = list(meta_dict.keys()) key_list.sort() for key in key_list: el_list = _index_list_of_values(meta_dict, key) for el in el_list: self._add_meta_v...
Python
nomic_cornstack_python_v1
function order_annulus_contour_points annulus_point_coordinates labels label_order begin set number_of_annulus_points = shape at 0 if label_order at 0 not in labels begin raise call ValueError format string First label ({0}) is not defined for contour. Defined labels: {1} label_order at 0 keys labels end set starting_p...
def order_annulus_contour_points(annulus_point_coordinates, labels, label_order): number_of_annulus_points = annulus_point_coordinates.shape[0] if label_order[0] not in labels: raise ValueError( "First label ({0}) is not defined for contour. Defined labels: {1}".format(label_order[0], la...
Python
nomic_cornstack_python_v1
function main begin set wn = call Screen call bgpic string cool_background.gif call make_a_tree - 250 - 127 call make_a_tree - 170 - 135 call make_a_tree - 200 - 140 call background_for_text - 30 50 call bgpic string forest_fire.gif call some_text string STOP AMAZON DESTRUCTION! 80 50 call fires_and_flames - 170 - 50 c...
def main(): wn = turtle.Screen() wn.bgpic("cool_background.gif") make_a_tree(-250, -127) make_a_tree(-170,-135) make_a_tree(-200, -140) background_for_text(-30, 50) wn.bgpic("forest_fire.gif") some_text("STOP AMAZON \n DESTRUCTION!", 80, 50) fires_and_flames(-170, -50) wn.exitonc...
Python
nomic_cornstack_python_v1
import re set NAME = compile string .*\s(\w{1,2})$ set EXPR = compile string (NOT|AND|OR|RSHIFT|LSHIFT) set data = dictionary comprehension call group 1 : i for i in read lines open string d07 string r set data = dictionary comprehension call group 1 : i for i in read lines open string scrap string r comment find wire ...
import re NAME = re.compile(r'.*\s(\w{1,2})$') EXPR = re.compile(r'(NOT|AND|OR|RSHIFT|LSHIFT)') data = {NAME.match(i).group(1):i for i in open("d07", "r").readlines()} data = {NAME.match(i).group(1):i for i in open("scrap", "r").readlines()} # find wire 'a' and connect recursively backwards... class node: def __in...
Python
zaydzuhri_stack_edu_python
function _update_custom_list_item builder_client guide_id custom_list_item changed_file begin comment Update the custom list item if custom_list_item at string name != changed_file at string name begin set custom_list_item_patch_url = format string https://builder.guidebook.com/open-api/v1/custom-list-items/{}/ custom_...
def _update_custom_list_item(builder_client, guide_id, custom_list_item, changed_file): # Update the custom list item if custom_list_item['name'] != changed_file['name']: custom_list_item_patch_url = "https://builder.guidebook.com/open-api/v1/custom-list-items/{}/".format(custom_list_item['id']) ...
Python
nomic_cornstack_python_v1
function topic_exercise tree begin set result = dict for tuple topic_name topic in call iteritems begin set result at topic_name = list for child in topic at string children begin if child at string kind == string Exercise begin append result at topic_name child at string name end end end return result end function
def topic_exercise(tree): result = {} for topic_name, topic in find_exercise_topics(tree).iteritems(): result[topic_name] = [] for child in topic['children']: if child['kind'] == 'Exercise': result[topic_name].append(child['name']) return result
Python
nomic_cornstack_python_v1
function test_mount_routes_with_middleware_url_path_for begin assert call url_path_for string route == string /http/ end function
def test_mount_routes_with_middleware_url_path_for() -> None: assert mounted_routes_with_middleware.url_path_for("route") == "/http/"
Python
nomic_cornstack_python_v1
from Graph_Generator.single_school_generator import School import EoN import networkx as nx import matplotlib.pyplot as plt set total_students = 1000 set num_grades = 4 set num_teachers = 60 set num_of_students_within_grade = integer total_students / num_grades comment [0.05,0.1,,0.2,0.4] set p_c = 1 comment 5 # [5,10]...
from Graph_Generator.single_school_generator import School import EoN import networkx as nx import matplotlib.pyplot as plt total_students=1000 num_grades=4 num_teachers=60 num_of_students_within_grade=int(total_students/num_grades) p_c=1 # [0.05,0.1,,0.2,0.4] cg_scale=1 #5 # [5,10] p_g=p_c*cg_scale alpha=1 high_infec...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import socket import getopt import sys import os import time function usage begin write stderr format string {0}: usage: {0} -i <inet ver> -a <addr> -p <port> base name path argv at 0 exit 1 end function if __name__ == string __main__ begin set i = none set a = none set p = none set tuple a...
#!/usr/bin/env python import socket import getopt import sys import os import time def usage(): sys.stderr.write("{0}: usage: {0} -i <inet ver> -a <addr> -p <port>\n".format(os.path.basename(sys.argv[0]))) sys.exit(1) if __name__ == "__main__": i = None a = None p = None args, rest = getopt...
Python
zaydzuhri_stack_edu_python
function get_route_distance self route begin set distance = 0 for i in range length route - 1 begin set distance = distance + distances at route at i at route at i + 1 end return distance end function
def get_route_distance(self, route): distance = 0 for i in range(len(route)-1): distance += self.delivery_data.distances[route[i]][route[i+1]] return distance
Python
nomic_cornstack_python_v1
import numpy as np import cv2 function rnd_warp a begin set tuple h w = shape at slice : 2 : set T = zeros tuple 2 3 set coef = 0.2 set ang = call rand - 0.5 * coef set tuple c s = tuple cos ang sin ang set T at tuple slice : 2 : slice : 2 : = list list c - s list s c set T at tuple slice : 2 : slice : 2 : = ...
import numpy as np import cv2 def rnd_warp(a): h, w = a.shape[:2] T = np.zeros((2, 3)) coef = 0.2 ang = (np.random.rand() - 0.5) * coef c, s = np.cos(ang), np.sin(ang) T[:2, :2] = [[c, -s], [s, c]] T[:2, :2] += (np.random.rand(2, 2) - 0.5) * coef c = (w / 2, h / 2) T[:, 2] = c - np...
Python
zaydzuhri_stack_edu_python
import csv from django.shortcuts import render from django.http import HttpResponse class CSVResponseMixin extends object begin set csv_filename = string csvfile.csv function get_csv_filename self begin return csv_filename end function function render_to_csv self data begin set response = call HttpResponse content_type...
import csv from django.shortcuts import render from django.http import HttpResponse class CSVResponseMixin(object): csv_filename = 'csvfile.csv' def get_csv_filename(self): return self.csv_filename def render_to_csv(self, data): response = HttpResponse(content_type='text/csv') cd...
Python
zaydzuhri_stack_edu_python
function estraiIDautoriMulti pfPersone pfAuthorRAW pfAutoriID begin comment print 'pfPersone:{}\tpfAuthorRAW:{}\tpfAutoriID:{}'.format(pfPersone, pfAuthorRAW, pfAutoriID) comment popolo il set set sPersone = call creaSetAbbreviazioni pfPersone comment print(sPersone) comment print 'abbreviazioni {}'.format(len(sPersone...
def estraiIDautoriMulti(pfPersone, pfAuthorRAW, pfAutoriID): # print 'pfPersone:{}\tpfAuthorRAW:{}\tpfAutoriID:{}'.format(pfPersone, pfAuthorRAW, pfAutoriID) # popolo il set sPersone = creaSetAbbreviazioni(pfPersone) # print(sPersone) # print 'abbreviazioni {}'.format(len(sPersone)) # cerco i nomi nel set ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding:utf-8 _*- string @author: wangye(Wayne) @license: Apache Licence @file: Delete Characters to Make Fancy String.py @time: 2021/08/07 @contact: wang121ye@hotmail.com @site: @software: PyCharm # code is far away from bugs. class Solution begin function makeFancyString self s...
#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author: wangye(Wayne) @license: Apache Licence @file: Delete Characters to Make Fancy String.py @time: 2021/08/07 @contact: wang121ye@hotmail.com @site: @software: PyCharm # code is far away from bugs. """ class Solution: def makeFancyString(self, s: str...
Python
zaydzuhri_stack_edu_python
import numpy as np import random import copy from collections import namedtuple , deque from model import Actor , Critic import torch import torch.nn.functional as F import torch.optim as optim import sum_tree comment replay buffer size set BUFFER_SIZE = integer 2 ^ 16 comment minibatch size set BATCH_SIZE = 256 commen...
import numpy as np import random import copy from collections import namedtuple, deque from model import Actor, Critic import torch import torch.nn.functional as F import torch.optim as optim import sum_tree BUFFER_SIZE = int(2 ** 16) # replay buffer size BATCH_SIZE = 256 # minibatch size GAMMA = 0.99 ...
Python
zaydzuhri_stack_edu_python
function create_text_rank self begin comment filtered_tokens = self.filter_pos() #if use, replace 2 self.lemma_tokens below set vocab = call create_vocab lemma_tokens set token_windows = call create_token_windows lemma_tokens set graph = call create_matrix vocab token_windows set text_rank = array list 1 * length vocab...
def create_text_rank(self): # filtered_tokens = self.filter_pos() #if use, replace 2 self.lemma_tokens below vocab = self.create_vocab(self.lemma_tokens) token_windows = self.create_token_windows(self.lemma_tokens) graph = self.create_matrix(vocab, token_windows) text_rank = n...
Python
nomic_cornstack_python_v1
function drawImage self image x1 y1 x2=none y2=none **kwargs begin return end function
def drawImage(self, image, x1,y1, x2=None,y2=None, **kwargs): return
Python
nomic_cornstack_python_v1
function initAfterBeams self begin return call AlpgenHooks_initAfterBeams self end function
def initAfterBeams(self): return _pythia8.AlpgenHooks_initAfterBeams(self)
Python
nomic_cornstack_python_v1
function cluster_latent_space latent_representations_current_epoch labels_current_epoch result_path epoch begin set rcParams at string figure.figsize = tuple 6.4 * 2 4.8 comment convert lists to numpy array set latent_representations_current_epoch = array latent_representations_current_epoch set labels_current_epoch = ...
def cluster_latent_space(latent_representations_current_epoch, labels_current_epoch, result_path, epoch): plt.rcParams["figure.figsize"] = (6.4*2, 4.8) # convert lists to numpy array latent_representations_current_epoch = np.array(latent_representations_current_epoch) labels_current_epoch = np.array(l...
Python
nomic_cornstack_python_v1
import sys function GenerateOutputFileName raw_file_name begin set splitted_name = split raw_file_name string . return string { splitted_name at 0 } .bin end function function GenerateROMLine instruction index begin return string tmp( { index } ) := " { instruction } "; end function set opcodes = dict string ADD string...
import sys def GenerateOutputFileName(raw_file_name): splitted_name = raw_file_name.split('.') return f'{splitted_name[0]}.bin' def GenerateROMLine(instruction, index): return f'tmp({index}) := "{instruction}"; \n' opcodes = { "ADD": "0001", "SUB": "0010", "LEA": "0011", "MOVMR": "0100", ...
Python
zaydzuhri_stack_edu_python
import os function toktar_ide begin print string [welcome to TOKTAR IDE] print string [enter <help> command in <file name : > to see instruction and usage] while true begin set f = input string file name : if f == string q begin break end else if f == string help begin print string [ABOUT] * TOKTAR IDE is a command lin...
import os def toktar_ide(): print("[welcome to TOKTAR IDE]") print("[enter <help> command in <file name : > to see instruction and usage]\n") while True: f = input("file name : ") if f == "q": break elif f == "help": print(""" [ABOUT] * TOKTAR IDE is a command line tool/ide for pythonier programmers and...
Python
zaydzuhri_stack_edu_python
import time as T import Adafruit_BBIO.GPIO as g set All = list string P8_11 string P8_12 string P8_13 string P8_14 string P8_15 string P8_16 string P8_17 set up = list string P9_24 string P9_11 string P9_13 string P9_15 set down = list string P9_23 string P9_12 string P9_14 string P9_16 set zero = list string P8_11 str...
import time as T import Adafruit_BBIO.GPIO as g All=["P8_11","P8_12","P8_13","P8_14","P8_15","P8_16","P8_17"] up=["P9_24","P9_11","P9_13","P9_15"] down=["P9_23","P9_12","P9_14","P9_16"] zero=["P8_11","P8_12","P8_13","P8_14","P8_15","P8_16"] one=["P8_12","P8_13"] two=["P8_11","P8_12","P8_17","P8_15","P8_14"] three=["P8_...
Python
zaydzuhri_stack_edu_python
comment n = 20 function KELCH df n begin set KelChM = rename string KelChM_ + string n set KelChU = rename string KelChU_ + string n set KelChD = rename string KelChD_ + string n return tuple KelChM KelChU KelChD end function
def KELCH(df, n): # n = 20 KelChM = ((df['High'] + df['Low'] + df['Close']) / 3).rolling(window=n).mean().rename('KelChM_' + str(n)) KelChU = ((4 * df['High'] - 2 * df['Low'] + df['Close']) / 3).rolling(window=n).mean().rename('KelChU_' + str(n)) KelChD = ((-2 * df['High'] + 4 * df['Low'] + df['Close']) / 3...
Python
nomic_cornstack_python_v1
comment Alex Liu comment 11/13/18 import pylab as plt import numpy as np import matplotlib.animation as animation import pandas as pd import matplotlib.cm as cm from matplotlib import colors comment constants set p = pi set A = 0.1 set epsilon = 0.25 set w = p / 5 set delta = 0.0001 set dt = 0.1 set partition = 20 set ...
# Alex Liu # 11/13/18 import pylab as plt import numpy as np import matplotlib.animation as animation import pandas as pd import matplotlib.cm as cm from matplotlib import colors # constants p = np.pi A = 0.1 epsilon = 0.25 w = p/5 delta = 0.0001 dt = 0.1 partition = 20 col = ['r','y','b','g','k','c','m','r','y','b'...
Python
zaydzuhri_stack_edu_python
function _get_timber_data beam input output begin debug format string Getting timber data from '{}' input try begin set fill_number = integer input end except ValueError begin set fill = call read_tfs input index=call COL_TIME drop fill list comprehension call COL_MAV p for p in PLANES if call COL_MAV p in columns axis...
def _get_timber_data(beam, input, output): LOG.debug("Getting timber data from '{}'".format(input)) try: fill_number = int(input) except ValueError: fill = tfs.read_tfs(input, index=COL_TIME()) fill.drop([COL_MAV(p) for p in PLANES if COL_MAV(p) in fill.columns], ax...
Python
nomic_cornstack_python_v1
function get_app begin global _app if _app is none begin set entrypoint = get call get_config string APP_ENTRYPOINT if not entrypoint begin raise call RuntimeError string APP_ENTRYPOINT missing from config end set tuple module_name attr_names = split entrypoint string : set obj = call __import__ module_name fromlist=li...
def get_app(): global _app if _app is None: entrypoint = get_config().get('APP_ENTRYPOINT') if not entrypoint: raise RuntimeError('APP_ENTRYPOINT missing from config') module_name, attr_names = entrypoint.split(':') obj = __import__(module_name, fromlist=['.']) ...
Python
nomic_cornstack_python_v1
async function _set_point self begin while not call empty begin call get_nowait end set retries = 3 set response_set_point = FAILURE while retries begin set response = await call async_send crc=true if response == SUCCESS begin try begin return await call wait_for get _response_set_point TIMEOUT end except TimeoutError...
async def _set_point(self): while not self._response_set_point.empty(): self._response_set_point.get_nowait() retries = 3 response_set_point = ResponseStatus.FAILURE while retries: response = await self._get_set_point_command.async_send(crc=True) if re...
Python
nomic_cornstack_python_v1
function copy self begin return call Cone end function
def copy(self): return Cone()
Python
nomic_cornstack_python_v1
function remove self item begin comment check if item is in list if item in list begin set message = string set i = index list item return call remove_idx i end comment if not, operation unsuccessfull add log itemname + string not in + name + string . return none end function
def remove(self, item): # check if item is in list if item in self.list: self.message = "" i = self.list.index(item) return self.remove_idx(i) # if not, operation unsuccessfull self.log.add(self.itemname + " not in " + self.name + ".") ...
Python
nomic_cornstack_python_v1
function reconstruct_node self begin set object_ref = call fetch_live_object end function
def reconstruct_node(self) -> None: self.object_ref = self.fetch_live_object()
Python
nomic_cornstack_python_v1
function latest_blog_posts self request *args **kwargs begin set context = call get_context request *args keyword kwargs set context at string latest_posts = call public at slice : 1 : return call render request string myblog/latest_posts.html context end function
def latest_blog_posts(self, request, *args, **kwargs): context = self.get_context(request, *args, **kwargs) context["latest_posts"] = MyblogDetailPage.objects.live().public()[:1] return render(request, "myblog/latest_posts.html", context)
Python
nomic_cornstack_python_v1
import json class User begin function __init__ self name age begin set name = name set age = age end function end class set user = call User string Max 27 string Serializarion thông thường sẽ báo lỗi như này TypeError: Object of type User is not JSON serializable comment userJSON = json.dumps(user) comment cần viết cus...
import json class User: def __init__(self, name, age): self.name = name self.age = age user = User('Max', 27) """ Serializarion thông thường sẽ báo lỗi như này TypeError: Object of type User is not JSON serializable """ # userJSON = json.dumps(user) # cần viết custom encoding function def enco...
Python
zaydzuhri_stack_edu_python
function load file begin if not ends with file string .biosim begin raise call ValueError string Must be a '.biosim' file. end try begin return load pickle open file string br end except any begin raise call ValueError string This file is not a readable BioSim file. end end function
def load(file): if not file.endswith(".biosim"): raise ValueError("Must be a '.biosim' file.") try: return pickle.load(open(file, "br")) except: raise ValueError("This file is not a readable BioSim file.")
Python
nomic_cornstack_python_v1
function locate_package_json begin string Find and return the location of package.json. set directory = SYSTEMJS_PACKAGE_JSON_DIR if not directory begin raise call ImproperlyConfigured string Could not locate 'package.json'. Set SYSTEMJS_PACKAGE_JSON_DIR to the directory that holds 'package.json'. end set path = join p...
def locate_package_json(): """ Find and return the location of package.json. """ directory = settings.SYSTEMJS_PACKAGE_JSON_DIR if not directory: raise ImproperlyConfigured( "Could not locate 'package.json'. Set SYSTEMJS_PACKAGE_JSON_DIR " "to the directory that holds...
Python
jtatman_500k
function add self classifier threshold begin=none end=none begin string Adds a new strong classifier with the given threshold to the cascade. **Parameters:** classifier : :py:class:`bob.learn.boosting.BoostedMachine` A strong classifier to add ``threshold`` : float The classification threshold for this cascade step ``b...
def add(self, classifier, threshold, begin=None, end=None): """Adds a new strong classifier with the given threshold to the cascade. **Parameters:** classifier : :py:class:`bob.learn.boosting.BoostedMachine` A strong classifier to add ``threshold`` : float The classification threshold for...
Python
jtatman_500k
function language_code self begin warn string Optional. Deprecated. The model automatically detects the text language. Your catalog can include text in different languages, but duplicating catalog items to provide text in multiple languages can result in degraded model performance. DeprecationWarning warn string langua...
def language_code(self) -> Optional[pulumi.Input[str]]: warnings.warn("""Optional. Deprecated. The model automatically detects the text language. Your catalog can include text in different languages, but duplicating catalog items to provide text in multiple languages can result in degraded model performance."""...
Python
nomic_cornstack_python_v1
import math from config_offline import conf function equal_mapping num begin return num end function function limit_log num lower=0.01 upper=100.0 begin if num < lower begin set num = lower end else if num > upper begin set num = upper end set num_log = log num return num_log end function function log_change_single num...
import math from config_offline import conf def equal_mapping(num): return num def limit_log(num, lower=0.01, upper=100.0): if num < lower: num = lower elif num > upper: num = upper num_log = math.log(num) return num_log def log_change_single(num): num_log = 100 * limit_log...
Python
zaydzuhri_stack_edu_python
function render_certificate begin if method == string POST begin set file_name = call generate_certificate form at string name form at string pr_num return call render_template string download.html file_name=file_name end end function
def render_certificate(): if request.method == "POST": file_name = generate_certificate( request.form['name'], request.form['pr_num']) return render_template('download.html', file_name=file_name)
Python
nomic_cornstack_python_v1
function unsubscribe_from_topic tokens topic app=none begin return call make_topic_management_request tokens topic string iid/v1:batchRemove end function
def unsubscribe_from_topic(tokens, topic, app=None): return _get_messaging_service(app).make_topic_management_request( tokens, topic, 'iid/v1:batchRemove')
Python
nomic_cornstack_python_v1
function collect_articles begin comment Create a json fixture for all articles which don't exist in the current comment fixture file comment TODO: Parse content before writing content to fixture for article in call get_new_local_articles begin with open article_root + string / + article string r as f begin comment exte...
def collect_articles(): # Create a json fixture for all articles which don't exist in the current # fixture file # TODO: Parse content before writing content to fixture for article in get_new_local_articles(): with open(article_root + "/" + article, 'r') as f: #extension = article.sp...
Python
nomic_cornstack_python_v1
with open string input.txt string r as f begin set a = read line f set n = integer a - 2 set d = integer a - 1 set r = integer a + 1 set e = integer a + 2 end with open string output.txt string w as f begin write f string n write f string write f string d write f string write f string a write f string write f string r ...
with open('input.txt','r') as f: a=f.readline() n=int(a)-2 d=int(a)-1 r=int(a)+1 e=int(a)+2 with open('output.txt','w') as f: f.write(str(n)) f.write(" ") f.write(str(d)) f.write(" ") f.write(str(a)) f.write(" ") f.write(str(r)) f.write(" ") f.w...
Python
zaydzuhri_stack_edu_python
import argparse import datetime import json import os import subprocess from src.db.db_connection import sql_cursor string This script should be set up with a cron job to run daily. Each user will have to set up their rclone config, in our case pointing to a Google Drive folder: https://rclone.org/drive/ This can be do...
import argparse import datetime import json import os import subprocess from src.db.db_connection import sql_cursor """ This script should be set up with a cron job to run daily. Each user will have to set up their rclone config, in our case pointing to a Google Drive folder: https://rclone.org/drive/ This can be don...
Python
zaydzuhri_stack_edu_python
from random import uniform from math import log , sqrt , pi , sin , cos class Boat begin function __init__ self begin set load_time = 0 set times = list 0 * 4 set type = call gen_boat set times at 0 = call boat_arrival end function function __lt__ b1 b2 begin return times at 0 < times at 0 end function function __gt__ ...
from random import uniform from math import log, sqrt, pi, sin, cos class Boat: def __init__(self): self.load_time = 0 self.times = [0] * 4 self.type = gen_boat() self.times[0] = boat_arrival() def __lt__(b1, b2): return b1.times[0] < b2.times[0] def __gt...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression import pickle import warnings filter warnings string ignore comment READ DATA set df1 = read csv string Heart Disease1.csv set df1 = drop df1 st...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression import pickle import warnings warnings.filterwarnings("ignore") #READ DATA df1=pd.read_csv("Heart Disease1.csv") df1=df1.drop('no',axis='colum...
Python
zaydzuhri_stack_edu_python
function Cancel self request global_params=none begin set config = call GetMethodConfig string Cancel return call _RunMethod config request global_params=global_params end function
def Cancel(self, request, global_params=None): config = self.GetMethodConfig('Cancel') return self._RunMethod( config, request, global_params=global_params)
Python
nomic_cornstack_python_v1
function __drawEvent self event begin call create_rectangle position at 0 - 10 position at 1 - 10 position at 0 + 10 position at 1 + 10 outline=string #000 fill=string #AAAAAA width=2 call create_text position at 0 position at 1 + 20 text=label end function
def __drawEvent(self, event): self.__canvas.create_rectangle(event.position[0] - 10, event.position[1] - 10, event.position[0] + 10, event.position[1] + 10, outline="#000", fill="#AAAAAA", width=2) self.__canvas.create_text(event.position[0], event.position[1] + 20, text=event.label)
Python
nomic_cornstack_python_v1