code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import itertools from typing import List , Tuple set boxes = list tuple 4 51 tuple 90 49 tuple 16 80 tuple 84 64 tuple 43 14 tuple 29 2 tuple 68 91 tuple 3 57 tuple 22 53 tuple 32 84 tuple 43 59 tuple 15 84 tuple 90 19 tuple 55 73 tuple 41 41 tuple 54 31 tuple 92 77 tuple 64 81 tuple 61 20 tuple 2 31 set current_weight...
import itertools from typing import List, Tuple boxes = [(4, 51), (90, 49), (16, 80), (84, 64), (43, 14), (29, 2), (68, 91), (3, 57), (22, 53), (32, 84), (43, 59), (15, 84), (90, 19), (55, 73), (41, 41), (54, 31), (92, 77), (64, 81), (61, 20), (2, 31)] current_weight = 908 current_volume = 1061 def calc_sizes(boxes...
Python
zaydzuhri_stack_edu_python
function test_edit_view_file_to_direct_link self mv begin set new_mv = call edit_test_helper mv string direct call verify_direct new_mv end function
def test_edit_view_file_to_direct_link(self, mv): new_mv = self.edit_test_helper(mv, 'direct') verify_direct(new_mv)
Python
nomic_cornstack_python_v1
function InsertBOMBalloon self begin return call InvokeTypes 65893 LCID 1 tuple 24 0 tuple end function
def InsertBOMBalloon(self): return self._oleobj_.InvokeTypes(65893, LCID, 1, (24, 0), (),)
Python
nomic_cornstack_python_v1
function alt_volcano_from_std_out dataframe stats_column_name **kwargs begin set dataframe = copy dataframe at list string Metadata stats_column_name call drop_super_columns set chart = call alt_volcano dataframe keyword kwargs set title = stats_column_name return chart end function
def alt_volcano_from_std_out(dataframe, stats_column_name, **kwargs): dataframe = dataframe[['Metadata', stats_column_name]].copy() dataframe.drop_super_columns() chart = alt_volcano(dataframe, **kwargs) chart.title = stats_column_name return chart
Python
nomic_cornstack_python_v1
comment get data from, and send data to, files (yaml, json, toml), processes comment create output string based on template file and dictionary object import jinja2 import yaml , toml , json import subprocess import getopt import tempfile import os , sys , stat comment description: runs a process and capture all its ou...
# get data from, and send data to, files (yaml, json, toml), processes # create output string based on template file and dictionary object import jinja2 import yaml,toml,json import subprocess import getopt import tempfile import os,sys,stat # description: runs a process and capture all its output, stdin is implicitl...
Python
zaydzuhri_stack_edu_python
string combtools: Extends itertools to provide more combinatorial constructs. Author: Ricardo Bittencourt <ricbit@ricbit.com> import itertools import math import random import unittest function integer_compositions n begin string Compositions of an integer (as an ordered sum of positive integers). Returns an iterator o...
"""combtools: Extends itertools to provide more combinatorial constructs. Author: Ricardo Bittencourt <ricbit@ricbit.com> """ import itertools import math import random import unittest def integer_compositions(n): """Compositions of an integer (as an ordered sum of positive integers). Returns an iterator o...
Python
zaydzuhri_stack_edu_python
function photo self photo_id begin set client = call _get_datastore_client comment Auth check: must be logged in, user profile exists, have comment admin or reviewer role set result = call authn_check headers if is instance result Response begin return result end set userid_hash = call get_userid_hash result if not cal...
def photo(self, photo_id): client = self._get_datastore_client() # Auth check: must be logged in, user profile exists, have # admin or reviewer role result = flask_users.authn_check(flask.request.headers) if isinstance(result, flask.Response): return result u...
Python
nomic_cornstack_python_v1
function m1 begin function fget self begin return _m1 end function function fset self value begin set _m1 = value call _update end function return locals end function
def m1(): def fget(self): return self._m1 def fset(self,value): self._m1 = value self._update() return locals()
Python
nomic_cornstack_python_v1
function _find_reads_per_cell self begin if uniform_over_celltypes begin string then reads for cell i given R_j reads for cell type j is s_{ij} * R_j / (\sum_j s_{ij}) where s_{ij} is number of reads in cell {ij}, and R_j = g_j D comment need to count lines in fastq files comment for (dir, cells) in self.cell_dict.item...
def _find_reads_per_cell(self): if self.uniform_over_celltypes: """ then reads for cell i given R_j reads for cell type j is s_{ij} * R_j / (\sum_j s_{ij}) where s_{ij} is number of reads in cell {ij}, and R_j = g_j D """ # need to count lines in fastq files # for (dir, cells) in self.cel...
Python
nomic_cornstack_python_v1
comment coding: utf-8 string Created on 2020年4月9日 @author: 10226475 考虑使用协程,所以废弃了多进程的日志记录方式 import os import logging import traceback import time from multiprocessing import Process from log.logprocess import _log_listener_process class LogInit begin comment 默认日志存储路径(相对于当前文件路径) set default_log_path = join path directory...
# coding: utf-8 ''' Created on 2020年4月9日 @author: 10226475 考虑使用协程,所以废弃了多进程的日志记录方式 ''' import os import logging import traceback import time from multiprocessing import Process from log.logprocess import _log_listener_process class LogInit: # 默认日志存储路径(相对于当前文件路径) default_log_path = os.path.join(os.path.dirname...
Python
zaydzuhri_stack_edu_python
function test_get_user_recipes self begin set result = call get_user_recipes 1 assert in string Pineapple Fried Rice data end function
def test_get_user_recipes(self): result = self.get_user_recipes(1) self.assertIn("Pineapple Fried Rice", result.data)
Python
nomic_cornstack_python_v1
function test_require_debug_true_filter self begin set filter_ = call RequireDebugTrue with call settings DEBUG=true begin call assertIs filter string record is not used true end with call settings DEBUG=false begin call assertIs filter string record is not used false end end function
def test_require_debug_true_filter(self): filter_ = RequireDebugTrue() with self.settings(DEBUG=True): self.assertIs(filter_.filter("record is not used"), True) with self.settings(DEBUG=False): self.assertIs(filter_.filter("record is not used"), False)
Python
nomic_cornstack_python_v1
from db import DB class Persona extends object begin set dni = none set nombre = none set apellido = none function Insertar self begin run string insert into Persona(dni,nombre,apellido) Values( + string dni + string , ' + nombre + string ', ' + apellido + string '); end function function Borrar self begin run string D...
from db import DB class Persona(object): dni = None nombre = None apellido = None def Insertar(self): DB.run("insert into Persona(dni,nombre,apellido) Values(" + str(self.dni) + ", '" + self.nombre + "', '" + self.apellido + "');") def Borrar(self): DB.run("Delete from Compra whe...
Python
zaydzuhri_stack_edu_python
comment This file will send a json object to vilma import config import socket import json function send_json_to_vilma json_object begin set s = call socket AF_INET SOCK_STREAM call connect tuple vilma_host vilma_port set str_data = encode dumps json_object call sendall encode string length str_data set ret = call recv...
#This file will send a json object to vilma import config import socket import json def send_json_to_vilma(json_object): s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((config.vilma_host,config.vilma_port)) str_data = json.dumps(json_object).encode() s.sendall(str(len(str_data)).en...
Python
zaydzuhri_stack_edu_python
function test_number_users self begin assert equal length users 4 string check the number of users returned end function
def test_number_users(self): self.assertEqual(len(self.users), 4, 'check the number of users returned')
Python
nomic_cornstack_python_v1
function view request begin set this_id = get matchdict string id - 1 set entry = call by_id this_id if not entry begin return call HTTPNotFound end set logged_in = call authenticated_userid request return dict string entry entry ; string logged_in logged_in end function
def view(request): this_id = request.matchdict.get('id', -1) entry = Entry.by_id(this_id) if not entry: return HTTPNotFound() logged_in = authenticated_userid(request) return {'entry': entry, 'logged_in': logged_in}
Python
nomic_cornstack_python_v1
function get_reconstructed_input self hidden begin return sigmoid dot hidden W_prime + b_prime end function
def get_reconstructed_input(self, hidden): return T.nnet.sigmoid(T.dot(hidden, self.W_prime) + self.b_prime)
Python
nomic_cornstack_python_v1
function create_prog_exp pd np file program final_report csv begin set df = read csv file set prog_exp_df = drop loc at df at string ProgramID == program string ProgramID axis=1 rename columns=dict string ProgramQuality string Overall, I am satisfied with the quality of my PA education. ; string AgainPA string If I cou...
def create_prog_exp(pd, np, file, program, final_report, csv): df = pd.read_csv(file) prog_exp_df = df[['ProgramQuality', 'AgainPA', 'AttendAgain', 'RecommendPACareer', 'ProgramID' ]].loc[df['ProgramID'] == program].drop('ProgramI...
Python
zaydzuhri_stack_edu_python
function get_null_value self **kwargs begin set error_map = dict 401 ClientAuthenticationError ; 404 ResourceNotFoundError ; 409 ResourceExistsError ; 304 ResourceNotModifiedError update error_map pop kwargs string error_map dict or dict set _headers = pop kwargs string headers dict or dict set _params = pop kwargs st...
def get_null_value(self, **kwargs: Any) -> Dict[str, str]: error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) ...
Python
nomic_cornstack_python_v1
function __decrypt self begin set key = get key_box string 1.0 string end-1c set key = base64 decode key comment validates key if length key >= 16 begin call __decrypt_files end else if length key == 0 begin print string Insert key end else begin print string key is invalid end end function
def __decrypt(self): key = self.key_box.get("1.0", "end-1c") self.key = b64decode(key) # validates key if len(key) >= 16: self.__decrypt_files() elif len(key) == 0: print ("Insert key") else: print ("key is invalid")
Python
nomic_cornstack_python_v1
import glob set filename = string dataFiles.json try begin with open filename as f begin set root_file = eval read f end end except SyntaxError begin print format string Unable to open the {} file. Terminating... filename end except IOError begin print format string Unable to find the {} file. Terminating... filename e...
import glob filename = 'dataFiles.json' try: with open(filename) as f: root_file = eval(f.read()) except SyntaxError: print('Unable to open the {} file. Terminating...'.format(filename)) except IOError: print('Unable to find the {} file. Terminating...'.format(filename)) def can_get(attr): ret...
Python
zaydzuhri_stack_edu_python
import random comment Generate a random number between 1 and 100 (inclusive) set random_number = random integer 1 100 comment List of numbers to add set numbers = list 3 6 8 12 4 19 23 12 15 10 random_number comment Calculate the sum of all the numbers set total = sum numbers comment Print the sum print string The sum ...
import random # Generate a random number between 1 and 100 (inclusive) random_number = random.randint(1, 100) # List of numbers to add numbers = [3, 6, 8, 12, 4, 19, 23, 12, 15, 10, random_number] # Calculate the sum of all the numbers total = sum(numbers) # Print the sum print("The sum of the numbers is:", total)
Python
jtatman_500k
function longest_common_substring s1 s2 begin set longest_length = 0 set longest_substring = string for i in range min length s1 length s2 begin set substr = s1 at i for j in range i + 1 min length s1 length s2 begin if s2 at j == s1 at i begin set substr = substr + s1 at j end if length substr > longest_length and su...
def longest_common_substring(s1, s2): longest_length = 0 longest_substring = "" for i in range(min(len(s1), len(s2))): substr = s1[i] for j in range(i + 1, min(len(s1), len(s2))): if s2[j] == s1[i]: substr += s1[j] if len(substr) > longest_length an...
Python
iamtarun_python_18k_alpaca
from db import DBSession , FinanceType from sqlalchemy import exc function create_finance_type_record user_id name begin set session = call DBSession try begin set new_finance_type = call FinanceType name=name add session new_finance_type commit session return call serialize end except SQLAlchemyError as e begin print ...
from .db import DBSession, FinanceType from sqlalchemy import exc def create_finance_type_record(user_id, name): session = DBSession() try: new_finance_type = FinanceType(name=name) session.add(new_finance_type) session.commit() return new_finance_type.serialize() except ex...
Python
zaydzuhri_stack_edu_python
function set_lut self lut begin set lut = lut end function
def set_lut(self, lut): self.lut = lut
Python
nomic_cornstack_python_v1
function eval_misclassified self predictions misclassified begin set misclassified_prob = list for i in misclassified begin set classification = test at i at - 1 set classification_prob = prediction_probabilities at i at classification set prediction = predictions at i set prediction_prob = prediction_probabilities at...
def eval_misclassified(self, predictions, misclassified): misclassified_prob = [] for i in misclassified: classification = self.test[i][-1] classification_prob = self.prediction_probabilities[i][classification] prediction = predictions[i] prediction_prob ...
Python
nomic_cornstack_python_v1
string @reroes import math function hacer_potencia valor1 valor2 begin set resultado = power valor1 valor2 return resultado end function
""" @reroes """ import math def hacer_potencia(valor1,valor2): resultado = math.pow(valor1, valor2) return resultado
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- comment Define your item pipelines here comment Don't forget to add your pipeline to the ITEM_PIPELINES setting comment See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import sys append path string /home/tzc/weibo/sinaSpider2/ import pymongo from sinaSpider2.items import Inf...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import sys sys.path.append('/home/tzc/weibo/sinaSpider2/') import pymongo from sinaSpider2.items import InformationItem,Tweets...
Python
zaydzuhri_stack_edu_python
function connect begin comment Exchange authorization code for acceess token and create session set session = call get_session url set client = call UberRidesClient session comment Fetch profile for driver set profile = json comment Fetch last 50 trips and payments for driver set trips = json set payments = json return...
def connect(): # Exchange authorization code for acceess token and create session session = auth_flow.get_session(request.url) client = UberRidesClient(session) # Fetch profile for driver profile = client.get_driver_profile().json # Fetch last 50 trips and payments for driver trips = clie...
Python
nomic_cornstack_python_v1
function distance self begin return call NumericRange_distance self end function
def distance(self): return _ilwisobjects.NumericRange_distance(self)
Python
nomic_cornstack_python_v1
function epc_calc_mod_freq reg_dict mclk demod_clk begin set external_mod = call epc_calc_external_mod reg_dict if external_mod is false begin set f_mod_clk = mclk / reg_dict at string mod_clk_div at 2 + 1 set f_led = f_mod_clk / 4.0 end else begin set f_led = demod_clk / 4.0 end return f_led end function
def epc_calc_mod_freq(reg_dict, mclk, demod_clk): external_mod = epc_calc_external_mod(reg_dict) if external_mod is False: f_mod_clk = (mclk) / (reg_dict["mod_clk_div"][2]+1) f_led = f_mod_clk / 4.0 else: f_led = demod_clk / 4.0 return f_led
Python
nomic_cornstack_python_v1
class GameStats begin comment 跟踪游戏的统计信息 function __init__ self ai_game begin comment 初始化统计信息 set settings = settings call reset_stats set game_active = false set high_score = 0 end function function reset_stats self begin comment 初始化在游戏运行期间可能变化的统计信息 set ship_left = ship_limit set score = 0 set level = 1 end function en...
class GameStats: #跟踪游戏的统计信息 def __init__(self,ai_game): #初始化统计信息 self.settings=ai_game.settings self.reset_stats() self.game_active=False self.high_score=0 def reset_stats(self): #初始化在游戏运行期间可能变化的统计信息 self.ship_left=self.settings.ship_limit sel...
Python
zaydzuhri_stack_edu_python
import pytest import random function test_1 rand_str begin assert rand_str * 3 == rand_str + rand_str + rand_str end function decorator call parametrize string i tuple string + string string string * random integer 1 10 + string string string * 10 + string string function test_2 i begin assert left strip i == string...
import pytest import random def test_1(rand_str): assert rand_str * 3 == rand_str + rand_str + rand_str @pytest.mark.parametrize('i', (' ' + 'string', ' ' * random.randint(1, 10) + 'string', ' ' * 10 + 'string')) def test_2(i): assert i.lstrip() == 'string' def test_3(rand_str): a = rand_str asser...
Python
zaydzuhri_stack_edu_python
import numpy as np from itertools import combinations , chain from tqdm import trange class oBTM begin function __init__ self num_topics V alpha=1.0 beta=0.01 l=0.5 theta_z_path=string phi_wz_path=string begin if theta_z_path != string and phi_wz_path != string begin comment load -> predict set theta_z = load np the...
import numpy as np from itertools import combinations, chain from tqdm import trange class oBTM: def __init__(self, num_topics, V, alpha=1., beta=0.01, l=0.5, theta_z_path="", phi_wz_path=""): if theta_z_path != "" and phi_wz_path != "": # load -> predict self.theta_z = np.load(the...
Python
zaydzuhri_stack_edu_python
function normalize_inv_x self x begin set normalize_x = integer __viewport_size at 0 * x + 1 * 1 / 2 + __viewport_start at 0 return normalize_x end function
def normalize_inv_x(self, x): normalize_x = int(self.__viewport_size[0] * (x + 1) * (1 / 2) + self.__viewport_start[0]) return normalize_x
Python
nomic_cornstack_python_v1
function pc_throughput_avg self begin return call softbittobit_sptr_pc_throughput_avg self end function
def pc_throughput_avg(self): return _ccsds_swig.softbittobit_sptr_pc_throughput_avg(self)
Python
nomic_cornstack_python_v1
comment program to group same type of anagrams together comment logic is to get tuple of all the words in a list in sorted order and comment add it to the list. comment like we get tuple for one of the word : ('e', 'a', 't') comment and then other words will be appended to the same order of comment lists like "ate" wil...
# program to group same type of anagrams together # logic is to get tuple of all the words in a list in sorted order and # add it to the list. # like we get tuple for one of the word : ('e', 'a', 't') # and then other words will be appended to the same order of # lists like "ate" will be also ('e', 'a', 't'). # ------...
Python
zaydzuhri_stack_edu_python
function raise_for_error self begin string raise `ShCmdError` if the proc's return_code is not 0 otherwise return self ..Usage:: >>> proc = shcmd.run("ls").raise_for_error() >>> proc.return_code == 0 True if ok begin return self end set tip = format string running {0} @<{1}> error, return code {2} join string cmd cwd ...
def raise_for_error(self): """ raise `ShCmdError` if the proc's return_code is not 0 otherwise return self ..Usage:: >>> proc = shcmd.run("ls").raise_for_error() >>> proc.return_code == 0 True """ if self.ok: return self ...
Python
jtatman_500k
comment !/usr/bin/env python3 function palindrome word begin if word == word at slice : : - 1 begin return true end else begin return false end end function if __name__ == string __main__ begin for i in range 0 999998 begin if call palindrome call rjust 6 string 0 at slice 2 : : begin if call palindrome call rjust 6...
#!/usr/bin/env python3 def palindrome(word): if word == word[::-1]: return True else: return False if __name__ == '__main__': for i in range(000000, 999998): if palindrome(str(i).rjust(6, '0')[2:]): if palindrome(str(i+1).rjust(6, '0')[1:]): if palindrome(str(i+2).rjust(6, '0')[0:]): print('%06d'...
Python
zaydzuhri_stack_edu_python
string Program name: rotate_rough_head_3d_1.py Objective: Rotate about the y-axis, a list of points representing some features on a crude face. around the X, Y or Z axis. Keywords: canvas, line, rotation, 3 dimension, 3d, face features. ============================================================================79 Comm...
""" Program name: rotate_rough_head_3d_1.py Objective: Rotate about the y-axis, a list of points representing some features on a crude face. around the X, Y or Z axis. Keywords: canvas, line, rotation, 3 dimension, 3d, face features. ============================================================================79 C...
Python
zaydzuhri_stack_edu_python
function format_quad_to_string quad begin set s = string for corner in quad begin set s = s + format string {},{}, corner at 0 corner at 1 end return s at slice : - 1 : end function
def format_quad_to_string(quad): s = '' for corner in quad: s += '{},{},'.format(corner[0], corner[1]) return s[:-1]
Python
nomic_cornstack_python_v1
import os import platform set contents = string if call system == string Windows begin try begin set currentDir = replace directory name path absolute path path __file__ string code\Testing string set f = open currentDir + string \code\Testing\RandText.txt string r set contents = read f end except any begin print stri...
import os import platform contents = "" if platform.system() == "Windows": try: currentDir = os.path.dirname(os.path.abspath(__file__)).replace("code\\Testing", "") f = open(currentDir + "\\code\\Testing\\RandText.txt", "r") contents = f.read() except: print("FAIL") else: t...
Python
zaydzuhri_stack_edu_python
comment GG comment Author: Jobin J Mathew comment All copyrights reserved to the author and DIRS group at Chester F. Carlson Center for Imaging Science (CIS), at Rochester Institute comment Technology (RIT), Rochester, NY. from PIL import Image import numpy as np import sys import cv2 import matplotlib.pyplot as plt fr...
#GG #Author: Jobin J Mathew #All copyrights reserved to the author and DIRS group at Chester F. Carlson Center for Imaging Science (CIS), at Rochester Institute #Technology (RIT), Rochester, NY. from PIL import Image import numpy as np import sys import cv2 import matplotlib.pyplot as plt from scipy.integr...
Python
zaydzuhri_stack_edu_python
function forward_backpropagation self a begin set a = call forward a return a end function
def forward_backpropagation(self, a): a = self.forward(a) return a
Python
nomic_cornstack_python_v1
function __init__ self boxes anchors scales decode_clip reversed_box kernel_name begin set tik_instance = call Tik call Dprofile set boxes_shape = get boxes string shape set boxes_dtype = lower get boxes string dtype set anchors_shape = get anchors string shape set anchors_dtype = lower get anchors string dtype set sca...
def __init__(self, boxes, anchors, scales, decode_clip, reversed_box, kernel_name): self.tik_instance = tik.Tik(tik.Dprofile()) self.boxes_shape = boxes.get("shape") self.boxes_dtype = boxes.get("dtype").lower() self.anchors_shape = anchors.get("shape") self.anch...
Python
nomic_cornstack_python_v1
from random import Random from xmlrpc.server import SimpleXMLRPCServer from Operations import * import xmlrpc.client class Slave extends object begin set MASTER_HOST = none string The host address of the master server set MASTER_PORT = none string The port on the master server set SERVER = none string The server to the...
from random import Random from xmlrpc.server import SimpleXMLRPCServer from .Operations import * import xmlrpc.client class Slave(object): MASTER_HOST = None """ The host address of the master server """ MASTER_PORT = None """ The port on the master server """ SERVER = None """ The server ...
Python
zaydzuhri_stack_edu_python
import sys function read_sys begin return read line stdin end function function solve begin set count = 0 set time = 0 for tuple x y in time_list begin if time <= x begin set time = y set count = count + 1 end end return count end function set n = integer call read_sys set time_list = list comprehension list map int sp...
import sys def read_sys(): return sys.stdin.readline() def solve(): count = 0 time = 0 for x, y in time_list: if time <= x: time = y count += 1 return count n = int(read_sys()) time_list = [list(map(int, read_sys().split())) for _ in range(n)] time_list = sorted(ti...
Python
zaydzuhri_stack_edu_python
function generateCombinedImagesById self hoys=none blindsStateIds=none mode=0 outputs=none begin set hoys = hoys or hoys if not blindsStateIds begin try begin set hoursCount = length hoys end except TypeError begin raise call TypeError format string hoys must be an iterable object: {} hoys end set blindsStateIds = list...
def generateCombinedImagesById(self, hoys=None, blindsStateIds=None, mode=0, outputs=None): hoys = hoys or self.hoys if not blindsStateIds: try: hoursCount = len(hoys) except TypeError: raise TypeError('hoys must ...
Python
nomic_cornstack_python_v1
function create_celery myapp warn=true begin comment pragma: no cover if config at string WITH_CELERY begin from exceptions import BUIserverException set tuple host oport pwd = call get_redis_server myapp set odb = 2 if is instance use_celery basestring begin try begin set tuple _ _ pwd host port db = call parse_db_set...
def create_celery(myapp, warn=True): if myapp.config['WITH_CELERY']: # pragma: no cover from .exceptions import BUIserverException host, oport, pwd = get_redis_server(myapp) odb = 2 if isinstance(myapp.use_celery, basestring): try: (_, _, pwd, host, port,...
Python
nomic_cornstack_python_v1
function has_backup_controller begin set conf = call config return conf at string backup_addr is not none or conf at string backup_controller is not none end function
def has_backup_controller(): conf = config() return conf['backup_addr'] is not None or \ conf['backup_controller'] is not None
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*- coding: utf-8 -*- import curses import time class PB2 begin string progress bar v2 if __name__ == string __main__ begin set stdscr = call initscr call start_color call init_pair 1 COLOR_WHITE COLOR_BLUE call init_pair 2 COLOR_RED COLOR_WHITE call init_pair 3 COLOR_BLUE COLOR_WHITE c...
#!/usr/bin/python # -*- coding: utf-8 -*- import curses import time class PB2: "progress bar v2" if __name__ == "__main__": stdscr=curses.initscr() curses.start_color() curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) curses.init_pair(2, curses.COLOR_RED,curses.COL...
Python
zaydzuhri_stack_edu_python
from urllib.parse import quote , unquote , urlencode , urljoin print url encode dict string a string 发 print quote string 发 print unquote string a=%E5%8F%91 print url join string http://www.baidu.com string s?w=1
from urllib.parse import quote, unquote, urlencode, urljoin print(urlencode({'a':'发'})) print(quote('发')) print(unquote('a=%E5%8F%91')) print(urljoin('http://www.baidu.com', 's?w=1'))
Python
zaydzuhri_stack_edu_python
function get_tcp_stats self begin print string ### get tcp stats ### set tcp_stat = dictionary comment if 'port' in kwargs: comment self.port = kwargs.get('port') set output = call response set out = split output string set out = list comprehension strip right strip i for i in out for line in out begin if length line >...
def get_tcp_stats(self): print("### get tcp stats ###") tcp_stat = dict() #if 'port' in kwargs: # self.port = kwargs.get('port') output = getattr(self.warp17_obj, 'shell')(command="show tcp statistics", pattern="warp17>").response() out = output.split("\n") o...
Python
nomic_cornstack_python_v1
function bubbleSort arr begin set n = length arr comment 7 for i in range n - 1 begin comment 6 comment 5 for j in range 0 4 begin comment 4 comment 4 if arr at j > arr at j + 1 begin set tuple arr at j arr at j + 1 = tuple arr at j + 1 arr at j end end end return arr end function comment n = 7 set arr = list 1 2 3 4 5...
def bubbleSort(arr): n = len(arr) for i in range(n-1): # 7 #6 for j in range(0, 4): #5 #4 if arr[j] > arr[j+1]: #4 arr[j], arr[j+1] = arr[j+1], arr[j] return arr arr = [1, 2, 3, 4, 5, 6, 7] # n = 7 bubbleSort(arr) print (arr) # time ...
Python
zaydzuhri_stack_edu_python
function gifstopngrate self begin try begin return _gifstopngrate end except Exception as e begin raise e end end function
def gifstopngrate(self) : try : return self._gifstopngrate except Exception as e: raise e
Python
nomic_cornstack_python_v1
comment for the really good random generator import secrets comment for exiting out import sys comment converting the number function pc_attack rand_num arr begin return arr at rand_num end function comment true means that you get the point, false is pc function match player pc begin if player == string r begin if pc =...
import secrets #for the really good random generator import sys #for exiting out def pc_attack(rand_num,arr): #converting the number return arr[rand_num] def match(player,pc): #true means that you get the point, false is pc if player == "r": if pc == "p": return False if pc == "s": return True...
Python
zaydzuhri_stack_edu_python
from csv import reader from models.song import Song from models.song_profile import SongProfile from services.config_service import ConfigService import time from services.nrc_service import NRC set ARTIST_COL = 0 set SONG_NAME_COL = 1 set LYRICS_COL = 3 function word_histogram words begin set counts = dictionary for w...
from csv import reader from models.song import Song from models.song_profile import SongProfile from services.config_service import ConfigService import time from services.nrc_service import NRC ARTIST_COL = 0 SONG_NAME_COL = 1 LYRICS_COL = 3 def word_histogram(words): counts = dict() for word in words: ...
Python
zaydzuhri_stack_edu_python
from random import randint , choice comment para randomizar um numero set numero = random integer 0 10 print numero comment para escolher aleatoriamente uma opção set lista = list 6 45 7 12 set numero = random choice lista print numero
from random import randint, choice # para randomizar um numero numero = randint(0, 10) print(numero) # para escolher aleatoriamente uma opção lista = [6,45,7,12] numero = choice(lista) print(numero)
Python
zaydzuhri_stack_edu_python
import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import json import numpy as np import matplotlib.pyplot as plt from numpy.linalg import norm , det import sys comment AQUI ESTAN LOS MODULOS DE NUESTRO PROGRAMA#### comment AQUI EMPIEZA LA INTERACCION JS-PYTHON### class IndexHan...
import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import json import numpy as np import matplotlib.pyplot as plt from numpy.linalg import norm, det import sys ###AQUI ESTAN LOS MODULOS DE NUESTRO PROGRAMA#### ###AQUI EMPIEZA LA INTERACCION JS-PYTHON### class IndexHandl...
Python
zaydzuhri_stack_edu_python
function virtual_server_item_update_command client args begin call validate_virtual_server_group args=args action=value set group_name = get args string group_name set item_id = get args string item_id set response = call virtual_server_item_update_request group_name=group_name item_id=item_id interface=get args string...
def virtual_server_item_update_command( client: Client, args: dict[str, Any] ) -> CommandResults: client.validate_virtual_server_group(args=args, action=CommandAction.UPDATE.value) group_name = args.get("group_name") item_id = args.get("item_id") response = client.virtual_server_item_update_request(...
Python
nomic_cornstack_python_v1
import numpy as np set r = array range 0.1 0.5 0.01 comment print(r) comment print(r[r>0.3]) comment 向量r 的内积 comment print(np.dot(r,r.T)) comment print(np.dot(r.T,r)) comment print(sum(r*r)) comment 数据集 from pandas import DataFrame set df = call DataFrame dict string data1 randn 5 ; string data2 randn 5 set a = apply d...
import numpy as np r = np.arange(0.1,0.5,0.01) # print(r) # print(r[r>0.3]) # 向量r 的内积 # print(np.dot(r,r.T)) # print(np.dot(r.T,r)) # print(sum(r*r)) #数据集 from pandas import DataFrame df = DataFrame( { 'data1':np.random.randn(5), 'data2':np.random.randn(5) } ) a = df.apply(lambda x:min(x)) b = ...
Python
zaydzuhri_stack_edu_python
function closefd self begin return false end function
def closefd(self): return False
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Sep 18 15:46:38 2016 @author: mathias comment -*- coding: utf-8 -*- string Created on Sun Sep 18 14:09:22 2016 @author: mathias Using Bisectional search to discover that the optimial monthly credit card payment should be comment balance = 999999 comment annualInterest...
# -*- coding: utf-8 -*- """ Created on Sun Sep 18 15:46:38 2016 @author: mathias """ # -*- coding: utf-8 -*- """ Created on Sun Sep 18 14:09:22 2016 @author: mathias Using Bisectional search to discover that the optimial monthly credit card payment should be """ #balance = 999999 #annualInterestRate = 0...
Python
zaydzuhri_stack_edu_python
comment Leetcode: https://leetcode.com/problems/task-scheduler/description/ comment Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each int...
# Leetcode: https://leetcode.com/problems/task-scheduler/description/ # Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU ...
Python
zaydzuhri_stack_edu_python
function make_job_details self row_idx begin string Create a `JobDetails` from an `astropy.table.row.Row` set row = _table at row_idx set job_details = call create_from_row row call get_file_paths _file_archive _table_id_array set _cache at fullkey = job_details return job_details end function
def make_job_details(self, row_idx): """Create a `JobDetails` from an `astropy.table.row.Row` """ row = self._table[row_idx] job_details = JobDetails.create_from_row(row) job_details.get_file_paths(self._file_archive, self._table_id_array) self._cache[job_details.fullkey] = job_d...
Python
jtatman_500k
import math import socket import threading from server import server_parser class Server begin function __init__ self port host begin set port = port set host = host set online = true end function function run self begin with call socket AF_INET SOCK_STREAM as s begin call bind tuple host port print string $_$ while on...
import math import socket import threading from server import server_parser class Server: def __init__(self, port, host): self.port = port self.host = host self.online = True def run(self): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind((self.h...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment Run NLTK sentence splitter on input and apply heuristics for comment addressing some frequent issues. import sys import re import nltk.data set ssplitter = load data string tokenizers/punkt/english.pickle comment rarely followed by a sentence split set ns_string = list string a.k.a....
#!/usr/bin/env python # Run NLTK sentence splitter on input and apply heuristics for # addressing some frequent issues. import sys import re import nltk.data ssplitter = nltk.data.load('tokenizers/punkt/english.pickle') # rarely followed by a sentence split ns_string = [ 'a.k.a.', 'approx.', 'ca.', 'cf.', 'e.g....
Python
zaydzuhri_stack_edu_python
import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import numpy as np set calculator_labels = list string abs( string x^3 string <> string x^-1 string OFF string sqrt( string x^2 string NONE string log string ln string sin( string cos( string tan( string ( string ) string 7 st...
import sys from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * import numpy as np calculator_labels = [ 'abs(', 'x^3', '<>', 'x^-1', 'OFF', 'sqrt(', 'x^2', 'NONE', 'log', 'ln', 'sin(', 'cos(', 'tan(', '(', ')', '7', '8',...
Python
zaydzuhri_stack_edu_python
function calculate_total_amount initial_amount rate_of_interest years yearly_deposit max_deposit begin pass end function comment Returns 6314.61 call calculate_total_amount 1000 2 5 100 500 comment Returns 29229.05 call calculate_total_amount 5000 5 10 1000 2000 comment Returns 8653.26 call calculate_total_amount 2000 ...
def calculate_total_amount(initial_amount: float, rate_of_interest: float, years: int, yearly_deposit: float, max_deposit: float) -> float: pass calculate_total_amount(1000, 2, 5, 100, 500) # Returns 6314.61 calculate_total_amount(5000, 5, 10, 1000, 2000) # Returns 29229.05 calculate_total_amount(2000, 1.5, 3, ...
Python
greatdarklord_python_dataset
comment from task.writetopwscf import varnameValue, atomic_positions comment from task.task import Task from qecalc import QECalc import numpy as np from scipy.optimize import brent import scipy function getHexEnergy c *args begin string Total energy launcher for scipy "brent" routine 'args' is a tuple with volume and ...
#from task.writetopwscf import varnameValue, atomic_positions #from task.task import Task from qecalc import QECalc import numpy as np from scipy.optimize import brent import scipy def getHexEnergy(c, *args ): """ Total energy launcher for scipy "brent" routine 'args' is a tuple with volume and task name ...
Python
zaydzuhri_stack_edu_python
import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db , Question , Category class TriviaTestCase extends TestCase begin string This class represents the trivia test case function setUp self begin string Define test variables and initializ...
import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db, Question, Category class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define test variables and initiali...
Python
zaydzuhri_stack_edu_python
comment Link: https://www.hackerrank.com/challenges/encryption/problem import math function rowAndColumn begin set arr = list global m L L_ceil L_floor set m = replace s string string set L = square root length m set L_floor = floor L set L_ceil = ceil L if L_floor == L_ceil begin append arr L_floor append arr L_ceil...
#Link: https://www.hackerrank.com/challenges/encryption/problem import math def rowAndColumn(): arr=[] global m,L,L_ceil,L_floor m = s.replace(" ", "") L=math.sqrt(len(m)) L_floor=math.floor(L) L_ceil=math.ceil(L) if L_floor==L_ceil: arr.append(L_floor) arr.append(L_ceil) ...
Python
zaydzuhri_stack_edu_python
import json import pandas as pd from pymongo import MongoClient function read_csv csv_file begin string :param csv_file: the path of csv file :return: A dataframe out of the csv file return read csv csv_file end function function print_dataframe dataframe print_column=true print_rows=true begin comment print column nam...
import json import pandas as pd from pymongo import MongoClient def read_csv(csv_file): """ :param csv_file: the path of csv file :return: A dataframe out of the csv file """ return pd.read_csv(csv_file) def print_dataframe(dataframe, print_column=True, print_rows=True): # print column names...
Python
zaydzuhri_stack_edu_python
function printf message=string newline=true begin none end function
def printf(message = "", newline = True): None
Python
nomic_cornstack_python_v1
function job_output self job_id begin set url = base_url + format string /ml-service/phoenix-ml/output/findBy?jobId={0} job_id set headers = dict string ApiKey api_key set response = get requests url=url headers=headers return json response end function
def job_output(self, job_id): url = self.base_url + "/ml-service/phoenix-ml/output/findBy?jobId={0}".format(job_id) headers = {"ApiKey": self.api_key} response = requests.get(url=url, headers=headers) return response.json()
Python
nomic_cornstack_python_v1
function can_be_moderated_by user begin return is_active and is_staff and call has_perm string blog.change_membership or call has_perm string blog.change_blog end function
def can_be_moderated_by(user): return user.is_active and user.is_staff and ( user.has_perm('blog.change_membership') or user.has_perm('blog.change_blog'))
Python
nomic_cornstack_python_v1
import time import asyncio import random set start = time function get_time begin return string at %1.1f seconds % time - start end function async function task1 begin comment do something blocking print format string task1 started work: {} call get_time await sleep random integer 1 5 print format string task1 ended wo...
import time import asyncio import random start = time.time() def get_time(): return 'at %1.1f seconds' % (time.time() - start) async def task1(): # do something blocking print('task1 started work: {}'.format(get_time())) await asyncio.sleep(random.randint(1, 5)) print('task1 ended work: {}'.for...
Python
zaydzuhri_stack_edu_python
function configure_logging config begin call basicConfig level=call getLevelName level format=format if subtask_debug begin call setLevel DEBUG call setLevel DEBUG call setLevel DEBUG end if asyncio_debug begin call setLevel DEBUG end end function
def configure_logging(config): logging.basicConfig(level=logging.getLevelName(config.logging.level), format=config.logging.format) if config.subtask_debug: logging.getLogger('mercury.rpc.ping').setLevel(logging.DEBUG) logging.getLogger('mercury.rpc.ping2').setLevel(loggi...
Python
nomic_cornstack_python_v1
function run self begin comment TODO: break up the _retrieve_flattened_violations method. comment Retrieving resource violations. set all_violations = call _retrieve_flattened_violations comment Retrieving iam violations. extend all_violations call _retrieve_flattened_violations iam_policy=true comment Output all viola...
def run(self): # TODO: break up the _retrieve_flattened_violations method. # Retrieving resource violations. all_violations = self._retrieve_flattened_violations() # Retrieving iam violations. all_violations.extend( self._retrieve_flattened_violations(iam_policy=True...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 comment # Issues with the normal equations comment In[1]: import numpy as np import numpy.linalg as la comment Here's an example matrix to use with the normal equations: comment In[4]: comment set to 1e-5, 1e-10 set eps = 1e-10 set A = array list list 1 1 list eps 0 li...
#!/usr/bin/env python # coding: utf-8 # # Issues with the normal equations # In[1]: import numpy as np import numpy.linalg as la # Here's an example matrix to use with the normal equations: # In[4]: eps = 1e-10 # set to 1e-5, 1e-10 A = np.array([ [1, 1], [eps, 0], [0, eps], ])...
Python
zaydzuhri_stack_edu_python
comment Inteira comment Real (ponto flutuante) comment Caracter comment Strings são cadeias de caracter - exemplo: casa comment estou voltando a fazer logica de programacao tenho de aprender tudo diretinho set letra = string a set palavra = string amor set inteira = 7 set outraInteira = 9 set soma = inteira + outrainte...
#Inteira #Real (ponto flutuante) #Caracter #Strings são cadeias de caracter - exemplo: casa #estou voltando a fazer logica de programacao tenho de aprender tudo diretinho letra ='a' palavra="amor" inteira = 7 outraInteira = 9 soma = inteira +outrainteira print(inteira)
Python
zaydzuhri_stack_edu_python
function _loss dz gamma=0.15 begin return 1 - 1 / 1 + dz / gamma ^ 2 end function
def _loss(dz, gamma=0.15): return 1-1/(1+(dz/gamma)**2)
Python
nomic_cornstack_python_v1
import json import sys comment TODO Abstract this into a base formatter class
import json import sys # TODO Abstract this into a base formatter class
Python
zaydzuhri_stack_edu_python
function put self id=0 begin set json = call get_json if not json begin return call make_response call jsonify dict string message string No input 400 end if id == 0 begin return call make_response call jsonify dict string message string ID is missing or wrong 400 end try begin comment Find the item first set item = ca...
def put(self, id=0): json = request.get_json() if not json: return make_response(jsonify({'message': 'No input'}), 400) if id == 0: return make_response( jsonify({'message': 'ID is missing or wrong'}), 400) try: # Fin...
Python
nomic_cornstack_python_v1
function nav_tree context request root_depth klass begin comment get the root accoding to root_depth if is instance context Folder begin set parents = list context end else begin set parents = list end set current = __parent__ while __parent__ begin insert parents 0 current set current = __parent__ end comment 超界 if l...
def nav_tree(context, request, root_depth, klass): # get the root accoding to root_depth if isinstance(context, Folder): parents = [context] else: parents = [] current = context.__parent__ while current.__parent__: parents.insert(0, current) current = current...
Python
nomic_cornstack_python_v1
function declare_sample_delay self *args begin return call add_cp_underlay_sptr_declare_sample_delay self *args end function
def declare_sample_delay(self, *args): return _ncofdm_swig.add_cp_underlay_sptr_declare_sample_delay(self, *args)
Python
nomic_cornstack_python_v1
function mint amount begin global total_supply call _assert_is_emitter sender set total_supply = call mint balance_of total_supply sender amount return total_supply end function
def mint(amount: int) -> int: global total_supply _assert_is_emitter(context.sender) total_supply = base.mint(balance_of, total_supply, context.sender, amount) return total_supply
Python
nomic_cornstack_python_v1
from enum import Enum from typing import List import sys class Pos begin function __init__ self y x begin set y = y set x = x end function end class class Response extends Enum begin set NOT_BROKEN = 0 set BROKEN = 1 set FINISH = 2 set INVALID = - 1 end class class Field begin function __init__ self N C begin set C = C...
from enum import Enum from typing import List import sys class Pos: def __init__(self, y: int, x: int): self.y = y self.x = x class Response(Enum): NOT_BROKEN = 0 BROKEN = 1 FINISH = 2 INVALID = -1 class Field: def __init__(self, N: int, C: int): self.C = C ...
Python
zaydzuhri_stack_edu_python
function test_fma_array_num_num_array_a2 self begin comment This version is expected to pass. call fma arrayx numy numz arrayout matherrors=true comment This is the actual test. with assert raises TypeError begin call fma arrayx numy numz arrayout matherrors=string a end end function
def test_fma_array_num_num_array_a2(self): # This version is expected to pass. arrayfunc.fma(self.arrayx, self.numy, self.numz, self.arrayout, matherrors=True) # This is the actual test. with self.assertRaises(TypeError): arrayfunc.fma(self.arrayx, self.numy, self.numz, self.arrayout, matherrors='a')
Python
nomic_cornstack_python_v1
for i in range 5 begin set time = integer input if time % 10 > 0 begin set diff = min diff time % 10 end set total = total + integer time + 9 / 10 * 10 end if diff == 1000 begin print total end else begin print total - 10 + diff end
for i in range(5) : time = int(input()) if time % 10 > 0 : diff = min(diff,time % 10) total += int((time + 9) / 10) * 10 if diff == 1000 : print(total) else : print(total - 10 + diff)
Python
zaydzuhri_stack_edu_python
function spline_plot spline *args **kwargs begin set xmin = pop kwargs string xmin call GetXmin set xmax = pop kwargs string xmax call GetXmax set n = pop kwargs string n call GetNp set x = linear space xmin xmax n set fcn = call frompyfunc Eval 1 1 set y = call fcn x return plot x y *args keyword kwargs end function
def spline_plot( spline, *args, **kwargs ): xmin = kwargs.pop( 'xmin', spline.GetXmin() ) xmax = kwargs.pop( 'xmax', spline.GetXmax() ) n = kwargs.pop( 'n', spline.GetNp() ) x = N.linspace( xmin, xmax, n ) fcn = N.frompyfunc( spline.Eval, 1, 1 ) y = fcn( x ) return P.plot( x, y, *args, ...
Python
nomic_cornstack_python_v1
function write self value begin if direction != OUTPUT begin mode OUTPUT end set direction = OUTPUT call uper_io 0 call encode_sfp 4 list logical_pin value end function
def write(self, value): if self.direction != self.OUTPUT: self.mode(self.OUTPUT) self.direction = self.OUTPUT self.board.uper_io(0, self.board.encode_sfp(4, [self.logical_pin, value]))
Python
nomic_cornstack_python_v1
import numpy as np import random import os from PIL import Image from sklearn.cross_validation import train_test_split import pickle function get_files_path shuffle=true seed=none begin if seed begin seed seed end set root_path = string input/my_train/ set files_path = list comprehension root_path + i for i in list dir...
import numpy as np import random import os from PIL import Image from sklearn.cross_validation import train_test_split import pickle def get_files_path(shuffle=True, seed=None): if seed: random.seed(seed) root_path = 'input/my_train/' files_path = [root_path + i for i in os.listdir(root_path)] ...
Python
zaydzuhri_stack_edu_python
function valid_pass_count path begin set res = 0 with open path as f begin for line in f begin set tuple edges letter word = split line string set tuple low high = map int split edges string - set n = count word strip letter string : if n >= low and n <= high begin set res = res + 1 end end end return res end function ...
def valid_pass_count(path): res = 0 with open(path) as f: for line in f: edges, letter, word = line.split(' ') low, high = map(int, edges.split('-')) n = word.count(letter.strip(':')) if n >= low and n <= high: res += 1 return res de...
Python
zaydzuhri_stack_edu_python
function get_beta self begin return value + continuous_param_space_limit end function
def get_beta(self): return self.beta_shifted.value + self.continuous_param_space_limit
Python
nomic_cornstack_python_v1
from flask import Flask , render_template , request , redirect set app = call Flask __name__ decorator call route string / function index begin return call render_template string index.html end function decorator call route string /checkout methods=list string POST function checkout begin print form set form = form set...
from flask import Flask, render_template, request, redirect app = Flask(__name__) @app.route('/') def index(): return render_template("index.html") @app.route('/checkout', methods=['POST']) def checkout(): print(request.form) form = request.form strawberry_entered = form['strawber...
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 set letra = integer input string Dime una letra
# coding: utf-8 letra = int(input("Dime una letra"))
Python
zaydzuhri_stack_edu_python
function critical self msg *args **kwargs begin set tuple msg args kwargs = process msg args kwargs critical msg *args keyword kwargs end function
def critical(self, msg, *args, **kwargs): msg, args, kwargs = self.process(msg, args, kwargs) self.logger.critical(msg, *args, **kwargs)
Python
nomic_cornstack_python_v1
function done self begin return __done * multiplier end function
def done(self): return self.__done * self.multiplier
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment *-* coding: utf-8 *-* import time , threading from threading import Thread , Semaphore set semaphore = semaphore 2
#!/usr/bin/env python # *-* coding: utf-8 *-* import time, threading from threading import Thread, Semaphore semaphore = Semaphore(2)
Python
zaydzuhri_stack_edu_python