code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function inconsistent_time_bounds cubes
begin
set time_point = points at 0
set bounds = tuple time_point - 10800 time_point
end function | def inconsistent_time_bounds(cubes: List[Cube]):
time_point = cubes[0].coord("time").points[0]
cubes[0].coord("time").bounds = (time_point - 10800, time_point) | Python | nomic_cornstack_python_v1 |
import sys
import threading
from queue import *
import random
import time
from threading import *
comment initialisation d'une file
set BUF_SIZE = 30
set Stock = queue BUF_SIZE
comment création de la class Producer
class Producer extends Thread
begin
function __init__ self
begin
set can_produce = true
call __init__ sel... | import sys
import threading
from queue import *
import random
import time
from threading import *
#initialisation d'une file
BUF_SIZE = 30
Stock = Queue(BUF_SIZE)
#création de la class Producer
class Producer(Thread):
def __init__(self):
self.can_produce = True
Thread.__init__(self)
#Méthode wait() qui permet d... | Python | zaydzuhri_stack_edu_python |
string Purpose: Date created: 2020-01-14 Contributor(s): Mark M.
import cvxpy as cp
import numpy as np
comment Generate a random non-trivial quadratic program.
set m = 15
set n = 10
set p = 5
seed 1
set P = randn n n
set P = T @ P
set q = randn n
set G = randn m n
set h = G @ randn n
set A = randn p n
set b = randn p
c... | """
Purpose:
Date created: 2020-01-14
Contributor(s):
Mark M.
"""
import cvxpy as cp
import numpy as np
# Generate a random non-trivial quadratic program.
m = 15
n = 10
p = 5
np.random.seed(1)
P = np.random.randn(n, n)
P = P.T@P
q = np.random.randn(n)
G = np.random.randn(m, n)
h = G@np.random.randn(n)
A = np.... | Python | zaydzuhri_stack_edu_python |
import numpy as np
class LinearRegression
begin
string 线性回归 参数: X - 训练集(需要将训练集的特征缩放到0~1,将参数以列向量重排) Y - 训练集的结果(取值为0|1) W - 假设函数的多参数组成矩阵(w1、w2、w3 ...)(W_j对应theta_j,j=1,2,3...) b - 假设函数的参数(x0 = 1的值)(b对应theta_0) learning_rate - 学习速率 num_iter - 迭代次数 costs - 代价函数值的集合(非必须操作) 使用: lg = LinearRegression() lg.initialize_parameter... | import numpy as np
class LinearRegression:
'''
线性回归
参数:
X - 训练集(需要将训练集的特征缩放到0~1,将参数以列向量重排)
Y - 训练集的结果(取值为0|1)
W - 假设函数的多参数组成矩阵(w1、w2、w3 ...)(W_j对应theta_j,j=1,2,3...)
b - 假设函数的参数(x0 = 1的值)(b对应theta_0)
learning_rate - 学习速率
num_iter - 迭代次数
costs - 代价函数值... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set NUM_V = 3
set NUM_C = 5
set NUM_N = 3
function print_array array
begin
for item in array
begin
print string item + string -------
end
end function
function print_tables tables
begin
for item in tables
begin
print item
print string -------
end
end function
function valid_values values
begin
return... | import numpy as np
NUM_V = 3
NUM_C = 5
NUM_N = 3
def print_array(array):
for item in array:
print(str(item)+"\n ------- \n")
def print_tables(tables):
for item in tables:
print(item)
print("-------")
def valid_values(values):
return values[values > 0]
def calc_h(prob):
val_v... | Python | zaydzuhri_stack_edu_python |
comment 引入模块
import xlrd
comment 打开文件,获取excel文件的workbook(工作簿)对象
comment 文件路径
set workbook = call open_workbook string F:\pytserver\company.xls
comment 获取所有sheet的名字
set names = call sheet_names
comment ['各省市', '测试表'] 输出所有的表名,以列表的形式
print names | import xlrd #引入模块
#打开文件,获取excel文件的workbook(工作簿)对象
workbook=xlrd.open_workbook("F:\\pytserver\\company.xls") #文件路径
#获取所有sheet的名字
names=workbook.sheet_names()
print(names) #['各省市', '测试表'] 输出所有的表名,以列表的形式
| Python | zaydzuhri_stack_edu_python |
function spam_quarantine_message_release_request self action quarantine_type message_ids
begin
set data = call assign_params action=action mids=message_ids quarantineType=quarantine_type
return call _http_request string POST string quarantine/messages json_data=data
end function | def spam_quarantine_message_release_request(
self, action: str, quarantine_type: str, message_ids: List[int]
) -> Dict[str, Any]:
data = assign_params(
action=action, mids=message_ids, quarantineType=quarantine_type
)
return self._http_request("POST", "quarantine/message... | Python | nomic_cornstack_python_v1 |
class Node extends object
begin
function __init__ self name kind layer=none
begin
set name = name
set kind = kind
set layer = none
set parents = list
set children = list
set data = none
set output_shape = none
set metadata = dict
end function
function add_parent self parent_node
begin
raise NotImplementedError
end f... | class Node(object):
def __init__(self, name, kind, layer=None):
self.name = name
self.kind = kind
self.layer = None
self.parents = []
self.children = []
self.data = None
self.output_shape = None
self.metadata = {}
def add_parent(self, parent_node... | Python | zaydzuhri_stack_edu_python |
comment A program that uses Euclid's algorithm to compute th greatest common divisor
comment of two positive integers entered by the user ##
function euclid a b
begin
if b == 0
begin
return a
end
else
begin
set c = a % b
return call euclid b c
end
end function
set a = decimal input string Please enter the first integer... | ## A program that uses Euclid's algorithm to compute th greatest common divisor
# of two positive integers entered by the user ##
def euclid(a,b):
if b == 0:
return a
else:
c = a % b
return euclid(b,c)
a = float(input("Please enter the first integer: "))
b = float(input("Please enter t... | Python | zaydzuhri_stack_edu_python |
function split string
begin
set words = lower call remove_accents string
return find all PATTERN words
end function | def split(string):
words = remove_accents(string).lower()
return re.findall(PATTERN, words) | Python | nomic_cornstack_python_v1 |
function test_cloudant_bluemix_context_helper_with_legacy_creds self
begin
set instance_name = string Cloudant NoSQL DB-lv
set vcap_services = dict string cloudantNoSQLDB list dict string credentials dict string username user ; string password pwd ; string host hostname ; string port 443 ; string url url ; string name ... | def test_cloudant_bluemix_context_helper_with_legacy_creds(self):
instance_name = 'Cloudant NoSQL DB-lv'
vcap_services = {'cloudantNoSQLDB': [{
'credentials': {
'username': self.user,
'password': self.pwd,
'host': urlparse(self.url).hostname,
'po... | Python | nomic_cornstack_python_v1 |
function configure_light self number subtype config platform_settings
begin
del platform_settings
if not controller_connection
begin
raise call AssertionError string A request was made to configure a PKONE light, but no connection to PKONE controller is available
end
if subtype == string simple
begin
comment simple LED... | def configure_light(self, number, subtype, config, platform_settings):
del platform_settings
if not self.controller_connection:
raise AssertionError("A request was made to configure a PKONE light, but no "
"connection to PKONE controller is available")
... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python
comment -*- coding:utf-8 -*-
comment @Time : 2018/3/17 上午2:14
import decimal
function format_app_num num f=2 is_separate=true
begin
if is instance num int or is instance num long
begin
return if expression is_separate then format string {:,} num else format string {:} num
end
else
if num is no... | #! /usr/bin/python
# -*- coding:utf-8 -*-
# @Time : 2018/3/17 上午2:14
import decimal
def format_app_num(num, f=2, is_separate=True):
if isinstance(num, int) or isinstance(num, long):
return '{:,}'.format(num) if is_separate else '{:}'.format(num)
elif num is None:
return "0"
elif num is ... | Python | zaydzuhri_stack_edu_python |
comment deterministic data
function get_data
begin
set data = dictionary
comment dimensions
comment 18 dimension, python generates numbers from 0
set data at string i = 19
comment 13 dimension, python generates numbers from 0
set data at string j = 14
comment c - significance
set data at string c = list 0 0 0 0 0 0 0 0... | # deterministic data
def get_data():
data = dict()
# dimensions
data['i'] = 19 # 18 dimension, python generates numbers from 0
data['j'] = 14 # 13 dimension, python generates numbers from 0
# c - significance
data['c'] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
return data
im... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3.4
comment coding: utf-8
import csv
import random
import string
import time
from string import ascii_letters
import os
import getpass
import sys
import re
from pathlib import Path
function sortLexo nbElem
begin
comment enregistre le temps de départ
set start_time = time
comment choisi une lettr... | #!/usr/bin/python3.4
# coding: utf-8
import csv
import random
import string
import time
from string import ascii_letters
import os
import getpass
import sys
import re
from pathlib import Path
def sortLexo(nbElem):
start_time = time.time() # enregistre le temps de départ
listwords = ["".join(random.choice(asc... | Python | zaydzuhri_stack_edu_python |
comment travel in m*n matrix only down or right allowed
comment find the number of ways one can reach start to end for example
comment [S x x]
comment [x x x]
comment [x x E]
comment has 3 unique ways to reach start to end
string To Solve these Kind of Problem ,try to divide problem in subproblem so suppose what if the... | # travel in m*n matrix only down or right allowed
# find the number of ways one can reach start to end for example
# [S x x]
# [x x x]
# [x x E]
# has 3 unique ways to reach start to end
"""
To Solve these Kind of Problem ,try to divide problem in subproblem so suppose what if there is only 1,1 grid present ,you can... | Python | zaydzuhri_stack_edu_python |
function must_handle_error self
begin
return call have_error and has attribute self string error_handler and error_handler is not none
end function | def must_handle_error(self):
return (self.have_error() and
hasattr(self, "error_handler") and
(self.error_handler is not None)) | Python | nomic_cornstack_python_v1 |
function test_render_template_nested
begin
from tapis_cli.templating import render_template
set source = string App Name {{ app.name }} is cool
set rendered = call render_template source passed_vals=dict string app dict string name string abcdef
assert string abcdef in string rendered
end function | def test_render_template_nested():
from tapis_cli.templating import render_template
source = 'App Name {{ app.name }} is cool'
rendered = render_template(source, passed_vals={'app': {'name': 'abcdef'}})
assert 'abcdef' in str(rendered) | Python | nomic_cornstack_python_v1 |
function objfunc_ener x rho0 pres0 eint0 pres1 eos_itp
begin
set cstate1 = call get_state rho=x pres=pres1 mode=string DP
set eint1 = cstate1 at string eint
set err = eint1 - eint0 - 0.5 * pres0 + pres1 * 1 / rho0 - 1 / x
return err
end function | def objfunc_ener(x, rho0, pres0, eint0, pres1, eos_itp):
cstate1 = eos_itp.get_state(rho=x, pres=pres1,
mode='DP')
eint1= cstate1['eint']
err = (eint1 - eint0) - 0.5*(pres0 + pres1)*(1/rho0 - 1/x)
return err | Python | nomic_cornstack_python_v1 |
comment !/usr/local/bin/python3
import sys
import subprocess
import datetime
if __name__ == string __main__
begin
if length argv < 4
begin
print string 至少需要三个参数
print string 1, 输入文件名字
print string 2, 开始截取时间,00:00:00 格式
print string 3, 截取时间长度,00:00:00 格式,或以秒为单位的数字
exit 1
end
set sourceFile = argv at 1
set startTime = ar... | #!/usr/local/bin/python3
import sys
import subprocess
import datetime
if __name__ == "__main__":
if (len(sys.argv) < 4):
print('至少需要三个参数')
print('1, 输入文件名字')
print('2, 开始截取时间,00:00:00 格式')
print('3, 截取时间长度,00:00:00 格式,或以秒为单位的数字')
sys.exit(1)
sourceFile = sys.argv[1] ... | Python | zaydzuhri_stack_edu_python |
function cluster_name self
begin
return get pulumi self string cluster_name
end function | def cluster_name(self) -> pulumi.Output[Optional[str]]:
return pulumi.get(self, "cluster_name") | Python | nomic_cornstack_python_v1 |
function initEntityFromSpec self spec key path
begin
raise call ContextEntityConflictError string Can't find entity with spec ' + name + string ' in this + call getSpecString
end function | def initEntityFromSpec(self, spec, key, path):
raise ContextEntityConflictError("Can't find entity with spec '" + spec.name + "' in this " + self.getSpecString()) | Python | nomic_cornstack_python_v1 |
function post self request
begin
try
begin
set serializer = call SongSerializer data=data
if call is_valid
begin
save
return call Response data status=HTTP_201_CREATED
end
end
except any
begin
return call Response errors status=HTTP_400_BAD_REQUEST
end
end function | def post(self,request):
try:
serializer = SongSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
except:
return Response(serializer.errors, status=s... | Python | nomic_cornstack_python_v1 |
function train_batch self batch eta truncate
begin
comment variables to accumlate the gradients wrt each weight and bias
set nabla_U1 = zeros shape
set nabla_W1 = zeros shape
set nabla_U2 = zeros shape
set nabla_W2 = zeros shape
set nabla_b1 = zeros shape
set nabla_b2 = zeros shape
set nabla_V = zeros shape
set nabla_f... | def train_batch(self, batch, eta, truncate):
# variables to accumlate the gradients wrt each weight and bias
nabla_U1 = nabla_W1 = np.zeros(self.net1.hidden_weight.shape)
nabla_U2 = nabla_W2 = np.zeros(self.net2.hidden_weight.shape)
nabla_b1 = np.zeros(self.net1.hidden_bias.shape)
... | Python | nomic_cornstack_python_v1 |
function isFluxDensity q
begin
if call isQuantity q
begin
return call is_equivalent string Jy
end
return false
end function | def isFluxDensity(q):
if isQuantity(q):
return q.unit.is_equivalent("Jy")
return False | Python | nomic_cornstack_python_v1 |
function tensor2span span_boundary span_labels parent_indices num_spans label_confidence idx2label label_ignore=none
begin
set label_ignore = label_ignore or list
if type != string cpu
begin
set span_boundary = to span_boundary device=string cpu
set parent_indices = to parent_indices device=string cpu
set span_labels ... | def tensor2span(
span_boundary: torch.Tensor,
span_labels: torch.Tensor,
parent_indices: torch.Tensor,
num_spans: torch.Tensor,
label_confidence: torch.Tensor,
idx2label: Dict[int, str],
label_ignore: Optional[List[int]] = None,
) -> List[Span]:
label_ignore =... | Python | nomic_cornstack_python_v1 |
set tuple_exapmle = tuple 2 0 1 8 6 4 9 5 9 9 3 8 7
set even_tuple = tuple list comprehension integer x for x in tuple_exapmle if x % 2 == 0
print even_tuple
set square_tuple = dictionary comprehension integer i : integer i ^ 2 for i in even_tuple
print square_tuple | tuple_exapmle = (2,0,1,8,6,4,9,5,9,9,3,8,7)
even_tuple = tuple([int(x) for x in tuple_exapmle if x%2 == 0])
print(even_tuple)
square_tuple = {int(i):int(i)**2 for i in even_tuple}
print(square_tuple)
| Python | zaydzuhri_stack_edu_python |
function inference_lp unary_potentials pairwise_potentials edges relaxed=false return_energy=false **kwargs
begin
set shape_org = shape at slice : - 1 :
set tuple n_states pairwise_potentials = call _validate_params unary_potentials pairwise_potentials edges
set unaries = reshape unary_potentials - 1 n_states
set res... | def inference_lp(unary_potentials, pairwise_potentials, edges, relaxed=False,
return_energy=False, **kwargs):
shape_org = unary_potentials.shape[:-1]
n_states, pairwise_potentials = \
_validate_params(unary_potentials, pairwise_potentials, edges)
unaries = unary_potentials.re... | Python | nomic_cornstack_python_v1 |
function icontain self idx
begin
return idx in _index_to_rowid
end function | def icontain(self, idx: Any):
return idx in self._index_to_rowid | Python | nomic_cornstack_python_v1 |
string 152. Maximum Product Subarray Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product. It is guaranteed that the answer will fit in a 32-bit integer. A subarray is a contiguous subsequence of the array.
class Solution extends object
... | """
152. Maximum Product Subarray
Given an integer array nums, find a contiguous non-empty subarray within the array that has the largest product, and return the product.
It is guaranteed that the answer will fit in a 32-bit integer.
A subarray is a contiguous subsequence of the array.
"""
class Solution(object):
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import sys
import sqlite3
function gen_mct cmds
begin
set db = call connect string mct.db
set c = call cursor
call executescript cmds
commit db
close db
end function
if __name__ == string __main__
begin
comment If there is an argument use that as the filename, otherwise assume the
comment S... | #!/usr/bin/env python
import sys
import sqlite3
def gen_mct(cmds):
db = sqlite3.connect('mct.db')
c = db.cursor()
c.executescript(cmds)
db.commit()
db.close()
if __name__ == '__main__':
# If there is an argument use that as the filename, otherwise assume the
# SQL command input file is na... | Python | zaydzuhri_stack_edu_python |
function sievecnt n p=none
begin
if p is none
begin
set p = call sqrtInt n
end
set V = list comprehension n // i for i in range 1 p + 1
set V = V + list range V at - 1 - 1 0 - 1
set S = dictionary comprehension i : i - 1 for i in V
for p in range 2 p + 1
begin
comment p is prime
if S at p > S at p - 1
begin
comment num... | def sievecnt(n, p=None):
if p is None:
p = sqrtInt(n)
V = [n//i for i in range(1, p+1)]
V += list(range(V[-1]-1, 0, -1))
S = {i: i-1 for i in V}
for p in range(2, p+1):
if S[p] > S[p-1]: # p is prime
sp = S[p-1] # number of primes smaller than p
p2 = p*p
... | Python | nomic_cornstack_python_v1 |
function subsample_n X n=0 seed=0
begin
if n < 0
begin
raise call ValueError string n must be greater 0
end
seed seed
set n = if expression n == 0 or n > shape at 0 then shape at 0 else n
set rows = random choice shape at 0 size=n replace=false
set Xsampled = array X at rows
return tuple Xsampled rows
end function | def subsample_n(X, n=0, seed=0):
if n < 0:
raise ValueError('n must be greater 0')
np.random.seed(seed)
n = X.shape[0] if (n == 0 or n > X.shape[0]) else n
rows = np.random.choice(X.shape[0],size=n,replace=False)
Xsampled = np.array(X[rows])
return Xsampled, rows | Python | nomic_cornstack_python_v1 |
comment Detect cycle in graph, dfs or bfs with union find
comment BFS
function dfs root
begin
set stack = list
set visited = set
while stack
begin
set item = pop stack 0
add visited visited
comment backedge has been detected
if stack in visited
begin
return true
end
for node in call getNeighbors item
begin
insert node... | #Detect cycle in graph, dfs or bfs with union find
#BFS
def dfs(root):
stack = []
visited = set()
while stack:
item = stack.pop(0)
visited.add(visited)
#backedge has been detected
if stack in visited:
return True
for node in getNeighbors(item):
node.insert(0, stack)
return False... | Python | zaydzuhri_stack_edu_python |
class Edge
begin
function __init__ self u=0 v=1
begin
set start = u
set end = v
end function
function __str__ self
begin
set s = format string {0} {1} start end
return s
end function
end class
set tuple m k = map int split input
set new_arr = list
set value_arr = list
set result_arr = list
set index_arr = list
for ... | class Edge:
def __init__(self, u=0, v=1):
self.start = u
self.end = v
def __str__(self):
s = "{0} {1}".format(self.start, self.end)
return s
m, k = map(int, input().split())
new_arr = []
value_arr = []
result_arr = []
index_arr = []
for i in range(m):
u, v, w = map(int, i... | Python | zaydzuhri_stack_edu_python |
string One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'. For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents ... | '''
One way to serialize a binary tree is to use preorder traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as '#'.
For example, the above binary tree can be serialized to the string "9,3,4,#,#,1,#,#,2,#,6,#,#", where '#' represents a... | Python | zaydzuhri_stack_edu_python |
function batch_iter4 data batch_size max_document_length shuffle=false
begin
set results = list
set data_size = length data
if data_size % batch_size != 0
begin
set remainder_size = batch_size - data_size % batch_size
set data = data + list zip array list list 0 * max_document_length * remainder_size array list list 0... | def batch_iter4(data, batch_size, max_document_length, shuffle=False):
results = []
data_size = len(data)
if data_size % batch_size != 0:
remainder_size = batch_size - data_size % batch_size
data += list(zip(np.array([[0]*max_document_length] * remainder_size), np.array([[0]*max_document_len... | Python | nomic_cornstack_python_v1 |
import os
function lock lockfile
begin
import fcntl
set lockfd = open lockfile string w+
call flock lockfd LOCK_EX ? LOCK_NB
return lockfd
end function
function unlock lockfd
begin
import fcntl
call flock lockfd LOCK_UN
end function
function write_rotation_status file_path status
begin
if is file path file_path
begin
w... | import os
def lock(lockfile):
import fcntl
lockfd = open(lockfile, 'w+')
fcntl.flock(lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
return lockfd
def unlock(lockfd):
import fcntl
fcntl.flock(lockfd, fcntl.LOCK_UN)
def write_rotation_status(file_path, status):
if os.path.isfile(file_path):
... | Python | zaydzuhri_stack_edu_python |
from flask import Flask , render_template
set app = call Flask __name__
class Item
begin
function __init__ self name
begin
set name = name
end function
end class
set name = string Ryan Dennis
set lista = list 1 1 2 3 5 8 11
set objects = list
append objects item string Judith
append objects item string Matilda
append ... | from flask import Flask, render_template
app = Flask(__name__)
class Item:
def __init__(self, name):
self.name = name
name = "Ryan Dennis"
lista = [1, 1, 2, 3, 5, 8, 11]
objects = []
objects.append(Item("Judith"))
objects.append(Item("Matilda"))
objects.append(Item("Jeannie"))
objects.append(Item("Sandi... | Python | zaydzuhri_stack_edu_python |
function _eig self A B
begin
set tuple lam vec = call eig A B
return tuple lam vec
end function | def _eig(self, A, B):
lam, vec = LA.eig(A, B)
return lam, vec | Python | nomic_cornstack_python_v1 |
function get_form self request obj=none **kwargs
begin
if obj is none
begin
comment Adding a new Slot
set kwargs at string form = SlotAdminAddForm
end
return call get_form request obj keyword kwargs
end function | def get_form(self, request, obj=None, **kwargs):
if obj is None:
# Adding a new Slot
kwargs['form'] = SlotAdminAddForm
return super(SlotAdmin, self).get_form(request, obj, **kwargs) | Python | nomic_cornstack_python_v1 |
import ArrayStack
import BinaryTree
import ChainedHashTable
import DLList
import operator
class Calculator
begin
function __init__ self
begin
set dict = call ChainedHashTable DLList
set stack = call ArrayStack
set expression = string
end function
function set_variable self k v
begin
add dict k v
end function
function ... | import ArrayStack
import BinaryTree
import ChainedHashTable
import DLList
import operator
class Calculator:
def __init__(self):
self.dict = ChainedHashTable.ChainedHashTable(DLList.DLList)
self.stack = ArrayStack.ArrayStack()
self.expression = ""
def set_variable(self, k: str, v: floa... | Python | zaydzuhri_stack_edu_python |
function get_non_fundamental_supermodes self tolerance=0.1
begin
set non_fundamental_supermodes = supermodes
for supermodes in call get_fundamental_supermodes tolerance=tolerance
begin
remove non_fundamental_supermodes supermodes
end
return non_fundamental_supermodes
end function | def get_non_fundamental_supermodes(self, *, tolerance: float = 0.1) -> list[SuperMode]:
non_fundamental_supermodes = self.supermodes
for supermodes in self.get_fundamental_supermodes(tolerance=tolerance):
non_fundamental_supermodes.remove(supermodes)
return non_fundamental_supermode... | Python | nomic_cornstack_python_v1 |
function search tree grid word pos results
begin
for m in call knight_moves pos
begin
if grid at m in keys tree
begin
if length word == 4
begin
if word + grid at m not in results
begin
append results word + grid at m
end
end
search tree at grid at m grid word + grid at m m results
end
end
end function | def search(tree, grid, word, pos, results):
for m in knight_moves(pos):
if grid[m] in tree.keys():
if len(word) == 4:
if (word + grid[m]) not in results:
results.append(word + grid[m])
search(tree[grid[m]], grid, word + grid[m], m, results) | Python | nomic_cornstack_python_v1 |
function caracal_exptime filin notfound=nan ext=0 outfmt=string single
begin
set kw = string EXPTIME
set dic = call read_header_keywords filin kw notfound=notfound ext=ext
if outfmt == string single
begin
return dic at kw
end
else
if outfmt == string dict
begin
return dic
end
else
begin
exit format string `outfmt`={} n... | def caracal_exptime(filin, notfound=np.nan, ext=0, outfmt='single'):
kw = 'EXPTIME'
dic = fitsutils.read_header_keywords(filin, kw, notfound=notfound, ext=ext)
if outfmt == 'single': return dic[kw]
elif outfmt == 'dict': return dic
else: sys.exit('`outfmt`={} not valid!'.format(outfmt)) | Python | nomic_cornstack_python_v1 |
function acl request
begin
set response_status_code = HTTP_403_FORBIDDEN
set username = get POST string username
set topic = get POST string topic
comment client_id = request.POST.get('clientid')
comment 1 == sub, 2 == pub
set acc = get POST string acc
set permission_name_map = dict string 1 string view_datastream ; st... | def acl(request):
response_status_code = status.HTTP_403_FORBIDDEN
username = request.POST.get('username')
topic = request.POST.get('topic')
# client_id = request.POST.get('clientid')
acc = request.POST.get('acc') # 1 == sub, 2 == pub
permission_name_map = {
'1': 'view_datastream',
... | Python | nomic_cornstack_python_v1 |
function print_person_details person
begin
if not person
begin
print string No details available
end
else
begin
set name = get person string name
set age = get person string age
set hobbies = get person string hobbies
if not name
begin
print string Name: Not available
end
else
if not is alpha name
begin
print string Na... | def print_person_details(person):
if not person:
print("No details available")
else:
name = person.get("name")
age = person.get("age")
hobbies = person.get("hobbies")
if not name:
print("Name: Not available")
elif not name.isalpha():
... | Python | jtatman_500k |
comment coding=utf-8
import sqlalchemy.exc
from app.helpers.middleware import db
from app.models.rating import VotableObject
class CommentRating extends Model
begin
set __tablename__ = string comment_rating
set id_user = call Column Integer call ForeignKey string user.id primary_key=true autoincrement=false
set id_targ... | # coding=utf-8
import sqlalchemy.exc
from app.helpers.middleware import db
from app.models.rating import VotableObject
class CommentRating(db.Model):
__tablename__ = 'comment_rating'
id_user = db.Column(db.Integer, db.ForeignKey('user.id'), primary_key=True, autoincrement=False)
id_target = db.Column(d... | Python | zaydzuhri_stack_edu_python |
function reduce_puzzle values
begin
set stalled = false
while not stalled
begin
comment Checking how many nodes have a determined value
set solved_values_before = length list comprehension node for node in keys values if length values at node == 1
comment Using the Eliminate Strategy
set values = call eliminate values
... | def reduce_puzzle(values):
stalled = False
while not stalled:
# Checking how many nodes have a determined value
solved_values_before = len([node for node in values.keys() if len(values[node]) == 1])
# Using the Eliminate Strategy
values = e... | Python | nomic_cornstack_python_v1 |
function login fun
begin
function wrapper *args **kwargs
begin
global login_success
if login_success == 1
begin
set res = call fun *args keyword kwargs
return res
end
else
begin
set user_password = dict
with open string user_password.txt string r as f
begin
set content = read line f
while content
begin
set tuple user ... | def login(fun):
def wrapper(*args, **kwargs):
global login_success
if login_success == 1:
res = fun(*args, **kwargs)
return res
else:
user_password = {}
with open('user_password.txt', 'r') as f:
content = f.readline()
... | Python | zaydzuhri_stack_edu_python |
string ..todo:: Fetch performance on a individual fund level, probably add a fricking tab for that to search by fund name and/or do it myself. Also RBC can link to files, but TD bank cannot no chance of scrapping individual consistenly, unless I click and copy the url, too much effort.
from selenium.webdriver.common.by... | """ ..todo:: Fetch performance on a individual fund level, probably add a fricking tab for that
to search by fund name and/or do it myself.
Also RBC can link to files, but TD bank cannot no chance of scrapping individual consistenly, unless I click and
copy the url, too much effort.
"""
from selenium.webdriver.common.... | Python | zaydzuhri_stack_edu_python |
comment parse out x start, x end, y start, y end
function parse line
begin
set tuple nid at start size = split line string
comment start: 1,3:
set tuple px py = map int split start at slice 0 : - 1 : string ,
comment size: 4x4
set tuple sx sy = map int split size string x
return tuple nid tuple px py tuple sx sy
end f... | # parse out x start, x end, y start, y end
def parse(line):
nid, at, start, size = line.split(' ')
# start: 1,3:
px, py = map(int, start[0: -1].split(','))
# size: 4x4
sx, sy = map(int, size.split('x'))
return nid, (px, py), (sx, sy)
def calc(p, s):
px, py = p
sx, sy = s
return px, py, sx+px, sy+p... | Python | zaydzuhri_stack_edu_python |
import cv2 as cv
import numpy as np
set alpha = 0.05
set capture = call VideoCapture string /home/weizy/Programs/opencv/opencv-4.1.0/samples/data/vtest.avi
if not isOpened
begin
print string cannot open the video
exit
end
set tuple ret frame = read capture
set background = call cvtColor frame COLOR_BGR2GRAY
set backgro... | import cv2 as cv
import numpy as np
alpha = 0.05
capture = cv.VideoCapture('/home/weizy/Programs/opencv/opencv-4.1.0/samples/data/vtest.avi')
if not capture.isOpened:
print('cannot open the video')
exit()
ret, frame = capture.read()
background = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
background = cv.blur(back... | Python | zaydzuhri_stack_edu_python |
import math
comment asks the user how many cookies are being produced.
set cookies = integer input string How many cookies are being produced?
if cookies < 200
begin
comment if the user puts a number under 200, lets the user know there is a minimum of 200 cookies.
print string There is a minimum of 200.
set cookies = i... | import math
cookies = int(input("How many cookies are being produced?")) #asks the user how many cookies are being produced.
if cookies < 200:
print ("There is a minimum of 200.") #if the user puts a number under 200, lets the user know there is a minimum of 200 cookies.
cookies = int(input("How many cookies ar... | Python | zaydzuhri_stack_edu_python |
function __len__ self
begin
return point_records_count
end function | def __len__(self):
return self.header.point_records_count | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function fourSum self nums target
begin
set answer = list
if length nums < 4
begin
return answer
end
sort nums
for i in range length nums - 3
begin
for j in range i + 1 length nums - 2
begin
set cur_sum = nums at i + nums at j
set l = j + 1
set r = length nums - 1
while l <... | from typing import List
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
answer = []
if len(nums) < 4:
return answer
nums.sort()
for i in range(len(nums)-3):
for j in range(i+1, len(nums)-2):
cur_sum = nu... | Python | zaydzuhri_stack_edu_python |
try
begin
set user_data_1 = integer input string Enter the 1st side of the triangle:
set user_data_2 = integer input string Enter the 2nd side of the triangle:
set user_data_3 = integer input string Enter the 3rd side of the triangle:
set triangle_side_max = 0
set triangle_side_a = 0
set triangle_side_b = 0
if user_dat... | try:
user_data_1 = int(input('Enter the 1st side of the triangle: '))
user_data_2 = int(input('Enter the 2nd side of the triangle: '))
user_data_3 = int(input('Enter the 3rd side of the triangle: '))
triangle_side_max = 0
triangle_side_a = 0
triangle_side_b = 0
if (user_data_1 + user_... | Python | zaydzuhri_stack_edu_python |
with open string text_3.txt encoding=string utf-8 as f
begin
set worker_list = list comprehension split worker_l for worker_l in read lines f
end
set worker_inf = list comprehension dict string name worker at 0 ; string rate decimal worker at 1 for worker in worker_list if length worker > 1
print string Зарплату меньше... | with open("text_3.txt", encoding="utf-8") as f:
worker_list = [worker_l.split() for worker_l in f.readlines()]
worker_inf = [{"name": worker[0],"rate": float(worker[1])} for worker in worker_list if len(worker) > 1]
print("Зарплату меньше 20'000 имеют:")
for worker in worker_inf:
if worker['rate'] < 20... | Python | zaydzuhri_stack_edu_python |
function find_index splitting delim to_find
begin
for entry in split splitting delim
begin
if entry == to_find
begin
set curr_index = index split splitting delim to_find
return curr_index
end
end
return none
end function | def find_index(splitting, delim, to_find):
for entry in splitting.split(delim):
if entry == to_find:
curr_index = splitting.split(delim).index(to_find)
return curr_index
return None | Python | nomic_cornstack_python_v1 |
comment import acquire
import prep
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import pandas as pd
comment data = acquire.wrangle_zillow()
comment data = prep.prep_zillow()
function remove_county county_num
begin
set data at string is_not = data at string fips != county_num
... | #import acquire
import prep
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import pandas as pd
#data = acquire.wrangle_zillow()
#data = prep.prep_zillow()
def remove_county(county_num):
data['is_not'] = data['fips'] != county_num
return data.loc[data.is_not, :]
d... | Python | zaydzuhri_stack_edu_python |
function _parse_tdisp_format tdisp
begin
comment Use appropriate regex for format type
set tdisp = strip tdisp
set fmt_key = if expression tdisp at 0 != string E or length tdisp > 1 and tdisp at 1 not in string NS then tdisp at 0 else tdisp at slice : 2 :
try
begin
set tdisp_re = TDISP_RE_DICT at fmt_key
end
except K... | def _parse_tdisp_format(tdisp):
# Use appropriate regex for format type
tdisp = tdisp.strip()
fmt_key = (
tdisp[0]
if tdisp[0] != "E" or (len(tdisp) > 1 and tdisp[1] not in "NS")
else tdisp[:2]
)
try:
tdisp_re = TDISP_RE_DICT[fmt_key]
except KeyError:
rais... | Python | nomic_cornstack_python_v1 |
function can_be_collected self
begin
return true
end function | def can_be_collected(self):
return True | Python | nomic_cornstack_python_v1 |
function blendenpik_srct A b d tol maxit
begin
set tic_all = performance counter
set timing = dict string srct_and_mult 0.0 ; string qr 0.0 ; string iter 0.0 ; string all 0.0
set flops = dict string srct_and_mult 0.0 ; string qr 0.0 ; string iter 0.0 ; string all 0.0
comment n >> m
set tuple n m = shape
set tuple R tup... | def blendenpik_srct(A, b, d, tol, maxit):
tic_all = perf_counter()
timing = {'srct_and_mult': 0.0, 'qr': 0.0, 'iter': 0.0, 'all': 0.0}
flops = {'srct_and_mult': 0.0, 'qr': 0.0, 'iter': 0.0, 'all': 0.0}
n, m = A.shape # n >> m
R, (r, e), time_srct_and_mult, time_qr = srct_precond(A, d, 1e-6)
... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python3
comment -*-coding:Utf-8 -*
comment code pour modifier les fichiers
comment ATTENTION : une idée de ce qui peut être fait mais LE CODE NE MARCHE PAS . PROBLEME AVEC PICKLE
import os , sys
import pickle
set nb = argv at - 1
set inputfile = string C:\Users\MENDES\Downloads\UNIV\L3\S5\TER\TER... | #! /usr/bin/env python3
# -*-coding:Utf-8 -*
# code pour modifier les fichiers
# ATTENTION : une idée de ce qui peut être fait mais LE CODE NE MARCHE PAS . PROBLEME AVEC PICKLE
import os,sys
import pickle
nb = sys.argv[-1]
inputfile= "C:\\Users\\MENDES\\Downloads\\UNIV\\L3\\S5\\TER\\TERibcp\\librairie_SD... | Python | zaydzuhri_stack_edu_python |
import math
function is_prime n
begin
if n <= 1
begin
return false
end
for i in range 2 call isqrt n + 1
begin
if n % i == 0
begin
return false
end
end
return true
end function
function is_palindrome n
begin
return string n == string n at slice : : - 1
end function
set primes = list
for num in range 1000 1101
begin
... | import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, math.isqrt(n) + 1):
if n % i == 0:
return False
return True
def is_palindrome(n):
return str(n) == str(n)[::-1]
primes = []
for num in range(1000, 1101):
if is_prime(num) and not is_palindrome(num):... | Python | jtatman_500k |
import RPi.GPIO as gpio
from RPi.GPIO import OUT as out
from RPi.GPIO import LOW as low
from RPi.GPIO import HIGH as high
from RPi.GPIO import PWM
import time
import threading
import random
from Queue import Empty
class plc_ok_th extends Thread
begin
function __init__ self q
begin
call __init__
set q = q
end function
f... | import RPi.GPIO as gpio
from RPi.GPIO import OUT as out
from RPi.GPIO import LOW as low
from RPi.GPIO import HIGH as high
from RPi.GPIO import PWM
import time
import threading
import random
from Queue import Empty
class plc_ok_th(threading.Thread):
def __init__(self,q):
super(plc_ok_th, self).__init__()
self.... | Python | zaydzuhri_stack_edu_python |
function test_project_file_write_output self
begin
comment Retrieve ProjectFile from database
set projectFile = call one
comment Invoke write output method
call writeOutput session=writeSession directory=writeDirectory name=string standard
comment Compare all files
call _compare_directories readDirectory writeDirectory... | def test_project_file_write_output(self):
# Retrieve ProjectFile from database
projectFile = self.writeSession.query(ProjectFile).one()
# Invoke write output method
projectFile.writeOutput(session=self.writeSession,
directory=self.writeDirectory,
... | Python | nomic_cornstack_python_v1 |
comment Constantes
set PORCENTAJE_BONO = 5 / 100
comment Entradas
set sueldo_minimo = integer input string Ingrese sueldo mínimo:
set utilidades_empresa = integer input string Ingrese utilidades de la empresa:
set cantidad_trabajadores = integer input string Ingrese cantidad de trabajadores:
set edad_empleado = integer... | # Constantes
PORCENTAJE_BONO = 5/100
# Entradas
sueldo_minimo = int(input('Ingrese sueldo mínimo: '))
utilidades_empresa = int(input('Ingrese utilidades de la empresa: '))
cantidad_trabajadores = int(input('Ingrese cantidad de trabajadores: '))
edad_empleado = int(input('Ingrese la edad del trabajador: '))
# Proceso... | Python | zaydzuhri_stack_edu_python |
from django.db import models
class Coordinate extends Model
begin
set latitude = call DecimalField max_digits=22 decimal_places=16
set longitude = call DecimalField max_digits=22 decimal_places=16
function __str__ self
begin
return string lat: { latitude } - lng: { longitude }
end function
end class
class DayHumidity e... | from django.db import models
class Coordinate(models.Model):
latitude = models.DecimalField(max_digits=22, decimal_places=16)
longitude = models.DecimalField(max_digits=22, decimal_places=16)
def __str__(self):
return f'lat: {self.latitude} - lng: {self.longitude}'
class DayHumidity(models.Mod... | Python | zaydzuhri_stack_edu_python |
set x = list
append x integer input string Digite um numero inteiro natural com final 0(zero):
print x | x = []
x.append(int(input("Digite um numero inteiro natural com final 0(zero): ")))
print(x)
| Python | zaydzuhri_stack_edu_python |
import datetime
import glob
import os
import xarray as xr
import numpy as np
from scipy.stats import circmean
from tqdm import tqdm
from rti_python.Codecs.BinaryCodec import BinaryCodec
from rti_python.Ensemble.EnsembleData import *
from mxtoolbox.read.adcp import adcp_init
from mxtoolbox.process.signal_ import xr_bin
... | import datetime
import glob
import os
import xarray as xr
import numpy as np
from scipy.stats import circmean
from tqdm import tqdm
from rti_python.Codecs.BinaryCodec import BinaryCodec
from rti_python.Ensemble.EnsembleData import *
from mxtoolbox.read.adcp import adcp_init
from mxtoolbox.process.signal_ import xr_bin
... | Python | zaydzuhri_stack_edu_python |
function associate_mention2candidate self mention labels sim_thr=0.7
begin
comment perform sim scores between entity mention and onto labels
set scores_and_labels = dictionary comprehension lid : call text_similarity mention ldata at 0 for tuple lid ldata in items labels
comment get scores and ids
set scores = array li... | def associate_mention2candidate(self, mention, labels, sim_thr=0.7):
# perform sim scores between entity mention and onto labels
scores_and_labels = {lid: self.text_similarity(mention, ldata)[0] for lid, ldata in labels.items()}
# get scores and ids
scores = np.array(list(scores_and_labels.values()))
labels ... | Python | nomic_cornstack_python_v1 |
function intmap value
begin
return list map int value
end function | def intmap(value):
return list(map(int, value)) | Python | nomic_cornstack_python_v1 |
function log_to_file min_level path append=false
begin
call BNLogToFile min_level string path append
end function | def log_to_file(min_level, path, append = False):
core.BNLogToFile(min_level, str(path), append) | Python | nomic_cornstack_python_v1 |
import boto3
import time
class SendToAunt
begin
function __init__ self filename number
begin
set client = call client string sns
set client = call client string sns
set filename = filename
set number = number
end function
function openFileAndSend self
begin
set file = open filename string r encoding=string utf8
set lis... | import boto3
import time
class SendToAunt():
def __init__(self,filename,number):
self.client=client = boto3.client('sns')
self.filename=filename
self.number=number
def openFileAndSend(self):
file = open(self.filename, "r",encoding="utf8")
listOfLines=file... | Python | zaydzuhri_stack_edu_python |
function idzp_rid eps m n matveca
begin
set proj = call empty m + 1 + 2 * n * min m n + 1 dtype=complex128 order=string F
set tuple k idx proj ier = call idzp_rid eps m n matveca proj
if ier
begin
raise _RETCODE_ERROR
end
set proj = reshape proj at slice : k * n - k : tuple k n - k order=string F
return tuple k idx p... | def idzp_rid(eps, m, n, matveca):
proj = np.empty(
m + 1 + 2*n*(min(m, n) + 1),
dtype=np.complex128, order='F')
k, idx, proj, ier = _id.idzp_rid(eps, m, n, matveca, proj)
if ier:
raise _RETCODE_ERROR
proj = proj[:k*(n-k)].reshape((k, n-k), order='F')
return k, idx, proj | Python | nomic_cornstack_python_v1 |
function glotSubs sql code stage lang
begin
set subs = list
for i in range 16
begin
set c = call hexchar i
set scode = code at slice : stage :
set scode = scode + lower c
set scode = call cleanCode scode
set sdesc = call glot scode sql lang stage + 1
append subs tuple scode c sdesc
end
return subs
end function | def glotSubs(sql,code,stage,lang):
subs = []
for i in range(16):
c = hexchar(i)
scode = code[:stage]
scode += c.lower()
scode = cleanCode(scode)
sdesc = glot(scode,sql,lang,stage + 1)
subs.append((scode,c,sdesc))
return subs | Python | nomic_cornstack_python_v1 |
class Solution
begin
function climbStairs self n
begin
if n <= 2
begin
return n
end
set s1 = 1
set s2 = 2
for i in range 3 n + 1
begin
set temp = s1 + s2
set s1 = s2
set s2 = temp
end
return temp
end function
end class
set sol = call Solution
set n = 5
print call climbStairs n | class Solution:
def climbStairs(self, n: int) -> int:
if n <=2:
return n
s1 = 1
s2 = 2
for i in range(3,n+1):
temp = s1+s2
s1 = s2
s2 = temp
return temp
sol = Solution()
n = 5
print(sol.climbStairs(n)) | Python | zaydzuhri_stack_edu_python |
function download_assembly assembly_name assembly_dirpath
begin
set tries = 1
set plant_name = call plant_assembly_name assembly_name
set refseq_path = call get_download_url_from_refseq_genomes assembly_name
if refseq_path is not none
begin
set url_for_assembly_file = refseq_path
end
else
if plant_name is none
begin
se... | def download_assembly(assembly_name, assembly_dirpath):
tries = 1
plant_name = plant_assembly_name(assembly_name)
refseq_path = get_download_url_from_refseq_genomes(assembly_name)
if refseq_path is not None:
url_for_assembly_file = refseq_path
elif plant_name is None:
url_for_assembly_file = get_dow... | Python | nomic_cornstack_python_v1 |
function get resource_name id opts=none custom_data=none desired_capacity=none draining_timeout=none fallback_to_on_demand=none images=none login=none managed_service_identities=none max_size=none min_size=none name=none network=none od_sizes=none on_demand_count=none os=none region=none resource_group_name=none spot_p... | def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
custom_data: Optional[pulumi.Input[str]] = None,
desired_capacity: Optional[pulumi.Input[int]] = None,
draining_timeout: Optional[pulumi.Input[int]] = None,
... | Python | nomic_cornstack_python_v1 |
string Условно-бесконечные циклы - это циклы, в которых заранее не известно количество итераций, но известен критерий остановки цикла.
while true
begin
set message = input
if length message > 10
begin
print string Ну наконец-то!
comment Останавливает выполнение тела цикла и ПЕРЕДАЕТ управление инструкции, стоящей следо... | """
Условно-бесконечные циклы - это циклы, в которых заранее не известно количество итераций,
но известен критерий остановки цикла.
"""
while True:
message = input()
if len(message) > 10:
print("Ну наконец-то!")
break # Останавливает выполнение тела цикла и ПЕРЕДАЕТ управление инструкции, стоящ... | Python | zaydzuhri_stack_edu_python |
import unittest
class TestDecompressor extends TestCase
begin
function setUp self
begin
set decompressor = call Decompressor
end function
function test_ADVENTDoesntChange self
begin
set input = string ADVENT
assert equal length input call decompress input
end function
function test_A1x5BCReturnsCorrectResult self
begin... | import unittest
class TestDecompressor(unittest.TestCase):
def setUp(self):
self.decompressor = Decompressor()
def test_ADVENTDoesntChange(self):
input = 'ADVENT'
self.assertEqual(len(input), self.decompressor.decompress(input))
def test_A1x5BCReturnsCorrectResult(self):
... | Python | zaydzuhri_stack_edu_python |
function increase self infile
begin
string Increase: 任意の箇所のバイト列と それより大きなサイズの任意のバイト列と入れ換える
set gf = infile at slice 31 : :
set index = index gf random choice gf
set index_len = length gf at index
set large_size_index = random choice list comprehension index gf g for g in gf if length g > index_len
set tuple gf at inde... | def increase(self, infile):
'''Increase: 任意の箇所のバイト列と それより大きなサイズの任意のバイト列と入れ換える
'''
gf = infile[31:]
index = gf.index(random.choice(gf))
index_len = len(gf[index])
large_size_index = random.choice([gf.index(g) for g in gf if len(g) > index_len])
gf[index], gf[large_... | Python | jtatman_500k |
function get_constants instance
begin
set costs = call get_entity instance string costs
set cpro = call get_entities instance list string cap_pro string cap_pro_new
set csto = call get_entities instance list string cap_sto_c string cap_sto_c_new string cap_sto_p string cap_sto_p_new
comment co2 timeseries
set co2 = cal... | def get_constants(instance):
costs = get_entity(instance, 'costs')
cpro = get_entities(instance, ['cap_pro', 'cap_pro_new'])
csto = get_entities(instance, ['cap_sto_c', 'cap_sto_c_new',
'cap_sto_p', 'cap_sto_p_new'])
# co2 timeseries
co2 = get_entity(instance... | Python | nomic_cornstack_python_v1 |
function preserve_view *predicates
begin
function wrapper view_callable
begin
function _wrapped self request context *args **kwargs
begin
if all list comprehension call predicate request context for predicate in predicates
begin
return call view_callable self request context *args keyword kwargs
end
else
begin
raise Vi... | def preserve_view(*predicates):
def wrapper(view_callable):
def _wrapped(self, request, context, *args, **kwargs):
if all([predicate(request, context) for predicate in predicates]):
return view_callable(self, request, context, *args, **kwargs)
else:
ra... | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2 as cv
import imutils
set template = call imread string ../../images/choco_pie_top.png
image show string Template template
print string template size: shape
set resized = call resize template width=100
image show string Resized resized
call imwrite string resize_template.png resized
print s... | import numpy as np
import cv2 as cv
import imutils
template=cv.imread("../../images/choco_pie_top.png")
cv.imshow("Template",template)
print("template size:",template.shape)
resized=imutils.resize(template,width=100)
cv.imshow("Resized",resized)
cv.imwrite("resize_template.png",resized)
print("resized template size:"... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode id=560 lang=python3
comment [560] Subarray Sum Equals K
comment @lc code=start
class Solution
begin
function subarraySum self nums k
begin
set dct = dict
set sums = 0
set count = 0
set dct at 0 = 1
for i in range length nums
begin
set sums = sums + nums at i
set count = count + get dct sums - ... | #
# @lc app=leetcode id=560 lang=python3
#
# [560] Subarray Sum Equals K
#
# @lc code=start
class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
dct = {}
sums = 0
count = 0
dct[0] = 1
for i in range(len(nums)):
sums += nums[i]
coun... | Python | zaydzuhri_stack_edu_python |
import requests , re , itertools
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
comment Make a request
set urls = list comprehension string https://www.gutenberg.org/ebooks/search/?sort_order=downloads&count=100&start_index= + i for i in list string 1 string 26 string 51 string 76 string 101
set b... | import requests, re, itertools
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup
# Make a request
urls = ['''https://www.gutenberg.org/ebooks/search/?sort_order=downloads&count=100&start_index='''
+ i for i in ['''1''', '''26''', '''51''', '''76''', '''101''']]
book_titles = []
book_ids = []
fir... | Python | zaydzuhri_stack_edu_python |
function status self status
begin
set _status = status
end function | def status(self, status):
self._status = status | Python | nomic_cornstack_python_v1 |
from tree import Tree
import matplotlib.pyplot as plt
import numpy as np
import sys
append path string ../
class RRT extends object
begin
function __init__ self config
begin
string Initializes RRT Args: config (dict): dict must contain following keys and values 'collision_check', function that takes in node and map and... | from tree import Tree
import matplotlib.pyplot as plt
import numpy as np
import sys
sys.path.append('../')
class RRT(object):
def __init__(self, config):
"""
Initializes RRT
Args:
config (dict): dict must contain following keys and values
'collision_check', ... | Python | zaydzuhri_stack_edu_python |
function Arc self *args
begin
return call GeomConvert_BSplineCurveToBezierCurve_Arc self *args
end function | def Arc(self, *args):
return _GeomConvert.GeomConvert_BSplineCurveToBezierCurve_Arc(self, *args) | Python | nomic_cornstack_python_v1 |
function _on_post_migrate app_config **kwargs
begin
call _on_app_models_updated app=models_module keyword kwargs
end function | def _on_post_migrate(app_config, **kwargs):
_on_app_models_updated(app=app_config.models_module, **kwargs) | Python | nomic_cornstack_python_v1 |
import os
function return_file_names_with_extension path extension=string
begin
return list filter lambda file -> ends with file extension list directory path
end function
function obj_to_str obj
begin
set obj_dict = dict
set not_private_fields = list filter lambda field -> not starts with field string __ and not ends... | import os
def return_file_names_with_extension(path, extension=""):
return list(filter(lambda file: file.endswith(extension), os.listdir(path)))
def obj_to_str(obj):
obj_dict = {}
not_private_fields = list(filter(lambda field: not field.startswith("__")
... | Python | zaydzuhri_stack_edu_python |
function lqr self R Q Q_f hor ks=none grid=false
begin
if call ready
begin
if B is not none
begin
if R is none
begin
set R = 0.2 * call eye call shape B at 1 + 1e-06
end
if Q is none
begin
set Q = call eye call shape A at 0
end
set P = array list Q_f
set K = none
set prev = Q_f
for hor_i in range hor - 1 - 1
begin
set ... | def lqr(self,R,Q,Q_f,hor,ks=None,grid=False):
if(self.ready()):
if(self.B is not None):
if(R is None):
R = 0.2*np.eye(np.shape(self.B)[1])+1e-6
if(Q is None):
Q = np.eye(np.shape(self.A)[0])
P = np.array([Q_f])
K = None
prev = Q_f
for hor_i in range(hor,-1,-1):
APB = np.matmu... | Python | nomic_cornstack_python_v1 |
function test_xml self
begin
set s = string <element><id>floor1</id><category>floor</category><bounds><corner1>0., 0., 0.</corner1><corner2>0., 0., 0.</corner2></bounds><pose><translation>-131.596614 , -39.9279011, 92.1260558</translation><rotation><c1>1., 0., 0.</c1><c2>0., 1., 0.</c2><c3>0., 0., 1.</c3></rotation></p... | def test_xml(self):
s = """<element><id>floor1</id><category>floor</category><bounds>\
<corner1>0., 0., 0.</corner1><corner2>0., 0., 0.</corner2></bounds>\
<pose><translation>-131.596614 , -39.9279011, 92.1260558</translation>\
<rotation><c1>1., 0., 0.</c1><c2>0., 1., 0.</c2><c3>0., 0., 1.</c3></rotation>\
... | Python | nomic_cornstack_python_v1 |
import os
import numpy as np
import sys
import random
import matplotlib.pyplot as plt
import datetime
from scipy.stats import binom
append path get current directory
import find_dependency as fd
import statistics_utils as su
set experiment_number = 5 * 10 ^ 4
set bins_num = 50
set exp_start = 5
set exp_end = 101
set ex... | import os
import numpy as np
import sys
import random
import matplotlib.pyplot as plt
import datetime
from scipy.stats import binom
sys.path.append(os.getcwd())
import find_dependency as fd
import statistics_utils as su
experiment_number = 5 * (10 ** 4)
bins_num = 50
exp_start = 5
exp_end = 101
exp_step = 10
def c... | Python | zaydzuhri_stack_edu_python |
function combined_history self
begin
set _r = list
for tuple _ v in items history
begin
extend _r v
end
if call has_box_desire
begin
for tuple _ v in items history
begin
extend _r v
end
end
return _r
end function | def combined_history(self):
_r = []
for _, v in self.history.items():
_r.extend(v)
if self.has_box_desire():
for _, v in self.desire.element.history.items():
_r.extend(v)
return _r | Python | nomic_cornstack_python_v1 |
with open string input.txt as file
begin
set lst = split read file string
end
comment part 1
comment solution: 204
set matches = list string byr string iyr string eyr string hgt string hcl string ecl string pid
set validCount = 0
for passport in lst
begin
if all generator expression x in passport for x in matches
begin... | with open("input.txt") as file:
lst = file.read().split("\n\n")
# part 1
# solution: 204
matches = ["byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"]
validCount = 0
for passport in lst:
if all(x in passport for x in matches):
validCount += 1
print(validCount)
# part 2
# solution:
| Python | zaydzuhri_stack_edu_python |
function wait_busy self tout_ms
begin
set tout = timeout
set timeout = tout_ms + 1000
call write_raw string PL:FLASH:WAit #%u % tout_ms
set r = call read_raw
set timeout = tout
if length r != 1
begin
raise call RuntimeError string unexpected PL:FLASH:WAit response
end
return ordinal r at 0 ? STATUS_BUSY == 0
end functi... | def wait_busy(self, tout_ms):
tout = self.dev.timeout
self.dev.timeout = tout_ms + 1000
self.dev.write_raw('PL:FLASH:WAit #%u' % tout_ms)
r = self.dev.read_raw()
self.dev.timeout = tout
if len(r) != 1:
raise RuntimeError('unexpected PL:FLASH:WAit response')
return (ord(r[0]) & PLFlash.STATUS_BUSY) == 0 | Python | nomic_cornstack_python_v1 |
function _generateBoardAndBoats game_key user_key
begin
comment Get a list of all available co-ords on the board.
set master_coord = call _buildBoard
comment Create all boats for the user.
call _addBoat game_key user_key master_coord CARRIER CARRIER_HITS
call _addBoat game_key user_key master_coord BATTLESHIP BATTLESHI... | def _generateBoardAndBoats(game_key, user_key):
# Get a list of all available co-ords on the board.
master_coord = _buildBoard()
# Create all boats for the user.
_addBoat(game_key,
user_key,
master_coord,
battle_consts.CARRIER,
battle_consts.CARRIER_... | 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.