code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import re
function convertDNA DNA
begin
set dnaLen = integer length DNA
if match string [ATGC] DNA and dnaLen % 3 == 0
begin
set RNA_LIST = list
set RNA = string
set codonList = list
set codonListChar = list
global aminoAcidList
set aminoAcidList = list
comment Convert to RNA
for x in DNA
begin
if x is string A
be... | import re
def convertDNA(DNA):
dnaLen = int(len(DNA))
if (re.match('[ATGC]', DNA)) and ((dnaLen % 3) == 0):
RNA_LIST = []
RNA = ""
codonList = []
codonListChar = []
global aminoAcidList
aminoAcidList = []
for x in DNA: # Convert to RNA
if x i... | Python | zaydzuhri_stack_edu_python |
function min_max_decision self gameState agentIndex depth
begin
if depth >= depth * call getNumAgents or call isLose or call isWin
begin
return call evaluationFunction gameState
end
comment If its pacman return max value of tree.
if agentIndex is 0
begin
comment Return node score.
return call max_value gameState agentI... | def min_max_decision(self, gameState, agentIndex, depth):
if depth >= self.depth * gameState.getNumAgents() or gameState.isLose() or gameState.isWin():
return self.evaluationFunction(gameState)
if agentIndex is 0: # If its pacman return max value of tree.
return self.max_value(g... | Python | nomic_cornstack_python_v1 |
function test_get_irename_dict__OPT_1 self
begin
assert equal call get_irename_dict OPT dictionary
end function | def test_get_irename_dict__OPT_1(self):
self.assertEqual(SConsArguments.Declarations._ArgumentDeclarations().get_irename_dict(SConsArguments.OPT), dict()) | Python | nomic_cornstack_python_v1 |
function _generate_repo_conf self
begin
debug format string Generating repo file for Dockerfile {} name
comment Make our metadata directory if it does not exist
if not is directory path string .oit
begin
make directory os string .oit
end
set repos = repos
set enabled_repos = get config string enabled_repos list
for t i... | def _generate_repo_conf(self):
self.logger.debug("Generating repo file for Dockerfile {}".format(self.metadata.name))
# Make our metadata directory if it does not exist
if not os.path.isdir(".oit"):
os.mkdir(".oit")
repos = self.runtime.repos
enabled_repos = self.c... | Python | nomic_cornstack_python_v1 |
function test_batch_norm_layers
begin
set layers = list list string gru 20 list string lstm 3 list string linear 4 list string linear 10
set rnn = rnn layers=layers hidden_activations=string relu input_dim=5 output_activation=string relu initialiser=string xavier batch_norm=true
assert length batch_norm_layers == 3
ass... | def test_batch_norm_layers():
layers = [["gru", 20], ["lstm", 3], ["linear", 4], ["linear", 10]]
rnn = RNN(layers=layers, hidden_activations="relu", input_dim=5,
output_activation="relu", initialiser="xavier", batch_norm=True)
assert len(rnn.batch_norm_layers) == 3
assert rnn.batch_norm_la... | Python | nomic_cornstack_python_v1 |
class Person
begin
function __init__ self Name Age Gender
begin
set Name = Name
set Age = Age
set Gender = Gender
end function
end class | class Person:
def __init__(self, Name, Age, Gender):
self.Name = Name
self.Age = Age
self.Gender = Gender | Python | jtatman_500k |
function name self
begin
return get raw_json string name
end function | def name(self):
return self.raw_json.get("name") | Python | nomic_cornstack_python_v1 |
function check func
begin
function inner *args **kwargs
begin
for val in args
begin
print string Input type is type val
end
for val in kwargs
begin
print string Input type is type val
end
set result = call func *args keyword kwargs
print string Reuslt type is type result
return result
end function
return inner
end func... | def check(func):
def inner(*args, **kwargs):
for val in args:
print('Input type is ', type(val))
for val in kwargs:
print('Input type is ', type(val))
result = func(*args, **kwargs)
print('Reuslt type is ', type(result))
return result
return inn... | Python | zaydzuhri_stack_edu_python |
function test_valid_user_auth self
begin
set user = call create_user username=string some_username password=string some_password email=string some_email@gmail.com
call create_player username=string some_username
set data = dict string username string some_username ; string password string some_password
set response = p... | def test_valid_user_auth(self):
user = User.objects.create_user(username='some_username', password='some_password',
email='some_email@gmail.com')
Profile.objects.create_player(username='some_username')
data = {'username': 'some_username', 'password': 'som... | Python | nomic_cornstack_python_v1 |
function _set_n_key self
begin
if _provided_n_key is not none
begin
comment further checks here? len() == 32
set _n_key = _provided_n_key
end
else
if _html_source
begin
set pattern = string n = '
if pattern in _html_source
begin
set _n_key = split split _html_source pattern at 1 string '; at 0
end
end
end function | def _set_n_key(self):
if self._provided_n_key is not None:
# further checks here? len() == 32
self._n_key = self._provided_n_key
else:
if self._html_source:
pattern = 'n = \''
if pattern in self._html_source:
self._n... | Python | nomic_cornstack_python_v1 |
comment coding = utf-8
comment server type: multithreading
import argparse , socket
import threading
import os
import app
set __author__ = string Cyris
function server host port
begin
set sock = call socket AF_INET SOCK_STREAM
call setsockopt SOL_SOCKET SO_REUSEADDR 1
call bind tuple host port
call listen 15
print stri... | # coding = utf-8
# server type: multithreading
import argparse, socket
import threading
import os
import app
__author__ = 'Cyris'
def server(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.li... | Python | zaydzuhri_stack_edu_python |
import geopandas as gpd
import pandas as pd
from shapely.geometry import LineString
import modules.log_controller
import networkx as nx
from networkx.algorithms.components import *
import copy
import numpy as np
class ThinNetwork extends object
begin
function __init__ self network_gdf junctions_gdf thin_nodes_list conf... | import geopandas as gpd
import pandas as pd
from shapely.geometry import LineString
import modules.log_controller
import networkx as nx
from networkx.algorithms.components import *
import copy
import numpy as np
class ThinNetwork(object):
def __init__(self, network_gdf, junctions_gdf, thin_nodes_list, config):
... | Python | zaydzuhri_stack_edu_python |
import random
import time
from zbox import z_algo as jit_z
from jit_zbox import z_algo as python_z
function timing func
begin
function wrapper *args **kwargs
begin
set start = time
set result = call func *args keyword kwargs
set elapsed = time - start
print string { __name__ } : { elapsed } s
return result
end function... | import random
import time
from zbox import z_algo as jit_z
from jit_zbox import z_algo as python_z
def timing(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start
print(f"{func.__name__}: {elapsed:.4f}s")
retu... | Python | zaydzuhri_stack_edu_python |
import tkinter as TKI
function click_btn
begin
insert text END string モンスターが現れた!
end function
string メイン
set root = call Tk
title root string 複数行のテキスト入力
call geometry string 400x200
comment ボタンの部品作成
set button = call Button text=string メッセージ command=click_btn
call pack
set text = call Text
call pack
comment ウィンドウの表示
ca... | import tkinter as TKI
def click_btn():
text.insert(TKI.END, "モンスターが現れた!")
"""
メイン
"""
root = TKI.Tk()
root.title("複数行のテキスト入力")
root.geometry("400x200")
# ボタンの部品作成
button = TKI.Button(text="メッセージ", command=click_btn)
button.pack()
text = TKI.Text()
text.pack()
# ウィンドウの表示
root.mainloop()
| Python | zaydzuhri_stack_edu_python |
comment Script to getauthorization code from Digi-key by providing
comment client-id and client-secret
comment See https://developer.digikey.com/documentation/oauth for more info
import argparse
import os
from pprint import pprint
import requests
import sys
import time
import webbrowser
import yaml
set DEFAULT_REDIRECT... | #
# Script to getauthorization code from Digi-key by providing
# client-id and client-secret
# See https://developer.digikey.com/documentation/oauth for more info
#
import argparse
import os
from pprint import pprint
import requests
import sys
import time
import webbrowser
import yaml
DEFAULT_REDIRECT_URI = "https://... | Python | zaydzuhri_stack_edu_python |
function S self
begin
return call generic_getter get_entropy string S string convert_entropy
end function | def S(self):
return self.generic_getter(get_entropy, "S", "convert_entropy") | Python | nomic_cornstack_python_v1 |
import speech_recognition as sr
from difflib import get_close_matches
import threading
set sample_rate = 48000
set chunk_size = 2048
comment Initialize the recognizer
set r = call Recognizer
set mic = call Microphone
set color_pattern = list string blue string green string yellow string red
set action_pattern = list st... | import speech_recognition as sr
from difflib import get_close_matches
import threading
sample_rate = 48000
chunk_size = 2048
#Initialize the recognizer
r = sr.Recognizer()
mic = sr.Microphone()
color_pattern = ['blue', 'green', 'yellow', 'red']
action_pattern = ['pickup', 'drop', 'dance']
obj_pattern = ['cub... | Python | zaydzuhri_stack_edu_python |
function GetAdGroup 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 GetAdGroup(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 single_distance self waypoints wp1 wp2
begin
set dl = lambda a b -> square root x - x ^ 2 + y - y ^ 2 + z - z ^ 2
set dist = call dl position position
return dist
end function | def single_distance(self, waypoints, wp1, wp2):
dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2)
dist = dl(waypoints[wp1].pose.pose.position, waypoints[wp2].pose.pose.position)
return dist | Python | nomic_cornstack_python_v1 |
function interaction_void self
begin
call swap_obj moving_character target
end function | def interaction_void(self) -> None:
self.grid.obj_list.swap_obj(self.moving_character, self.target) | Python | nomic_cornstack_python_v1 |
function btn_display_hist_callback self
begin
call show_as_waiting true
set ids = call get_selected_ids
set names = call get_selected_names
for tuple id name in zip ids names
begin
set ret = call get_single_image id user_hash
if get ret string success is false
begin
call show_error ret at string error_msg
end
else
begi... | def btn_display_hist_callback(self):
self.show_as_waiting(True)
ids = self.tbl_images.get_selected_ids()
names = self.tbl_images.get_selected_names()
for id, name in zip(ids, names):
ret = api.get_single_image(id, self.user_hash)
if ret.get('success') is False:
... | Python | nomic_cornstack_python_v1 |
function GetNameScope
begin
return call CurrentNameScope
end function | def GetNameScope():
return scope.CurrentNameScope() | Python | nomic_cornstack_python_v1 |
function center_world_about self center
begin
set screen_center = tuple call get_width / 2 call get_height / 2
set player_center = tuple w / 2 h / 2
set new_player_pos = tuple screen_center at 0 - player_center at 0 screen_center at 1 - player_center at 1
set delta = tuple new_player_pos at 0 - x new_player_pos at 1 - ... | def center_world_about(self, center:ObjectBase):
screen_center = (self.screen.get_width() / 2, self.screen.get_height() / 2)
player_center = (center.w / 2, center.h / 2)
new_player_pos = (screen_center[0] - player_center[0], screen_center[1] - player_center[1])
delta = (new_player_pos[0... | Python | nomic_cornstack_python_v1 |
function train self conversation
begin
for tuple conversation_count text in enumerate conversation
begin
if conversation_count % 1000 == 0
begin
print string training %d : % conversation_count text at 0 string | text at 1
end
set statement = call get_or_create text at 1
call add_response call Response text at 0
update ... | def train(self, conversation):
for conversation_count, text in enumerate(conversation):
if conversation_count%1000==0:
print("training %d : "%conversation_count, text[0],"|", text[1])
statement = self.get_or_create(text[1])
statement.add_response(Response(tex... | Python | nomic_cornstack_python_v1 |
import scipy
from pylab import *
import scipy
from pylab import *
import matplotlib.pyplot as plt
figure 1
set pos = find y == 1
set neg = find y == 0
set tuple fig axs = call subplots 1 1 figsize=tuple 18 5
scatter axs X at tuple pos 0 X at tuple pos 1
show
function plotData X y
begin
set pos = find y == 1
set neg = f... | import scipy
from pylab import *
import scipy
from pylab import *
import matplotlib.pyplot as plt
plt.figure(1)
pos = find(y==1); neg = find(y == 0);
fig, axs = plt.subplots(1,1,figsize=(18, 5))
axs.scatter(X[pos,0], X[pos,1])
plt.show()
def plotData(X, y):
pos = find(y == 1);
neg = find(y == 0);
pr... | Python | zaydzuhri_stack_edu_python |
function Disabled func
begin
return call _SkipTestDecoratorHelper func list string win string linux string mac string android
end function | def Disabled(func):
return _SkipTestDecoratorHelper(func, ['win', 'linux', 'mac', 'android']) | Python | nomic_cornstack_python_v1 |
import subprocess
import time
import Tkinter as tk
import ttk
class Gui extends Tk
begin
function __init__ self
begin
call __init__ self
set f0 = call Frame self
set start_subprocess_btn = call Button f0 text=string Start subprocess command=start_subprocess
call pack side=string left padx=10
call configure state=string... | import subprocess
import time
import Tkinter as tk
import ttk
class Gui(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
f0 = ttk.Frame(self)
self.start_subprocess_btn = ttk.Button(f0, text="Start subprocess", command=self.start_subprocess)
self.start_subprocess_btn.pack(side='le... | Python | zaydzuhri_stack_edu_python |
function players self
begin
return call _get string players
end function | def players(self):
return self._get("players") | Python | nomic_cornstack_python_v1 |
comment ! usr/bin/env python
import time
import datetime
set data1 = call raw_input string Write your Date(yyyy-mm-dd):
set data = string parse time data1 string %Y-%m-%d
set datimeStarp = integer call mktime data
set days = call raw_input string Write your Days:
for i in range integer days
begin
set date1 = call utcfr... | #! usr/bin/env python
import time
import datetime
data1 = raw_input('Write your Date(yyyy-mm-dd):')
data = time.strptime(data1,"%Y-%m-%d")
datimeStarp = int(time.mktime(data))
days = raw_input('Write your Days:')
for i in range(int(days)):
date1 = datetime.datetime.utcfromtimestamp(datimeStarp)
dates = (date1... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
string This is the code to accompany the Lesson 2 (SVM) mini-project. Use a SVM to identify emails from the Enron corpus by their authors: Sara has label 0 Chris has label 1
import sys
from time import time
append path string ../tools/
from email_preprocess import preprocess
comment features_tr... | #!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preprocess
... | Python | zaydzuhri_stack_edu_python |
import sqlite3
set connection = call connect string salesdb
set cursor = call cursor
execute cursor string SELECT C.CustomerID, C.FirstName, C.LastName, O.OrderID, O.Quantity, O.PricePerItem FROM customer_t As C INNER JOIN order_t AS O ON C.CustomerID=O.CustomerID
set results = call fetchall | import sqlite3
connection = sqlite3.connect("salesdb")
cursor = connection.cursor()
cursor.execute('''SELECT C.CustomerID, C.FirstName, C.LastName, O.OrderID, O.Quantity, O.PricePerItem
FROM customer_t As C
INNER JOIN order_t AS O
ON C.CustomerID=O.CustomerID ''')
results = cursor.fetchall()
| Python | zaydzuhri_stack_edu_python |
function build_dygraph_predict_ground_truth self mode=string numpy
begin
if not exists path join path exp_path case_name
begin
make directories join path exp_path case_name
end
info string dygraph predict build ground truth start~
set exp_out = predict self to_static=false
if mode == string numpy
begin
save join path e... | def build_dygraph_predict_ground_truth(self, mode="numpy"):
if not os.path.exists(os.path.join(self.exp_path, self.case_name)):
os.makedirs(os.path.join(self.exp_path, self.case_name))
self.logger.get_log().info("dygraph predict build ground truth start~")
exp_out = self.predict(to_s... | Python | nomic_cornstack_python_v1 |
from turtle import Turtle
import turtle
import random
import math
call tracer 0
set SCREEN_WIDTH = call winfo_width / 2
set SCREEN_HEIGHT = call winfo_height / 2
set colors = list string Black string Red string Green string Orange string Yellow
call listen
set BALLS = list
set score = 0
class Ball extends Turtle
begin... | from turtle import Turtle
import turtle
import random
import math
turtle.tracer(0)
SCREEN_WIDTH = turtle.getcanvas().winfo_width()/2
SCREEN_HEIGHT = turtle.getcanvas().winfo_height()/2
colors = ["Black","Red","Green","Orange","Yellow"]
turtle.listen()
BALLS = []
score = 0
class Ball(Turtle):
def __init__(self,radius... | Python | zaydzuhri_stack_edu_python |
function strip_useless_nodes model_graph
begin
set stripped_nodes_type_all = list
set stripped_nodes_type = list string Const string Identity
set stripped_nodes_keywords = list string /weight string /weight/read string /ReadVariableOp string /kernel string /gamma string /beta string /moving_mean string /moving_varianc... | def strip_useless_nodes(model_graph):
stripped_nodes_type_all = []
stripped_nodes_type = ["Const", "Identity"]
stripped_nodes_keywords = [
"/weight",
"/weight/read",
"/ReadVariableOp",
"/kernel",
"/gamma",
"/beta",
... | Python | nomic_cornstack_python_v1 |
from collections import namedtuple
from itertools import chain , islice , repeat
from interpreter.node import Node
set AstLine = named tuple string AstLine list string id string indent string contents
function parse_ast ast
begin
set ast_lines = list
comment Parses contents and indentation level from each lines
for tu... | from collections import namedtuple
from itertools import chain, islice, repeat
from interpreter.node import Node
AstLine = namedtuple('AstLine', ['id', 'indent', 'contents'])
def parse_ast(ast):
ast_lines = []
# Parses contents and indentation level from each lines
for index, line in enumerate(ast):
... | Python | zaydzuhri_stack_edu_python |
function get_reversion
begin
return call to_str call af_get_revision
end function | def get_reversion():
return to_str(backend.get().af_get_revision()) | Python | nomic_cornstack_python_v1 |
import unittest
import importlib
from os import walk
set stuff = 0
class unitTest_stuff extends TestCase
begin
string testing stuff
function test_stuff self
begin
call assertEquals 9 call forFun 4 5 string Stuff For Fun
call assertEquals 10 call forWork 4 5 string Stuff For Work
end function
end class
function main
beg... | import unittest
import importlib
from os import walk
stuff=0
class unitTest_stuff(unittest.TestCase):
"""testing stuff"""
def test_stuff(self):
self.assertEquals(9,stuff.forFun(4,5),"Stuff For Fun")
self.assertEquals(10,stuff.forWork(4,5),"Stuff For Work")
def main():
path = "hw3/"
f = []
for (d... | Python | zaydzuhri_stack_edu_python |
import urllib.request
import easygui as g
import sys
import os
set msg1 = string 请填写喵的尺寸
set title1 = string 下载一只喵
set fields1 = list string 宽: string 高:
set values1 = list 400 600
while true
begin
set res = call multenterbox msg=msg1 title=title1 fields=fields1 values=values1
if res == none
begin
exit 0
end
set turl =... | import urllib.request
import easygui as g
import sys
import os
msg1 = '请填写喵的尺寸'
title1 = '下载一只喵'
fields1 = ['宽:', '高:']
values1 = [400, 600]
while True:
res = g.multenterbox(msg = msg1, title = title1, fields = fields1, values = values1)
if res == None:
sys.exit(0)
turl = 'http://placekitten.com/g... | Python | zaydzuhri_stack_edu_python |
string Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. Example: n = 15, Return: [ "1", "2", "Fizz... | """
Write a program that outputs the string representation of numbers from 1 to n.
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,
Return:
[
"1",
"... | Python | zaydzuhri_stack_edu_python |
function process_merged_dataframe chunk max_taxa_per_query
begin
set data = copy chunk
return call parse_query_counts call drop_rows_over_max_taxa call add_taxa_count data max_taxa_per_query
end function | def process_merged_dataframe(chunk, max_taxa_per_query):
data = chunk.copy()
return parse_query_counts(
drop_rows_over_max_taxa(
add_taxa_count(data),
max_taxa_per_query)) | Python | nomic_cornstack_python_v1 |
function _check_cdf2
begin
set df = 3
set t = list comprehension call _simulate_chi2 for i in range 1000
set t2 = list comprehension call cdf x df for x in t
set cdf = call _make_cdf_from_list t2
call _cdf cdf
call _show
end function | def _check_cdf2():
df = 3
t = [_simulate_chi2() for i in range(1000)]
t2 = [scipy.stats.chi2.cdf(x, df) for x in t]
cdf = _13_Cdf._make_cdf_from_list(t2)
_05_myplot._cdf(cdf)
_05_myplot._show() | Python | nomic_cornstack_python_v1 |
comment Import Pmw from this directory tree.
import sys
set path at slice : 0 : = list string ../../..
import tkinter
import Pmw
class Demo
begin
function __init__ self parent
begin
comment Create button to launch the toplevel with main menubar.
set w = call Button parent text=string Show Pmw.MainMenuBar demo command... | # Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']
import tkinter
import Pmw
class Demo:
def __init__(self, parent):
# Create button to launch the toplevel with main menubar.
w = tkinter.Button(parent, text = 'Show Pmw.MainMenuBar demo',
command = lambda ... | Python | zaydzuhri_stack_edu_python |
function is_good_response resp
begin
set content_type = lower headers at string Content-Type
return status_code == 200 and content_type is not none and find content_type string html > - 1
end function | def is_good_response(resp):
content_type = resp.headers['Content-Type'].lower()
return (resp.status_code == 200
and content_type is not None
and content_type.find('html') > -1) | Python | nomic_cornstack_python_v1 |
function read_grid self query **kwargs
begin
set show = false
if string show in keys kwargs
begin
set show = kwargs at string show
end
set data = list
set cv_image = none
for f in find grid query
begin
append data read f
end
for image in data
begin
set np_image = call fromstring image uint8
set cv_image = call imdecod... | def read_grid(self, query, **kwargs):
show = False
if 'show' in kwargs.keys():
show = kwargs['show']
data = []
cv_image = None
for f in self.grid.find(query):
data.append(f.read())
for image in data:
np_image = np.fromstring(image, np.... | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template , request , redirect
comment import the function that will return an instance of a connection
from mysqlconnection import connectToMySQL
set app = call Flask __name__
set id = 0
decorator call route string /
function index
begin
comment call the function, passing in the name of... | from flask import Flask, render_template, request, redirect
from mysqlconnection import connectToMySQL # import the function that will return an instance of a connection
app = Flask(__name__)
id = 0
@app.route('/')
def index():
mysql = connectToMySQL('first_flask') # call the function, passing in the nam... | Python | zaydzuhri_stack_edu_python |
import datetime as dt
class Record
begin
function __init__ self amount comment date=none
begin
set amount = amount
set comment = comment
if date is none
begin
set date = today
end
else
begin
set date = call date
end
end function
end class
class Calculator
begin
function __init__ self limit
begin
set limit = limit
set c... | import datetime as dt
class Record:
def __init__(self, amount: float, comment: str, date=None):
self.amount = amount
self.comment = comment
if date is None:
self.date = dt.date.today()
else:
self.date = dt.datetime.strptime(date, "%d.%m.%Y").date()
class C... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from LOGINPAGE import *
function sign
begin
class signup
begin
function __init__ self root
begin
set root = root
set geometry = string 700x700
call maxsize 700 700
call minsize 700 700
title root string Sign Up
call configure bg=string grey
set signuplabel = call Label root width=30 justify=CENTER... | from tkinter import *
from LOGINPAGE import *
def sign():
class signup:
def __init__(self,root):
self.root=root
root.geometry=('700x700')
root.maxsize(700,700)
root.minsize(700,700)
root.title('Sign Up')
root.configure(bg='grey')
... | Python | zaydzuhri_stack_edu_python |
function connect sqlite_file
begin
debug string Open DB [%s] sqlite_file
set conn = call connect sqlite_file
set text_factory = str
set acursor = call cursor
debug string Opened DB [%s] sqlite_file
return tuple conn acursor
end function | def connect(sqlite_file):
logging.debug('Open DB [%s]', sqlite_file)
conn = lite.connect(sqlite_file)
conn.text_factory = str
acursor = conn.cursor()
logging.debug('Opened DB [%s]', sqlite_file)
return conn, acursor | Python | nomic_cornstack_python_v1 |
function draw self network file_format path=none
begin
try
begin
import cairocffi as cairo
end
except ImportError
begin
try
begin
import cairo
end
except ImportError
begin
warning string Cairo not found; potential energy surface will not be drawn.
return
end
end
set network = network
comment The order of wells is as fo... | def draw(self, network, file_format, path=None):
try:
import cairocffi as cairo
except ImportError:
try:
import cairo
except ImportError:
logging.warning('Cairo not found; potential energy surface will not be drawn.')
re... | Python | nomic_cornstack_python_v1 |
import string
function letter_frequency sentence
begin
comment 统计字母和空格
set chars = list ascii_letters + list string
set frequencies = list comprehension tuple c 0 for c in chars
for letter in sentence
begin
set index = index chars letter
comment print(frequencies[index])
comment print(frequencies[index][1])
set freque... | import string
def letter_frequency(sentence):
# 统计字母和空格
chars = list(string.ascii_letters) + [" "]
frequencies = [(c, 0) for c in chars]
for letter in sentence:
index = chars.index(letter)
# print(frequencies[index])
# print(frequencies[index][1])
frequencies[index] = (... | Python | zaydzuhri_stack_edu_python |
for x in range length lst
begin
append newlst lst at x * 2
end
print newlst | for x in range(len(lst)):
newlst.append(lst[x] *2)
print(newlst)
| Python | zaydzuhri_stack_edu_python |
function attach_process *args
begin
return call attach_process *args
end function | def attach_process(*args):
return _idaapi.attach_process(*args) | Python | nomic_cornstack_python_v1 |
function updateParameters self parameters
begin
return
end function | def updateParameters(self, parameters):
return | Python | nomic_cornstack_python_v1 |
function __orthogonal_indexing__ self
begin
return true
end function | def __orthogonal_indexing__(self):
return True | Python | nomic_cornstack_python_v1 |
function test_registr_incorrect_value self
begin
set REGISTRATION_DATA at string email = string admin@gmail
set return_data = call user_registration REGISTRATION_DATA
set ERROR_DATA at string error = list dict string email ERROR_MSG at string check_email % string email
set REGISTRATION_DATA at string email = string adm... | def test_registr_incorrect_value(self):
REGISTRATION_DATA['email'] = "admin@gmail"
return_data = validator.user_registration(REGISTRATION_DATA)
ERROR_DATA['error'] = [{'email': ERROR_MSG['check_email']
% 'email'}]
REGISTRATION_DATA['email'] = 'adm... | Python | nomic_cornstack_python_v1 |
from random import shuffle
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import time
from datetime import timedelta
from sklearn.metrics import confusion_matrix
from typing import NamedTuple
class Meta extends NamedTuple
begin
set metadata_size : int
set state_size : int... | from random import shuffle
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import time
from datetime import timedelta
from sklearn.metrics import confusion_matrix
from typing import NamedTuple
class Meta(NamedTuple):
metadata_size: int
state_size: int
num_act... | Python | zaydzuhri_stack_edu_python |
comment /usr/bin/python3.6
comment -*- coding:utf-8 -*-
class Solution extends object
begin
function getMaximumGold self grid
begin
string :type grid: List[List[int]] :rtype: int
set row = length grid
set col = length grid at 0
function dfs i j
begin
if 0 <= i < row and 0 <= j < col and grid at i at j > 0
begin
set cur... | # /usr/bin/python3.6
# -*- coding:utf-8 -*-
class Solution(object):
def getMaximumGold(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
self.row = len(grid)
self.col = len(grid[0])
def dfs(i, j):
if 0 <= i < self.row and 0 <= j < sel... | Python | zaydzuhri_stack_edu_python |
function read_chunk fobj off l head
begin
import fastavro
if has attribute fastavro string iter_avro
begin
set reader = iter_avro
end
else
begin
set reader = reader
end
with fobj as f
begin
set chunk = call read_block f off l head at string sync
end
set head_bytes = head at string head_bytes
if not starts with chunk MA... | def read_chunk(fobj, off, l, head):
import fastavro
if hasattr(fastavro, "iter_avro"):
reader = fastavro.iter_avro
else:
reader = fastavro.reader
with fobj as f:
chunk = read_block(f, off, l, head["sync"])
head_bytes = head["head_bytes"]
if not chunk.startswith(MAGIC):
... | Python | nomic_cornstack_python_v1 |
function get_queryset self
begin
set site = call get_current_site request
return filter site=site
end function | def get_queryset(self):
site = get_current_site(self.request)
return Video.objects.filter(site=site) | Python | nomic_cornstack_python_v1 |
string 04.A tabela abaixo demonstra a quantidade de vendas dos fabricantes de veículos durante o período de 2013 a 2018, em mil unidades. Fabricante/Ano 2013 2014 2015 2016 2017 2018 Fiat 204 223 230 257 290 322 Ford 195 192 198 203 208 228 GM 220 222 217 231 245 280 Wolkswagen 254 262 270 284 296 330 Faça um programa ... | '''
04.A tabela abaixo demonstra a quantidade de vendas dos fabricantes de veículos durante o período de 2013 a 2018, em
mil unidades.
Fabricante/Ano 2013 2014 2015 2016 2017 2018
Fiat 204 223 230 257 290 322
Ford 195 192 198 203 20... | Python | zaydzuhri_stack_edu_python |
function blobs self min_r=none max_r=none num_r=25 threshold=0.0 max_overlap=0.0 log_scale=false exclude_edges=0 exclude_scale_endpoints=false ignore_missing=false
begin
set bset = bset
if not regular
begin
raise call ValueError format string instances of {} must be defined over a regular {} instance (having bins of eq... | def blobs(self, min_r=None, max_r=None, num_r=25, threshold=0.0,
max_overlap=0.0, log_scale=False, exclude_edges=0,
exclude_scale_endpoints=False, ignore_missing=False):
bset = self.bset
if not bset.regular:
raise ValueError("instances of {} must be defined over a... | Python | nomic_cornstack_python_v1 |
import math
set x = - 5.999
set y = 198.42
set result1 = call fabs x
set result2 = floor y
print result1 string is the absolute value of x
print result2 string is the floor y | import math
x = -5.999
y = 198.42
result1 = math.fabs(x)
result2 = math.floor(y)
print(result1, " is the absolute value of ", x)
print(result2, " is the floor ", y)
| Python | zaydzuhri_stack_edu_python |
function reset_old_compute_state self
begin
comment nothing to do
pass
end function | def reset_old_compute_state(self):
pass # nothing to do | Python | nomic_cornstack_python_v1 |
function id self id
begin
set _id = id
end function | def id(self, id):
self._id = id | Python | nomic_cornstack_python_v1 |
function post_restr self
begin
return call AndList list string trainer_fn = prev_trainer_fn string trainer_hash = prev_trainer_hash string dataset_fn = prev_dataset_fn string dataset_hash = prev_dataset_hash
end function | def post_restr(self) -> dj.AndList:
return dj.AndList(
[
"trainer_fn = prev_trainer_fn",
"trainer_hash = prev_trainer_hash",
"dataset_fn = prev_dataset_fn",
"dataset_hash = prev_dataset_hash",
]
) | Python | nomic_cornstack_python_v1 |
function pad self minibatch
begin
comment Compute maximum length with __NEW_EQN and __END_EQN.
comment 2 = BOE/EOE
set max_len = max generator expression length item for item in minibatch + 2
set padded_batch = list
comment Padding for no-operand functions (i.e. special commands)
set max_arity_pad = list tuple none no... | def pad(self, minibatch: List[List[Tuple[str, list]]]) -> List[List[Tuple[str, list]]]:
# Compute maximum length with __NEW_EQN and __END_EQN.
max_len = max(len(item) for item in minibatch) + 2 # 2 = BOE/EOE
padded_batch = []
# Padding for no-operand functions (i.e. special commands)
... | Python | nomic_cornstack_python_v1 |
comment 默认按照升序排序
comment gl_list.sort()
comment 如果需要降序排序, 需要传递 reverse 参数
sort gl_list reverse=true
print gl_list | # 默认按照升序排序
# gl_list.sort()
# 如果需要降序排序, 需要传递 reverse 参数
gl_list.sort(reverse=True)
print(gl_list) | Python | zaydzuhri_stack_edu_python |
comment Translate SVN path to local file system path in Python
set baselen = length basePath
return generator expression replace path at slice baselen : : string / string \ for path in paths | # Translate SVN path to local file system path in Python
baselen = len(self.basePath)
return (path[baselen:].replace("/", "\\") for path in paths)
| Python | zaydzuhri_stack_edu_python |
function type self
begin
return get pulumi self string type
end function | def type(self) -> str:
return pulumi.get(self, "type") | Python | nomic_cornstack_python_v1 |
function __eq__ self other
begin
if not is instance other Referer
begin
return false
end
return __dict__ == __dict__
end function | def __eq__(self, other):
if not isinstance(other, Referer):
return False
return self.__dict__ == other.__dict__ | Python | nomic_cornstack_python_v1 |
function key_gen blocks=3 chars=5 length=32 keys=1000 filename=string keys.txt
begin
comment Generate, avoiding repetition
set keys_set = set list comprehension call gen_a_key blocks chars length for _ in range keys
while length keys_set < keys
begin
add keys_set call gen_a_key blocks chars length
end
with open filenam... | def key_gen(blocks=3, chars=5, length=32, keys=1000, filename="keys.txt"):
# Generate, avoiding repetition
keys_set = set([gen_a_key(blocks, chars, length) for _ in range(keys)])
while len(keys_set) < keys:
keys_set.add(gen_a_key(blocks, chars, length))
with open(filename, "w") as t:
... | Python | nomic_cornstack_python_v1 |
function create_dashboard_table_head rules_columns rtype rstate sort_key sort_order search_query=string group_op=true macro_file=string macros.j2 macro_name=string build_rules_thead
begin
set tstring = string {%
set tstring = tstring + string from ' { macro_file } ' import { macro_name }
set tstring = tstring + string... | def create_dashboard_table_head(
rules_columns,
rtype,
rstate,
sort_key,
sort_order,
search_query="",
group_op=True,
macro_file="macros.j2",
macro_name="build_rules_thead",
):
tstring = "{% "
tstring = tstring + f"from '{macro_file}' import {macro_name}"
tstring = tstring... | Python | nomic_cornstack_python_v1 |
from collections import Counter
function read_file filename
begin
set file_data = open filename
set data = list map lambda line -> strip line file_data
return data
end function
function count_letters line
begin
return counter line
end function
function does_repeat_x_times line x
begin
set letter_count = call count_lett... | from collections import Counter
def read_file(filename):
file_data = open(filename)
data = list(map(lambda line: line.strip(), file_data))
return data
def count_letters(line: str) -> Counter:
return Counter(line)
def does_repeat_x_times(line: str, x: int) -> bool:
letter_count = count_letters(... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Time : 2020/6/9 16:09
comment @Author : AsiHacker
comment @Site :
comment @File : yied_demo.py
comment @Software: PyCharm
set test_list = list string jb1 string jb2 string jb3
function get_test test_list
begin
for key in test_list
begin
comment yield 就... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/6/9 16:09
# @Author : AsiHacker
# @Site :
# @File : yied_demo.py
# @Software: PyCharm
test_list = ['jb1', 'jb2', 'jb3']
def get_test(test_list: list):
for key in test_list:
yield key # yield 就是返回,但是她可以记住上次的位置
def get_test2(test_li... | Python | zaydzuhri_stack_edu_python |
function removeIpAddresses self uids=none
begin
set data = copy locals
del data at string self
set resp = call make_request url_path string NetworkRouter string removeIpAddresses list data
return call create_response resp
end function | def removeIpAddresses(self, uids=None):
data = locals().copy()
del data["self"]
resp = client.make_request(self.url_path, "NetworkRouter", "removeIpAddresses", [data])
return create_response(resp) | Python | nomic_cornstack_python_v1 |
function on_launch launch_request session
begin
print string on_launch requestId= + launch_request at string requestId + string , sessionId= + session at string sessionId
comment Dispatch to your skill's launch
return call get_welcome_response session at string sessionId
end function | def on_launch(launch_request, session):
print("on_launch requestId=" + launch_request['requestId'] +
", sessionId=" + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response(session['sessionId']) | Python | nomic_cornstack_python_v1 |
function register_simulant_initializer self initializer creates_columns=tuple requires_columns=tuple requires_values=tuple requires_streams=tuple
begin
add _initializer_components initializer creates_columns
set dependencies = list comprehension string column. { name } for name in requires_columns + list comprehensi... | def register_simulant_initializer(
self,
initializer: Callable,
creates_columns: List[str] = (),
requires_columns: List[str] = (),
requires_values: List[str] = (),
requires_streams: List[str] = (),
):
self._initializer_components.add(initializer, creates_colum... | Python | nomic_cornstack_python_v1 |
function _cutadapt_trim fastq_files quality_format adapters out_files cores
begin
if quality_format == string illumina
begin
set quality_base = string 64
end
else
begin
set quality_base = string 33
end
comment --times=2 tries twice remove adapters which will allow things like:
comment realsequenceAAAAAAadapter to remov... | def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, cores):
if quality_format == "illumina":
quality_base = "64"
else:
quality_base = "33"
# --times=2 tries twice remove adapters which will allow things like:
# realsequenceAAAAAAadapter to remove both the poly-A ... | Python | nomic_cornstack_python_v1 |
comment basement of the all supporter
comment simulate hand to click and drag, eyes to observe game stage
import copy
import pyautogui
import random
import sys
import time
comment call click() to simulate the click operation
comment parameter:
comment area: where should to be clicked, a random point in the give area wi... | # basement of the all supporter
# simulate hand to click and drag, eyes to observe game stage
import copy
import pyautogui
import random
import sys
import time
# call click() to simulate the click operation
# parameter:
# area: where should to be clicked, a random point in the give area will be clicked
# (use a 2*2... | Python | zaydzuhri_stack_edu_python |
string Created on Jan 10, 2015 @author: cksharma
class Solution
begin
comment @return a list of integers
function grayCode self n
begin
set ans = list
append ans 0
for i in range n
begin
for j in reversed range length ans
begin
append ans ans at j + 1 ? i
end
end
return ans
end function
end class
if __name__ == string ... | '''
Created on Jan 10, 2015
@author: cksharma
'''
class Solution:
# @return a list of integers
def grayCode(self, n):
ans = list();
ans.append(0);
for i in range(n):
for j in reversed(range(len(ans))):
ans.append(ans[j] + (1 << i));
return ans;
if __n... | Python | zaydzuhri_stack_edu_python |
string A script to generate reference data for testing. This can be run from the command line.
import os
import argparse
from qaccel.reference import make_muller_reference_data , make_alanine_reference_data , get_src_kinase_data
function make_reference_data dirname alanine=true muller=true srckinase=false
begin
string ... | """A script to generate reference data for testing.
This can be run from the command line.
"""
import os
import argparse
from qaccel.reference import make_muller_reference_data, \
make_alanine_reference_data, get_src_kinase_data
def make_reference_data(dirname, alanine=True, muller=True, srckinase=False):
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set a = array list list 3 4 list 1 - 1 list 7 3
print
set musk = zeros shape
print a * musk
set one_sample = lambda row -> call diag row - matrix multiply reshape row - 1 1 reshape row 1 - 1
set Print = lambda row -> print row
set b = array list list list 1 1 list 0 1 list list 3 4 list 5 1 list list... | import numpy as np
a = np.array([
[3,4],
[1,-1],
[7,3]
])
print()
musk = np.zeros(a[0].shape)
print(a*musk)
one_sample = lambda row: np.diag(row) - np.matmul(row.reshape(-1,1),row.reshape(1,-1))
Print = lambda row: print (row)
b = np.array([
[[1,1],
[0,1]],
[[3,4],
[5,1]],
[[1,2],... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[2]:
import requests
from bs4 import BeautifulSoup
from __future__ import print_function
from bs4 import BeautifulSoup
from __future__ import print_function
import csv
if __name__ == string __main__
begin
print string Enter the person name
set n = call raw_in... | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import requests
from bs4 import BeautifulSoup
from __future__ import print_function
from bs4 import BeautifulSoup
from __future__ import print_function
import csv
if __name__ == '__main__':
print("Enter the person name")
n = raw_input()
print(n)
main_url... | Python | zaydzuhri_stack_edu_python |
function _get_entity_mappings query_list
begin
set entity_labels = set
info string Generating Entity Labels...
for tuple d i entities in zip call domains call intents call entities
begin
if length entities
begin
for entity in entities
begin
set e = string type
add entity_labels string { d } . { i } .B| { e }
add entity... | def _get_entity_mappings(query_list: ProcessedQueryList) -> Dict:
entity_labels = set()
logger.info("Generating Entity Labels...")
for d, i, entities in zip(
query_list.domains(), query_list.intents(), query_list.entities()
):
if len(entities):
for... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import scrapy
from qzstory.items import QzStorysItem , QzStoryItem
class qzSpider extends Spider
begin
set name = string qzspider
set allowed_domains = list string http://www.gushi365.com
set start_urls = list string http://www.gushi365.com/
comment def start_requests(self):
comment yield ... | # -*- coding: utf-8 -*-
import scrapy
from qzstory.items import QzStorysItem,QzStoryItem
class qzSpider(scrapy.Spider):
name = 'qzspider'
allowed_domains = ['http://www.gushi365.com']
start_urls = [
'http://www.gushi365.com/',
]
# def start_requests(self):
# yield scrapy.Request("h... | Python | zaydzuhri_stack_edu_python |
import sys
function isithalloween lines
begin
if lines at 0 == string OCT 31 or lines at 0 == string DEC 25
begin
return string yup
end
return string nope
end function
function main
begin
set lines = list comprehension strip line for line in stdin
print call isithalloween lines
end function
call main | import sys
def isithalloween(lines):
if lines[0] == "OCT 31" or lines[0] == "DEC 25":
return "yup"
return "nope"
def main():
lines = [line.strip() for line in sys.stdin]
print(isithalloween(lines))
main()
| Python | zaydzuhri_stack_edu_python |
import random
set plaintext = call raw_input string Enter the plaintext:
set key = call raw_input string Enter the key:
set splittedKey = list key
set splittedPlaintext = list plaintext
set listOfRows = list
for letter in splittedKey
begin
set row = list
for i in range length splittedKey
begin
set x = ordinal letter ... | import random
plaintext = raw_input("Enter the plaintext: ")
key = raw_input("Enter the key: ")
splittedKey = list(key)
splittedPlaintext = list(plaintext)
listOfRows = []
for letter in splittedKey:
row = []
for i in range(len(splittedKey)):
x = ord(letter)+i
if x>122:
x -= 26
... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment usage: python3 test.py -m "{\"dates\": [\"2018-10-29\", \"2018-10-21\"], \"isRegen\": false}"
import pandas as pd
import requests
from lxml import html
import json
import re
import argparse
from datetime import datetime
function get_url day month year
begin
return string https://www.basket... | # coding: utf-8
# usage: python3 test.py -m "{\"dates\": [\"2018-10-29\", \"2018-10-21\"], \"isRegen\": false}"
import pandas as pd
import requests
from lxml import html
import json
import re
import argparse
from datetime import datetime
def get_url(day, month, year):
return("https://www.basketball-reference.com/f... | Python | zaydzuhri_stack_edu_python |
function setReferenceId self *args
begin
return call ReferenceGlyph_setReferenceId self *args
end function | def setReferenceId(self, *args):
return _libsbml.ReferenceGlyph_setReferenceId(self, *args) | Python | nomic_cornstack_python_v1 |
import collections
print string dict : end=string
set d1 = dict
set d1 at string a = string A
set d1 at string b = string B
set d1 at string c = string C
set d2 = dict
set d2 at string c = string C
set d2 at string b = string B
set d2 at string a = string A
print d1 == d2
print string OrderedDict: end=string
set d1 =... | import collections
print('dict :', end=' ')
d1 = {}
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d2 = {}
d2['c'] = 'C'
d2['b'] = 'B'
d2['a'] = 'A'
print(d1 == d2)
print('OrderedDict:', end=' ')
d1 = collections.OrderedDict()
d1['a'] = 'A'
d1['b'] = 'B'
d1['c'] = 'C'
d2 = collections.OrderedDict()
d2['c'] = 'C'... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Ciphers.Transposition ~~~~~~~~~~~~~~~~~~~~~ This module implements the processes needed to decipher Transposition ciphers.
import itertools
import random
from string import ascii_lowercase as ALPH
from string import digits as NUMS
from Formatting import Format , SpaceAdd
from Proces... | # -*- coding: utf-8 -*-
"""
Ciphers.Transposition
~~~~~~~~~~~~~~~~~~~~~
This module implements the processes needed to decipher Transposition ciphers.
"""
import itertools
import random
from string import ascii_lowercase as ALPH
from string import digits as NUMS
from Formatting import Format, SpaceAdd... | Python | zaydzuhri_stack_edu_python |
function add_title_text img title_pane key mode num_gstrings
begin
set title = string { key } { mode } on a { num_gstrings } string guitar
return call add_text img=img rectangle=title_pane text=title
end function | def add_title_text(img: Img, title_pane: GeometricRectangle, key: str, mode: str, num_gstrings: int) -> Img:
title = f'{key} {mode} on a {num_gstrings} string guitar'
return add_text(img=img, rectangle=title_pane, text=title) | Python | nomic_cornstack_python_v1 |
comment boleh liat" asal jangan di recode
comment untuk pembelajaran
import sys | # boleh liat" asal jangan di recode
# untuk pembelajaran
import sys | Python | zaydzuhri_stack_edu_python |
comment Logging
import logging
set log = call getLogger __name__
comment Python Utility imports
import os
import json
import configargparse
import time
import geocoder
import sys
import re
from glob import glob
from datetime import datetime , timedelta
from math import radians , sin , cos , atan2 , sqrt
from s2sphere i... | #Logging
import logging
log = logging.getLogger(__name__)
#Python Utility imports
import os
import json
import configargparse
import time
import geocoder
import sys
import re
from glob import glob
from datetime import datetime, timedelta
from math import radians, sin, cos, atan2, sqrt
from s2sphere import LatLng
#Loc... | Python | zaydzuhri_stack_edu_python |
for key in graph
begin
set graph at key = set list comprehension i for i in graph at key
end
set a = list
while true
begin
set com = input
if com == string q
begin
break
end
set x = integer input
if com == string i
begin
set y = integer input
if x in graph
begin
add graph at x y
end
else
begin
set graph at x = set lis... | for key in graph: graph[key] = set([i for i in graph[key]])
a = []
while True:
com = input()
if com == "q": break
x = int(input())
if com == "i":
y = int(input())
if x in graph: graph[x].add(y)
else: graph[x] = set([y])
if y in graph: graph[y].add(x)
el... | Python | zaydzuhri_stack_edu_python |
import math
print absolute - 44
print call fabs - 54
print ceil 44.5434
print floor 44.5434
print call factorial 3
print max 2 3 4 5 5 6 6 6 6 78
print min 2 3 4 5 5 6 6 6 6 78
print square root 4
print power 2 5 | import math
print(abs(-44))
print(math.fabs(-54))
print(math.ceil(44.5434))
print(math.floor(44.5434))
print(math.factorial(3))
print(max(2,3,4,5,5,6,6,6,6,78))
print(min(2,3,4,5,5,6,6,6,6,78))
print(math.sqrt(4))
print(math.pow(2,5))
| Python | zaydzuhri_stack_edu_python |
function say_hello
begin
comment block belonging to the function
print string hello world
end function
comment End of function
comment call the function
call say_hello
call say_hello
comment --------------------------------------------------------------------
comment Function Parameters
function print_max a b
begin
if ... | def say_hello():
# block belonging to the function
print('hello world')
# End of function
say_hello() # call the function
say_hello()
# --------------------------------------------------------------------
# Function Parameters
def print_max(a, b):
if a > b:
print(a, 'is maximum')
elif a ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import numpy as np
string Constraints and the gradient of the constraints:
function c_function x lambda_low lambda_high
begin
set c = zeros 5
set c at 0 = x at 0 - lambda_low
set c at 1 = - x at 0 + lambda_high
set c at 2 = x at 2 - lambda_low
set c at 3 = - x ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
'''Constraints and the gradient of the constraints: '''
def c_function(x, lambda_low, lambda_high):
c=np.zeros(5)
c[0]=x[0] - lambda_low
c[1]=-x[0] + lambda_high
c[2]=x[2] - lambda_low
c[3]=-x[2] + lambda_high
c[4]=x[0]*x[2] - lam... | Python | zaydzuhri_stack_edu_python |
function get_event_transaction_id
begin
return get call get_cache string event_transaction string id none
end function | def get_event_transaction_id():
return get_cache('event_transaction').get('id', None) | Python | nomic_cornstack_python_v1 |
function convert_mp3_to_ogg self filename
begin
set mp3_path = join path directory filename
set ogg_path = replace mp3_path extension_mp3 extension_ogg
if is file path ogg_path
begin
comment already done
return
end
set command = list FFMPEG_BIN string -i mp3_path ogg_path
set pipe = popen command shell=false stdout=PIP... | def convert_mp3_to_ogg(self, filename: str):
mp3_path = os.path.join(self.directory, filename)
ogg_path = mp3_path.replace(self.extension_mp3, self.extension_ogg)
if os.path.isfile(ogg_path):
# already done
return
command = [FFMPEG_BIN, '-i', mp3_path, ogg_path]
... | 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.