code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string This is a sampling n elements without replacement problem. It is the same as the operation that random shuffe an array and then return the first n elements. Here come the trick. When we random pick an element in the array we can store its new position in a hash table instead of the array because n is extremely l... | """
This is a sampling n elements without replacement problem. It is the same as the operation that random shuffe an array and then return the first n elements.
Here come the trick. When we random pick an element in the array we can store its new position in a hash table
instead of the array because n is extremely les... | Python | zaydzuhri_stack_edu_python |
function parse_books_into_dict
begin
if not exists path call books_store_location
begin
return call empty_books_dictionary
end
with open call books_store_location mode=string r as books_file
begin
return load yaml books_file
end
end function | def parse_books_into_dict():
if not os.path.exists(books_store_location()):
return empty_books_dictionary()
with open(books_store_location(), mode='r') as books_file:
return yaml.load(books_file) | Python | nomic_cornstack_python_v1 |
comment reference: http://wakabame.hatenablog.com/entry/2017/09/06/221400
string ベルマンフォード法 Params: edges: エッジに関する情報 num_v: ノードの数 s: スタート地点のノード番号 Return: d: sから各地点への距離リスト
function bellman_ford edges num_v s
begin
set INF = decimal string inf
set d = list comprehension INF for i in range num_v
set d at s = 0
for i in ran... | # reference: http://wakabame.hatenablog.com/entry/2017/09/06/221400
"""
ベルマンフォード法
Params:
edges: エッジに関する情報
num_v: ノードの数
s: スタート地点のノード番号
Return:
d: sから各地点への距離リスト
"""
def bellman_ford(edges:list, num_v:int, s:int):
INF = float("inf")
d = [INF for i in range(num_v)]
d[s] = 0
for i in r... | Python | zaydzuhri_stack_edu_python |
function _skip_breakpoint self message
begin
set tuple container_id = call unpack_from string B message
set tuple bee_container_name read_bytes = call unpack_pascal_string message 1
set bee_container_ref = tuple container_id bee_container_name
set breakpoint = _breakpoints at bee_container_ref
print string DBG::Skip br... | def _skip_breakpoint(self, message):
container_id, = unpack_from('B', message)
bee_container_name, read_bytes = unpack_pascal_string(message, 1)
bee_container_ref = container_id, bee_container_name
breakpoint = self._breakpoints[bee_container_ref]
print("DBG::Skip breakpoint!",... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment @Time : 2019/4/14 13:02
comment @Author : hjj
comment @Site :
comment @File : test_create_member4.py
from apis.contact.member.member_managerment import MemberManagermentApi
from utils import toolskit , comparator
class TestCreateMember4
begin
comment 动态更新用户名 手机号 邮箱
comment 通过配置文件,发... | # -*- coding: utf-8 -*-
# @Time : 2019/4/14 13:02
# @Author : hjj
# @Site :
# @File : test_create_member4.py
from apis.contact.member.member_managerment import MemberManagermentApi
from utils import toolskit, comparator
class TestCreateMember4:
# 动态更新用户名 手机号 邮箱
# 通过配置文件,发送req请求,并通过配置文件比较返回结果(全量比较)
... | Python | zaydzuhri_stack_edu_python |
function is_invalid_date d
begin
string Return boolean to indicate whether date is invalid, None if valid, False if not a date >>> import datetime >>> is_invalid_date(datetime.datetime(1970, 1, 1, 0, 0, 1)) >>> is_invalid_date(datetime.datetime(1970, 1, 1)) >>> is_invalid_date(datetime.datetime(1969, 12, 31, 23, 59, 59... | def is_invalid_date(d):
"""Return boolean to indicate whether date is invalid, None if valid, False if not a date
>>> import datetime
>>> is_invalid_date(datetime.datetime(1970, 1, 1, 0, 0, 1))
>>> is_invalid_date(datetime.datetime(1970, 1, 1))
>>> is_invalid_date(datetime.datetime(1969, 12, 31, 23... | Python | jtatman_500k |
from collections import Counter
from random import randint
class Node
begin
function __init__ self data
begin
set data = data
set next = none
set previous = none
end function
function __str__ self
begin
return string %s % data
end function
end class
class HistoryList
begin
function __init__ self
begin
set head = none
s... | from collections import Counter
from random import randint
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
def __str__(self):
return '%s' % self.data
class HistoryList:
def __init__(self):
self.head = None
self.... | Python | zaydzuhri_stack_edu_python |
from PhysicalQuantities import PhysicalQuantity as PQ
comment velocity
set v = call PQ string 120 yd/min
comment time
set t = call PQ string 1 h
comment distance
set s = v * t | from PhysicalQuantities import PhysicalQuantity as PQ
v = PQ('120 yd/min') # velocity
t = PQ('1 h') # time
s = v*t # distance | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- encoding:utf-8 -*-
from word2vec_encoder import Word2VecEncoder
function load_sentence_pair input_file skip_head=true
begin
set sentence_pairs = list
with open input_file string r encoding=string utf-8 as fp
begin
set lines = read lines fp
for tuple idx line in enumerate lines
... | #!/usr/bin/env python
# -*- encoding:utf-8 -*-
from word2vec_encoder import Word2VecEncoder
def load_sentence_pair(input_file, skip_head=True):
sentence_pairs = []
with open(input_file, "r", encoding="utf-8") as fp:
lines = fp.readlines()
for idx, line in enumerate(lines):
if skip... | Python | zaydzuhri_stack_edu_python |
string Created on May 21, 2018 @author: venkateshwara.d
import os
from selenium import webdriver
import time
set chrome_driver_path = directory name path __file__ + string \chromedriver.exe
set driver = call Chrome chrome_driver_path
get driver string http://codepad.org
comment click radio button
set python_button = ca... | '''
Created on May 21, 2018
@author: venkateshwara.d
'''
import os
from selenium import webdriver
import time
chrome_driver_path = os.path.dirname(__file__) + "\chromedriver.exe"
driver=webdriver.Chrome(chrome_driver_path)
driver.get('http://codepad.org')
# click radio button
python_button = drive... | Python | zaydzuhri_stack_edu_python |
function advanced_degree self
begin
comment Prepare
set advanced_degree = zeros N
set A = adjacency
for i in range N
begin
set advanced_degree at i = sum
end
return advanced_degree
end function | def advanced_degree(self):
# Prepare
advanced_degree = np.zeros(self.N)
A = self.adjacency
for i in range(self.N):
advanced_degree[i] = A[i, i:].sum()
return advanced_degree | Python | nomic_cornstack_python_v1 |
function __or__ self rhs
begin
return chain self rhs
end function | def __or__(self, rhs):
return Chain(self, rhs) | Python | nomic_cornstack_python_v1 |
function _get_staff_out_of_sync_data self
begin
set output = list
set tuple missing_in_campus_directory missing_in_wagtail = call _staff_out_of_sync
if missing_in_campus_directory
begin
append output list string THE FOLLOWING STAFF DATA APPEARS IN WAGTAIL, + string BUT NOT THE UNIVERSITY'S API:
for c in missing_in_cam... | def _get_staff_out_of_sync_data(self):
output = []
missing_in_campus_directory, missing_in_wagtail = self._staff_out_of_sync(
)
if missing_in_campus_directory:
output.append(
[
"THE FOLLOWING STAFF DATA APPEARS IN WAGTAIL, " +
... | Python | nomic_cornstack_python_v1 |
string purpose : To create a Player Object having Deck of Cards, and having ability to Sort by Rank and maintain the cards in a Queue implemented using Linked List. Do not use any Collection Library. Further the Player are also arranged in Queue. Finally Print the Player and the Cards received by each Player. @Author :... | """
purpose : To create a Player Object having Deck of Cards, and having ability to Sort by Rank
and maintain the cards in a Queue implemented using Linked List. Do not use any
Collection Library. Further the Player are also arranged in Queue. Finally Print
the Player and the Cards... | Python | zaydzuhri_stack_edu_python |
function clock self
begin
set match = search comment
if match is none
begin
return none
end
return integer call group string hours * 3600 + integer call group string minutes * 60 + decimal call group string seconds
end function | def clock(self) -> Optional[float]:
match = CLOCK_REGEX.search(self.comment)
if match is None:
return None
return int(match.group("hours")) * 3600 + int(match.group("minutes")) * 60 + float(match.group("seconds")) | Python | nomic_cornstack_python_v1 |
function proba D
begin
return 1.0 / 1 + exp - D * log 10 / 400
end function | def proba(D):
return 1./(1+np.exp(-D*np.log(10)/400)) | Python | nomic_cornstack_python_v1 |
function launch_simulation self parameter
begin
string Launch a single simulation, using SimulationRunner's facilities. This function is used by ParallelRunner's run_simulations to map simulation running over the parameter list. Args: parameter (dict): the parameter combination to simulate.
return next call run_simulat... | def launch_simulation(self, parameter):
"""
Launch a single simulation, using SimulationRunner's facilities.
This function is used by ParallelRunner's run_simulations to map
simulation running over the parameter list.
Args:
parameter (dict): the parameter combinatio... | Python | jtatman_500k |
comment Applied Data Science/ fall 2014 #
comment Video Project (Final) #
comment Dimas Rinarso Putro | drp354@nyu.edu #
comment image_exploration_part2.py #
import os
import sys
import time
import pylab
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as nd
from scipy.ndimage.filters import medi... | ##############################################
##############################################
# Applied Data Science/ fall 2014 #
# Video Project (Final) #
# Dimas Rinarso Putro | drp354@nyu.edu #
# image_exploration_part2.py #
#####################################... | Python | zaydzuhri_stack_edu_python |
function Clone self
begin
return call itkLaplacianSharpeningImageFilterIF2IF2_Clone self
end function | def Clone(self) -> "itkLaplacianSharpeningImageFilterIF2IF2_Pointer":
return _itkLaplacianSharpeningImageFilterPython.itkLaplacianSharpeningImageFilterIF2IF2_Clone(self) | Python | nomic_cornstack_python_v1 |
import pandas as pd
from bs4 import BeautifulSoup
import re
import nltk
call download
from nltk.corpus import stopwords
set train = read csv string labeledTrainData.tsv header=0 delimiter=string quoting=3
set example1 = call BeautifulSoup train at string review at 0
set letters_only = sub string [^a-zA-Z] string get ... | import pandas as pd
from bs4 import BeautifulSoup
import re
import nltk
nltk.download()
from nltk.corpus import stopwords
train = pd.read_csv("labeledTrainData.tsv", header=0, \
delimiter="\t", quoting=3)
example1 = BeautifulSoup(train["review"][0])
letters_only = re.sub("[^a-zA-Z]",
... | Python | zaydzuhri_stack_edu_python |
function fact x
begin
set p = 1
for i in range 2 x + 1
begin
set p = p * i
end
return p
end function
set x = integer input
print call fact x | def fact(x):
p=1
for i in range(2,x+1):
p*=i
return p
x=int(input())
print(fact(x))
| Python | zaydzuhri_stack_edu_python |
function find_mandatory_hidden_packs_dependencies self pack_ids
begin
with call session as session
begin
set results = call execute_read validate_hidden_pack_dependencies pack_ids
call _add_nodes_to_mapping generator expression node_from for result in values results
call _add_relationships_to_objects session results
re... | def find_mandatory_hidden_packs_dependencies(
self, pack_ids: List[str]
) -> List[BaseContent]:
with self.driver.session() as session:
results = session.execute_read(validate_hidden_pack_dependencies, pack_ids)
self._add_nodes_to_mapping(result.node_from for result in results... | Python | nomic_cornstack_python_v1 |
function update self
begin
info string Updating MONET station %s... % code
if _current
begin
call _update_current
end
else
begin
call _update_average
end
end function | def update(self):
log.info('Updating MONET station %s...' % self._station.code)
if self._current:
self._update_current()
else:
self._update_average() | Python | nomic_cornstack_python_v1 |
string 1. Given an integer array, output all the * *unique** pairs that sum up to a specific value k. So the input: pair_sum([1,3,2,2],4) would return "2" pairs 2. FOR TESTING PURPOSES CHANGE YOUR FUNCTION SO IT OUTPUTS THE NUMBER OF PAIRS: (1,3) (2,2)
comment #
comment Solution 1 #
comment #
function pair_sum arr k
be... | '''
1. Given an integer array, output all the * *unique** pairs that sum up to a specific value k.
So the input:
pair_sum([1,3,2,2],4)
would return "2" pairs
2. FOR TESTING PURPOSES CHANGE YOUR FUNCTION SO IT OUTPUTS THE NUMBER OF PAIRS:
(1,3)
(2,2)
'''
######################
# #
# Solution ... | Python | zaydzuhri_stack_edu_python |
import os
from hashlib import md5
from meta import Metadata , OldStyleMetadata
from exceptions import InvalidDistribution
class Distribution extends object
begin
function __init__ self path
begin
set path = path
try
begin
set meta = call Metadata self
end
except InvalidDistribution
begin
set meta = call OldStyleMetadat... | import os
from hashlib import md5
from .meta import Metadata, OldStyleMetadata
from .exceptions import InvalidDistribution
class Distribution(object):
def __init__(self, path):
self.path = path
try:
self.meta = Metadata(self)
except InvalidDistribution:
self.meta =... | Python | zaydzuhri_stack_edu_python |
import math
set a = 3 + 5
set b = 6 / 3
set c = square root 4
set d = 2 * 1.25
print a b c d | import math
a = 3+5
b = 6/3
c = math.sqrt(4)
d = 2*1.25
print(a,b,c,d)
| Python | zaydzuhri_stack_edu_python |
function main n
begin
if n <= 1
begin
return n
end
else
begin
return call main n - 1 + call main n - 2
end
end function
set nterms = integer input string enter terms:
if nterms <= 0
begin
print string Plese enter a positive integer
end
else
begin
print string Fibonacci sequence:
for i in range nterms
begin
print call m... | def main(n):
if n <= 1:
return n
else:
return(main(n-1) + main(n-2))
nterms = int(input("enter terms:"))
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(main(i),end="")
| Python | zaydzuhri_stack_edu_python |
function time_stats df
begin
print string Calculating The Most Frequent Times of Travel...
set start_time = time
comment TO DO: display the most common month
set months = list string January string February string March string April string May string June
set index = mode at 0
print format string Most Common Month is: ... | def time_stats(df):
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# TO DO: display the most common month
months = ['January','February','March','April','May','June']
index = df['Month'].mode()[0]
print("Most Common Month is: \033[1m {} \033[0m.\n".... | Python | nomic_cornstack_python_v1 |
function bind self var value type=b''
begin
set tuple error result = yield from call _communicate _BIND + _query_id + SUCCESS_TERM + var + SUCCESS_TERM + value + SUCCESS_TERM + type + SUCCESS_TERM success_term_twice=true
if error
begin
raise call QueryError result
end
info result
end function | def bind(self, var, value, type=b''):
error, result = yield from self._communicate(
self._BIND + self._query_id +
self._connection.SUCCESS_TERM + var +
self._connection.SUCCESS_TERM + value +
self._connection.SUCCESS_TERM + type +
self._connection.SUC... | Python | nomic_cornstack_python_v1 |
import numpy as np
import random
set a = linear space 0 10 11
set a = list a
set b = list 0 1 2 3 4 5 6 7 8 9 10 11 12
set c = random choice a
set d = random choice range 0 99
set e = random sample b 1
comment e=[int(i) for i in e]
print b at e at 0
print e | import numpy as np
import random
a=np.linspace(0,10,11)
a=list(a)
b=[0,1,2,3,4,5,6,7,8,9,10,11,12]
c=random.choice(a)
d=random.choice(range(0,99))
e=random.sample(b,1)
#e=[int(i) for i in e]
print (b[e[0]])
print(e)
| Python | zaydzuhri_stack_edu_python |
function get_as_thread_change_sequence_events self
begin
set source = stitches
set current_index = 0
for stitch in source
begin
set change = call decode_embroidery_command stitch at 2
set command = change at 0
set flags = command ? COMMAND_MASK
if current_index == 0
begin
if flags == STITCH or flags == SEW_TO or flags ... | def get_as_thread_change_sequence_events(self):
source = self.source_pattern.stitches
current_index = 0
for stitch in source:
change = decode_embroidery_command(stitch[2])
command = change[0]
flags = command & COMMAND_MASK
if current_index =... | Python | nomic_cornstack_python_v1 |
comment Print leaf nodes from preorder traversal of BST
class Solution
begin
function leafNodes self arr N
begin
set res = list
function recurse i j
begin
if i + 1 == j
begin
append res arr at i
return
end
if i == j
begin
return
end
set val = arr at i
set k = i + 1
while k < j and arr at k <= val
begin
set k = k + 1
e... | # Print leaf nodes from preorder traversal of BST
class Solution:
def leafNodes(self, arr, N):
res = []
def recurse(i, j):
if i + 1 == j:
res.append(arr[i])
return
if i == j:
return
val = arr[i]
k ... | Python | zaydzuhri_stack_edu_python |
function save self force_insert=false force_update=false using=none update_fields=none
begin
if capacity - occupied_sits < 0
begin
raise call ValueError string all sits in this classroom are occupied try other classes
end
else
begin
save
end
end function | def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if (self.capacity - self.occupied_sits) < 0:
raise ValueError("all sits in this classroom are occupied try other classes")
else:
super(ClassRoom, self).save() | Python | nomic_cornstack_python_v1 |
function run_on_tier self tier tier_y=none
begin
info format string Apply sppasFilter() on tier: {:s} call get_name
set sfilter = call sppasTierFilters tier
set ann_sets = list
for d in data
begin
if length d at 2 >= 1
begin
set d2 = call cast_data tier d at 0 d at 2 at 0
comment a little bit of doc:
comment - getattr(... | def run_on_tier(self, tier, tier_y=None):
logging.info("Apply sppasFilter() on tier: {:s}".format(tier.get_name()))
sfilter = sppasTierFilters(tier)
ann_sets = list()
for d in self.data:
if len(d[2]) >= 1:
d2 = sppasTierFilters.cast_data(tier, d[0], d[2][0])... | Python | nomic_cornstack_python_v1 |
function __init_connector self
begin
set creds = none
comment The file token.pickle stores the user's access and refresh tokens, and is
comment created automatically when the authorization flow completes for the first
comment time.
try
begin
if exists path TOKEN_PICKLE
begin
with open TOKEN_PICKLE string rb as token
be... | def __init_connector(self):
self.creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
try:
if os.path.exists(self.TOKEN_PICKLE):
wit... | Python | nomic_cornstack_python_v1 |
function calc_total_duration self
begin
set foo_delta = call create_timedelta foo_duration
set bar_delta = call create_timedelta bar_duration
return foo_delta + bar_delta
end function | def calc_total_duration(self):
foo_delta = self.create_timedelta(self.foo_duration)
bar_delta = self.create_timedelta(self.bar_duration)
return foo_delta + bar_delta | Python | nomic_cornstack_python_v1 |
comment Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius.
comment C = 5 * ((F-32) / 9).
comment 10. Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit.
set fahrenheit = 200
set celsius = 5 * fahrenheit - 32 / 9... | # Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius.
# C = 5 * ((F-32) / 9).
#10. Faça um Programa que peça a temperatura em graus Celsius, transforme e mostre em graus Fahrenheit.
fahrenheit = 200
celsius = 5 * ((fahrenheit - 32) / 9)
print(f'celsius: {c... | Python | zaydzuhri_stack_edu_python |
comment Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
comment Importing the dataset
set dataset = read csv string HealthData.csv
set X = values
set y = values
comment handling missing data
from sklearn.preprocessing import Imputer
set imputer = call Imputer missing_value... | # Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('HealthData.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:, 13].values
#handling missing data
from sklearn.preprocessing import Imputer
imputer=Imputer(... | Python | zaydzuhri_stack_edu_python |
function numWaterBottles numBottles numExchange
begin
set totalBottles = numBottles
while numBottles >= numExchange
begin
set newBottles = numBottles // numExchange
set totalBottles = totalBottles + newBottles
set numBottles = newBottles + numBottles % numExchange
end
return totalBottles
end function | def numWaterBottles(numBottles: int, numExchange: int) -> int:
totalBottles = numBottles
while numBottles >= numExchange:
newBottles = numBottles // numExchange
totalBottles += newBottles
numBottles = newBottles + numBottles % numExchange
return totalBottles
| Python | jtatman_500k |
from __future__ import print_function
function main
begin
set length = integer call raw_input string Length:
set width = integer call raw_input string Width:
if length <= 0
begin
print string length is not positive
return
end
if width <= 0
begin
print string width is not positive
return
end
set area = length * width
pr... | from __future__ import print_function
def main():
length = int(raw_input('Length: '))
width = int(raw_input('Width: '))
if length <= 0:
print("length is not positive")
return
if width <= 0:
print("width is not positive")
return
area = length * width
print("The... | Python | zaydzuhri_stack_edu_python |
from __future__ import division
import sympy as sp
set tuple x y z t = call symbols string x y z t
call solve x ^ 2 - 1
call solve x ^ 3 + 2 * x ^ 2 - x + 1
call solve tuple x + 5 * y - 2 - 3 * x + 6 * y - 15 x y
call solve tuple x + y + z y + 1 z - 2 x y z
call solve x ^ 3 + 3 * x ^ 2 + 2 * x + 1
call solve sin x + co... | from __future__ import division
import sympy as sp
x, y, z, t = sp.symbols('x y z t')
sp.solve(x**2 - 1)
sp.solve(x**3 +2*x**2 -x + 1)
sp.solve((x + 5*y - 2, -3*x + 6*y - 15), x, y)
sp.solve((x+y+z,y+1,z-2),x,y,z)
sp.solve(x**3 + 3*x**2 + 2*x + 1)
sp.solve(sp.sin(x)+ sp.cos(x) - 0.5)
sp.solve(sp.sin(x)+ sp.cos(x)... | Python | zaydzuhri_stack_edu_python |
import os
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from string import punctuation
from collections import Counter
function compute_human_summaries_rogue
begin
set summaries_root = string data/summaries-gold
set summary_dirs = list comprehension f for f in list directory summaries_root i... | import os
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from string import punctuation
from collections import Counter
def compute_human_summaries_rogue():
summaries_root = "data/summaries-gold"
summary_dirs = [f for f in os.listdir(summaries_root) if os.path.isdir(os.path.join(summ... | Python | zaydzuhri_stack_edu_python |
from math import factorial
from fractions import Fraction
function calculate_probability_odd_sum
begin
comment Condition 1: abc is odd, de is even
comment the odd numbers from the set
set odd_numbers = list 1 3 5
comment the even numbers from the set
set even_numbers = list 2 4
comment Choosing 3 odd numbers for a, b, ... | from math import factorial
from fractions import Fraction
def calculate_probability_odd_sum():
# Condition 1: abc is odd, de is even
odd_numbers = [1, 3, 5] # the odd numbers from the set
even_numbers = [2, 4] # the even numbers from the set
# Choosing 3 odd numbers for a, b, c (there are 3 odd... | Python | dbands_pythonMath |
comment This program is free software: you can redistribute it and/or modify
comment it under the terms of the GNU Lesser General Public License as published by
comment the Free Software Foundation, either version 3 of the License, or
comment (at your option) any later version.
comment This program is distributed in th... | #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be use... | Python | zaydzuhri_stack_edu_python |
for x in range 101
begin
set sum = sum + x
print sum
set sum = 0
set n = 99
while n > 0
begin
set sum = sum + n
set n = n - 2
print sum
end
end | for x in range (101) :
sum = sum + x
print( sum )
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print( sum)
| Python | zaydzuhri_stack_edu_python |
from __future__ import print_function
set a = integer call raw_input string Enter Total Inputs :
set l = list string * a
set n = 0
while n < a
begin
set b = integer call raw_input string Enter Value :
set c = integer call raw_input string Enter Value :
set d = integer call raw_input string Enter Value :
if b < c and b... | from __future__ import print_function
a=int(raw_input("Enter Total Inputs : "))
l=[""]*a
n=0
while n<a:
b=int(raw_input("Enter Value :"))
c=int(raw_input("Enter Value :"))
d=int(raw_input("Enter Value :"))
if (b<c) and (b<d):
l[n]=b
elif (c<b) and (c<d):
l[n]=c
elif (d<b) and (d<c):
l[n]=d
else:
print("E... | Python | zaydzuhri_stack_edu_python |
function empty
begin
return call RowSet call bigtable_empty_row_set
end function | def empty() -> RowSet:
return RowSet(core_ops.bigtable_empty_row_set()) | Python | nomic_cornstack_python_v1 |
comment noqa: E501 # noqa: E501
function __init__ self status=none message=none sim_time=none plan=none config=none sensors=none
begin
set _status = none
set _message = none
set _sim_time = none
set _plan = none
set _config = none
set _sensors = none
set discriminator = none
set status = status
if message is not none
b... | def __init__(self, status=None, message=None, sim_time=None, plan=None, config=None, sensors=None): # noqa: E501 # noqa: E501
self._status = None
self._message = None
self._sim_time = None
self._plan = None
self._config = None
self._sensors = None
self.discrimi... | Python | nomic_cornstack_python_v1 |
function get_row_names self
begin
return call get_rows
end function | def get_row_names(self):
return self.get_rows() | Python | nomic_cornstack_python_v1 |
import telebot
import key
import database as db
from telebot import types
import solo_database as s_db
from random import randint
import num_update as n_u
import supernum as sn
set bot = call TeleBot key
decorator call message_handler content_types=list string text
function sey_hello message call=false
begin
if call !=... | import telebot
import key
import database as db
from telebot import types
import solo_database as s_db
from random import randint
import num_update as n_u
import supernum as sn
bot = telebot.TeleBot(key.key)
@bot.message_handler(content_types=['text'])
def sey_hello(message,call=False):
if call != False:
p... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Thu Apr 16 15:56:10 2020 @author: chen 937. Reorder Data in Log Files Easy 471 1481 Add to List Share You have an array of logs. Each log is a space delimited string of words. For each log, the first word in each log is an alphanumeric identi... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 16 15:56:10 2020
@author: chen
937. Reorder Data in Log Files
Easy
471
1481
Add to List
Share
You have an array of logs. Each log is a space delimited string of words.
For each log, the first word in each log is an alphanumeric identifier. ... | Python | zaydzuhri_stack_edu_python |
function _idToRname self rId
begin
return _referenceIdMap at rId
end function | def _idToRname(self, rId):
return self._referenceIdMap[rId] | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python2
import usb
import os
set G9_VENDOR_ID = 1133
set G9_PRODUCT_IDS = list 49224 49254 49254
function get_g9_device
begin
for bus in call busses
begin
for device in devices
begin
if idVendor == G9_VENDOR_ID and idProduct in G9_PRODUCT_IDS
begin
return open
end
end
end
return none
end function
func... | #!/usr/bin/python2
import usb
import os
G9_VENDOR_ID = 0x046d
G9_PRODUCT_IDS = [0xc048, 0xc066, 0xc066]
def get_g9_device():
for bus in usb.busses():
for device in bus.devices:
if device.idVendor == G9_VENDOR_ID and \
device.idProduct in G9_PRODUCT_IDS:
retu... | Python | zaydzuhri_stack_edu_python |
comment while some_boolean_condition:
comment do something
comment else
comment do something different
set x = 0
while x < 5
begin
print string The current value of x is { x }
set x = x + 1
end
while else
begin
print string x is too large
end
set my_list = list 1 2 3
for item in x
begin
comment comment
pass
end
set mys... | #while some_boolean_condition:
#do something
#else
#do something different
x=0
while x<5:
print(f'The current value of x is {x}')
x=x+1
else:
print('x is too large')
my_list=[1,2,3]
for item in x:
#comment
pass
mystring='Sammy' | Python | zaydzuhri_stack_edu_python |
string Name:Ranbir Dixit Program: Dictreader CSV Version:3 Description: uses DictReader to open a csv file and loop over all the rows and prints them out
import csv
with open string C:\Users\rkd\Desktop\ITNPBD2\lab-fileio-regex.csv as f
begin
set r = dict reader f delimiter=string ,
end | '''
Name:Ranbir Dixit
Program: Dictreader CSV
Version:3
Description: uses DictReader to open a csv file and loop over all the rows and prints them out
'''
import csv
with open('C:\\Users\\rkd\\Desktop\\ITNPBD2\\lab-fileio-regex.csv') as f:
r=csv.DictReader(f,delimiter=',') | Python | zaydzuhri_stack_edu_python |
function test_copy_loader_files_to_worker__empty_next_run_folder self
begin
comment mock up that next_run_folder exists
set directories at home + string /signal/deploy/loader_files/next_run = true
comment run the deployer
set deployer = call GeoProcessingDeployer string 1.1.1.1
comment run create server to fake the add... | def test_copy_loader_files_to_worker__empty_next_run_folder(self):
# mock up that next_run_folder exists
self.file_provider.directories[self.home + "/signal/deploy/loader_files/next_run"] = True
# run the deployer
deployer = GeoProcessingDeployer('1.1.1.1')
# run create server t... | Python | nomic_cornstack_python_v1 |
string Tests that transformer works as expected
import pandas as pd
from spookyauthor.models.transform import TextTransformer
import numpy as np
import pytest
decorator fixture
function text
begin
string Return a series with text
set test = list string This is four words string This one is five words
return call Series... | """
Tests that transformer works as expected
"""
import pandas as pd
from spookyauthor.models.transform import TextTransformer
import numpy as np
import pytest
@pytest.fixture
def text():
"""Return a series with text"""
test = ["This is four words",
"This one is five words"]
return pd.Series(... | Python | zaydzuhri_stack_edu_python |
from math import sqrt
from OOP.Figures.Figure import Figure
class Triangle extends Figure
begin
function __init__ self name colour a b c
begin
call __init__ name colour
set sides = list a b c
set m = max sides
pop sides index sides m
if m < sum sides
begin
set a = a
set b = b
set c = c
set created = true
end
else
begin... | from math import sqrt
from OOP.Figures.Figure import Figure
class Triangle(Figure):
def __init__(self, name, colour, a, b, c):
super().__init__(name, colour)
sides = [a, b, c]
m = max(sides)
sides.pop(sides.index(m))
if m < sum(sides):
self.a = a
se... | Python | zaydzuhri_stack_edu_python |
comment my dp
class Solution
begin
function maxProduct self nums
begin
if not nums
begin
return 0
end
comment positive & negative
set dp = list comprehension list 0 * length nums for _ in range 2
set max_prod = decimal string -inf
for i in range length nums
begin
if i == 0
begin
set dp at 0 at i = nums at i
set dp at 1... | #my dp
class Solution:
def maxProduct(self, nums: List[int]) -> int:
if not nums:
return 0
#positive & negative
dp = [[0] * len(nums) for _ in range(2)]
max_prod = float('-inf')
for i in range(len(nums)):
if i == 0:
... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python3
comment -*- coding: utf-8 -*-
string Imprime lso registro ya seatodo o de uno en uno
import caso.datos as datos
function despliega_uno elemento
begin
for campo in orden
begin
print campo + string : + string elemento at campo
end
end function
function despliega_todos
begin
set contador = 0
for... | #! /usr/bin/python3
# -*- coding: utf-8 -*-
"""Imprime lso registro ya seatodo o de uno en uno"""
import caso.datos as datos
def despliega_uno(elemento):
for campo in datos.orden:
print(campo + ": " + str(elemento[campo]))
def despliega_todos():
contador = 0
for alumno in datos.alumnos:
... | Python | zaydzuhri_stack_edu_python |
function create_db
begin
try
begin
set conn = call connect user=string postgres password=string postgres host=string 127.0.0.1 port=string 5432 database=string postgres
set cur = call cursor
return tuple conn cur
end
except tuple Exception DatabaseError as error
begin
print string Error while connecting to PostgreSQL d... | def create_db():
try:
conn = psycopg2.connect(user='postgres',
password='postgres',
host = '127.0.0.1',
port = '5432',
database = 'postgres')
cur = conn.cursor()
re... | Python | nomic_cornstack_python_v1 |
comment Importa as bibliotecas necessarias
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix , accuracy_score
from sklearn.naive_bayes import GaussianNB
com... | #Importa as bibliotecas necessarias
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix , accuracy_score
from sklearn.naive_bayes import GaussianNB
#Le o dat... | Python | zaydzuhri_stack_edu_python |
function unit_to_dict self unit
begin
assert type == string A
set path = call _get_assessment_path unit
set fs = fs
if is file fs path
begin
set content = get fs path
end
else
begin
set content = string
end
set review_form_path = call _get_review_form_path unit
if review_form_path and is file fs review_form_path
begin... | def unit_to_dict(self, unit):
assert unit.type == 'A'
path = self._get_assessment_path(unit)
fs = self.app_context.fs
if fs.isfile(path):
content = fs.get(path)
else:
content = ''
review_form_path = self._get_review_form_path(unit)
if rev... | Python | nomic_cornstack_python_v1 |
comment This is a really cool example of using closures to store data.
comment We must look at the signature type of cons to retrieve its first and last elements. cons takes in a and b, and returns a new anonymous function, which itself takes in f, and calls f with a and b. So the input to car and cdr is that anonymous... | #This is a really cool example of using closures to store data.
# We must look at the signature type of cons to retrieve its first and last elements. cons takes in a and b, and returns a new anonymous function, which itself takes in f, and calls f with a and b. So the input to car and cdr is that anonymous function, w... | Python | zaydzuhri_stack_edu_python |
import os
import unittest
import json
from flask_sqlalchemy import SQLAlchemy
from flaskr import create_app
from models import setup_db , Question , Category
class TriviaTestCase extends TestCase
begin
string This class represents the trivia test case
function setUp self
begin
string Define test variables and initializ... | import os
import unittest
import json
from flask_sqlalchemy import SQLAlchemy
from flaskr import create_app
from models import setup_db, Question, Category
class TriviaTestCase(unittest.TestCase):
"""This class represents the trivia test case"""
def setUp(self):
"""Define test variables and initiali... | Python | zaydzuhri_stack_edu_python |
function do_fetch self id
begin
set id = id
try
begin
set sexps = call fetch database args
end
except FetchError as e
begin
error msg
end
try else
begin
call print_sexp sexps
end
end function | def do_fetch(self, id):
self.args.id = id
try:
sexps = fetch(self.database, self.args)
except FetchError as e:
logging.error(e.msg)
else:
self.print_sexp(sexps) | Python | nomic_cornstack_python_v1 |
while star < stars + 1
begin
print star * string *
set star = star + 1
end
for star in range 3
begin
print string **
end | while star < stars+1:
print(star * '*')
star = star + 1
for star in range (3):
print('*' '*') | Python | zaydzuhri_stack_edu_python |
import sys , math
set lines = read lines stdin
for line in lines
begin
set line = strip line
set letters = dict
for c in line
begin
if c not in letters
begin
set letters at c = 1
end
else
begin
set letters at c = letters at c + 1
end
end
set t = 1
set s = 0
for key in letters
begin
set tmp = call factorial letters at ... | import sys,math
lines = sys.stdin.readlines()
for line in lines:
line = line.strip()
letters = {}
for c in line:
if c not in letters:
letters[c] = 1
else:
letters[c] += 1
t = 1
s = 0
for key in letters:
tmp = math.factorial(letters[key])
t ... | Python | zaydzuhri_stack_edu_python |
function json_compact obj
begin
return dumps obj separators=tuple string , string :
end function | def json_compact(obj) -> str:
return json.dumps(obj, separators=(",", ":")) | Python | nomic_cornstack_python_v1 |
from math import sqrt
set a = decimal input string Enter a:
set b = decimal input string Enter b:
set c = decimal input string Enter c:
if a == 0 and b != 0
begin
set x = - c / b
print string x= %0.1f % x
end
else
if a == 0 and b == 0
begin
print string Пустое множество
end
else
if a != 0 and b == 0
begin
if c < 0
begi... | from math import sqrt
a=float(input("Enter a: "))
b=float(input("Enter b: "))
c=float(input("Enter c: "))
if a==0 and b!=0:
x=-c/b
print("x= %0.1f"%(x))
elif a==0 and b==0:
print('Пустое множество')
elif a!=0 and b==0:
if c<0:
x1=(-c/a)**0.5
x2=-(-c/a)**0.5
print("x1= %0.1f"%(x1... | Python | zaydzuhri_stack_edu_python |
async function getImageURLS self tags fuzzy=false singlePage=false
begin
if fuzzy
begin
set tags = split tags string
for tag in tags
begin
set tag = tag + string ~
end
set temp = string
set tags = join temp tags
print tags
end
set num = await call totalImages tags
if num != 0
begin
set PID = 0
set imgList = list
set ... | async def getImageURLS(self, tags, fuzzy=False, singlePage=False):
if fuzzy:
tags = tags.split(" ")
for tag in tags:
tag = tag + "~"
temp = " "
tags = temp.join(tags)
print(tags)
num = await self.totalImages(tags)
if num... | Python | nomic_cornstack_python_v1 |
function test_plugins_search_odatav4search_normalize_results_onda self
begin
assert true has attribute config string metadata_pre_mapping
call assertDictEqual metadata_pre_mapping dict string metadata_path call cached_parse string $.Metadata ; string metadata_path_id string id ; string metadata_path_value string value
... | def test_plugins_search_odatav4search_normalize_results_onda(self):
self.assertTrue(hasattr(self.onda_search_plugin.config, "metadata_pre_mapping"))
self.assertDictEqual(
self.onda_search_plugin.config.metadata_pre_mapping,
{
"metadata_path": cached_parse("$.Meta... | Python | nomic_cornstack_python_v1 |
string When this application is imported then it will attach a handler to class_prepared signal. Then handler mark models as translatable if they has a `translatable_fields` attribute or was described in `settings.TRANSLATABLE_MODELS` or some of the model parents are marked for translation Describing in settings.py is ... | """
When this application is imported then it will attach a handler to
class_prepared signal. Then handler mark models as translatable
if they has a `translatable_fields` attribute or was described in
`settings.TRANSLATABLE_MODELS` or some of the model parents are marked
for translation
Describing in settings.py is fo... | Python | zaydzuhri_stack_edu_python |
function split_simsplit_3epochs_iter4 params ns
begin
comment 24 parameters
set tuple nu1a nu2a nu3a nu1b nu2b nu3b nu1c nu2c nu3c m1_12 m1_13 m1_21 m1_23 m1_31 m1_32 m2_12 m2_13 m2_21 m2_23 m2_31 m2_32 T1 T2 T3 = params
set sts = call steady_state_1D ns at 0 + ns at 1 + ns at 2
set fs = call Spectrum sts
set fs = call... | def split_simsplit_3epochs_iter4(params, ns):
#24 parameters
nu1a, nu2a, nu3a, nu1b, nu2b, nu3b, nu1c, nu2c, nu3c, m1_12, m1_13, m1_21, m1_23, m1_31, m1_32, m2_12, m2_13, m2_21, m2_23, m2_31, m2_32, T1, T2, T3 = params
sts = moments.LinearSystem_1D.steady_state_1D(ns[0] + ns[1] + ns[2])
fs = moments.Sp... | Python | nomic_cornstack_python_v1 |
comment Написать программу, которая собирает «Хиты продаж» с сайтов техники М.видео, ОНЛАЙН ТРЕЙД и складывает данные в БД.
comment Магазины можно выбрать свои. Главный критерий выбора: динамически загружаемые товары.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from ... | # Написать программу, которая собирает «Хиты продаж» с сайтов техники М.видео, ОНЛАЙН ТРЕЙД и складывает данные в БД.
# Магазины можно выбрать свои. Главный критерий выбора: динамически загружаемые товары.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from pymongo imp... | Python | zaydzuhri_stack_edu_python |
function build_main_layout self
begin
set _main_frame = call frameLayout string frm_main p=_main_window lv=false mh=5 mw=5
set _main_layout = call columnLayout string lay_main p=_main_frame adj=true
end function | def build_main_layout(self):
self._main_frame = cmds.frameLayout("frm_main", p=self._main_window, lv=False, mh=5, mw=5)
self._main_layout = cmds.columnLayout("lay_main", p=self._main_frame, adj=True) | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
comment x = tf.add (5,2)
comment x = tf.sub(5,2)
comment x = tf.mult(3,4)
set x = call placeholder string
set y = call placeholder int32
set z = call placeholder float32
with call Session as sess
begin
set feed_dict = dict x string Hello World ; y 123 ; z 45.67
set output = run x feed_dict=feed_... | import tensorflow as tf
#x = tf.add (5,2)
#x = tf.sub(5,2)
#x = tf.mult(3,4)
x = tf.placeholder(tf.string)
y = tf.placeholder(tf.int32)
z = tf.placeholder(tf.float32)
with tf.Session() as sess:
feed_dict = {
x: "Hello World",
y: 123,
z: 45.67
}
output = sess.run(x, feed_dict=feed_... | Python | zaydzuhri_stack_edu_python |
function run_file file_path globals_ script_dir=SCRIPT_DIR
begin
call fix_sys_path
set script_name = base name path file_path
set script_name = get SCRIPT_EXCEPTIONS script_name script_name
set script_path = join path script_dir script_name
end function | def run_file(file_path, globals_, script_dir=SCRIPT_DIR):
fix_sys_path()
script_name = os.path.basename(file_path)
script_name = SCRIPT_EXCEPTIONS.get(script_name, script_name)
script_path = os.path.join(script_dir, script_name) | Python | nomic_cornstack_python_v1 |
import csv
comment utilities used by various scripts.
class UnicodeReader
begin
function __init__ self f dialect=excel encoding=string utf-8 **kwds
begin
set reader = reader f dialect=dialect keyword kwds
set encoding = encoding
end function
function next self
begin
set row = next
return list comprehension call unicode... | import csv
# utilities used by various scripts.
class UnicodeReader:
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
self.reader = csv.reader(f, dialect=dialect, **kwds)
self.encoding = encoding
def next(self):
row = self.reader.next()
return [un... | Python | zaydzuhri_stack_edu_python |
import urlparse
function app environ start_response
begin
set params = call parse_qs environ at string QUERY_STRING
call start_response string 200 OK list tuple string Content-Type string text/plain
set body = list
for tuple keys values in call iteritems
begin
if length values > 1
begin
for val in values
begin
append ... | import urlparse
def app(environ, start_response):
params = urlparse.parse_qs(environ["QUERY_STRING"])
start_response("200 OK", [("Content-Type", "text/plain")])
body = []
for keys, values in params.iteritems():
if len(values) > 1:
for val in values:
body.append('%s=%s' % (keys, val))
continue
else:... | Python | zaydzuhri_stack_edu_python |
function __init__ self params
begin
call __init__ params
set p = params
assert left_context >= 1 msg string Left context should be at least one.
assert not packed_input msg string Packed input not implemented yet.
if block_size is none
begin
set block_size = max 1 left_context - 1
set block_size = block_size + - block_... | def __init__(self, params):
super().__init__(params)
p = self.params
assert p.left_context >= 1, 'Left context should be at least one.'
assert not p.packed_input, 'Packed input not implemented yet.'
if p.block_size is None:
block_size = max(1, p.left_context - 1)
p.block_size = block_s... | Python | nomic_cornstack_python_v1 |
function _GetAllDeps self solution_urls
begin
set deps = dict
for solution in call GetVar string solutions
begin
set custom_vars = get solution string custom_vars dict
set solution_deps = call _GetDefaultSolutionDeps solution at string name custom_vars
for d in solution_deps
begin
if string custom_deps in solution and... | def _GetAllDeps(self, solution_urls):
deps = {}
for solution in self.GetVar("solutions"):
custom_vars = solution.get("custom_vars", {})
solution_deps = self._GetDefaultSolutionDeps(solution["name"],
custom_vars)
for d in solution_deps:
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
string @project= Life_is_short_you_need_python @file= Lession_1 @author= wubingyu @create_time= 2017/12/15 上午10:36 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
@project= Life_is_short_you_need_python
@file= Lession_1
@author= wubingyu
@create_time= 2017/12/15 上午10:36
"""
| Python | zaydzuhri_stack_edu_python |
function DeactivateTimeOut self
begin
set callResult = call _Call string DeactivateTimeOut
end function | def DeactivateTimeOut(self):
callResult = self._Call("DeactivateTimeOut", ) | Python | nomic_cornstack_python_v1 |
import json
from datetime import timedelta
from airflow.utils.decorators import apply_defaults
from presidio.utils.airflow.context_wrapper import ContextWrapper
from presidio.utils.airflow.operators.spring_boot_jar_operator import SpringBootJarOperator
from presidio.utils.services.fixed_duration_strategy import FIX_DUR... | import json
from datetime import timedelta
from airflow.utils.decorators import apply_defaults
from presidio.utils.airflow.context_wrapper import ContextWrapper
from presidio.utils.airflow.operators.spring_boot_jar_operator import SpringBootJarOperator
from presidio.utils.services.fixed_duration_strategy import FIX_D... | Python | zaydzuhri_stack_edu_python |
function format_strings strings
begin
set formatted_strings = list
for string in strings
begin
set words = split string
set formatted_words = list
for word in words
begin
set formatted_word = upper word at 0 + lower word at slice 1 : :
append formatted_words formatted_word
end
set formatted_string = join string for... | def format_strings(strings):
formatted_strings = []
for string in strings:
words = string.split()
formatted_words = []
for word in words:
formatted_word = word[0].upper() + word[1:].lower()
formatted_words.append(formatted_word)
form... | Python | jtatman_500k |
comment 判断链表是否有环
comment class Node:
comment def __init__(self,data):
comment self.data = data
comment self.next = None
comment def pan(data):
comment curr = data
comment prev = data
comment while curr and curr.next is not None:
comment prev = prev.next
comment curr = curr.next.next
comment if prev == curr:
comment ret... | # 判断链表是否有环
# class Node:
# def __init__(self,data):
# self.data = data
# self.next = None
#
# def pan(data):
# curr = data
# prev = data
# while curr and curr.next is not None:
# prev = prev.next
# curr = curr.next.next
# if prev == curr:
# return Tru... | Python | zaydzuhri_stack_edu_python |
function updateReadyTasks g readyTasks nodes scheduledNode deletion=true verbose=false
begin
for n in call successors scheduledNode
begin
set ready = true
for p in call predecessors n
begin
if p in readyTasks or p in nodes
begin
set ready = false
end
end
if ready
begin
if n not in readyTasks
begin
append readyTasks n
e... | def updateReadyTasks(g, readyTasks, nodes, scheduledNode, deletion=True, verbose=False):
for n in g.successors(scheduledNode):
ready = True
for p in g.predecessors(n):
if p in readyTasks or p in nodes:
ready = False
if ready:
if n not in readyTa... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
import Lw2_1
function draw x y name
begin
plot x y
grid true
save figure name
call cla
end function
function main
begin
set tuple a b = tuple - 1 1
set x = linear space - 5 5 1000
set y = list comprehension f dist i for i in x
call draw x y string func
set x = linear s... | import matplotlib.pyplot as plt
import numpy as np
import Lw2_1
def draw(x, y, name):
plt.plot(x, y)
plt.grid(True)
plt.savefig(name)
plt.cla()
def main():
a, b = (-1, 1)
x = np.linspace(-5, 5, 1000)
y = [Lw2_1.Solver.f(i) for i in x]
draw(x, y, 'func')
x = np.linspace(a, b, 10... | Python | zaydzuhri_stack_edu_python |
from PyQt5.QtWidgets import QMainWindow , QWidget , QVBoxLayout , QApplication , QPushButton
from PyQt5.QtCore import QTimer , QThread
import pyqtgraph as pg
from pyqtgraph import PlotWidget
import numpy as np
class StartWindow extends QMainWindow
begin
function __init__ self oscilloscope=none
begin
call __init__
set o... | from PyQt5.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QApplication, QPushButton
from PyQt5.QtCore import QTimer, QThread
import pyqtgraph as pg
from pyqtgraph import PlotWidget
import numpy as np
class StartWindow(QMainWindow):
def __init__(self, oscilloscope = None):
super().__init__()
... | Python | zaydzuhri_stack_edu_python |
class AppInitializedError extends Exception
begin
function __init__ self dErrorArguments
begin
call __init__ self string App %s already initialized % dErrorArguments
set dErrorArguments = dErrorArguments
end function
end class | class AppInitializedError(Exception):
def __init__(self, dErrorArguments):
Exception.__init__(self,"App %s already initialized" % dErrorArguments)
self.dErrorArguments = dErrorArguments | Python | zaydzuhri_stack_edu_python |
class FaseInvalida extends Exception
begin
function __init__ self
begin
call __init__ string Acho que essa fase não é valida não!
end function
end class | class FaseInvalida(Exception):
def __init__(self):
super(FaseInvalida, self).__init__(
'Acho que essa fase não é valida não!')
| Python | zaydzuhri_stack_edu_python |
function __setattr__ self *args **kwargs
begin
Ellipsis
end function | def __setattr__(self, *args, **kwargs):
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import numpy as np
from implementations import *
from proj1_helpers import *
from run_helper import *
from data_processing import *
comment Acquire data from the csv file
print string Load Data
set tuple y_data x_data ids = call load_csv_data string train.csv sub_sample=false
comment %% FE... | # -*- coding: utf-8 -*-
import numpy as np
from implementations import *
from proj1_helpers import *
from run_helper import *
from data_processing import *
# Acquire data from the csv file
print('Load Data')
y_data, x_data, ids = load_csv_data('train.csv', sub_sample=False)
#%% FEATURE BUILDING
""" Add features to t... | Python | zaydzuhri_stack_edu_python |
import unittest
function happy x
begin
set seen = list
while x != 1
begin
set y = 0
for n in range length string x
begin
set y = y + integer string x at n ^ 2
end
if y in seen
begin
return false
end
append seen y
set x = y
end
return true
end function
for x in range 1 100
begin
if call happy x
begin
print x end=string... | import unittest
def happy (x) :
seen = []
while x != 1:
y = 0
for n in range(len(str(x))):
y += int(str(x)[n])**2
if y in seen : return False
seen.append(y)
x = y
return True
for x in range (1, 100) :
if hap... | Python | zaydzuhri_stack_edu_python |
class cell
begin
set row = 0
set col = 0
set isWalled = false
set visted = false
set colorState = 0
set isStartingPoint = false
set isEndingPoint = false
function __init__ self
begin
set row = 0
set col = 0
set isWalled = false
set visted = false
set colorState = 0
set isStartingPoint = false
set isEndingPoint = false
... | class cell:
row = 0
col = 0
isWalled = False
visted = False
colorState = 0;
isStartingPoint = False
isEndingPoint = False
def __init__(self):
row = 0
col = 0
isWalled = False
visted = False
colorState = 0;
isStartingPoint... | Python | zaydzuhri_stack_edu_python |
comment STANDARD IMPLEMENTATION
set hash_table = list comprehension list for _ in range 10
function insert hash_table key value
begin
set hash_key = call hash key % length hash_table
set key_exists = false
set bucket = hash_table at hash_key
for tuple count key_value in enumerate bucket
begin
set tuple keyy val = key_... | # STANDARD IMPLEMENTATION
hash_table = [[] for _ in range(10)]
def insert(hash_table, key, value):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for count, key_value in enumerate(bucket):
keyy, val = key_value
if key == keyy:
key... | Python | zaydzuhri_stack_edu_python |
function _get_relevant_features self X
begin
if only_binary_features
begin
set feature_mask = call which_columns_are_binary X
end
else
begin
set feature_mask = ones shape at 1 dtype=bool
end
return feature_mask
end function | def _get_relevant_features(self, X):
if self.only_binary_features:
feature_mask = which_columns_are_binary(X)
else:
feature_mask = np.ones(X.shape[1], dtype=bool)
return feature_mask | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on 2017 年 9 月 9 日 @author: Nick
string 题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。 例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。 程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
set a = 1
set b = 1
set c = 1
for a in range 0 10
begin
for b in range 0 10
begin
for c in range 0 10
begin... | # -*- coding: utf-8 -*-
'''
Created on 2017 年 9 月 9 日
@author: Nick
'''
'''
题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。
例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
'''
a = 1
b = 1
c = 1
for a in range(0,10):
for b in range(0,10):
for c in range(0,10):... | Python | zaydzuhri_stack_edu_python |
function handle_error self error
begin
string Try to detect repetitive errors and sleep for a while to avoid being marked as spam
exception string try to sleep if there are repeating errors.
set error_desc = string error
set now = now
if error_desc not in error_time_log
begin
set error_time_log at error_desc = now
retu... | def handle_error(self, error):
"""
Try to detect repetitive errors and sleep for a while to avoid being marked as spam
"""
logging.exception("try to sleep if there are repeating errors.")
error_desc = str(error)
now = datetime.datetime.now()
if error_desc not in s... | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.