code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
class Districts
begin
function __init__ self dataset
begin
string initialize variables. :param dataset: Data object that contains the data
set dataset = dataset
end function
function filter_districts self letters
begin
string :param letters: :return:
set districts = call get_all_districts
set filtered_districts = list ... | class Districts:
def __init__(self, dataset):
"""
initialize variables.
:param dataset: Data object that contains the data
"""
self.dataset = dataset
def filter_districts(self, letters):
"""
:param letters:
:return:
"""
districts ... | Python | zaydzuhri_stack_edu_python |
function get_element_field self name
begin
assert mode in list string r string a msg string Attach field option only available in mode 'r' or 'a'
assert name in elem_var_names msg string Could not find the requested field
set values = call get_element_variable_values blockId=1 name=name step=1
return values
end functio... | def get_element_field(self, name):
assert self.mode in ['r', 'a'], "Attach field option only available in mode 'r' or 'a'"
assert name in self.elem_var_names, "Could not find the requested field"
values = self.e.get_element_variable_values(blockId=1, name=name, step=1)
return values | Python | nomic_cornstack_python_v1 |
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.distributions import Normal
from likelihoods import Likelihood , Bernoulli , HomoGaussian
class MNISTClassificationNet extends Module
begin
function __init__ self nonlinearity=relu
begin
call __init__
set nonlinearity = nonlinearity
set ... | import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.distributions import Normal
from .likelihoods import Likelihood, Bernoulli, HomoGaussian
class MNISTClassificationNet(nn.Module):
def __init__(self, nonlinearity=F.relu):
super().__init__()
self.nonlinearity = non... | Python | zaydzuhri_stack_edu_python |
comment install Required Packages:
comment pip install termcolor2
comment pip install pyfiglet
comment import Required packages:
import termcolor2
import pyfiglet
comment list of qualify colors
set list_of_colors = list string red string green string yellow string blue string magenta string cyan string white
comment ge... | # install Required Packages:
# pip install termcolor2
# pip install pyfiglet
# import Required packages:
import termcolor2
import pyfiglet
list_of_colors = ['red', 'green', 'yellow','blue', 'magenta', 'cyan', 'white'] # list of qualify colors
Word = input("Please enter your word to ascii art : ") # get a word f... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
string 第四周作业: 1)canny实现 2)相机模型推导 3)透视变换实现
comment 点击鼠标,获得图像坐标
function on_EVENT_LBUTTONDOWN event x y flags param
begin
string :param event: 鼠标事件 :param x: 点击点的横坐标 :param y: #点击点的纵坐标 :param flags: :param param: :return:
set a = list
set b = list
if event == EVENT_LBUTTONDOWN
begin
commen... | import cv2
import numpy as np
'''
第四周作业:
1)canny实现
2)相机模型推导
3)透视变换实现
'''
#点击鼠标,获得图像坐标
def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
'''
:param event: 鼠标事件
:param x: 点击点的横坐标
:param y: #点击点的纵坐标
:param flags:
:param param:
:return:
'''
a = []
b = []
if event == cv2.EVE... | Python | zaydzuhri_stack_edu_python |
comment Importacion de la Clase de la Interfaz Grafica
from tkinter import *
import random
import threading
import time
import requests
comment ************************ CONSTRUCCION DE LA VENTANA
comment Construccion de la Raiz llamamos a TK
set raiz = call Tk
comment Titulo de la Ventana
title raiz string Simulador De... | from tkinter import * # Importacion de la Clase de la Interfaz Grafica
import random
import threading
import time
import requests
#************************ CONSTRUCCION DE LA VENTANA
raiz=Tk() # Construccion de la Raiz llamamos a TK
raiz.title("Simulador De Trafico") # Titulo de la Ventan... | Python | zaydzuhri_stack_edu_python |
import csv
import unidecode
import sys
if length argv is not 2
begin
print string Usage: python remove_accent.py accented_file output_file
exit
end
set arquivo_sujo = argv at 1
set saida = open argv at 2 string w
with open arquivo_sujo string r as file
begin
for linha in file
begin
set unaccented_string = call unidecod... | import csv
import unidecode
import sys
if (len(sys.argv) is not 2):
print('Usage: python remove_accent.py accented_file output_file')
exit()
arquivo_sujo= sys.argv[1]
saida = open(sys.argv[2],'w')
with open(arquivo_sujo, 'r') as file:
for linha in file:
unaccented_string = unidecode.unidecode(linha)
saida.write... | Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render , redirect
import pandas as pd
comment import matplotlib.pyplot as plt
import numpy as np
import json
from models import IrisPlants
import pickle
import joblib
comment Create your views here.
function home request
begin
if method == string POST
begin
set length_petal = POST at string... | from django.shortcuts import render, redirect
import pandas as pd
# import matplotlib.pyplot as plt
import numpy as np
import json
from .models import IrisPlants
import pickle
import joblib
# Create your views here.
def home(request):
if request.method == 'POST':
length_petal = request.POST['petal_lengt... | Python | zaydzuhri_stack_edu_python |
comment Use Hit/Miss Monte Carlo integration method to estimate integral of 1D
comment function f(x) over specified range (a,b). f(x) must stay within (ymin,ymax)
comment Oliver Watt-Meyer, November 16, 2015. Adapted from Newman solutions.
from math import sin , sqrt
from random import random
comment define integrand
f... | # Use Hit/Miss Monte Carlo integration method to estimate integral of 1D
# function f(x) over specified range (a,b). f(x) must stay within (ymin,ymax)
# Oliver Watt-Meyer, November 16, 2015. Adapted from Newman solutions.
from math import sin,sqrt
from random import random
# define integrand
def f(x):
return sin(1... | Python | zaydzuhri_stack_edu_python |
function add_depend self data
begin
try
begin
add _session call StepDependencyEntity child_id=data at string child_id parent_id=data at string parent_id
end
except SQLAlchemyError as err
begin
error string sql exception [%s] string err
return false
end
return true
end function | def add_depend(self, data):
try:
self._session.add(StepDependencyEntity(
child_id=data['child_id'],
parent_id=data['parent_id']
))
except SQLAlchemyError as err:
Log.an().error('sql exception [%s]', str(err))
return False
... | Python | nomic_cornstack_python_v1 |
try
begin
print string 나누기 전용 계산기입니다.
set num1 = integer input string 첫 번째 숫자를 입력하세요 :
set num2 = integer input string 두 번째 숫자를 입력하세요 :
print format string {0} / {1} = {2} num1 num2 integer num1 / num2
end
except ValueError
begin
comment 잘못된 입력값을 넣었을때, ex) 삼,넷 ....한글등 입력시 오류
print string 에러! 잘못된 값을 입력하였습니다.
end
comment... | try:
print("나누기 전용 계산기입니다.")
num1 = int(input("첫 번째 숫자를 입력하세요 : "))
num2 = int(input("두 번째 숫자를 입력하세요 : "))
print("{0} / {1} = {2}" .format(num1, num2, int(num1/num2)))
except ValueError:
print("에러! 잘못된 값을 입력하였습니다.") # 잘못된 입력값을 넣었을때, ex) 삼,넷 ....한글등 입력시 오류
except ZeroDivisionError as err: # 0을 입력했... | Python | zaydzuhri_stack_edu_python |
function merge_seqs seq1 seq2
begin
return map lambda item1 item2 -> item2 or item1 seq1 or tuple seq2 or tuple
end function | def merge_seqs(seq1, seq2):
return map(lambda item1, item2: item2 or item1, seq1 or (), seq2 or ()) | Python | nomic_cornstack_python_v1 |
function itkMovingHistogramImageFilterBaseISS3ISS3Neighborhood_cast obj
begin
return call itkMovingHistogramImageFilterBaseISS3ISS3Neighborhood_cast obj
end function | def itkMovingHistogramImageFilterBaseISS3ISS3Neighborhood_cast(obj: 'itkLightObject') -> "itkMovingHistogramImageFilterBaseISS3ISS3Neighborhood *":
return _itkAdaptiveHistogramEqualizationImageFilterPython.itkMovingHistogramImageFilterBaseISS3ISS3Neighborhood_cast(obj) | Python | nomic_cornstack_python_v1 |
function is_doc_not_found self
begin
return _tag == string doc_not_found
end function | def is_doc_not_found(self):
return self._tag == 'doc_not_found' | Python | nomic_cornstack_python_v1 |
function list_of_options iterable conj=string and period=true
begin
if length iterable < 2
begin
raise call PlotlyError string Your list or tuple must contain at least 2 items.
end
set template = length iterable - 2 * string {}, + string {} + conj + string {} + period * string .
return format template *iterable
end fun... | def list_of_options(iterable, conj='and', period=True):
if len(iterable) < 2:
raise exceptions.PlotlyError(
'Your list or tuple must contain at least 2 items.'
)
template = (len(iterable) - 2)*'{}, ' + '{} ' + conj + ' {}' + period*'.'
return template.format(*iterable) | Python | nomic_cornstack_python_v1 |
import sqlite3
from rosidl_runtime_py.utilities import get_message
from rclpy.serialization import deserialize_message
comment Extract a rosbag as a python dictionary with topic as keys and msg array as values
function deserialize_rosbag filename
begin
set output = dict
set bag = call connect filename
for topic in exe... | import sqlite3
from rosidl_runtime_py.utilities import get_message
from rclpy.serialization import deserialize_message
# Extract a rosbag as a python dictionary with topic as keys and msg array as values
def deserialize_rosbag(filename):
output = {}
bag = sqlite3.connect(filename)
for topic in bag.execute... | Python | zaydzuhri_stack_edu_python |
from __future__ import print_function , division
from keras.layers import Input , Dense , Reshape
from keras.layers.advanced_activations import LeakyReLU
from keras.layers import Lambda
from keras.models import Sequential , Model
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
import keras... | from __future__ import print_function, division
from keras.layers import Input, Dense, Reshape
from keras.layers.advanced_activations import LeakyReLU
from keras.layers import Lambda
from keras.models import Sequential, Model
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
import ke... | Python | zaydzuhri_stack_edu_python |
comment Bu araç @keyiflerolsun tarafından | @KekikAkademi için yazılmıştır.
comment -------------------------------#
import requests
from bs4 import BeautifulSoup
comment -------------------------------#
function ECZANE il ilce
begin
set link = string https://www.eczaneler.gen.tr/nobetci- { il } - { ilce }
set kimlik =... | # Bu araç @keyiflerolsun tarafından | @KekikAkademi için yazılmıştır.
#-------------------------------#
import requests #
from bs4 import BeautifulSoup #
#-------------------------------#
def ECZANE(il,ilce):
link = f"https://www.eczaneler.gen.tr/nobetci-{il}-{ilce}"
kimlik = {'User-Agent': ... | Python | zaydzuhri_stack_edu_python |
function chao1_lower *args **kwargs
begin
return call chao1_confidence *args keyword kwargs at 0
end function | def chao1_lower(*args,**kwargs):
return chao1_confidence(*args,**kwargs)[0] | Python | nomic_cornstack_python_v1 |
string [the divide and conquer algorithm design paradigm] 1. DIVIDE your problem into smaller subproblems. 2. CONQUER subproblems recursively. 3. COMBINE solutions of subproblems into one for the original problem. [Closest Pair] 1.Here in the closest pair problem, we're going to proceed exactly as we did in the merge s... | '''
[the divide and conquer algorithm design paradigm]
1. DIVIDE your problem into smaller subproblems.
2. CONQUER subproblems recursively.
3. COMBINE solutions of subproblems into one for the original problem.
[Closest Pair]
1.Here in the closest pair problem,
we're going to proceed exactly as we did in the m... | Python | zaydzuhri_stack_edu_python |
for i in b
begin
if count a i > 1
begin
print integer i
end
end | for i in b:
if a.count(i) > 1:
print(int(i))
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment Tests a value given on the command line.
comment Evaluates that value against a logical expression and reports whether the result of the logical test is True or False.
import sys
print string
print string
print string Testing if the value entered, + argv at 1 + string , is True or ... | #!/usr/bin/env python3
# Tests a value given on the command line.
# Evaluates that value against a logical expression and reports whether the result of the logical test is True or False.
import sys
print('')
print('')
print("Testing if the value entered, " + sys.argv[1] + ", is True or Not True...")
print('')
if sys.... | Python | zaydzuhri_stack_edu_python |
function create_and_commit cls request properties clean_headers=false
begin
import transaction
set collection = registry at COLLECTIONS at string TrackingItem
comment set remote_user to standarize permissions
set prior_remote = remote_user
set remote_user = string EMBED
comment remove any missing attributes from Downlo... | def create_and_commit(cls, request, properties, clean_headers=False):
import transaction
collection = request.registry[COLLECTIONS]['TrackingItem']
# set remote_user to standarize permissions
prior_remote = request.remote_user
request.remote_user = 'EMBED'
# remove any mi... | Python | nomic_cornstack_python_v1 |
function segment_and_visualize_image model image_path show_image=true save_to_dir=none result_image_name=string result.png
begin
set image = call imread image_path
set image_tensor = transpose image tuple 2 0 1
set image_tensor = reshape image_tensor tuple 1 shape at 0 shape at 1 shape at 2
set image_tensor = type uint... | def segment_and_visualize_image(model, image_path, show_image=True, save_to_dir=None, result_image_name='result.png'):
image = io.imread(image_path)
image_tensor = image.transpose((2, 0, 1))
image_tensor = image_tensor.reshape((1, image_tensor.shape[0], image_tensor.shape[1], image_tensor.shape[2]))
ima... | Python | nomic_cornstack_python_v1 |
function DraftBody self NumOfFaces=defaultNamedNotOptArg FaceList=defaultNamedNotOptArg EdgeList=defaultNamedNotOptArg DraftAngle=defaultNamedNotOptArg Dir=defaultNamedNotOptArg
begin
return call InvokeTypes 106 LCID 1 tuple 11 0 tuple tuple 3 1 tuple 12 1 tuple 12 1 tuple 5 1 tuple 12 1 NumOfFaces FaceList EdgeList Dr... | def DraftBody(self, NumOfFaces=defaultNamedNotOptArg, FaceList=defaultNamedNotOptArg, EdgeList=defaultNamedNotOptArg, DraftAngle=defaultNamedNotOptArg
, Dir=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(106, LCID, 1, (11, 0), ((3, 1), (12, 1), (12, 1), (5, 1), (12, 1)),NumOfFaces
, FaceList, EdgeList... | Python | nomic_cornstack_python_v1 |
function SendSms self *TargetNumbers **Properties
begin
string Creates and sends an SMS message. :Parameters: TargetNumbers : str One or more target SMS numbers. Properties Message properties. Properties available are same as `SmsMessage` object properties. :return: An sms message object. The message is already sent at... | def SendSms(self, *TargetNumbers, **Properties):
"""Creates and sends an SMS message.
:Parameters:
TargetNumbers : str
One or more target SMS numbers.
Properties
Message properties. Properties available are same as `SmsMessage` object properties.
:re... | Python | jtatman_500k |
function is_adult person
begin
return age >= 18
end function | def is_adult(person):
return person.age >= 18
| Python | zaydzuhri_stack_edu_python |
function _del_data self key
begin
pass
end function | def _del_data(self, key: int):
pass | Python | nomic_cornstack_python_v1 |
function ICombineVolumes self ToolBody=defaultNamedNotOptArg
begin
return call InvokeTypes 48 LCID 1 tuple 24 0 tuple tuple 9 1 ToolBody
end function | def ICombineVolumes(self, ToolBody=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(48, LCID, 1, (24, 0), ((9, 1),),ToolBody
) | Python | nomic_cornstack_python_v1 |
function norm_calc A
begin
set B = call tolist
set lst = list
for i in range length B
begin
append lst sum B at i
end
return max lst
end function | def norm_calc(A):
B=A.tolist()
lst=[]
for i in range(len(B)):
lst.append(sum(B[i]))
return max(lst) | Python | nomic_cornstack_python_v1 |
function get_kwargs_applicable_to_function function kwargs
begin
return dictionary comprehension key : value for tuple key value in items kwargs if key in args
end function | def get_kwargs_applicable_to_function(function, kwargs):
return {
key: value
for key, value in kwargs.items()
if key in inspect.getfullargspec(function).args
} | Python | nomic_cornstack_python_v1 |
function copy_model_parameters sess estimator1 estimator2
begin
set e1_params = list comprehension t for t in call trainable_variables if starts with name scope
set e1_params = sorted e1_params key=lambda v -> name
set e2_params = list comprehension t for t in call trainable_variables if starts with name scope
set e2_p... | def copy_model_parameters(sess, estimator1, estimator2):
e1_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator1.scope)]
e1_params = sorted(e1_params, key=lambda v: v.name)
e2_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator2.scope)]
e2_params = sorte... | Python | nomic_cornstack_python_v1 |
function median self
begin
set size = length values
set sorted_cp = sorted values at slice : :
if size ? 1 == 0
begin
set part_one = sorted_cp at size - 1 // 2
set part_two = sorted_cp at size // 2
return part_one + part_two / 2
end
return sorted_cp at size // 2
end function | def median(self):
size = len(self.values)
sorted_cp = sorted(self.values[:])
if size & 1 == 0:
part_one = sorted_cp[(size - 1) // 2]
part_two = sorted_cp[size // 2]
return (part_one + part_two) / 2
return sorted_cp[size // 2] | Python | nomic_cornstack_python_v1 |
import numpy as np
function convert_to_bin number range_start range_end bin
begin
comment number is the real value of the input
comment range_start is the minimal value of the range
comment range_end is the maximal value of the range
comment bin is the number of bins
set range_per_bin = range_end - range_start / bin
se... | import numpy as np
def convert_to_bin(number, range_start, range_end, bin):
# number is the real value of the input
# range_start is the minimal value of the range
# range_end is the maximal value of the range
# bin is the number of bins
range_per_bin = (range_end - range_start) / bin
current_... | Python | zaydzuhri_stack_edu_python |
from itertools import product
function abundant n
begin
set properdivisors = 1
for b in range 2 integer n ^ 0.5 + 1
begin
if n % b == 0
begin
set properdivisors = properdivisors + b
if n / b != b
begin
set properdivisors = properdivisors + n / b
end
end
end
if properdivisors > n
begin
return true
end
end function
set a... | from itertools import product
def abundant(n):
properdivisors = 1
for b in range(2, int(n**0.5) + 1):
if n%b == 0:
properdivisors += b
if n/b != b:
properdivisors += n/b
if properdivisors > n:
return True
abundant_numbers = [i for i in range(1,28124)... | Python | zaydzuhri_stack_edu_python |
function test_set_hp self
begin
set s = call State substance=string water
set hp = tuple call Q_ 1061602.391543017 string J/kg call Q_ 101325.0 string Pa
comment Pylance does not support NumPy ufuncs
comment type: ignore
assert call isclose T call Q_ 373.1242958476843 string K
comment type: ignore
assert call isclose p... | def test_set_hp(self):
s = State(substance="water")
s.hp = Q_(1061602.391543017, "J/kg"), Q_(101325.0, "Pa")
# Pylance does not support NumPy ufuncs
assert np.isclose(s.T, Q_(373.1242958476843, "K")) # type: ignore
assert np.isclose(s.p, Q_(101325.0, "Pa")) # type: ignore
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Dec 10 22:48:27 2020 @author: Shanthi
import os
print get current directory
set path = join path get current directory string Desktop\Practise\practice
for file in list directory path
begin
if ends with file string .txt
begin
set f = open join path path string demo.tx... | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 10 22:48:27 2020
@author: Shanthi
"""
import os
print(os.getcwd())
path = os.path.join(os.getcwd(),"Desktop\Practise\practice")
for file in os.listdir(path):
if file.endswith('.txt'):
f = open(os.path.join(path,'demo.txt'),'r')
s = f.read()
... | Python | zaydzuhri_stack_edu_python |
function _make_waiting self patient
begin
comment we need to know if we waited at the end
set waited = false
comment check all waiting rooms, keeping the right order
for waiting_ward in waiting_wards
begin
if call has_capacity patient=patient
begin
comment we found a free waiting room
comment we will have been waiting ... | def _make_waiting(
self,
patient: Patient) -> Generator[sm.events.Process, None, None]:
# we need to know if we waited at the end
waited = False
# check all waiting rooms, keeping the right order
for waiting_ward in self.waiting_wards:
if self.hospit... | Python | nomic_cornstack_python_v1 |
comment @lc app=leetcode.cn id=215 lang=python3
comment [215] 数组中的第K个最大元素
comment @lc code=start
class Solution
begin
comment 方法一:基于快速排序的选择方法 O(nlogn)
comment 时间复杂度:O(n) 空间 O(logn)
string partition 函数执行的次数是 logN ,每次输入的数组大小缩短一半。 所以总的时间复杂度为: N + N/2 + N/4 + N/8 + ... + 1 = 2N = O(N)
function findKthLargest self nums k
be... | # @lc app=leetcode.cn id=215 lang=python3
#
# [215] 数组中的第K个最大元素
#
# @lc code=start
class Solution:
# 方法一:基于快速排序的选择方法 O(nlogn)
# 时间复杂度:O(n) 空间 O(logn)
'''
partition 函数执行的次数是 logN
,每次输入的数组大小缩短一半。 所以总的时间复杂度为:
N + N/2 + N/4 + N/8 + ... + 1 = 2N = O(N)
'''
def findKthLargest(self, nums: Li... | Python | zaydzuhri_stack_edu_python |
comment eClub Summer Camp 2014, www.eclub.cvutmedialab.cz
comment Martin Kersner, m.kersner@gmail.com
comment 08-07-2014
comment Computes penalized accuracy.
comment CM confusion matrix
import numpy as np
function getPenAcc CM
begin
set CC = list list 1 0.5 1 0.5 1 1 1 2 list 0.5 1 0.5 1 1 1 2 1 list 1 0.5 1 1 0.5 2 1 ... | ## eClub Summer Camp 2014, www.eclub.cvutmedialab.cz
## Martin Kersner, m.kersner@gmail.com
## 08-07-2014
##
## Computes penalized accuracy.
##
## CM confusion matrix
import numpy as np
def getPenAcc(CM):
CC = [[1, 0.5, 1, 0.5, 1, 1, 1, 2],
[0.5, 1, 0.5, 1, 1, 1, 2, 1],
... | Python | zaydzuhri_stack_edu_python |
function opening img kernel=tuple 5 5
begin
set tmp = call grayscale img
set k = ones kernel uint8
return call morphologyEx tmp MORPH_OPEN k
end function | def opening(img, kernel = (5,5)):
tmp = grayscale(img)
k = np.ones(kernel, np.uint8)
return cv2.morphologyEx(tmp, cv2.MORPH_OPEN, k) | Python | nomic_cornstack_python_v1 |
class EmptyStack extends Exception
begin
pass
end class
class Node
begin
function __init__ self value next=none
begin
set value = value
set next = next
end function
end class
class Stack
begin
function __init__ self head=none
begin
set head = if expression head is not none then call Node head else none
end function
fun... | class EmptyStack(Exception):
pass
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class Stack:
def __init__(self, head=None):
self.head = Node(head) if head is not None else None
def push(self, *values):
for v in values:
new_head = Node(v, self.head)
self.hea... | Python | zaydzuhri_stack_edu_python |
import pygame
import math
import numpy as np
import os
function find_point_in_array array pos
begin
for i in range shape at 0
begin
if y != pos at 1
begin
continue
end
else
begin
for j in range shape at 1
begin
if x == pos at 0
begin
return array at tuple i j
end
end
end
end
return none
end function
function round_to_n... | import pygame
import math
import numpy as np
import os
def find_point_in_array(array, pos):
for i in range(array.shape[0]):
if array[i, 1].y != pos[1]:
continue
else:
for j in range(array.shape[1]):
if array[i, j].x == pos[0]:
return array... | Python | zaydzuhri_stack_edu_python |
function is_dir path
begin
if exists path path
begin
if is directory path path
begin
return true
end
else
begin
raise call ValueError string { path } is not a valid path.
end
end
else
begin
return false
end
end function | def is_dir(path):
if os.path.exists(path):
if os.path.isdir(path):
return True
else:
raise ValueError(f"{path} is not a valid path.")
else:
return False | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import numpy as np
function compute_normalized_patch_descriptors image_bw X Y feature_width
begin
string Cree features locales usando parches normalizados. Normalizar la intensidad de la imagen en una ventana local centrada en el punto de interes a un vector cuya norma es la unidad. Este featu... | #!/usr/bin/python3
import numpy as np
def compute_normalized_patch_descriptors(
image_bw: np.ndarray, X: float, Y: float, feature_width: int
) -> np.ndarray:
"""Cree features locales usando parches normalizados.
Normalizar la intensidad de la imagen en una ventana local centrada en
el punto de inte... | Python | zaydzuhri_stack_edu_python |
string functions to define basic simulation trials
from collections import deque
from DndDice import *
comment Dice Rolling Simulations
function runTrialAvgCritical n weapon modifier critFunc
begin
string simulates n number of crits calculating using the provided parameters and method args - n : the number of trials to... | """
functions to define basic simulation trials
"""
from collections import deque
from DndDice import *
# Dice Rolling Simulations
def runTrialAvgCritical(n, weapon, modifier, critFunc):
"""
simulates n number of crits calculating using the provided parameters and method
args -
n : the number ... | Python | zaydzuhri_stack_edu_python |
import requests
import json
import os
import time
import matplotlib.pyplot as plt
import sql_handler as sql
set pretotal = none
function GetData
begin
print string Receiving Data...
try
begin
set raw_data = get requests string https://api.covid19india.org/raw_data.json
print string Data Received!
end
except any
begin
p... | import requests
import json
import os
import time
import matplotlib.pyplot as plt
import sql_handler as sql
pretotal = None
def GetData():
print('Receiving Data...')
try:
raw_data = requests.get("https://api.covid19india.org/raw_data.json")
print('Data Received!')
except:
print('Un... | Python | zaydzuhri_stack_edu_python |
comment weakref_valuedict.py
import gc
from pprint import pprint
import weakref
call set_debug DEBUG_UNCOLLECTABLE
class ExpensiveObject extends object
begin
function __init__ self name
begin
set name = name
end function
function __repr__ self
begin
return string ExpensiveObject(%s) % name
end function
function __del__... | # weakref_valuedict.py
import gc
from pprint import pprint
import weakref
gc.set_debug(gc.DEBUG_UNCOLLECTABLE)
class ExpensiveObject(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'ExpensiveObject(%s)' % self.name
def __del__(self):
print(' (... | Python | zaydzuhri_stack_edu_python |
comment Author: Chuanhe Liu
comment this is uesd for the CPR method
comment which can get the wright points and wrong points
comment it also can count the number of points
import math
import obj_pose_eval.misc
import numpy as np
function dist p1 p2
begin
string get the distance of two 3D points :param p1: the coordiant... | # Author: Chuanhe Liu
# this is uesd for the CPR method
# which can get the wright points and wrong points
# it also can count the number of points
import math
import obj_pose_eval.misc
import numpy as np
def dist(p1, p2):
'''
get the distance of two 3D points
:param p1: the coordiante of point1 which is... | Python | zaydzuhri_stack_edu_python |
function use_gpu self gpu
begin
if gpu
begin
set device = device if expression call is_available then string cuda:0 else string cpu
end
else
begin
set device = device string cpu
end
end function | def use_gpu(self, gpu):
if gpu:
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
else:
self.device = torch.device("cpu") | Python | nomic_cornstack_python_v1 |
import scipy as sp
import numpy as np
import scipy.optimize
import matplotlib.pyplot
function vec2 func pts param
begin
return array list comprehension call func p param for p in pts
end function
function Henon init args
begin
string args = (a,b) init = (x0, y0) Henon map f(x,y) = y + 1 - ax^n g(x,y) = b*x
set a = args... | import scipy as sp
import numpy as np
import scipy.optimize
import matplotlib.pyplot
def vec2(func, pts, param):
return sp.array([func(p,param) for p in pts])
def Henon(init, args):
"""
args = (a,b)
init = (x0, y0)
Henon map
f(x,y) = y + 1 - ax^n
g(x,y) = b*x
"""
a = args[0]
b... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
comment Generates a data set assuming b=1
set dmag = 0.1
set mext = array range 4.0 7.01 0.1
set mval = mext at slice 0 : - 1 : + dmag / 2.0
set bval = 1.0
set numobs = call flipud diff np call flipud 10.0 ^ - bval * mext + 7.0
comment Define completeness window
set numobs at slice 0 : 6 : =... | def setUp(self):
# Generates a data set assuming b=1
self.dmag = 0.1
mext = np.arange(4.0,7.01,0.1)
self.mval = mext[0:-1] + self.dmag / 2.0
self.bval = 1.0
numobs = np.flipud(np.diff(np.flipud(10.0**(-self.bval*mext+7.0))))
# Define completeness window
n... | Python | nomic_cornstack_python_v1 |
function swap_state self
begin
set down = not down
comment if the node goes down
if down
begin
call stop
end
else
begin
comment if the node goes up
comment remove whitepage component
call recover_from_drop
comment not anymore
set is_whitepage = false
start _discovery_instance
end
end function
comment What if nobody is ... | def swap_state(self):
self.down = not self.down
if self.down: # if the node goes down
self._discovery_instance.stop()
else: # if the node goes up
self.ts.recover_from_drop() # remove whitepage component
self._discovery_instance.get_my_record().is_whitepage = F... | Python | nomic_cornstack_python_v1 |
function merge_entries self source_entry
begin
string Merge two entries. Allow the merging of two MFTEntries copying the attributes to the correct place and the datastreams. Args: source_entry (:obj:`MFTEntry`) - Source entry where the data will be copied from
comment TODO should we change this to an overloaded iadd?
c... | def merge_entries(self, source_entry):
'''Merge two entries.
Allow the merging of two MFTEntries copying the attributes to the correct
place and the datastreams.
Args:
source_entry (:obj:`MFTEntry`) - Source entry where the data will be
copied from
'... | Python | jtatman_500k |
comment \t = add a tab to the text
comment \n = linefeed (prints the stuff after this on the next line)
comment \r = carriage return (basically also used for printing stuff on the next line)
comment (\r\n to prevent problems, else useless) Linux uses \n osx \r
comment \’ = print a single quote ( ‘ ) in your text
commen... | # \t = add a tab to the text
# \n = linefeed (prints the stuff after this on the next line)
# \r = carriage return (basically also used for printing stuff on the next line)
# (\r\n to prevent problems, else useless) Linux uses \n osx \r
# \’ = print a single quote ( ‘ ) in your text
# \” = print a double quote ( “ ) in... | Python | zaydzuhri_stack_edu_python |
function handle mapping fvars=none
begin
for tuple url ofno in call group mapping 2
begin
if is instance ofno tuple
begin
set tuple ofn fna = tuple ofno at 0 list ofno at slice 1 : :
end
else
begin
set tuple ofn fna = tuple ofno list
end
set tuple fn result = call re_subm string ^ + url + string $ ofn path
comment it... | def handle(mapping, fvars=None):
for url, ofno in group(mapping, 2):
if isinstance(ofno, tuple):
ofn, fna = ofno[0], list(ofno[1:])
else:
ofn, fna = ofno, []
fn, result = re_subm('^' + url + '$', ofn, ctx.path)
if result: # it's a match
if fn.spli... | Python | nomic_cornstack_python_v1 |
comment Multiple Function Arguments
comment Every function in Python receives a predefined number of arguments, if declared normally, like this:
function myfunction first second third
begin
comment do something with the 3 variables
comment ...
pass
end function
comment It is possible to declare functions which receive ... | # Multiple Function Arguments
# Every function in Python receives a predefined number of arguments, if declared normally, like this:
def myfunction(first, second, third):
# do something with the 3 variables
# ...
pass
# It is possible to declare functions which receive a variable number of arguments, us... | Python | zaydzuhri_stack_edu_python |
function test_exception_tuple self
begin
set spill = call point_line_release_spill num_elements start_position start_time
set sp2 = call point_line_release_spill num_elements start_position2 start_time2
set scp = call SpillContainerPair true
with raises ValueError
begin
set scp = scp + tuple spill sp2 spill
end
end fun... | def test_exception_tuple(self):
spill = point_line_release_spill(self.num_elements,
self.start_position, self.start_time)
sp2 = point_line_release_spill(self.num_elements,
self.start_position2, self.start_time2)
scp = SpillContainerPair(True)
with raises... | Python | nomic_cornstack_python_v1 |
function SelectMicrophoneDevice self devIndex
begin
comment Maybe a new audio device is included, so create new pyaudio instance.
call resetPyAudio
call setUpAudioDevices
set defaultMicrophoneIndex = devIndex
if DEBUG_AUDIO_CONTROL2 and devIndex != - 1
begin
set devinfo = call get_device_info_by_index devIndex
debug st... | def SelectMicrophoneDevice(self, devIndex):
# Maybe a new audio device is included, so create new pyaudio instance.
self.resetPyAudio()
self.setUpAudioDevices()
self.defaultMicrophoneIndex = devIndex
if DEBUG_AUDIO_CONTROL2 and devIndex != -1:
devinfo = self.p.get_... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
set v_global = 10
function print_some2 num
begin
string print_some1 은 실행시 에러가 발생하지 않는데, 이 함수는 에러가 발생한다 에러의 이유에 대해 알아보고, 코드가 의도대로 동작하도록 주석을 해제하고 코드를 추가하자
string Q.에러내용 UnboundLocalError: local variable 'v_global' referenced before assignment -> 함수 밖에 있는 v_global전역 변수를 함수안에서 사용하기 위해서는 global... | # -*- coding: utf-8 -*-
v_global = 10
def print_some2(num):
""" print_some1 은 실행시 에러가 발생하지 않는데, 이 함수는 에러가 발생한다
에러의 이유에 대해 알아보고,
코드가 의도대로 동작하도록 주석을 해제하고 코드를 추가하자
"""
#
'''
Q.에러내용
UnboundLocalError: local variable 'v_global' referenced before assignment
-> 함수 밖에 있는 v_global전역 변수를
함수안에서 사용... | Python | zaydzuhri_stack_edu_python |
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score as f1
from sklearn.metrics import confusion_matrix as con
from sklearn import datasets
comment 载入威斯康辛州乳腺癌数据
set tuple X y = call load_breast_cancer return_X_y=true
comment 分割训练集与... | from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score as f1
from sklearn.metrics import confusion_matrix as con
from sklearn import datasets
# 载入威斯康辛州乳腺癌数据
X, y = datasets.load_breast_cancer(return_X_y=True)
# 分割训练集与测试集
X_train, X... | Python | zaydzuhri_stack_edu_python |
function sum_multiples_of_3_and_5 n
begin
set sum = 0
for i in range 1 n + 1
begin
if i % 3 == 0 or i % 5 == 0
begin
set sum = sum + i
end
end
return sum
end function | def sum_multiples_of_3_and_5(n):
sum = 0
for i in range(1, n+1):
if i % 3 == 0 or i % 5 == 0:
sum += i
return sum
| Python | flytech_python_25k |
import read
import pandas as pd
import collections as cl
set data1 = call load_data
set longstr = string
for tuple index each in call iterrows
begin
set longstr = longstr + string + string each at string headline
end
set longstr_spl = split longstr string
set longstr_spl_lower = list
for each in longstr_spl
begin
ap... | import read
import pandas as pd
import collections as cl
data1 = read.load_data()
longstr = ''
for index,each in data1.iterrows():
longstr = longstr + ' ' + str(each['headline'])
longstr_spl = longstr.split(' ')
longstr_spl_lower = []
for each in longstr_spl:
longstr_spl_lower.append(each.lower())
count_str = ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding: utf-8 -*-
comment __author__ = "Jeako_Wu"
import sql
import pymysql
import utility
from db_link import commodity_id2commodity_name
from product_op import total_commoditys
function vendor_exist name_get
begin
try
begin
comment 打开数据库连接
set db = call connect string localhost s... | # !/usr/bin/python3
# -*- coding: utf-8 -*-
# __author__ = "Jeako_Wu"
import sql
import pymysql
import utility
from db_link import commodity_id2commodity_name
from product_op import total_commoditys
def vendor_exist(name_get):
try:
# 打开数据库连接
db = pymysql.connect("localhost", "root", "wujiahao.", "... | Python | zaydzuhri_stack_edu_python |
function test_get_next_tag self
begin
set current = current_tag
set control = next_tag
set newVersion = call get_next_tag system_call_mock_next_tag
assert equal newVersion control
end function | def test_get_next_tag(self):
current = current_tag
control = next_tag
newVersion = core.get_next_tag(system_call_mock_next_tag)
self.assertEqual(newVersion, control) | Python | nomic_cornstack_python_v1 |
for i in range 1 n + 1
begin
if i == 1
begin
print p
end
else
begin
set j = j + 2
for k in range j
begin
if k != j
begin
print p end=string
end
else
begin
print p
end
end
print
end
end | for i in range(1,n+1):
if i==1:
print(p)
else:
j=j+2
for k in range(j):
if k!=j:
print(p,end=" ")
else:
print(p)
print()
| Python | zaydzuhri_stack_edu_python |
function launch self m
begin
if x == initial_position_x and y == initial_position_y
begin
string if self.window.get_object_at(m.x, m.y) is not None or self.window.get_object_at(m.x, m.y) is None:
if _dx == 0 or _dy == 0
begin
set _dx = random integer 1 MAX_X_SPEED
set _dy = INITIAL_Y_SPEED
comment Make the ball doesn't... | def launch(self, m):
if self.ball.x == self.initial_position_x and self.ball.y == self.initial_position_y:
""" if self.window.get_object_at(m.x, m.y) is not None or \
self.window.get_object_at(m.x, m.y) is None: """
if self._dx == 0 or self._dy == 0:
... | Python | nomic_cornstack_python_v1 |
if n >= sum a
begin
print n - sum a
end
else
begin
print - 1
end | if n >= sum(a):
print(n-sum(a))
else:
print(-1)
| Python | zaydzuhri_stack_edu_python |
function boxBlur image
begin
set row = length image
set col = length image at 0
set result = list
comment 두 번째 행부터 마지막 전 행까지 탐색
for i in range 1 row - 1
begin
set init = list
comment 두 번째 열부터 마지막 전 행까지 탐색
for j in range 1 col - 1
begin
append init sum list comprehension image at i + k at j + l for k in list - 1 0 1 f... | def boxBlur(image):
row = len(image)
col = len(image[0])
result = []
# 두 번째 행부터 마지막 전 행까지 탐색
for i in range(1, row - 1):
init = [] #
# 두 번째 열부터 마지막 전 행까지 탐색
for j in range(1, col - 1):
init.append(sum([image[i+k][j+l] for k in [-1, 0, 1] for l in [-1, 0, 1]]) /... | Python | zaydzuhri_stack_edu_python |
function payments_non_first_amount self payments_non_first_amount
begin
set _payments_non_first_amount = payments_non_first_amount
end function | def payments_non_first_amount(self, payments_non_first_amount):
self._payments_non_first_amount = payments_non_first_amount | Python | nomic_cornstack_python_v1 |
function test_new_instance_defaults_to_zero self
begin
set instance = call TestCounterModel
assert counter == 0
end function | def test_new_instance_defaults_to_zero(self):
instance = TestCounterModel()
assert instance.counter == 0 | Python | nomic_cornstack_python_v1 |
comment Week 4 - Lista de Exercícios 3
comment Exercício 2
comment Receba um número inteiro positivo na entrada e imprima os n primeiros números
comment ímpares naturais.
comment Aluno: Paulo Freitas Nobrega
set incremento = 1
set primeirosNumeros = list
set quantidadeDeNumeros = integer input string Forneça um número... | # Week 4 - Lista de Exercícios 3
# Exercício 2
# Receba um número inteiro positivo na entrada e imprima os n primeiros números
# ímpares naturais.
#Aluno: Paulo Freitas Nobrega
incremento = 1
primeirosNumeros = []
quantidadeDeNumeros = int(input("Forneça um número inteiro positivo: "))
while len(primeirosNumeros) ... | Python | zaydzuhri_stack_edu_python |
from datetime import time
function decimal_to_money count decimal=2 comment=string delimiter=string ,
begin
string Переводит значение DECIMAL из БД в печатный вид
if count
begin
set count = replace string count string , string .
end
else
begin
set count = string 0.00
end
set fnd = find count string .
set length = leng... | from datetime import time
def decimal_to_money (count, decimal = 2, comment = '', delimiter = ','):
'''Переводит значение DECIMAL из БД в печатный вид'''
if count:
count = str (count).replace (',', '.')
else:
count = '0.00'
fnd = count.find ('.')
length = len (count)
count_in... | Python | zaydzuhri_stack_edu_python |
function video_feed
begin
return call Response call gen call Camera mimetype=string multipart/x-mixed-replace; boundary=frame
end function | def video_feed():
return Response(gen(Camera()),
mimetype='multipart/x-mixed-replace; boundary=frame') | Python | nomic_cornstack_python_v1 |
for i in range n
begin
set b = integer input
insert my_list i b
end
set my_finallist = list comprehension i for tuple j i in enumerate my_list if i not in my_list at slice : j :
print list my_finallist | for i in range(n):
b= int(input())
my_list.insert(i,b)
my_finallist = [i for j, i in enumerate(my_list) if i not in my_list[:j]]
print(list(my_finallist)) | Python | zaydzuhri_stack_edu_python |
comment import torch
comment import pdb
comment from torch.autograd import Variable
comment x_data = [1.0,2.0,3.0]
comment y_data = [2.0,4.0,6.0]
comment w = Variable(torch.Tensor([1,0]), requires_grad = True)
comment def forward(x):
comment return x*w
comment def loss(x,y):
comment y_pred = forward(x)
comment return (... | # import torch
# import pdb
# from torch.autograd import Variable
#
# x_data = [1.0,2.0,3.0]
# y_data = [2.0,4.0,6.0]
#
# w = Variable(torch.Tensor([1,0]), requires_grad = True)
#
#
#
# def forward(x):
# return x*w
#
# def loss(x,y):
# y_pred = forward(x)
# return (y_pred - y)**2
#
#
# print("Predict (befor... | Python | zaydzuhri_stack_edu_python |
function rotate_towards self position slowmo_factor=1.0
begin
set angle = call angle_between position position
set delta_angle = angle - angle
if delta_angle > pi
begin
set delta_angle = - pi * 2 - delta_angle
end
else
if delta_angle < - pi
begin
set delta_angle = - - pi * 2 - delta_angle
end
set angle = angle + delta_... | def rotate_towards(self, position, slowmo_factor=1.0):
angle = geometry.angle_between(self.position, position)
delta_angle = angle - self.angle
if delta_angle > math.pi:
delta_angle = -(math.pi * 2 - delta_angle)
elif delta_angle < -math.pi:
delta_angle = -(-math... | Python | nomic_cornstack_python_v1 |
function _subplots naxes=none sharex=false sharey=false squeeze=true subplot_kw=none ax=none layout=none layout_type=string box **fig_kw
begin
string Create a figure with a set of subplots already made. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object,... | def _subplots(naxes=None, sharex=False, sharey=False, squeeze=True,
subplot_kw=None, ax=None, layout=None, layout_type='box',
**fig_kw):
"""Create a figure with a set of subplots already made.
This utility wrapper makes it convenient to create common layouts of
subplots, includi... | Python | jtatman_500k |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import gtk
class Window extends Window
begin
function __init__ self
begin
call __init__
comment Priprava hlavního okna
call set_size_request 200 50
call set_title string Pridat jmeno
call connect string destroy main_quit
set main_layout = call VBox
set napis = ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import gtk
class Window(gtk.Window):
def __init__(self):
super(Window, self).__init__()
#Priprava hlavního okna
self.set_size_request(200,50)
self.set_title("Pridat jmeno")
self.connect("destroy", gtk.main_quit)
self.main_layout = gtk.VBox()
self.napi... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import tkinter as tk
from tkinter.filedialog import askopenfilename , asksaveasfilename
function read_data
begin
set df = call askopenfilename filetypes=list tuple string CSV string *.csv tuple string Excel tuple string *.xls string *.xlsx defaultextension=string .xlsx
global data... | import numpy as np
import pandas as pd
import tkinter as tk
from tkinter.filedialog import askopenfilename, asksaveasfilename
def read_data():
df = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xlsx'))],defaultextension='.xlsx')
global data
if df :
if df .endswith(... | Python | zaydzuhri_stack_edu_python |
import datetime
import json
import time
from kafka import KafkaProducer
import numpy
class Message
begin
function __init__ self identifier
begin
set timestamp = call utcnow
set temperature = uniform 0.0 45.0
set id = identifier
end function
function next_point self
begin
return dict string timestamp call utcnow ; strin... | import datetime
import json
import time
from kafka import KafkaProducer
import numpy
class Message:
def __init__(self, identifier):
self.timestamp = datetime.datetime.utcnow()
self.temperature = numpy.random.uniform(0.0, 45.0)
self.id = identifier
def next_point(self):
retur... | Python | zaydzuhri_stack_edu_python |
import itertools
from Bio import SeqIO
set handle = open string /Users/sethcommichaux/Desktop/Rosalind.txt
for i in parse SeqIO handle string fasta
begin
set query_seq = seq
end
set letter_ls = list string A string C string G string T
set word_length = 4
set combinations_of_words = dictionary comprehension join string ... | import itertools
from Bio import SeqIO
handle = open('/Users/sethcommichaux/Desktop/Rosalind.txt')
for i in SeqIO.parse(handle,'fasta'):
query_seq = i.seq
letter_ls = ['A','C','G','T']
word_length = 4
combinations_of_words = {''.join(item):0 for item in itertools.product(letter_ls,repeat=word_length)}
for i in ra... | Python | zaydzuhri_stack_edu_python |
function greek_name self greek_name
begin
set _greek_name = greek_name
end function | def greek_name(self, greek_name):
self._greek_name = greek_name | Python | nomic_cornstack_python_v1 |
function retry count
begin
string This wrapper is used for retry the function(f) if has error, will continue for count times
end function | def retry(count):
"""
This wrapper is used for retry the function(f) if has error,
will continue for count times
""" | Python | zaydzuhri_stack_edu_python |
function coord_to_uv coord
begin
set c = icrs
set ds = list x y z
set uv = list comprehension d / norm d for d in transpose np ds
return uv
end function | def coord_to_uv(coord):
c = coord.icrs
ds = [c.cartesian.x, c.cartesian.y, c.cartesian.z]
uv = [d / np.linalg.norm(d) for d in np.transpose(ds)]
return uv | Python | nomic_cornstack_python_v1 |
function bacon_strategy score opponent_score margin=8 num_rolls=5
begin
set opp_score_tens = opponent_score // 10
set opp_score_ones = opponent_score % 10
set max_bacon = max opp_score_tens opp_score_ones
if call is_prime max_bacon + 1 == true
begin
if call next_prime max_bacon + 1 >= margin
begin
return 0
end
end
else... | def bacon_strategy(score, opponent_score, margin=8, num_rolls=5):
opp_score_tens = opponent_score // 10
opp_score_ones = opponent_score % 10
max_bacon = max(opp_score_tens, opp_score_ones)
if is_prime(max_bacon + 1) == True:
if next_prime(max_bacon + 1) >= margin:
return 0
e... | Python | nomic_cornstack_python_v1 |
comment Given an array of n elements. Find two elements in the array such that their sum is equal to given T
comment [3, 2, 7, 1, 4], 7
comment There is a O(nlogn) solution: O(nlogn)+O(n) - sort and n
function subset2_sum nums T
begin
if not nums
begin
return
end
set len_n = length nums
sort nums
set low = 0
set high =... | # Given an array of n elements. Find two elements in the array such that their sum is equal to given T
# [3, 2, 7, 1, 4], 7
# There is a O(nlogn) solution: O(nlogn)+O(n) - sort and n
def subset2_sum(nums, T):
if not nums: return
len_n = len(nums)
nums.sort()
low = 0
high = len_n -1
out_lis... | Python | zaydzuhri_stack_edu_python |
comment Depth-Firsh Search Algorithm
comment ----------------------------
comment First Edit: Saturday, April 18,2020
comment Second Edit: Sunday, April 19, 2020
comment Edit desciption:
comment Author: Stu.Nguyen Truong An
import numpy as np
class Node
begin
function __init__ self state parent action
begin
set state =... | # Depth-Firsh Search Algorithm
# ----------------------------
# First Edit: Saturday, April 18,2020
# Second Edit: Sunday, April 19, 2020
# Edit desciption:
#
# Author: Stu.Nguyen Truong An
import numpy as np
class Node:
def __init__(self, state, parent, action):
self.state = state
self.parent = p... | Python | zaydzuhri_stack_edu_python |
import collections
import re
comment clean and preprocess text
set words = split sub string \W+ string input_text
comment find most common words
set word_counter = counter words
comment print top five most common words
print call most_common 5
comment Output:
list tuple string a 1 tuple string Python 1 tuple string is... | import collections
import re
# clean and preprocess text
words = re.sub('\W+', ' ', input_text).split()
# find most common words
word_counter = collections.Counter(words)
# print top five most common words
print(word_counter.most_common(5))
# Output:
[('a', 1), ('Python', 1), ('is', 1), ('powerful', 1), ('general',... | Python | jtatman_500k |
function test_cels
begin
set N = 999
set kcc = call rand N - 0.5 * 10
set pp = call rand N - 0.5 * 10
set cc = call rand N - 0.5 * 10
set ss = call rand N - 0.5 * 10
set res0 = list comprehension call cel0 kc p c s for tuple kc p c s in zip kcc pp cc ss
set res1 = call celv kcc pp cc ss
set res2 = call cel kcc pp cc ss... | def test_cels():
N = 999
kcc = (np.random.rand(N) - 0.5) * 10
pp = (np.random.rand(N) - 0.5) * 10
cc = (np.random.rand(N) - 0.5) * 10
ss = (np.random.rand(N) - 0.5) * 10
res0 = [cel0(kc, p, c, s) for kc, p, c, s in zip(kcc, pp, cc, ss)]
res1 = celv(kcc, pp, cc, ss)
res2 = cel(kcc, pp, c... | Python | nomic_cornstack_python_v1 |
comment Nana Abekah
comment November 02, 2018
comment Counter Assignment
comment Comp 1001
import random
function pathString slots nBalls
begin
set path = list
for x in range nBalls
begin
set p = string
for x in range slots - 1
begin
set rNum = random integer 0 10
set LR = if expression rNum % 2 is 0 then string R el... | #Nana Abekah
#November 02, 2018
#Counter Assignment
#Comp 1001
import random
def pathString(slots, nBalls):
path = [];
for x in range(nBalls):
p="";
for x in range(slots-1):
rNum = random.randint(0,10);
LR = "R" if rNum%2 is 0 else "L";
p += LR;
pat... | Python | zaydzuhri_stack_edu_python |
function list_datafiles data_store
begin
set session = call Session bind=engine
set result = all
set headers = list string Id string Reference
set rows = list
for row in result
begin
append rows list datafile_id reference
end
set res = call tabulate rows headers=headers
return res
end function | def list_datafiles(data_store):
session = Session(bind=data_store.engine)
result = session.query(Datafile).all()
headers = ["Id", "Reference"]
rows = []
for row in result:
rows.append([row.datafile_id, row.reference])
res = tabulate(rows, headers=headers)
return res | Python | nomic_cornstack_python_v1 |
function next_step step_info=string iteration=false find_axes_iteration=false
begin
set gv at string step = gv at string step + 1
if iteration
begin
set gv at string iter = gv at string iter + 1
end
if find_axes_iteration
begin
set gv at string fa_iter = gv at string fa_iter + 1
end
append db dict string beam_visible ... | def next_step(step_info='', iteration=False, find_axes_iteration=False):
gv['step'] += 1
if iteration:
gv['iter'] += 1
if find_axes_iteration:
gv['fa_iter'] += 1
db.append({'beam_visible': None,
'beam_at_border': None,
'beam_c... | Python | nomic_cornstack_python_v1 |
function duration self duration
begin
set _duration = duration
end function | def duration(self, duration):
self._duration = duration | Python | nomic_cornstack_python_v1 |
function memoize func
begin
set mem = dict
function memoizer *args **kwargs
begin
set key = string args + string kwargs
if key not in mem
begin
set mem at key = call func *args keyword kwargs
end
return mem at key
end function
return memoizer
end function | def memoize(func):
mem = {}
def memoizer(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in mem:
mem[key] = func(*args, **kwargs)
return mem[key]
return memoizer | Python | nomic_cornstack_python_v1 |
function __init__ self
begin
set ram = list 0 * 256
set register = list 0 * 8
set pc = 0
set running = true
set branch_table = dict HLT HLT_op ; LDI LDI_op ; PRN PRN_op ; MUL MUL_op ; PUSH PUSH_op ; POP POP_op
end function | def __init__(self):
self.ram = [0] * 256
self.register = [0] * 8
self.pc = 0
self.running = True
self.branch_table = {
HLT: self.HLT_op,
LDI: self.LDI_op,
PRN: self.PRN_op,
MUL: self.MUL_op,
PUSH: self.PUSH_op,
... | Python | nomic_cornstack_python_v1 |
function all_lookml_tests self project_id file_id=none transport_options=none
begin
comment Project Id
comment File Id
set response = get self string /projects/ { project_id } /lookml_tests Sequence at LookmlTest query_params=dict string file_id file_id transport_options=transport_options
assert is instance response li... | def all_lookml_tests(
self,
# Project Id
project_id: str,
# File Id
file_id: Optional[str] = None,
transport_options: Optional[transport.TransportSettings] = None,
) -> Sequence[models.LookmlTest]:
response = self.get(
f"/projects/{project_id}/look... | Python | nomic_cornstack_python_v1 |
import datetime
set days = list string Monday string Tuesday string Wednesday string Thursday string Friday string Saturday string Sunday
set tuple d m = map int split input
set weekdays = call weekday
print days at weekdays | import datetime
days = ["Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"]
d, m = map(int, input().split())
weekdays = datetime.date(2009,m,d).weekday()
print(days[weekdays])
| Python | zaydzuhri_stack_edu_python |
set my_tuple = tuple 1 7 - 3 string a true none
set my_tuple1 = tuple 2 3
print my_tuple + my_tuple1
print type my_tuple | my_tuple = (1, 7, -3, 'a', True, None)
my_tuple1 = (2, 3)
print(my_tuple + my_tuple1)
print(type(my_tuple)) | Python | zaydzuhri_stack_edu_python |
function double_and_sort lst
begin
comment Check if the list is empty
if not lst
begin
return list
end
comment Double every element in the list using list comprehension
set doubled_list = list comprehension 2 * num for num in lst
comment Sort the doubled list using a custom sorting algorithm
for i in range length doub... | def double_and_sort(lst):
# Check if the list is empty
if not lst:
return []
# Double every element in the list using list comprehension
doubled_list = [2 * num for num in lst]
# Sort the doubled list using a custom sorting algorithm
for i in range(len(doubled_list)):
f... | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.