code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from get_geocode import get_geocode
from json import dumps
set address = input string Address name:
print string Getting data...
set geocode = call get_geocode address
print
print dumps geocode indent=4 sort_keys=true | from get_geocode import get_geocode
from json import dumps
address = input('Address name: ')
print('Getting data...')
geocode = get_geocode(address)
print()
print(dumps(geocode, indent=4, sort_keys=True)) | Python | zaydzuhri_stack_edu_python |
string Tests for the poetry-classifier-program.
import pytest
from poetry_classification.check_poets import check_poets_function
from poetry_classification.scrape_clean import scrape_texts_function , clean_text_function
from poetry_classification.tokenize_poems import tokenize_function
from poetry_classification.aggreg... | ''' Tests for the poetry-classifier-program.'''
import pytest
from poetry_classification.check_poets import check_poets_function
from poetry_classification.scrape_clean import scrape_texts_function, clean_text_function
from poetry_classification.tokenize_poems import tokenize_function
from poetry_classification.aggrega... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Jan 29 21:35:11 2020 Script to essentially augment the images as well as their labels @author: Elijah
from PIL import Image
import random
import cv2
import numpy as np
import math
import glob
import os
function grasp_to_bbox x y theta h w img
begin
comment This functi... | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 29 21:35:11 2020
Script to essentially augment the images
as well as their labels
@author: Elijah
"""
from PIL import Image
import random
import cv2
import numpy as np
import math
import glob
import os
def grasp_to_bbox(x, y, theta, h, w, img):
... | Python | zaydzuhri_stack_edu_python |
function delete self plugin_id **kwargs
begin
return call remove_plugin plugin_id=plugin_id force=false
end function | def delete(self, plugin_id, **kwargs):
return get_resource_manager().remove_plugin(plugin_id=plugin_id,
force=False) | Python | nomic_cornstack_python_v1 |
function syntaxError self recognizer offendingSymbol line column msg e
begin
raise call LexCancellationException recognizer=recognizer offendingSymbol=offendingSymbol line=line column=column msg=msg e=e
end function | def syntaxError(self,
recognizer: Recognizer,
offendingSymbol: Optional[CommonToken],
line: int,
column: int,
msg: str,
e: RecognitionException):
raise LexCancellationException(
re... | Python | nomic_cornstack_python_v1 |
from flask_wtf import FlaskForm
from wtforms import StringField , PasswordField , BooleanField , SubmitField , TextAreaField , validators
from wtforms.validators import DataRequired
class LoginForm extends FlaskForm
begin
set username = call StringField string Username validators=list call DataRequired string Pleae Ent... | from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, TextAreaField, validators
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
username = StringField('Username', validators=[validators.DataRequired("Pleae Enter Valid Username"), validato... | Python | zaydzuhri_stack_edu_python |
function rule_60_all_server_routable session
begin
comment Depends on: rule_40_extend_subnet_cidr
set conf_server = session at string config at string server
set subnets = list comprehension call IpRange sn for sn in conf_server at string ipsec at string subnets
for server in conf_server at string res at string servers... | def rule_60_all_server_routable(session):
# Depends on: rule_40_extend_subnet_cidr
conf_server = session["config"]["server"]
subnets = [IpRange(sn) for sn in conf_server["ipsec"]["subnets"]]
for server in conf_server["res"]["servers_allowed"]:
for subnet in subnets:
if server['ip']... | Python | nomic_cornstack_python_v1 |
function define_optimizer self
begin
raise NotImplementedError
end function | def define_optimizer(self):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import json
import re
function categories_col_tolist col_categories
begin
return split col_categories string 本書分類: at slice 1 : :
end function
function get_nth_category_str col_categories nth
begin
if length call categories_col_tolist col_categories < nth
begin
return nan
end
re... | import pandas as pd
import numpy as np
import json
import re
def categories_col_tolist(col_categories):
return col_categories.split('本書分類:')[1:]
def get_nth_category_str(col_categories, nth):
if len(categories_col_tolist(col_categories)) < nth:
return np.nan
return categories_col_tolist(col_catego... | Python | zaydzuhri_stack_edu_python |
function add_line dwg position size numbered=false
begin
comment normalize size
set nor_size = tuple size at 0 / a_length * nor_length size at 1
set end = tuple position at 0 + nor_size at 0 position at 1 + nor_size at 1
set line = add dwg call line start=call normalize dwg position end=end stroke=call rgb 10 10 16 str... | def add_line(dwg,position,size,numbered=False):
# normalize size
nor_size = (size[0]/dwg.a_length)*dwg.nor_length,size[1]
end = position[0]+nor_size[0],position[1]+nor_size[1]
line = dwg.add(dwg.line(start=normalize(dwg,position),end=end,stroke=svgwrite.rgb(10, 10, 16, '%')))
if numbered:
# ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string * PTStemmer - A Stemming toolkit for the Portuguese language (C) 2008-2010 Pedro Oliveira * * This file is part of PTStemmer. * PTStemmer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free S... | #!/usr/bin/env python
'''
* PTStemmer - A Stemming toolkit for the Portuguese language (C) 2008-2010 Pedro Oliveira
*
* This file is part of PTStemmer.
* PTStemmer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Fr... | Python | zaydzuhri_stack_edu_python |
function openexchangerates_service self
begin
pass
end function | def openexchangerates_service(self):
pass | Python | nomic_cornstack_python_v1 |
async function run self obj
begin
pass
end function | async def run(self, obj: typing.Any) -> Result:
pass | Python | nomic_cornstack_python_v1 |
function add_arguments p
begin
call add_argument string -n string --no_bytes action=string store_true help=string Do not output bytes (default=%(default)s)
end function
comment type=bool, | def add_arguments(p):
p.add_argument(
'-n', '--no_bytes',
action='store_true',
# type=bool,
help='Do not output bytes'
' (default=%(default)s)') | Python | nomic_cornstack_python_v1 |
function enrollment district_id
begin
set conn = call connect host=string localhost database=string teacher_strike_db user=string postgres password=string postgres
set cur = call cursor
set enroll_data = dict
execute cur string SELECT * FROM district_enrollment
set ELL_percent = list
set IEP_percent = list
set teach... | def enrollment(district_id):
conn = psycopg2.connect(host="localhost",database="teacher_strike_db", user="postgres", password="postgres")
cur = conn.cursor()
enroll_data = {}
cur.execute("SELECT * FROM district_enrollment")
ELL_percent = []
IEP_percent = []
teacher_ratio = []
for ... | Python | nomic_cornstack_python_v1 |
function Do self input_dict output_dict exec_properties
begin
call _log_startup input_dict output_dict exec_properties
set artifact_export = call get_single_instance input_dict at ARTIFACT_KEY
set artifact_path = uri
set artifact_push = call get_single_instance output_dict at PUSHED_ARTIFACT_KEY
set push_destination = ... | def Do(self, input_dict: Dict[Text, List[types.Artifact]],
output_dict: Dict[Text, List[types.Artifact]],
exec_properties: Dict[Text, Any]) -> None:
self._log_startup(input_dict, output_dict, exec_properties)
artifact_export = artifact_utils.get_single_instance(input_dict[ARTIFACT_KEY])
ar... | Python | nomic_cornstack_python_v1 |
function process self
begin
return _process
end function | def process(self):
return self._process | Python | nomic_cornstack_python_v1 |
function shuffle orig_colors _config
begin
set colors = list
for orig_color in orig_colors
begin
set rgb = list *orig_color
shuffle rand rgb
set tmp_color = call Color *rgb
set tuple saturation brightness = call to_hsv at slice 1 : :
set hue = call to_hsv at 0
set color = call from_hsv tuple hue saturation brightnes... | def shuffle(orig_colors: ColorList, _config: ConfigParser) -> ColorList:
colors = []
for orig_color in orig_colors:
rgb = [*orig_color]
rand.shuffle(rgb)
tmp_color = Color(*rgb)
saturation, brightness = orig_color.to_hsv()[1:]
hue = tmp_color.to_hsv()[0]
color = ... | Python | nomic_cornstack_python_v1 |
function from_annotype cls anno writeable **kwargs
begin
comment type: (Anno, bool, **Any) -> VMeta
string Return an instance of this class from an Anno
set ret = call cls description=description writeable=writeable keyword kwargs
set widget = call default_widget
if widget != NONE
begin
call set_tags list call tag
end
... | def from_annotype(cls, anno, writeable, **kwargs):
# type: (Anno, bool, **Any) -> VMeta
"""Return an instance of this class from an Anno"""
ret = cls(description=anno.description, writeable=writeable, **kwargs)
widget = ret.default_widget()
if widget != Widget.NONE:
r... | Python | jtatman_500k |
function CheckIfInSelLdrRegion line cur_range_base
begin
set fields = split line
comment cur_range_base should be set if we are already parsing the
comment untrusted sandbox section of the log.
if cur_range_base
begin
comment Check if we are exiting the untrusted sandbox section of the log.
comment The header of a new ... | def CheckIfInSelLdrRegion(line, cur_range_base):
fields = line.split()
# cur_range_base should be set if we are already parsing the
# untrusted sandbox section of the log.
if cur_range_base:
# Check if we are exiting the untrusted sandbox section of the log.
# The header of a new non-untrusted-sandbox s... | Python | nomic_cornstack_python_v1 |
import datetime
import pandas as pd
import numpy as np
from pandas import DataFrame , Series
import MySQLdb as mdb
import numpy as np
import statsmodels.tsa.stattools as ts
comment get name
function get_tickers_from_db con
begin
with con
begin
set cur = call cursor
execute cur string SELECT id,ticker,name FROM symbol
s... | import datetime
import pandas as pd
import numpy as np
from pandas import DataFrame,Series
import MySQLdb as mdb
import numpy as np
import statsmodels.tsa.stattools as ts
#get name
def get_tickers_from_db(con):
with con:
cur = con.cursor()
cur.execute('SELECT id,ticker,name FROM symbol')
data = cur.fetchall()
... | Python | zaydzuhri_stack_edu_python |
function requestAuth self
begin
set obj = self
set params = dict string oauth_callback _callbackURL
set req = call Request _key _secret string params=params path=path host=netloc useHttps=_useHttps
return call handleRequestAuth post
end function | def requestAuth ( self ):
obj = self
params = {
"oauth_callback": self._callbackURL
}
req = Request( self._key, self._secret, "", params=params,
path=self._requestTokenURL.path,
host=self._requestTokenURL.netloc,
useHttps=self._useHttps )
return self.handleRequestAuth( req.post(... | Python | nomic_cornstack_python_v1 |
comment !/usr/local/bin/env python3
comment -*- coding: utf-8 -*-
comment Author : Bhishan Poudel, Physics PhD Student, Ohio University
comment Date : Jun 22, 2017 Thu
comment Last update :
comment Imports
import numpy as np
set visually_bad_gals = list 9 11 12 34 35 42 88 93 99 108 111 119 126 134 135 136 140 144 146 ... | #!/usr/local/bin/env python3
# -*- coding: utf-8 -*-
#
# Author : Bhishan Poudel, Physics PhD Student, Ohio University
# Date : Jun 22, 2017 Thu
# Last update :
#
# Imports
import numpy as np
visually_bad_gals = [9, 11, 12, 34, 35, 42, 88, 93, 99, 108, 111, 119, 126,
134, 135, 136, 1... | Python | zaydzuhri_stack_edu_python |
comment Function that takes a string and prints the letters in decreasing order of frequency.
function most_frequent string
begin
set dictionary = dictionary
for key in string
begin
if key not in dictionary
begin
set dictionary at key = 1
end
else
begin
set dictionary at key = dictionary at key + 1
end
end
return dicti... | #Function that takes a string and prints the letters in decreasing order of frequency.
def most_frequent(string):
dictionary = dict()
for key in string:
if key not in dictionary:
dictionary[key] = 1
else:
dictionary[key] += 1
return dictionary
print(most_frequent('Mississippi'))
... | Python | zaydzuhri_stack_edu_python |
function main
begin
set tuple N C K = map int split input
set T = list comprehension integer input for _ in range N
set T = sorted T
set num_bus = 1
set num_passenger = 1
set first_passenger = T at 0
for i in range 1 N
begin
if first_passenger + K < T at i
begin
set first_passenger = T at i
set num_passenger = 1
set nu... | def main():
N, C, K = map(int, input().split())
T = [int(input()) for _ in range(N)]
T = sorted(T)
num_bus = 1
num_passenger = 1
first_passenger = T[0]
for i in range(1, N):
if first_passenger + K < T[i]:
first_passenger = T[i]
num_passenger = 1
num_bus += 1
elif num_passenger == C:
first_pas... | Python | zaydzuhri_stack_edu_python |
function mark_read user message
begin
call inbox_delete user message
end function | def mark_read(user, message):
backend.inbox_delete(user, message) | Python | nomic_cornstack_python_v1 |
comment breakdown
comment store starting height
comment as long as the following heights are lower, stay (add to volume)
comment following heights higher, end and new start (recorded collected volume)
class Solution
begin
function lakeVolume terrain
begin
comment O(n) time
comment O(n) space
comment init storage variab... | # breakdown
# store starting height
## as long as the following heights are lower, stay (add to volume)
### following heights higher, end and new start (recorded collected volume)
class Solution:
def lakeVolume(terrain):
# O(n) time
# O(n) space
# init storage variables
p_start = ... | Python | zaydzuhri_stack_edu_python |
function format_img_size img C
begin
set img_min_side = decimal im_size
set tuple height width _ = shape
if width >= height
begin
set ratio = width / img_min_side
set new_height = integer height / ratio
set new_width = integer img_min_side
end
else
begin
set ratio = height / img_min_side
set new_width = integer width /... | def format_img_size(img, C):
img_min_side = float(C.im_size)
(height,width,_) = img.shape
if width >= height:
ratio = width / img_min_side
new_height = int(height / ratio)
new_width = int(img_min_side)
else:
ratio = height / img_min_side
new_width = int(width / ratio)
new_height = int(img_min_side)
img... | Python | nomic_cornstack_python_v1 |
function id self
begin
return get pulumi self string id
end function | def id(self) -> str:
return pulumi.get(self, "id") | Python | nomic_cornstack_python_v1 |
function generate_cb_service_choices checked=false service_list=none
begin
set services = if expression service_list is not none then service_list else Service
return list comprehension dict string name fullname ; string value s ; string checked checked for s in services
end function | def generate_cb_service_choices(checked=False, service_list=None):
services = service_list if service_list is not None else Service
return [
{'name': s.fullname, 'value': s, 'checked': checked} for s in services
] | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment Example.py
string .. centered:: Learing Sphinx .. codeauthor:: Shane <chwang12341@gmail.com>
comment 建立一個House
class House
begin
string House 這個class 有什麼 >>> __init__(self, address, name, phone_number) 初始化一個House >>> move_in(self, amount) 遷入 >>> move_out(self, amount) 遷出 >>> __del_... | # -*- coding: utf-8 -*-
## Example.py
"""
.. centered:: Learing Sphinx
.. codeauthor:: Shane <chwang12341@gmail.com>
"""
## 建立一個House
class House:
""" House 這個class 有什麼
>>> __init__(self, address, name, phone_number)
初始化一個House
>>> move_in(self, amount)
遷入
>>> move_out(self, amount)
遷... | Python | zaydzuhri_stack_edu_python |
import sys
import math
from fractions import Fraction
import sys
import math
from fractions import Fraction
from typing import Dict , List
class Vector
begin
function __init__ self x y
begin
set x = x
set y = y
end function
decorator staticmethod
function from_str s
begin
set tuple x y = split s string ,
return call Ve... | import sys
import math
from fractions import Fraction
import sys
import math
from fractions import Fraction
from typing import Dict, List
class Vector:
def __init__(self, x: Fraction, y: Fraction):
self.x = x
self.y = y
@staticmethod
def from_str(s: str):
x, y = s.split(',')
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Time : 2017/7/29 14:11
comment @Author : Patrick.hu
comment @Site :
comment @File : 25.py
comment @Software: PyCharm
comment 题目:求1+2!+3!+...+20!的和。
set r = 0
for i in range 1 21
begin
set r_i = 1
while i > 1
begin
set r_i = r_i * i
set i = i - 1
end
se... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/7/29 14:11
# @Author : Patrick.hu
# @Site :
# @File : 25.py
# @Software: PyCharm
# 题目:求1+2!+3!+...+20!的和。
r = 0
for i in range(1,21):
r_i = 1
while i>1:
r_i *= i
i-=1
r +=r_i
print(r) | Python | zaydzuhri_stack_edu_python |
comment import scipy as sp
import matplotlib.pylot as plt
import pandas as pd
set data = read csv string scratch3.csv
plot kind=string bar
title plt string number of bedrooms
x label string bedrooms
y label string count
show | #import scipy as sp
import matplotlib.pylot as plt
import pandas as pd
data=pd.read_csv("scratch3.csv")
data['bedrooms'].value_counts().plot(kind='bar')
plt.title('number of bedrooms')
plt.xlabel('bedrooms')
plt.ylabel('count')
plt.show()
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import argparse
import random
import pandas as pd
import numpy as np
import cv2 as cv
import scipy.misc as misc
import matplotlib.image as mpimg
from sklearn.utils import shuffle
import keras
from keras.models import Sequential , Model
from keras.layers import Cropping2D , Lambda , Input , ... | #!/usr/bin/env python
import argparse
import random
import pandas as pd
import numpy as np
import cv2 as cv
import scipy.misc as misc
import matplotlib.image as mpimg
from sklearn.utils import shuffle
import keras
from keras.models import Sequential, Model
from keras.layers import Cropping2D, Lambda, Input, ELU
fro... | Python | zaydzuhri_stack_edu_python |
from classifications import *
import unittest
class TestPredict
begin
function test_predict self
begin
set t = call DecisionTree
set dataset = call load_iris
fit t data target
set r = predict t list 4.9 3.0 1.4 0.2
assert equal r 0
end function
end class
class TestMajorityValue
begin
function test_majority_value self
b... | from .classifications import *
import unittest
class TestPredict():
def test_predict(self):
t = DecisionTree()
dataset = datasets.load_iris()
t.fit(dataset.data, dataset.target)
r = t.predict([4.9, 3.0, 1.4, 0.2])
self.assertEqual(r, 0)
class TestMajorityValue():
def ... | Python | zaydzuhri_stack_edu_python |
import pylab
import numpy as np
from scipy.misc import imread , imshow
set a = call imread string pic1.jpg
set b = call imread string pic2.jpg
set c = a + b / 2.0
image show c | import pylab
import numpy as np
from scipy.misc import imread,imshow
a = imread("pic1.jpg")
b = imread("pic2.jpg")
c = (a+b)/2.0
imshow(c)
| Python | zaydzuhri_stack_edu_python |
function _pred_mag self params times
begin
set tE = exp params at 0
set A0 = exp params at 1
set deltaT = exp params at 2
set fbl = params at 3
set mb = params at 4
set u0 = square root 2 * A0 / square root A0 ^ 2 - 1 - 2
set u = square root u0 ^ 2 + times - deltaT - alert_time / tE ^ 2
set Amp = u ^ 2 + 2 / u * square... | def _pred_mag(self,params: ndarray, times: ndarray) -> ndarray:
tE = np.exp(params[0])
A0 = np.exp(params[1])
deltaT = np.exp(params[2])
fbl = params[3]
mb = params[4]
u0 = np.sqrt((2*A0/np.sqrt(A0**2-1))-2)
u = np.sqrt(u0**2+((times-deltaT-self.alert_time)/tE)**... | Python | nomic_cornstack_python_v1 |
function read self offset length pad=false
begin
if not call is_valid offset length
begin
set invalid_address = offset
if minimum_address < offset <= maximum_address
begin
set invalid_address = maximum_address + 1
end
raise call InvalidAddressException name invalid_address string Offset outside of the buffer boundaries... | def read(self, offset: int, length: int, pad: bool = False) -> bytes:
if not self.is_valid(offset, length):
invalid_address = offset
if self.minimum_address < offset <= self.maximum_address:
invalid_address = self.maximum_address + 1
raise exceptions.InvalidAd... | Python | nomic_cornstack_python_v1 |
string This probably saved me a lot of time, idk tho
import os
from os import path as path
import string
for ch in ascii_lowercase
begin
set dirfrom = absolute path path join path get current directory format string lower/lower_{} ch
set dirtrain = absolute path path join path get current directory format string train/... | '''
This probably saved me a lot of time, idk tho
'''
import os
from os import path as path
import string
for ch in string.ascii_lowercase:
dirfrom = path.abspath(path.join(os.getcwd(), 'lower/lower_{}'.format(ch)))
dirtrain = path.abspath(path.join(os.getcwd(), 'train/lower/{}'.format(ch)))
dirtest = pa... | Python | zaydzuhri_stack_edu_python |
import urllib2
set URL = string http://www.gutenberg.org/files/11/11-0.txt
set data = url open URL
function get_from_network url
begin
set data = url open url
set lines = read lines data
return lines
end function | import urllib2
URL = "http://www.gutenberg.org/files/11/11-0.txt"
data = urllib2.urlopen(URL)
def get_from_network(url):
data = urllib2.urlopen(url)
lines = data.readlines()
return lines | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup as bs
with call Session as c
begin
set url = string http://www.boerse.de/historische-kurse/wertpapier/DE000BASF111_jahr,2009#jahr
get c url
post url headers=dict string Referer string http://www.boerse.de
set page = get c string http://www.boerse.de/historische-kurse/wertpa... | import requests
from bs4 import BeautifulSoup as bs
with requests.Session() as c:
url = 'http://www.boerse.de/historische-kurse/wertpapier/DE000BASF111_jahr,2009#jahr'
c.get(url)
c.post(url, headers = {"Referer": "http://www.boerse.de"})
page = c.get('http://www.boerse.de/historische-kurse/wertp... | Python | zaydzuhri_stack_edu_python |
function reverse_sentence sentence
begin
set words = split sentence
set reversed_words = list
for word in reversed words
begin
append reversed_words word
end
set reversed_sentence = join string reversed_words
return reversed_sentence
end function
print call reverse_sentence string Hello World! | def reverse_sentence(sentence):
words = sentence.split()
reversed_words = []
for word in reversed(words):
reversed_words.append(word)
reversed_sentence = " ".join(reversed_words)
return reversed_sentence
print(reverse_sentence("Hello World!")) | Python | jtatman_500k |
import threading
from time import time
set TIMEOUT = 2.0
class LoggingBot extends Thread
begin
function __init__ self message queue timeout=TIMEOUT
begin
call __init__ self
set mMessage = message
set mQueue = queue
set mTimeout = timeout
end function
function run self
begin
set start = time
while not acquire mQueue at ... | import threading
from time import time
TIMEOUT = 2.0
class LoggingBot(threading.Thread):
def __init__(self, message, queue, timeout = TIMEOUT):
threading.Thread.__init__(self)
self.mMessage = message
self.mQueue = queue
self.mTimeout = timeout
def run(self):
start = time()
while not self.mQue... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment 生成纯色的照片。Windows自带画图无法建立大图片。
comment pip install mumpy
comment pip install matplotlib
function draw w h color path
begin
import numpy as np
import matplotlib.image as img
set rgb = list
if color in keys color_point
begin
set rgb_value = color_point at color
end
else
begin
set rgb_value = s... | # coding: utf-8
# 生成纯色的照片。Windows自带画图无法建立大图片。
# pip install mumpy
# pip install matplotlib
def draw(w, h, color, path):
import numpy as np
import matplotlib.image as img
rgb = []
if color in color_point.keys():
rgb_value = color_point[color]
else:
rgb_value = color.split(',')
... | Python | zaydzuhri_stack_edu_python |
comment Perform a 75% training and 25% test data split
set tuple X_train X_test y_train y_test = train test split X y test_size=0.25 random_state=0
comment Fit the random forest model to the training data
set rf = random forest classifier random_state=0
fit rf X_train y_train
comment Calculate the accuracy
set acc = ca... | # Perform a 75% training and 25% test data split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
# Fit the random forest model to the training data
rf = RandomForestClassifier(random_state=0)
rf.fit(X_train, y_train)
# Calculate the accuracy
acc = accuracy_score(y_test, rf.pr... | Python | zaydzuhri_stack_edu_python |
function print_board_state self board
begin
try
begin
set str_board = string
for y in range height
begin
for x in range width
begin
if board at y at x == 0
begin
set str_board = str_board + string X
end
if board at y at x == 1
begin
set str_board = str_board + string O
end
if board at y at x == - 1
begin
set str_board... | def print_board_state(self, board):
try:
str_board = ""
for y in range(self.height):
for x in range(self.width):
if board[y][x] == 0:
str_board += "X"
if board[y][x] == 1:
str_board +=... | Python | nomic_cornstack_python_v1 |
import socket
set s = call socket AF_INET SOCK_DGRAM
call bind tuple call gethostname 7765
print string __SERVER__ side...
while true
begin
set tuple data address = call recvfrom 1024
print string ->>>receiver says : string data
set msg = input string SERVER :
call sendto bytes msg string utf-8 address
print string sen... | import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((socket.gethostname(), 7765))
print("__SERVER__ side...")
while True:
data, address=s.recvfrom(1024)
print('->>>receiver says :', str(data))
msg = input('SERVER : ')
s.sendto(bytes(msg, 'utf-8'), address)
print('sent')
... | Python | zaydzuhri_stack_edu_python |
comment 在Python中,定义一个函数要使用 'def' 语句,
comment 依次写出函数名、括号、括号中的参数和冒号 ':',
comment 然后,在缩进块中编写函数体,
comment 函数的返回值用return语句返回。
comment 文件的引用于内部函数的引用
from com.fuction.base.TempFunction import my_abs
function declare_demo
begin
set x = input string please input the num:
print call my_abs integer x
set tuple y z = call return_d... | # 在Python中,定义一个函数要使用 'def' 语句,
# 依次写出函数名、括号、括号中的参数和冒号 ':',
# 然后,在缩进块中编写函数体,
# 函数的返回值用return语句返回。
# 文件的引用于内部函数的引用
from com.fuction.base.TempFunction import my_abs
def declare_demo():
x = input('please input the num:')
print(my_abs(int(x)))
y, z = return_demo()
print(y, z)
b = return_demo()
... | Python | zaydzuhri_stack_edu_python |
function changeState self
begin
set state = not state
end function | def changeState(self):
self.status.state = not self.status.state | Python | nomic_cornstack_python_v1 |
function collect_music_event self folder event_id db
begin
comment collection of file name patterns, pid, and particle name.
comment string in filename, particle name
set toCollect = list string charged_hydro string pion_p_hydro string kaon_p_hydro string proton_hydro
set differential_vn_filename_list = list string FpT... | def collect_music_event(self, folder, event_id, db):
# collection of file name patterns, pid, and particle name.
# string in filename, particle name
toCollect = ["charged_hydro",
"pion_p_hydro", "kaon_p_hydro", "proton_hydro"]
differential_vn_filename_list = [
... | Python | nomic_cornstack_python_v1 |
function GetCheckExpectedVerdict self
begin
set callResult = call _Call string GetCheckExpectedVerdict
if callResult is none
begin
return none
end
return callResult
end function | def GetCheckExpectedVerdict(self):
callResult = self._Call("GetCheckExpectedVerdict", )
if callResult is None:
return None
return callResult | Python | nomic_cornstack_python_v1 |
function test_nodeAbsent self
begin
set uri = b'xmpp:pubsub.example.org?'
set tuple service nodeIdentifier = call getServiceAndNode uri
assert equal call JID string pubsub.example.org service
assert equal string nodeIdentifier
end function | def test_nodeAbsent(self):
uri = b'xmpp:pubsub.example.org?'
service, nodeIdentifier = gateway.getServiceAndNode(uri)
self.assertEqual(JID(u'pubsub.example.org'), service)
self.assertEqual(u'', nodeIdentifier) | Python | nomic_cornstack_python_v1 |
function get_caller_name N=0 allow_genexpr=true
begin
if is instance N tuple list tuple range
begin
set name_list = list
for N_ in N
begin
try
begin
append name_list call get_caller_name N_
end
except AssertionError
begin
append name_list string X
end
end
return string [ + join string ][ name_list + string ]
end
set p... | def get_caller_name(N=0, allow_genexpr=True):
if isinstance(N, (list, tuple, range)):
name_list = []
for N_ in N:
try:
name_list.append(get_caller_name(N_))
except AssertionError:
name_list.append('X')
return '[' + ']['.join(name_list) ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
set kenar1 = integer input string İlk kenarı giriniz:
set kenar2 = integer input string İkinci kenarı giriniz:
set alan = kenar1 * kenar2
print string Dikdörtgenin alanı = + string alan | #!/usr/bin/python3
kenar1 = int(input("İlk kenarı giriniz: "))
kenar2 = int(input("İkinci kenarı giriniz: "))
alan = kenar1*kenar2
print("Dikdörtgenin alanı = " + str(alan))
| Python | zaydzuhri_stack_edu_python |
function get_event_loop
begin
try
begin
call get_event_loop
end
except RuntimeError as ex
begin
if string There is no current event loop in thread in string ex
begin
set loop = call new_event_loop
call set_event_loop loop
end
end
return call get_event_loop
end function | def get_event_loop() -> asyncio.AbstractEventLoop:
try:
asyncio.get_event_loop()
except RuntimeError as ex:
if "There is no current event loop in thread" in str(ex):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
return asyncio.get_event_loop() | Python | nomic_cornstack_python_v1 |
function copy self
begin
comment NB: This is untested and might not be optimal tbh
return deep copy self
end function | def copy(self) -> "FilterAlgorithmState":
# NB: This is untested and might not be optimal tbh
return deepcopy(self) | Python | nomic_cornstack_python_v1 |
if __name__ == string __main__
begin
set lowest = 100
set second = 100
set arr = list
for _ in range integer input
begin
set name = input
set score = decimal input
append arr list name score
end
set arr2 = set list generator expression val at 1 for val in arr
set second = sorted arr2 at 1
set result = list
for val in... | if __name__ == '__main__':
lowest = 100
second = 100
arr = []
for _ in range(int(input())):
name = input()
score = float(input())
arr.append([name,score])
arr2 = set(list(val[1] for val in arr))
second = sorted(arr2)[1]
result = []
for val in arr:
name = ... | Python | zaydzuhri_stack_edu_python |
string Interface between LuxEnv (mostly lists, vectors) and rllib Trainer (dicts of actors). To change the logic and do feature/reward engineering, create a new class that inherits from this one and pass it to LuxEnv when instantiating it. Author: Jaime Ruiz Serra (@RuizSerra) Date: September 2021
import logging
set lo... | """
Interface between LuxEnv (mostly lists, vectors) and rllib Trainer (dicts of actors).
To change the logic and do feature/reward engineering, create a new class that
inherits from this one and pass it to LuxEnv when instantiating it.
Author: Jaime Ruiz Serra (@RuizSerra)
Date: September 2021
"""
import logging
... | Python | zaydzuhri_stack_edu_python |
from flask import Flask , request , jsonify , render_template
import webbrowser
import pandas as pd
import json
import csv
set app = call Flask __name__ instance_relative_config=true
decorator call route string /submit methods=list string POST
function predict
begin
set data = read csv get files string file
set val = r... | from flask import Flask, request, jsonify, render_template
import webbrowser
import pandas as pd
import json
import csv
app = Flask(__name__, instance_relative_config=True)
@app.route('/submit',methods=['POST'])
def predict():
data = pd.read_csv(request.files.get('file'))
val = pd.read_csv('tes... | Python | zaydzuhri_stack_edu_python |
import json
import unittest
from adventure.input_parser import InputParser
class TestInputParser extends TestCase
begin
function setUp self
begin
pass
end function
function test_single_input_key self
begin
set input_inputs = loads string {"no":["no"]}
set collection = parse call InputParser input_inputs
assert equal 1 ... | import json
import unittest
from adventure.input_parser import InputParser
class TestInputParser(unittest.TestCase):
def setUp(self):
pass
def test_single_input_key(self):
input_inputs = json.loads("{\"no\":[\"no\"]}")
collection = InputParser().parse(input_inputs)
self.assertEqual(1, len(collection.in... | Python | zaydzuhri_stack_edu_python |
function solve
begin
set tuple groups lights = list map int split input string
set lst = list
for i in range groups
begin
set group = list map int split input string
set num = pop group 0
set lst = lst + group
end
set lst = list set lst
if length lst == lights
begin
print string YES
end
else
begin
print string NO
end
... | def solve():
groups, lights = list(map(int, input().split(" ")))
lst = []
for i in range(groups):
group = list(map(int, input().split(" ")))
num = group.pop(0)
lst = lst + group
lst = list(set(lst))
if len(lst) == lights:
print("YES")
else:
print("NO")
so... | Python | zaydzuhri_stack_edu_python |
import os
import os.path
set nand_dff_count = dict
function get_hdl_files
begin
set hdl_files = dict
for tuple dirname _ filenames in walk string .
begin
for filename in filenames
begin
set tuple chip ext = call splitext filename
if ext == string .hdl
begin
set hdl_files at chip = join path dirname filename
end
end
e... | import os
import os.path
nand_dff_count = {}
def get_hdl_files():
hdl_files = {}
for dirname, _, filenames in os.walk('.'):
for filename in filenames:
chip, ext = os.path.splitext(filename)
if ext == '.hdl':
hdl_files[chip] = os.path.join(dirname, filename)
... | Python | zaydzuhri_stack_edu_python |
function getDataCrossValidation self pos
begin
set set = dict
if type inputs at pos == dict
begin
update set inputs at pos
end
else
begin
set set at string input = inputs at pos
end
if targets
begin
if type targets at pos == dict
begin
update set targets at pos
end
else
begin
set set at string output = targets at pos
... | def getDataCrossValidation(self, pos):
set = {}
if type(self.inputs[pos]) == dict:
set.update(self.inputs[pos])
else:
set["input"] = self.inputs[pos]
if self.targets:
if type(self.targets[pos]) == dict:
set.update(self.targets[pos])
... | Python | nomic_cornstack_python_v1 |
function get_candidates self word
begin
comment shape: [batch_size, 1]
set original_target_ids = squeeze word at string target
comment shape: [batch_size, num_variants]
set candidate_ids = mapping_ids at original_target_ids
comment shape: [batch_size, num_variants]
set mask = mapping_mask at original_target_ids
comment... | def get_candidates(
self,
word: Dict[str, torch.LongTensor]
) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
# shape: [batch_size, 1]
original_target_ids = word['target'].squeeze()
# shape: [batch_size, num_variants]
candidate_ids = self.mappi... | Python | nomic_cornstack_python_v1 |
import re
from collections import Counter
function get_most_frequent_words text stopwords min_word_length top_n
begin
comment Remove special characters and punctuation, and convert to lowercase
set cleaned_text = sub string [^\w\s] string lower text
comment Split the cleaned text into words
set words = split cleaned_t... | import re
from collections import Counter
def get_most_frequent_words(text, stopwords, min_word_length, top_n):
# Remove special characters and punctuation, and convert to lowercase
cleaned_text = re.sub(r'[^\w\s]', '', text.lower())
# Split the cleaned text into words
words = cleaned_text.split()... | Python | jtatman_500k |
comment Every function here should return a label telling us exactly what it is
import math
import numpy as np
function sphereVol r
begin
return 4 / 3 * pi * r ^ 3
end function
function getDist r1 r2
begin
return dot r1 - r2 r1 - r2 ^ 0.5
end function | ## Every function here should return a label telling us exactly what it is
import math
import numpy as np
def sphereVol(r):
return (4/3)*math.pi*r**3;
def getDist(r1, r2):
return (np.dot(r1-r2, r1- r2))**0.5; | Python | zaydzuhri_stack_edu_python |
function getcoloracion self
begin
return coloracion_camisa
end function | def getcoloracion(self):
return self.coloracion_camisa | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding:utf-8
import wx
class MyWindow extends Frame
begin
function __init__ self parent=none id=- 1 title=none
begin
call __init__ self parent id title
set panel = call Panel self size=tuple 300 200
call SetBackgroundColour string WHITE
set font = call Font 60 FONTFAMILY_DEFAULT FON... | #!/usr/bin/env python
#coding:utf-8
import wx
class MyWindow(wx.Frame):
def __init__(self, parent=None, id=-1, title=None):
wx.Frame.__init__(self, parent, id, title)
self.panel = wx.Panel(self, size=(300, 200))
self.panel.SetBackgroundColour('WHITE')
font = wx.Font(60, wx.FONTFA... | Python | zaydzuhri_stack_edu_python |
comment Equipment
comment Projectile, Weapon, and Armour models
import coord
class Weapon extends object
begin
string Weapons are a "Projectile factory" and manage their rof, cooldown, and chargeup. Attributes: owner (Entity): The Entity with this weapon.
set STATE_WAITING = 0
set STATE_CHARGEUP = 1
set STATE_FIRING = ... | # Equipment
#
# Projectile, Weapon, and Armour models
import coord
class Weapon( object ):
"""
Weapons are a "Projectile factory" and manage their rof, cooldown, and chargeup.
Attributes:
owner (Entity): The Entity with this weapon.
"""
STATE_WAITING = 0
STATE_CHARGEUP = 1
ST... | Python | zaydzuhri_stack_edu_python |
comment code for input
comment Parenthesis balancing
function parenthesis_balancing exp
begin
set temp = list
for b in exp
begin
if b in list string ( string { string [
begin
append temp b
continue
end
if length temp == 0
begin
print string not balanced
return
end
else
if b in list string ) string } string ]
begin
set... | # code for input
#Parenthesis balancing
def parenthesis_balancing(exp):
temp = []
for b in exp:
if b in ['(', '{', '[']:
temp.append(b)
continue
if len(temp) == 0:
print('not balanced')
return
elif b in [')', '}', ']']:
stb =... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Wed Oct 16 21:49:59 2019 @author: emmanuel
import numpy as np
import cv2
comment Crea una imagen en negro
set img = zeros tuple 512 512 3 uint8
comment Dibuja una línea horizontal verde con un grosor de 4 px
set img = call line img tuple 0 25... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 16 21:49:59 2019
@author: emmanuel
"""
import numpy as np
import cv2
# Crea una imagen en negro
img = np.zeros((512,512,3), np.uint8)
# Dibuja una línea horizontal verde con un grosor de 4 px
img = cv2.line(img,(0,255),(511,255),(0,255,0),4)
cv2... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
string Properties All HubSpot objects store data in default and custom properties. These endpoints provide access to read and modify object properties in HubSpot. # noqa: E501 The version of the OpenAPI document: v3 Generated by: https://openapi-generator.tech
import pprint
comment noqa: F401
impo... | # coding: utf-8
"""
Properties
All HubSpot objects store data in default and custom properties. These endpoints provide access to read and modify object properties in HubSpot. # noqa: E501
The version of the OpenAPI document: v3
Generated by: https://openapi-generator.tech
"""
import pprint
import... | Python | jtatman_500k |
function load_config repo_dir
begin
comment Provide defaults.
set config = dictionary config at string CONFIG_DEFAULT
comment Load the configuration file, if any.
set config_fn = join path repo_dir config at string CONFIG_FILENAME
if exists path config_fn
begin
with open config_fn as f
begin
set overlay = load yaml f
e... | def load_config(repo_dir):
# Provide defaults.
config = dict(app.config['CONFIG_DEFAULT'])
# Load the configuration file, if any.
config_fn = os.path.join(repo_dir, app.config['CONFIG_FILENAME'])
if os.path.exists(config_fn):
with open(config_fn) as f:
overlay = yaml.load(f)
... | Python | nomic_cornstack_python_v1 |
function program self
begin
if _cache_app is none
begin
set _cache_app = call ProcessingProgram APPID _db
end
return _cache_app
end function | def program(self):
if self._cache_app is None:
self._cache_app = ispyb.model.processingprogram.ProcessingProgram(
self.APPID, self._db
)
return self._cache_app | Python | nomic_cornstack_python_v1 |
function subcommand_builder self command_name description=none
begin
string Decorate a function that builds a subcommand. Builders should accept a single argument (the subparser instance) and return the function to be run as the command.
function wrapper decorated
begin
set subparser = call add_parser command_name
set ... | def subcommand_builder(self, command_name, description=None):
"""
Decorate a function that builds a subcommand. Builders should accept a
single argument (the subparser instance) and return the function to be
run as the command."""
def wrapper(decorated):
subparser = s... | Python | jtatman_500k |
class Item
begin
function __init__ self nome preco quantidade=50
begin
set nome = nome
set preco = preco
set quantidade = quantidade
end function
function baixa self quantidade
begin
set quantidade = quantidade - quantidade
end function
end class | class Item:
def __init__(self, nome, preco, quantidade=50):
self.nome = nome
self.preco = preco
self.quantidade = quantidade
def baixa(self, quantidade):
self.quantidade -= quantidade
| Python | zaydzuhri_stack_edu_python |
import socket
import datetime
import pymysql
set conn = call connect host=string 127.0.0.1 user=string bigdata password=string 12345678 db=string mysql charset=string utf8
comment 커서 설정
set cursor = call cursor
set HOST = string 192.168.0.3
set PORT = 9999
comment 객체생성
set client_socket = call socket AF_INET SOCK_STREA... | import socket
import datetime
import pymysql
conn = pymysql.connect(host = '127.0.0.1', user = 'bigdata', password = '12345678', db = 'mysql', charset = 'utf8')
cursor = conn.cursor() # 커서 설정
HOST = '192.168.0.3'
PORT = 9999
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 객체생성
client_socket.conne... | Python | zaydzuhri_stack_edu_python |
function count_boolops node
begin
return length list comprehension subnode for subnode in walk node if is instance subnode BoolOp
end function | def count_boolops(node: ast.AST) -> int:
return len([
subnode
for subnode in ast.walk(node)
if isinstance(subnode, ast.BoolOp)
]) | Python | nomic_cornstack_python_v1 |
string Created by Nicolas Raymond on 2019-11-15. This file provides a LoadBuilder. This object manage all trailer's loading from one plant to another. Last update : 2019-10-31 By : Nicolas Raymond
import numpy as np
import LoadingObjects as LoadObj
import pandas as pd
from collections import Counter
from packer import ... | """
Created by Nicolas Raymond on 2019-11-15.
This file provides a LoadBuilder. This object manage all trailer's loading from one plant to another.
Last update : 2019-10-31
By : Nicolas Raymond
"""
import numpy as np
import LoadingObjects as LoadObj
import pandas as pd
from collections import Counter
from packer im... | Python | zaydzuhri_stack_edu_python |
function search_enriched_clusters
begin
set form = call SearchEnrichedClustersForm form
call populate_form
if method == string POST
begin
set term = get form string go_term
set method = integer get form string method
set check_enrichment = get form string check_enrichment == string y
set check_p = get form string check... | def search_enriched_clusters():
form = SearchEnrichedClustersForm(request.form)
form.populate_form()
if request.method == "POST":
term = request.form.get("go_term")
method = int(request.form.get("method"))
check_enrichment = request.form.get("check_enrichment") == "y"
check... | Python | nomic_cornstack_python_v1 |
import math
function digit num digit
begin
return integer floor num / power 10 digit % 10
end function
function get_next_palindrome num
begin
set num_digits = length string num
set middle_idx = integer floor num_digits / 2
set incr = power 10 middle_idx
set num = num + incr
set num_digits = length string num
set middle... | import math
def digit(num, digit):
return int(math.floor((num / pow(10, digit)) % 10))
def get_next_palindrome(num):
num_digits = len(str(num))
middle_idx = int(math.floor(num_digits / 2))
incr = pow(10, middle_idx)
num = num + incr
num_digits = len(str(num))
middle_idx = int(math.floor((num_digits - 1) /... | Python | zaydzuhri_stack_edu_python |
function confirm_payment self charge_id idempotency_key=none body=none
begin
comment Prepare query URL
set _url_path = string /charges/{charge_id}/confirm-payment
set _url_path = call append_url_with_template_parameters _url_path dict string charge_id charge_id
set _query_builder = base_uri
set _query_builder = _query_... | def confirm_payment(self,
charge_id,
idempotency_key=None,
body=None):
# Prepare query URL
_url_path = '/charges/{charge_id}/confirm-payment'
_url_path = APIHelper.append_url_with_template_parameters(_url_path, {
... | Python | nomic_cornstack_python_v1 |
function evaluate_t_before self t submodels=none errors=string raise iteration=none **kwargs
begin
pass
end function | def evaluate_t_before(self, t: int, *, submodels: Optional[Sequence[Hashable]] = None, errors: str = 'raise', iteration: Optional[int] = None, **kwargs: Dict[str, Any]) -> None:
pass | Python | nomic_cornstack_python_v1 |
comment import the necessary libraries
import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import train_test_split
comment Read the dataset
set data = read csv string dataset.csv
comment Split the dataset into train and test datasets
set tuple x_train x_test ... | # import the necessary libraries
import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.model_selection import train_test_split
# Read the dataset
data = pd.read_csv('dataset.csv')
# Split the dataset into train and test datasets
x_train, x_test, y_train, y_test = train_test_... | Python | jtatman_500k |
comment !/usr/bin/env python
comment Program to fill in a google doc for a party invite
import time
import yaml
import logging
call basicConfig level=INFO
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
set items_map = dict string Mains 0 ; string Salad 1 ; string Dessert 2 ; string Drink... | #!/usr/bin/env python
#Program to fill in a google doc for a party invite
import time
import yaml
import logging
logging.basicConfig(level=logging.INFO)
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
items_map = {"Mains":0,"Salad":1, "Dessert":2, "Drinks":3, "Sides/Appetizers":4}
def... | Python | zaydzuhri_stack_edu_python |
comment encoding:utf-8
from numpy import *
function loadDataSet fileName
begin
set dataMat = list
set fr = open fileName
for line in read lines fr
begin
set curLine = split strip line string
comment 将每行转换成浮点数
set fltLine = list comprehension decimal x for x in curLine
append dataMat fltLine
end
return dataMat
end func... | #encoding:utf-8
from numpy import *
def loadDataSet(fileName):
dataMat=[]
fr=open(fileName)
for line in fr.readlines():
curLine=line.strip().split('\t')
# 将每行转换成浮点数
fltLine = [float(x) for x in curLine]
dataMat.append(fltLine)
return dataMat
def binSplitDataSet(data... | Python | zaydzuhri_stack_edu_python |
function importer
begin
comment Lager liste der eg legg transaksjonar som blir henta og ikkje laga:
set get_list = list
comment Gjer txt-fila i mappen om til csv-fil
call file_fixer
with open out_path as file
begin
set reader = reader file
set r_0 = next reader
append r_0 string type
append r_0 string amount
append r_... | def importer():
#Lager liste der eg legg transaksjonar som blir henta og ikkje laga:
get_list = []
#Gjer txt-fila i mappen om til csv-fil
file_fixer()
with open(out_path) as file:
reader = csv.reader(file)
r_0 = next(reader)
r_0.append("type")
r_0.append('amount')
... | Python | nomic_cornstack_python_v1 |
function __init__ self jsondict=none strict=true
begin
set label = none
string Describes the purpose of this example. Type `str`.
set valueAddress = none
string Value of Example (one of allowed types). Type `Address` (represented as `dict` in JSON).
set valueAge = none
string Value of Example (one of allowed types). Ty... | def __init__(self, jsondict=None, strict=True):
self.label = None
""" Describes the purpose of this example.
Type `str`. """
self.valueAddress = None
""" Value of Example (one of allowed types).
Type `Address` (represented as `dict` in JSON). """
... | Python | nomic_cornstack_python_v1 |
function get_default_flickr30k_loader d_batch **kwargs
begin
set dataset = call Flickr30k keyword kwargs
set data_loader = call DataLoader dataset batch_size=d_batch num_workers=4 shuffle=true pin_memory=true collate_fn=collate_fn
return tuple dataset data_loader
end function | def get_default_flickr30k_loader(d_batch, **kwargs):
dataset = Flickr30k(**kwargs)
data_loader = DataLoader(dataset, batch_size=d_batch, num_workers=4, shuffle=True, pin_memory=True, collate_fn=collate_fn)
return dataset, data_loader | Python | nomic_cornstack_python_v1 |
function percept self agent
begin
set status = call if_ call some_things_at location Dirt string Dirty string Clean
set bump = call if_ bump string Bump string None
return tuple status bump
end function | def percept(self, agent):
status = if_(self.some_things_at(agent.location, Dirt), 'Dirty', 'Clean')
bump = if_(agent.bump, 'Bump', 'None')
return (status, bump) | Python | nomic_cornstack_python_v1 |
with open string combos2.txt as f
begin
set t = read f
end
function divide l n
begin
for i in range 0 length l n
begin
yield l at slice i : i + n :
end
end function
set a = call divide sum list split t string , 3
set out = list
for i in a
begin
if string Hydreigon in i and not string * in i
begin
if string Honedge i... | with open("combos2.txt") as f:
t = f.read()
def divide(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
a = divide(sum([], t.split(",")), 3)
out = []
for i in a:
if "Hydreigon" in i and not "*" in i:
if "Honedge" in i:
pass
if "Doublade" in i:
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import tensorflow as tf
from model import Model
from preprocess import get_data , pad_corpus , convert_to_id
function train model train_input train_output padding_index
begin
string Runs through one epoch - all training examples. :param model: the initialized model to use for forward and backward pas... | import numpy as np
import tensorflow as tf
from model import Model
from preprocess import get_data, pad_corpus, convert_to_id
def train(model, train_input, train_output, padding_index):
"""
Runs through one epoch - all training examples.
:param model: the initialized model to use for forward and backwar... | Python | zaydzuhri_stack_edu_python |
function apply_random_transform self video_path output_path metadata=none
begin
return call change_aspect_ratio video_path output_path ratio=chosen_value metadata=metadata
end function | def apply_random_transform(
self,
video_path: str,
output_path: str,
metadata: Optional[List[Dict[str, Any]]] = None,
) -> str:
return F.change_aspect_ratio(
video_path, output_path, ratio=self.chosen_value, metadata=metadata
) | Python | nomic_cornstack_python_v1 |
function linear_merge list1 list2
begin
set merge = list
while length list1 ? length list2
begin
if list1 at - 1 > list2 at - 1
begin
append merge pop list1
end
else
begin
append merge pop list2
end
end
set merge = merge + list1 + list2 at slice : : - 1
reverse merge
return merge
end function | def linear_merge(list1, list2):
merge = []
while (len(list1) & len(list2)):
if list1[-1] > list2[-1]:
merge.append(list1.pop())
else:
merge.append(list2.pop())
merge += (list1 + list2)[::-1]
merge.reverse()
return merge | Python | nomic_cornstack_python_v1 |
import random
function random_number
begin
return random integer 1 10
end function | import random
def random_number():
return random.randint(1,10)
| Python | flytech_python_25k |
function get_calendar_record self calendar_record_type
begin
comment osid.calendaring.records.CalendarRecord
return
end function | def get_calendar_record(self, calendar_record_type):
return # osid.calendaring.records.CalendarRecord | Python | nomic_cornstack_python_v1 |
function select self *cols **kwargs
begin
set limit = call _gen_limit get kwargs string limit
set where = call _gen_where get kwargs string where
set field_str = call _field_str cols
set q = string SELECT + field_str + string FROM + api_name + where + limit
if get kwargs string bulk
begin
return call queryb q api_name
... | def select(self, *cols, **kwargs):
limit = self._gen_limit(kwargs.get('limit'))
where = self._gen_where(kwargs.get('where'))
field_str = self._field_str(cols)
q = ('SELECT ' + field_str + ' FROM ' + self.api_name
+ where + limit)
if kwargs.get('bulk'):
re... | Python | nomic_cornstack_python_v1 |
function _isWrapped self
begin
set cont = split call readContents
if length cont < 1 or cont at 0 != b'q' or cont at - 1 != b'Q'
begin
return false
end
return true
end function | def _isWrapped(self):
cont = self.readContents().split()
if len(cont) < 1 or cont[0] != b"q" or cont[-1] != b"Q":
return False
return True | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
import math
set contador_disparos = 0
set soma_distancia = 0
while true
begin
set tiro = split call raw_input string ,
set distancia = square root decimal tiro at 0 ^ 2 + decimal tiro at 1 ^ 2
if distancia <= 200
begin
set contador_disparos = contador_disparos + 1
set soma_distancia = soma_distanc... | # coding: utf-8
import math
contador_disparos = 0
soma_distancia = 0
while True:
tiro = raw_input().split(",")
distancia = math.sqrt((float(tiro[0]) ** 2) + (float(tiro[1]) ** 2))
if distancia <= 200:
contador_disparos += 1
soma_distancia += distancia | 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.