code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
class ListNode
begin
function __init__ self val=0 next=none
begin
set val = val
set next = next
end function
end class
function mergeLists l1 l2
begin
comment Base case: if either list is empty, return the other list
if not l1
begin
return l2
end
if not l2
begin
return l1
end
comment Compare the values of the heads of ... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeLists(l1, l2):
# Base case: if either list is empty, return the other list
if not l1:
return l2
if not l2:
return l1
# Compare the values of the heads of the two lists... | Python | greatdarklord_python_dataset |
function round_nearest_whole_dollar amount
begin
set amount = call Decimal amount
return call quantize call Decimal string 1 rounding=ROUND_HALF_UP
end function | def round_nearest_whole_dollar(amount):
amount = Decimal(amount)
return amount.quantize(Decimal('1'), rounding=ROUND_HALF_UP) | Python | nomic_cornstack_python_v1 |
import numpy as np
import itertools
from rdkit import Chem
from graphillion import GraphSet
comment 原子番号→色のリスト
set color_dict = dict 1 string silver ; 6 string black ; 9 string deepskyblue ; 17 string lawngreen
function atm_color atomic_no
begin
string 原子番号→色を返す
if atomic_no in color_dict
begin
set color = color_dict a... | import numpy as np
import itertools
from rdkit import Chem
from graphillion import GraphSet
# 原子番号→色のリスト
color_dict = {
1: "silver",
6: "black",
9: "deepskyblue",
17: "lawngreen"
}
def atm_color(atomic_no):
"""
原子番号→色を返す
"""
if atomic_no in color_dict:
color=color_dict[atomic_no... | Python | zaydzuhri_stack_edu_python |
function cross_validation_accuracy clf X labels k
begin
comment TODO
set cv = call KFold n_splits=k
set accuracies = list
for tuple train_ind test_ind in split cv X
begin
fit clf X at train_ind labels at train_ind
set predictions = predict clf X at test_ind
append accuracies call accuracy_score labels at test_ind pred... | def cross_validation_accuracy(clf, X, labels, k):
###TODO
cv = KFold(n_splits=k)
accuracies=[]
for train_ind, test_ind in cv.split(X):
clf.fit(X[train_ind], labels[train_ind])
predictions = clf.predict(X[test_ind])
accuracies.append(accuracy_score(labels[test_ind],predictions))
... | Python | nomic_cornstack_python_v1 |
function get_movement_frame window mqtt_sender
begin
comment Construct the frame to return:
set frame = call Frame window padding=10 borderwidth=5 relief=string ridge
grid
comment Construct the widgets on the frame:
set frame_label = call Label frame text=string Movement
set straight_for_seconds_seconds_label = call La... | def get_movement_frame(window, mqtt_sender):
# Construct the frame to return:
frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
frame.grid()
# Construct the widgets on the frame:
frame_label = ttk.Label(frame, text="Movement")
straight_for_seconds_seconds_label = ttk.Label(f... | Python | nomic_cornstack_python_v1 |
function test_user_register_bad_request self
begin
set response = post USER_REGISTER_URL data=invalid_user_data format=string json
assert equal status_code HTTP_400_BAD_REQUEST
end function | def test_user_register_bad_request(self):
response = self.client.post(
CONSTS.USER_REGISTER_URL,
data=self.invalid_user_data,
format='json'
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) | Python | nomic_cornstack_python_v1 |
string gen cohen, connor ciccone, nick barnes, ryan cole card game hackNA
import pygame , sys , math , random , time
comment Initializing game engine
call init
call init
comment Set up drawing surface
set w = 800
set h = 600
set size = tuple w h
set surface = call set_mode size
comment Set window title bar
call set_cap... | '''
gen cohen, connor ciccone, nick barnes, ryan cole
card game
hackNA
'''
import pygame, sys, math, random, time
#Initializing game engine
pygame.init()
pygame.mixer.init()
#Set up drawing surface
w = 800
h = 600
size = (w,h)
surface = pygame.display.set_mode(size)
#Set window title bar
pygame.d... | Python | zaydzuhri_stack_edu_python |
comment Esse app foi desenvoldo com o objetivo de facilitar as operações financeiras da Plumeria Arte e Design
comment IMPORTÇÕES
import PySimpleGUI as sg
comment TELA CONVITES
comment Tema de Cores
call theme string LightBrown9
set img = list list call Image string C:\Users\ULTRABOOK\Desktop\projetos\programacao\Cpad\... | #Esse app foi desenvoldo com o objetivo de facilitar as operações financeiras da Plumeria Arte e Design
#IMPORTÇÕES
import PySimpleGUI as sg
#TELA CONVITES
sg.theme('LightBrown9') # Tema de Cores
img = [ [sg.Image(r'C:\Users\ULTRABOOK\Desktop\projetos\programacao\Cpad\data\logo250x250.png',size=(250,250)... | Python | zaydzuhri_stack_edu_python |
function getaverage lines
begin
set num = 0
set whole = 0
for line in lines
begin
set line = integer line
set num = num + 1
set whole = whole + line
end
set average = integer whole / num
return average
end function
set f1 = open string C:/Users/강민주/Desktop/대학/동아리/포리프/파이썬 스터디/sample.txt string r
set lines = read lines f... | def getaverage (lines):
num=0
whole=0
for line in lines:
line=int(line)
num+=1
whole+=line
average=int(whole/num)
return average
f1=open("C:/Users/강민주/Desktop/대학/동아리/포리프/파이썬 스터디/sample.txt",'r')
lines=f1.readlines()
average=getaverage(lines)
print("평균은 ... | Python | zaydzuhri_stack_edu_python |
function AccessSelections self TopDoc=defaultNamedNotOptArg Component=defaultNamedNotOptArg
begin
return call InvokeTypes 1 LCID 1 tuple 11 0 tuple tuple 9 1 tuple 9 1 TopDoc Component
end function | def AccessSelections(self, TopDoc=defaultNamedNotOptArg, Component=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(1, LCID, 1, (11, 0), ((9, 1), (9, 1)),TopDoc
, Component) | Python | nomic_cornstack_python_v1 |
function failure self text msg=none type_=string failure
begin
set fail = call Failure msg or string { name } issues type_
call _result fail text
end function | def failure(self, text, msg=None, type_="failure"):
fail = Failure(msg or f'{type(self).name} issues', type_)
self._result(fail, text) | Python | nomic_cornstack_python_v1 |
import csv
import matplotlib.pyplot as plt
import numpy as np
function mod x y
begin
set result = list
for tuple _x _y in zip x y
begin
append result _x ^ 2 + _y ^ 2 ^ 0.5
end
return result
end function
comment Specifying formatting for axis
set axis_label_font = dict string fontname string serif ; string size 18
set ... | import csv
import matplotlib.pyplot as plt
import numpy as np
def mod(x, y):
result = []
for _x, _y in zip(x, y):
result.append((_x**2 + _y**2) ** 0.5)
return result
# Specifying formatting for axis
axis_label_font = {'fontname': 'serif','size': 18}
axes_tick_font = {'fontname': 'serif', 'fontsi... | Python | zaydzuhri_stack_edu_python |
function parse_numeric numeric
begin
if numeric at 0 == string -
begin
set polarity = 1
set numeric = left strip numeric string -
set numeric = left strip numeric string 0
end
else
begin
set polarity = 0
end
set digits = list
for character in numeric
begin
try
begin
append digits integer character 10
end
except ValueE... | def parse_numeric(numeric: str):
if numeric[0] == '-':
polarity = 1
numeric = numeric.lstrip('-')
numeric = numeric.lstrip('0')
else:
polarity = 0
digits = []
for character in numeric:
try:
digits.append(int(character, 10))
except ... | Python | nomic_cornstack_python_v1 |
import sys
set input = readline
function find_parent parent x
begin
if parent at x != x
begin
set parent at x = call find_parent parent parent at x
end
return parent at x
end function
function union parent a b
begin
set a = call find_parent parent a
set b = call find_parent parent b
if a < b
begin
set parent at b = a
e... | import sys
input = sys.stdin.readline
def find_parent(parent,x):
if(parent[x]!=x):
parent[x]=find_parent(parent,parent[x])
return parent[x]
def union(parent,a,b):
a=find_parent(parent,a)
b=find_parent(parent,b)
if(a<b):
parent[b]=a
else:
parent[a]=b
edges=[]
n,m=map(int... | Python | zaydzuhri_stack_edu_python |
function on_pushVar self
begin
if not exists path binPath
begin
set mess = string !!! ERROR: rndBin path not found, check __init__.py !!!
call _defaultErrorDialog mess mainUi
end
else
begin
set tmpPath = join path userBinPath string tmp
call mkPathFolders binPath tmpPath
set tmpFile = join path tmpPath string varBuffer... | def on_pushVar(self):
if not os.path.exists(grapher.binPath):
mess = "!!! ERROR: rndBin path not found, check __init__.py !!!"
self.mainUi._defaultErrorDialog(mess, self.mainUi)
else:
tmpPath = os.path.join(self.grapher.userBinPath, 'tmp')
pFile.mkPathFold... | Python | nomic_cornstack_python_v1 |
function description_in self description_in
begin
set _description_in = description_in
end function | def description_in(self, description_in):
self._description_in = description_in | Python | nomic_cornstack_python_v1 |
comment 40 rows
import helpers
function get_new_line line
begin
set traps = list tuple string ^ string ^ string . tuple string . string ^ string ^ tuple string ^ string . string . tuple string . string . string ^
set data = list line
insert data 0 string .
append data string .
set result = list
for tuple x y z in zip d... | # 40 rows
import helpers
def get_new_line(line):
traps = [("^", "^", "."), (".", "^", "^"), ("^", ".", "."), (".", ".", "^")]
data = list(line)
data.insert(0, ".")
data.append(".")
result = list()
for (x, y, z) in zip(data, data[1:], data[2:]):
token = "^" if (x, y, z) in traps else... | Python | zaydzuhri_stack_edu_python |
comment Strings
comment 'hello' is the same as "hello"
comment a = "Hello"
comment print(a)
comment Multiline Strings
comment b = """Lorem ipsum dolor sit amet,
comment consectetur adipiscing elit,
comment sed do eiusmod tempor incididunt
comment ut labore et dolore magna aliqua. """
comment print(b)
comment c = '''Lor... | # Strings
# 'hello' is the same as "hello"
# a = "Hello"
# print(a)
# Multiline Strings
# b = """Lorem ipsum dolor sit amet,
# consectetur adipiscing elit,
# sed do eiusmod tempor incididunt
# ut labore et dolore magna aliqua. """
# print(b)
# c = '''Lorem ipsum dolor sit amet,
# # consectetur adipiscing elit,
# # ... | Python | zaydzuhri_stack_edu_python |
function _decorated self cls=none instance=none
begin
return call _deco _func
end function | def _decorated(self, cls=None, instance=None):
return self._deco(self._func) | Python | nomic_cornstack_python_v1 |
import random
import string
set random_string = join string random choices ascii_letters + digits k=10
print random_string | import random
import string
random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=10))
print(random_string)
| Python | jtatman_500k |
set tuple A B = map int split input
if absolute A - B % 2 == 1
begin
print string IMPOSSIBLE
end
else
begin
print absolute A - B // 2 + min A B
end | A,B = map(int,input().split())
if(abs(A-B) % 2 == 1):
print("IMPOSSIBLE")
else:
print((abs(A-B)//2) + min(A,B)) | Python | zaydzuhri_stack_edu_python |
comment -*-coding:utf-8-*-
import pickle
import os , platform , time , re
import webbrowser
import pdb
from functools import reduce
set __all__ = list string quicksave string quickload string beep string inherit_docstring_from string match_money string load_samplepage string browselink string browsepage
function quicks... | #-*-coding:utf-8-*-
import pickle
import os,platform,time,re
import webbrowser
import pdb
from functools import reduce
__all__=['quicksave','quickload','beep','inherit_docstring_from','match_money',\
'load_samplepage','browselink','browsepage']
def quicksave(filename,obj):
'''Save an instance.'''
f=o... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
string Aplicações distribuídas - Projeto 1 - lock_stub.py Grupo: 3 Membros: Francisco Pimenta 54973, Pedro Quintão 54971
import net_client
class Lock_stub
begin
function __init__ self address port
begin
set conn_sock = call server address port
end function
function... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Aplicações distribuídas - Projeto 1 - lock_stub.py
Grupo: 3
Membros: Francisco Pimenta 54973, Pedro Quintão 54971
"""
import net_client
class Lock_stub:
def __init__(self, address, port):
self.conn_sock = net_client.server(address, port)
def disconnect... | Python | zaydzuhri_stack_edu_python |
import numpy as np
comment PARAMETER VALUES AND FUNCTIONS USED FOR ROSSBY WAVE SCRIPTS
comment SET DIMENSIONAL SCALES FOR VARIABLES
comment (m) typical length scale
set L = 1000000.0
comment (s^-1) Coriolis parameter
set f0 = 0.0001
comment (s) typical time scale
set T = 1.0 / f0
comment (m^-1) horizontal wavenumber
se... | import numpy as np
#PARAMETER VALUES AND FUNCTIONS USED FOR ROSSBY WAVE SCRIPTS
#SET DIMENSIONAL SCALES FOR VARIABLES
L = 1e6 #(m) typical length scale
f0 = 1e-4 #(s^-1) Coriolis parameter
T = 1./f0 #(s) typical time scale
k = 1e-5 #(m^-1) horizontal wavenumber
a = 3e4 #(m) deformation radius
psi0 = 3e4 #(m^2*s^-1) w... | Python | zaydzuhri_stack_edu_python |
string Testing file for weather server sends random data to the server via POST request acts as a fake weather station Written by: Sam Hillcoat Last Modified: 26/12/20 9:25 PM
import requests , time
from random import randint
comment URL = "https://deviotweather.com/senddata"
set URL = string http://127.0.0.1:5000/send... | """
Testing file for weather server
sends random data to the server via POST request
acts as a fake weather station
Written by: Sam Hillcoat
Last Modified: 26/12/20 9:25 PM
"""
import requests, time
from random import randint
#URL = "https://deviotweather.com/senddata"
URL = "http://127.0.0.1:5000/senddata"
#URL = ... | Python | zaydzuhri_stack_edu_python |
comment --------------------------------------------------------------------- ###
comment This script commands the UAV to takeoff, fly to a defined distance, and
comment return to its origin and land. This is done in SLAM mode.
comment Call the script with the correct args to set the flight path.
comment Example:
comme... | ### --------------------------------------------------------------------- ###
#
# This script commands the UAV to takeoff, fly to a defined distance, and
# return to its origin and land. This is done in SLAM mode.
# Call the script with the correct args to set the flight path.
#
# Example:
#
# sudo python3 slam/tes... | Python | zaydzuhri_stack_edu_python |
function unitVectorYawCenter self
begin
set AB = nodes at 1 - nodes at 0
set AG = nodes at 6 - nodes at 0
set point = AG / 2 + nodes at 0
set axis = AB
set unit = axis / square root axis at 0 ^ 2 + axis at 1 ^ 2 + axis at 2 ^ 2
return tuple point unit
end function | def unitVectorYawCenter(self):
AB = self.nodes[1]-self.nodes[0]
AG = self.nodes[6]-self.nodes[0]
point = (AG/2)+self.nodes[0]
axis = AB
unit = axis/math.sqrt((axis[0]**2)+(axis[1]**2)+(axis[2]**2))
return point, unit | Python | nomic_cornstack_python_v1 |
import requests
import string
import re
class TextAnalyzer
begin
function __init__ self url
begin
set url = url
set text = string
end function
function retrieve_data self
begin
set response = get requests url
if status_code == 200
begin
set text = text
end
end function
function remove_punctuation self
begin
set text =... | import requests
import string
import re
class TextAnalyzer:
def __init__(self, url):
self.url = url
self.text = ""
def retrieve_data(self):
response = requests.get(self.url)
if response.status_code == 200:
self.text = response.text
def remove_punctuation(self)... | Python | jtatman_500k |
function _create_all_tables self
begin
set tables_to_create = list string keyword string user string question string answer string question_keyword
comment create all tables
for table in tables_to_create
begin
set sql_statement = get attribute self table + string _table_sql
call _create_table sql_statement
end
end func... | def _create_all_tables(self: db_connection) -> None:
tables_to_create = ["keyword", "user", "question", "answer", "question_keyword"]
# create all tables
for table in tables_to_create:
sql_statement = getattr(self, table + "_table_sql")
self._create_table(sql_statement) | Python | nomic_cornstack_python_v1 |
from collections import deque
class Parser extends object
begin
function __init__ self file_path
begin
set trace_file = open file_path string r
set items = deque
end function
function __iter__ self
begin
return self
end function
function __next__ self
begin
if not items
begin
set line = read line trace_file
if not line... | from collections import deque
class Parser(object):
def __init__(self, file_path):
self.trace_file = open(file_path, 'r')
self.items = deque()
def __iter__(self):
return self
def __next__(self):
if not self.items:
line = self.trace_file.readline()
if ... | Python | zaydzuhri_stack_edu_python |
function zone_id self
begin
return get pulumi self string zone_id
end function | def zone_id(self) -> pulumi.Input[str]:
return pulumi.get(self, "zone_id") | Python | nomic_cornstack_python_v1 |
while true
begin
set sum = temp // 10 + temp % 10
set new = temp % 10 * 10 + sum % 10
if new == N
begin
break
end
set temp = new
set cycle = cycle + 1
end
print cycle | while True:
sum = temp // 10 + temp % 10
new = temp % 10 * 10 + sum % 10
if new == N:
break
temp = new
cycle += 1
print(cycle) | Python | zaydzuhri_stack_edu_python |
import random
set monito1 = string +---+ | | | | | | =========
set monito2 = string +---+ | | O | | | | =========
set monito3 = string +---+ | | O | | | | | =========
set monito4 = string +---+ | | O | |\ | | | =========
set monito5 = string +---+ | | O | /|\ | | | =========
set monito6 = string +---+ | | O | /|\ | \ |... | import random
monito1 = (
" +---+ \n"
" | |\n"
" |\n"
" |\n"
" |\n"
" |\n"
" =========\n")
monito2 = (
" +---+ \n"
" | |\n"
" O |\n"
" |\n"
" |\n"
" |\n"
" =========\n")
monito3 = (
" +---+ \n"
" | |\n"
" O |\n"
" | |\n"
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
function hashIt tileLen totalLen
begin
return tileLen + 10 ^ 3 * totalLen
end function
set mappy = dict
function getCount tileLen totalLen
begin
set v = call hashIt tileLen totalLen
if v in mappy
begin
return mappy at v
end
if tileLen == totalLen
begin
set mappy at v = 1
return 1
end
if tileLe... | #!/usr/bin/python
def hashIt(tileLen, totalLen):
return tileLen + ((10 ** 3)*totalLen)
mappy = {}
def getCount(tileLen, totalLen):
v = hashIt(tileLen, totalLen)
if (v in mappy):
return mappy[v]
if (tileLen == totalLen):
mappy[v] = 1
return 1
if (tileLen > totalLen):
mappy[v] = 0
return 0
r = totalLe... | Python | zaydzuhri_stack_edu_python |
function append_ccp4i_header self line
begin
comment FIXME should be internally accessible only?
append __ccp4i_header line
set __isccp4i = true
end function | def append_ccp4i_header(self, line):
# FIXME should be internally accessible only?
self.__ccp4i_header.append(line)
self.__isccp4i = True | Python | nomic_cornstack_python_v1 |
class Solution
begin
function firstUniqChar self s
begin
string Return index of first char in string occurring only once :type s: str :rtype: int
comment Remove any duplicates from the string
set uniques = call del_dupes s
comment Handle the empty-string case (all dupes or empty on input)
if not uniques
begin
return - ... | class Solution:
def firstUniqChar(self, s):
"""Return index of first char in string occurring only once
:type s: str
:rtype: int
"""
# Remove any duplicates from the string
uniques = self.del_dupes(s)
# Handle the empty-string case (all dupes or empty on input... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string Module
import json
from models.base_model import BaseModel
from models.user import User
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.review import Review
from models.state import State
class FileStorage
begin
string serialize... | #!/usr/bin/python3
"""Module
"""
import json
from models.base_model import BaseModel
from models.user import User
from models.city import City
from models.amenity import Amenity
from models.place import Place
from models.review import Review
from models.state import State
class FileStorage:
"""
serializes ... | Python | zaydzuhri_stack_edu_python |
comment CODE
class TimeTask
begin
function __init__ self heure minute seconde ms=0
begin
set heure = heure
set minute = minute
set seconde = seconde
set ms = ms
end function
function add self t2
begin
set nms = ms + ms % 100
set secondeTrop = ms + ms // 100
set nseconde = seconde + seconde + secondeTrop % 60
set minute... | # CODE
class TimeTask:
def __init__(self, heure, minute ,seconde , ms=0):
self.heure = heure
self.minute = minute
self.seconde = seconde
self.ms = ms
def add(self, t2):
nms = (self.ms + t2.ms)%100
secondeTrop = (self.ms + t2.ms)//100
nseconde = (self.sec... | Python | zaydzuhri_stack_edu_python |
function test_required_passes dummy_form dummy_field
begin
set validator = call data_required
set data = string foobar
call validator dummy_form dummy_field
end function | def test_required_passes(dummy_form, dummy_field):
validator = data_required()
dummy_field.data = "foobar"
validator(dummy_form, dummy_field) | Python | nomic_cornstack_python_v1 |
import csv
from datetime import datetime
set path = string C:\Users\elepo\PycharmProjects\0-hello\google_stock_data.csv
set file = open path newline=string
set reader = reader file
comment estraggo prima linea che non contiene dati importanti, ma solo l'header
set header = next reader
comment estraggo rimanenti dati, F... | import csv
from datetime import datetime
path = "C:\\Users\\elepo\\PycharmProjects\\0-hello\\google_stock_data.csv"
file = open(path, newline="")
reader = csv.reader(file)
#estraggo prima linea che non contiene dati importanti, ma solo l'header
header = next(reader)
#estraggo rimanenti dati, FACENDO ATTENZIONE A METT... | Python | zaydzuhri_stack_edu_python |
function create_transaction self iban bic name reference amount pin
begin
set tuple encrypted_secret encrypted_pin = call encrypt_user_pin pin
set pin_headers = dict string encrypted-secret encrypted_secret ; string encrypted-pin encrypted_pin
comment Prepare headers as a json for a transaction call
set data = dict str... | def create_transaction(self, iban: str, bic: str, name: str, reference: str, amount: float, pin: str):
encrypted_secret, encrypted_pin = self.encrypt_user_pin(pin)
pin_headers = {
'encrypted-secret': encrypted_secret,
'encrypted-pin': encrypted_pin
}
# Prepare he... | Python | nomic_cornstack_python_v1 |
from scipy.interpolate import griddata
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm
import tiling
import random
class GridInterpolating
begin
function __init__ self tilingsShapePure samplePoints
begin
comment tiling_shape ist raum der Poses ~> Werte für die Dista... | from scipy.interpolate import griddata
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm
import tiling
import random
class GridInterpolating:
def __init__(self, tilingsShapePure, samplePoints):
# tiling_shape ist raum der Poses ~> Werte für die Distanzen ... | Python | zaydzuhri_stack_edu_python |
function sell
begin
set username = get session string username
if method == string POST
begin
set symbol = get form string symbol
set req_quantity = get form string shares
if not is digit req_quantity or integer req_quantity <= 0
begin
return call apology string Quantity must be positive integer 400
end
set req_quantit... | def sell():
username = session.get("username")
if request.method == "POST":
symbol = request.form.get("symbol")
req_quantity = request.form.get("shares")
if not req_quantity.isdigit() or int(req_quantity)<=0:
return apology("Quantity must be positive integer", 400)
re... | Python | nomic_cornstack_python_v1 |
if distancia <= 200
begin
set preço = distancia * 0.5
end
else
begin
set preço = distancia * 0.45
end
print format string O preço de sua passagem será de R$ {:.2f}. preço
print string ====== Solução nº 2 ======
set preço = if expression distancia <= 200 then distancia * 0.5 else distancia * 0.45
print format string O p... | if distancia <= 200:
preço = distancia * 0.50
else:
preço = distancia * 0.45
print('\nO preço de sua passagem será de R$ {:.2f}.'.format(preço))
print('\n====== Solução nº 2 ======')
preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45
print('\nO preço de sua passagem será de R$ {:.2f}.'.forma... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from numba import jit
import matplotlib as mpl
call use string tkagg
import matplotlib.pyplot as plt
import matplotlib.animation as anim
from time import time
set start = time
comment parameter space
set sp = list 0 2 * pi
comment number of frames
set num = 100
comment interval between frames
set int... | import numpy as np
from numba import jit
import matplotlib as mpl
mpl.use('tkagg')
import matplotlib.pyplot as plt
import matplotlib.animation as anim
from time import time
start = time()
#parameter space
sp = [0,2*np.pi]
#number of frames
num = 100
#interval between frames
interval = 30
def fc(p):
#define c as fun... | Python | zaydzuhri_stack_edu_python |
comment title: all-nodes-distance-k-in-binary-tree
comment detail: https://leetcode.com/submissions/detail/407305503/
comment datetime: Sun Oct 11 17:42:11 2020
comment runtime: 36 ms
comment memory: 14.2 MB
comment Definition for a binary tree node.
comment class TreeNode:
comment def __init__(self, x):
comment self.v... | # title: all-nodes-distance-k-in-binary-tree
# detail: https://leetcode.com/submissions/detail/407305503/
# datetime: Sun Oct 11 17:42:11 2020
# runtime: 36 ms
# memory: 14.2 MB
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# ... | Python | zaydzuhri_stack_edu_python |
function isFull self
begin
return rear - front == size
end function | def isFull(self):
return self.rear - self.front == self.size | Python | nomic_cornstack_python_v1 |
function add_improper_torsion self smarts central_smarts scan_range=none scan_increment=15
begin
append improper_scans call ImproperScan smarts=smarts central_smarts=central_smarts scan_range=scan_range scan_increment=list scan_increment
end function | def add_improper_torsion(
self,
smarts: str,
central_smarts: str,
scan_range: Optional[Tuple[int, int]] = None,
scan_increment: int = 15,
) -> None:
self.improper_scans.append(
ImproperScan(
smarts=smarts,
central_smarts=cen... | Python | nomic_cornstack_python_v1 |
import numpy as np
function combined_mean_std means stds counts
begin
string [calculates combined statistics] Args: means (np.array): [mean array of all distributions] stds (np.array): [standart deviations array of all distributions] counts (np.array): [list of num of elements for all distributions ] Returns: [tuple]: ... | import numpy as np
def combined_mean_std(means: np.array, stds: np.array, counts:np.array)->tuple:
"""[calculates combined statistics]
Args:
means (np.array): [mean array of all distributions]
stds (np.array): [standart deviations array of all distributions]
counts (np.array): [list of n... | Python | zaydzuhri_stack_edu_python |
comment -*- coding :utf-8 -*-
import json
class Student extends object
begin
function __init__ self name age score
begin
set name = name
set age = age
set score = score
end function
end class
set s = call Student string Bob 20 88
comment 该隐函数把任意 class 的实例变为 dict
set t = dumps s default=lambda obj -> __dict__
print t
fu... | # -*- coding :utf-8 -*-
import json
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student('Bob', 20, 88)
# 该隐函数把任意 class 的实例变为 dict
t = json.dumps(s, default=lambda obj: obj.__dict__)
print(t)
def dictstude... | Python | zaydzuhri_stack_edu_python |
function restore_default_highlights bv=none
begin
call highlight_set total_coverage
call log_info string Default highlight colors restored
end function | def restore_default_highlights(bv=None):
highlight_set(covdb.total_coverage)
log.log_info("Default highlight colors restored") | Python | nomic_cornstack_python_v1 |
import os
import numpy as np
from frameLoader import Frameloader
from No_use.stipReader import Stipreader
from No_use.surfExtractor import Surfextractor
class Framefeaturecalculator extends object
begin
function __init__ self frame_path stips_path save_path
begin
set video_store_path = save_path
set frame_loader = call... | import os
import numpy as np
from frameLoader import Frameloader
from No_use.stipReader import Stipreader
from No_use.surfExtractor import Surfextractor
class Framefeaturecalculator(object):
def __init__(self, frame_path, stips_path, save_path):
self.video_store_path = save_path
self.frame_loade... | Python | zaydzuhri_stack_edu_python |
function currentFrame self
begin
if moveFlag
begin
set tau = thetas * t / moveSteps
end
else
begin
set tau = 1
end
return B @ call constructR tau @ Wa
end function | def currentFrame(self):
if self.moveFlag:
tau = self.thetas * self.t / self.moveSteps
else:
tau = 1
return self.B @ constructR(tau) @ self.Wa | Python | nomic_cornstack_python_v1 |
function set_rival_move self pos
begin
set rival_pos = where board == 2
set prev_pos = tuple generator expression ax at 0 for ax in rival_pos
set board at prev_pos = - 1
set board at pos = 2
end function | def set_rival_move(self, pos):
rival_pos = np.where(self.board == 2)
prev_pos = tuple(ax[0] for ax in rival_pos)
self.board[prev_pos] = -1
self.board[pos] = 2 | Python | nomic_cornstack_python_v1 |
function parse_file_format path
begin
comment Handle directory.
if is directory path path or ends with path string /
begin
if ends with lower right strip path string / string lmdb
begin
return string lmdb
end
return string dir
end
comment Handle file.
if is file path path and call splitext path at 1 == string
begin
re... | def parse_file_format(path):
# Handle directory.
if os.path.isdir(path) or path.endswith('/'):
if path.rstrip('/').lower().endswith('lmdb'):
return 'lmdb'
return 'dir'
# Handle file.
if os.path.isfile(path) and os.path.splitext(path)[1] == '':
return 'txt'
path = ... | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
string 爬取某个用户的所有issue主要是适合保存备份, 注意一次最多只能请求30条数据,所以要先拿到页数, 然后再分页请求
import re
import time
import pip._vendor.requests as requests
print string 输入github用户名
set user_name = input
set page_url = string https://api.github.com/search/issues?q=+state:open+repo: + user_name + string / + user_name + ... | # -*- coding:utf-8 -*-
'''
爬取某个用户的所有issue主要是适合保存备份, 注意一次最多只能请求30条数据,所以要先拿到页数,
然后再分页请求
'''
import re
import time
import pip._vendor.requests as requests
print('输入github用户名')
user_name = input()
page_url = "https://api.github.com/search/issues?q=+state:open+repo:" + user_name + "/" + user_name + ".github.io"
page_re... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import random
from time import ctime , gmtime , strftime
set category = list string center string left string right string up string down string left_rotate string right_rotate string up_rotate string down_rotate
function data_processing sensor_data timesteps data_dim nb_classes
begin
set num_data = ... | import numpy as np
import random
from time import ctime, gmtime, strftime
category = ['center', 'left', 'right', 'up', 'down', 'left_rotate', 'right_rotate', 'up_rotate', 'down_rotate']
def data_processing(sensor_data, timesteps, data_dim, nb_classes):
num_data = sensor_data.num_data / timesteps
Labels = sensor_d... | Python | zaydzuhri_stack_edu_python |
comment Swapping is used
function sort nums
begin
comment go in reverse from 0 to last index
for i in range length nums - 1 0 - 1
begin
comment after each iteration, you will get max value in the end
comment that's why the range goes to i
for j in range i
begin
if nums at j > nums at j + 1
begin
set temp = nums at j
se... | # Swapping is used
def sort(nums):
# go in reverse from 0 to last index
for i in range(len(nums)-1, 0, -1):
# after each iteration, you will get max value in the end
# that's why the range goes to i
for j in range(i):
if nums[j] > nums[j + 1]:
temp = nums[j]
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment encoding: utf-8
string @author: jiangsy @eamil: jiangshanyao_heu@163.com
set tuple a b = list comprehension integer i for i in split input
set q = a // b
set r = a - b * q
print q r | #!/usr/bin/env python
# encoding: utf-8
'''
@author: jiangsy
@eamil: jiangshanyao_heu@163.com
'''
a, b = [int(i) for i in input().split()]
q = a // b
r = a - b*q
print(q, r) | Python | zaydzuhri_stack_edu_python |
function DFSMaze self
begin
set dfs = list
for i in range size // 2
begin
append dfs list
for j in range size // 2
begin
append dfs at i 0
end
end
set stack = list
comment The walls take up a slot, so we only have half the slots open for paths
set i = call randrange size // 2
set j = call randrange size // 2
comment ... | def DFSMaze(self):
dfs = []
for i in range(self.size // 2):
dfs.append([])
for j in range(self.size // 2):
dfs[i].append(0)
stack = []
#The walls take up a slot, so we only have half the slots open for paths
i = random.ran... | Python | nomic_cornstack_python_v1 |
function reverseNodesInKGroups l k
begin
set h = call ListNode 0
set jump = call ListNode 0
set next = l
set left = l
set right = l
while true
begin
set i = 0
end
end function | def reverseNodesInKGroups(l, k):
h = jump = ListNode(0)
h.next = left = right = l
while True:
i = 0 | Python | zaydzuhri_stack_edu_python |
function test_create_context_path_comp_service_name_name_by_id self
begin
set name = call NameAndValue
set response = open format string /restconf/config/context/path-comp-service/{uuid}/name/{value_name}/ uuid=string uuid_example value_name=string value_name_example method=string POST data=dumps name content_type=stri... | def test_create_context_path_comp_service_name_name_by_id(self):
name = NameAndValue()
response = self.client.open(
'/restconf/config/context/path-comp-service/{uuid}/name/{value_name}/'.format(uuid='uuid_example', value_name='value_name_example'),
method='POST',
data... | Python | nomic_cornstack_python_v1 |
function main
begin
try
begin
comment Check if file exists
set arg = argv at 1
open arg
end
except FileNotFoundError
begin
print string File does not exist
end
except IndexError
begin
print string Please enter one file to columnize
end
try else
begin
comment Get content from one file. (Use loop if batching files)
set a... | def main():
try:
# Check if file exists
arg = sys.argv[1]
open(arg)
except FileNotFoundError:
print('File does not exist')
except IndexError:
print('Please enter one file to columnize')
else:
# Get content from one file. (Use loop if batching files)
... | Python | nomic_cornstack_python_v1 |
function test_scroll_down self
begin
notify self string Scroll down
call assert_stop string No scroll down registered on_scroll=lambda x y dx dy -> not dy < 0
end function | def test_scroll_down(self):
self.notify('Scroll down')
self.assert_stop(
'No scroll down registered',
on_scroll=lambda x, y, dx, dy: not (
dy < 0)) | Python | nomic_cornstack_python_v1 |
comment Import général
import wget
import os
import datetime
import sh
import sys
comment Import pour les logs
import logging
from logging.handlers import RotatingFileHandler
comment maps label to attribute name and types
set label_attr_map = dict string path_to_file: list string path_to_file str ; string base_url: lis... | # Import général
import wget
import os
import datetime
import sh
import sys
# Import pour les logs
import logging
from logging.handlers import RotatingFileHandler
# maps label to attribute name and types
label_attr_map = {
"path_to_file:": [ "path_to_file", str],
"base_url:": [ "base_url", str],
"extensi... | Python | zaydzuhri_stack_edu_python |
function gateway_ends_with self gateway_ends_with
begin
set _gateway_ends_with = gateway_ends_with
end function | def gateway_ends_with(self, gateway_ends_with):
self._gateway_ends_with = gateway_ends_with | Python | nomic_cornstack_python_v1 |
set v = input string Введите число от 1 до 10:
set v = integer v + 10
print v | v = input ("Введите число от 1 до 10: ")
v = int(v) + 10
print (v) | Python | zaydzuhri_stack_edu_python |
function slices series n
begin
if length series < n or n <= 0
begin
raise call ValueError string
end
return list comprehension list comprehension integer d for d in series at slice i : i + n : for i in range 0 length series + 1 - n
end function | def slices(series, n):
if len(series) < n or n <= 0: raise ValueError("")
return [ [int(d) for d in series[i:i+n] ] for i in range(0,len(series)+1-n)]
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: UTF-8 -*-
comment @Time : 2019/3/27 20:55
comment @Author : xiongzongyang
comment @Site :
comment @File : SQuAD_data_helper.py
comment @Software: PyCharm
import json
import nltk
function word_tokenize tokens
begin
return list comprehension replace replace token string '' string " string `` string " ... | #-*- coding: UTF-8 -*-
# @Time : 2019/3/27 20:55
# @Author : xiongzongyang
# @Site :
# @File : SQuAD_data_helper.py
# @Software: PyCharm
import json
import nltk
def word_tokenize(tokens):
return [token.replace("''", '"').replace("``", '"') for token in nltk.word_tokenize(tokens)]
def preprocess_file(p... | Python | zaydzuhri_stack_edu_python |
function test
begin
set name = string translation
comment | name = 'sample-submission'
comment | name = 'train-csv'
comment | name = 'test-images'
comment | name = 'train-images'
set filepath = call get_dataset_file_path name
print string DEBUG filepath: filepath
set kanji_font_filepath = call get_kanji_font_file_path
... | def test():
name = 'translation'
#| name = 'sample-submission'
#| name = 'train-csv'
#| name = 'test-images'
#| name = 'train-images'
filepath = get_dataset_file_path(name)
print("DEBUG filepath:", filepath)
kanji_font_filepath = get_kanji_font_file_path()
print("DEBUG kanji fo... | Python | nomic_cornstack_python_v1 |
function __init__ self init_pose=array list 0.0 0.0 10.0 0.0 0.0 0.0 init_velocities=array list 0.0 0.0 0.1 init_angle_velocities=array list 0.0 0.0 0.0 runtime=5.0 target_pos=array list 0.0 0.0 50.0
begin
comment Simulation
set sim = call PhysicsSim init_pose init_velocities init_angle_velocities runtime
set action_re... | def __init__(self,
init_pose = np.array([0.0,0.0,10.0,0.0,0.0,0.0]),
init_velocities = np.array([0.0,0.0,0.1]),
init_angle_velocities = np.array([0.0,0.0,0.0]),
runtime=5.,
target_pos=np.array([0.0,0.0,50.0])):
# Simulation
... | Python | nomic_cornstack_python_v1 |
function stream_name self
begin
return _stream_name
end function | def stream_name(self):
return self._stream_name | Python | nomic_cornstack_python_v1 |
function double_word word
begin
set doubleword = word * 2
return doubleword + string length doubleword
end function
comment Should return hellohello10
print call double_word string hello
comment Should return abcabc6
print call double_word string abc
comment Should return 0
print call double_word string
comment String ... | def double_word(word):
doubleword = word * 2
return doubleword + str(len(doubleword))
print(double_word("hello")) # Should return hellohello10
print(double_word("abc")) # Should return abcabc6
print(double_word("")) # Should return 0
# String Indexing
name = "James"
print(name[1])
print(len(name))
... | Python | zaydzuhri_stack_edu_python |
from flask import Flask , render_template , request , redirect , url_for
set app = call Flask __name__
decorator call route string /
decorator call route string /index
function index
begin
return call render_template string index.html
end function
decorator call route string /Bob
function Bob
begin
return call render_t... | from flask import Flask, render_template, request, redirect, url_for
app = Flask(__name__)
@app.route('/')
@app.route('/index')
def index():
return render_template("index.html")
@app.route('/Bob')
def Bob():
return render_template("Bob.html")
@app.route('/Robin')
def Robin():
return render_template(... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string Generate random unused MAC address(es) This script generates random MAC addresses and checks them against list of existing MAC addresses obtained from libvirt instance(s). In case libvirt is not installed or given URI(s) aren't accessible script will still generate random MAC addres... | #!/usr/bin/env python3
"""Generate random unused MAC address(es)
This script generates random MAC addresses and checks them against list of
existing MAC addresses obtained from libvirt instance(s). In case libvirt is
not installed or given URI(s) aren't accessible script will still generate
random MAC addresses withou... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sqlite3
import sys
class DB
begin
function __init__ self
begin
set con = call connect string /var/www/db/log.db
comment dict_factory
set row_factory = Row
end function
end class | #!/usr/bin/python
import sqlite3
import sys
class DB:
def __init__(self):
self.con = sqlite3.connect('/var/www/db/log.db')
self.con.row_factory = sqlite3.Row #dict_factory
| Python | zaydzuhri_stack_edu_python |
function query pid doi_param timeout=1.0
begin
try
begin
set doi = call match_doi doi_param
end
except TypeError
begin
set msg = string invalid doi parameter: %s % doi_param
warning msg
return dict string msg msg ; string status 400
end
if doi == string
begin
set msg = string invalid doi parameter: %s % doi_param
warn... | def query(pid, doi_param, timeout=1.0):
try:
doi = match_doi(doi_param)
except TypeError:
msg = 'invalid doi parameter: %s' % doi_param
logger.warning(msg)
return {'msg': msg, 'status': 400}
if doi == '':
msg = 'invalid doi parameter: %s' % doi_param
logger.... | Python | nomic_cornstack_python_v1 |
function __init__ self bot_instance
begin
set bot_instance = bot_instance
end function | def __init__(self, bot_instance):
self.bot_instance = bot_instance | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template
from util import createFileWithFileName
from model import TestModel , ZhihuModel
import urllib , json
import urllib.request
set app = call Flask __name__
decorator call route string /
function hello_world
begin
comment url = "http://news-at.zhihu.com/api/4/news/latest"
comment ... | from flask import Flask,render_template
from util import createFileWithFileName
from model import TestModel,ZhihuModel
import urllib,json
import urllib.request
app=Flask(__name__)
@app.route('/')
def hello_world():
# url = "http://news-at.zhihu.com/api/4/news/latest"
# data=urllib.request.urlopen(url).read()
# z_d... | Python | zaydzuhri_stack_edu_python |
from goal_builders.shooting.goal_builder import GoalBuilderForShooting
class GoalBuilderForShootingINT extends GoalBuilderForShooting
begin
function __init__ self goal_generator conditional_policy
begin
set _goal_generator = goal_generator
set _conditional_policy = conditional_policy
call construct_networks
call constr... | from goal_builders.shooting.goal_builder import GoalBuilderForShooting
class GoalBuilderForShootingINT(GoalBuilderForShooting):
def __init__(self, goal_generator, conditional_policy):
self._goal_generator = goal_generator
self._conditional_policy = conditional_policy
self._goal_generator.... | Python | zaydzuhri_stack_edu_python |
string Simple Balanced Parentheses using stack
class Stack
begin
function __init__ self
begin
set items = list
end function
function isEmpty self
begin
return items == list
end function
function push self item
begin
append items item
end function
function pop self
begin
return pop items
end function
function peek sel... | '''
Simple Balanced Parentheses using stack
'''
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
re... | Python | zaydzuhri_stack_edu_python |
function add self AutoGenerateSessionName=none BackupLspIdPoolStart=none Bandwidth=none BandwidthProtectionDesired=none EnableBfdMpls=none EnableFastReroute=none EnableLspPing=none EnablePathReoptimization=none EnablePeriodicReEvaluationRequest=none EnableResourceAffinities=none Enabled=none ExcludeAny=none FastReroute... | def add(
self,
AutoGenerateSessionName=None,
BackupLspIdPoolStart=None,
Bandwidth=None,
BandwidthProtectionDesired=None,
EnableBfdMpls=None,
EnableFastReroute=None,
EnableLspPing=None,
EnablePathReoptimization=None,
EnablePeriodicReEvaluati... | Python | nomic_cornstack_python_v1 |
from django.db import models
from django.utils import timezone
comment Create your models here.
comment models.Model -> significa que Post es un modelo de Django y por tanto Django debe guardarlo en la base de datos
class Post extends Model
begin
comment ForeingKey -> vinculo con otro modelo
set author = call ForeignKe... | from django.db import models
from django.utils import timezone
# Create your models here.
#models.Model -> significa que Post es un modelo de Django y por tanto Django debe guardarlo en la base de datos
class Post(models.Model):
author = models.ForeignKey('auth.User') #ForeingKey -> vinculo con otro modelo
title = ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import requests
import argparse
import ssl
import json
import base64
set gitlab_token = string 1q2w3e4r
comment curl -s --request GET --header "Private-Token: KtERxDvHg_rn-d97z7Bk" 'https://mygitlab.com/api/v4/projects/?search=seed'
comment TT
set projects = list string project1 string pro... | #!/usr/bin/env python3
import requests
import argparse
import ssl
import json
import base64
gitlab_token="1q2w3e4r"
#curl -s --request GET --header "Private-Token: KtERxDvHg_rn-d97z7Bk" 'https://mygitlab.com/api/v4/projects/?search=seed'
# TT
projects=[
"project1",
"project2"
]
projects_data=[
"other_pr... | Python | zaydzuhri_stack_edu_python |
comment Importing the data + visual module, and other methods from the sklearn, seaborn, panda, numpy, and matplotlib libraries.
import data
import numpy as np
import visuals
import seaborn as sn
from collections import Counter
from sklearn.naive_bayes import MultinomialNB , BernoulliNB , GaussianNB
from sklearn.svm im... | # Importing the data + visual module, and other methods from the sklearn, seaborn, panda, numpy, and matplotlib libraries.
import data
import numpy as np
import visuals
import seaborn as sn
from collections import Counter
from sklearn.naive_bayes import MultinomialNB, BernoulliNB, GaussianNB
from sklearn.svm import Lin... | Python | zaydzuhri_stack_edu_python |
function interrupt self uuid cellid=none
begin
call interrupt uuid call Args cellid=cellid okay fail
end function | def interrupt(self, uuid, cellid=None):
self.manager.interrupt(uuid, Args(cellid=cellid), self.okay, self.fail) | Python | nomic_cornstack_python_v1 |
function forward self inputs state=tuple
begin
set tuple observations actions = inputs
set encoded_obs = observations
set encoded_action = actions
set joint = call cat list encoded_obs encoded_action - 1
set tuple out _ = call _joint_encoder joint
if _projection_net is not none
begin
set tuple out _ = call _projection_... | def forward(self, inputs, state=()):
observations, actions = inputs
encoded_obs = observations
encoded_action = actions
joint = torch.cat([encoded_obs, encoded_action], -1)
out, _ = self._joint_encoder(joint)
if self._projection_net is not None:
out, _ = self.... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import time
from itertools import groupby
from collections import defaultdict
from glob import glob
import os
comment Каталог из которого будем брать изображения
set directory = string data
function open directory
begin
change directory directory
set files = glob string *.xlsx
extend files glob stri... | import pandas as pd
import time
from itertools import groupby
from collections import defaultdict
from glob import glob
import os
#Каталог из которого будем брать изображения
directory = 'data'
def open(directory):
os.chdir(directory)
files = glob('*.xlsx')
files.extend(glob('*.csv'))
for file in fil... | Python | zaydzuhri_stack_edu_python |
function print_dict_items d
begin
for tuple k v in items d
begin
info format string {}: {} k v
end
end function | def print_dict_items(d):
for k, v in d.items():
logger.info("{}: {}".format(k, v)) | Python | nomic_cornstack_python_v1 |
string Created on 2020年3月5日 @author: yanzi
comment 使用requests方法
import requests
from bs4 import BeautifulSoup
from config import logindata
from config import seachdata
import re
import get_detail
import con_mysql
set session = call Session
function checkToken
begin
comment 判断token是否过期
comment 检查会话
set status = get sess... | '''
Created on 2020年3月5日
@author: yanzi
'''
#使用requests方法
import requests
from bs4 import BeautifulSoup
from config import logindata
from config import seachdata
import re
import get_detail
import con_mysql
session = requests.Session()
def checkToken():
#判断token是否过期
status=session.get(logindata.url2, heade... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
function text_indentation text
begin
set new_list = list
set la_otra_lista = list
if type text is not str
begin
raise call TypeError string text must be a string
end
set new_str1 = replace text string . string .
set new_str2 = replace new_str1 string ? string ?
set new_str1 = replace new_str... | #!/usr/bin/python3
def text_indentation(text):
new_list = []
la_otra_lista = []
if type(text) is not str:
raise TypeError("text must be a string")
new_str1 = text.replace('.', '.\n\n')
new_str2 = new_str1.replace('?', '?\n\n')
new_str1 = new_str2.replace(':', ':\n\n')
new_str1 = new_... | Python | zaydzuhri_stack_edu_python |
function dumpData self out index
begin
comment --SCVR
call pack string 4siBB2sB string SCVR 5 + length text index + 48 type func oper
if text
begin
write out text
end
comment --Value
if is instance value int
begin
call packSub string INTV string i value
end
else
begin
call packSub string FLTV string f value
end
end fun... | def dumpData(self,out,index):
#--SCVR
out.pack('4siBB2sB',
'SCVR', 5+len(self.text), index+48, self.type, self.func, self.oper)
if self.text: out.write(self.text)
#--Value
if isinstance(self.value,int):
out.packSub('INTV','i', self.value)
else:
... | Python | nomic_cornstack_python_v1 |
comment inverso = nome[::-1]
set inverso = string
for letra in range length nome - 1 - 1 - 1
begin
set inverso = inverso + nome at letra
end
if nome == inverso
begin
print string Essa frase é palindromo
end
else
begin
print string Essa frase não é palindromo
end | # inverso = nome[::-1]
inverso = ''
for letra in range(len(nome) - 1, -1, -1):
inverso += nome[letra]
if nome == inverso:
print('Essa frase é palindromo')
else:
print('Essa frase não é palindromo')
| Python | zaydzuhri_stack_edu_python |
import os
import sys
from optparse import OptionParser
from optparse import SUPPRESS_HELP
import ConfigParser
class Helper
begin
string This class gets some data from ENV and arglist for further usage in Statistics Methods ======= * Constructor/Destructor: - __init__(self, args): constructs an object * Functions used f... | import os
import sys
from optparse import OptionParser
from optparse import SUPPRESS_HELP
import ConfigParser
class Helper:
'''
This class gets some data from ENV and arglist for further usage in Statistics
Methods
=======
* Constructor/Destructor:
- __init__(self, args): ... | Python | zaydzuhri_stack_edu_python |
function flatten dict_ key=string children children=list
begin
set flat = list
if key in dict_
begin
for child in dict_ at key
begin
extend flat flatten child key
end
del dict_ at key
end
append flat dict_
return flat
end function | def flatten(dict_, key='children', children=[]):
flat = []
if key in dict_:
for child in dict_[key]:
flat.extend(flatten(child, key))
del(dict_[key])
flat.append(dict_)
return flat | Python | nomic_cornstack_python_v1 |
function add_figure_to_slide fig slide figsize verbose
begin
set fname = call mktemp prefix=string qcodesimageitem- suffix=string .png
if is instance fig Figure
begin
save figure fname
end
else
if is instance fig int
begin
set fig = figure fig
save figure fname
end
else
if is instance fig VideoMode or __name__ == strin... | def add_figure_to_slide(fig, slide, figsize, verbose):
fname = tempfile.mktemp(prefix='qcodesimageitem-', suffix='.png')
if isinstance(fig, matplotlib.figure.Figure):
fig.savefig(fname)
elif isinstance(fig, int):
fig = plt.figure(fig)
f... | Python | nomic_cornstack_python_v1 |
comment compatible with Python 2
comment Imports needed libraries (part 1)
import glob
import os
comment defines variables
set trueDir = false
set output = string
set last1 = string
set last2 = string
set last3 = string
set last4 = string
set last5 = string
set newstring = list
set noDup = list
comment Number t... | #compatible with Python 2
#Imports needed libraries (part 1)
import glob
import os
#defines variables
trueDir = False
output = ""
last1 = ""
last2 = ""
last3 = ""
last4 = ""
last5 = ""
newstring = []
noDup = []
#Number testing statement for Daniel's code (part 1)
def is_number(s): ... | Python | zaydzuhri_stack_edu_python |
function _handleCheckMarkAllButtonClicked self
begin
for checkBox in checkBoxes
begin
call setCheckState Checked
end
comment Call this to update the internal artifact object according
comment to what the widgets have set (in this case, the 'enabled'
comment checkboxes).
call _handleCheckMarkToggled
end function | def _handleCheckMarkAllButtonClicked(self):
for checkBox in self.checkBoxes:
checkBox.setCheckState(Qt.Checked)
# Call this to update the internal artifact object according
# to what the widgets have set (in this case, the 'enabled'
# checkboxes).
self._handleCheck... | Python | nomic_cornstack_python_v1 |
function setRefChain self ref_chain
begin
set _ref_chain = ref_chain
set _ref_chainBackup = copy ref_chain
end function | def setRefChain(self, ref_chain):
self._ref_chain = ref_chain
self._ref_chainBackup = ref_chain.copy() | Python | nomic_cornstack_python_v1 |
function paintMask self
begin
if avatarConfiguration at string mask
begin
if not is file path MASK_UPLOAD
begin
set image = call getImageLabel
set filePath = call getDataPath image
call generateImageSize filePath list 244 244 IMG_UPLOAD
call generateMask string imgUpload.png
end
set imgPath = MASK_UPLOAD
end
else
begin... | def paintMask(self):
if self.avatarConfiguration["mask"]:
if not os.path.isfile(MASK_UPLOAD):
image = self.parent.getPlayer().getImageLabel()
filePath = GG.genteguada.GenteGuada.getInstance().getDataPath(image)
guiobjects.generateImageSize(filePath, [244, 244], IMG_UPLOAD)
sel... | 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.