code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment -*- coding: utf-8 -*-
string Created on Fri Feb 26 01:40:35 2021 @author: flama000711@icloud.com
import os
for FILE in list directory string .
begin
if ends with FILE string .py
begin
continue
end
with open FILE string r as ifp
begin
set lines = read lines ifp
end
set total_time = integer split lines at 0 at 0
... | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 26 01:40:35 2021
@author: flama000711@icloud.com
"""
import os
for FILE in os.listdir('.'):
if FILE.endswith('.py'):
continue
with open(FILE, 'r') as ifp:
lines = ifp.readlines()
total_time = int(lines[0].split()[0])
num_in... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
set matrix = list list 1 2 3 list 4 5 6
for j in matrix
begin
for a in j
begin
if type a is not int and type a is not float
begin
raise call TypeError string matrix must be a matrix(list of lists) of integers/floats
end
end
end
set list_1 = list
for i in range length matrix
begin
append list_... | #!/usr/bin/python3
matrix = [
[1, 2, 3], [4, 5, 6]
]
for j in matrix:
for a in j:
if type(a) is not int and type(a) is not float:
raise TypeError("matrix must be a matrix"
"(list of lists) of integers/floats")
list_1 = []
for i in range(len(matrix)):
li... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Oct 20 19:20:05 2020 @author: Vaseem Naazleen Shaik
import requests
import json
from matplotlib import pyplot as plt
function compare user1 user2
begin
set url = string https://codeforces.com/api/user.rating?handle=
set url1 = url + user1
set url2 = url + user2
set re... | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 20 19:20:05 2020
@author: Vaseem Naazleen Shaik
"""
import requests
import json
from matplotlib import pyplot as plt
def compare(user1, user2):
url = 'https://codeforces.com/api/user.rating?handle='
url1= url + user1
url2= url + user2
resp1 = requests.ge... | Python | zaydzuhri_stack_edu_python |
from geometry.bangun_ruang import BangunRuang
class PersegiPanjang extends BangunRuang
begin
function __init__ self panjang lebar
begin
comment fungsi yang dipanggil pertama kali saat objek dibuat
set panjang = panjang
set lebar = lebar
end function
function info self
begin
return string Ini adalah objek persegi panjan... | from geometry.bangun_ruang import BangunRuang
class PersegiPanjang(BangunRuang):
def __init__(self, panjang, lebar):
# fungsi yang dipanggil pertama kali saat objek dibuat
self.panjang = panjang
self.lebar = lebar
def info(self):
return f'Ini adalah objek persegi panjang denga... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python3
comment coding: utf-8
string CNVD漏洞列表(http://ics.cnvd.org.cn/) 爬虫 数据库操作
from time import sleep
import pymysql
from device_parser.device_parser import DeviceParser
set __author__ = string bovenson
set __email__ = string szhkai@qq.com
set __date__ = string 2017-11-22 10:11
set HOST = string localhos... | #!/bin/python3
# coding: utf-8
"""
CNVD漏洞列表(http://ics.cnvd.org.cn/) 爬虫
数据库操作
"""
from time import sleep
import pymysql
from device_parser.device_parser import DeviceParser
__author__ = "bovenson"
__email__ = "szhkai@qq.com"
__date__ = "2017-11-22 10:11"
HOST = 'localhost'
USER = 'localhost'
PASSWORD = 'localhost'
... | Python | zaydzuhri_stack_edu_python |
function mark_square self column row player
begin
if not call in_bounds column row
begin
return false
end
if not call positionAlreadyMarked column row
begin
set board at column at row = player
return true
end
else
begin
return false
end
end function | def mark_square(self, column, row, player):
if not self.in_bounds(column, row):
return False
if not self.positionAlreadyMarked(column, row):
self.board[column][row] = player
return True
else:
return False | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.cm import rainbow
from sklearn import tree
import seaborn as sns
import warnings
filter warnings string ignore
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeCl... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib.cm import rainbow
from sklearn import tree
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree impor... | Python | zaydzuhri_stack_edu_python |
function withdraws account
begin
set limit = 500
print string Your account balance is $ format account string 0.2f sep=string
print string Your withdraw limit is $ format limit string 0.2f sep=string
while true
begin
try
begin
set withdraw_amount = integer input string Enter withdraw amount. $
break
end
except ValueErr... | def withdraws(account):
limit = 500
print("Your account balance is $", format(account, "0.2f"), sep='')
print("Your withdraw limit is $", format(limit, "0.2f"), sep='')
while True:
try:
withdraw_amount = int(input("Enter withdraw amount. $"))
break
except ... | Python | nomic_cornstack_python_v1 |
function display_ self
begin
return list tuple string blue string GazelleAvgThreshold string Gazelles' average threshold tuple string red string LionAvgThreshold string Lions' average threshold tuple string yellow string LionAvgScore string Lions' average score
end function | def display_(self):
return [('blue', 'GazelleAvgThreshold', "Gazelles' average threshold"),
('red', 'LionAvgThreshold', "Lions' average threshold"),
('yellow', 'LionAvgScore', "Lions' average score")] | Python | nomic_cornstack_python_v1 |
function Mkgrid
begin
set tuple inputs classes = next iterate dataset_loader_t at string train
set out = call make_grid inputs
set half = round length classes / 2 - 1
print half
set titles = list comprehension split class_names at x string _ at 1 at slice 0 : 3 : for x in classes
set titles at half = join string list... | def Mkgrid():
inputs, classes = next(iter(dataset_loader_t['train']))
out = torchvision.utils.make_grid(inputs)
half = round(len(classes)/2) -1
print(half)
titles = [class_names[x].split("_")[1][0:3] for x in classes]
titles[half] = "".join([titles[half], "\n"])
title_joined = ", ".join(titles)
imshow(out, ti... | Python | nomic_cornstack_python_v1 |
function SendMsg self request context
begin
call set_code UNIMPLEMENTED
call set_details string Method not implemented!
raise call NotImplementedError string Method not implemented!
end function | def SendMsg(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | Python | nomic_cornstack_python_v1 |
function swagger_serializer_method serializer_or_field
begin
function decorator serializer_method
begin
comment stash the serializer for SerializerMethodFieldInspector to find
set _swagger_serializer = serializer_or_field
return serializer_method
end function
return decorator
end function | def swagger_serializer_method(serializer_or_field):
def decorator(serializer_method):
# stash the serializer for SerializerMethodFieldInspector to find
serializer_method._swagger_serializer = serializer_or_field
return serializer_method
return decorator | Python | nomic_cornstack_python_v1 |
comment run through spark-submit, or the spark context will be missing
import pandas as pd
import numpy as np
import re
from datetime import datetime
from datetime import timedelta
comment takes a line from weblogs and splits it into fields
comment for convenience, this only grabs up until the request_url
comment sampl... | #run through spark-submit, or the spark context will be missing
import pandas as pd
import numpy as np
import re
from datetime import datetime
from datetime import timedelta
#takes a line from weblogs and splits it into fields
#for convenience, this only grabs up until the request_url
#sample weblog line:
#2015-07-2... | Python | zaydzuhri_stack_edu_python |
function run batch_size
begin
set start = time
set model = call get_model
set history = train model batch_size
set tuple y_true y_pred = predict model
set tuple precision recall fscore acc_score = call get_metrics y_true y_pred
set tuple tn fp fn tp = call get_confusion_matrix y_true y_pred
set acc = history at string ... | def run(batch_size):
start = time.time()
model = get_model()
history = train(model, batch_size)
y_true, y_pred = predict(model)
precision, recall, fscore, acc_score = get_metrics(y_true, y_pred)
tn, fp, fn, tp = get_confusion_matrix(y_true, y_pred)
acc = history.history['acc']
val... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment import matplotlib.pyplot as plt
import os
import json
from pprint import pprint
comment M A I N ########################################
set datas = dict
set fileNY = open string Req200/new_york.txt string r
set fileCWB = open string Req200/curitiba.txt string r
set fileCH = open ... | # -*- coding: utf-8 -*-
#import matplotlib.pyplot as plt
import os
import json
from pprint import pprint
#######################################################################################
################################ M A I N ########################################
##############################... | Python | zaydzuhri_stack_edu_python |
function __call__ self
begin
return 10
end function | def __call__(self):
return 10 | Python | nomic_cornstack_python_v1 |
function di self x delta=0
begin
return tuple First Last
end function | def di(self, x, delta=0):
return x.First, x.Last | Python | nomic_cornstack_python_v1 |
string TESTCASE 2019-02-01 23:21 2019-01-03 12:35 - 2019-02-01 23:21 2017-01-03 12:35 - 2014-03-01 21:21 2017-01-03 12:35 - 2017-01-01 23:21 2017-01-01 12:00
from datetime import datetime
function get_dt
begin
return string parse time input string %Y-%m-%d %H:%M
end function
set d1 = call get_dt
set d2 = call get_dt
se... | '''TESTCASE
2019-02-01 23:21
2019-01-03 12:35
-
2019-02-01 23:21
2017-01-03 12:35
-
2014-03-01 21:21
2017-01-03 12:35
-
2017-01-01 23:21
2017-01-01 12:00
'''
from datetime import datetime
def get_dt():
return datetime.strptime(input(), "%Y-%m-%d %H:%M")
d1 = get_dt()
d2 = get_dt()
delta = abs(d1 - d2)
print(del... | Python | zaydzuhri_stack_edu_python |
from Nodes.Node import Node
from Nodes.Executable import Executable
from Nodes.AssignNode import AssignNode
from Nodes.IfNode import IfNode
from Nodes.LoopNode import LoopNode
from Nodes.InNode import InNode
from Nodes.OutNode import OutNode
from Nodes.Parsing import match_consume , TOKEN_VALUE_IDENTIFIER , RESERVED_WO... | from Nodes.Node import Node
from Nodes.Executable import Executable
from Nodes.AssignNode import AssignNode
from Nodes.IfNode import IfNode
from Nodes.LoopNode import LoopNode
from Nodes.InNode import InNode
from Nodes.OutNode import OutNode
from Nodes.Parsing import match_consume, TOKEN_VALUE_IDENTIFIER, RESERVED_WORD... | Python | zaydzuhri_stack_edu_python |
function unlike db filename user
begin
set cur = call cursor
if call like_exists db filename user
begin
set sql = string delete from likes where filename=? and usernick=?;
execute cur sql tuple filename user
commit db
end
end function | def unlike(db, filename, user):
cur = db.cursor()
if like_exists(db, filename, user):
sql = """
delete from likes where filename=? and usernick=?;
"""
cur.execute(sql, (filename, user))
db.commit() | Python | nomic_cornstack_python_v1 |
import csv
set info_list = list string id string title string released string on_video string url string unknown string Action string Adventure string Animation string Children string Comedy string Crime string Documentary string Drama string Fantasy string Noir string Horror string Musical string Mystery string Romanc... | import csv
info_list = ['id', 'title', 'released', 'on_video', 'url', 'unknown',
'Action', 'Adventure', 'Animation', 'Children', 'Comedy',
'Crime', 'Documentary', 'Drama', 'Fantasy', 'Noir', 'Horror',
'Musical', 'Mystery', 'Romance', 'Scifi', 'Thriller', 'War',
'Wes... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
comment from lr_utils import load_dataset | import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
#from lr_utils import load_dataset
| Python | zaydzuhri_stack_edu_python |
comment crypto utils
function egcd a b
begin
set tuple x y u v = tuple 0 1 1 0
while a != 0
begin
set tuple q r = tuple b // a b % a
set tuple m n = tuple x - u * q y - v * q
set tuple b a x y u v = tuple a r u v m n
end
set gcd = b
return tuple gcd x y
end function
function mod_inv a m
begin
set tuple gcd x y = call e... | #crypto utils
def egcd(a, b):
x,y, u,v = 0,1, 1,0
while a != 0:
q, r = b//a, b%a
m, n = x-u*q, y-v*q
b,a, x,y, u,v = a,r, u,v, m,n
gcd = b
return gcd, x, y
def mod_inv(a, m):
gcd, x, y = egcd(a, m)
if gcd != 1:
return None # modular inverse does not exist
... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
function few_life str_arg
begin
call world_and_day str_arg
print string big_child_and_time
end function
function world_and_day str_arg
begin
print str_arg
end function
if __name__ == string __main__
begin
call few_life string different_man
end | #! /usr/bin/env python
def few_life(str_arg):
world_and_day(str_arg)
print('big_child_and_time')
def world_and_day(str_arg):
print(str_arg)
if __name__ == '__main__':
few_life('different_man')
| Python | zaydzuhri_stack_edu_python |
function calc number
begin
set number = number + 100
call calc2 number
return number
end function
function calc2 number
begin
set number = number + 100
end function
function loop_example
begin
for i in range 5
begin
if i == 2
begin
return
end
print i
end
end function
set number = 200
print call calc number
print number... | def calc(number):
number += 100
calc2(number)
return number
def calc2(number):
number += 100
def loop_example():
for i in range(5):
if i == 2:
return
print(i)
number = 200
print(calc(number))
print(number)
loop_example() | Python | zaydzuhri_stack_edu_python |
function transform_points points T
begin
set homo_points = array list comprehension tuple x y 1 for tuple y x in points
set t_points = array list comprehension dot v for v in homo_points
set swap = array list comprehension tuple x y for tuple y x z in t_points
return swap
end function | def transform_points(points, T):
homo_points = np.array([(x, y, 1) for (y, x) in points])
t_points = np.array([T.dot(v) for v in homo_points ])
swap = np.array([(x,y) for (y,x,z) in t_points])
return swap | Python | nomic_cornstack_python_v1 |
for i in range size
begin
for i in range size
begin
print string * end=string
end
print
end | for i in range(size):
for i in range(size):
print("*", end=" ")
print()
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sun Jan 31 22:39:23 2016 @author: konin_de New update 09-02-2016: Database issue is fixed, however it was found that the statistics for first 9 darts do not match yet. Furthermore the code can possibly be cleaned a fair bit. ** Still to be added ** 1. combine the 2 screen... | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 31 22:39:23 2016
@author: konin_de
New update 09-02-2016:
Database issue is fixed, however it was found that the statistics for first 9 darts do not match yet.
Furthermore the code can possibly be cleaned a fair bit.
** Still to be added **
1. combine th... | Python | zaydzuhri_stack_edu_python |
function format_selector ctx
begin
comment formats are already sorted worst to best
set formats = get ctx string formats at slice : : - 1
comment acodec='none' means there is no audio
set best_video = next generator expression f for f in formats if f at string vcodec != string none and f at string acodec == string no... | def format_selector(ctx):
# formats are already sorted worst to best
formats = ctx.get("formats")[::-1]
# acodec='none' means there is no audio
best_video = next(
f for f in formats if f["vcodec"] != "none" and f["acodec"] == "none"
)
# find compatible audio extension
a... | Python | nomic_cornstack_python_v1 |
function feedback self likes dislikes
begin
raise NotImplementedError
end function | def feedback(self, likes, dislikes):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
from datetime import datetime
function convert_time_to_string dt
begin
return string { hour } : { minute }
end function
function time_has_changed prev_time
begin
return call convert_time_to_string now != prev_time
end function
function ts_to_date timestamp
begin
return call fromtimestamp timestamp
end function | from datetime import datetime
def convert_time_to_string(dt):
return f"{dt.hour}:{dt.minute:02}"
def time_has_changed(prev_time):
return convert_time_to_string(datetime.now()) != prev_time
def ts_to_date(timestamp):
return datetime.fromtimestamp(timestamp)
| Python | zaydzuhri_stack_edu_python |
comment This Simulation Created by Vijay Kag
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import math as mt
from physical_objects import circle , sline , springcoil
class Two_Body_Interaction
begin
function __init__ self interaction_const=- 20 mass1=1 mass2=1 position1=tup... | #This Simulation Created by Vijay Kag
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import math as mt
from physical_objects import circle,sline,springcoil
class Two_Body_Interaction:
def __init__(self,interaction_const=-20,mass1=1,mass2=1,position1=(0,0),positio... | Python | zaydzuhri_stack_edu_python |
function detect_and_open_fd comm args
begin
set part_header = dict
set part_table = dict
for tuple dev opencmd in items disk_opener
begin
set disk_fd = call laf_open_disk comm opencmd
if disk_fd
begin
debug string opened a disk_fd: %i on %s % tuple disk_fd dev
comment detect the device type and based on that set the ... | def detect_and_open_fd(comm, args):
part_header = {}
part_table = {}
for dev,opencmd in disk_opener.items():
disk_fd = laf_open_disk(comm, opencmd)
if disk_fd:
_logger.debug("opened a disk_fd: %i on %s" % (disk_fd, dev))
# detect the device type and based on that set the block ... | Python | nomic_cornstack_python_v1 |
class ExoWhile
begin
function calcul self notes
begin
set i = 0
print string minimum : + string min notes
print string maximum : + string max notes
for note in notes
begin
set i = i + note
end
print string moyenne : + string round i / length notes 2
end function
function threeNote self
begin
set i = 0
set notes = list ... | class ExoWhile:
def calcul(self, notes):
i = 0
print("minimum : " + str(min(notes)))
print("maximum : " + str(max(notes)))
for note in notes:
i += note
print("moyenne : " + str(round(i / len(notes), 2)))
def threeNote(self):
i = 0
notes = [... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import struct
set MSG_TYPES = dict 1 string PING ; 2 string PONG ; 16 string Weather Report ; 17 string Weather Report Request
set PAYLOAD_TYPES = dict 32 string Outside Temperature ; 33 string Outside Humidity ; 34 string Outside Pressure ; 80 string Inside Temperature ; 81 string Inside ... | #!/usr/bin/env python3
import struct
MSG_TYPES = {0x01: 'PING',
0x02: 'PONG',
0x10: 'Weather Report',
0x11: 'Weather Report Request'}
PAYLOAD_TYPES = {0x20: 'Outside Temperature',
0x21: 'Outside Humidity',
0x22: 'Outside Pressure',
... | Python | zaydzuhri_stack_edu_python |
function _add_noise self y
begin
if not _noise_scale
begin
return y
end
set y = y + array list comprehension random choice range - _noise_scale _noise_scale for i in range length y
return y
end function | def _add_noise(self, y):
if not self._noise_scale:
return y
y += np.array(
[
np.random.choice(range(-self._noise_scale, self._noise_scale))
for i in range(len(y))
]
)
return y | Python | nomic_cornstack_python_v1 |
set iterator = generator expression string Hello for i in range 3
print next iterator
print next iterator
print next iterator
print next iterator | iterator= ("Hello" for i in range(3))
print(next(iterator))
print(next(iterator))
print(next(iterator))
print(next(iterator)) | Python | zaydzuhri_stack_edu_python |
function _set_state self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=yc_state_openconfig_access_points__access_points_access_point_radios_radio_neighbors_neighbor_state is_container=string container yang_name=string state parent=self pat... | def _set_state(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_access_points__access_points_access_point_radios_radio_neighbors_neighbor_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, ext... | Python | nomic_cornstack_python_v1 |
for tuple k v in items d
begin
set d1 at v = k
end
print d
print d1 | for k,v in d.items():
d1[v]=k
print(d)
print(d1)
| Python | zaydzuhri_stack_edu_python |
comment FOR COLOURING CELLS IN SIMULATION DF
function crColour val
begin
if val > 0
begin
set color = string green
end
else
if val == 0
begin
set color = string green
end
else
begin
set color = string red
end
return string color: %s % color
end function
function crBackground val
begin
if val > 0
begin
set color = strin... | ######################################
# FOR COLOURING CELLS IN SIMULATION DF
######################################
def crColour(val):
if val > 0: color = 'green'
elif val == 0: color = 'green'
else: color = 'red'
return 'color: %s' % color
def crBackground(val):
if val > 0: color = '#adfc83'
... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
set col1 = list comprehension i for i in range 4
set col2 = list comprehension decimal i ^ 2 for i in range 4
set col3 = list string cat1 string cat2 string cat3 string cat1
print col1
set MyDataframe = call DataFrame dict string INDEX col1 ; string DATE timestamp pd string 201301... | import pandas as pd
import numpy as np
col1 = [i for i in range(4)]
col2 = [float(i**2) for i in range(4)]
col3 = ['cat1', 'cat2', 'cat3', 'cat1']
print(col1)
MyDataframe = pd.DataFrame({'INDEX': col1,
'DATE': pd.Timestamp('20130102'),
'SQUARED': col2,
... | Python | zaydzuhri_stack_edu_python |
function all items
begin
return all items
end function | def all(items):
return all(items) | Python | nomic_cornstack_python_v1 |
function optional_function func
begin
function wrapper x *args **kwargs
begin
if x is none
begin
return none
end
return call func x *args keyword kwargs
end function
return wrapper
end function | def optional_function(func):
def wrapper(x, *args, **kwargs):
if x is None:
return None
return func(x, *args, **kwargs)
return wrapper | Python | nomic_cornstack_python_v1 |
function use self
begin
set image = copy item_img at type
add group self layer=layer
set dir = lastdir
set angle = 0
set angle = angle + angle2
set image = call rotate image angle
set rect = call get_rect
set hit_rect = rect
set center = center
end function | def use(self):
self.image = self.game.imageLoader.item_img[self.type].copy()
self.group.add(self, layer=self.layer)
self.dir = self.player.lastdir
self.angle = 0
self.angle += self.player.angle2
self.image = pygame.transform.rotate(self.image, self.angle)
sel... | Python | nomic_cornstack_python_v1 |
function secret_key_generator size=32 chars=ALLOWED_CHARS
begin
return join string generator expression random choice chars for c in range size
end function | def secret_key_generator(size=32, chars=ALLOWED_CHARS):
return ''.join(random.SystemRandom().choice(chars) for c in range(size)) | Python | nomic_cornstack_python_v1 |
import os
import sys
from random import randint
function _make_joke_list jokes_text
begin
set joke_list = list
while jokes_text != string
begin
append joke_list jokes_text at slice index jokes_text string < + 1 : index jokes_text string > :
set jokes_text = jokes_text at slice index jokes_text string > + 1 : :
end
... | import os
import sys
from random import randint
def _make_joke_list(jokes_text):
joke_list = []
while jokes_text != '':
joke_list.append(jokes_text[jokes_text.index('<') + 1:jokes_text.index('>')])
jokes_text = jokes_text[jokes_text.index('>') + 1:]
return joke_list
def gene... | Python | zaydzuhri_stack_edu_python |
function test_set_config__unsupported_datafile_version self
begin
set test_datafile = dumps config_dict_with_features
set mock_logger = call Mock
set mock_notification_center = call Mock
with patch string optimizely.config_manager.BaseConfigManager._validate_instantiation_options
begin
set project_config_manager = call... | def test_set_config__unsupported_datafile_version(self):
test_datafile = json.dumps(self.config_dict_with_features)
mock_logger = mock.Mock()
mock_notification_center = mock.Mock()
with mock.patch('optimizely.config_manager.BaseConfigManager._validate_instantiation_options'):
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment @Time : 2019/6/10 23:49
comment @Author : songxy
comment @Email : 2953xx998@qq.com
comment @File : 3.fibnaci数列.py
set a = 1
set b = 1
for i in range 5000
begin
set tuple a b = tuple b a + b
end
for else
begin
print b
end
function fbnc num
begin
if num == 1 or num == 2
begin
return ... | # -*- coding: utf-8 -*-
# @Time : 2019/6/10 23:49
# @Author : songxy
# @Email : 2953xx998@qq.com
# @File : 3.fibnaci数列.py
a = 1
b = 1
for i in range(5000):
a,b = b,a+b
else:
print(b)
def fbnc(num):
if num == 1 or num == 2:
return 1
else:
return fbnc(num -1) + fbnc(num-2)
pri... | Python | zaydzuhri_stack_edu_python |
function _set_priority_configured self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=YANGBool is_leaf=true yang_name=string priority-configured rest_name=string priority-configured parent=self path_helper=_path_helper extmethods=_extmethod... | def _set_priority_configured(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="priority-configured", rest_name="priority-configured", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=T... | Python | nomic_cornstack_python_v1 |
from json import loads as jsonload
from urllib.request import urlopen
from django.http import HttpResponse
from models import Product
set FAPI_URL = string https://api.upcitemdb.com/prod/trial/lookup?upc=
function get_product_info upc
begin
set url = string { FAPI_URL } { upc }
print url
return call jsonload title read... | from json import loads as jsonload
from urllib.request import urlopen
from django.http import HttpResponse
from .models import Product
FAPI_URL = 'https://api.upcitemdb.com/prod/trial/lookup?upc='
def get_product_info(upc):
url = f'{FAPI_URL}{upc}'
print(url)
return jsonload(urlopen(url).read().title())
def get_... | Python | zaydzuhri_stack_edu_python |
function Centroid_dLdt termpts1 termpts2 time_interval vx_func vy_func
begin
set term1 = call LineString termpts1
set term1_centr = centroid
set centr1_coords = squeeze np list coords
set term2 = call LineString termpts2
set term2_centr = centroid
set centr2_coords = squeeze np list coords
set disp_vector = centr1_coor... | def Centroid_dLdt(termpts1, termpts2, time_interval, vx_func, vy_func):
term1 = geom.LineString(termpts1)
term1_centr = term1.centroid
centr1_coords = np.squeeze(list(term1_centr.coords))
term2 = geom.LineString(termpts2)
term2_centr = term2.centroid
centr2_coords = np.squeeze(list(term2_centr.c... | Python | nomic_cornstack_python_v1 |
function forward self letter
begin
if letter in ascii_lowercase
begin
return call unpos forward_map at call pos letter + position % 26 - position
end
else
begin
return string
end
end function | def forward(self, letter):
if letter in string.ascii_lowercase:
return unpos((self.forward_map[(pos(letter) + self.position) % 26] - self.position))
else:
return '' | Python | nomic_cornstack_python_v1 |
import numpy as np
set x1 = array list list 1 2 list 3 4
print x1
print call ravel
set x2 = array list list 1 2 3 list 4 5 6 list 7 8 9
print x2
print call ravel
print flatten x2 | import numpy as np
x1 = np.array([[1, 2], [3, 4]])
print(x1)
print(x1.ravel())
x2 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(x2)
print(x2.ravel())
print(x2.flatten()) | Python | zaydzuhri_stack_edu_python |
function unique_group groups
begin
set ugroups = set groups
set ugroups = ugroups - set tuple none
set ugroups = list ugroups
sort ugroups
return ugroups
end function | def unique_group(groups):
ugroups = set(groups)
ugroups -= set((None,))
ugroups = list(ugroups)
ugroups.sort()
return ugroups | Python | nomic_cornstack_python_v1 |
function create_private self fqdomain availability_zone
begin
set body = dict string domain_entry dict string scope string private ; string availability_zone availability_zone
return call _update string /os-floating-ip-dns/%s % call _quote_domain fqdomain body string domain_entry
end function | def create_private(self, fqdomain, availability_zone):
body = {'domain_entry': {'scope': 'private',
'availability_zone': availability_zone}}
return self._update('/os-floating-ip-dns/%s' % _quote_domain(fqdomain),
body,
... | Python | nomic_cornstack_python_v1 |
import os
import re
import sys
import time
from pprint import pprint as echo
class TextProcessor
begin
function __init__ self
begin
set WrapperMap = dict string WrapTextBtn_1 string 「」 ; string WrapTextBtn_2 string ()
set WrapperShortcutMap = dict string WrapTextBtn_1 string Ctrl+= ; string WrapTextBtn_2 string Ctrl+9
... | import os
import re
import sys
import time
from pprint import pprint as echo
class TextProcessor():
def __init__(self):
self.WrapperMap = {
'WrapTextBtn_1': '「」',
'WrapTextBtn_2': '()'
}
self.WrapperShortcutMap = {
'WrapTextBtn_1': 'Ctrl+=',
... | Python | zaydzuhri_stack_edu_python |
function _flatten_log L
begin
for i in L
begin
if is instance i TaskLog
begin
yield call _to_dict
end
else
begin
yield from call _flatten_log i
end
end
end function | def _flatten_log(L):
for i in L:
if isinstance(i, TaskLog):
yield i._to_dict()
else:
yield from _flatten_log(i) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment encoding: utf-8
string @version: python3 @author: ‘aprilkuo‘ @contact: aprilvkuo@live.com @site: @software: PyCharm Community Edition @file: main.py @time: 2020/5/3 20:37
comment print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package... | #!/usr/bin/env python
# encoding: utf-8
"""
@version: python3
@author: ‘aprilkuo‘
@contact: aprilvkuo@live.com
@site:
@software: PyCharm Community Edition
@file: main.py
@time: 2020/5/3 20:37
"""
# print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))
import n... | Python | zaydzuhri_stack_edu_python |
function GetShows self start=0 end=0 sortmethod=string title sortorder=string ascending hidewatched=0 filter=string
begin
debug string Fetching TV Shows
try
begin
set xbmc = call Server call url string /jsonrpc true
set sort = dict string order sortorder ; string method sortmethod ; string ignorearticle true
set proper... | def GetShows(self, start=0, end=0, sortmethod='title', sortorder='ascending', hidewatched=0, filter=''):
self.logger.debug("Fetching TV Shows")
try:
xbmc = Server(self.url('/jsonrpc', True))
sort = {'order': sortorder, 'method': sortmethod, 'ignorearticle': True}
prop... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sat Nov 10 18:09:55 2018 @author: iosu
import requests
from bs4 import BeautifulSoup
import time
import csv
function extraer_productos url fecha
begin
print string -------------------------------
print url
set products = list
set page = get requests url
set soup = call B... | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 10 18:09:55 2018
@author: iosu
"""
import requests
from bs4 import BeautifulSoup
import time
import csv
def extraer_productos(url, fecha):
print('-------------------------------')
print(url)
products = [];
page = requests.get( url )
soup = BeautifulSo... | Python | zaydzuhri_stack_edu_python |
string Representation of 3D Shape This file contains the script for calculating the predictions of pixel-based model for experiment 2 on view-dependency. Created on Jun 10, 2016 Goker Erdogan https://github.com/gokererdogan/
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from plot.plot_viewpoint... | """
Representation of 3D Shape
This file contains the script for calculating the predictions of pixel-based model for experiment 2 on view-dependency.
Created on Jun 10, 2016
Goker Erdogan
https://github.com/gokererdogan/
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from plot.plot_view... | Python | zaydzuhri_stack_edu_python |
function _get_gos_tx_drop_cnt self
begin
return __gos_tx_drop_cnt
end function | def _get_gos_tx_drop_cnt(self):
return self.__gos_tx_drop_cnt | Python | nomic_cornstack_python_v1 |
function deleteConfirm request
begin
set paste = get Paste matchdict at string idContent
if not username and password
begin
return call HTTPFound call route_path string oneContent idContent=_id
end
set lexer = call get_lexer_by_name typeContent stripall=true
set result = call highlight paste at string content lexer for... | def deleteConfirm(request):
paste = Paste.get(request.matchdict['idContent'])
if not(paste.username and paste.password):
return HTTPFound(request.route_path('oneContent', idContent=paste._id))
lexer = get_lexer_by_name(paste.typeContent, stripall=True)
result = highlight(paste['content'], lex... | Python | nomic_cornstack_python_v1 |
import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
comment 定义训练设备
set device = device string cuda:0
comment 添加SummaryWriter
from torch.utils.tensorboard import SummaryWriter
set writer = call SummaryWriter string logs
comment 模型
class FirstNet extends Module
begin
function __in... | import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
# 定义训练设备
device = torch.device("cuda:0")
# 添加SummaryWriter
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter("logs")
# 模型
class FirstNet(nn.Module):
def __init__(self):
super(FirstNet, sel... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function isCousins self root x y
begin
set queue = deque list tuple root none
set tuple x_p y_p = tuple none none
while queue
begin
for i in range length queue
begin
set tuple node parent = call popleft
if val == x
begin
set x_p = parent
end
if val == y
begin
set y_p = parent
end
if left
begin
set ... | class Solution:
def isCousins(self, root: TreeNode, x: int, y: int) -> bool:
queue = collections.deque([(root, None)])
x_p, y_p = None, None
while queue:
for i in range(len(queue)):
node, parent = queue.popleft()
if node.val == x:
... | Python | zaydzuhri_stack_edu_python |
import requests
from PIL import Image
from io import BytesIO
comment Target image URL
set url = string https://i.imgur.com/EdAGGFS.jpg
comment Get the text after the last slash in the URL, that is, the file name,\
comment which includes its extension
set file_name = split url string / at - 1
comment Make a GET request ... | import requests
from PIL import Image
from io import BytesIO
# Target image URL
url = "https://i.imgur.com/EdAGGFS.jpg"
# Get the text after the last slash in the URL, that is, the file name,\
# which includes its extension
file_name = url.split("/")[-1]
# Make a GET request for the URL
img_request = requests.get(url... | Python | zaydzuhri_stack_edu_python |
function remakewig wigFile genomeSize=4639675
begin
set startTime = time
comment This is how a file must start to be recognizable by MochiView
set s = string track type=wiggle_0 variableStep chrom=NC_000913_2
comment Initialize the dictionary. Open the old wig file and create and open the new wig file.
set allPoints = ... | def remakewig(wigFile, genomeSize=4639675):
startTime= time.time()
#This is how a file must start to be recognizable by MochiView
s = "track type=wiggle_0\nvariableStep chrom=NC_000913_2\n"
#Initialize the dictionary. Open the old wig file and create and open the new wig file.
allPoints = {}
my... | Python | nomic_cornstack_python_v1 |
function compose_before_inplace self transform
begin
if is instance transform composes_inplace_with
begin
call _compose_before_inplace transform
end
else
begin
raise call ValueError format string {} can only compose inplace with {} - not {} type self composes_inplace_with type transform
end
end function | def compose_before_inplace(self, transform):
if isinstance(transform, self.composes_inplace_with):
self._compose_before_inplace(transform)
else:
raise ValueError(
"{} can only compose inplace with {} - not "
"{}".format(type(self), self.composes_in... | Python | nomic_cornstack_python_v1 |
while true
begin
print call xf
end | while True:
print(xf()) | Python | zaydzuhri_stack_edu_python |
function render_env_spec spec_str
begin
set env_spec_list = parse spec_str
set html_output = call render_to_html env_spec_list
return html_output
end function | def render_env_spec(spec_str):
env_spec_list = parse(spec_str)
html_output = render_to_html(env_spec_list)
return html_output | Python | nomic_cornstack_python_v1 |
comment deleting element from the dictionary
set myDict = dict string apple string red ; string grapes string green ; string banana string yellow
print myDict
pop myDict string grapes
print myDict | #deleting element from the dictionary
myDict={"apple":"red","grapes":"green","banana":"yellow"}
print(myDict)
myDict.pop("grapes")
print(myDict)
| Python | zaydzuhri_stack_edu_python |
import os
from django.core.management.base import BaseCommand
from django.conf import settings
from telegram.ext import *
from telegram.utils.request import Request
from telegram import Bot , Update
from buttons import keyboard_1 , keyboard_2 , get_keyboard
from telegram import KeyboardButton , ReplyKeyboardMarkup , In... | import os
from django.core.management.base import BaseCommand
from django.conf import settings
from telegram.ext import *
from telegram.utils.request import Request
from telegram import Bot, Update
from .buttons import keyboard_1, keyboard_2,get_keyboard
from telegram import KeyboardButton, ReplyKeyboardMarkup,Inline... | Python | zaydzuhri_stack_edu_python |
function standby_site_name standby_mgmt_session
begin
return string site-b
end function | def standby_site_name(standby_mgmt_session):
return 'site-b' | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
import math
set vals = list
for _ in range 5
begin
set num = integer input
append vals num
end
set a = ceil vals at 1 / vals at 3
set b = ceil vals at 2 / vals at 4
if a > b
begin
set l = vals at 0 - a
end
else
begin
set l = vals at 0 - b
end
print l | # coding: utf-8
import math
vals = []
for _ in range(5):
num = int(input())
vals.append(num)
a = math.ceil(vals[1] / vals[3])
b = math.ceil(vals[2] / vals[4])
if a > b:
l = vals[0] - a
else:
l = vals[0] - b
print(l)
| Python | zaydzuhri_stack_edu_python |
function add_credit_card_view self
begin
call clear_screen
print string _ _ _ ___ _ _ _ ___ _ /_\ __| |__| | / __|_ _ ___ __| (_) |_ / __|__ _ _ _ __| | / _ \/ _` / _` | | (__| '_/ -_) _` | | _| | (__/ _` | '_/ _` | /_/ \_\__,_\__,_| \___|_| \___\__,_|_|\__| \___\__,_|_| \__,_|
end function | def add_credit_card_view(self):
self._system.clear_screen()
print( "\t _ _ _ ___ _ _ _ ___ _ \n"
"\t /_\ __| |__| | / __|_ _ ___ __| (_) |_ / __|__ _ _ _ __| |\n"
"\t / _ \/ _` / _` | | (__| '_/ -_) _` | | _| | (__/ _` | '_/... | Python | nomic_cornstack_python_v1 |
function make_grp self name=string grp
begin
if _subs is true
begin
set name = string subgrp
end
set base at name = call get_group_array
end function | def make_grp(self, name='grp'):
if self._subs is True:
name = 'subgrp'
self.base[name] = self.get_group_array() | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment http://stackoverflow.com/questions/20081866/generating-and-plotting-a-fourier-series-square-wave-in-python
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
set list_ = list
set phase = integer call raw_input string Phase =
set numofpts = 1000... | #!/usr/bin/env python
#
# http://stackoverflow.com/questions/20081866/generating-and-plotting-a-fourier-series-square-wave-in-python
#
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
list_ = []
phase = int(raw_input('Phase = '))
numofpts = 1000
#numofpts = int(raw_input('Numbe... | Python | zaydzuhri_stack_edu_python |
function update_html_content part this_disclaimer_text this_footer_text
begin
set html_content = call get_content
set soup = call BeautifulSoup html_content string html.parser
set html_disclaimer = format disclaimer_html_template this_disclaimer_text
set disclaimer_tag = call BeautifulSoup html_disclaimer string html.p... | def update_html_content(part, this_disclaimer_text, this_footer_text):
html_content = part.get_content()
soup = BeautifulSoup(html_content, "html.parser")
html_disclaimer = disclaimer_html_template.format(this_disclaimer_text)
disclaimer_tag = BeautifulSoup(html_disclaimer, "html.parser")
html_foot... | Python | nomic_cornstack_python_v1 |
set dicaca = dict string personas list
set dicaca2 = dict string nombre string pedro ; string apellido string rodriguez ; string nacimiento string nunca
append dicaca at string personas dicaca2
print dicaca | dicaca = {'personas':[]}
dicaca2= {
'nombre':'pedro',
'apellido':'rodriguez',
'nacimiento':'nunca'
}
dicaca['personas'].append(dicaca2)
print(dicaca) | Python | zaydzuhri_stack_edu_python |
function get_spelling self
begin
return sp
end function | def get_spelling(self):
return self.sp | Python | nomic_cornstack_python_v1 |
function highlightCtabFragmentSvg
begin
set number_of_files = length files
set data = none
if number_of_files
begin
if number_of_files == 1
begin
set data = read file
end
else
if number_of_files == 2
begin
set data = read file
set smarts = read file
set params at string smarts = smarts
end
end
else
begin
set data = rea... | def highlightCtabFragmentSvg():
number_of_files = len(request.files)
data = None
if number_of_files:
if number_of_files == 1:
data = request.files.values()[0].file.read()
elif number_of_files == 2:
data = request.files['file'].file.read()
smarts = request... | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function decompressRLElist self nums
begin
set ans = list
for i in range length nums - 1
begin
if i % 2 == 0
begin
append ans nums at i * list nums at i + 1
end
end
set zq = list
for k in range length ans
begin
set zq = zq + ans at k
end
return zq
end function
end class
st... | from typing import List
class Solution:
def decompressRLElist(self, nums: List[int]) -> List[int]:
ans = []
for i in range(len(nums)-1):
if i%2 == 0:
ans.append(nums[i]*[nums[i+1]])
zq = []
for k in range(len(ans)):
zq += ans[k]
retur... | Python | zaydzuhri_stack_edu_python |
function get_center_tile self
begin
set mid_x = integer length map / 2
set mid_y = integer length map at 0 / 2
return map at mid_x at mid_y
end function | def get_center_tile(self):
mid_x = int(len(self.map)/2)
mid_y = int(len(self.map[0])/2)
return self.map[mid_x][mid_y] | Python | nomic_cornstack_python_v1 |
function read_times self filename=none
begin
string Read true time step data from individual time steps. Returns ------- steps : array The time steps. times : array The times of the time steps. nts : array The normalized times of the time steps, in [0, 1]. Notes ----- The default implementation returns empty arrays.
se... | def read_times(self, filename=None):
"""
Read true time step data from individual time steps.
Returns
-------
steps : array
The time steps.
times : array
The times of the time steps.
nts : array
The normalized times of the time... | Python | jtatman_500k |
comment ! /usr/bin/env python
comment coding=utf-8
class node
begin
function __init__ self s
begin
set data = s
set left = none
set right = none
end function
end class
function build_tree
begin
set tree_data = list string A string B string C string D string E string F string G string H string I
set node_list = list
fo... | #! /usr/bin/env python
#coding=utf-8
class node:
def __init__(self, s):
self.data = s
self.left = None
self.right = None
def build_tree():
tree_data = ['A','B','C','D','E','F','G','H','I']
node_list = []
for i in range(0, len(tree_data)):
if(i == 0):
root = node(tree_data[i])
root.l... | Python | zaydzuhri_stack_edu_python |
function remote_url self
begin
set cmd = string svn info | grep "^Repository Root:"
return strip split call sh cmd shell=true string : 1 at 1
end function | def remote_url(self):
cmd = 'svn info | grep "^Repository Root:"'
return (
self.sh(cmd, shell=True).split(': ', 1)[1]).strip() | Python | nomic_cornstack_python_v1 |
function people self
begin
return dictionary comprehension username : call from_yaml username data for tuple username data in items call _read_file string people.yaml
end function | def people(self):
return {
username: Person.from_yaml(username, data)
for username, data
in self._read_file('people.yaml').items()
} | Python | nomic_cornstack_python_v1 |
class FakeRecipesRepository extends object
begin
string A Fake Recipes repository implementing the basic required functionality for writing unit tests for logic that requires a Recipes repository
set recipes = dict
function find_recipe_by_id self recipe_id
begin
return recipes at recipe_id
end function
function find_r... | class FakeRecipesRepository(object):
"""
A Fake Recipes repository implementing the basic required functionality
for writing unit tests for logic that requires a Recipes repository
"""
recipes = {}
def find_recipe_by_id(self, recipe_id):
return self.recipes[recipe_id]
def f... | Python | zaydzuhri_stack_edu_python |
function AddItem
begin
if get ITEMCODE == string or get ITEMNAME == string or get STATUS == string or get ITEMPRICE == string or get ITEMQUANTITY == string or get STOCKARRIVALDATE == string or get MINIMUMORDER == string or get MAXIMUMORDER == string
begin
call config text=string Please complete the required fie... | def AddItem():
if ITEMCODE.get() == "" or ITEMNAME.get() == "" or STATUS.get() == "" or ITEMPRICE.get() == "" or ITEMQUANTITY.get() == "" or STOCKARRIVALDATE.get() == "" or MINIMUMORDER.get() == "" or MAXIMUMORDER.get() == "":
txt_result.config(text="Please complete the required field!", fg="red")
else... | Python | zaydzuhri_stack_edu_python |
comment return string and length of palindrome; truly terrible running time of O(n^2)
function find_palin start end l
begin
while start != end
begin
set i = start
set k = end
while i < k
begin
if l at i != l at k
begin
break
end
set i = i + 1
set k = k - 1
end
if i >= k
begin
return tuple l at slice start : end + 1 : ... | # return string and length of palindrome; truly terrible running time of O(n^2)
def find_palin(start, end, l):
while (start != end):
i = start
k = end
while (i < k):
if (l[i] != l[k]):
break;
i = i + 1
k = k - 1
if i >= k:
return (l[start:end + 1], end - start + 1)
... | Python | zaydzuhri_stack_edu_python |
function deleted_since self **params
begin
return call _make_request endpoint params
end function | def deleted_since(self, **params):
return self._make_request(self.endpoint, params) | Python | nomic_cornstack_python_v1 |
from datetime import datetime
import pandas as pd
from matplotlib import pyplot
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
comment 数据预处理
comment 加载并解析原始数据,转变成需要的数据集
function resolveData
begin
function parse x
begin
return string parse time x string %Y %m %d %H
end func... | from datetime import datetime
import pandas as pd
from matplotlib import pyplot
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
# 数据预处理
# 加载并解析原始数据,转变成需要的数据集
def resolveData():
def parse(x):
return datetime.strptime(x, '%Y %m %d %H')
dataset = pd.read_csv('... | Python | zaydzuhri_stack_edu_python |
if string_tem == string_tem at slice : : - 1
begin
print 1
set flag = 1
end
set string_list_temporary_1 = list inp
set last_character = inp at length inp - 1
del string_list_temporary_1 at length inp - 1
set string_tem_1 = last_character + join string string_list_temporary_1
if string_tem_1 == string_tem_1 at slice ... | if string_tem == string_tem[::-1]:
print(1)
flag = 1
string_list_temporary_1 = list(inp)
last_character = inp[len(inp) - 1]
del string_list_temporary_1[len(inp)-1]
string_tem_1 = last_character + ''.join(string_list_temporary_1)
if string_tem_1 == string_tem_1[::-1]:
print(1)
flag = 1
if flag == 0:
... | Python | zaydzuhri_stack_edu_python |
comment pylint: disable=redefined-builtin
function id self operator id
begin
call add_filter string id operator id INTEGER
end function | def id(self, operator, id): # pylint: disable=redefined-builtin
self._tql.add_filter('id', operator, id, TQL.Type.INTEGER) | Python | nomic_cornstack_python_v1 |
function interpret_complete_cdf cdfs_p cdfs_v distribution=none
begin
comment Todo: refactor, currently too many possible types of output
if distribution is none
begin
for cdf_p in cdfs_p
begin
comment Last value is the highest
set cdf_p at - 1 = 1
end
return tuple cdfs_p cdfs_v
end
set cdfs = list
if distribution == ... | def interpret_complete_cdf(
cdfs_p: List[Union[list, np.ndarray]],
cdfs_v: List[Union[list, np.ndarray]],
distribution: str = None,
) -> Union[
List[Union[list, np.ndarray]],
Tuple[List[Union[list, np.ndarray]], List[Union[list, np.ndarray]]],
ot.DistributionImplementation,
]:
# Todo: refact... | Python | nomic_cornstack_python_v1 |
function cam_get_autoexposed_image cam shutter=64.0 gain=0 min_shutter=2 max_shutter=2000 min_gain=0 max_gain=24.0 interesting_colours=list 0 1 binning=list 4 4 max_iter=14 min_acceptable_value=100 max_acceptable_value=220 shutter_factor=2.0 gain_increment=6.0 colour_ratio_noise_threshold=0 verbose=false
begin
comment ... | def cam_get_autoexposed_image(cam, shutter=64., gain=0, min_shutter= 2, max_shutter=2000, \
min_gain=0, max_gain=24., interesting_colours = [0,1], binning = [4,4], max_iter = 14, \
min_acceptable_value = 100, max_acceptable_value=220, shutter_factor = 2.0, \
gain_increment = 6.0, colour_ratio_noise_threshold = 0,
v... | Python | nomic_cornstack_python_v1 |
function parse_arguments
begin
import argparse
set parser = call ArgumentParser description=string A COMPSs-Redis Kmeans implementation.
call add_argument string -s string --seed type=int default=0 help=string Pseudo-random seed. Default = 0
call add_argument string -n string --numpoints type=int default=100 help=strin... | def parse_arguments():
import argparse
parser = argparse.ArgumentParser(description='A COMPSs-Redis Kmeans implementation.')
parser.add_argument('-s', '--seed', type=int, default=0,
help='Pseudo-random seed. Default = 0')
parser.add_argument('-n', '--numpoints', type=int, default... | Python | nomic_cornstack_python_v1 |
from mindmap_parser.mindmap import Node , calculate_level
from spesial_asserts import assert_lines_equal
function test_create_node
begin
set node = call Node raw_text=string Node 1
assert raw_text == string Node 1
assert children == list
end function
function test_add_child
begin
set node_1 = call Node raw_text=string... | from mindmap_parser.mindmap import Node, calculate_level
from spesial_asserts import assert_lines_equal
def test_create_node():
node = Node(raw_text='Node 1')
assert node.raw_text == 'Node 1'
assert node.children == []
def test_add_child():
node_1 = Node(raw_text='Node *1*')
node_1_1 = Node(raw_... | Python | zaydzuhri_stack_edu_python |
comment Ingresar por teclado la cantidad de términos a generar de la siguiente serie: 1 7 19 43 91 187 379 763 1531 3067 6139 El primer término es el 1 y cada término se genera como el doble del término anterior más 5. Mostrar la serie por pantalla e informar la suma de los términos generados.
set numero = integer inpu... | #Ingresar por teclado la cantidad de términos a generar de la siguiente serie: 1 7 19 43 91 187 379 763 1531 3067 6139 El primer término es el 1 y cada término se genera como el doble del término anterior más 5. Mostrar la serie por pantalla e informar la suma de los términos generados.
numero = int (input("ingrese un... | Python | zaydzuhri_stack_edu_python |
function _apply_grads variables grads
begin
set v_new = list
for tuple v dv in zip variables grads
begin
if not train_batch_norm and string offset in name or string scale in name
begin
append v_new v
end
else
begin
append v_new v - alpha * dv
end
end
return v_new
end function | def _apply_grads(variables, grads):
v_new = []
for (v, dv) in zip(variables, grads):
if (not self.train_batch_norm and
('offset' in v.name or 'scale' in v.name)):
v_new.append(v)
else:
v_new.append(v - self.alpha * dv)
return v_new | 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.