code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment !/usr/bin/env python
comment coding: utf-8
comment In[2]:
import numpy as np
comment . 將下兩列array存成npz檔
set array1 = array range 30
set array2 = array list 2 3 5
with open string multi_array.npz string wb as f
begin
call savez f array1 array2
end
comment In[7]:
set npzfile = load np string multi_array.npz
type n... | #!/usr/bin/env python
# coding: utf-8
# In[2]:
import numpy as np
#. 將下兩列array存成npz檔
array1 = np.array(range(30))
array2 = np.array([2,3,5])
with open('multi_array.npz', 'wb') as f:
np.savez(f, array1, array2)
# In[7]:
npzfile=np.load('multi_array.npz')
type(npzfile)
# In[8]:
npzfile
# In[14]:
p... | Python | zaydzuhri_stack_edu_python |
function predict_target self state
begin
return max flatten run target_q_values dict target_state state
end function | def predict_target(self, state):
return np.max(self.sess.run(self.target_q_values, {self.target_state: state}).flatten()) | Python | nomic_cornstack_python_v1 |
function ecg_systole ecg rpeaks t_waves_ends
begin
string Returns the localization of systoles and diastoles. Parameters ---------- ecg : list or ndarray ECG signal (preferably filtered). rpeaks : list or ndarray R peaks localization. t_waves_ends : list or ndarray T waves localization. Returns ---------- systole : nda... | def ecg_systole(ecg, rpeaks, t_waves_ends):
"""
Returns the localization of systoles and diastoles.
Parameters
----------
ecg : list or ndarray
ECG signal (preferably filtered).
rpeaks : list or ndarray
R peaks localization.
t_waves_ends : list or ndarray
T waves loc... | Python | jtatman_500k |
function sirsam_rf_conf sirsam_rf
begin
return join path sirsam_rf string sirsam_Na_randomforest.yaml
end function | def sirsam_rf_conf(sirsam_rf):
return os.path.join(sirsam_rf, 'sirsam_Na_randomforest.yaml') | Python | nomic_cornstack_python_v1 |
import sys
set a = read line stdin
set res = list comprehension integer i for i in split a if is digit i
set tuple r D x2000 = list comprehension res at i for i in tuple 0 1 2
if r >= 2 and r <= 5 and D >= 1 and D <= 100 and x2000 > D and x2000 <= 200
begin
set x2001 = r * x2000 - D
set x2002 = r * x2001 - D
set x2003 ... | import sys
a=sys.stdin.readline()
res = [int(i) for i in a.split() if i.isdigit()]
r,D,x2000 = [res[i] for i in (0,1,2)]
if (r>=2 and r<=5) and (D>=1 and D<=100) and (x2000>D and x2000<=200):
x2001=r*x2000-D
x2002=r*x2001-D
x2003=r*x2002-D
x2004=r*x2003-D
x2005=r*x2004-D
x2006=r*x2005-D
x20... | Python | zaydzuhri_stack_edu_python |
comment This program takes an Image and Secret Message from the user. It encrypts the Secret Message into the Image by altering the Image pixels.
comment The decode function, then decodes the encrypted message and prints the Secret Message
comment Importing the necessary Modules
from PIL import Image
from os.path impor... | # This program takes an Image and Secret Message from the user. It encrypts the Secret Message into the Image by altering the Image pixels.
# The decode function, then decodes the encrypted message and prints the Secret Message
# Importing the necessary Modules
from PIL import Image
from os.path import exists
... | Python | zaydzuhri_stack_edu_python |
function get_model_from_name model_name initializer outputs=none
begin
set outputs = outputs or 10
if not call is_valid_model_name model_name
begin
raise call ValueError format string Invalid model name: {} model_name
end
set bn = if expression string bn in model_name then true else false
set nmp = if expression string... | def get_model_from_name(model_name, initializer, outputs=None):
outputs = outputs or 10
if not Model.is_valid_model_name(model_name):
raise ValueError('Invalid model name: {}'.format(model_name))
bn = True if "bn" in model_name else False
nmp = True if "nmp" in model_name ... | Python | nomic_cornstack_python_v1 |
import matplotlib
call use string Agg
import matplotlib.pyplot as plt
import numpy as np
comment _BENCHMARK.txt","r")
set f = open string Loss_to_plot.txt string r
set lines = read lines f
set train_loss = list
set val_loss = list
for x in lines
begin
append train_loss split x at 0
append val_loss split x at 1
end
cl... | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
f=open("Loss_to_plot.txt","r") #_BENCHMARK.txt","r")
lines=f.readlines()
train_loss=[]
val_loss=[]
for x in lines:
train_loss.append(x.split()[0])
val_loss.append(x.split()[1])
f.close()
xrange=range(1,len(train_loss)+... | Python | zaydzuhri_stack_edu_python |
function column_range_validation_factory minim=none maxim=none ignore_missing_vals=false
begin
if minim is none
begin
if is instance maxim datetime
begin
set minim = min
end
else
begin
set minim = - 1 * maxsize - 1
end
end
if maxim is none
begin
if is instance minim datetime
begin
set maxim = max
end
else
begin
set max... | def column_range_validation_factory(minim=None, maxim=None, ignore_missing_vals=False):
if minim is None:
if isinstance(maxim, datetime):
minim = datetime.min
else:
minim = -1 * (sys.maxsize - 1)
if maxim is None:
if isinstance(minim, datetime):
maxim ... | Python | nomic_cornstack_python_v1 |
string Datasource manager module.
from datasource.creator.datasource_aggregator import DatasourceAggregator
from datasource.provider.datasource_factory import DatasourceFactory
class DatasourceManager extends object
begin
string Datasource manager class.
function __init__ self configuration_manager
begin
set properties... | '''Datasource manager module.'''
from datasource.creator.datasource_aggregator import DatasourceAggregator
from datasource.provider.datasource_factory import DatasourceFactory
class DatasourceManager(object):
'''Datasource manager class.'''
def __init__(self, configuration_manager):
properties = config... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Apr 17 18:22:10 2020 @author: TheAre
function closest_power base target
begin
string This function takes in two integers as parameter, a base and a target. It returns the smallest number that the base number has to be raised to that brings it closest to the target num... | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 17 18:22:10 2020
@author: TheAre
"""
def closest_power(base, target):
''' This function takes in two integers as parameter, a base and a target.
It returns the smallest number that the base number has to be raised to that brings it closest to the target number.... | Python | zaydzuhri_stack_edu_python |
function drop self column axis=1 inplace=true
begin
if inplace
begin
comment Checking to see if the test/train split is already in place
if test_set
begin
drop dataset column axis=axis inplace=inplace
drop dataset column axis=axis inplace=inplace
drop dataset column axis=axis inplace=inplace
end
else
begin
drop dataset... | def drop(self, column: str, axis: int = 1, inplace: bool = True):
if inplace:
if self.test_set: # Checking to see if the test/train split is already in place
self.dataset.drop(column, axis=axis, inplace=inplace)
self.test_set.dataset.drop(column, axis=axis, inplace=i... | Python | nomic_cornstack_python_v1 |
import socket
set host = string localhost
set port = 8080
set s = call socket AF_INET SOCK_STREAM
call connect tuple host port
set message = b'Hello, world'
set msg_len = length message
set header = encode string { msg_len } string utf-8
call sendall header + message
set buffer = b''
while true
begin
set data = call re... | import socket
host = 'localhost'
port = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
message = b'Hello, world'
msg_len = len(message)
header = f'{msg_len:<10}'.encode('utf-8')
s.sendall(header + message)
buffer = b''
while True:
data = s.recv(1024)
if not data:
... | Python | flytech_python_25k |
for _ in range N
begin
set tuple D C H M = split input
set tuple C H M = tuple integer C integer H integer M
if D == string B
begin
set C = C * - 1
end
set tuple h_diff m = divide mod M + C 60
set h = H + h_diff % 24
print h m
end | for _ in range(N):
D, C, H, M = input().split()
C, H, M = int(C), int(H), int(M)
if D == 'B':
C *= -1
h_diff, m = divmod(M + C, 60)
h = (H + h_diff) % 24
print(h, m)
| Python | zaydzuhri_stack_edu_python |
from itertools import combinations
class Board
begin
function __init__ self n w
begin
set n = n
set w = w
set board = list
for i in range 0 n
begin
append board list string O * n
end
end function
function isValid self r c
begin
if 0 <= r and r < n and 0 <= c and c < n
begin
return true
end
return false
end function
fu... | from itertools import combinations
class Board:
def __init__(self, n, w):
self.n = n
self.w = w
self.board = []
for i in range (0, n):
self.board.append(['O']*n)
def isValid(self, r, c):
if 0<=r and r<self.n and 0<=c and c<self.n:
return True
... | Python | zaydzuhri_stack_edu_python |
function get_remote_username self
begin
raise call NotImplementedError string Abstract method `Transport.get_remote_username()` called - this should have been defined in a derived class.
end function | def get_remote_username(self):
raise NotImplementedError(
"Abstract method `Transport.get_remote_username()` called - "
"this should have been defined in a derived class.") | Python | nomic_cornstack_python_v1 |
function get_user_by_username cls username
begin
return call frist
end function | def get_user_by_username (cls, username: str) -> object:
return cls.query.filter_by(username=username).frist() | Python | nomic_cornstack_python_v1 |
comment panlindrome
comment n=123
comment re=321
comment n=rev #panlindrom
comment n!=rev #not panlindrom
set n = integer input
set t = n
set rev = 0
while n
begin
set r = n % 10
set rev = rev * 10 + r
set n = n // 10
end
if t == rev
begin
print string panlindrome
end
else
begin
print string not panlindrome
end | #panlindrome
#n=123
#re=321
#n=rev #panlindrom
#n!=rev #not panlindrom
n=int(input())
t=n
rev=0
while(n):
r=n%10
rev=rev*10+r
n=n//10
if t==rev:
print("panlindrome")
else:
print(" not panlindrome")
| Python | zaydzuhri_stack_edu_python |
function main
begin
set ans = 0
for i in range 1 1000
begin
if i % 3 == 0 or i % 5 == 0
begin
set ans = ans + i
end
end
print ans
end function
call main | def main():
ans=0
for i in range (1,1000):
if i%3==0 or i%5==0:
ans=ans+i
print(ans)
main()
| Python | zaydzuhri_stack_edu_python |
function stop self
begin
move 0 0
end function | def stop(self):
self.move(0, 0) | Python | nomic_cornstack_python_v1 |
function SetReferenceImage self _arg
begin
return call itkGenerateImageSourceIUC3_SetReferenceImage self _arg
end function | def SetReferenceImage(self, _arg: 'itkImageBase3') -> "void":
return _itkGenerateImageSourcePython.itkGenerateImageSourceIUC3_SetReferenceImage(self, _arg) | Python | nomic_cornstack_python_v1 |
import numpy as np
class Shape extends object
begin
function __init__ self box rgb
begin
set box = box
set rgb = rgb
end function
function paint self x H W
begin
raise call RuntimeError string abstract not implemented
end function
function to_gt self
begin
set label = 0
if __class__ == Circle
begin
set label = 1
end
if... | import numpy as np
class Shape(object):
def __init__(self, box, rgb):
self.box = box
self.rgb = rgb
def paint(self, x, H, W):
raise RuntimeError("abstract not implemented")
def to_gt(self):
label = 0
if self.__class__ == Circle:
label = 1
if sel... | Python | zaydzuhri_stack_edu_python |
from random import randint
class Node
begin
function __init__ self value=none
begin
set data = value
set next = none
end function
end class
class LinkedList
begin
function __init__ self
begin
set head = call Node
end function
function insert self value
begin
set temp = head
while next is not none
begin
set temp = next
... | from random import randint
class Node:
def __init__(self, value=None):
self.data = value
self.next = None
class LinkedList:
def __init__(self):
self.head = Node()
def insert(self, value):
temp = self.head
while temp.next is not None:
temp = temp.nex... | Python | zaydzuhri_stack_edu_python |
function acquire_data_for_interval_in_seconds self duration
begin
comment create acquisition thread
set data_acq_thread = thread target=start_acquisition
set daemon = true
start data_acq_thread
comment create subscriber listening thread
set sub_thread = thread target=start_listening
set daemon = true
start sub_thread
s... | def acquire_data_for_interval_in_seconds(self, duration):
# create acquisition thread
data_acq_thread = threading.Thread(target=self.data_acquisition.start_acquisition)
data_acq_thread.daemon = True
data_acq_thread.start()
# create subscriber listening thread
sub_thread ... | Python | nomic_cornstack_python_v1 |
function _map_listparameter value separator=string , dtype=none
begin
comment set function name (cannot break here --> no access to inputs)
set func_name = call display_func string _map_listparameter __NAME__
comment return list if already a list
if is instance value tuple list ndarray
begin
return list value
end
comme... | def _map_listparameter(value: Union[str, list], separator: str = ',',
dtype: Union[None, Type] = None) -> List[object]:
# set function name (cannot break here --> no access to inputs)
func_name = display_func('_map_listparameter', __NAME__)
# return list if already a list
if isins... | Python | nomic_cornstack_python_v1 |
function floyd_warshall_predecessor_and_distance G weight=string weight
begin
from collections import defaultdict
comment dictionary-of-dictionaries representation for dist and pred
comment use some defaultdict magick here
comment for dist the default is the floating point inf value
set dist = default dictionary lambda... | def floyd_warshall_predecessor_and_distance(G, weight='weight'):
from collections import defaultdict
# dictionary-of-dictionaries representation for dist and pred
# use some defaultdict magick here
# for dist the default is the floating point inf value
dist = defaultdict(lambda: defaultdict(lambda: ... | Python | nomic_cornstack_python_v1 |
for tuple key val in items dictionary
begin
print string { key } : { val }
end | for key,val in dictionary.items():
print(f"{key}: {val}") | Python | jtatman_500k |
function dfp x t
begin
comment ratio of gravity acceleration to length of pendulum
set k = 1.0
comment damping coefficient
set d = 0.1
comment amplitude of forcing
set A = 1.5
set t = decimal t
set x = array x
if shape != tuple 2
begin
raise call ValueError string The state of the pendulum is described by a vector with... | def dfp(x, t):
k = 1. #ratio of gravity acceleration to length of pendulum
d = 0.1 #damping coefficient
A = 1.5 #amplitude of forcing
t = float(t)
x = array(x)
if x.shape != (2,):
raise ValueError("The state of the pendulum is described by a vector with two elements")
return array([... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function maxProfit self prices fee
begin
string :type prices: List[int] :type fee: int :rtype: int convert from:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/108871/2-solutions-2-states-DP-solutions-clear-explanation!
set days = length pri... | class Solution(object):
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
convert from:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/108871/2-solutions-2-states-DP-solutions-clear-explanation!... | Python | zaydzuhri_stack_edu_python |
import json , time , datetime , decimal , fractions
from config import *
function set_headers allow_cache=false
begin
call header string Content-Type string application/json
if not allow_cache
begin
call header string Cache-Control string no-store, no-cache, must-revalidate
call header string Cache-Control string post-... | import json, time, datetime, decimal, fractions
from config import *
def set_headers(allow_cache=False):
web.header('Content-Type', 'application/json')
if not allow_cache:
web.header('Cache-Control', 'no-store, no-cache, must-revalidate')
web.header('Cache-Control', 'post-check=0, pre-check=0',... | Python | zaydzuhri_stack_edu_python |
if t and r and u and e and l and o and v and e
begin
set ans = string t + r + u + e + string l + o + v + e
end
print ans | if t and r and u and e and l and o and v and e:
ans = str(t+r+u+e) + str(l+o+v+e)
print(ans) | Python | zaydzuhri_stack_edu_python |
from numpy import pi , random , vectorize
from math import sin , sqrt
import numpy as np
import matplotlib.pyplot as plt
function generate_random_points lo hi num_samples si
begin
return uniform lo hi size=tuple num_samples si
end function
function estimate_expectance f points
begin
return mean f dist sum axis=1 axis=0... | from numpy import pi, random, vectorize
from math import sin, sqrt
import numpy as np
import matplotlib.pyplot as plt
def generate_random_points(lo, hi, num_samples, si):
return np.random.uniform(lo, hi, size = (num_samples, si))
def estimate_expectance(f, points):
return f(points.sum(axis=1)).mean(axis=0);
... | Python | zaydzuhri_stack_edu_python |
class Accesscard
begin
string This class models an access card which can be used to check whether a card should open a particular door or not.
function __init__ self id name
begin
string Constructor, creates a new object that has no access rights. :param id: str, card holders personal id :param name: str, card holders ... | class Accesscard:
"""
This class models an access card which can be used to check
whether a card should open a particular door or not.
"""
def __init__(self, id, name):
"""
Constructor, creates a new object that has no access rights.
:param id: str, card holders personal id... | Python | zaydzuhri_stack_edu_python |
import sys
append path string /home/tvromen/research
from Common.Utils import IdAssigner , print_flush
from Common import RatingsData
import numpy as np
import scipy.io
function load_ml_100k path verbose=true
begin
if verbose
begin
call print_flush string Loading MovieLens 100k ratings...
end
with open path as f
begin
... | import sys
sys.path.append('/home/tvromen/research')
from Common.Utils import IdAssigner, print_flush
from Common import RatingsData
import numpy as np
import scipy.io
def load_ml_100k(path, verbose=True):
if verbose:
print_flush('Loading MovieLens 100k ratings...')
with open(path) as f:
if ve... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
import random
from scipy.stats import norm
import matplotlib.pyplot as plt
from scipy.stats.kde import gaussian_kde
from itertools import combinations
from scipy.spatial import distance
set data = read csv string ./bank.csv sep=string ; header=0
comment 2 Calculate mean, standart ... | import pandas as pd
import numpy as np
import random
from scipy.stats import norm
import matplotlib.pyplot as plt
from scipy.stats.kde import gaussian_kde
from itertools import combinations
from scipy.spatial import distance
data = pd.read_csv("./bank.csv", sep=r';', header=0)
##2 Calculate mean, standart deviati... | Python | zaydzuhri_stack_edu_python |
function cost self src_state dest_state
begin
set src_elevation = call elevation position at 0 position at 1
set dest_elevation = call elevation position at 0 position at 1
comment determine if the move is uphill or downhill and return the according cost calculation
if src_elevation > dest_elevation
begin
comment move ... | def cost(self, src_state, dest_state):
src_elevation = self.environment.elevation(src_state.position[0], src_state.position[1])
dest_elevation = self.environment.elevation(dest_state.position[0], dest_state.position[1])
# determine if the move is uphill or downhill and return the according cost... | Python | nomic_cornstack_python_v1 |
function _matching_jobs buildername all_jobs
begin
debug string Find jobs matching '%s' % buildername
set matching_jobs = list
for j in all_jobs
begin
if j at string buildername == buildername
begin
append matching_jobs j
end
end
debug string We have found %d job(s) of '%s'. % tuple length matching_jobs buildername
re... | def _matching_jobs(buildername, all_jobs):
LOG.debug("Find jobs matching '%s'" % buildername)
matching_jobs = []
for j in all_jobs:
if j["buildername"] == buildername:
matching_jobs.append(j)
LOG.debug("We have found %d job(s) of '%s'." %
(len(matching_jobs), builderna... | Python | nomic_cornstack_python_v1 |
comment ================================================================
comment Editor : Pycharm
comment File name : train
comment Author : HuangWei
comment Created date: 2020-12-23 14:51
comment Email : 446296992@qq.com
comment Description : 开启训练
comment ( ˶˙º˙˶ )୨ Have Fun!!!
comment ================================... | # ================================================================
#
# Editor : Pycharm
# File name : train
# Author : HuangWei
# Created date: 2020-12-23 14:51
# Email : 446296992@qq.com
# Description : 开启训练
#
# ( ˶˙º˙˶ )୨ Have Fun!!!
# =============================================... | Python | zaydzuhri_stack_edu_python |
set word = string App
set sentence = string This is our first + word
print sentence | word = "App"
sentence = "This is our first " + word
print(sentence)
| Python | zaydzuhri_stack_edu_python |
function pass_validator password
begin
set is_password_valid = true
set counter_digits = 0
for digits in password
begin
if call isnumeric
begin
set counter_digits = counter_digits + 1
end
end
if not 6 <= length password <= 10
begin
set is_password_valid = false
print string Password must be between 6 and 10 characters
... | def pass_validator(password):
is_password_valid = True
counter_digits = 0
for digits in password:
if digits.isnumeric():
counter_digits += 1
if not 6 <= len(password) <= 10:
is_password_valid = False
print("Password must be between 6 and 10 characters")
if not pas... | Python | zaydzuhri_stack_edu_python |
from typing import List
from fastapi import FastAPI , Depends , HTTPException
from sqlalchemy.orm import Session
from database import SessionLocal , engine
import crud
import models
import schemas
call create_all bind=engine
set app = call FastAPI
function get_db
begin
set db = call SessionLocal
try
begin
yield db
end
... | from typing import List
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from database import SessionLocal, engine
import crud
import models
import schemas
models.Base.metadata.create_all(bind=engine)
app=FastAPI()
def get_db():
db=SessionLocal()
try:
yield db
... | Python | zaydzuhri_stack_edu_python |
function action_name self
begin
return get _values string action_name
end function | def action_name(self) -> typing.Optional[str]:
return self._values.get("action_name") | Python | nomic_cornstack_python_v1 |
function priority self
begin
return 5
end function | def priority(self):
return 5 | Python | nomic_cornstack_python_v1 |
class DuplicatedUser extends Exception
begin
set username : str = none
function __init__ self username
begin
set username = username
call __init__ string has %s % username
end function
end class
class NoPermission extends Exception
begin
pass
end class
class NotFound extends Exception
begin
pass
end class | class DuplicatedUser(Exception):
username: str = None
def __init__(self, username):
self.username = username
super().__init__("has %s" % username)
class NoPermission(Exception):
pass
class NotFound(Exception):
pass
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Mon Apr 30 09:34:48 2018 @author: eareyanv All operations related to constructing BRGs are here. Graphs are all implemented using the networkx library.
import networkx as nx
import matplotlib.pyplot as plt
class BRG
begin
decorator staticmeth... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 30 09:34:48 2018
@author: eareyanv
All operations related to constructing BRGs are here.
Graphs are all implemented using the networkx library.
"""
import networkx as nx
import matplotlib.pyplot as plt
class BRG:
@staticmethod
... | Python | zaydzuhri_stack_edu_python |
comment coding=utf8
comment 题目: 给定一个m*n的方格, 机器人要从左上角位置到达右下角位置,有多少种不同的走法
comment 思路: 动态规划, dp[i][j] = dp[i-1][j] + dp[i][j-1], 其中dp[i][j]表示到达i,j位置有多少种不同的走法
class Solution extends object
begin
function uniquePaths self m n
begin
string :type m: int :type n: int :rtype: int
set dp = list comprehension list 0 * n for _ in ... | # coding=utf8
# 题目: 给定一个m*n的方格, 机器人要从左上角位置到达右下角位置,有多少种不同的走法
# 思路: 动态规划, dp[i][j] = dp[i-1][j] + dp[i][j-1], 其中dp[i][j]表示到达i,j位置有多少种不同的走法
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[0] * n for _ in range(m)... | Python | zaydzuhri_stack_edu_python |
function fibonacci n
begin
if n <= 1
begin
return n
end
else
begin
return call fibonacci n - 1 + call fibonacci n - 2
end
end function
for i in range 10
begin
print call fibonacci i
end | def fibonacci(n):
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
for i in range(10):
print(fibonacci(i)) | Python | iamtarun_python_18k_alpaca |
import os
comment Create a list of files from the current directory who's last 4 characters
comment as lowercase are either '.jpg' or '.png'
set files = list comprehension f for f in list directory string . if lower f at slice - 4 : : in string .jpg
set DRYRUN = true
for tuple index filename in enumerate files
begin
s... | import os
# Create a list of files from the current directory who's last 4 characters
# as lowercase are either '.jpg' or '.png'
files = [ f for f in os.listdir('.') if f[-4:].lower() in ('.jpg') ]
DRYRUN=True
for (index,filename) in enumerate(files):
extension = os.path.splitext(filename)[1]
newname = "image_%d... | Python | zaydzuhri_stack_edu_python |
function group_text_into_sentences raw_text
begin
set grouped_by_sentence = list
for tuple _ g in group by itertools call split_lines_into_token_tag raw_text lambda x -> x == string
begin
comment Store group iterator as a list
append grouped_by_sentence list g
end
return list comprehension g for g in grouped_by_senten... | def group_text_into_sentences(raw_text):
grouped_by_sentence = []
for _, g in itertools.groupby(split_lines_into_token_tag(raw_text), lambda x: x == "\n"):
grouped_by_sentence.append(list(g)) # Store group iterator as a list
return [g for g in grouped_by_sentence if g != ["\n"]] | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
import numpy as np
import random
import time
from simulator import Sim
from dqn import DQN
call DEFINE_boolean string train false string 학습모드. 게임을 화면에 보여주지 않습니다.
set FLAGS = FLAGS
class agent_car
begin
function __init__ self
begin
set target_pos = dict string m_ row - 1 ; string m_col - 1
set ob... | import tensorflow as tf
import numpy as np
import random
import time
from simulator import Sim
from dqn import DQN
tf.app.flags.DEFINE_boolean("train", False, "학습모드. 게임을 화면에 보여주지 않습니다.")
FLAGS = tf.app.flags.FLAGS
class agent_car :
def __init__(self) :
self.target_pos = {'m_ row' : -1, 'm_col' : -1}
... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function convert self s numRows
begin
string :type s: str :type numRows: int :rtype: str
if length s < 2 or numRows == 1
begin
return s
end
set jump1 = numRows - 1 * 2
set jump2 = 0
set output = s at slice 0 : : jump1
set jump1 = jump1 - 2
set jump2 = jump2 + 2
set i = 1
while jump1 != 0
begin
set... | class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if len(s) < 2 or numRows == 1:
return s
jump1 = (numRows - 1) * 2
jump2 = 0
output = s[0::jump1]
jump1 -= 2
jump2 += ... | Python | zaydzuhri_stack_edu_python |
function download_link self value
begin
if call _validate_type basestring value string download_link
begin
set _release at string download_link = lower value
end
end function | def download_link(self, value):
if self._validate_type(basestring, value, 'download_link'):
self._release['download_link'] = value.lower() | Python | nomic_cornstack_python_v1 |
function MutateRow self request context
begin
call code UNIMPLEMENTED
end function | def MutateRow(self, request, context):
context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) | Python | nomic_cornstack_python_v1 |
from hw11 import greedy
import math
import time
from queue import Queue
from load_data import load_data
import numpy as np
set mat10 = call load_data string ./TSP10cities.tsp
set mat100 = call load_data string ./TSP100cities.tsp
set dist = mat10
set CityNum = shape at 0
set Dist = dist
class Node
begin
function __init_... | from hw11 import greedy
import math
import time
from queue import Queue
from load_data import load_data
import numpy as np
mat10 = load_data("./TSP10cities.tsp")
mat100 = load_data("./TSP100cities.tsp")
dist = mat10
CityNum = dist.shape[0]
Dist = dist
class Node:
def __init__(self, citynum):
self.visited ... | Python | zaydzuhri_stack_edu_python |
function setup_call_account config
begin
set kwargs = dict string insid call get_callaccnt_name config at string shortName CALLACCNT_GENERAL ; string start_date config at string startDate ; string rate_dict dict string type string float ; string ref config at string generalCallAccountRateIndex ; string spread config at... | def setup_call_account(config):
kwargs = {
'insid': get_callaccnt_name(config['shortName'], CALLACCNT_GENERAL),
'start_date': config['startDate'],
'rate_dict': {'type': 'float',
'ref': config['generalCallAccountRateIndex'],
'spread': config['genera... | Python | nomic_cornstack_python_v1 |
string Day 08 Answers
from itertools import dropwhile
function decode_layers digits width=25 height=6
begin
string Each image actually consists of a series of identically-sized layers that are filled in this way. So, the first digit corresponds to the top-left pixel of the first layer, the second digit corresponds to t... | """Day 08 Answers"""
from itertools import dropwhile
def decode_layers(digits: list, width=25, height=6):
"""Each image actually consists of a series of identically-sized layers that are filled in this way. So, the first digit corresponds to the top-left pixel of the first layer, the second digit corresponds to t... | Python | zaydzuhri_stack_edu_python |
import sqlite3
import time
class Book
begin
function __init__ self name writer publisher type publish
begin
set name = name
set writer = writer
set publisher = publisher
set type = type
set publish = publish
end function
function __str__ self
begin
return format string kitap ismi: {} /n yazar ismi: {} /n yayinci: {} /n... | import sqlite3
import time
class Book:
def __init__(self, name, writer, publisher, type, publish):
self.name = name
self.writer = writer
self.publisher = publisher
self.type = type
self.publish = publish
def __str__(self):
return 'kitap ismi: {} /n yazar ismi: {... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function findLUSlength self strs
begin
from collections import Counter
function check part whole
begin
set idx = 0
for ltr in part
begin
set lw = length whole
set inthere = false
while idx < lw
begin
if ltr == whole at idx
begin
set inthere = true
set idx = idx + 1
break
end
else
begin
set idx = id... | class Solution:
def findLUSlength(self, strs: List[str]) -> int:
from collections import Counter
def check(part, whole):
idx = 0
for ltr in part:
lw = len(whole)
inthere = False
while idx < lw:
if lt... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import argparse
import calculator
function parse_arguments
begin
string This method will parse arguments and returns the arguments
global args
set parser = call ArgumentParser description=string Argument parser for accepting two numbers to perform addtions
call add_argument string number ty... | #!/usr/bin/env python
import argparse
import calculator
def parse_arguments():
"""
This method will parse arguments and returns the arguments
"""
global args
parser = argparse.ArgumentParser(description='Argument parser for accepting two numbers to perform addtions')
parser.add_argument("numbe... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
comment cv2.CvFeatureParams_HAAR()
function acimage image type
begin
comment image=cv2.imread("2.png",flags=0)
comment cv2.waitKey()
comment cv2.destroyAllWindows(0)
comment image=np.array(image)
comment print(image.shape)
set w = shape at 0
set h = shape at 1
comment 生成不带旋转的积分图像 type=0
co... | import cv2
import numpy as np
#cv2.CvFeatureParams_HAAR()
def acimage(image,type):
#image=cv2.imread("2.png",flags=0)
#cv2.waitKey()
#cv2.destroyAllWindows(0)
#image=np.array(image)
#print(image.shape)
w=image.shape[0]
h=image.shape[1]
#生成不带旋转的积分图像 type=0
#生成带45角度旋转的积分图像 type=1
... | Python | zaydzuhri_stack_edu_python |
function verify_orders self trade
begin
if orderId <= 0 and orderType not in tuple string STP string TRAIL and status in list string PreSubmitted string Inactive
begin
debug string manual trade reporting event attached
clear filledEvent
clear cancelledEvent
clear commissionReportEvent
clear modifyEvent
call attach_even... | def verify_orders(self, trade: Trade) -> None:
if ((trade.order.orderId <= 0)
and (trade.order.orderType not in ('STP', 'TRAIL'))
and (trade.orderStatus.status in ['PreSubmitted', 'Inactive'])):
log.debug(f'manual trade reporting event attached')
trade.filledE... | Python | nomic_cornstack_python_v1 |
function error_feeds self
begin
set feeds = list
for c in categories
begin
for f in error_feeds
begin
append feeds f
end
end
return feeds
end function | def error_feeds(self) -> List[FeedResult]:
feeds = []
for c in self.categories:
for f in c.error_feeds:
feeds.append(f)
return feeds | Python | nomic_cornstack_python_v1 |
function get_section self title
begin
for section in sections
begin
if lower title == lower title
begin
return section
end
end
set section = call ReleaseSection title=title
append sections section
return section
end function | def get_section(self, title):
for section in self.sections:
if section.title.lower() == title.lower():
return section
section = ReleaseSection(title=title)
self.sections.append(section)
return section | Python | nomic_cornstack_python_v1 |
function deploy_cluster_client_config self cluster_name
begin
return json call _post endpoint=format string {}/clusters/{}/commands/deployClientConfig api_version cluster_name
end function | def deploy_cluster_client_config(self, cluster_name):
return self._post(endpoint=('{}/clusters/{}/commands/'
'deployClientConfig').format(self.api_version,
cluster_name)).json() | Python | nomic_cornstack_python_v1 |
function log *message
begin
set realMessage = string
for i in message
begin
try
begin
set realMessage = realMessage + string + string encode i string utf-8 + string
end
except any
begin
set realMessage = realMessage + string + encode string i string utf-8 + string
end
end
debug realMessage
end function | def log(*message):
realMessage = ''
for i in message:
try:
realMessage = realMessage + ' ' + str(i.encode("utf-8"))+' '
except:
realMessage = realMessage + ' ' + str(i).encode("utf-8")+' '
my_logger.debug(realMessage) | Python | nomic_cornstack_python_v1 |
from random import randint
class Environment
begin
function __init__ self
begin
comment define the boundary of the Environment
set x_limit = 5
set y_limit = 5
comment define the action space
set action_space = list string up string left string down string right
comment define a mapping from state to reward
comment use ... | from random import randint
class Environment:
def __init__(self):
# define the boundary of the Environment
self.x_limit = 5
self.y_limit = 5
# define the action space
self.action_space = ["up", "left", "down", "right"]
# define a mapping from state to reward
... | Python | zaydzuhri_stack_edu_python |
function update_forms_containing_this_form_as_morpheme form change=string create previous_version=none
begin
if call is_lexical form
begin
comment Here we construct the query to get all forms that may have been affected
comment by the change to the lexical item (i.e., form).
set morpheme_delimiters = call get_morpheme_... | def update_forms_containing_this_form_as_morpheme(form, change='create', previous_version=None):
if h.is_lexical(form):
# Here we construct the query to get all forms that may have been affected
# by the change to the lexical item (i.e., form).
morpheme_delimiters = h.get_morpheme_delimiter... | Python | nomic_cornstack_python_v1 |
function lista_conx_maliciosas self
begin
return list comprehension x for x in _todas if estado is MALICIOSA
end function | def lista_conx_maliciosas(self):
return [x for x in self._todas if x.estado is Estado.MALICIOSA] | Python | nomic_cornstack_python_v1 |
function test_login_logout client test_db
begin
set rv = call login client config at string USERNAME config at string PASSWORD
assert b'You were logged in' in data
set rv = call logout client
assert b'You were logged out' in data
set rv = call login client config at string USERNAME + string x config at string PASSWORD
... | def test_login_logout(client, test_db):
rv = login(client, app.config["USERNAME"], app.config["PASSWORD"])
assert b"You were logged in" in rv.data
rv = logout(client)
assert b"You were logged out" in rv.data
rv = login(client, app.config["USERNAME"] + "x", app.config["PASSWORD"])
assert b"Invali... | Python | nomic_cornstack_python_v1 |
function fetch_page url params=none rettype=string text MAX_RETRIES=3 MAX_TIMEOUT=5 RETRY_WAIT_TIME=0.1
begin
assert is instance url str msg string URL is not a string!
assert rettype in list string text string json
for i in range MAX_RETRIES
begin
try
begin
set resp = get requests url params=params timeout=MAX_TIMEOUT... | def fetch_page(url, params = None, rettype = "text",
MAX_RETRIES = 3, MAX_TIMEOUT = 5, RETRY_WAIT_TIME = 0.1):
assert isinstance(url, str), "URL is not a string!"
assert rettype in ["text", "json"]
for i in range(MAX_RETRIES):
try:
resp = requests.get(url, params = params, timeout =... | Python | nomic_cornstack_python_v1 |
function main
begin
set result_part_one = call number_spoken_at puzzle_input at 0 2020
print string Part one : the 2020th number spoken is { result_part_one }
set result_part_two = call number_spoken_at puzzle_input at 0 30000000
print string Part two : the 30000000th number spoken is { result_part_two } (with brute fo... | def main():
result_part_one = number_spoken_at(puzzle_input[0], 2020)
print(f"Part one : the 2020th number spoken is {result_part_one}")
result_part_two = number_spoken_at(puzzle_input[0], 30000000)
print(f"Part two : the 30000000th number spoken is {result_part_two} (with brute force :))")
def number... | Python | zaydzuhri_stack_edu_python |
function thermalization_analysis
begin
set verbose = true
set run_pre_analysis = true
set mark_every = 50
comment Skip every 100 points with 2000 therm-steps!!
set mc_cutoff = - 1
set batch_folder = call check_relative_path string data/thermalization_data
set base_figure_folder = call check_relative_path string figures... | def thermalization_analysis():
verbose = True
run_pre_analysis = True
mark_every = 50
mc_cutoff = -1 # Skip every 100 points with 2000 therm-steps!!
batch_folder = check_relative_path("data/thermalization_data")
base_figure_folder = check_relative_path("figures/")
base_figure_folder = os.pa... | Python | nomic_cornstack_python_v1 |
function untag_resource resourceArn=none tagKeys=none
begin
pass
end function | def untag_resource(resourceArn=None, tagKeys=None):
pass | Python | nomic_cornstack_python_v1 |
comment !/user/bin/env python
comment -*- coding:utf-8 -*-
comment kiki 210507
comment 问卷调查,计数排序
import sys
set nums = read lines stdin
set n = integer strip nums at 0
set temp = list 0 * 1001
set ans = list
for i in range 1 length nums
begin
set num = integer strip nums at i
if n > 0
begin
set n = n - 1
end
else
begi... | # !/user/bin/env python
# -*- coding:utf-8 -*-
# kiki 210507
# 问卷调查,计数排序
import sys
nums = sys.stdin.readlines()
n = int(nums[0].strip())
temp = [0]*1001
ans = []
for i in range(1,len(nums)):
num = int(nums[i].strip())
if n > 0:
n -= 1
else:
n = num
ans.append(temp)
temp = [0... | Python | zaydzuhri_stack_edu_python |
function save_user_data bot update
begin
info call log_msg update
set user = call chosen_owns update
if not updated
begin
set text = string В базу ДОДАНО сусіда:
end
else
begin
set text = string В базі ОНОВЛЕНО сусіда:
end
if data == string _apart_reject
begin
set user_mode = get Show user_id=id
set msg_apart_mode = fa... | def save_user_data(bot, update):
log.info(log_msg(update))
user = chosen_owns(update)
if not user.updated:
text = 'В базу ДОДАНО сусіда:\n'
else:
text = 'В базі ОНОВЛЕНО сусіда:\n'
if update.callback_query.data == '_apart_reject':
user_mode = Show.get(user_id=update.effectiv... | Python | nomic_cornstack_python_v1 |
function calcPattern N Y
begin
for i in range 0 N + 1
begin
for j in range 0 N + 1 - i
begin
if i == Y - 1000 * N - 4000 * j / 9000
begin
if N - i - j >= 0
begin
return string i + string + string j + string + string N - i - j
end
end
end
end
return string -1 -1 -1
end function
set tuple n y = map int split input
prin... | def calcPattern(N, Y):
for i in range(0, N+1):
for j in range(0, N+1-i):
if i == ((Y - 1000*N - 4000*j) / 9000):
if (N-i-j) >= 0: return (str(i) + " " + str(j) + " " +str(N-i-j))
return ("-1 -1 -1")
n,y = map(int, input().split())
print(calcPattern(n,y)) | Python | zaydzuhri_stack_edu_python |
function lookup_parameter self parameter_name
begin
return call lookup_parameter parameter_name
end function | def lookup_parameter(self, parameter_name):
return self.context.lookup_parameter(parameter_name) | Python | nomic_cornstack_python_v1 |
class Blocker
begin
string BLOCKER TOOL TO MAKE LEMMINGS TRANSFORM AND MAKE OTHER LEMMINGS CHANGE DIRECTION
comment Note: since, at the moment only one lemming is technically implemented, the only way to make
comment it change direction is activating god mode and placing platforms on the sides
comment of the lemming
fu... | class Blocker:
""" BLOCKER TOOL TO MAKE LEMMINGS TRANSFORM AND MAKE OTHER LEMMINGS
CHANGE DIRECTION"""
# Note: since, at the moment only one lemming is technically implemented, the only way to make
# it change direction is activating god mode and placing platforms on the sides
# of the lemming... | Python | zaydzuhri_stack_edu_python |
function show self id
begin
return call _get url=format string {0}notification_channels/{1}.json URL id headers=headers
end function | def show(self, id):
return self._get(
url='{0}notification_channels/{1}.json'.format(self.URL, id),
headers=self.headers,
) | Python | nomic_cornstack_python_v1 |
set s1 = input
set s2 = input
set k = integer input
if length s1 > length s2
begin
set d = list comprehension i for i in range min length s1 length s2 if s1 at i != s2 at i
set count = length s1 at slice length s2 : :
set minC = count + length d * 2
end
else
if length s1 < length s2
begin
set d = list comprehension i ... | s1 = input()
s2 = input()
k = int(input())
if(len(s1) > len(s2)):
d = [i for i in range(min(len(s1), len(s2))) if s1[i] != s2[i]]
count = len(s1[len(s2):])
minC = count + (len(d) * 2)
elif(len(s1) < len(s2)):
d = [i for i in range(min(len(s1), len(s2))) if s1[i] != s2[i]]
count = len(s2[len(s1):])
... | Python | zaydzuhri_stack_edu_python |
set s = string Python - 中文
comment Python - 中文
print s
set b = encode s string utf-8
comment b'Python - \xe4\xb8\xad\xe6\x96\x87'
print b
comment Python - 中文
print decode b string utf-8 | s = 'Python - 中文'
print(s) # Python - 中文
b = s.encode('utf-8')
print(b) # b'Python - \xe4\xb8\xad\xe6\x96\x87'
print(b.decode('utf-8')) # Python - 中文 | Python | zaydzuhri_stack_edu_python |
function find_entity self x
begin
set qstr = prefixes + format string SELECT ?x WHERE {{ ?x rn:hasName "{0}" . }} x
set res = query graph qstr
if list res
begin
set en = call toPython
return en
end
else
begin
return none
end
end function | def find_entity(self, x):
qstr = self.prefixes + """
SELECT ?x WHERE {{
?x rn:hasName "{0}" .
}}
""".format(x)
res = self.graph.query(qstr)
if list(res):
en = list(res)[0][0].toPython()
return en
else:
... | Python | nomic_cornstack_python_v1 |
function findPath self source destination vertices edges
begin
set connectedNodes = list comprehension vertices at index for tuple index edge in enumerate edges at source at string index if edge == 1
for node in connectedNodes
begin
set childConnectedNodes = list comprehension vertices at index for tuple index edge in ... | def findPath(self, source, destination, vertices, edges):
connectedNodes = [vertices[index] for index, edge in enumerate(edges[source['index']]) if edge == 1]
for node in connectedNodes:
childConnectedNodes = [vertices[index] for index, edge in enumerate(edges[node['index']]) if edge == 1]
... | Python | nomic_cornstack_python_v1 |
function update_meterstate self query_result
begin
if id != query_result at string deviceId or query_result at string state at string @type != string powerMeterState
begin
error string Wrong device id %s or state type %s % tuple query_result at string deviceId query_result at string state at string @type
return false
e... | def update_meterstate(self, query_result):
if self.id != query_result['deviceId'] or query_result['state']['@type'] != "powerMeterState":
_LOGGER.error("Wrong device id %s or state type %s" % (
query_result['deviceId'], query_result['state']['@type']))
return False
... | Python | nomic_cornstack_python_v1 |
function addNote self note
begin
if type note is str
begin
if note == string sample
begin
set note = call getNotes top=1
return note at 0
end
else
begin
raise exception string note must be a dictionary with valid fields, or the string 'sample' to request a sample object
end
end
else
if type note is dict
begin
if get no... | def addNote(self, note):
if type(note) is str:
if note == 'sample':
note = self.getNotes(top=1)
return note[0]
else:
raise Exception('note must be a dictionary with valid fields, or the string \'sample\' to request a sample object')
... | Python | nomic_cornstack_python_v1 |
function test_get_public_key self
begin
set query_string = list tuple string agentid string false tuple string companyid string false
set response = open string /v0_9_1/PublicKeys method=string GET query_string=query_string
call assert200 response string Response body is : + decode data string utf-8
end function | def test_get_public_key(self):
query_string = [('agentid', 'false'),
('companyid', 'false')]
response = self.client.open(
'/v0_9_1/PublicKeys',
method='GET',
query_string=query_string)
self.assert200(response,
'Re... | Python | nomic_cornstack_python_v1 |
function generate_model self
begin
set rootpath = string c:\Users\Gamelab\Desktop\RT\Others\Thesis\Thesis_coding\ABM\
set df = read csv rootpath + string data\subset_initialized_latlonvalues.csv
set df = drop df columns=string Unnamed: 0
set households_in_block = dict
set household_ids_in_block = dict
comment holds a... | def generate_model(self):
rootpath = 'c:\\Users\\Gamelab\\Desktop\\RT\\Others\\Thesis\\Thesis_coding\\ABM\\'
df = pd.read_csv(rootpath+'data\\subset_initialized_latlonvalues.csv')
df = df.drop(columns='Unnamed: 0')
households_in_block = {}
household_ids_in_block = {}
... | Python | nomic_cornstack_python_v1 |
function load_from_csv path delimiter=string ,
begin
return read csv path encoding=string ISO-8859-1 dtype=object
end function | def load_from_csv(path, delimiter=','):
return pd.read_csv(path,encoding = "ISO-8859-1",dtype=object) | Python | nomic_cornstack_python_v1 |
function __init__ self regex_list
begin
set regex_filters : List at Pattern at str = list
for regex_str in regex_list
begin
try
begin
append regex_filters compile regex_str IGNORECASE
end
except error
begin
warning string Failed to parse regex: {} regex_str
end
end
end function | def __init__(self, regex_list: List[str]) -> None:
self.regex_filters: List[Pattern[str]] = []
for regex_str in regex_list:
try:
self.regex_filters.append(re.compile(regex_str, re.IGNORECASE))
except re.error:
logger.warning("Failed to parse regex:... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
from collections import deque
import sys
function part1 nums
begin
set tuple d1 d3 = tuple 1 1
for tuple i value in enumerate nums at slice 1 : : 1
begin
if value - 1 == nums at i - 1
begin
set d1 = d1 + 1
end
else
begin
for j in range 1 4
begin
if i - j > 0 and value - 3 == nums at i - ... | #!/usr/bin/env python3
from collections import deque
import sys
def part1(nums):
d1, d3 = 1, 1
for i, value in enumerate(nums[1:], 1):
if value - 1 == nums[i-1]:
d1 += 1
else:
for j in range(1, 4):
if i - j > 0 and value - 3 == nums[i-j]:
... | Python | zaydzuhri_stack_edu_python |
function last_processor_id self last_processor_id
begin
set _last_processor_id = last_processor_id
end function | def last_processor_id(self, last_processor_id):
self._last_processor_id = last_processor_id | Python | nomic_cornstack_python_v1 |
function register self name thread_obj=none event=none
begin
if thread_obj is not none
begin
set threads at name = thread_obj
end
if event is not none
begin
if event not in registry
begin
set registry at event = list
end
if add_event not in registry at event
begin
append registry at event add_event
end
end
end functio... | def register(self, name, thread_obj=None, event=None):
if thread_obj is not None:
self.threads[name] = thread_obj
if event is not None:
if event not in self.registry:
self.registry[event] = []
if self.threads[name].add_event not in self.registry[event]... | Python | nomic_cornstack_python_v1 |
function test_fetch_emd_history config=CONFIG
begin
set data = call fetch_market_history_emd region_id=get config string TEST string region_id type_id=get config string TEST string type_id data_range=get config string TEST string history_count config=config
comment validate contents ##
assert data at string version == ... | def test_fetch_emd_history(config=CONFIG):
data = forecast_utils.fetch_market_history_emd(
region_id=config.get('TEST', 'region_id'),
type_id=config.get('TEST', 'type_id'),
data_range=config.get('TEST', 'history_count'),
config=config
)
## validate contents ##
assert dat... | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
function getGrades fname
begin
try
begin
set gradesFile = open fname string r
end
except IOError
begin
raise call ValueError string getGrades could not open fname
end
set grades = list
for line in gradesFile
begin
try
begin
append grades decimal line
end
except any
begin
raise call ValueErr... | # -*- coding:utf-8 -*-
def getGrades(fname):
try:
gradesFile = open(fname, 'r')
except IOError:
raise ValueError('getGrades could not open ', fname)
grades = list()
for line in gradesFile:
try:
grades.append(float(line))
except:
raise ValueError('... | Python | zaydzuhri_stack_edu_python |
import math as m
import numpy as np
import matplotlib.pyplot as plt
import sklearn.datasets as datasets
from tensorflow import keras , math , random , stack
from tensorflow.keras import layers , initializers , utils
comment x[0] --- h1 ---- out[0]
comment \ /
comment X
comment / \
comment x[1] --- h2 ---- out[1]
commen... | import math as m
import numpy as np
import matplotlib.pyplot as plt
import sklearn.datasets as datasets
from tensorflow import keras, math, random, stack
from tensorflow.keras import layers, initializers, utils
#
# x[0] --- h1 ---- out[0]
# \ /
# X
# / \
# x... | Python | zaydzuhri_stack_edu_python |
function create_index_dictionary list_one list_two
begin
string This function takes two lists of equal length and creates a dictionary of the elements in each list that have the same index. The function also handles cases where the input lists are not of equal length and provides appropriate error handling. Additionall... | def create_index_dictionary(list_one, list_two):
"""
This function takes two lists of equal length and creates a dictionary of the elements in each list that have the same index.
The function also handles cases where the input lists are not of equal length and provides appropriate error handling.
Additi... | Python | jtatman_500k |
string Subarray with given sum Given an array of positive integers A and an integer B, find and return first continuous subarray which adds to B. If the answer does not exist return an array with a single element "-1". First sub-array means the sub-array for which starting index in minimum. Problem Constraints 1 <= len... | '''
Subarray with given sum
Given an array of positive integers A and an integer B, find and return first continuous subarray which adds to B.
If the answer does not exist return an array with a single element "-1".
First sub-array means the sub-array for which starting index in minimum.
Problem Constraints
1 <= leng... | Python | zaydzuhri_stack_edu_python |
function setResults self soc charge discharge
begin
comment Save state of charge
set results = call saveResultInit timer current_soc total_soc soc
set tuple current_soc total_soc soc_init = results
comment Save charging power
set results = call saveResult timer current_p_charge total_p_charge charge
set tuple current_p... | def setResults(self, soc, charge, discharge):
# Save state of charge
results = handleData.saveResultInit(self.environment.timer,
self.current_soc,
self.total_soc,
soc)
... | Python | nomic_cornstack_python_v1 |
function setRequiredColumns self colnames
begin
comment Make sure all column names are lower case so comparisons in _TableRow
comment are not case sensitive. From a modularity standpoint, this should be
comment done in _TableRow, but it is more efficient to do it here, since the
comment conversion need be done only onc... | def setRequiredColumns(self, colnames):
# Make sure all column names are lower case so comparisons in _TableRow
# are not case sensitive. From a modularity standpoint, this should be
# done in _TableRow, but it is more efficient to do it here, since the
# conversion need be done only on... | Python | nomic_cornstack_python_v1 |
function run self
begin
for _ in range val
begin
set my_id = call send_id
set time_val = string format time time string %Y-%m-%d %H:%M:%S call localtime
call emit call Notification my_id time_val
comment Defining a ranodm sleep time (0-10) seconds.
set sleep_time = random * 10
sleep sleep_time
end
end function | def run(self):
for _ in range(self.val):
my_id = MyObject().send_id()
time_val = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.object_signal.emit(Notification(my_id, time_val))
# Defining a ranodm sleep time (0-10) seconds.
sleep_time = ran... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.