code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string 策略模式
from abc import ABCMeta , abstractclassmethod
class Strategy
begin
decorator abstractclassmethod
function execute self data
begin
pass
end function
end class
class FastStrategy extends Strategy
begin
function execute self data
begin
print string fast method: data
end function
end class
class SlowStrategy ex... | ''' 策略模式
'''
from abc import ABCMeta, abstractclassmethod
class Strategy(metaclass=ABCMeta):
@abstractclassmethod
def execute(self, data):
pass
class FastStrategy(Strategy):
def execute(self, data):
print('fast method:', data)
class SlowStrategy(Strategy):
def execute(self, ... | Python | zaydzuhri_stack_edu_python |
function startd_will_hibernate condor_startd machine
begin
comment because we are querying partionable slots, even if the node is full the partionable slot
comment will show as ShouldHibernate, so need to check if the total cpus in the
comment partionable slot == total on machine, if so, no cpus is doing anything and n... | def startd_will_hibernate(condor_startd, machine):
#because we are querying partionable slots, even if the node is full the partionable slot
#will show as ShouldHibernate, so need to check if the total cpus in the
#partionable slot == total on machine, if so, no cpus is doing anything and node truly idle.
... | Python | nomic_cornstack_python_v1 |
function find_gtype stats
begin
comment Throw away individuals with 0 reference and alternate reads.
if stats at string AD at 0 == 0 and stats at string AD at 1 == 0
begin
return none
end
else
if stats at string GT in tuple string 0/0 string 0|0
begin
return string homoRef
end
else
if stats at string GT in tuple string... | def find_gtype(stats):
# Throw away individuals with 0 reference and alternate reads.
if stats['AD'][0] == 0 and stats['AD'][1] == 0:
return None
elif stats['GT'] in ('0/0', '0|0'):
return 'homoRef'
elif stats['GT'] in ('0/1', '0|1', '1/0', '1|0'):
return 'het'
elif... | Python | nomic_cornstack_python_v1 |
comment https://practice.geeksforgeeks.org/problems/maximum-sum-problem/0
string Given a number n, we can divide it in only three parts n/2, n/3 and n/4 (we will consider only integer part). The task is to find the maximum sum we can make by dividing number in three parts recursively and summing up them together. Note:... | # https://practice.geeksforgeeks.org/problems/maximum-sum-problem/0
"""
Given a number n, we can divide it in only three parts n/2, n/3 and n/4 (we will consider only integer part). The task is to find the maximum sum we can make by dividing number in three parts recursively and summing up them together.
Note: Sometim... | Python | zaydzuhri_stack_edu_python |
function set_vsl self voltage
begin
comment Set DC offset to V/2 since it is doubled by FGen for some reason
set func_dc_offset = voltage / 2
end function | def set_vsl(self, voltage):
# Set DC offset to V/2 since it is doubled by FGen for some reason
self.sl_ext_chan.func_dc_offset = voltage/2 | Python | nomic_cornstack_python_v1 |
function popular_messages self convthread_id
begin
if call has_key convthread_id
begin
return dfs at convthread_id
end
else
begin
import warnings
warn string No record matched with convthread_id Warning
return list
end
end function | def popular_messages(self, convthread_id):
if self.dfs.has_key(convthread_id):
return self.dfs[convthread_id]
else:
import warnings
warnings.warn("No record matched with convthread_id", Warning)
return [] | Python | nomic_cornstack_python_v1 |
function _get_page_html self url
begin
set response = get requests url cookies=cookies
set content = decode content string utf-8
return content
end function | def _get_page_html(self, url):
response = requests.get(url, cookies=self.cookies)
content = response.content.decode('utf-8')
return content | Python | nomic_cornstack_python_v1 |
function tallenna_henkilo henkilo
begin
comment CSV nimi(string);ika(int);pituus(float) --> lisätään tiedostoon merkkijonona
with open string henkilot.csv string a as tiedosto
begin
set henkilotieto = henkilo at 0 + string ; + string henkilo at 1 + string ; + string henkilo at 2
write tiedosto henkilotieto + string
end... | def tallenna_henkilo(henkilo: tuple):
# CSV nimi(string);ika(int);pituus(float) --> lisätään tiedostoon merkkijonona
with open ("henkilot.csv", "a") as tiedosto:
henkilotieto = henkilo[0] + ";" + str(henkilo[1]) + ";" + str(henkilo[2])
tiedosto.write(henkilotieto + "\n")
#main
if __name__ == ... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from PyDictionary import PyDictionary
set root = call Tk
call geometry string 250x200
title root string Dictionary
function find_meaning
begin
set word = get e1
set dictionary = call PyDictionary word
set meaning = call printMeanings
print meaning
end function
set e1 = call Entry root font=tuple s... | from tkinter import *
from PyDictionary import PyDictionary
root=Tk()
root.geometry("250x200")
root.title("Dictionary")
def find_meaning():
word = e1.get()
dictionary = PyDictionary(word)
meaning = dictionary.printMeanings()
print(meaning)
e1 = Entry(root, font=("times", 15, "bold"))
e1.grid(row=2, c... | Python | zaydzuhri_stack_edu_python |
import autograd.numpy as np
from line_search import get_line_length
from helpers import many_matmul
function newton f grad_f hess_f x
begin
print string This doesn't work because the hessian is not always PD. There are ways around this (see 3.4 in NW). I just haven't implemented them.
set positions = list x
while norm ... | import autograd.numpy as np
from .line_search import get_line_length
from helpers import many_matmul
def newton(f, grad_f, hess_f, x):
print("""
This doesn't work because the hessian is not always PD.
There are ways around this (see 3.4 in NW). I just haven't implemented them.
""")
positions = [x]
... | Python | zaydzuhri_stack_edu_python |
function initGui self
begin
set icon_path = string :/plugins/QGISSolr/icon.png
call add_action icon_path text=call tr string QGIS SOLR Query callback=run parent=call mainWindow
comment will be set False in run()
set first_start = true
end function | def initGui(self):
icon_path = ':/plugins/QGISSolr/icon.png'
self.add_action(
icon_path,
text=self.tr(u'QGIS SOLR Query'),
callback=self.run,
parent=self.iface.mainWindow())
# will be set False in run()
self.first_start = ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
function roman_to_int roman_string
begin
if type roman_string is not str or roman_string is none
begin
return 0
end
set num = list
for i in roman_string
begin
if i == string I
begin
append num 1
end
if i == string V
begin
append num 5
end
if i == string X
begin
append num 10
end
if i == strin... | #!/usr/bin/python3
def roman_to_int(roman_string):
if type(roman_string) is not str or roman_string is None:
return 0
num = []
for i in roman_string:
if i == 'I':
num.append(1)
if i == 'V':
num.append(5)
if i == 'X':
num.append(10)
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
comment 基本计算器.py
string 实现一个基本的计算器来计算一个简单的字符串表达式的值。 字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。 示例 1: 输入: "1 + 1" 输出: 2 示例 2: 输入: " 2-1 + 2 " 输出: 3 示例 3: 输入: "(1+(4+5+2)-3)+(6+8)" 输出: 23 说明: 你可以假设所给定的表达式都是有效的。 请不要使用内置的库函数 eval。
string 思路:使用栈。
set __author__ = ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 基本计算器.py
"""
实现一个基本的计算器来计算一个简单的字符串表达式的值。
字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。
示例 1:
输入: "1 + 1"
输出: 2
示例 2:
输入: " 2-1 + 2 "
输出: 3
示例 3:
输入: "(1+(4+5+2)-3)+(6+8)"
输出: 23
说明:
你可以假设所给定的表达式都是有效的。
请不要使用内置的库函数 eval。
"""
"""
思路:使用栈。
"""
__author__ = 'Aiyane'
clas... | Python | zaydzuhri_stack_edu_python |
comment Function for calculating the
comment greatest common divisor
function gcd a b
begin
if a == 0
begin
return b
end
return call gcd b % a a
end function
comment Take input from the user
set val1 = integer input string Enter the first value:
set val2 = integer input string Enter the second value:
comment Calculate ... | # Function for calculating the
# greatest common divisor
def gcd(a, b):
if (a == 0):
return b
return gcd(b%a, a)
# Take input from the user
val1 = int(input("Enter the first value: "))
val2 = int(input("Enter the second value: "))
# Calculate the gcd
result = gcd(val1, val2)
print("The GCD... | Python | flytech_python_25k |
function start self
begin
set thread = thread target=broadcast_thread
set daemon = true
start thread
end function | def start(self):
thread = threading.Thread(target=self.broadcast_thread)
thread.daemon = True
thread.start() | Python | nomic_cornstack_python_v1 |
function replace_whitespaces string character
begin
return replace string string character
end function | def replace_whitespaces(string, character):
return string.replace(" ", character) | Python | iamtarun_python_18k_alpaca |
comment -*- coding: utf-8 -*-
string ------------------------------------------------ describe: 识别网站所用技术,主要用到了builtwith ------------------------------------------------
import builtwith
set __version__ = string v.10
set __author__ = string PyGo
set __time__ = string 2017/3/5
set url = string http://example.webscraping.... | # -*- coding: utf-8 -*-
"""
------------------------------------------------
describe:
识别网站所用技术,主要用到了builtwith
------------------------------------------------
"""
import builtwith
__version__ = "v.10"
__author__ = "PyGo"
__time__ = "2017/3/5"
url = 'http://example.webscraping.com'
rlt = builtwith.parse(url) | Python | zaydzuhri_stack_edu_python |
class Foo extends object
begin
function __init__ self
begin
set name = string wupeiqi
end function
function func self
begin
return string func
end function
end class
set obj = call Foo
comment #### 检查是否含有成员 ####
print has attribute obj string name
print has attribute obj string func
print has attribute obj string funac... | class Foo(object):
def __init__(self):
self.name = 'wupeiqi'
def func(self):
return 'func'
obj = Foo()
# #### 检查是否含有成员 ####
print(hasattr(obj, 'name'))
print(hasattr(obj, 'func'))
print(hasattr(obj, 'funac'))
# #### 获取成员 ####
print(getattr(obj, 'name'))
print(getattr(obj, 'func'))
# #### 设... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import matplotlib.pyplot as plt
import csv
import math
set x1 = list
set y1 = list
set x2 = list
set y2 = list
set h = 0.5 / 1000
set x3 = list comprehension i * h + 0.5 for i in range 0 1001
set y3 = list comprehension log 2 * h * i + 0.5 + h * i + 0.5 * log h * i + 0.5 for i in range 0 1... | #!/usr/bin/python3
import matplotlib.pyplot as plt
import csv
import math
x1 = []
y1 = []
x2 = []
y2 = []
h = 0.5 / 1000
x3 = [ i*h +0.5 for i in range(0,1001) ]
y3 = [ math.log(2)*(h*i+0.5) + (h*i+0.5)*math.log(h*i+0.5) for i in range(0,1001) ]
dy_dx = []
with open("data_TDMA.csv", "r") as f1, open("data_SM.csv", ... | Python | zaydzuhri_stack_edu_python |
import time
from multiprocessing import Lock
class GroupChatManager
begin
string Group chat manager, calculates chat count in specified duration(default 3600 seconds).
set LOCK = lock
function __init__ self duration=none prefix=string groupchat
begin
comment structure: {group_id: {int(timestamp / duration): count}}
set... | import time
from multiprocessing import Lock
class GroupChatManager:
"""Group chat manager, calculates chat count in specified duration(default 3600 seconds)."""
LOCK = Lock()
def __init__(self, duration=None, prefix='groupchat'):
# structure: {group_id: {int(timestamp / duration): count}}
... | Python | zaydzuhri_stack_edu_python |
function mixture_log_pdf x prior_logits means log_scales
begin
set log_ps = call log_softmax prior_logits dim=- 1 + call _log_pdf unsqueeze x dim=- 1 means log_scales
set log_p = call logsumexp log_ps dim=- 1
return log_p
end function | def mixture_log_pdf(x, prior_logits, means, log_scales):
log_ps = F.log_softmax(prior_logits, dim=-1) \
+ _log_pdf(x.unsqueeze(dim=-1), means, log_scales)
log_p = torch.logsumexp(log_ps, dim=-1)
return log_p | Python | nomic_cornstack_python_v1 |
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
import time
import codecs
import os
comment consumer key, consumer secret, access token, access secret.
set ckey = string
set csecret = string
set atoken = string
set asecret = string
print string FileN... | from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
import time
import codecs
import os
#consumer key, consumer secret, access token, access secret.
ckey=""
csecret=""
atoken=""
asecret=""
print("FileName:")
fn = input()
file_name = "data/"+fn+".txt"
... | Python | zaydzuhri_stack_edu_python |
function _for_package_files self pref
begin
assert revision is not none msg string _for_package_files needs PREV
assert revision is not none msg string _for_package_files needs RREV
return call _format_pref package_revision_files pref
end function | def _for_package_files(self, pref):
assert pref.revision is not None, "_for_package_files needs PREV"
assert pref.ref.revision is not None, "_for_package_files needs RREV"
return _format_pref(self.routes.package_revision_files, pref) | Python | nomic_cornstack_python_v1 |
import os
from patricesorter._version import __version__
set VERSION = __version__
set COPYRIGHT = string Copyright (C) 2022
set LICENSE = string MIT | import os
from patricesorter._version import __version__
VERSION = __version__
COPYRIGHT = "Copyright (C) 2022"
LICENSE = "MIT"
| Python | jtatman_500k |
function normalise_space s
begin
return sub string string s
end function | def normalise_space(s):
return whitespace_re.sub(" ", str(s)) | Python | nomic_cornstack_python_v1 |
class AVLNode
begin
function __init__ self key
begin
set key = key
set left = none
set right = none
set height = 1
end function
end class
class AVLTree
begin
function __init__ self
begin
set root = none
end function
function insert self key
begin
set root = call _insert root key
end function
function _insert self node ... | class AVLNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1
class AVLTree:
def __init__(self):
self.root = None
def insert(self, key):
self.root = self._insert(self.root, key)
def _insert(self, node, key):
... | Python | greatdarklord_python_dataset |
function write_common_header self writer
begin
call write_var_octet_string public_key
end function | def write_common_header(self, writer):
writer.write_var_octet_string(self.public_key) | Python | nomic_cornstack_python_v1 |
function merge_file_metadata dup_dict base_dir=string
begin
set metadatas = values dup_dict
set old_file_name = keys dup_dict at 0
end function | def merge_file_metadata(dup_dict, base_dir=''):
metadatas = dup_dict.values()
old_file_name = dup_dict.keys()[0] | Python | nomic_cornstack_python_v1 |
comment Hunter Set 1 Problem 1
import collections as col
set n = integer input
set nums = list map int split input
set c = counter nums
set o = set comprehension k for tuple k v in items c if v > 1
if o
begin
for i in o
begin
print *o
end
end
else
begin
print string unique
end | # Hunter Set 1 Problem 1
import collections as col
n = int(input())
nums = list(map(int, input().split()))
c = col.Counter(nums)
o = {k for k, v in c.items() if v > 1}
if o:
for i in o:
print(*o)
else:
print('unique')
| Python | zaydzuhri_stack_edu_python |
comment 01 Tamanho de strings. Faça um programa que leia 2 strings e informe o conteúdo delas seguido do seu comprimento.
comment Informe também se as duas strings possuem o mesmo comprimento e são iguais ou diferentes no conteúdo.
set string1 = input string Digite uma String:
set string2 = input string Digite outra St... | #01 Tamanho de strings. Faça um programa que leia 2 strings e informe o conteúdo delas seguido do seu comprimento.
# Informe também se as duas strings possuem o mesmo comprimento e são iguais ou diferentes no conteúdo.
string1 = input('Digite uma String: ')
string2 = input('Digite outra String: ')
tamanho_string1 = le... | Python | zaydzuhri_stack_edu_python |
comment https://atcoder.jp/contests/abc109/tasks/abc109_b
set n = integer input
set w = list comprehension input for _ in range n
if length set w < n
begin
print string No
exit
end
for i in range n - 1
begin
if w at i at - 1 == w at i + 1 at 0
begin
continue
end
print string No
exit
end
print string Yes | # https://atcoder.jp/contests/abc109/tasks/abc109_b
n=int(input())
w=[input() for _ in range(n)]
if len(set(w))<n:
print('No')
exit()
for i in range(n-1):
if w[i][-1]==w[i+1][0]: continue
print('No')
exit()
print('Yes') | Python | zaydzuhri_stack_edu_python |
import numpy as np
class BaseModel
begin
string Default class for drawing a figure by formula
function __init__ self formulaXY
begin
string Get formulas for X and Y :param formulaXY: {x: ..., y: ...}
set formula_x = formulaXY at string x
set formula_y = formulaXY at string y
end function
function get_coords self center... | import numpy as np
class BaseModel():
'''
Default class for drawing a figure by formula
'''
def __init__(self, formulaXY: dict):
'''
Get formulas for X and Y
:param formulaXY: {x: ..., y: ...}
'''
self.formula_x = formulaXY['x']
self.formula_y = formula... | Python | zaydzuhri_stack_edu_python |
function detect_using_name_mapping declared
begin
set declared = lower declared
set detected = get call get_declared_to_detected declared
if detected
begin
set licensing = call Licensing
return string parse licensing detected simple=true
end
end function | def detect_using_name_mapping(declared):
declared = declared.lower()
detected = get_declared_to_detected().get(declared)
if detected:
licensing = Licensing()
return str(licensing.parse(detected, simple=True)) | Python | nomic_cornstack_python_v1 |
comment Definition for a binary tree node.
comment class TreeNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Codec
begin
function serialize self root
begin
string Encodes a tree to a single string. :type root: TreeNode :rtype: str
call preorderT... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"... | Python | zaydzuhri_stack_edu_python |
from __future__ import absolute_import
import base64
from colander import SchemaType , null , Invalid , _
import six
from import compat
class AbstractEncodedBytes extends SchemaType
begin
set encoder = none
set decoder = none
function serialize self node appstruct
begin
if appstruct is null
begin
return null
end
if no... | from __future__ import absolute_import
import base64
from colander import SchemaType, null, Invalid, _
import six
from . import compat
class AbstractEncodedBytes(SchemaType):
encoder = None
decoder = None
def serialize(self, node, appstruct):
if appstruct is null:
return null
... | Python | zaydzuhri_stack_edu_python |
import os
import sys
from datetime import datetime
comment Complete the timeConversion function below.
function timeConversion s
begin
set dt = string parse time s string %I:%M:%S%p
return string format time dt string %H:%M:%S
end function
string INPUT: 07:05:45PM | import os
import sys
from datetime import datetime
#
# Complete the timeConversion function below.
#
def timeConversion(s):
dt=datetime.strptime(s, '%I:%M:%S%p')
return(dt.strftime('%H:%M:%S'))
'''
INPUT:
07:05:45PM
''' | Python | zaydzuhri_stack_edu_python |
string 装饰器 概念:一个闭包,把一个函数当成参数,返回一个替代版的函数。 本质上就是一个返回函数的函数
function func1
begin
print string sunck is a good man
end function
function outer func
begin
function inner
begin
print string *******************
call func
end function
return inner
end function
comment f 是函数func1的加强版本
set f = call outer func1
f dist
string 那么,函数... | """
装饰器
概念:一个闭包,把一个函数当成参数,返回一个替代版的函数。
本质上就是一个返回函数的函数
"""
def func1():
print("sunck is a good man")
def outer(func):
def inner():
print("*******************")
func()
return inner
# f 是函数func1的加强版本
f = outer(func1)
f()
"""
那么,函数装饰器的工作原理是怎样的呢?假设用 funA() 函数装饰器去装饰 funB() 函数,如下所示:
纯文本复制
#fu... | Python | zaydzuhri_stack_edu_python |
function directory_variables
begin
set root_path = string ../../../
set root_dir = join path root_path get current directory
set file_path = join path root_dir string resources string EuroSense string eurosense.v1.0.high-precision.xml
set train_o_matic_file_path = join path root_dir string resources string train-o-mati... | def directory_variables():
root_path = "../../../"
root_dir = os.path.join(root_path, os.getcwd())
file_path = os.path.join(root_dir, 'resources',
'EuroSense', 'eurosense.v1.0.high-precision.xml')
train_o_matic_file_path = os.path.join(root_dir, 'resources',
... | Python | nomic_cornstack_python_v1 |
function execute self kusto_database kusto_query accept_partial_results=false **options
begin
if starts with kusto_query string .
begin
set endpoint_version = _MGMT_ENDPOINT_VERSION
set endpoint = _mgmt_endpoint
end
else
begin
set endpoint_version = _QUERY_ENDPOINT_VERSION
set endpoint = _query_endpoint
end
comment pri... | def execute(self, kusto_database, kusto_query, accept_partial_results=False, **options):
if kusto_query.startswith("."):
endpoint_version = self._MGMT_ENDPOINT_VERSION
endpoint = self._mgmt_endpoint
else:
endpoint_version = self._QUERY_ENDPOINT_VERSION
e... | Python | nomic_cornstack_python_v1 |
function _markAsDeleted self path
begin
set tuple folder name = call _splitPath path
if exists mountSource path
begin
execute sqlConnection string INSERT OR REPLACE INTO "files" (path,name,deleted) VALUES (?,?,?) tuple folder name true
end
else
begin
execute sqlConnection string DELETE FROM "files" WHERE (path,name) ==... | def _markAsDeleted(self, path: str):
folder, name = self._splitPath(path)
if self.mountSource.exists(path):
self.sqlConnection.execute(
'INSERT OR REPLACE INTO "files" (path,name,deleted) VALUES (?,?,?)', (folder, name, True)
)
else:
self.sqlC... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Mar 15 19:23:21 2018 @author: Di Yi
from bs4 import BeautifulSoup
import re , os , codecs
from glob import glob
function hasNumber inputString
begin
return any generator expression is digit char for char in inputString
end function
function process_word word
begin
if ... | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 19:23:21 2018
@author: Di Yi
"""
from bs4 import BeautifulSoup
import re, os, codecs
from glob import glob
def hasNumber(inputString):
return any(char.isdigit() for char in inputString)
def process_word(word):
if hasNumber(word):
... | Python | zaydzuhri_stack_edu_python |
function same_case txt
begin
set flag = is upper txt at 0
for i in range 1 length txt
begin
if flag != is upper txt at i
begin
return false
end
end
return true
end function | def same_case(txt):
flag = txt[0].isupper()
for i in range (1, len(txt)):
if flag != txt[i].isupper():
return False
return True
| Python | zaydzuhri_stack_edu_python |
function service_template self
begin
return get pulumi self string service_template
end function | def service_template(self) -> Optional['outputs.SearchHeadClusterSpecServiceTemplate']:
return pulumi.get(self, "service_template") | Python | nomic_cornstack_python_v1 |
string 座右铭:将来的你一定会感激现在拼命的自己 @project:正课 @author:Mr.Chen @file:使用函数+数据库完成学生信息管理系统.PY @ide:PyCharm @time:2018-08-02 14:33:37
import sqlite3
comment 定义一个创建表的函数
function create_table
begin
comment UNIQUE:表示字段的值是惟一的
comment NOT NULL:表示字段值不允许为空
comment IF NOT EXISTS:当表不存在时,在执行创建表的sql语句,如果表已经存在,则sql语句不再执行,可以避免异常。
set create_s... | """
座右铭:将来的你一定会感激现在拼命的自己
@project:正课
@author:Mr.Chen
@file:使用函数+数据库完成学生信息管理系统.PY
@ide:PyCharm
@time:2018-08-02 14:33:37
"""
import sqlite3
# 定义一个创建表的函数
def create_table():
# UNIQUE:表示字段的值是惟一的
# NOT NULL:表示字段值不允许为空
# IF NOT EXISTS:当表不存在时,在执行创建表的sql语句,如果表已经存在,则sql语句不再执行,可以避免异常。
create_sql = "create table ... | Python | zaydzuhri_stack_edu_python |
class Person
begin
set name = string
set age = 0
set power = 0
set instrument = none
function __init__ self name age power
begin
set age = age
set power = power
set name = name
end function
function take_instrument self instrument
begin
set instrument = instrument
set owner = name
end function
function play self
begin... | class Person:
name = ''
age = 0
power = 0
instrument = None
def __init__(self, name, age, power):
self.age = age
self.power = power
self.name = name
def take_instrument(self, instrument):
self.instrument = instrument
self.instrument.owner = self.name
... | Python | zaydzuhri_stack_edu_python |
function __init__ self floor head y_shoulder x_length bearing_center_y bearing_head_dia x0 y0 tool_dia z_safe z_rapid
begin
comment shoulder height
set floor = floor
set head = head
set y_shoulder = y_shoulder
set x_length = x_length
set bearing_center_y = bearing_center_y
set bearing_head_dia = bearing_head_dia
set x0... | def __init__(self,
floor,
head,
y_shoulder, # shoulder height
x_length,
bearing_center_y,
bearing_head_dia,
x0,
y0,
tool_dia,
z_safe,
... | Python | nomic_cornstack_python_v1 |
function create_left_parenthesis_token symbol idx=- 1 pos=- 1
begin
return call Token symbol TOKEN_TYPE_PARENTHESIS TOKEN_SUBTYPE_PARENTHESIS_LEFT idx pos
end function | def create_left_parenthesis_token(symbol, idx=-1, pos=-1):
return Token(symbol, TOKEN_TYPE_PARENTHESIS, TOKEN_SUBTYPE_PARENTHESIS_LEFT, idx, pos) | Python | nomic_cornstack_python_v1 |
function get_shear_from_potential_in_fourier_space self potential shape boxsize
begin
set shape = integer shape
set a_space = concatenate tuple array range shape / 2 array range - shape / 2 0
set k_mode = 2 * pi * a_space / boxsize
set shear_fourier = zeros tuple shape shape shape 3 3 dtype=complex
for i in range shape... | def get_shear_from_potential_in_fourier_space(self, potential, shape, boxsize):
shape = int(shape)
a_space = np.concatenate((np.arange(shape/2), np.arange(-shape/2, 0)))
k_mode = 2 * np.pi * a_space / boxsize
shear_fourier = np.zeros((shape, shape, shape, 3, 3), dtype=complex)
... | Python | nomic_cornstack_python_v1 |
set lst = list list 1 2 3 list 4 5 6 list 7 8 9
set sum_greater_than_5 = 0
for row in lst
begin
for value in row
begin
if value > 5
begin
set sum_greater_than_5 = sum_greater_than_5 + value
end
end
end
print sum_greater_than_5 | lst = [[1,2,3],[4,5,6],[7,8,9]]
sum_greater_than_5 = 0
for row in lst:
for value in row:
if value > 5:
sum_greater_than_5 += value
print(sum_greater_than_5)
| Python | greatdarklord_python_dataset |
function get_terms self vocabulary=none
begin
set search_request = dict
if vocabulary is not none
begin
set search_request = call _gen_search_request dict string vocabulary string VocabularyTerm ; string criteria list dict string vocabulary string Vocabulary ; string code vocabulary
end
set fetch_options = dict string... | def get_terms(self, vocabulary=None):
search_request = {}
if vocabulary is not None:
search_request = _gen_search_request( {
"vocabulary": "VocabularyTerm",
"criteria" : [{
"vocabulary": "Vocabulary",
"code": vocabula... | Python | nomic_cornstack_python_v1 |
import numpy as np
set t = call dtype list tuple string name str_ 40 tuple string numitems int32 tuple string price float32
print t
print t at string name
set item = array list tuple string DVD 42 3.14 tuple string Butter 13 2.72 dtype=t
print item at 1 | import numpy as np
t = np.dtype([('name', np.str_, 40), ('numitems', np.int32), ('price', np.float32)])
print(t)
print(t['name'])
item = np.array([('DVD', 42, 3.14), ('Butter', 13, 2.72)], dtype=t)
print(item[1])
| Python | zaydzuhri_stack_edu_python |
function prefix_replace original old new
begin
Ellipsis
end function | def prefix_replace(original, old, new):
... | Python | nomic_cornstack_python_v1 |
function stop self
begin
call stop
end function | def stop(self):
self._reactor.stop() | Python | nomic_cornstack_python_v1 |
function search_workspace name
begin
return call search_workspace name=name
end function | def search_workspace(name):
return instance().search_workspace(name=name) | Python | nomic_cornstack_python_v1 |
class Point
begin
function __init__ self x y cluster=none
begin
set x = x
set y = y
set cluster = cluster
end function
end class
class ClassifierKnn
begin
function __init__ self cluster distance
begin
set cluster = cluster
set distance = distance
end function
function comparator x y
begin
if distance < distance
begin
r... | class Point:
def __init__(self, x, y, cluster=None):
self.x = x
self.y = y
self.cluster = cluster
class ClassifierKnn:
def __init__(self, cluster, distance):
self.cluster = cluster
self.distance = distance
def comparator(x, y):
if x.distance < y.distance:
... | Python | zaydzuhri_stack_edu_python |
function changeMelody Infos
begin
set melodies = list string C string C# string D string D# string E string F string F# string G string G# string A string A# string B
set Info = string
for tuple index i in enumerate Infos
begin
set melody = string
if i != string #
begin
if index + 1 < length Infos
begin
if Infos at i... | def changeMelody(Infos):
melodies = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']
Info = ""
for index, i in enumerate(Infos):
melody = ""
if i != '#':
if index + 1 < len(Infos):
if Infos[index + 1] == '#':
melody = Infos[ind... | Python | zaydzuhri_stack_edu_python |
function plot_many_sims n_sims=1000
begin
set tuple true_ps obs_xs = call get_ground_truth
set tuple ps xs = load call SimsLoader n_sims
comment parameter histogram
set fig = call plot_hist_marginals ps lims=call get_disp_lims gt=true_ps
call suptitle string parameters
comment data histogram
set fig = call plot_hist_ma... | def plot_many_sims(n_sims=1000):
true_ps, obs_xs = get_ground_truth()
ps, xs = SimsLoader().load(n_sims)
# parameter histogram
fig = util.plot.plot_hist_marginals(ps, lims=get_disp_lims(), gt=true_ps)
fig.suptitle('parameters')
# data histogram
fig = util.plot.plot_hist_marginals(xs, gt=o... | Python | nomic_cornstack_python_v1 |
comment print(nums[5]) Way 1
comment for i in nums: Way 2
comment print(i)
comment Way 3
set it = iterate nums
comment Way 3.1
print call __next__
print call __next__
comment Way 3.2
print next it
comment Way 3.3
for i in nums
begin
print i
end
comment Way 4 (Creating own Iterator)
class TopTen
begin
function __init__ ... | # print(nums[5]) Way 1
# for i in nums: Way 2
# print(i)
it = iter(nums) # Way 3
print(it.__next__()) # Way 3.1
print(it.__next__())
print(next(it)) # Way 3.2
for i in nums: # Way 3.3
print(i)
class TopTen: # Way 4 (Creating own Iterator)
def __init__(self):
self.num = 1
def __iter... | Python | zaydzuhri_stack_edu_python |
function get_relays self
begin
if _relays and not call is_config_changed
begin
return _relays
end
set dict_data = call get_relay_config
for name in dict_data
begin
debug string loading relay %s name
set _relays at name = call objectify_dict name dict_data at name default_type=Relay
end
return _relays
end function | def get_relays(self):
if self._relays and not self.is_config_changed():
return self._relays
dict_data = self.get_relay_config()
for name in dict_data:
self.log.debug("loading relay %s", name)
self._relays[name] = self.objectify_dict(name, dict_data[name], defa... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string Some players. TODO: -implement an Alpha-Beta algorithm to play chess -implement a simple position evaluation function -implement an RL based evaluation function
from chess import Location
class HumanPlayer
begin
string A class that takes human input to make moves.
decorator classmet... | #!/usr/bin/env python3
""" Some players.
TODO:
-implement an Alpha-Beta algorithm to play chess
-implement a simple position evaluation function
-implement an RL based evaluation function
"""
from chess import Location
class HumanPlayer:
""" A class that takes human input to make moves."""
... | Python | zaydzuhri_stack_edu_python |
function _get_locators self
begin
return DashboardWidget
end function | def _get_locators(self):
return locator.DashboardWidget | Python | nomic_cornstack_python_v1 |
function remove_session_files session_id temp_folder=none timeout=none
begin
if temp_folder is none
begin
set temp_folder = TEMP_FOLDERS at 0
end
set args = list string find TEMP_FOLDERS at 0 string -name string * { session_id } *.* string -delete
set process = run join string args shell=true stdout=PIPE stderr=PIPE t... | def remove_session_files(session_id, temp_folder=None, timeout=None):
if temp_folder is None:
temp_folder = TEMP_FOLDERS[0]
args = ['find',TEMP_FOLDERS[0], '-name', f'*{session_id}*.*', '-delete']
process = subprocess.run(' '.join(args), shell=True, stdout=subprocess.PIPE,
... | Python | nomic_cornstack_python_v1 |
function parse_args_and_create_context self args
begin
string Helper method that will parse the args into options and remaining args as well as create an initial :py:class:`swiftly.cli.context.CLIContext`. The new context will be a copy of :py:attr:`swiftly.cli.cli.CLI.context` with the following attributes added: ====... | def parse_args_and_create_context(self, args):
"""
Helper method that will parse the args into options and
remaining args as well as create an initial
:py:class:`swiftly.cli.context.CLIContext`.
The new context will be a copy of
:py:attr:`swiftly.cli.cli.CLI.context` wit... | Python | jtatman_500k |
comment https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
from typing import List
set logger = if expression false then print else lambda -> none
class Solution
begin
function minRemoveToMakeValid self s
begin
set resultS = call func s
call logger string resultS=%s % resultS
set result = call con... | # https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
from typing import List
logger = print if False else lambda *arg: None
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
resultS = func(s)
logger("resultS=%s" % resultS)
result = convertFunc(resultS)... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
from base import Compare
from half import Half
from normal import Normal
function main
begin
set test_case_list = list dict string test_args dict string x 12 ; string expect_val dict string ret_val false ; string comment string 12 dict string test_args dict st... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from base import Compare
from half import Half
from normal import Normal
def main():
test_case_list = [
{
'test_args': {'x': 12},
'expect_val': {'ret_val': False},
'comment': '12'
},
{
'test_ar... | Python | zaydzuhri_stack_edu_python |
function mock_read_file_and_write_config monkeypatch test_file
begin
set attribute string ScriptRunner.taskhandler.config_handler.read_file call MagicMock return_value=CONFIG_CONTENT
call test_file CONFIG_NAME CONFIG_CONTENT
end function | def mock_read_file_and_write_config(monkeypatch, test_file):
monkeypatch.setattr(
"ScriptRunner.taskhandler.config_handler.read_file",
MagicMock(return_value=CONFIG_CONTENT),
)
test_file(CONFIG_NAME, CONFIG_CONTENT) | Python | nomic_cornstack_python_v1 |
function update self subject
begin
comment store pointer to subject (table) which sends message that
comment data has changed, needed for displaying mouse selection of
comment data
set subject = subject
comment get data from subject
set tuple xdata ydatas d = plotdata
comment and len(d['ycols']) > 0: #note xcol could b... | def update(self, subject):
#store pointer to subject (table) which sends message that
#data has changed, needed for displaying mouse selection of
#data
self.subject = subject
#get data from subject
xdata, ydatas, d = subject.plotdata
if d['xcol']: # and len(d[... | Python | nomic_cornstack_python_v1 |
function get_accuracy data_input label_input pred sess labels samples offset=none batch_size=none
begin
comment Get the predicted labels and the real labels
if offset is none and batch_size is none
begin
set tuple pred_out label_input_out = run list pred label_input feed_dict=dict data_input samples ; label_input label... | def get_accuracy(data_input, label_input, pred, sess, labels, samples, offset=None, batch_size=None):
# Get the predicted labels and the real labels
if offset is None and batch_size is None:
pred_out, label_input_out = sess.run([pred, label_input],
feed_dict... | Python | nomic_cornstack_python_v1 |
string Input: string (all lower case) Edge Cases: - empty string - all non-repeating - all repeating -> return -1 - non-alphabetical characters in str Solution #1: Loop through string and add each char to a hash_map with (total,position) then return the least common -> Time Complexity: O(n) Space Complexity: O(n) Solut... | """
Input: string (all lower case)
Edge Cases:
- empty string
- all non-repeating
- all repeating -> return -1
- non-alphabetical characters in str
Solution #1: Loop through string and add each char to a hash_map with (total,position) then return the least common -> Time Complexity: O(n) Space Complexity: O(n)
Soluti... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string make_sparse_test_data.py ------------------------ Generate random data to use with MapReduce experiments. Usage:
set usage_str = string python %s <nrows>
import sys
import numpy
if length argv != 2
begin
tuple print ? stderr usage_str % argv at 0
exit - 1
end
set m = integer argv at ... | #!/usr/bin/env python
"""
make_sparse_test_data.py
------------------------
Generate random data to use with MapReduce experiments.
Usage:
"""
usage_str = "python %s <nrows>"
import sys
import numpy
if len(sys.argv) != 2:
print>>sys.stderr, usage_str%(sys.argv[0])
sys.exit(-1)
m = int(sys.argv[1])
A = numpy.r... | Python | zaydzuhri_stack_edu_python |
function read_command self
begin
if _pending_commands
begin
return call popleft
end
set msg = call read_msg
while call _msg_is_taskid msg
begin
append _pending_taskids msg
set msg = call read_msg
end
return msg
end function | def read_command(self):
if self._pending_commands:
return self._pending_commands.popleft()
msg = self._serializer.read_msg()
while self._msg_is_taskid(msg):
self._pending_taskids.append(msg)
msg = self._serializer.read_msg()
return msg | Python | nomic_cornstack_python_v1 |
function slot_catch_rate_rank self slot_catch_rate_rank
begin
set _slot_catch_rate_rank = slot_catch_rate_rank
end function | def slot_catch_rate_rank(self, slot_catch_rate_rank):
self._slot_catch_rate_rank = slot_catch_rate_rank | Python | nomic_cornstack_python_v1 |
set a = 10
set b = 20
print string a= a string b= b
set tuple a b = tuple b a
print string a= a string b= b | a=10
b=20
print("a=",a,"b=",b)
a,b=b,a
print("a=",a,"b=",b)
| Python | zaydzuhri_stack_edu_python |
function get_str_products_by_zone self location_id
begin
set delimiter = string ********************
comment str_menu = "0 -> Volver\n"
set str_menu = string
set products = call get_product_by_picking_location user_id location_id
set inc = 1
if products
begin
for key in products
begin
set key_ = integer key
if key_ >=... | def get_str_products_by_zone(self, location_id):
delimiter = "\n********************\n"
#str_menu = "0 -> Volver\n"
str_menu=""
self.products = self.factory.odoo_con.get_product_by_picking_location(self.user_id, location_id)
inc=1
if self.products:
for key in... | Python | nomic_cornstack_python_v1 |
import sys
for i in range 3
begin
set sum = 0
for j in range integer read line stdin
begin
set a = integer read line stdin
set sum = sum + a
end
if sum > 0
begin
print string +
end
else
if sum == 0
begin
print string 0
end
else
begin
print string -
end
end | import sys
for i in range(3):
sum = 0
for j in range(int(sys.stdin.readline())):
a = int(sys.stdin.readline())
sum += a
if sum > 0: print('+')
elif sum == 0: print('0')
else: print('-')
| Python | zaydzuhri_stack_edu_python |
function pretend_move self action
begin
set _copy = deep copy self
move action
return _copy
end function | def pretend_move(self, action):
_copy = deepcopy(self)
_copy.move(action)
return _copy | Python | nomic_cornstack_python_v1 |
function add self name args def_args filepath location
begin
raise NotImplementedError
end function | def add(self, name, args, def_args, filepath, location):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
string Instructions: You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. Example sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
string Solution
... | '''
Instructions:
You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.
Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it.
Example
sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
'''
''' Solut... | Python | zaydzuhri_stack_edu_python |
function get_pressure self altitude
begin
return P0 * 1 + dTdH / 1000 * altitude / T0 ^ - G0 / R / dTdH * 1000
end function | def get_pressure(self, altitude: float) -> float:
return self.P0 * (1 + self.dTdH / 1000 * altitude / self.T0) ** (-self.G0 / self.R / self.dTdH * 1000) | Python | nomic_cornstack_python_v1 |
function defineAnalyticalSystem matrix junkStates
begin
comment This is the core of this solution.
comment Essentially, let P_i,j be the probability of ending up at state j (terminal state)
comment from state i. We are interested in P_1,j for every terminal state.
comment For instance, lets assume we wanna compute P_1,... | def defineAnalyticalSystem(matrix, junkStates):
# This is the core of this solution.
# Essentially, let P_i,j be the probability of ending up at state j (terminal state)
# from state i. We are interested in P_1,j for every terminal state.
# For instance, lets assume we wanna compute P_1,4 (where 4 i... | Python | nomic_cornstack_python_v1 |
function testAdminGetQueryBadPlatform self
begin
set params = dict string search string DoesntMatter ; string searchBase string bundleId ; string asAdmin true
with call LoggedInUser admin=true
begin
get testapp ROUTE + string /bit9 params status=BAD_REQUEST
end
end function | def testAdminGetQueryBadPlatform(self):
params = {'search': 'DoesntMatter',
'searchBase': 'bundleId',
'asAdmin': True}
with self.LoggedInUser(admin=True):
self.testapp.get(self.ROUTE + '/bit9', params, status=httplib.BAD_REQUEST) | Python | nomic_cornstack_python_v1 |
function _FormatIPCPermToken self token_data
begin
return dict string user_id user_identifier ; string group_id group_identifier ; string creator_user_id creator_user_identifier ; string creator_group_id creator_group_identifier ; string access access_mode
end function | def _FormatIPCPermToken(self, token_data):
return {
'user_id': token_data.user_identifier,
'group_id': token_data.group_identifier,
'creator_user_id': token_data.creator_user_identifier,
'creator_group_id': token_data.creator_group_identifier,
'access': token_data.access_mode... | Python | nomic_cornstack_python_v1 |
function _get_per_point_info self pointclouds **kwargs
begin
set raster_settings = get kwargs string raster_settings raster_settings
set cutoff_thres = cutoff_threshold
comment GV = M_k V_k^T M_k^T + V^h
set tuple GVs detMk = call _compute_variance_and_detMk pointclouds keyword kwargs
set GVdets = call det GVs
set GVin... | def _get_per_point_info(self, pointclouds, **kwargs):
raster_settings = kwargs.get("raster_settings", self.raster_settings)
cutoff_thres = raster_settings.cutoff_threshold
# GV = M_k V_k^T M_k^T + V^h
GVs, detMk = self._compute_variance_and_detMk(pointclouds, **kwargs)
GVdets =... | Python | nomic_cornstack_python_v1 |
comment leetcode # 9
comment complete
function ispalindrome x
begin
comment print(str(x)[::-1])
if string x at slice : : - 1 == string x
begin
return true
end
else
begin
return false
end
end function
function ispalindromenostring x
begin
set reversedNum = 0
set xcopy = x
while xcopy != 0 or xcopy != - 1
begin
comment... | # leetcode # 9
# complete
def ispalindrome(x):
# print(str(x)[::-1])
if(str(x)[::-1] == str(x)):
return True
else:
return False
def ispalindromenostring(x):
reversedNum = 0
xcopy = x
while xcopy != 0 or xcopy != -1:
# print(xcopy)
if xcopy == 0 or xcopy == -... | Python | zaydzuhri_stack_edu_python |
comment Author: Orion Ford
comment This program allows you to donwload images from Instagram.
import requests
from bs4 import BeautifulSoup
set start_url = input string Input your link:
set response = get requests start_url
set html = text
set soup = call BeautifulSoup html string lxml
set photo_url = find soup string ... | # Author: Orion Ford
# This program allows you to donwload images from Instagram.
import requests
from bs4 import BeautifulSoup
start_url = input('Input your link: ')
response = requests.get(start_url)
html = response.text
soup = BeautifulSoup(html, 'lxml')
photo_url = soup.find('meta', property="og.image... | Python | zaydzuhri_stack_edu_python |
for i in range 1 n + 1
begin
set line = input
append list1 line
end
print list1 | for i in range(1,n+1):
line=input()
list1.append(line)
print(list1) | Python | zaydzuhri_stack_edu_python |
from utilities import document_iterator
from sklearn.feature_extraction.text import CountVectorizer , TfidfVectorizer
from sklearn.linear_model import Lasso , Ridge , LogisticRegression
from sklearn.metrics import mean_squared_error , mean_absolute_error
from scipy.sparse import vstack
import numpy as np
function lasso... | from utilities import document_iterator
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.linear_model import Lasso, Ridge, LogisticRegression
from sklearn.metrics import mean_squared_error, mean_absolute_error
from scipy.sparse import vstack
import numpy as np
def lasso(term... | Python | zaydzuhri_stack_edu_python |
function no_teen_sum a b c
begin
if call fix_teen a and call fix_teen b and call fix_teen c
begin
return 0
end
if call fix_teen b and call fix_teen c
begin
return a
end
if call fix_teen a and call fix_teen c
begin
return b
end
if call fix_teen a and call fix_teen b
begin
return c
end
if call fix_teen a
begin
return b +... | def no_teen_sum(a, b, c):
if fix_teen(a) and fix_teen(b) and fix_teen(c):
return 0
if fix_teen(b) and fix_teen(c):
return a
if fix_teen(a) and fix_teen(c):
return b
if fix_teen(a) and fix_teen(b):
return c
if fix_teen(a):
return b + c
if fix_teen(b):
return a + c
if fix_teen(c):
... | Python | zaydzuhri_stack_edu_python |
function _determine_clashing_namespaces self py_namespaces_by_target
begin
string Check for any overlapping namespaces.
set namespaces_by_files = default dictionary list
for tuple target all_namespaces in items py_namespaces_by_target
begin
for tuple path namespace in all_namespaces
begin
append namespaces_by_files at ... | def _determine_clashing_namespaces(self, py_namespaces_by_target):
"""Check for any overlapping namespaces."""
namespaces_by_files = defaultdict(list)
for target, all_namespaces in py_namespaces_by_target.items():
for (path, namespace) in all_namespaces:
namespaces_by_files[namespace].append((... | Python | jtatman_500k |
comment !/usr/bin/env python
import rospy
import numpy as np
import math
from geometry_msgs.msg import Vector3
from geometry_msgs.msg import Vector3Stamped
comment Gets encoder data from arduino
comment Applies modified PD-feedforward control
comment Publishes control output as pwm value to arduino
class MotorControlle... | #!/usr/bin/env python
import rospy
import numpy as np
import math
from geometry_msgs.msg import Vector3
from geometry_msgs.msg import Vector3Stamped
# Gets encoder data from arduino
# Applies modified PD-feedforward control
# Publishes control output as pwm value to arduino
class MotorController:
def __init__(sel... | Python | zaydzuhri_stack_edu_python |
function remove_repeats movie_dict
begin
comment Get list of ids in same order as list of movie dics
set id_list = list comprehension x at string info at string m_id for x in movie_dict
comment Create dict of occurences of each number
set y = call bincount id_list
set ii = call nonzero y at 0
set count_dic = dictionary... | def remove_repeats(movie_dict):
# Get list of ids in same order as list of movie dics
id_list = [x['info']['m_id'] for x in movie_dict]
# Create dict of occurences of each number
y = np.bincount(id_list)
ii = np.nonzero(y)[0]
count_dic = dict(zip(ii,y[ii]))
del_idx = []
# Now loop through movie_dict entries, re... | Python | nomic_cornstack_python_v1 |
function show_warning_message self msg msecs=3
begin
warning msg parent=self duration=msecs closable=true
end function | def show_warning_message(self, msg, msecs=3):
message.PopupMessage.warning(msg, parent=self, duration=msecs, closable=True) | Python | nomic_cornstack_python_v1 |
function test_get_duplicates_size self
begin
for tuple desc files_dict duplicates_dict degree exp_size in DUPLICATES_SIZE_CHECK
begin
with call subTest msg=desc
begin
set degree = degree
set files = files_dict
set results = call get_duplicates_size duplicates=duplicates_dict
assert equal results exp_size
end
end
end fu... | def test_get_duplicates_size(self):
for desc, files_dict, duplicates_dict, degree, exp_size in DUPLICATES_SIZE_CHECK:
with self.subTest(msg=desc):
self.duplicates_instance.degree = degree
self.duplicates_instance.files = files_dict
results = self.dupli... | Python | nomic_cornstack_python_v1 |
function is_radiative cls source_subshell destination_subshell
begin
function electric_dipole_permitted n0 l0 j0_n n1 l1 j1_n
begin
set delta_j_n = absolute j1_n - j0_n
if delta_j_n > 2
begin
return false
end
assert delta_j_n == 0 or delta_j_n == 2
return absolute l1 - l0 == 1
end function
function electric_quadrupole_... | def is_radiative(cls, source_subshell, destination_subshell):
def electric_dipole_permitted(n0, l0, j0_n, n1, l1, j1_n):
delta_j_n = abs(j1_n - j0_n)
if delta_j_n > 2:
return False
assert delta_j_n == 0 or delta_j_n == 2
return abs(l1 - l0) == 1
... | Python | nomic_cornstack_python_v1 |
import sys
set STR_VER = b'LK_VER:'
set AMZN_MAGIC = b'AMZN'
set LK_HDR = b'lk'
function check_header hdr bl
begin
if hdr != LK_HDR
begin
print format string E: Cannot find lk header in {}! Abort... bl
exit 1
end
else
begin
pass
end
end function
function check_amzn data bl
begin
if not data
begin
print string E: Cannot... | import sys
STR_VER = b'LK_VER:'
AMZN_MAGIC = b'AMZN'
LK_HDR = b'lk'
def check_header(hdr, bl):
if hdr != LK_HDR:
print("E: Cannot find lk header in {}! Abort...".format(bl))
exit(1)
else:
pass
def check_amzn(data, bl):
if not data:
print("E: Cannot open bootloader data! Abort...")
... | Python | zaydzuhri_stack_edu_python |
comment pylint: disable=too-many-arguments,too-many-locals
function __multi_arity_dispatch_fn ctx name arity_map default_name=none max_fixed_arity=none meta_node=none is_async=false
begin
string Return the Python AST nodes for a argument-length dispatch function for multi-arity functions. def fn(*args): nargs = len(arg... | def __multi_arity_dispatch_fn( # pylint: disable=too-many-arguments,too-many-locals
ctx: GeneratorContext,
name: str,
arity_map: Mapping[int, str],
default_name: Optional[str] = None,
max_fixed_arity: Optional[int] = None,
meta_node: Optional[MetaNode] = None,
is_async: bool = False,
) -> G... | Python | jtatman_500k |
function inference
begin
set data = call get_json force=true
comment 自行取用,可紀錄玉山呼叫的 timestamp
set esun_timestamp = data at string esun_timestamp
comment 取 image(base64 encoded) 並轉成 cv2 可用格式
set image_64_encoded = data at string image
set image = call base64_to_binary_for_cv2 image_64_encoded
set t = now
set ts = string ... | def inference():
data = request.get_json(force=True)
# 自行取用,可紀錄玉山呼叫的 timestamp
esun_timestamp = data['esun_timestamp']
# 取 image(base64 encoded) 並轉成 cv2 可用格式
image_64_encoded = data['image']
image = base64_to_binary_for_cv2(image_64_encoded)
t = datetime.datetime.now()
ts = str(int(t.... | Python | nomic_cornstack_python_v1 |
class Employee
begin
function __init__ self name salary
begin
set name = name
set salary = salary
end function
end class
class Manager extends Employee
begin
function __init__ self name salary experience teamSize performanceRatings
begin
call __init__ name salary
set experience = experience
set teamSize = teamSize
set ... | class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class Manager(Employee):
def __init__(self, name, salary, experience, teamSize, performanceRatings):
super().__init__(name, salary)
self.experience = experience
self.teamSize = teamSi... | Python | jtatman_500k |
from sys import argv
set tuple script first second third = argv | from sys import argv
script, first, second, third = argv
| Python | zaydzuhri_stack_edu_python |
from model.tables import session , User
from utils.utils import hash_password , validate_password
class UserController
begin
decorator classmethod
function user_login cls username password
begin
set hashed = call hash_password username password
if call scalar is not none
begin
return call one
end
else
begin
return none... | from model.tables import session, User
from utils.utils import hash_password, validate_password
class UserController:
@classmethod
def user_login(cls, username, password):
hashed = hash_password(username, password)
if session.query(User).filter(User.username == username, User.password == hashe... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.