code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import numpy as np
function read_data file
begin
set data = list
with open file as f
begin
for line in f
begin
append data call format_string split line
end
return data
end
end function
function format_string string
begin
set tuple pos1 pos2 = split string at 0 string -
set letter = replace string at 1 string : string... | import numpy as np
def read_data(file):
data = []
with open(file) as f:
for line in f:
data.append(format_string(line.split()))
return data
def format_string(string):
pos1, pos2 = string[0].split('-')
letter = string[1].replace(':', '')
password = string[2]
forma... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function isAdditiveNumber self num
begin
if length num <= 2
begin
return false
end
set ret = false
call dfs num list 0
return ret
end function
function dfs self num arr k
begin
if ret or k == length num
begin
if length arr >= 3 and arr at - 3 + arr at - 2 == arr at - 1
begin
set ret = true
end
ret... | class Solution:
def isAdditiveNumber(self, num: str) -> bool:
if len(num) <= 2:
return False
self.ret = False
self.dfs(num, [], 0)
return self.ret
def dfs(self, num, arr, k):
if self.ret or k == len(num):
if len(arr) >= 3 and arr[-3] + arr[-2] == ... | Python | zaydzuhri_stack_edu_python |
function get_total_duration self
begin
return total_duration
end function | def get_total_duration(self):
return self.total_duration | Python | nomic_cornstack_python_v1 |
function start_time self
begin
return get pulumi self string start_time
end function | def start_time(self) -> str:
return pulumi.get(self, "start_time") | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
from keras import layers
from keras.models import Model
import numpy as np
from models.discriminator import discriminator
from models.generator import generator
import os
comment --------------------------------------------------
comment ----------------------GAN-------------------------
comment... | import tensorflow as tf
from keras import layers
from keras.models import Model
import numpy as np
from models.discriminator import discriminator
from models.generator import generator
import os
# --------------------------------------------------
# ----------------------GAN-------------------------
# -----------------... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment Problem 012 - Highly divisible triangular number
import math
function gen_primes n
begin
set primes = list 2
set i = 3
while length primes < n
begin
if call primo i
begin
append primes i
end
set i = i + 2
end
return primes
end function
function primo n
begin
if not n % 2 and n > 2
... | # -*- coding: utf-8 -*-
#Problem 012 - Highly divisible triangular number
import math
def gen_primes(n):
primes = [2]
i = 3
while len(primes) < n:
if primo(i):
primes.append(i)
i += 2
return primes
def primo(n):
if not(n % 2) and n > 2:
return False
for... | Python | zaydzuhri_stack_edu_python |
function send self value
begin
string Send text to stdin. Can only be used on non blocking commands Args: value (str): the text to write on stdin Raises: TypeError: If command is blocking Returns: ShellCommand: return this ShellCommand instance for chaining
if not block and _stdin is not none
begin
write writer format ... | def send(self, value):
"""
Send text to stdin. Can only be used on non blocking commands
Args:
value (str): the text to write on stdin
Raises:
TypeError: If command is blocking
Returns:
ShellCommand: return this ShellCommand instance for chain... | Python | jtatman_500k |
function find_x_codons_before self genome_pos num_codons bool_find_nearest=false complete_rf=true
begin
comment if not genome_pos in self.arr_genome_pos:
comment if bool_find_nearest:
comment direction = -1 if self.iso_sj.strand < 0 else 1
comment genome_pos = self.find_nearest_pos( genome_pos, direction )
comment if n... | def find_x_codons_before( self, genome_pos, num_codons, bool_find_nearest = False, complete_rf = True ):
# if not genome_pos in self.arr_genome_pos:
# if bool_find_nearest:
# direction = -1 if self.iso_sj.strand < 0 else 1
# genome_pos = self.find_nearest_pos( genome_... | Python | nomic_cornstack_python_v1 |
function gamma_mixture_distillation_profile crude1 crude2 vol1 vol2
begin
assert vol1 >= 0 and vol2 >= 0 msg string Specified volumes 'vol1' and 'vol2' must be positive.
comment fit gamma CDF to each crude
set tuple fig ax = call subplots 1 3 figsize=tuple 20 6
try
begin
set tuple fit_params1 cov_matrix1 fit_vals1 ax1 ... | def gamma_mixture_distillation_profile(crude1, crude2, vol1, vol2):
assert vol1 >= 0 and vol2 >= 0, \
"Specified volumes 'vol1' and 'vol2' must be positive."
# fit gamma CDF to each crude
fig, ax = plt.subplots(1, 3, figsize=(20, 6))
try:
fit_params1, cov_matrix1, fit_vals1, ax1 = gamma... | Python | nomic_cornstack_python_v1 |
comment class Animal:
comment _x = 10
comment def test(self):
comment print(Animal._x)
comment print(self._x)
comment class Dog(Animal):
comment def test2(self):
comment print(Dog._x)
comment print(self._x)
comment a = Animal()
comment a.test()
comment d = Dog()
comment d.test2()
comment print(Animal._x)
comment print(... | # class Animal:
# _x = 10
# def test(self):
# print(Animal._x)
# print(self._x)
# class Dog(Animal):
# def test2(self):
# print(Dog._x)
# print(self._x)
# a = Animal()
# a.test()
# d = Dog()
# d.test2()
# print(Animal._x)
# print(Dog._x)
# print(a._x)
# print(d._x)
_a = 98
__all__ = ['_a'] #指在其他模块里面,哪些... | Python | zaydzuhri_stack_edu_python |
function __truediv__ self other
begin
return call Div self other
end function | def __truediv__(self, other):
return Div(self, other) | Python | nomic_cornstack_python_v1 |
function most_frequent_word text
begin
set words = split lower text
set word_count = dict
set max_count = 0
set max_word = string
for word in words
begin
if word in word_count
begin
set word_count at word = word_count at word + 1
end
else
begin
set word_count at word = 1
end
if word_count at word > max_count
begin
se... | def most_frequent_word(text: str) -> str:
words = text.lower().split()
word_count = {}
max_count = 0
max_word = ''
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
if word_count[word] > max_count:
m... | Python | jtatman_500k |
set num1 = input string Enter a number
set num2 = input string Enter a number
set num1 = integer num1
set num2 = integer num2
set div = num1 / num2
print div | num1 = input("Enter a number")
num2 = input("Enter a number")
num1 = int(num1)
num2 = int(num2)
div = num1/num2
print(div) | Python | zaydzuhri_stack_edu_python |
function nexus_users_list_tokens_by_genesis self page limit
begin
if genesis_id == none
begin
return call __error string Not logged in
end
set parms = format string ?genesis={}&page={}&limit={} genesis_id page limit
set url = format users_url sdk_url string list/tokens + parms
set json_data = call __get url
return json... | def nexus_users_list_tokens_by_genesis(self, page, limit):
if (self.genesis_id == None): return(self.__error("Not logged in"))
parms = "?genesis={}&page={}&limit={}".format(self.genesis_id, page,
limit)
url = users_url.format(sdk_url, "list/tokens") + parms
json_data = self... | Python | nomic_cornstack_python_v1 |
function _version_to_tuple version
begin
set tuple major minor = split version string .
return tuple integer major integer minor
end function | def _version_to_tuple(version):
major, minor = version.split('.')
return (int(major), int(minor)) | Python | nomic_cornstack_python_v1 |
function IsActive self CompStr=defaultNamedNotOptArg
begin
return call InvokeTypes 65699 LCID 1 tuple 11 0 tuple tuple 8 1 CompStr
end function | def IsActive(self, CompStr=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(65699, LCID, 1, (11, 0), ((8, 1),),CompStr
) | Python | nomic_cornstack_python_v1 |
from src.main.python.Solution import Solution
comment Given an array of strings, group anagrams together.
comment For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
comment Return:
comment [
comment ["ate", "eat","tea"],
comment ["nat","tan"],
comment ["bat"]
comment ]
comment Note:
comment For the return ... | from src.main.python.Solution import Solution
# Given an array of strings, group anagrams together.
#
# For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"],
# Return:
#
# [
# ["ate", "eat","tea"],
# ["nat","tan"],
# ["bat"]
# ]
# Note:
# For the return value, each inner list's elements ... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
from datetime import date
comment Contact for issues: @brownsarahm, smb@sarahmbrown.org
function get_links
begin
string generate md links for the trainer repo
comment URL to use GH API and query trainer repository for all issues, both open and closed up to the maximum (100)
set trainer_issues_url = ... | import pandas as pd
from datetime import date
# Contact for issues: @brownsarahm, smb@sarahmbrown.org
def get_links():
'''
generate md links for the trainer repo
'''
# URL to use GH API and query trainer repository for all issues, both open and closed up to the maximum (100)
trainer_issues_url =... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment UFCG - Programação I - 2018.1
comment Aluno: Ezequias Rocha
comment Questão: Parte Fracionária - Unidade 2
set numero = decimal call raw_input
set parte_fracionaria = numero % 1 | #coding: utf-8
#UFCG - Programação I - 2018.1
#Aluno: Ezequias Rocha
#Questão: Parte Fracionária - Unidade 2
numero = float(raw_input())
parte_fracionaria = numero % 1
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Time : 20-3-30 下午5:27
comment @Author : ivy_nie
comment @File : new_words_find.py
comment @Software: PyCharm
from collections import Counter
import numpy as np
import re
function n_gram_words text n_gram
begin
string To get n_gram word frequency dict i... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 20-3-30 下午5:27
# @Author : ivy_nie
# @File : new_words_find.py
# @Software: PyCharm
from collections import Counter
import numpy as np
import re
def n_gram_words(text, n_gram):
"""
To get n_gram word frequency dict
input: str of the chinese s... | Python | zaydzuhri_stack_edu_python |
function gcm_credential self
begin
return get pulumi self string gcm_credential
end function | def gcm_credential(self) -> Optional['outputs.GcmCredentialResponse']:
return pulumi.get(self, "gcm_credential") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import logging
import os
import re
import rrdtool
function grab_data file_directory toner_file_list
begin
string This function: 1. Goes through each file in the target directory `for file in os.listdir(file_directory)` 2. If the file is in toner_file_list `if file in toner_file_list` then it g... | #!/usr/bin/python3
import logging
import os
import re
import rrdtool
def grab_data(file_directory, toner_file_list):
"""
This function:
1. Goes through each file in the target directory `for file in os.listdir(file_directory)`
2. If the file is in toner_file_list `if file in toner_file_list` then it ... | Python | zaydzuhri_stack_edu_python |
import sys
import csv
import math
from training import read_source_data
import matplotlib.pyplot as plt
comment The csv file is opened to get the t0 and t1 values. If the file doesn't exist or is un-openable,
comment the values are set to default (0.0) and a warning message is displayed.
function read_thetas
begin
set ... | import sys
import csv
import math
from training import read_source_data
import matplotlib.pyplot as plt
# The csv file is opened to get the t0 and t1 values. If the file doesn't exist or is un-openable,
# the values are set to default (0.0) and a warning message is displayed.
def read_thetas():
t0 = 0.0
t1 = 0.0
t... | Python | zaydzuhri_stack_edu_python |
function load_received_public_key self public_key
begin
if not curve
begin
set curve = curve
end
if curve != curve
begin
raise call InvalidCurveError string Curve mismatch.
end
set public_key = public_key
end function | def load_received_public_key(self, public_key):
if not self.curve:
self.curve = public_key.curve
if self.curve != public_key.curve:
raise InvalidCurveError("Curve mismatch.")
self.public_key = public_key | Python | nomic_cornstack_python_v1 |
comment Imports
import tkinter as tk
from tkinter import PhotoImage
import matplotlib.pyplot as plt
from PIL import Image
from PIL import ImageTk
from camera import camera
from control import control
from tkinter import messagebox
comment initialise the control class
set x = call control
set y = call camera
class Demo1... | #Imports
import tkinter as tk
from tkinter import PhotoImage
import matplotlib.pyplot as plt
from PIL import Image
from PIL import ImageTk
from camera import camera
from control import control
from tkinter import messagebox
#initialise the control class
x = control()
y = camera()
class Demo1():
"""
... | Python | zaydzuhri_stack_edu_python |
function test_user_profile_list_response user_with_profile user_client
begin
call user_with_profile group=string IPZ-41
set endpoint = string /api/v1/users/profiles/
set response = get user_client endpoint
assert status_code == HTTP_200_OK
end function | def test_user_profile_list_response(user_with_profile, user_client):
user_with_profile(group="IPZ-41")
endpoint = "/api/v1/users/profiles/"
response = user_client.get(endpoint)
assert response.status_code == status.HTTP_200_OK | Python | nomic_cornstack_python_v1 |
function get_noise_frame window mqtt_sender
begin
comment Construct the frame to return:
set frame = call Frame window padding=10 borderwidth=5 relief=string ridge
grid
comment Construct the widgets on the frame:
set frame_label = call Label frame text=string Sounds
set beep_label = call Label frame text=string Number ... | def get_noise_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Sounds")
beep_label = ttk.Label(frame, text="Number of Beeps")... | Python | nomic_cornstack_python_v1 |
import os
from collections import defaultdict
set d = default dictionary int
for tuple dirpath dirnames filenames in walk string .
begin
for filename in filenames
begin
set path = join path dirpath filename
set ext = call splitext filename at 1
set d at ext = d at ext + length list open path
end
end | import os
from collections import defaultdict
d = defaultdict(int)
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
path = os.path.join(dirpath, filename)
ext = os.path.splitext(filename)[1]
d[ext] += len(list(open(path)))
| Python | zaydzuhri_stack_edu_python |
function standaardprijs afstandKM
begin
if afstandKM > 50
begin
return 15 + afstandKM - 50 * 0.6
end
else
if afstandKM <= 0
begin
return 0
end
else
begin
return afstandKM * 0.8
end
end function
function ritprijs leeftijd weekendrit afstandKM
begin
set standaard = call standaardprijs afstandKM
set prijs = 0
if leeftijd ... | def standaardprijs(afstandKM):
if afstandKM > 50:
return 15 + (afstandKM - 50) * 0.6
elif afstandKM <= 0:
return 0
else:
return afstandKM * 0.8
def ritprijs(leeftijd, weekendrit, afstandKM):
standaard = standaardprijs(afstandKM)
prijs = 0
if leeftijd <= 12 or leeftijd >... | Python | zaydzuhri_stack_edu_python |
from flask import Flask , redirect
import mysql.connector
import keys
import events
import json
from datetime import date
set app = call Flask __name__
decorator call route string /
decorator call route string /about
decorator call route string /sobre
decorator call route string /info
decorator call route string /odc
f... | from flask import Flask, redirect
import mysql.connector
import keys
import events
import json
from datetime import date
app = Flask(__name__)
@app.route('/')
@app.route('/about')
@app.route('/sobre')
@app.route('/info')
@app.route('/odc')
def hello_world():
return 'For usage information, visit the project githu... | Python | zaydzuhri_stack_edu_python |
function max_len items
begin
return length max items key=len
end function | def max_len(items):
return len(max(items, key=len)) | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
from math import ceil
from single_image_visualization import get_simple_img_visualization
function generate_localization_images images predictions visualization_function=string simple_visualization image_titles=none color_coeff=0.5 nb_images_per_row=4 image_save_path=string ../figures/im... | import matplotlib.pyplot as plt
from math import ceil
from .single_image_visualization import get_simple_img_visualization
def generate_localization_images(images, predictions, visualization_function="simple_visualization", image_titles=None, color_coeff=0.5, nb_images_per_row=4, image_save_path="../figures/images_w... | Python | zaydzuhri_stack_edu_python |
function reset_model self candidates
begin
set model_ = call CorrelatedBetaBernoulliModel candidates_ nn_ kernel_ tolerance_ alpha_prior_ beta_prior_ p=p_
comment always update the selection policy!
call set_model model_
end function | def reset_model(self, candidates):
self.model_ = models.CorrelatedBetaBernoulliModel(
self.candidates_, self.model_.nn_, self.model_.kernel_,
self.model_.tolerance_, self.model_.alpha_prior_, self.model_.beta_prior_, p=self.model_.p_
)
self.selection_policy_.set_model(sel... | Python | nomic_cornstack_python_v1 |
function probe_objects_for_model self model_id group
begin
comment get the probe files for the specific model
if call uses_probe_file_sets
begin
return call probe_file_sets model_id=model_id group=group
end
else
begin
return call probe_files model_id=model_id group=group
end
end function | def probe_objects_for_model(self, model_id, group):
# get the probe files for the specific model
if self.uses_probe_file_sets():
return self.m_database.probe_file_sets(model_id = model_id, group = group)
else:
return self.m_database.probe_files(model_id = model_id, group = group) | Python | nomic_cornstack_python_v1 |
function set_base_image_labels driver user_disk img_name branch target
begin
set dashes = list comprehension i for tuple i c in enumerate img_name if c == string -
set cf_version = img_name at slice dashes at 0 + 1 : dashes at 3 :
set build_id = img_name at slice dashes at - 1 + 1 : :
call ex_set_volume_labels user_... | def set_base_image_labels(driver, user_disk, img_name, branch, target):
dashes = [i for i, c in enumerate(img_name) if c=='-']
cf_version = img_name[dashes[0]+1:dashes[3]]
build_id = img_name[dashes[-1]+1:]
driver.ex_set_volume_labels(user_disk,
{'cf_version': cf_version, 'branch': branch,
... | Python | nomic_cornstack_python_v1 |
import funciones
import main
while true
begin
set rol = input string Bienvenido a PC'S GOSU, donde usted tiene el derecho de tener lo mejor. Soy: 1. Admin 2. Cliente 3. Salir
comment Salir
if rol == string 3
begin
break
end
else
comment Admin
if rol == string 1
begin
while true
begin
print string
print string * * 130
p... | import funciones
import main
while True:
rol = input("\nBienvenido a PC'S GOSU, donde usted tiene el derecho de tener lo mejor. \n"
"\n"
"Soy:\n"
"\n"
"1. Admin\n"
"2. Cliente\n"
"3. Salir\n")
# Salir
... | Python | zaydzuhri_stack_edu_python |
comment ----------------------------------------------------------------
comment Find a phrase in a file
comment Define a function which accepts two string-valued arguments,
comment the name of a text file and a string representing a particular
comment phrase we expect to occur in the file. The function must
comment pr... | #----------------------------------------------------------------
#
# Find a phrase in a file
#
# Define a function which accepts two string-valued arguments,
# the name of a text file and a string representing a particular
# phrase we expect to occur in the file. The function must
# print each line in the file where ... | Python | zaydzuhri_stack_edu_python |
function __init__ self data
begin
call __init__
set _data = call _VariationAnalysisData data=data
set _figure = figure title=value x_axis_label=value y_axis_label=value x_axis_type=string datetime y_axis_type=string linear plot_width=1200
comment add tools
call add_tools call HoverTool tooltips=list tuple string x form... | def __init__(self, data):
super().__init__()
self._data = self._VariationAnalysisData(data=data)
self._figure = bkp.figure(title=_JsonKey.TITLE.value,
x_axis_label=_JsonKey.X_NAME.value,
y_axis_label=_JsonKey.... | Python | nomic_cornstack_python_v1 |
comment to print all notices with url on board
import requests
from bs4 import BeautifulSoup
set html = text
set soup = call BeautifulSoup html string lxml
set global_div = find soup string div dict string class string global_width ct
set dd_tags = find all soup string dd
for dd_tag in dd_tags
begin
set message = get t... | # to print all notices with url on board
import requests
from bs4 import BeautifulSoup
html = requests.get("https://www.bithumb.com").text
soup = BeautifulSoup(html, 'lxml')
global_div = soup.find('div', {"class":"global_width ct"})
dd_tags = soup.find_all('dd')
for dd_tag in dd_tags:
message = dd_tag.get_text()... | Python | zaydzuhri_stack_edu_python |
function replace_invalid arr max_value=none
begin
with catch warnings
begin
filter warnings string ignore
set arr at arr < 0.0 = nan
if max_value
begin
set arr at arr > max_value = nan
end
end
end function | def replace_invalid(arr, max_value=None):
with np.warnings.catch_warnings():
np.warnings.filterwarnings('ignore')
arr[arr < 0.0] = np.nan
if max_value:
arr[arr > max_value] = np.nan | Python | nomic_cornstack_python_v1 |
import sys
import codecs
function main
begin
try
begin
set file_in = argv at 1
set file_out = argv at 2
end
except Exception
begin
print string usage: python big5_to_utf8.py ${file_in} ${file_out}
return
end
with open file_in string r string big5 as source
begin
set content = read source
end
with open file_out string w... | import sys
import codecs
def main():
try:
file_in = sys.argv[1]
file_out = sys.argv[2]
except Exception:
print('usage: python big5_to_utf8.py ${file_in} ${file_out}')
return
with codecs.open(file_in, 'r', 'big5') as source:
content = source.read()
with codecs.o... | Python | zaydzuhri_stack_edu_python |
function icon self
begin
return ICON
end function | def icon(self):
return ICON | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[ ]:
call system string pip install instaloader
comment In[1]:
import datetime
import os , json
import pprint
import os , json
import pandas as pd
comment In[10]:
comment Import the module
import instaloader
comment Create an instance of Instaloader class
set... | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
get_ipython().system('pip install instaloader')
# In[1]:
import datetime
import os, json
import pprint
import os, json
import pandas as pd
# In[10]:
# Import the module
import instaloader
# Create an instance of Instaloader class
loader = instaloader.Instaloade... | Python | zaydzuhri_stack_edu_python |
comment Dictionaries
set players = dict string ss string Puyol ; string 2b string Chicharito ; string 3b string Beckam ; string DH string Neimar ; string OF string DosSantos
set second_base = players at string 2b
set designated_hitter = players at string DH
print designated_hitter
print second_base
comment Nested Colle... | #Dictionaries
players = {
"ss": "Puyol",
"2b": "Chicharito",
"3b": "Beckam",
"DH": "Neimar",
"OF": "DosSantos",
}
second_base = players['2b']
designated_hitter = players['DH']
print(designated_hitter)
print(second_base)
#Nested Collections in Dictionaries (You can add list of team and teamplayer)
teams ... | Python | zaydzuhri_stack_edu_python |
import sys
import unittest
from subprocess import Popen , PIPE
class ApplicationTest extends TestCase
begin
function test_start_ok self
begin
set tuple stdout stderr status = call _call
call assertEquals stdout b'' string datafaser without arguments produces no standard output
call assertNotRegexpMatches stderr b'ERROR... | import sys
import unittest
from subprocess import Popen, PIPE
class ApplicationTest(unittest.TestCase):
def test_start_ok(self):
stdout, stderr, status = self._call()
self.assertEquals(stdout, b'', 'datafaser without arguments produces no standard output')
self.assertNotRegexpMatches(stde... | Python | zaydzuhri_stack_edu_python |
comment Build the lists
while name != string quit
begin
set name = input string What is the name of this account?
if name != string quit
begin
set balance = decimal input string What is the balance?
append names name
append balances balance
end
end
comment Display all of the accounts with their balances
comment Compute... | # Build the lists
while name != "quit":
name = input("What is the name of this account? ")
if name != "quit":
balance = float(input("What is the balance? "))
names.append(name)
balances.append(balance)
# Display all of the accounts with their balances
# Compute the total at the same t... | Python | zaydzuhri_stack_edu_python |
comment HOWTO : prepare text using pickletext.py, add worms, doallworms
import random
import math
import nltk
import pickle
import collections
import functools
import itertools
import sys , pygame
set cmudict = dictionary
call init
set wormfont = call SysFont string monospace 10
function rhyme a b
begin
if lower a not ... | # HOWTO : prepare text using pickletext.py, add worms, doallworms
import random
import math
import nltk
import pickle
import collections
import functools
import itertools
import sys, pygame
cmudict = nltk.corpus.cmudict.dict()
pygame.init()
wormfont = pygame.font.SysFont("monospace", 10)
def rhyme(a, b):
if a.l... | Python | zaydzuhri_stack_edu_python |
function update self hosted_number_order_sids=unset address_sid=unset email=unset cc_emails=unset status=unset contact_title=unset contact_phone_number=unset
begin
string Update the AuthorizationDocumentInstance :param unicode hosted_number_order_sids: A list of HostedNumberOrder sids. :param unicode address_sid: Addre... | def update(self, hosted_number_order_sids=values.unset,
address_sid=values.unset, email=values.unset, cc_emails=values.unset,
status=values.unset, contact_title=values.unset,
contact_phone_number=values.unset):
"""
Update the AuthorizationDocumentInstance
... | Python | jtatman_500k |
comment real signature unknown; restored from __doc__
function MotionSaliencyBinWangApr2014_create
begin
pass
end function | def MotionSaliencyBinWangApr2014_create(): # real signature unknown; restored from __doc__
pass | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from xml.dom.minidom import Document
import os
import glob
global filelist filedict
class XMLData
begin
string docstring for XMLData
function __init__ self sourcedir outputfile
begin
call __init__
set sourcedir = sourcedir
set outfile = outputfile
set filelist = list
set filedict = dict
... | # -*- coding: utf-8 -*-
from xml.dom.minidom import Document
import os
import glob
global filelist,filedict
class XMLData:
"""docstring for XMLData"""
def __init__(self, sourcedir, outputfile):
super(XMLData, self).__init__()
self.sourcedir = sourcedir
self.outfile = outputfile
self.filelist = []
self.filed... | Python | zaydzuhri_stack_edu_python |
comment 2. В інтервалі від 1 до 10 визначити числа
comment • парні, які діляться на 2,
comment • непарні, які діляться на 3,
comment • числа, які не діляться на 2 та 3.
set odd2 = list comprehension x for x in range 1 10 if x % 2 == 0
set odd3 = list comprehension x for x in range 1 10 if x % 3 == 0 and x % 2 != 0
set ... | # 2. В інтервалі від 1 до 10 визначити числа
# • парні, які діляться на 2,
# • непарні, які діляться на 3,
# • числа, які не діляться на 2 та 3.
odd2 = [x for x in range(1,10) if x % 2 == 0 ]
odd3 = [x for x in range(1,10) if x % 3 == 0 and x % 2 != 0]
odd = [x for x in range(1,10) if x % 3 != 0 and x % 2 !=0]
p... | Python | zaydzuhri_stack_edu_python |
function Create self parent
begin
set lsw = call ElementListWidget parent manage=false
set lc = Control
call Bind EVT_MOTION OnMotion
call Bind EVT_LEFT_DOWN ActivateItem
call Bind EVT_CHAR OnChar
call Bind EVT_LIST_ITEM_ACTIVATED ActivateItem
return true
end function | def Create(self, parent):
self.lsw = ElementListWidget(parent, manage=False)
self.lc = self.lsw.Control
self.lc.Bind(wx.EVT_MOTION, self.OnMotion)
self.lc.Bind(wx.EVT_LEFT_DOWN, self.ActivateItem)
self.lc.Bind(wx.EVT_CHAR, self.OnChar)
self.lc.Bind(wx.EVT_LIST_ITEM_ACTIVA... | Python | nomic_cornstack_python_v1 |
from turtle import *
from math import *
from random import *
call up
call goto - 100 50
call colormode 255
function pixel r g b alpha
begin
call begin_fill
call down
if alpha == 1
begin
call up
end
for i in range 4
begin
call color r g b
call fd 10
call rt 90
end
call end_fill
call up
call fd 10
end function
function m... | from turtle import *
from math import *
from random import *
up()
goto(-100,50)
colormode(255)
def pixel(r,g,b,alpha):
begin_fill()
down()
if alpha == 1:
up()
for i in range(4):
color(r,g,b)
fd(10)
rt(90)
end_fill()
up()
fd(10)
def mario():
for p in ra... | Python | zaydzuhri_stack_edu_python |
comment !/bin/env python3
string Server for multithreaded (asynchronouse) chat application.
from socket import socket , AF_INET , SOCK_STREAM
from threading import Thread
set clients = dict
set addresses = dict
set HOST = string
comment PORT that we will use.
set PORT = 33000
comment 1GB
set BUFSIZE = 1024
set ADDR ... | #!/bin/env python3
'''Server for multithreaded (asynchronouse) chat application.'''
from socket import socket, AF_INET, SOCK_STREAM
from threading import Thread
clients = {}
addresses = {}
HOST = ''
PORT = 33000 # PORT that we will use.
BUFSIZE = 1024 # 1GB
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_ST... | Python | zaydzuhri_stack_edu_python |
comment CSE423 Compilers
comment llvm_ir_test.py: basic test for producing LLVM from an AST
string DUMMY C PROGRAM: int add_int(int x, int y) { return x + y; } int main(void) { int a; int b; int c; a = 1; b = 2; c = add_int(a, b); return 0; }
comment Import non-project modules
from treelib import Node , Tree
from llvml... | # CSE423 Compilers
# llvm_ir_test.py: basic test for producing LLVM from an AST
'''
DUMMY C PROGRAM:
int add_int(int x, int y) {
return x + y;
}
int main(void) {
int a;
int b;
int c;
a = 1;
b = 2;
c = add_int(a, b);
return 0;
}
'''
# Import non-project modules
from treelib import ... | Python | zaydzuhri_stack_edu_python |
string 209. Minimum Size Subarray Sum Medium Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. Example: Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal ... | """
209. Minimum Size Subarray Sum
Medium
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal l... | Python | zaydzuhri_stack_edu_python |
function _load_csv self csv_url
begin
comment Reading CSV File containing 1 min candlestick data
set data = read csv csv_url index_col=string Timestamp
comment Converting Timestamp numbers into a new column of readable dates
set data at string Datetime = list comprehension call fromtimestamp i for i in index
set data a... | def _load_csv(self, csv_url: str) -> pd.DataFrame:
# Reading CSV File containing 1 min candlestick data
data = pd.read_csv(csv_url, index_col='Timestamp')
# Converting Timestamp numbers into a new column of readable dates
data['Datetime'] = [datetime.fromtimestamp(i) for i in data.index]... | Python | nomic_cornstack_python_v1 |
function pad_square image output_path=none color=DEFAULT_COLOR metadata=none
begin
call validate_rgb_color color
set image = call validate_and_load_image image
set func_kwargs = call get_func_kwargs metadata locals
set tuple width height = size
if width < height
begin
set h_factor = 0
set dw = height - width
set w_fact... | def pad_square(
image: Union[str, Image.Image],
output_path: Optional[str] = None,
color: Tuple[int, int, int] = utils.DEFAULT_COLOR,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> Image.Image:
utils.validate_rgb_color(color)
image = imutils.validate_and_load_image(image)
func_kwargs... | Python | nomic_cornstack_python_v1 |
function timestamp self name value
begin
string Records the given timestamp. :param name: a counter name of Timestamp type. :param value: a timestamp to record.
set counter = get self name Timestamp
set time = if expression value != none then value else call utcnow
call _update
end function | def timestamp(self, name, value):
"""
Records the given timestamp.
:param name: a counter name of Timestamp type.
:param value: a timestamp to record.
"""
counter = self.get(name, CounterType.Timestamp)
counter.time = value if value != None else datetime.datetim... | Python | jtatman_500k |
function download_holdings_file holdings_file_url file_extension ticker
begin
set r = get requests holdings_file_url headers=dict string User-Agent string Mozilla/5.0 allow_redirects=true
set filename = format string holdings-{}.{} ticker file_extension
write open filename string wb content
return filename
end function | def download_holdings_file(holdings_file_url, file_extension, ticker):
r = requests.get(holdings_file_url, headers={'User-Agent': 'Mozilla/5.0'}, allow_redirects=True)
filename = 'holdings-{}.{}'.format(ticker, file_extension)
open(filename, 'wb').write(r.content)
return filename | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
from tensorflow.keras.layers import Conv2D , LeakyReLU , BatchNormalization
class PatchGAN
begin
decorator staticmethod
function one_cnn_layer input num_filters kernel_size strides padding batch_norm=true
begin
set initializer = call random_normal_initializer 0.0 0.02
set layer = call conv 2d nu... | import tensorflow as tf
from tensorflow.keras.layers import Conv2D, LeakyReLU, BatchNormalization
class PatchGAN:
@staticmethod
def one_cnn_layer(input, num_filters, kernel_size, strides, padding, batch_norm=True):
initializer = tf.random_normal_initializer(0., 0.02)
layer = Conv2D(num_filter... | Python | zaydzuhri_stack_edu_python |
function customEqualizeHist srcImg
begin
set tuple hist _ = call histogram call ravel 256 list 0 256
set cumHist = cumulative sum hist
set maxVal = max
set minVal = min
set transformedHist = as type cumHist at cumHist > 0 - minVal * 255 / maxVal - minVal string uint8
plot hist color=string r
plot transformedHist color=... | def customEqualizeHist(srcImg):
hist, _ = np.histogram(srcImg.ravel(), 256, [0, 256])
cumHist = hist.cumsum()
maxVal = cumHist[cumHist > 0].max()
minVal = cumHist[cumHist > 0].min()
transformedHist = ((cumHist[cumHist > 0] - minVal)
* 255/(maxVal - minVal)).astype('uint8')
... | Python | nomic_cornstack_python_v1 |
function mean self
begin
return decimal mean numpy call asnumpy at 1
end function | def mean(self):
return float(numpy.mean(self.asnumpy()[1])) | Python | nomic_cornstack_python_v1 |
import sys
import math
import random
import getopt
import numpy as np
import matplotlib.pyplot as plot
import matplotlib.patches as mpatches
import time
from scipy import stats
function preprocess train
begin
set line = read line train
set newTrain = string
while line
begin
set line = strip line string
set line = repl... | import sys
import math
import random
import getopt
import numpy as np
import matplotlib.pyplot as plot
import matplotlib.patches as mpatches
import time
from scipy import stats
def preprocess(train):
line = train.readline()
newTrain = ""
while line:
line = line.strip(" ")
line = line.replac... | Python | zaydzuhri_stack_edu_python |
import time
import random
import numpy
import math
from Obstacle import ObjecClass
from path_shortening import isCollisionFreeVertex , isCollisionFreeEdge , uniPruning
import numpy as np
set tuple ADVANCED REACHED TRAPPED = tuple string ADVANCED string REACHED string TRAPPED
comment Implementation of Algorithm Section ... | import time
import random
import numpy
import math
from Obstacle import ObjecClass
from path_shortening import isCollisionFreeVertex,isCollisionFreeEdge,uniPruning
import numpy as np
(ADVANCED, REACHED, TRAPPED) = ("ADVANCED", "REACHED", "TRAPPED")
###################### Implementation of Algorithm Section #######... | Python | zaydzuhri_stack_edu_python |
function AddLowerDisplayInfo self display_info
begin
if not _format
begin
set _format = format
end
if transforms
begin
set transforms = dictionary transforms
update transforms transforms
set _transforms = transforms
end
if aliases
begin
set aliases = dictionary aliases
update aliases _aliases
set _aliases = aliases
end... | def AddLowerDisplayInfo(self, display_info):
if not self._format:
self._format = display_info.format
if display_info.transforms:
transforms = dict(display_info.transforms)
transforms.update(self.transforms)
self._transforms = transforms
if display_info.aliases:
aliases = dict(d... | Python | nomic_cornstack_python_v1 |
import numpy as np
from copy import deepcopy
comment Velocity limits
set X_VEL_LO_LIM = - 5
set X_VEL_UP_LIM = 5
set Y_VEL_LO_LIM = - 5
set Y_VEL_UP_LIM = 5
comment State transition probabilities
set ACTION_SUCCESS_PROB = 0.8
set ACTION_FAIL_PROB = 0.2
class RaceTrack
begin
string Class for representing and abstracting... | import numpy as np
from copy import deepcopy
# Velocity limits
X_VEL_LO_LIM = -5
X_VEL_UP_LIM = 5
Y_VEL_LO_LIM = -5
Y_VEL_UP_LIM = 5
# State transition probabilities
ACTION_SUCCESS_PROB = 0.8
ACTION_FAIL_PROB = 0.2
class RaceTrack:
"""
Class for representing and abstracting the RaceTrack environment
"""... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment Copyright 2009 Google Inc. All Rights Reserved.
string A Google Quick Search plugin for Mac OS X screensavers. Given a user's Quick Search Box query, this search source retrieves and returns screensavers matching the query. Screensaver: The core search source class. SetScreensaverAction... | #!/usr/bin/python
#
# Copyright 2009 Google Inc. All Rights Reserved.
"""A Google Quick Search plugin for Mac OS X screensavers.
Given a user's Quick Search Box query, this search source
retrieves and returns screensavers matching the query.
Screensaver: The core search source class.
SetScreensaverAction: QSB ac... | Python | zaydzuhri_stack_edu_python |
import random
function display_board board
begin
print string * 10
print board at 7 + string | + board at 8 + string | + board at 9
print string ----------
print board at 4 + string | + board at 5 + string | + board at 6
print string ----------
print board at 1 + string | + board at 2 + string | + board at 3
end funct... | import random
def display_board(board):
print('\n' * 10)
print(board[7] + ' | ' + board[8] + ' | ' + board[9])
print('----------')
print(board[4] + ' | ' + board[5] + ' | ' + board[6])
print('----------')
print(board[1] + ' | ' + board[2] + ' | ' + board[3])
def player_input():
"""
:... | Python | zaydzuhri_stack_edu_python |
function put self schedule
begin
set schedule_conflict = call total_conflict
comment Don't add the new schedule if the mpq is full and it's conflict is already at the threshold
if threshold <= schedule_conflict and call qsize == max_size
begin
return
end
comment Make a shallow copy so that the schedule's events are not... | def put(self, schedule):
schedule_conflict = schedule.total_conflict()
# Don't add the new schedule if the mpq is full and it's conflict is already at the threshold
if self.threshold <= schedule_conflict and self.mpq.qsize() == self.max_size:
return
sch = schedule.copy() ... | Python | nomic_cornstack_python_v1 |
function _clean_fields self
begin
string Overriding the default cleaning behaviour to exit early on errors instead of validating each field.
end function | def _clean_fields(self):
"""
Overriding the default cleaning behaviour to exit early on errors
instead of validating each field.
""" | Python | jtatman_500k |
import os , sys , cv2
from PIL import Image
import numpy as np
string A small script for converting images from user-defined directories to grayscale
set __doc__ = string Usage: ./grayscaler.py /dir/of/images
function main in_dir
begin
change directory in_dir
set filelist = list directory string .
end function | import os,sys, cv2
from PIL import Image
import numpy as np
"""A small script for converting images from user-defined directories to grayscale"""
__doc__ = ''' Usage: ./grayscaler.py /dir/of/images'''
def main(in_dir):
os.chdir(in_dir)
filelist = os.listdir('.') | Python | zaydzuhri_stack_edu_python |
function merge_sort lst
begin
if length lst == 1
begin
return list lst at 0
end
set pivot = median lst
set left = call merge_sort lst at slice : pivot :
set right = call merge_sort lst at slice pivot : :
set sorted_lst = call sort_helper left right
return sorted_lst
end function | def merge_sort(lst):
if len(lst) == 1:
return [lst[0]]
pivot = median(lst)
left = merge_sort(lst[:pivot])
right = merge_sort(lst[pivot:])
sorted_lst = sort_helper(left, right)
return sorted_lst | Python | nomic_cornstack_python_v1 |
function get_standard_fwl_rules self firewall_id
begin
set svc = client at string Network_Component_Firewall
return call getRules id=firewall_id mask=RULE_MASK
end function | def get_standard_fwl_rules(self, firewall_id):
svc = self.client['Network_Component_Firewall']
return svc.getRules(id=firewall_id, mask=RULE_MASK) | Python | nomic_cornstack_python_v1 |
function test_withdraw_interactive_success client acc1_usd_withdrawal_transaction_factory
begin
call acc1_usd_withdrawal_transaction_factory
set response = get client string /withdraw?asset_code=USD follow=true
set content = loads content
assert status_code == 403
assert content at string type == string interactive_cus... | def test_withdraw_interactive_success(client, acc1_usd_withdrawal_transaction_factory):
acc1_usd_withdrawal_transaction_factory()
response = client.get(f"/withdraw?asset_code=USD", follow=True)
content = json.loads(response.content)
assert response.status_code == 403
assert content["type"] == "inter... | Python | nomic_cornstack_python_v1 |
function encrypt public_key secret_value
begin
set public_key = call PublicKey encode public_key string utf-8 call Base64Encoder
set sealed_box = call SealedBox public_key
set encrypted = call encrypt encode secret_value string utf-8
return decode base64 encode encrypted string utf-8
end function | def encrypt(public_key: str, secret_value: str) -> str:
public_key = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder())
sealed_box = public.SealedBox(public_key)
encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
return b64encode(encrypted).decode("utf-8") | Python | nomic_cornstack_python_v1 |
function autocor self
begin
set flag = 0
set input = none
set level = none
set board = none
set ainps = dict string L0 list ; string L1 list ; string L2 list ; string H0 list
end function | def autocor(self):
flag=0
input=None
level=None
board=None
ainps={'L0':[],'L1':[],'L2':[],'H0':[]} | Python | nomic_cornstack_python_v1 |
function _get_nits self filename
begin
string Iterate over the instances style checker and yield Nits. :param filename: str pointing to a file within the buildroot.
try
begin
set python_file = parse PythonFile filename root=_root_dir
end
except CheckSyntaxError as e
begin
yield call as_nit
return
end
if call noqa_file_... | def _get_nits(self, filename):
"""Iterate over the instances style checker and yield Nits.
:param filename: str pointing to a file within the buildroot.
"""
try:
python_file = PythonFile.parse(filename, root=self._root_dir)
except CheckSyntaxError as e:
yield e.as_nit()
return
... | Python | jtatman_500k |
function ISOT_to_MJD isot
begin
set date = time isot format=string isot
set format = string mjd
return value
end function | def ISOT_to_MJD(isot):
date = astropy.time.Time(isot, format='isot')
date.format = 'mjd'
return date.value | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import sys
import os
import rospy
import math
import matplotlib.pyplot as plt
set dirname = directory name path __file__
set svea = join path dirname string ../../
append path absolute path path svea
from models.bicycle_simple import SimpleBicycleState , plot_car
from simulators.sim_SVEA_si... | #!/usr/bin/env python
import sys
import os
import rospy
import math
import matplotlib.pyplot as plt
dirname = os.path.dirname(__file__)
svea = os.path.join(dirname, '../../')
sys.path.append(os.path.abspath(svea))
from models.bicycle_simple import SimpleBicycleState, plot_car
from simulators.sim_SVEA_simple import S... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
with open string log/1571393509.897512-TrialDurations-randomPersist.txt as fh
begin
set random_data = call loadtxt fh
end
print string Random Median median random_data
print string Random First Quartile call percentile random_data 25
print string Random Third Quartile ... | import numpy as np
import matplotlib.pyplot as plt
with open('log/1571393509.897512-TrialDurations-randomPersist.txt') as fh:
random_data = np.loadtxt(fh)
print("Random Median", np.median(random_data))
print("Random First Quartile", np.percentile(random_data,25))
print("Random Third Quartile", np.percentile(rando... | Python | zaydzuhri_stack_edu_python |
function autodiscover path=none plugin_prefix=string intake_
begin
string Scan for Intake plugin packages and return a dict of plugins. This function searches path (or sys.path) for packages with names that start with plugin_prefix. Those modules will be imported and scanned for subclasses of intake.source.base.Plugin.... | def autodiscover(path=None, plugin_prefix='intake_'):
"""Scan for Intake plugin packages and return a dict of plugins.
This function searches path (or sys.path) for packages with names that
start with plugin_prefix. Those modules will be imported and scanned for
subclasses of intake.source.base.Plugin... | Python | jtatman_500k |
function summary_filepath source
begin
set filename = string { source } .dat
return join path OBS_DATA_PATH source filename
end function | def summary_filepath(source):
filename = f'{source}.dat'
return os.path.join(OBS_DATA_PATH, source, filename) | Python | nomic_cornstack_python_v1 |
function circuit_one_qubit_two_params inpt
begin
call RY inpt at 0 wires=0
call RX inpt at 1 wires=0
return call expval call PauliZ 0
end function | def circuit_one_qubit_two_params(inpt):
qml.RY(inpt[0], wires=0)
qml.RX(inpt[1], wires=0)
return qml.expval(qml.PauliZ(0)) | Python | nomic_cornstack_python_v1 |
function color_rgb r g b
begin
return string #%02x%02x%02x % tuple r g b
end function | def color_rgb(r,g,b):
return "#%02x%02x%02x" % (r,g,b) | Python | nomic_cornstack_python_v1 |
function summarize_graph self graph
begin
if not graph_stats
begin
set node_stats = call summarize_graph_nodes graph
set edge_stats = call summarize_graph_edges graph
set graph_stats = dict string graph_name if expression name then name else name ; string node_stats node_stats ; string edge_stats edge_stats
end
return ... | def summarize_graph(
self,
graph: BaseGraph
) -> Dict:
if not self.graph_stats:
node_stats = self.summarize_graph_nodes(graph)
edge_stats = self.summarize_graph_edges(graph)
self.graph_stats = {
'graph_name': self.name if self.name ... | Python | nomic_cornstack_python_v1 |
function setIdColAcol self
begin
return call Sigma2qqbar2qqbarNew_setIdColAcol self
end function | def setIdColAcol(self):
return _pythia8.Sigma2qqbar2qqbarNew_setIdColAcol(self) | Python | nomic_cornstack_python_v1 |
function parse_pull_output output
begin
for line in call splitlines
begin
if search strip line
begin
return string
end
else
if search strip line
begin
return split line string at 1
end
end
return string
end function | def parse_pull_output(output: str) -> str:
for line in output.splitlines():
if RE_GIT_AUTD.search(line.strip()):
return ''
elif RE_GIT_UPDATING.search(line.strip()):
return line.split(' ')[1]
return '' | Python | nomic_cornstack_python_v1 |
function get_token client
begin
comment Begin by looking in token cache, first arg is for scopes,
comment because token is for app rather than user, second arg is None.
set result = call acquire_token_silent list string https://graph.microsoft.com/.default account=none
if not result
begin
info string No suitable token ... | def get_token(client):
# Begin by looking in token cache, first arg is for scopes,
# because token is for app rather than user, second arg is None.
result = client.acquire_token_silent(
["https://graph.microsoft.com/.default"], account=None
)
if not result:
logger.info("No suitable ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment ### Proxilmal Policy Optimization
comment PPO is a state of the art algorithm in the field of Reinforcement learning. It has proven record of performing well in sophisticated envoronments especially with continuous action spaces such as Robotics. It is similar ... | #!/usr/bin/env python
# coding: utf-8
# ### Proxilmal Policy Optimization
#
# PPO is a state of the art algorithm in the field of Reinforcement learning. It has proven record of performing well in sophisticated envoronments especially with continuous action spaces such as Robotics. It is similar to Trust Region Polic... | Python | zaydzuhri_stack_edu_python |
from GameElements import *
class SimpleGameSimulator
begin
string SimpleGameSimulator is designed to test whether we can converge to a strategy of never switching when the only reward is a penalty for not switching. The only parameter for the NN is a one-hot encoding of the previous policy. This NN also trains
function... | from GameElements import *
class SimpleGameSimulator:
"""
SimpleGameSimulator is designed to test whether we can converge to a strategy of never
switching when the only reward is a penalty for not switching. The only parameter for
the NN is a one-hot encoding of the previous policy.
This NN also tr... | Python | zaydzuhri_stack_edu_python |
function __init__ self size=tuple 3 3 board=none seed=none random=true solvable=none
begin
raise NotImplementedError
end function | def __init__(self,
size: Tuple[Integral, Integral] = (3, 3),
board: Optional[List[List[Integral]]] = None,
seed: Optional[Integral] = None,
random: bool = True,
solvable: Optional[bool] = None) -> None:
raise NotImplementedErro... | Python | nomic_cornstack_python_v1 |
function multiply num_1 num_2
begin
if num_1 == 0 or num_2 == 0
begin
return 0
end
set sign = 1
if num_1 < 0
begin
set num_1 = - num_1
set sign = - sign
end
if num_2 < 0
begin
set num_2 = - num_2
set sign = - sign
end
set result = 0
for _ in range num_2
begin
set result = result + num_1
end
return result * sign
end fun... | def multiply(num_1, num_2):
if num_1 == 0 or num_2 == 0:
return 0
sign = 1
if num_1 < 0:
num_1 = -num_1
sign = -sign
if num_2 < 0:
num_2 = -num_2
sign = -sign
result = 0
for _ in range(num_2):
result += num_1
return result * sign... | Python | jtatman_500k |
function test_language_cookie_caching self
begin
comment Run a session where the default language is English
set en_session = call Session verbose=1
set s = call Session verbose=1
comment sets cookie
set doc = call go string /haiti?lang=en
assert string I'm looking for someone in text
set doc = call go string /haiti
as... | def test_language_cookie_caching(self):
# Run a session where the default language is English
en_session = self.s = scrape.Session(verbose=1)
doc = self.go('/haiti?lang=en') # sets cookie
assert 'I\'m looking for someone' in doc.text
doc = self.go('/haiti')
assert 'I\... | Python | nomic_cornstack_python_v1 |
function deal self
begin
if cards
begin
set card = pop cards
string Check wether there are any copies of that card left
assert ideal_count at rank > 0 msg string Error, no more of that card
set ideal_count at rank = ideal_count at rank - 1
return card
end
else
begin
global GAME_OVER
set GAME_OVER = true
end
end functio... | def deal(self):
if self.cards:
card = self.cards.pop()
"""
Check wether there are any copies of that card left
"""
assert self.ideal_count[card.rank] > 0, "Error, no more of that card"
self.ideal_count[card.rank] -= 1
return car... | Python | nomic_cornstack_python_v1 |
function _gen_folder_ self
begin
make directories fld_name
set dic_json = dict string PARAM_EXCOND cond_ex ; string PARAM_CALCOND cond_cal ; string PARAM_MODELCONST const_model
with open join path fld_name string cond.json string w as f
begin
dump dic_json f ensure_ascii=false indent=4
end
end function | def _gen_folder_(self):
os.makedirs(self.fld_name)
dic_json = {"PARAM_EXCOND": self.cond_ex,
"PARAM_CALCOND": self.cond_cal,
"PARAM_MODELCONST": self.const_model
}
with open(os.path.join(self.fld_name, "cond.json"), "w") as f:
... | Python | nomic_cornstack_python_v1 |
import itertools
from collections import Counter
from parse import load_dataframes
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
function set_config
begin
comment 폰트, 그래프 색상 설정
set font_list = call findSystemFonts fontpaths=none fontext=string ttf
set rcP... | import itertools
from collections import Counter
from parse import load_dataframes
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
def set_config():
# 폰트, 그래프 색상 설정
font_list = fm.findSystemFonts(fontpaths=None, fontext="ttf")
plt.rcParams["fo... | Python | zaydzuhri_stack_edu_python |
function inferObjectsWithRandomMovements self objectPlacements maxTouches=20 settlingTime=2
begin
string Infer each object without any location input.
for monitor in values monitors
begin
call afterPlaceObjects objectPlacements
end
for tuple objectName objectDict in call iteritems
begin
call reset
set visitCounts = def... | def inferObjectsWithRandomMovements(self, objectPlacements, maxTouches=20,
settlingTime=2):
"""
Infer each object without any location input.
"""
for monitor in self.monitors.values():
monitor.afterPlaceObjects(objectPlacements)
for objectName, objectDic... | Python | jtatman_500k |
import re
from import base
from import domains
from import exceptions
class Primitive extends Type
begin
string A `Primitive` is the first `Type` that validates data by looking at its contents. It is intended as a common base class among primitive types and is not intended for regular use. It extends validation by c... | import re
from . import base
from . import domains
from .. import exceptions
class Primitive(base.Type):
"""
A `Primitive` is the first `Type` that validates data by looking at its
contents. It is intended as a common base class among primitive types and
is not intended for regular use.
It exten... | Python | zaydzuhri_stack_edu_python |
function setup_plot self
begin
set tuple x y s c = call get_data
set scat = scatter ax x y c=c s=s animated=true
set tuple xm xs = tuple mean x 0.5 * standard deviation x
set tuple ym ys = tuple mean y 0.5 * standard deviation y
set axlim_ = list xm - xs xm + xs ym - ys ym + ys
axis axlim_
call set_title string Particl... | def setup_plot(self):
x, y, s, c = self.get_data()
self.scat = self.ax.scatter(x, y, c=c, s=s, animated=True)
xm, xs = x.mean(), 0.5*x.std()
ym, ys = y.mean(), 0.5*y.std()
self.axlim_ = [xm-xs, xm+xs, ym-ys, ym+ys]
self.ax.axis(self.axlim_)
self.ax.set_title('Pa... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.