code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function lambda_handler event context
begin
comment gets (group, search query list) tuple for 1 search group from the SQS queue
set search_group = call download_from_queue event context
set tuple api_key api_secret access_token access_token_secret = call get_secret
comment ----------------------- REMOVE RETURN---------... | def lambda_handler(event, context):
# gets (group, search query list) tuple for 1 search group from the SQS queue
search_group = download_from_queue(event, context)
api_key, api_secret, access_token, access_token_secret = get_secret()
# ----------------------- REMOVE RETURN--------------------
api ... | Python | nomic_cornstack_python_v1 |
from sklearn.feature_extraction.text import CountVectorizer
import pickle
with open string /Users/eunseo/Desktop/countries/cat_tokens_countries2_2.txt string r as f
begin
set my_doc = read f
end
set documents = list my_doc
set new_regex = string (?u)\b\w+\b
comment initialize your count vectorizer
set example_vectorize... | from sklearn.feature_extraction.text import CountVectorizer
import pickle
with open("/Users/eunseo/Desktop/countries/cat_tokens_countries2_2.txt", "r") as f:
my_doc = f.read()
documents = [my_doc]
new_regex = r"(?u)\b\w+\b"
example_vectorizer = CountVectorizer(token_pattern=new_regex) #initialize your count vectoriz... | Python | zaydzuhri_stack_edu_python |
for i in range 0 length a - 1
begin
if a at i at 1 > a at i + 1 at 0
begin
set count = count + 1
end
else
begin
pass
end
end
print count | for i in range(0,len(a)-1):
if a[i][1]>a[i+1][0]:
count+=1
else:
pass
print(count) | Python | zaydzuhri_stack_edu_python |
function _exec_commands
begin
set timeout = 2.5
set cooldown = 3600
set exe = string rclone
set opt = string --verbose
set copy = string copy
set sync = string sync
comment Wait for get_stats()'s initial checks
sleep timeout
while alive
begin
set copy_num = 0
set sync_num = 0
if copy_status and copy_src_dst
begin
set s... | def _exec_commands():
timeout = 2.5
cooldown = 3600
exe = 'rclone'
opt = '--verbose'
copy = 'copy'
sync = 'sync'
time.sleep(timeout) # Wait for get_stats()'s initial checks
while alive:
copy_num = 0
sync_num = 0
if copy_status and copy_src_dst:
srcs... | Python | nomic_cornstack_python_v1 |
import re
import os
import csv
import sys
comment Constants
set NUM_ENTRIES = 11
set NUM_PUBLICATIONS_INDEX = 5
comment Functions
function addPublicationsToIndex templateNewPaper pubslistPath
begin
comment Open template files
set templateNewPaperRaw = read open templateNewPaper string r
comment Parse publications
set r... | import re
import os
import csv
import sys
## Constants
NUM_ENTRIES = 11
NUM_PUBLICATIONS_INDEX = 5
## Functions
def addPublicationsToIndex(templateNewPaper, pubslistPath):
# Open template files
templateNewPaperRaw = open(templateNewPaper, 'r').read()
# Parse publications
rows = csv.reader(open(pubs... | Python | zaydzuhri_stack_edu_python |
for i in range t
begin
set n = integer input
set names = list comprehension input for _ in range n
set nameCount = dict
set maxCount = 0
for name in names
begin
set count = set name
discard count string
set nameCount at name = length count
if nameCount at name > maxCount
begin
set maxCount = nameCount at name
end
end
... | for i in range(t):
n = int(input())
names = [input() for _ in range(n)]
nameCount = {}
maxCount = 0
for name in names:
count = set(name)
count.discard(" ")
nameCount[name] = len(count)
if nameCount[name] > maxCount:
maxCount = nameCount[name]
... | Python | zaydzuhri_stack_edu_python |
import click
from database import Base
from sqlalchemy import create_engine
decorator call group
decorator call option string --host string -h default=string localhost help=string PostgreSQL host.
decorator call option string --port string -p type=int default=5432 help=string PostgreSQL port.
decorator call option stri... | import click
from ..database import Base
from sqlalchemy import create_engine
@click.group()
@click.option('--host', '-h', default="localhost", help="PostgreSQL host.")
@click.option('--port', '-p', type=int, default=5432, help="PostgreSQL port.")
@click.option('--user', '-u', required=True, help="PostgreSQL user.")
... | Python | zaydzuhri_stack_edu_python |
function tf_idf_score
begin
global final_doc_set
global final_dictionary
set final_score = list
for doc_id in final_doc_set
begin
set score = 0
for query_term in keys final_dictionary
begin
if get final_dictionary at query_term at 1 doc_id
begin
set tf = final_dictionary at query_term at 1 at doc_id at 0
set df = fina... | def tf_idf_score():
global final_doc_set
global final_dictionary
final_score = []
for doc_id in final_doc_set:
score = 0
for query_term in final_dictionary.keys():
if final_dictionary[query_term][1].get(doc_id):
tf = final_dictionary[query_term][1][doc_id][0... | Python | nomic_cornstack_python_v1 |
function __iter__ self
begin
for item in array
begin
if item is none
begin
yield none
end
else
begin
yield value
end
end
end function | def __iter__(self):
for item in self.array:
if item is None:
yield None
else:
yield item.value | Python | nomic_cornstack_python_v1 |
function showcase_archived cls val
begin
return call cls string showcase_archived val
end function | def showcase_archived(cls, val):
return cls('showcase_archived', val) | Python | nomic_cornstack_python_v1 |
string Walker program to draw a path that moves in random directions
import random
import pyglet
from pyglet.shapes import Rectangle
set window = call Window 1080 768
set main_batch = call Batch
set x = width // 2
set y = height // 2
function update dt
begin
global x y
set r = call randrange 4
if r == 0
begin
set x = x... | '''
Walker program to draw a path that moves in random directions
'''
import random
import pyglet
from pyglet.shapes import Rectangle
window = pyglet.window.Window(1080, 768)
main_batch = pyglet.graphics.Batch()
x = window.width // 2
y = window.height // 2
def update(dt):
global x, y
r = random.randrang... | Python | zaydzuhri_stack_edu_python |
if __name__ == string __main__
begin
set list = list 1 5 7 2 6 4 3 8 9
sort list reverse=true
print list
set char = list string cat string Tom string Angelga
sort char
print char
sort char key=lower reverse=true
print char
set char2 = sorted char key=lower
print char2
end | if __name__ == '__main__':
list = [1, 5, 7, 2, 6, 4, 3, 8, 9]
list.sort(reverse=True)
print(list)
char = ['cat','Tom','Angelga']
char.sort()
print(char)
char.sort(key=str.lower, reverse=True)
print(char)
char2 = sorted(char, key=str.lower)
print(char2) | Python | zaydzuhri_stack_edu_python |
function clean_text_lines textcontent
begin
set lines = map lambda x -> strip x call splitlines
set lines = filter lambda x -> x and not starts with x string # and not starts with x string -- lines
return lines
end function | def clean_text_lines(textcontent):
lines = map(lambda x: x.strip(), textcontent.splitlines())
lines = filter(lambda x: x and not x.startswith('#') and not x.startswith('--'), lines)
return lines | Python | nomic_cornstack_python_v1 |
set f = open string D:/python assingment2/Q-1.txt string a
set a = input string Enter the text you want to append:
write f a
close f
set f = open string D:/python assingment2/Q-1.txt string r
print read f
close f | f=open('D:/python assingment2/Q-1.txt', 'a')
a=input('Enter the text you want to append: ')
f.write(a)
f.close()
f=open('D:/python assingment2/Q-1.txt', 'r')
print(f.read())
f.close() | Python | zaydzuhri_stack_edu_python |
import re
set sentence = string The students are very concentrated
comment Extract the subject and verb using regular expressions
set match = match string ^(.*?)\b(are|is|was|were|am)\b(.*)$ sentence
set subject = call group 1
set verb = call group 2
set rest_of_sentence = call group 3
comment Construct the interrogati... | import re
sentence = "The students are very concentrated"
# Extract the subject and verb using regular expressions
match = re.match(r"^(.*?)\b(are|is|was|were|am)\b(.*)$", sentence)
subject = match.group(1)
verb = match.group(2)
rest_of_sentence = match.group(3)
# Construct the interrogative form
if verb == "am":
i... | Python | jtatman_500k |
comment transform from recipe to greek
from parse import wrapper , remove_punc_lower , food , direction , make_recipe_obj
import string
from collections import deque
from get_key_ingredient import get_key , get_key_food
function lookup ing lst
begin
set name_lst = split call translate call maketrans string string pun... | # transform from recipe to greek
from parse import wrapper, remove_punc_lower, food, direction, make_recipe_obj
import string
from collections import deque
from get_key_ingredient import get_key, get_key_food
def lookup(ing, lst):
name_lst = ing.name.lower().translate(str.maketrans('', '', string.punctuation)).sp... | Python | zaydzuhri_stack_edu_python |
function read_one self url headers
begin
update headers headers
set response = get requests url headers=headers
call raise_for_status
return text
end function | def read_one(self, url, headers):
headers.update(self.headers)
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.text | Python | nomic_cornstack_python_v1 |
set my_2d_array = list list 1 2 3 list 4 5 6 list 7 8 9
set row_to_retrieve = 2
set column_to_retrieve = 0
set retrieved_element = my_2d_array at row_to_retrieve at column_to_retrieve | my_2d_array = [[1,2,3],[4,5,6],[7,8,9]]
row_to_retrieve = 2
column_to_retrieve = 0
retrieved_element = my_2d_array[row_to_retrieve][column_to_retrieve] | Python | iamtarun_python_18k_alpaca |
function get_public_repos login
begin
set response = get requests string https://api.github.com/orgs/ { login } /repos
set public_repos = json response
return length public_repos
end function | def get_public_repos(login):
response = requests.get(
f'https://api.github.com/orgs/{login}/repos')
public_repos = response.json()
return len(public_repos) | Python | nomic_cornstack_python_v1 |
function use_system_trust_store self
begin
return get pulumi self string use_system_trust_store
end function | def use_system_trust_store(self) -> Optional[Any]:
return pulumi.get(self, "use_system_trust_store") | Python | nomic_cornstack_python_v1 |
function create_markdown comment mode repo_context
begin
comment Added a try-except to account for '400: Bad Reqeust' when incorrect POST is made
try
begin
set comment_data = dict string text string %s % comment ; string mode string %s % mode ; string context string %s % repo_context
set req = call Request BASE_URL + s... | def create_markdown(comment, mode, repo_context):
#Added a try-except to account for '400: Bad Reqeust' when incorrect POST is made
try:
comment_data = {
"text": "%s" % comment,
"mode": "%s" % mode,
"context": "%s" % repo_context
}
req = urllib2.Request(BASE_URL+"/markdown")
req.add_header('Conten... | Python | nomic_cornstack_python_v1 |
function test_send_sms_fail self
begin
set failure_published = call FailureCounter 1
yield call mk_mock_server string Result_code: 04, Internal system error occurred while processing message dict
set msg = call make_outbound string outbound
yield call dispatch_outbound msg
yield deferred
yield call kick_delivery
assert... | def test_send_sms_fail(self):
self.worker.failure_published = FailureCounter(1)
yield self.mk_mock_server("Result_code: 04, Internal system error "
"occurred while processing message",
{})
msg = self.make_outbound("... | Python | nomic_cornstack_python_v1 |
function CreateBank
begin
set page_num = get args string page 1 type=int
set form = call BankForm
set banks = paginate query per_page=5 page=page_num
set table = dict
for bank in items
begin
set manager = first filter by query id=manager_id
update table dict location dict string id id ; string location location ; stri... | def CreateBank():
page_num = request.args.get('page', 1, type=int)
form = BankForm()
banks = Bank.query.paginate(per_page=5, page=page_num)
table = {}
for bank in banks.items:
manager = Staff.query.filter_by(id=bank.manager_id).first()
table.update({bank.location: {
"id":... | Python | nomic_cornstack_python_v1 |
import numpy as np
comment Define the automata
set cell_size = 10
set auto = zeros cell_size
comment Create the display | import numpy as np
# Define the automata
cell_size = 10
auto = np.zeros(cell_size)
# Create the display | Python | iamtarun_python_18k_alpaca |
comment Libraries to extract music data
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials , SpotifyOAuth
comment Libraries to deal with special data types and automatization process
import time
from IPython.core.display import clear_output
from collections import defaultdict
comment Libraries to deal w... | #Libraries to extract music data
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials, SpotifyOAuth
#Libraries to deal with special data types and automatization process
import time
from IPython.core.display import clear_output
from collections import defaultdict
#Libraries to deal with text from wikipe... | Python | zaydzuhri_stack_edu_python |
import mysql.connector
import csv
import time
comment connection
class DBConnection
begin
function __init__ self DB_HOST DB_USER DB_PASSWORD DB_NAME
begin
set host = DB_HOST
set database = DB_NAME
set user = DB_USER
set password = DB_PASSWORD
set conn = none
end function
function get_conn self
begin
if conn is none
beg... | import mysql.connector
import csv
import time
# connection
class DBConnection:
def __init__(self, DB_HOST, DB_USER, DB_PASSWORD, DB_NAME):
self.host = DB_HOST
self.database = DB_NAME
self.user = DB_USER
self.password = DB_PASSWORD
self.conn = None
def get_conn(self):
... | Python | zaydzuhri_stack_edu_python |
string Created on 2014-4-19 @author: ezonghu
set slot = dict string . 0 ; string R 1 ; string B 2
set rslot = list string . string R string B
function clockwise90 board
begin
function r l
begin
reverse l
return l
end function
return list comprehension call r list l for l in zip *board
end function
function anticlockwis... | '''
Created on 2014-4-19
@author: ezonghu
'''
slot={".":0, "R":1, "B":2}
rslot=[".", "R", "B"]
def clockwise90(board):
def r(l):
l.reverse()
return l
return [r(list(l)) for l in zip(*board)]
def anticlockwise90(board):
newboard = [list(l) for l in zip(*board)]
newboard.reverse()
re... | Python | zaydzuhri_stack_edu_python |
string Created on Apr 5, 2014 @author: c3h3
import numpy as np
import inspect
function check_args checker *args
begin
assert callable checker
set args_len = length args
return sum == args_len
end function
function class_checker xx
begin
return call isclass xx
end function
function check_type_of_args valid_type *args
be... | '''
Created on Apr 5, 2014
@author: c3h3
'''
import numpy as np
import inspect
def check_args(checker, *args):
assert callable(checker)
args_len = len(args)
return np.ones(args_len,dtype=np.int)[np.array(map(checker,args))].sum() == args_len
def class_checker(xx):
return inspect.isclass(xx... | Python | zaydzuhri_stack_edu_python |
function fit_Gaussian x y region_start region_stop mu_guess A_guess=0 sigma_guess=1
begin
comment these define a region of interest in our data binning:
set region = region_start < x ? x < region_stop
comment now limit our data by 'slicing' it, limiting it to the region of interest:
set peak_region_bc = x at region
set... | def fit_Gaussian(x, y, region_start, region_stop, mu_guess, A_guess=0, sigma_guess=1):
# these define a region of interest in our data binning:
region = (region_start < x) & (x < region_stop)
# now limit our data by 'slicing' it, limiting it to the region of interest:
peak_region_bc = x[region]
... | Python | nomic_cornstack_python_v1 |
function peek self
begin
if head is none
begin
return head
end
return value
end function | def peek(self):
if self._dblinkedlist.head is None:
return self._dblinkedlist.head
return self._dblinkedlist.tail.value | Python | nomic_cornstack_python_v1 |
function get_position_distribution self game_state
begin
set opponent_position = call get_agent_position index
set legal_actions = call get_legal_actions index
set dist = counter
comment consider all actions equally probable
for action in legal_actions
begin
set successor_position = call get_successor opponent_position... | def get_position_distribution(self, game_state):
opponent_position = game_state.get_agent_position(self.index)
legal_actions = game_state.get_legal_actions(self.index)
dist = util.Counter()
# consider all actions equally probable
for action in legal_actions:
... | Python | nomic_cornstack_python_v1 |
set name = input string What is your name? :
set age = input string What is your age? :
set color = input string What is your favorite color? :
print name
print age
print color | name=input('What is your name? : ' )
age=input('What is your age? : ')
color=input('What is your favorite color? : ')
print(name)
print(age)
print(color)
| Python | zaydzuhri_stack_edu_python |
import pickle
import copy
from TarockBasics import TarockBasics
from GameStateTarock import GameStateTarock
from MilestoneAgents import MilestoneAgents
from probamo import index
import matplotlib.pyplot as plt
from os import listdir
from os.path import isfile , join
set gst = call GameStateTarock list list list list... | import pickle
import copy
from TarockBasics import TarockBasics
from GameStateTarock import GameStateTarock
from MilestoneAgents import MilestoneAgents
from probamo import index
import matplotlib.pyplot as plt
from os import listdir
from os.path import isfile, join
gst = GameStateTarock([], [], [], [1,2,3], 1, [2... | Python | zaydzuhri_stack_edu_python |
function draw_app self
begin
call setBg string #FFFFFF
comment app.setTransparency(0.8)
call setSize 800 350
call setResizable canResize=false
call setLocation string CENTER
call setFont size=11
comment self.app.setButtonFont(size=12, family="Verdana")
call setStretch string both
comment Frame 0
call startTabbedFrame s... | def draw_app(self):
self.app.setBg('#FFFFFF')
# app.setTransparency(0.8)
self.app.setSize(800, 350)
self.app.setResizable(canResize=False)
self.app.setLocation("CENTER")
self.app.setFont(size=11)
# self.app.setButtonFont(size=12, family="Verdana")
self.app... | Python | nomic_cornstack_python_v1 |
comment Rock-paper-scissors-lizard-Spock game simulation
import math
import random
import simplegui
comment helper functions
function number_to_name number
begin
return dict 0 string rock ; 1 string Spock ; 2 string paper ; 3 string lizard ; 4 string scissors at number
end function
function name_to_number name
begin
if... | # Rock-paper-scissors-lizard-Spock game simulation
import math
import random
import simplegui
# helper functions
def number_to_name(number):
return {
0:'rock',
1:'Spock',
2:'paper',
3:'lizard',
4:'scissors'
}[number]
def name_to_number(name):... | Python | zaydzuhri_stack_edu_python |
function test_text_indexes self
begin
from models import IndexedArticle
set index_sql = list comprehension string statement for statement in call _model_indexes_sql IndexedArticle
assert equal length index_sql 5
assert in string ("headline" varchar_pattern_ops) index_sql at 1
assert in string ("body" text_pattern_ops) ... | def test_text_indexes(self):
from .models import IndexedArticle
index_sql = [str(statement) for statement in connection.schema_editor()._model_indexes_sql(IndexedArticle)]
self.assertEqual(len(index_sql), 5)
self.assertIn('("headline" varchar_pattern_ops)', index_sql[1])
self.ass... | Python | nomic_cornstack_python_v1 |
function _get_task_id_from_xmodule_args xmodule_instance_args
begin
return if expression xmodule_instance_args is not none then get xmodule_instance_args string task_id UNKNOWN_TASK_ID else UNKNOWN_TASK_ID
end function | def _get_task_id_from_xmodule_args(xmodule_instance_args):
return xmodule_instance_args.get('task_id', UNKNOWN_TASK_ID) if xmodule_instance_args is not None else UNKNOWN_TASK_ID | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string Write a function that queries the Reddit API and returns the number of subscribers (not active users, total subscribers) for a given subreddit. If an invalid subreddit is given, the function should return 0.
import requests
function number_of_subscribers subreddit
begin
if type subreddi... | #!/usr/bin/python3
"""
Write a function that queries the Reddit API and returns the number of
subscribers (not active users, total subscribers) for a given subreddit. If an
invalid subreddit is given, the function should return 0.
"""
import requests
def number_of_subscribers(subreddit):
if type(subreddit) is not... | Python | zaydzuhri_stack_edu_python |
function generate_dag self graph=none
begin
if graph
begin
for child in _contents
begin
add nodes child
add edges at self child
if is instance child Key
begin
if lock
begin
add edges at child lock
end
end
comment recursive call
call generate_dag graph
end
for part_of_obj in part_of
begin
add nodes part_of_obj
add edges... | def generate_dag(self, graph=None):
if graph:
for child in self._contents:
graph.nodes.add(child)
graph.edges[self].add(child)
if isinstance(child, Key):
if child.lock:
graph.edges[child].add(child.lock)
... | Python | nomic_cornstack_python_v1 |
comment @lc app=leetcode.cn id=53 lang=python3
comment [53] 最大子序和
comment https://leetcode-cn.com/problems/maximum-subarray/description/
comment algorithms
comment Easy (44.92%)
comment Total Accepted: 58.6K
comment Total Submissions: 129.9K
comment Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
comment 给定一个整数数组 nums ,找到一... | #
# @lc app=leetcode.cn id=53 lang=python3
#
# [53] 最大子序和
#
# https://leetcode-cn.com/problems/maximum-subarray/description/
#
# algorithms
# Easy (44.92%)
# Total Accepted: 58.6K
# Total Submissions: 129.9K
# Testcase Example: '[-2,1,-3,4,-1,2,1,-5,4]'
#
# 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
#
# 示... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
set train = read csv string train1.csv index_col=none na_values=list string NA
set test = read csv string test1.csv index_col=none na_values=list string NA
comment X = train[['Pclass', 'Sex_0', 'Sex_1', 'Age', 'SibSp', 'Parch', 'Fare', 'FamilySize', 'Name_0', 'Name_1', 'Name_2', '... | import pandas as pd
import numpy as np
train = pd.read_csv('train1.csv', index_col=None, na_values=['NA'])
test = pd.read_csv('test1.csv', index_col=None, na_values=['NA'])
# X = train[['Pclass', 'Sex_0', 'Sex_1', 'Age', 'SibSp', 'Parch', 'Fare', 'FamilySize', 'Name_0', 'Name_1', 'Name_2', 'Name_3', 'Name_4', 'Embark... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from matplotlib import pyplot as plt
import utils
from network import Network
set SMALL_SIZE = 20
set MEDIUM_SIZE = 25
set BIGGER_SIZE = 30
comment controls default text sizes
call rc string font size=SMALL_SIZE
comment fontsize of the axes title
call rc string axes titlesize=MEDIUM_SIZE
comment font... | import numpy as np
from matplotlib import pyplot as plt
import utils
from network import Network
SMALL_SIZE = 20
MEDIUM_SIZE = 25
BIGGER_SIZE = 30
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=MED... | Python | zaydzuhri_stack_edu_python |
function print_progress_bar text done total width
begin
string Print progress bar.
if total > 0
begin
set n = integer decimal width * decimal done / decimal total
write stdout format string {0} [{1}{2}] ({3}/{4}) text string # * n string * width - n done total
flush stdout
end
end function | def print_progress_bar(text, done, total, width):
"""
Print progress bar.
"""
if total > 0:
n = int(float(width) * float(done) / float(total))
sys.stdout.write("\r{0} [{1}{2}] ({3}/{4})".format(text, '#' * n, ' ' * (width - n), done, total))
sys.stdout.flush() | Python | jtatman_500k |
comment include "stdio.h"
comment define PI 3.1445926 | #include "stdio.h"
#define PI 3.1445926
| Python | zaydzuhri_stack_edu_python |
function storage_handler_conf_from_env handler_name
begin
if handler_name not in keys STORAGE_CONFIG_MAP
begin
raise call ValueError string { handler_name } is not a valid storage handler name. Valid options are { join string , list keys STORAGE_CONFIG_MAP }
end
set config_vals = dict
for tuple key value in items envi... | def storage_handler_conf_from_env(handler_name: str) -> StorageConfig:
if handler_name not in STORAGE_CONFIG_MAP.keys():
raise ValueError(
f'{handler_name} is not a valid storage handler name. Valid options are {", ".join(list(STORAGE_CONFIG_MAP.keys()))}')
config_vals = {}
for key, va... | Python | nomic_cornstack_python_v1 |
import sys
function check lat n
begin
set gold = lat at 0 at 0
for i in range n
begin
if lat at i at 0 != gold
begin
return string Fegla Won
end
end
set edits = 0
for j in range length gold
begin
set nsum = 0
for i in range n
begin
set nsum = nsum + lat at i at 1 at j
end
set avg = nsum / n
for i in range n
begin
set e... | import sys
def check(lat,n):
gold = lat[0][0]
for i in range(n):
if lat[i][0] != gold:
return 'Fegla Won'
edits = 0
for j in range(len(gold)):
nsum = 0
for i in range(n):
nsum += lat[i][1][j]
avg = nsum/n
for i in range(n):
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
set inf = call file string A-large.in string r
set outf = call file string A-large.out string w
set casenum = integer read line inf
for T in range 0 casenum
begin
set n = integer read line inf
set A = 0
set x = list
set y = list
comment tmp=inf.readline()
comment for i in range(0,n):
comm... | #!/usr/bin/env python
inf=file('A-large.in','r')
outf=file('A-large.out','w')
casenum=int(inf.readline())
for T in range(0,casenum):
n=int(inf.readline())
A=0
x=[]
y=[]
# tmp=inf.readline()
# for i in range(0,n):
# x.append(int(tmp.split(' ')[i]))
# tmp=inf.readline()
# for i in range(0,n):
# y.append(int(tmp.sp... | Python | zaydzuhri_stack_edu_python |
import Image
import turtle
from PIL import Image
import canvas
from Tkinter import *
import Tkinter
import tkMessageBox
function Drawpath
begin
set wn = call Screen
set alex = call Turtle
call forward 50
call left 90
call right 30
call mainloop
end function
function Puzzle
begin
set top = call Tk
set C = call Canvas to... | import Image
import turtle
from PIL import Image
import canvas
from Tkinter import *
import Tkinter
import tkMessageBox
def Drawpath():
wn=turtle.Screen()
alex=turtle.Turtle()
alex.forward(50)
alex.left(90)
alex.right(30)
wn.mainloop()
def Puzzle():
top = Tkinter.Tk()
C = Tkinter.... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python3
comment vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
comment Neven Sajko
from turtle import degrees , forward , circle , left , pen
set tuple n d r = split input
set tuple n d r = tuple integer n integer d integer r
comment 'n' is the full circle.
call degrees n
for unused_count in ran... | #! /usr/bin/python3
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
# Neven Sajko
from turtle import degrees, forward, circle, left, pen
(n, d, r) = input().split()
(n, d, r) = (int(n), int(d), int(r))
degrees(n) # 'n' is the full circle.
for unused_count in range(n):
forward(d-4*r)
pen(pendown=False... | Python | zaydzuhri_stack_edu_python |
function __call__ self x is_training nfilt=32 reuse=false
begin
with call variable_scope name
begin
set x = reshape tf x list - 1 input_dim input_dim channels
comment attnh1 = unet_conv(x, nfilt*1, 'attnh1', reuse, is_training, use_batch_norm=False)
comment attn1 = unet_conv_t(attnh1, None, 1, 'attn1', reuse, is_traini... | def __call__(self, x, is_training, nfilt=32, reuse=False):
with tf.variable_scope(self.name):
x = tf.reshape(x, [-1, self.input_dim, self.input_dim, self.channels])
# attnh1 = unet_conv(x, nfilt*1, 'attnh1', reuse, is_training, use_batch_norm=False)
# attn1 = unet_conv_t(att... | Python | nomic_cornstack_python_v1 |
comment !/bin/python3
import torch
set x = array range 12
print x
print shape
set x = reshape x 3 4
print x
print zeros tuple 2 3 4
print ones tuple 2 3 4
print randn 3 4
print tensor list list 2 1 4 3 list 1 2 3 4 list 4 3 2 1
set x = tensor list 1.0 2 4 8
set y = tensor list 2 2 2 2
print x + y
print x - y
print x * ... | #!/bin/python3
import torch
x = torch.arange(12)
print(x)
print(x.shape)
x = x.reshape(3, 4)
print(x)
print(torch.zeros((2, 3, 4)))
print(torch.ones((2, 3, 4)))
print(torch.randn(3, 4))
print(torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]]))
x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2, 2, 2, 2])
print... | Python | zaydzuhri_stack_edu_python |
function load_rpeak_indices self rec sampfrom=none sampto=none use_manual=true keep_original=false
begin
set fp = join path db_dir rec
if use_manual
begin
set ext = manual_ann_ext
end
else
begin
set ext = auto_ann_ext
end
set wfdb_ann = call rdann fp extension=ext sampfrom=sampfrom or 0 sampto=sampto
set rpeak_inds = s... | def load_rpeak_indices(self, rec:str, sampfrom:Optional[int]=None, sampto:Optional[int]=None, use_manual:bool=True, keep_original:bool=False) -> np.ndarray:
fp = os.path.join(self.db_dir, rec)
if use_manual:
ext = self.manual_ann_ext
else:
ext = self.auto_ann_ext
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string Python3 script for getting info about an IP/CIDR
import sys
import re
if length argv == 1
begin
comment Get some user input
print string
set y = input string Enter an IP address with CIDR mask, for example 10.100.23.1/24:
end
if length argv > 1
begin
set y = argv at 1
end
comment In... | #!/usr/bin/env python3
'''
Python3 script for getting info about an IP/CIDR
'''
import sys
import re
if len(sys.argv) == 1:
# Get some user input
print('\n')
y = input('Enter an IP address with CIDR mask, for example 10.100.23.1/24:\n')
if len(sys.argv) > 1:
y = sys.argv[1]
####################
# I... | Python | zaydzuhri_stack_edu_python |
comment p = [0, 1, 0, 0, 0]
comment world = ['green', 'red', 'red', 'green', 'green'] #Replace Z with measurements vector and assume the robot is going to sense red, then green
comment Replace Z with measurements vector and assume the robot is going to sense red, then green
set world = list string green string red stri... | #p = [0, 1, 0, 0, 0]
#world = ['green', 'red', 'red', 'green', 'green'] #Replace Z with measurements vector and assume the robot is going to sense red, then green
world = ['green', 'red', 'green', 'green', 'green'] #Replace Z with measurements vector and assume the robot is going to sense red, then green
#measurements ... | Python | zaydzuhri_stack_edu_python |
comment !/use/bin/env python3
comment -*- coding=utf-8 -*-
set __author__ = string penghuang
string excel test
comment import openpyxl
import random
import excel_util
function wirte_excel
begin
set header = list string 第一季度 string 第二季度 string 第三季度 string 第四季度
set file_path = string /upload/jidubaobiao.xlsx
set body = l... | #!/use/bin/env python3
# -*- coding=utf-8 -*-
__author__ = "penghuang"
'''
excel test
'''
# import openpyxl
import random
import excel_util
def wirte_excel():
header = ["第一季度", "第二季度", "第三季度", "第四季度"]
file_path = "/upload/jidubaobiao.xlsx"
body = list()
for item in range(1, 10):
line = list()... | Python | zaydzuhri_stack_edu_python |
from tkinter import Tk
from tkinter import Label
from tkinter import Radiobutton
from tkinter import ttk
from tkinter import messagebox
from tkinter import StringVar
from tkinter import Entry
from tkinter import Frame
from tkinter import IntVar
from tkinter import Button
import base_datos
import opcion_temas
from obser... | from tkinter import Tk
from tkinter import Label
from tkinter import Radiobutton
from tkinter import ttk
from tkinter import messagebox
from tkinter import StringVar
from tkinter import Entry
from tkinter import Frame
from tkinter import IntVar
from tkinter import Button
import base_datos
import opcion_temas
from ob... | Python | zaydzuhri_stack_edu_python |
from StrCompBack import StrCompBack
function SuffixZValues s
begin
set n = length s
set l = n - 1
set r = n - 1
set zs = list comprehension 0 for i in range n
for i in range n - 2 0 - 1
begin
if i <= l
begin
set zs at i = call StrCompBack s i n - 1
set r = i
set l = r - zs at i
end
else
begin
set j = n - r + 1 - i
if z... | from StrCompBack import StrCompBack
def SuffixZValues(s):
n = len(s)
l = r = n - 1
zs = [0 for i in range(n)]
for i in range(n - 2, 0, -1):
if i <= l:
zs[i] = StrCompBack(s, i, n - 1)
r = i
l = r - zs[i]
else:
j = n - (r + 1 - i)
... | Python | zaydzuhri_stack_edu_python |
function sparse_dot_product_attention q k v bi use_map_fn experts_params
begin
set tuple batch_size nb_heads _ depth = call shape_list q
decorator call add_name_scope
function flatten_first_dims x
begin
string Reshape such that x is [num_heads, -1, depth].
comment Case 1: Either constant batch size of size 1 or batch a... | def sparse_dot_product_attention(q, k, v, bi, use_map_fn, experts_params):
batch_size, nb_heads, _, depth = common_layers.shape_list(q)
@expert_utils.add_name_scope()
def flatten_first_dims(x):
"""Reshape such that x is [num_heads, -1, depth]."""
# Case 1: Either constant batch size of size 1 or batch al... | Python | nomic_cornstack_python_v1 |
function fit_mlp X_train Y_train X_val Y_val neurons param verbose=false
begin
set mdl = sequential
add mdl dense neurons input_dim=n_lags activation=string tanh
dropout ratio_dropout
add mdl dense neurons activation=string tanh
add mdl dense pre_step
compile loss=string mean_squared_error optimizer=string adam
fit mdl... | def fit_mlp(X_train, Y_train, X_val, Y_val, neurons, param, verbose=False):
mdl = Sequential()
mdl.add(Dense(neurons, input_dim=param.n_lags, activation='tanh'))
mdl.Dropout(param.ratio_dropout)
mdl.add(Dense(neurons, activation='tanh'))
mdl.add(Dense(param.pre_step))
mdl.compile(loss='mean_squa... | Python | nomic_cornstack_python_v1 |
import json
import urllib3
comment AWS lambda function to turn a TP-Link bulb's colour relating to the current carbon intensity of the National Grid
comment Basic get request
function getRequest url
begin
set http = call PoolManager
set resp = call request string GET url
return status
end function
comment Get the TP-Li... | import json
import urllib3
# AWS lambda function to turn a TP-Link bulb's colour relating to the current carbon intensity of the National Grid
# Basic get request
def getRequest(url):
http = urllib3.PoolManager()
resp = http.request('GET', url)
return resp.status
# Get the TP-Link token using a UUID
def ... | Python | zaydzuhri_stack_edu_python |
function reverseWords s
begin
comment split the string
set words = split s string
comment reverse the words
set words = words at slice : : - 1
comment join the words
set reverseString = join string words
return reverseString
end function
set s = string This is an example sentence.
print call reverseWords s
comment O... | def reverseWords(s):
# split the string
words = s.split(' ')
# reverse the words
words = words[::-1]
# join the words
reverseString = ' '.join(words)
return reverseString
s = "This is an example sentence."
print(reverseWords(s))
# Output: sentence. example an is This | Python | iamtarun_python_18k_alpaca |
function longest_palindrome text
begin
set n = length text
set result = 0
set dp = list comprehension list false * n + 1 for _ in range n + 1
for l in range 1 n + 1
begin
for i in range n - l + 1
begin
set j = i + l - 1
if l == 1
begin
set dp at i at j = true
end
else
if l == 2 and text at i == text at j
begin
set dp a... | def longest_palindrome(text):
n = len(text)
result = 0
dp = [[False] * (n + 1) for _ in range(n + 1)]
for l in range(1, n + 1):
for i in range(n - l + 1):
j = i + l - 1
if l == 1:
dp[i][j] = True
elif l == 2 and text[i] == text[j]:
... | Python | flytech_python_25k |
comment -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import urllib2
import re
import pandas as pd
function my_function name url
begin
set header = dict string User-Agent string Mozilla/5.0
set req = call Request url headers=header
set page = url open req
set soup = call BeautifulSoup page string ... | # -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import urllib2
import re
import pandas as pd
def my_function(name, url):
header = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(url, headers=header)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page, 'lxml')
span = sou... | Python | zaydzuhri_stack_edu_python |
from utils import modular_exponentiation as me , modinv
from bsgs import bsgs
function pohe g h p order factors
begin
string Pohlig-Hellman-Algorithm :param g: :param h: :param p: :param order: :param factors: :return: alpha
set alphas = list
comment CRT
for tuple p_i e_i in factors
begin
comment necessarily < p
set p... | from utils import modular_exponentiation as me, modinv
from bsgs import bsgs
def pohe(g, h, p, order, factors):
"""
Pohlig-Hellman-Algorithm
:param g:
:param h:
:param p:
:param order:
:param factors:
:return: alpha
"""
alphas = []
for p_i, e_i in factors: # CRT
... | Python | zaydzuhri_stack_edu_python |
import json
function array_obj_to_json arr
begin
set json_arr = list
for obj in arr
begin
append json_arr dumps obj
end
return json_arr
end function | import json
def array_obj_to_json(arr):
json_arr = []
for obj in arr:
json_arr.append(json.dumps(obj))
return json_arr
| Python | flytech_python_25k |
comment https://www.hackerrank.com/challenges/py-if-else/problem
import math
set a = integer input
if a % 2 == 1
begin
print string Weird
end
else
if 2 <= a and a <= 5
begin
print string Not Weird
end
else
if 6 <= a and a <= 20
begin
print string Weird
end
else
begin
print string Not Weird
end | # https://www.hackerrank.com/challenges/py-if-else/problem
import math
a = int(input())
if a%2==1:
print("Weird")
elif 2<=a and a<=5 :
print("Not Weird")
elif 6<=a and a<=20 :
print("Weird")
else:
print("Not Weird") | Python | zaydzuhri_stack_edu_python |
function _buffer_list_equal a b
begin
if length a != length b
begin
return false
end
if a == b
begin
return true
end
for tuple ia ib in zip a b
begin
comment Check byte equality, since bytes are what is actually synced
comment NOTE: Simple ia != ib does not always work as intended, as
comment e.g. memoryview(np.frombuf... | def _buffer_list_equal(a, b):
if len(a) != len(b):
return False
if a == b:
return True
for ia, ib in zip(a, b):
# Check byte equality, since bytes are what is actually synced
# NOTE: Simple ia != ib does not always work as intended, as
# e.g. memoryview(np.frombuffer(... | Python | nomic_cornstack_python_v1 |
string Author: Ho Trong Son Date: 24/07/2021 Program: exercise_05_page_85.py Problem: 5. Explain how to check for an invalid input number and prevent it being used in a program. You may assume that the user enters a number. Set Case: A valid number is a number between 0 and 10 other than that it is invalid Solution: Di... | """
Author: Ho Trong Son
Date: 24/07/2021
Program: exercise_05_page_85.py
Problem:
5. Explain how to check for an invalid input number and prevent it being used in a program.
You may assume that the user enters a number.
Set Case:
A valid number is a number between 0 and 10 other than that it is inval... | Python | zaydzuhri_stack_edu_python |
for element in list_data
begin
print element at string name
end | for element in list_data:
print(element['name']) | Python | jtatman_500k |
function generate_pattern_swatches output_folder=string data/pattern_swatches output_csv=string pattern_dataset.csv swatch_size=tuple 100 100
begin
set cwd = get current directory
set outdir = cwd / call Path output_folder
if not exists outdir
begin
make directory outdir parents=true
end
set image_locs = list
set patt... | def generate_pattern_swatches(
output_folder='data/pattern_swatches',
output_csv='pattern_dataset.csv',
swatch_size=(100, 100)
):
cwd = os.getcwd()
outdir = cwd / Path(output_folder)
if not outdir.exists():
outdir.mkdir(parents=True)
image_locs = []
pattern_types = []
f... | Python | nomic_cornstack_python_v1 |
comment To change this license header, choose License Headers in Project Properties.
comment To change this template file, choose Tools | Templates
comment and open the template in the editor.
from Operation import Operation
set __author__ = string talba
set __date__ = string $10/04/2015 18:44:16$
set operator_set = di... | # To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
from Operation import Operation
__author__ = "talba"
__date__ = "$10/04/2015 18:44:16$"
operator_set = {
'+': Operation.make_increme... | Python | zaydzuhri_stack_edu_python |
function update_config self conf stanzaDict
begin
set conf = string %s.conf % conf
set localconfpath = join path dir string local conf
call writeConfFile localconfpath stanzaDict
return true
end function | def update_config(self, conf, stanzaDict):
conf = "%s.conf" % conf
localconfpath = os.path.join(self.dir, "local", conf)
cli.writeConfFile(localconfpath, stanzaDict)
return True | Python | nomic_cornstack_python_v1 |
function plot_technical_indicators self
begin
set dataset = call get_data
comment Replace 0 with Nan so indicators such as ma that don't have a value
comment until 7 days of data don't display inaccurate data
replace dataset 0 nan inplace=true
set trace1 = dict string name ticker ; string type string candlestick ; stri... | def plot_technical_indicators(self) -> Figure:
dataset = self.get_data()
# Replace 0 with Nan so indicators such as ma that don't have a value
# until 7 days of data don't display inaccurate data
dataset.replace(0, np.nan, inplace=True)
trace1 = {
'name': self.tick... | Python | nomic_cornstack_python_v1 |
function get_customer_full_info self cr uid id context=dict
begin
comment We process only 1 customer per call ; the first if user passed several
if has attribute id string __getitem__
begin
set id = id at 0
end
comment noinspection PyBroadException
try
begin
set res_partner_dict = call browse cr uid id context=context
... | def get_customer_full_info(self, cr, uid, id, context={}):
# We process only 1 customer per call ; the first if user passed several
if hasattr(id, '__getitem__'):
id = id[0]
# noinspection PyBroadException
try:
res_partner_dict = self.browse(cr, uid, id, context=... | Python | nomic_cornstack_python_v1 |
function GetComment self
begin
set callResult = call _Call string GetComment
if callResult is none
begin
return none
end
return callResult
end function | def GetComment(self):
callResult = self._Call("GetComment", )
if callResult is None:
return None
return callResult | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
from mycrypto import *
comment http://cryptopals.com/sets/1/challenges/4
set codes = list comprehension right strip line string for line in open string 4.txt
set results = list comprehension call find_byte_key call hex2bin bin for bin in codes
set results = list comprehension x for y in results... | #!/usr/bin/python
from mycrypto import *
#http://cryptopals.com/sets/1/challenges/4
codes = [line.rstrip('\n') for line in open('4.txt')]
results = [ find_byte_key(hex2bin(bin)) for bin in codes]
results = [ x for y in results for x in y if x[0]>0]
results.sort(reverse=True)
| Python | zaydzuhri_stack_edu_python |
function get_args
begin
if length argv < 2
begin
print string Please provide a config json file. You can also provide a specific episode to view.
exit 0
end
set tuple agent _ = call from_config argv at 1 get_action_num
if length argv > 2
begin
load agent suffix=argv at 2
end
else
begin
load agent suffix=string final
en... | def get_args():
if len(sys.argv) < 2:
print(
'Please provide a config json file.\n'
'You can also provide a specific episode to view.'
)
sys.exit(0)
agent, _ = agents.from_config(sys.argv[1], get_action_num)
if len(sys.argv) > 2:
agent.load(suffix=sy... | Python | nomic_cornstack_python_v1 |
function test_token_valid self
begin
set resp = post call url_for string api.token data=dumps dict string email USR ; string password string password content_type=string application/json
set data = loads call get_data
assert status_code == 200
assert data at string status == string success
assert data at string token i... | def test_token_valid(self):
resp = self.client.post(
url_for("api.token"),
data=json.dumps({"email": USR, "password": "password"}),
content_type="application/json",
)
data = json.loads(resp.get_data())
assert resp.status_code == 200
assert data... | Python | nomic_cornstack_python_v1 |
async function test_web opsdroid
begin
set app = call Web opsdroid
assert config == dict
end function | async def test_web(opsdroid):
app = web.Web(opsdroid)
assert app.config == {} | Python | nomic_cornstack_python_v1 |
set N = integer input
set d = list comprehension integer input for _ in range N
set d = set d
print length d | N = int(input())
d = [int(input()) for _ in range(N)]
d = set(d)
print(len(d)) | Python | zaydzuhri_stack_edu_python |
for number in range 1 N + 1
begin
set clap = 0
set answer = string number
for idx in list string 3 string 6 string 9
begin
set clap = clap + count answer idx
end
if clap == 0
begin
set answer = string number
end
else
begin
set answer = string - * clap
end
print answer end=string
end | for number in range(1, N+1):
clap = 0
answer = str(number)
for idx in ['3','6','9']:
clap += answer.count(idx)
if clap == 0 :
answer = str(number)
else :
answer = '-' * clap
print(answer, end = ' ')
| Python | zaydzuhri_stack_edu_python |
function phasearrays npup tiltlist
begin
set phaselist = list
for t in tiltlist
begin
append phaselist call tiltarray tuple npup npup t
end
return phaselist
end function | def phasearrays(npup, tiltlist):
phaselist = []
for t in tiltlist:
phaselist.append(tiltarray((npup,npup), t))
return phaselist | Python | nomic_cornstack_python_v1 |
string This script uses a package called Brian. It is developed with the intention of modeling biologically realisting (or not) neural networks. For more info and install instructions, see: https://brian2.readthedocs.io/en/stable/ Before running, please make sure there is a folder created matching the prefix variable i... | """
This script uses a package called Brian. It is developed with the intention
of modeling biologically realisting (or not) neural networks. For more info
and install instructions, see: https://brian2.readthedocs.io/en/stable/
Before running, please make sure there is a folder created matching the
prefix vari... | Python | zaydzuhri_stack_edu_python |
function write_exception self e
begin
comment _log("exception: %s" % sys.exc_info()[0])
comment TODO: serialize traceback using generalization of code from mulib.htmlexception
global _g_debug_mode
if _g_debug_mode
begin
call _log string traceback: %s % call format_tb call exc_info at 2
end
call respond list string exce... | def write_exception(self, e):
#_log("exception: %s" % sys.exc_info()[0])
# TODO: serialize traceback using generalization of code from mulib.htmlexception
global _g_debug_mode
if _g_debug_mode:
_log("traceback: %s" % traceback.format_tb(sys.exc_info()[2]))
self.resp... | Python | nomic_cornstack_python_v1 |
comment d1 = {"suraj": "kumar", 'sony': 'mylove'}
comment name = input('enter your key word :')
comment print(d1[name])
comment a = ""
comment b = ""
comment while a != "suraj" or b != "kumar":
comment a = input("enter name:")
comment b = input("entr pass:")
comment print("try again")
comment print("welocme")
comment l... | # d1 = {"suraj": "kumar", 'sony': 'mylove'}
# name = input('enter your key word :')
# print(d1[name])
# a = ""
# b = ""
# while a != "suraj" or b != "kumar":
# a = input("enter name:")
# b = input("entr pass:")
# print("try again")
# print("welocme")
# l = eval(input("enter your number:"))
# for i ... | Python | zaydzuhri_stack_edu_python |
set file1 = open string myfile.txt string w
write file1 string Hello World
write lines file1 string This Is FYCS I am in Batch2 My Roll NO Is 54 Hi I m amazing This is line 6 line 7 test abc
close file1
set file1 = open string myfile.txt string r+
print string Output of read function is
print read file1
seek file1 0
pr... | file1=open("myfile.txt","w")
file1.write("Hello World\n")
file1.writelines("This Is FYCS \n I am in Batch2 \n My Roll NO Is 54 \n Hi \n I m amazing \n This is line 6 \n line 7 \n test \n abc \n")
file1.close()
file1=open("myfile.txt","r+")
print("Output of read function is")
print(file1.read())
file1.s... | Python | zaydzuhri_stack_edu_python |
function _assert_one_unblock_the_other self first_fn second_fn
begin
set first_fn_done = event
set second_fn_done = event
set coord = call Coordinator clean_stop_exception_types=list
function wrapped_first_fn
begin
with call stop_on_exception
begin
assert false call is_set
call first_fn
set
end
end function
assert fals... | def _assert_one_unblock_the_other(self, first_fn, second_fn):
first_fn_done = threading.Event()
second_fn_done = threading.Event()
coord = coordinator.Coordinator(clean_stop_exception_types=[])
def wrapped_first_fn():
with coord.stop_on_exception():
self.assertFalse(second_fn_done.is_set(... | Python | nomic_cornstack_python_v1 |
set number = integer input string Nhập số bạn muốn bình phương :
set numberxx = number ^ 2
print string Kết quả là : numberxx | number = int(input("Nhập số bạn muốn bình phương : "))
numberxx = number**2
print("Kết quả là : ",numberxx) | Python | zaydzuhri_stack_edu_python |
comment A skeleton database program
comment NB: INPUTS ARE NOT GUARANTEED SAFE OR SANITISED. PLEASE SANITISE YOUR INPUTS FOR THE DATABASE
comment Test implementation
from datetime import datetime
from time import mktime
from Crypto.Random import random
import numpy as np
import string
import cbor
import re
from header ... | # A skeleton database program
# NB: INPUTS ARE NOT GUARANTEED SAFE OR SANITISED. PLEASE SANITISE YOUR INPUTS FOR THE DATABASE
# Test implementation
from datetime import datetime
from time import mktime
from Crypto.Random import random
import numpy as np
import string
import cbor
import re
from header import *
def ch... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
import sys
from mutagen.mp3 import MP3 | #!/usr/bin/env python2
import sys
from mutagen.mp3 import MP3
| Python | zaydzuhri_stack_edu_python |
function infer_endpoint rule_payload
begin
set bucket = get if expression is instance rule_payload dict then rule_payload else loads rule_payload string bucket
return if expression bucket then string counts else string search
end function | def infer_endpoint(rule_payload):
bucket = (rule_payload if isinstance(rule_payload, dict)
else json.loads(rule_payload)).get("bucket")
return "counts" if bucket else "search" | Python | nomic_cornstack_python_v1 |
function set_bb_stage_start_date_time self _bb_stage_start_date_time
begin
set _bb_stage_start_date_time = _bb_stage_start_date_time
end function | def set_bb_stage_start_date_time(self, _bb_stage_start_date_time):
self._bb_stage_start_date_time = _bb_stage_start_date_time | Python | nomic_cornstack_python_v1 |
class solution extends object
begin
function threeSumCloseat self nums target
begin
if length nums <= 3
begin
return sum nums
end
sort nums
set result = nums at 0 + nums at 1 + nums at 2
for i in range length nums - 2
begin
if i > 0 and nums at i == nums at i - 1
begin
continue
end
set begin = i + 1
set end = length nu... | class solution(object):
def threeSumCloseat(self, nums, target):
if len(nums) <= 3:
return sum(nums)
nums.sort()
result = nums[0] + nums[1] + nums[2]
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
... | Python | zaydzuhri_stack_edu_python |
function text_ self label=none style=none opts=none
begin
try
begin
return call _get_chart string text style=style opts=opts label=label
end
except Exception as e
begin
call err e string Can not draw text marks chart
end
end function | def text_(self, label=None, style=None, opts=None):
try:
return self._get_chart("text", style=style, opts=opts, label=label)
except Exception as e:
self.err(e, "Can not draw text marks chart") | Python | nomic_cornstack_python_v1 |
from BmiCalculator import Bmi
import pytest
decorator fixture
function readingJsonFile
begin
string This is fixture which will create new Bmi object for each test
set mybmi = call Bmi
call readJsonFile string data.json
set data = call returnData string data.json
return mybmi
end function
function test_ReadJsonFile
begi... | from BmiCalculator import Bmi
import pytest
@pytest.fixture()
def readingJsonFile():
"""
This is fixture which will create new Bmi object for each test
"""
mybmi = Bmi()
mybmi.readJsonFile('data.json')
data = mybmi.returnData('data.json')
return mybmi
def test_ReadJsonFile():
"""
... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
import requests
import time
import sys
import datetime
import MySQLdb
function deleteBook input
begin
comment open database and delete book
set db = call connect host=string localhost user=string root passwd=string password db=string webscrape3
set c = call cursor
comment set to utf8 for f... | from bs4 import BeautifulSoup
import requests
import time
import sys
import datetime
import MySQLdb
def deleteBook(input):
#open database and delete book
db = MySQLdb.connect(host='localhost', user='root', passwd='password', db='webscrape3')
c = db.cursor()
# set to utf8 for foreign names ... | Python | zaydzuhri_stack_edu_python |
function download_france_data
begin
set start = time
set oc19_file = string opencovid19-fr-chiffres-cles.csv
set gouv_file = string data-gouv-fr-chiffres-cles.csv
set oc19_url = string https://raw.githubusercontent.com/opencovid19-fr/data/master/dist/chiffres-cles.csv
set gouv_url = string https://www.data.gouv.fr/fr/d... | def download_france_data():
start = time.time()
oc19_file = "opencovid19-fr-chiffres-cles.csv"
gouv_file = "data-gouv-fr-chiffres-cles.csv"
oc19_url = "https://raw.githubusercontent.com/opencovid19-fr/data/master/dist/chiffres-cles.csv"
gouv_url = "https://www.data.gouv.fr/fr/datasets/r/f335f9ea-86e... | Python | nomic_cornstack_python_v1 |
import os
import urllib2
import sys
import logging
set logger = call getLogger string AnimBuddy
comment This is Local Version
set VERSION = string 1.0.6
function getLatestSetupPyFileFromRepo
begin
string Parses latest setup.py's version number
set response = url open string https://raw.githubusercontent.com/darkuress/a... | import os
import urllib2
import sys
import logging
logger = logging.getLogger("AnimBuddy")
#This is Local Version
VERSION = "1.0.6"
def getLatestSetupPyFileFromRepo():
"""Parses latest setup.py's version number"""
response = urllib2.urlopen(
'https://raw.githubusercontent.com/darkuress/animBuddy/rele... | Python | zaydzuhri_stack_edu_python |
function get_command self
begin
if name == string posix
begin
set code_command = call _get_code_command_linux
end
else
if name == string nt
begin
set code_command = call _get_code_command_windows
end
set command = call _build_command code_command
return command
end function | def get_command(self):
if os.name == 'posix':
code_command = self._get_code_command_linux()
elif os.name == 'nt':
code_command = self._get_code_command_windows()
command = self._build_command(code_command)
return command | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
function hist xx bins tot=none bottom=none *args **kwargs
begin
string Inputs: xx: The data values to bin and plot a histogram for. bins: The number of bins to use, or the bin edges. (This is passed directly to np.histogram) tot: The total number of points to use for s... | import numpy as np
import matplotlib.pyplot as plt
def hist(xx, bins, tot=None, bottom=None,
*args, **kwargs):
"""
Inputs:
xx: The data values to bin and plot a histogram for.
bins: The number of bins to use, or the bin edges.
(This is passed directly to n... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.