code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment !/usr/bin/env python3 comment -*- coding:utf-8 -*- comment 3 請利用以下空白範本設計一支程式。程式可輸入一段字串,並自動計算出字串中包括空白字元出現的機率。 comment 並由高排到低。 function charFreqLister inputSTR begin set d = dictionary for char in inputSTR begin if char not in d begin set d at char = 1 end else begin set d at char = d at char + 1 end end return d...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # 3 請利用以下空白範本設計一支程式。程式可輸入一段字串,並自動計算出字串中包括空白字元出現的機率。 # 並由高排到低。 def charFreqLister(inputSTR): d = dict() for char in inputSTR: if char not in d: d[char] = 1 else: d[char] += 1 return d h = charFreqLister(input('Please...
Python
zaydzuhri_stack_edu_python
import time import mysql.connector import json import random from datetime import datetime function db_connection begin set mydb = call connect host=string comp123.cafkc5h3ic4r.us-east-1.rds.amazonaws.com user=string admin port=string 3306 database=string comp123 passwd=string password autocommit=true comment print("su...
import time import mysql.connector import json import random from datetime import datetime def db_connection(): mydb = mysql.connector.connect( host = 'comp123.cafkc5h3ic4r.us-east-1.rds.amazonaws.com', user = 'admin', port = '3306', database = 'comp123', passwd = 'password', autocommit = True) #print...
Python
zaydzuhri_stack_edu_python
function to_str self begin return call pformat call to_dict end function
def to_str(self): return pprint.pformat(self.to_dict())
Python
nomic_cornstack_python_v1
function __setRegion__ self x begin set region = x end function
def __setRegion__(self, x): self.region = x
Python
nomic_cornstack_python_v1
function oscillator_bank frequency amplitude sample_rate begin comment constrain frequencies set frequency = clamp torch frequency 20.0 sample_rate / 2.0 comment translate frequencies in hz to radians set omegas = frequency * 2 * pi set omegas = omegas / sample_rate set phases = cumulative sum torch omegas dim=- 1 set ...
def oscillator_bank(frequency, amplitude, sample_rate): # constrain frequencies frequency = torch.clamp(frequency, 20., sample_rate / 2.) # translate frequencies in hz to radians omegas = frequency * (2 * np.pi) omegas = omegas / sample_rate phases = torch.cumsum(omegas, dim=-1) wavs = to...
Python
nomic_cornstack_python_v1
set num1 = integer input string num1 set num2 = integer input string num2 print num1 // num2 print num1 / num2 print num1 % num2
num1=int(input("num1")) num2=int(input("num2")) print(num1//num2) print(num1/num2) print(num1%num2)
Python
zaydzuhri_stack_edu_python
function list self local=false begin if local begin return list end return list resource_group_name=_resource_group_name workspace_name=_workspace_name cls=lambda objs -> list comprehension call _from_rest_object obj for obj in objs keyword _init_kwargs end function
def list(self, *, local: bool = False) -> ItemPaged[OnlineEndpoint]: if local: return self._local_endpoint_helper.list() return self._online_operation.list( resource_group_name=self._resource_group_name, workspace_name=self._workspace_name, cls=lambda objs...
Python
nomic_cornstack_python_v1
import requests string This is a base class used to define the necessary interface between the PYC rest service using the requests library set __author__ = string McKay Clawson set __email__ = string mckay.clawson@gmail.com class RestController begin function __init__ self begin pass end function function get self url ...
import requests """ This is a base class used to define the necessary interface between the PYC rest service using the requests library """ __author__ = "McKay Clawson" __email__ = "mckay.clawson@gmail.com" class RestController: def __init__(self): pass def get(self, url, endpoint): return requests.get(url...
Python
zaydzuhri_stack_edu_python
class Budget begin pass function depositFunds self begin set deposit = integer input string How much would you like to deposit? print format string You have successfully deposited #{} deposit string into this category end function function balance self begin set balance = integer input string Your balance in this categ...
class Budget(): pass def depositFunds(self): deposit = int(input("How much would you like to deposit? \n")) print('You have successfully deposited #{}'.format(deposit),'into this category') def balance(self): balance = int(input('''Your balance in this category is #0.00. Would you li...
Python
zaydzuhri_stack_edu_python
function deco func begin function inner begin print string hello call func return inner end function end function function hello begin print string helo world end function print call deco call hello
def deco(func): def inner(): print('hello') func() return inner def hello(): print('helo world') print(deco(hello()))
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment Copyright 2007 Google Inc. comment Licensed under the Apache License, Version 2.0 (the "License"); comment you may not use this file except in compliance with the License. comment You may obtain a copy of the License at comment http://www.apache.org/licenses/LICENSE-2.0 comment Unle...
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
Python
zaydzuhri_stack_edu_python
function bz2_file_reader path begin return open path string rt end function
def bz2_file_reader(path): return bz2.open(path, 'rt')
Python
nomic_cornstack_python_v1
function load_metadata self name begin return call load_metadata _casedir / call Path format string {name}/metadata_{name}.yaml name=name end function
def load_metadata(self, name) -> Dict[str, str]: return load_metadata(self._casedir / Path("{name}/metadata_{name}.yaml".format(name=name)))
Python
nomic_cornstack_python_v1
for i in range n 0 - 1 begin for j in range 1 i + 1 begin print n end=string end set n = n - 1 print string end
for i in range(n,0,-1): for j in range(1,i+1): print(n , end=' ') n-=1 print(' ')
Python
zaydzuhri_stack_edu_python
function spanish_tokenize text begin set tokens = call word_tokenize text string spanish set stems = call stem_tokens tokens stemmers at string spanish set stems = list comprehension i for i in stems if i not in punctuations return stems end function
def spanish_tokenize(text): tokens = word_tokenize(text, 'spanish') stems = stem_tokens(tokens, stemmers['spanish']) stems = [i for i in stems if i not in punctuations] return stems
Python
nomic_cornstack_python_v1
import pygame.font class Scoreboard begin string A class to report scoring information. function __init__ self ai_settings screen stats begin string Initialize scorekeeping attributes. set screen = screen set screen_rect = call get_rect set ai_settings = ai_settings set stats = stats comment Font settings for scoring i...
import pygame.font class Scoreboard(): """A class to report scoring information.""" def __init__(self, ai_settings, screen, stats): """Initialize scorekeeping attributes.""" self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.s...
Python
zaydzuhri_stack_edu_python
function optimize initial_weights=default_weights thresh=0.001 verbose=true begin set fast_bleu = call fast_bleu_calculator set all_hyps = list comprehension split pair string ||| for pair in open infile at slice : 40000 : set num_sents = length all_hyps / 100 print string num_sents = %d % num_sents set max_change = ...
def optimize(initial_weights = default_weights, thresh = .001, verbose = True): fast_bleu = fast_bleu_calculator() all_hyps = [pair.split(' ||| ') for pair in open(infile)][:40000] num_sents = len(all_hyps) / 100 print("num_sents = %d" % num_sents) max_change = float('inf') weights = dict(initial_weights) ...
Python
nomic_cornstack_python_v1
from django.shortcuts import render from django.http import HttpResponse comment Create your views here. function index request begin return call HttpResponse string this is webapp world, powered by django end function function time_stamp request begin import datetime set res = string now return call HttpResponse strin...
from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("this is webapp world, powered by django") def time_stamp(request): import datetime res = str(datetime.datetime.now()) return HttpResponse(f"current time stamp {re...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment http://www.bogotobogo.com/python/NLTK/tf_idf_with_scikit-learn_NLTK.php import sys import os function mergeResultToCSV path_in=string ./temp-processing-data/04_tf path_out=string ./temp-processing-data/05_merge-csv file_name=string test_data.csv limit_c...
#!/usr/bin/env python # -*- coding: utf-8 -*- # http://www.bogotobogo.com/python/NLTK/tf_idf_with_scikit-learn_NLTK.php import sys import os def mergeResultToCSV(path_in = './temp-processing-data/04_tf', path_out = './temp-processing-data/05_merge-csv', file_name="test_data.csv", limit_count_word=100): foutname = ...
Python
zaydzuhri_stack_edu_python
function is_prime num begin for i in range 2 num begin if num % i == 0 begin return false end end return true end function set number = 27 if call is_prime number begin print string number + string is a prime number. end else begin print string number + string is not a prime number. end
def is_prime(num): for i in range(2, num): if (num % i) == 0: return False return True number = 27 if is_prime(number): print(str(number) + ' is a prime number.') else: print(str(number) + ' is not a prime number.')
Python
flytech_python_25k
function test_TextureModel1 self begin call delayDisplay string Starting the test comment Download import urllib set url = string https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/752ce9afe8b708fcd4f8448612170f8e730670d845f65177860edc0e08004ecf set zipFilePath = temporaryPath + string / + string Femu...
def test_TextureModel1(self): slicer.util.delayDisplay("Starting the test") # Download import urllib url = 'https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/752ce9afe8b708fcd4f8448612170f8e730670d845f65177860edc0e08004ecf' zipFilePath = slicer.app.temporaryPath + '/' + 'FemurHe...
Python
nomic_cornstack_python_v1
function read_map_file path begin with open path as f begin set dir_name = directory name path path set img = call imread dir_name + string / + strip read line f assert shape at 0 > 0 and shape at 1 > 0 msg string Can not open image file set meter_per_pixel = decimal strip read line f set ori_str = split strip read lin...
def read_map_file(path): with open(path) as f: dir_name = os.path.dirname(path) img = cv2.imread(dir_name + '/' + f.readline().strip()) assert img.shape[0] > 0 and img.shape[1] > 0, 'Can not open image file' meter_per_pixel = float(f.readline().strip()) ori_str = f.read...
Python
nomic_cornstack_python_v1
function merge_sort list begin string 并归排序 时间复杂度O(nlogn) 空间复杂度O(n) :param list: :return: if length list <= 1 begin return list end set n = length list // 2 comment 递归地将左边二分,直至只剩一个元素 set left = call merge_sort list at slice : n : comment 递归地将右边二分,直至只剩一个元素 set right = call merge_sort list at slice n : : comment 将左右两边合并...
def merge_sort(list): """ 并归排序 时间复杂度O(nlogn) 空间复杂度O(n) :param list: :return: """ if len(list) <= 1: return list n = len(list) // 2 left = merge_sort(list[:n]) # 递归地将左边二分,直至只剩一个元素 right = merge_sort(list[n:]) # 递归地将右边二分,直至只剩一个元素 return merge(left, right) # 将左右两边合并 ...
Python
zaydzuhri_stack_edu_python
function select_calib_from_database index_file dateobs begin comment get instrument name set mobj = match string wlcalib_(\S*)\.dat$ base name path index_file set instrument = call group 1 set calibtable = read Table index_file format=string ascii.fixed_width_two_line set input_date = parse parser dateobs comment selec...
def select_calib_from_database(index_file, dateobs): # get instrument name mobj = re.match('wlcalib_(\S*)\.dat$', os.path.basename(index_file)) instrument = mobj.group(1) calibtable = Table.read(index_file, format='ascii.fixed_width_two_line') input_date = dateutil.parser.parse(dateobs) # se...
Python
nomic_cornstack_python_v1
from collections import OrderedDict from functools import partial from time import time from sklearn.manifold import TSNE import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter from bioinfokit.visuz import cluster from sklearn import manifold , datasets set s...
from collections import OrderedDict from functools import partial from time import time from sklearn.manifold import TSNE import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import NullFormatter from bioinfokit.visuz import cluster from sklearn import manifold, datasets showc...
Python
zaydzuhri_stack_edu_python
comment WAP to check if a number is positive ,negative,zero set num = decimal input string enter a number if num > 0 begin print string number is positive end else if num == 0 begin print string zero end else begin print string Negative number end
#WAP to check if a number is positive ,negative,zero num=float(input('enter a number')) if num>0: print('number is positive') elif(num==0): print('zero') else: print('Negative number')
Python
zaydzuhri_stack_edu_python
function full_event self behavior_idx begin set event = dictionary pj at ETHOGRAM at behavior_idx return event end function
def full_event(self, behavior_idx): event = dict(self.pj[ETHOGRAM][behavior_idx]) return event
Python
nomic_cornstack_python_v1
function main begin set n = integer input set a_li = list map int split input set b_li = list map int split input set ans = 0 for i in range n begin if a_li at i >= b_li at i begin set ans = ans + b_li at i end else begin set ans = ans + a_li at i set mod = b_li at i - a_li at i if mod <= a_li at i + 1 begin set a_li a...
def main(): n = int(input()) a_li = list(map(int, input().split())) b_li = list(map(int, input().split())) ans = 0 for i in range(n): if a_li[i] >= b_li[i]: ans += b_li[i] else: ans += a_li[i] mod = b_li[i]-a_li[i] ...
Python
zaydzuhri_stack_edu_python
import sys set stdin = open string 예산_input.txt set N = integer input set data = list map int split input set M = integer input comment 이진탐색에서는 sort가 필요하지 않다 sort data set temp = 0 set money = 0 for i in range N begin if temp + data at i * N - i <= M begin set temp = temp + data at i comment 모든 부분을 통과하면 가장 마지막 값을 배정하면 ...
import sys sys.stdin = open("예산_input.txt") N = int(input()) data = list(map(int, input().split())) M = int(input()) data.sort() # 이진탐색에서는 sort가 필요하지 않다 temp = 0 money = 0 for i in range(N): if temp + (data[i] * (N-i)) <= M: temp += data[i] money = data[i] # 모든 부분을 통과하면 가장 마지막 값을 배정하면 된다 ...
Python
zaydzuhri_stack_edu_python
function check_valid_password pwd begin set length_valid = length pwd >= 8 set has_uppercase = false set has_lowercase = false set has_digit = false end function
def check_valid_password(pwd): length_valid = (len(pwd) >= 8) has_uppercase = False has_lowercase = False has_digit = False
Python
jtatman_500k
function query self search query begin if query begin return query search string multi_match fields=fields query=query end return search end function
def query(self, search, query): if query: return search.query('multi_match', fields=self.fields, query=query) return search
Python
nomic_cornstack_python_v1
from datetime import datetime , time , timedelta from typing import Any , List , Callable from pydantic import Field from marta.enums.direction import Direction from marta.enums.train_line import TrainLine from marta.models.vehicle import Train class Arrivals begin function __init__ self arrivals begin set _arrivals = ...
from datetime import datetime, time, timedelta from typing import Any, List, Callable from pydantic import Field from marta.enums.direction import Direction from marta.enums.train_line import TrainLine from marta.models.vehicle import Train class Arrivals: def __init__(self, arrivals: List['Arrival']): ...
Python
zaydzuhri_stack_edu_python
function forward self x begin set feat = call features x set feat = squeeze feat set out = call classifier feat return out end function
def forward(self, x): feat = self.features(x) feat = feat.squeeze() out = self.classifier(feat) return out
Python
nomic_cornstack_python_v1
string 4. Escreva um programa que declare um inteiro, inicialize-o com 0, e incremente-o de 1000 em 1000, imprimindo seu valor na tela, até que seu valor seja 100000(cem mil). for n in range 0 100001 1000 begin print n end
""" 4. Escreva um programa que declare um inteiro, inicialize-o com 0, e incremente-o de 1000 em 1000, imprimindo seu valor na tela, até que seu valor seja 100000(cem mil). """ for n in range (0, 100001, 1000): print(n)
Python
zaydzuhri_stack_edu_python
function __init__ self transition_matrix seed=0 begin set transition_matrix = transition_matrix comment Set up the RNG call __init__ seed end function
def __init__(self, transition_matrix, seed=0): self.transition_matrix = transition_matrix # Set up the RNG super().__init__(seed)
Python
nomic_cornstack_python_v1
function setWidth self w begin if not is instance w tuple int float begin raise call TypeError string width must be numeric end if w <= 0 begin raise call ValueError string width must be positive end call setSize w end function
def setWidth(self, w): if not isinstance(w, (int, float)): raise TypeError('width must be numeric') if w <= 0: raise ValueError("width must be positive") self.setSize(w)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment +!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+! comment # comment extractMeshNodes.py # comment # comment +!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+! comment Author: Pat Prodanovic, Ph.D., P.Eng. comment Date: December 1, 2015 c...
#!/usr/bin/env python3 # #+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+!+! # # # extractMeshNodes.py # # ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import HTMLParser class MyParse extends HTMLParser begin function __init__ self begin comment super() does not work for this class call __init__ self set tag_stack = list set attr_stack = list end function function handle_endtag self tag begin comment take the tag off the stack if it matches ...
#!/usr/bin/python import HTMLParser class MyParse(HTMLParser.HTMLParser): def __init__(self): #super() does not work for this class HTMLParser.HTMLParser.__init__(self) self.tag_stack = [] self.attr_stack = [] def handle_endtag(self, tag): #take the tag off the stack i...
Python
zaydzuhri_stack_edu_python
string Maximum height of staircase Problem Description Given an integer A representing the number of square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on....
''' Maximum height of staircase Problem Description Given an integer A representing the number of square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on. ...
Python
zaydzuhri_stack_edu_python
comment begin lexer.py comment TODO: replace tokenizer with a generator in lexer class without RegEx import re from algebraic_function_grammar import calculation_operator_dict from algebraic_function_grammar import linking_operator_dict from algebraic_function_grammar import linking_operator_order from algebraic_functi...
# begin lexer.py # TODO: replace tokenizer with a generator in lexer class without RegEx import re from .algebraic_function_grammar import calculation_operator_dict from .algebraic_function_grammar import linking_operator_dict from .algebraic_function_grammar import linking_operator_order from .algebraic_function_gram...
Python
zaydzuhri_stack_edu_python
from ipycanvas import Canvas , hold_canvas from ipywidgets import Image import numpy as np import matplotlib.pyplot as plt import math from time import sleep class Render extends object begin function __init__ self wall_thickness=0.1 scale=50 mx=600 my=600 begin set scale = scale set mx = mx set my = my set wall_th = w...
from ipycanvas import Canvas, hold_canvas from ipywidgets import Image import numpy as np import matplotlib.pyplot as plt import math from time import sleep class Render(object): def __init__(self, wall_thickness=0.1, scale=50, mx=600, my=600): self.scale = scale self.mx = mx self.my = my ...
Python
zaydzuhri_stack_edu_python
function velocity length time method=string slope sort_length=false deg=2 begin set delta_t = call roll time - 1 - time if sort_length begin set length = sort np length end if method == string slope begin set vel = call roll length - 1 - length / delta_t end else if method == string gradient begin set vel = call gradie...
def velocity(length, time, method='slope', sort_length=False, deg=2): delta_t = np.roll(time, -1) - time if sort_length: length = np.sort(length) if method == 'slope': vel = (np.roll(length, -1) - length) / delta_t elif method == 'gradient': vel = np.gradient(length, time) ...
Python
nomic_cornstack_python_v1
comment import necessary packages import face_recognition import numpy as np import cv2 comment this sets a variable for the image filter set elf = call imread string ck4.png - 1 comment this opens the camera set cap = call VideoCapture 0 set CAP_PROP_FPS 30 comment this is responsible in overlaying the filter to the f...
#import necessary packages import face_recognition import numpy as np import cv2 #this sets a variable for the image filter elf = cv2.imread('ck4.png',-1) #this opens the camera cap = cv2.VideoCapture(0) cap.set(cv2.CAP_PROP_FPS, 30) #this is responsible in overlaying the filter to the face detected in the video cl...
Python
zaydzuhri_stack_edu_python
function warn_with_traceback message category filename lineno file=none line=none begin set log = if expression has attribute file string write then file else stderr call print_stack file=log write log call formatwarning message category filename lineno line end function
def warn_with_traceback(message, category, filename, lineno, file=None, line=None): log = file if hasattr(file,'write') else sys.stderr traceback.print_stack(file=log) log.write(warnings.formatwarning(message, category, filename, lineno, line))
Python
nomic_cornstack_python_v1
function decimal_to_binary number begin comment Check if the input is zero if number == 0 begin return string 0 end comment Handle negative numbers set is_negative = false if number < 0 begin set is_negative = true set number = absolute number end comment Separate the integer and fractional parts set integer_part = int...
def decimal_to_binary(number): # Check if the input is zero if number == 0: return '0' # Handle negative numbers is_negative = False if number < 0: is_negative = True number = abs(number) # Separate the integer and fractional parts integer_part = int(number) fra...
Python
jtatman_500k
import math function binary_search array val begin set f = 0 set l = length array - 1 while l >= f begin set mid = integer f + l / 2 if array at mid == val begin return mid end else if val > array at mid begin set f = mid + 1 end else begin set l = mid - 1 end end end function set array = list 12 68 46 21 98 50 set val...
import math def binary_search(array,val): f=0 l=len(array)-1 while(l>=f): mid=int((f+l)/2) if(array[mid]==val): return mid elif(val>array[mid]): f=mid+1 else: l=mid-1 array=[12,68,46,21,98,50] val=12 index=binary_search(array,...
Python
zaydzuhri_stack_edu_python
function add_digital_hw_pin self pin read=none write=none inital_state=none begin if is instance pin int begin set _digital_hw_pins at pin = call HwPin read=read write=write blynk_ref=self initial_state=inital_state end else begin raise call ValueError string pin value must be an integer value end end function
def add_digital_hw_pin(self, pin, read=None, write=None, inital_state=None): if isinstance(pin, int): self._digital_hw_pins[pin] = HwPin(read=read, write=write, blynk_ref=self, initial_state=inital_state) else: raise ValueError("pin value must be an integer value")
Python
nomic_cornstack_python_v1
string Created on Aug 22, 2017 Reading and Writing Python Files https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/2.4/lib/bltin-file-objects.html https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding @author: rduvalwa2 comment from encodings.utf_8 impor...
''' Created on Aug 22, 2017 Reading and Writing Python Files https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/2.4/lib/bltin-file-objects.html https://docs.python.org/3/library/sys.html#sys.getfilesystemencoding @author: rduvalwa2 ''' #from encodings.utf_8 import en...
Python
zaydzuhri_stack_edu_python
function testHealthAssessLegEdema self begin set attr = call create_visit_attr call boolTypeTest self attr string leg_edema call boolPropertyTest self attr string leg_edema end function
def testHealthAssessLegEdema(self): attr = self.session.create_visit_attr() self.util.boolTypeTest(self, attr, "leg_edema") self.util.boolPropertyTest(self, attr, "leg_edema")
Python
nomic_cornstack_python_v1
import random function showDie die begin if die == 1 begin print string |-----------| print string | | print string | O | print string | | print string |-----------| print end else if die == 2 begin print string |-----------| print string | | print string | O O | print string | | print string |-----------| print end el...
import random def showDie(die): if die == 1: print ("|-----------|") print ("| |") print ("| O |") print ("| |") print ("|-----------|") print elif die == 2: ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np from pyecharts.charts import * import pyecharts.options as opts import os from functools import reduce function plot_one_y df title begin set index = call to_datetime df at string date sort index df inplace=true set df = drop df list string date axis=1 return call set_series_opts ...
import pandas as pd import numpy as np from pyecharts.charts import * import pyecharts.options as opts import os from functools import reduce def plot_one_y(df, title:str): df.index = pd.to_datetime(df['date']) df.sort_index(inplace=True) df = df.drop(['date'], axis=1) return ( Line(init_opts=o...
Python
zaydzuhri_stack_edu_python
function is_valid self raise_exception=false begin assert has attribute self string initial_data msg string Cannot call `.is_valid()` as no `data=` keyword argument was passed when instantiating the serializer instance. if not has attribute self string _validated_data begin try begin set _validated_data = call run_vali...
def is_valid(self, raise_exception=False): assert hasattr(self, 'initial_data'), ( 'Cannot call `.is_valid()` as no `data=` keyword argument was ' 'passed when instantiating the serializer instance.' ) if not hasattr(self, '_validated_data'): try: ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- set num = 0 set ou_num = 0 for i in range 101 begin if i % 2 == 0 begin set ou_num = ou_num + i end else begin set num = num + i end end print ou_num print num
#!/usr/bin/env python # -*- coding: utf-8 -*- num = 0 ou_num = 0 for i in range(101): if i % 2 == 0: ou_num += i else: num += i print(ou_num) print(num)
Python
zaydzuhri_stack_edu_python
function permute nums begin set permutations = list list for n in nums begin set ans = list for item in permutations begin for i in range length item + 1 begin set s = item at slice : i : + list n + item at slice i : : if s not in ans begin append ans s end end end comment 这里按理说保险的话就是深拷贝,但是经过测试,ans直接为空的话,不会影响perm...
def permute(nums): permutations=[[]] for n in nums: ans=[] for item in permutations: for i in range(len(item)+1): s=item[:i] + [n] + item[i:] if s not in ans: ans.append(s) permutations=ans#这里按理说保险的话就是深拷贝,但是经过测试,ans直接为空的话,不会...
Python
zaydzuhri_stack_edu_python
function distance_table tables distance_func begin set num_tables = length tables set res = zeros tuple num_tables num_tables info string Calculating distance for %d pairs... % num_tables ^ 2 - num_tables / 2 set timer = call MultiTimer num_tables ^ 2 - num_tables / 2 for i in call xrange num_tables begin for j in call...
def distance_table(tables, distance_func): num_tables = len(tables) res = np.zeros((num_tables, num_tables)) logging.info( 'Calculating distance for %d pairs...' % ((num_tables ** 2 - num_tables) / 2)) timer = MultiTimer((num_tables ** 2 - num_tables) / 2) for i in xrange(num_tables): for j in xrang...
Python
nomic_cornstack_python_v1
set keys = list 1 2 3 set values = list string a string b string c set list_of_dict = list comprehension dictionary zip keys values for i in range length keys comment Output: [{1: 'a', 2: 'b', 3: 'c'}] print list_of_dict
keys = [1,2,3] values = ["a","b","c"] list_of_dict = [dict(zip(keys, values)) for i in range(len(keys))] print(list_of_dict) # Output: [{1: 'a', 2: 'b', 3: 'c'}]
Python
iamtarun_python_18k_alpaca
function bp name config begin return name in call backports end function
def bp(name, config): return name in config.backports()
Python
nomic_cornstack_python_v1
function __getitem__ self key begin return _value at key end function
def __getitem__(self, key): return self._value[key]
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import matplotlib as mpl call use string Agg import matplotlib.pyplot as plt import matplotlib.backends.backend_pdf import numpy as np import keras if __name__ == string __main__ begin from keras import Input , layers from keras.models import Sequential , Mode...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import matplotlib.backends.backend_pdf import numpy as np import keras if __name__ == '__main__': from keras import Input, layers from keras.models import Sequential, Model model = Sequential() ...
Python
zaydzuhri_stack_edu_python
function published self published begin set _published = published end function
def published(self, published): self._published = published
Python
nomic_cornstack_python_v1
import requests from pprint import pprint set intelligence_dict = dictionary function hero_intelligence hero_lis begin for name in hero_lis begin set resp = get requests string https://superheroapi.com/api/2619421814940190/search/ { name } set resp_get = json resp set hero = resp_get at string results for info in hero ...
import requests from pprint import pprint intelligence_dict = dict() def hero_intelligence(hero_lis): for name in hero_lis: resp = requests.get(f'https://superheroapi.com/api/2619421814940190/search/{name}') resp_get = resp.json() hero = resp_get['results'] for info in hero: ...
Python
zaydzuhri_stack_edu_python
function select_policy self key begin if key not in _policies begin raise call PolicyException string Invalid key specified { key } when selecting policy end set _selected_policy = key set _policy_model = _policies at key at string model set _templates = _policies at key at string templates info string Selected policy ...
def select_policy(self, key): if key not in self._policies: raise PolicyException(f"Invalid key specified {key} when selecting policy") self._selected_policy = key self._policy_model = self._policies[key]["model"] self._templates = self._policies[key]["templates"] s...
Python
nomic_cornstack_python_v1
function _job_get_create_time self job_id begin comment check if we can / should update if jobs at job_id at string gone is not true and jobs at job_id at string create_time is none begin set jobs at job_id = call _job_get_info job_id=job_id end return jobs at job_id at string create_time end function
def _job_get_create_time(self, job_id): # check if we can / should update if (self.jobs[job_id]['gone'] is not True) \ and (self.jobs[job_id]['create_time'] is None): self.jobs[job_id] = self._job_get_info(job_id=job_id) return self.jobs[job_id]['create_time']
Python
nomic_cornstack_python_v1
function get_amr_gene_name self begin pass end function
def get_amr_gene_name(self): pass
Python
nomic_cornstack_python_v1
function compare da op thresh begin return call call get_op op da thresh end function
def compare(da: xr.DataArray, op: str, thresh: Union[float, int]) -> xr.DataArray: return get_op(op)(da, thresh)
Python
nomic_cornstack_python_v1
from flask import render_template , Blueprint , flash , json , request from flaskapp.projects.forms import ProjectForm from flaskapp import db from flaskapp.models import Project from flask_login import login_required set projects = call Blueprint string projects __name__ decorator call route string /projects function ...
from flask import (render_template, Blueprint, flash, json, request) from flaskapp.projects.forms import ProjectForm from flaskapp import db from flaskapp.models import Project from flask_login import login_required projects = Blueprint('projects', __name__) @projects.route("/projects") def all_projects(): proje...
Python
zaydzuhri_stack_edu_python
function get_metrics predicted gold begin string Takes a predicted answer and a gold answer (that are both either a string or a list of strings), and returns exact match and the DROP F1 metric for the prediction. If you are writing a script for evaluating objects in memory (say, the output of predictions during validat...
def get_metrics(predicted: Union[str, List[str], Tuple[str, ...]], gold: Union[str, List[str], Tuple[str, ...]]) -> Tuple[float, float]: """ Takes a predicted answer and a gold answer (that are both either a string or a list of strings), and returns exact match and the DROP F1 metric for the...
Python
jtatman_500k
function margin self value begin string Setter for **self.__margin** attribute. :param value: Attribute value. :type value: int if value is not none begin assert type value is int msg format string '{0}' attribute: '{1}' type is not 'int'! string margin value assert value > 0 msg format string '{0}' attribute: '{1}' ne...
def margin(self, value): """ Setter for **self.__margin** attribute. :param value: Attribute value. :type value: int """ if value is not None: assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("margin", value) assert v...
Python
jtatman_500k
import io import os from django.utils.unittest import TestCase from animal3 import iso_3166 class TestISO_3166 extends TestCase begin string Country lists match data file, and are internally consistent. comment Read in the only freely available source file from ISO for validation: comment [['AFGHANISTAN', 'AF'], ['ALBA...
import io import os from django.utils.unittest import TestCase from animal3 import iso_3166 class TestISO_3166(TestCase): """ Country lists match data file, and are internally consistent. """ # Read in the only freely available source file from ISO for validation: # [['AFGHANISTAN', 'AF'], ['AL...
Python
zaydzuhri_stack_edu_python
function bias_variable shape stddev=0.1 begin set initial = call constant stddev shape=shape return call Variable initial end function
def bias_variable(shape, stddev=0.1): initial = tf.constant(stddev, shape=shape) return tf.Variable(initial)
Python
nomic_cornstack_python_v1
comment Step 1 set new_node = call Node new_element set current_node = head set index = 0 comment Step 2 while next is not none and index < desired_index begin set current_node = next set index = index + 1 end comment Step 3 set next = next comment Step 4 set next = new_node
new_node = Node(new_element) # Step 1 current_node = head index = 0 while current_node.next is not None and index < desired_index: # Step 2 current_node = current_node.next index += 1 new_node.next = current_node.next # Step 3 current_node.next = new_node # Step 4
Python
greatdarklord_python_dataset
function reveal_cell self event begin set x = x - 2 // CELLWIDTH set y = y - 2 // CELLWIDTH if gamestate is none begin call reveal_cell y x call update_cells end end function
def reveal_cell(self, event): x = (event.x-2) // CELLWIDTH y = (event.y-2) // CELLWIDTH if self.mineboard.gamestate is None: self.mineboard.reveal_cell(y, x) self.update_cells()
Python
nomic_cornstack_python_v1
import sys call setrecursionlimit 2000 from collections import Counter from functools import reduce comment sys.stdin.readline() if __name__ == string __main__ begin comment single variables set n = list comprehension integer val for val in split read line stdin at 0 set count = 0 set s = set list while not n in s begi...
import sys sys.setrecursionlimit(2000) from collections import Counter from functools import reduce # sys.stdin.readline() if __name__ == "__main__": # single variables n = [int(val) for val in sys.stdin.readline().split()][0] count = 0 s = set([]) while(not n in s): s.add(n) n +=...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import os import sys from sklearn.utils import shuffle if length argv != 2 begin print format string Usg: python {} csvfile argv at 0 exit end set SCRIPTPATH = directory name path real path path __file__ set df = read csv argv at 1 comment split by labels set label_dfs = list for...
import numpy as np import pandas as pd import os import sys from sklearn.utils import shuffle if len(sys.argv) != 2: print('Usg: python {} csvfile'.format(sys.argv[0])) exit() SCRIPTPATH = os.path.dirname(os.path.realpath(__file__)) df = pd.read_csv(sys.argv[1]) # split by labels label_dfs = [] for label in range...
Python
zaydzuhri_stack_edu_python
function pctFourOfKindCombinations self round_=none begin if round_ is none begin return call pFourOfKindCombinations * 100 end else begin return round call pFourOfKindCombinations * 100 round_ end end function
def pctFourOfKindCombinations(self, round_=None): if round_ is None: return self.pFourOfKindCombinations() * 100 else: return round(self.pFourOfKindCombinations() * 100, round_)
Python
nomic_cornstack_python_v1
function op_parser self begin set resolvers = resolvers set hole_range = hole_range function parse_parthole_ops op term begin string Parse the operator for particle/hole field operator. set tuple label char indices = call parse_field_op op term set orb_range = call try_resolve_range indices at 0 dictionary sums value i...
def op_parser(self): resolvers = self.resolvers hole_range = self.hole_range def parse_parthole_ops(op: Vec, term: Term): """Parse the operator for particle/hole field operator.""" label, char, indices = parse_field_op(op, term) orb_range = try_resolve_range...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as pat set DIV = 100 set f = open string data string r set y = list for line in f begin for word in split line begin append y integer word end end set N = integer length y / 2 print length y set x = array range 1 N + 1 * DIV set width = 0.3 *...
import matplotlib.pyplot as plt import numpy as np import matplotlib.patches as pat DIV = 100 f = open('data', 'r') y = [] for line in f: for word in line.split(): y.append(int(word)) N = int(len(y)/2) print(len(y)) x = np.arange(1, N+1) * DIV width = 0.3 * DIV print(len(x)) ax = plt.subplot(111) ax....
Python
zaydzuhri_stack_edu_python
function fit self train_ds=none epochs=100 gen_optimizer=string Adam disc_optimizer=string Adam verbose=1 gen_learning_rate=0.0001 disc_learning_rate=0.0002 beta_1=0.5 tensorboard=false save_model=none begin assert train_ds is not none msg string Initialize training data through train_ds parameter call __load_model set...
def fit( self, train_ds=None, epochs=100, gen_optimizer="Adam", disc_optimizer="Adam", verbose=1, gen_learning_rate=0.0001, disc_learning_rate=0.0002, beta_1=0.5, tensorboard=False, save_model=None, ): assert ( ...
Python
nomic_cornstack_python_v1
function error_message cls identifier error_status error_message begin return call OPDSMessage urn error_status error_message end function
def error_message(cls, identifier, error_status, error_message): return OPDSMessage(identifier.urn, error_status, error_message)
Python
nomic_cornstack_python_v1
from vector import Vector class Plane extends object begin set NO_NONZERO_ELTS_FOUND_MSG = string No nonzero elements found function __init__ self normal_vector=none constant_term=none begin try begin set dimension = length coordinates set normal_vector = normal_vector end except TypeError begin raise exception string ...
from vector import Vector class Plane(object): NO_NONZERO_ELTS_FOUND_MSG = 'No nonzero elements found' def __init__(self, normal_vector=None, constant_term=None): try: self.dimension = len(normal_vector.coordinates) self.normal_vector = normal_vector except TypeError:...
Python
zaydzuhri_stack_edu_python
from mongoengine import Document from mongoengine.fields import ObjectIdField , StringField , DecimalField class Recharge extends Document begin set companyId = call ObjectIdField required=true set productId = call ObjectIdField required=true set createdAt = call StringField required=true set phoneNumber = call StringF...
from mongoengine import Document from mongoengine.fields import ObjectIdField, StringField, DecimalField class Recharge(Document): companyId = ObjectIdField(required=True) productId = ObjectIdField(required=True) createdAt = StringField(required=True) phoneNumber = StringField(required=True) value...
Python
zaydzuhri_stack_edu_python
comment This file describes a class for storing and manipulating genotype data from __future__ import division from bisect import * import sys import numpy as np from gwas import missing , complete_cases , is_na set zero = call int16 0 set un = call int16 1 set deux = call int16 2 class Dataset begin function __init__ ...
# This file describes a class for storing and manipulating genotype data from __future__ import division from bisect import * import sys import numpy as np from gwas import missing, complete_cases, is_na zero=np.int16(0) un=np.int16(1) deux=np.int16(2) class Dataset(): def __init__(self,fileName,nsnp,nindiv): ...
Python
zaydzuhri_stack_edu_python
comment Victor Duan comment text-based Puzzle & Dragons damage calculator function main begin comment blah = raw_input("enter fire combos: ").split() comment print blah comment print [int(x) for x in blah] comment return comment get team stats set fire = integer input string Enter fire damage: set water = integer input...
# Victor Duan # text-based Puzzle & Dragons damage calculator def main(): # blah = raw_input("enter fire combos: ").split() # print blah # print [int(x) for x in blah] # return # get team stats fire = int(input("Enter fire damage: ")) water = int(input("Enter water damage: ")) woo...
Python
zaydzuhri_stack_edu_python
function recursive_str_to_unicode target begin set pack_result = list if is instance target dict begin set level = dict for tuple key val in call iteritems begin set ukey = call recursive_str_to_unicode key set uval = call recursive_str_to_unicode val set level at ukey = uval end append pack_result level end else if ...
def recursive_str_to_unicode(target): pack_result = [] if isinstance(target, dict): level = {} for key, val in target.iteritems(): ukey = recursive_str_to_unicode(key) uval = recursive_str_to_unicode(val) level[ukey] = uval pack_result.append(level) ...
Python
nomic_cornstack_python_v1
function __init__ self *args **kwds begin if args or kwds begin call __init__ *args keyword kwds comment message fields cannot be None, assign default values for those that are if enable_steering is none begin set enable_steering = false end if enable_braking is none begin set enable_braking = false end if enable_drivi...
def __init__(self, *args, **kwds): if args or kwds: super(Cmd_WF, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.enable_steering is None: self.enable_steering = False if self.enable_braking is None: self.enable_b...
Python
nomic_cornstack_python_v1
function update_dbx_oauth2_token config begin if config at 0 != string dropbox.key begin print format string Couldn't recognize {0} option. See: sync-music --help config at 0 return false end set env_file = expand user path string ~/.sync-music/config/.env try begin with open env_file string w as f begin write f string...
def update_dbx_oauth2_token(config): if config[0] != 'dropbox.key': print("\nCouldn't recognize {0} option." " See: sync-music --help".format(config[0])) return False env_file = os.path.expanduser('~/.sync-music/config/.env') try: with open(env_file, 'w') as f: ...
Python
nomic_cornstack_python_v1
function __init__ self monitor include begin call __init__ set readables = list stdout set _monitor = monitor set _include = include comment The format strings use to display the stauts of the desktops set _formats = dict string O tuple string %{B#333} string %{-u}%{B-} ; string F tuple string %{B#333}%{F#000} string %...
def __init__(self, monitor, include): super().__init__() self.readables = [ sp.Popen( ['bspc', 'subscribe', 'report'], stdout=sp.PIPE, bufsize=0).stdout ] self._monitor = monitor self._include = include # The format strings u...
Python
nomic_cornstack_python_v1
function clean_hashtags self tweet begin set hashtags = list comprehension strip tag string # for tag in split tweet if starts with tag string # for hashtag in hashtags begin set tweet = replace tweet string # + hashtag string end set tweet = call clean_unnecessary_whitespaces tweet return tweet end function
def clean_hashtags(self, tweet): self.hashtags = [tag.strip('#') for tag in tweet.split() if tag.startswith('#')] for hashtag in self.hashtags: tweet = tweet.replace('#'+hashtag, '') tweet = self.clean_unnecessary_whitespaces(tweet) return tweet
Python
nomic_cornstack_python_v1
comment if input in (0, 1, 11): comment print 'winter' comment elif input in (2, 3, 4): comment print 'spring' comment elif input in (5, 6, 7): comment print 'summer' comment else: comment print 'fall' set seasons = tuple string w string sp string sum string aut
# if input in (0, 1, 11): # print 'winter' # elif input in (2, 3, 4): # print 'spring' # elif input in (5, 6, 7): # print 'summer' # else: # print 'fall' seasons = 'w', 'sp', 'sum', 'aut'
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function partition self head x begin set greater = call ListNode 0 set greater_ptr = greater set less = call ListNode 0 set less_ptr = less while head begin if val >= x begin set next = head set greater = next end else begin set next = head set less = next end set head = next end set...
class Solution(object): def partition(self, head, x): greater = ListNode(0) greater_ptr = greater less = ListNode(0) less_ptr = less while head: if head.val >= x: greater.next = head greater = greater.next else: ...
Python
zaydzuhri_stack_edu_python
string 程序:袋中取球 作者:苏秦@小海豚科学馆公众号 来源:图书《Python趣味编程:从入门到人工智能》 function main begin string 袋中取球 set n = 3 set i = 1 while i <= 5 begin set n = n - 1 * 2 set i = i + 1 end print string 袋中原有小球%d个 % n end function if __name__ == string __main__ begin call main end
''' 程序:袋中取球 作者:苏秦@小海豚科学馆公众号 来源:图书《Python趣味编程:从入门到人工智能》 ''' def main(): '''袋中取球''' n = 3 i = 1 while i <= 5: n = (n - 1) * 2 i = i + 1 print('袋中原有小球%d个' % n) if __name__ == '__main__': main()
Python
zaydzuhri_stack_edu_python
function calculate_tf self begin set tf = dict for tuple k v in items terms begin set tf at k = v / docLen end return tf end function
def calculate_tf(self): tf = {} for k, v in self.terms.items(): tf[k] = v / self.docLen return tf
Python
nomic_cornstack_python_v1
function mean mylist begin set the_mean = sum mylist / length mylist return the_mean end function print mean list 9.8 85 7.3 print type mean type sum
def mean(mylist): the_mean = sum(mylist) / len(mylist) return the_mean print(mean([9.8, 85, 7.3])) print(type(mean), type(sum))
Python
zaydzuhri_stack_edu_python
function search_pfae self init_gamma init_delta **search_kwargs begin function pfa_fun gamma delta begin set elo = call EloModel set pfae = call PFAExt elo gamma=gamma delta=delta set pfae_test = call PerformanceTest pfae data run return off end function set parameters = dict string gamma init_gamma ; string delta init...
def search_pfae(self, init_gamma, init_delta, **search_kwargs): def pfa_fun(gamma, delta): elo = EloModel() pfae = PFAExt(elo, gamma=gamma, delta=delta) pfae_test = PerformanceTest(pfae, self.data) pfae_test.run() return pfae_test.results['train'].off...
Python
nomic_cornstack_python_v1
function display_square number begin set result = number * number print result end function call display_square 5
def display_square(number): result = number * number print(result) display_square(5)
Python
flytech_python_25k
function assert_key_has_value self key caller begin assert key msg string key parameter must be specified. call assert_key_exists key caller if self at key is none begin raise call KeyInContextHasNoValueError string context[' { key } '] must have a value for { caller } . end end function
def assert_key_has_value(self, key, caller): assert key, ("key parameter must be specified.") self.assert_key_exists(key, caller) if self[key] is None: raise KeyInContextHasNoValueError( f"context['{key}'] must have a value for {caller}.")
Python
nomic_cornstack_python_v1
string Cluster ports waiting areas (pwa). Takes only anchoring activity and only container vessels, and cluster ports waiting areas by destination. For each destination port, first find anchoring container vessels that were heading to it (i.e. had this port as their NextPort) and are less than 200km away from it. Then ...
""" Cluster ports waiting areas (pwa). Takes only anchoring activity and only container vessels, and cluster ports waiting areas by destination. For each destination port, first find anchoring container vessels that were heading to it (i.e. had this port as their NextPort) and are less than 200km away from it. Then clu...
Python
zaydzuhri_stack_edu_python
function test_search self begin with patch string builtins.input return_value=string a begin set good = search assert true good end with patch string builtins.input return_value=string b begin set good = search assert true good end with patch string builtins.input return_value=string c begin set good = search assert tr...
def test_search(self): with unittest.mock.patch('builtins.input', return_value='a'): good = self.ec.search() self.assertTrue(good) with unittest.mock.patch('builtins.input', return_value='b'): good = self.ec.search() self.assertTrue(good) with unit...
Python
nomic_cornstack_python_v1
function ipv4_format ip begin set octets = split ip string . extend octets list string 0 string 0 string 0 string 0 set octets = octets at slice : 4 : return join string . octets end function if __name__ == string __main__ begin set ip = string 192.168.1 print call ipv4_format ip end
def ipv4_format(ip): octets = ip.split('.') octets.extend(['0', '0', '0', '0']) octets = octets[:4] return '.'.join(octets) if __name__ == '__main__': ip = '192.168.1' print(ipv4_format(ip))
Python
flytech_python_25k
function normalize_prices df begin set bid_price_cols = list comprehension c for c in df if match string OB_bid1?_\d{1} c set df at bid_price_cols = - df at bid_price_cols print string Bid prices normalized return df end function
def normalize_prices(df: pd.DataFrame) -> pd.DataFrame: bid_price_cols = [c for c in df if re.match(r"OB_bid1?_\d{1}", c)] df[bid_price_cols] = - df[bid_price_cols] print("Bid prices normalized") return df
Python
nomic_cornstack_python_v1