code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_config self
begin
set config = dict string output_dim output_dim ; string units nodes ; string return_probabilities return_alphas
set base_config = call get_config
return dictionary list items base_config + list items config
end function | def get_config(self):
config = {
'output_dim': self.output_dim,
'units': self.nodes,
'return_probabilities': self.return_alphas
}
base_config = super(BadhanauAttentionDecoder, self).get_config()
return dict(list(base_config.items()) + list(config.items... | Python | nomic_cornstack_python_v1 |
function path_tokens self
begin
set curpath = call curpath
if start_path != curpath
begin
return list tuple PromptPath curpath
end
else
begin
return list
end
end function | def path_tokens(self):
curpath = self.curpath()
if self.start_path != curpath:
return [(Token.PromptPath, curpath)]
else:
return [] | Python | nomic_cornstack_python_v1 |
function task_created request
begin
if not call test_user_authenticated request
begin
return call login request next=string /cobbler_web/task_created expired=true
end
set t = call get_template string task_created.tmpl
set html = call render call RequestContext request dict string version call extended_version session a... | def task_created(request):
if not test_user_authenticated(request): return login(request, next="/cobbler_web/task_created", expired=True)
t = get_template("task_created.tmpl")
html = t.render(RequestContext(request,{
'version' : remote.extended_version(request.session['token'])['version'],
'user... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
import re
import json
import os
string s = u'hello world world' r = ur'.*([a-z])' print re.match(r, s)
comment note : match好像不能匹配(?<=xxxx)的字符串,如果xxx不为空的话.有待验证,只是偶然碰巧碰到而已.因为这种模式是不消耗前面的字符串的 | #coding=utf-8
import re
import json
import os
'''
s = u'hello world world'
r = ur'.*([a-z])\1'
print re.match(r, s)
'''
#note : match好像不能匹配(?<=xxxx)的字符串,如果xxx不为空的话.有待验证,只是偶然碰巧碰到而已.因为这种模式是不消耗前面的字符串的 | Python | zaydzuhri_stack_edu_python |
class A extends object
begin
function aa self
begin
return string 1
end function
end class
class B extends A
begin
function aa self
begin
set b = call aa
print b
end function
end class
set b = call B
call aa | class A(object):
def aa(self):
return '1'
class B(A):
def aa(self):
b = super(B, self).aa()
print(b)
b = B()
b.aa()
| Python | zaydzuhri_stack_edu_python |
function lambda_handler event context
begin
set missing_fields = call verify_fields event
if missing_fields
begin
raise exception string Missing fields: + join string , missing_fields
end
set user_data = call copy_event_data event
call clean_data user_data
set net_resources_cap = MONTHLY_NET_RESOURCES_CAP * 12.0
set us... | def lambda_handler(event, context):
missing_fields = verify_fields(event)
if missing_fields:
raise Exception("Missing fields: " + ", ".join(missing_fields))
user_data = copy_event_data(event)
clean_data(user_data)
net_resources_cap = MONTHLY_NET_RESOURCES_CAP * 12.0
user_data['gross_inc... | Python | nomic_cornstack_python_v1 |
function _distro_release_info self
begin
string Get the information items from the specified distro release file. Returns: A dictionary containing all information items.
if distro_release_file
begin
comment If it was specified, we use it and parse what we can, even if
comment its file name or content does not match the... | def _distro_release_info(self):
"""
Get the information items from the specified distro release file.
Returns:
A dictionary containing all information items.
"""
if self.distro_release_file:
# If it was specified, we use it and parse what we can, even if
... | Python | jtatman_500k |
function standardize_X_data X_train X_test
begin
comment Fit StandardScaler to X_train
set scaler = standard scaler
fit scaler X_train
comment Use the fit StandardScaler model to standardize both X_train and X_test
set X_train_std = transform scaler X_train
set X_test_std = transform scaler X_test
return tuple X_train_... | def standardize_X_data(X_train, X_test):
# Fit StandardScaler to X_train
scaler = StandardScaler()
scaler.fit(X_train)
# Use the fit StandardScaler model to standardize both X_train and X_test
X_train_std = scaler.transform(X_train)
X_test_std = scaler.transform(X_test)
return X_train_std... | Python | nomic_cornstack_python_v1 |
function test_import_string_invalid_path self
begin
set invalid_path = string some invalid module path
with raises ImportError as error
begin
call import_string invalid_path
end
assert format string {} doesn't look like a module path invalid_path == string value
end function | def test_import_string_invalid_path(self):
invalid_path = 'some invalid module path'
with pytest.raises(ImportError) as error:
utils.import_string(invalid_path)
assert '{} doesn\'t look like a module path'.format(
invalid_path) == str(error.value) | Python | nomic_cornstack_python_v1 |
for x in range 1 11
begin
print n string x x string = n * x
end
comment multiplication
comment while True:
comment s=int(input("enter a number: "))
comment i=1
comment while(i<=10):
comment print(f"{s}*{i}={s*i}")
comment i=i+1 | for x in range(1,11):
print(n,'x',x,'=',n*x)
#########multiplication
#while True:
# s=int(input("enter a number: "))
# i=1
# while(i<=10):
# print(f"{s}*{i}={s*i}")
# i=i+1
#
#
| Python | zaydzuhri_stack_edu_python |
string EGTS_SR_POS_DATA
from egts_types import *
from egts_types.date_time_field import DateTime
class PosData extends EGTSRecord
begin
string EGTS_SR_POS_DATA Class
function __init__ self *args **kwargs
begin
string Overriding constructor with fields :param args: additional args :param kwargs: parent class kwargs
call... | """EGTS_SR_POS_DATA"""
from ....egts_types import *
from ....egts_types.date_time_field import DateTime
class PosData(EGTSRecord):
"""EGTS_SR_POS_DATA Class"""
def __init__(self, *args, **kwargs):
"""
Overriding constructor with fields
:param args: additional args
:param kwargs... | Python | zaydzuhri_stack_edu_python |
comment -> BuildingType
function get_building_type self
begin
return BACKGROUND
end function | def get_building_type(self): # -> BuildingType
return BuildingType.BACKGROUND | Python | nomic_cornstack_python_v1 |
function set_chat_photo self *args **kwargs
begin
string See :func:`set_chat_photo`
return run
end function | def set_chat_photo(self, *args, **kwargs):
"""See :func:`set_chat_photo`"""
return set_chat_photo(*args, **self._merge_overrides(**kwargs)).run() | Python | jtatman_500k |
with open string pi_digits.txt as file_object
begin
set contents = read file_object
end
print contents
set filename = string pi_digits.txt
with open filename as file_object
begin
for line in file_object
begin
comment rstrip works to remove the blank line, you can just remove .rstripand see it.
print right strip line
en... | with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents)
filename= 'pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line.rstrip()) #rstrip works to remove the blank line, you can just remove .rstripand see it.
| Python | zaydzuhri_stack_edu_python |
string OpenGymのテスト
import gym
set episode_num = 5
set max_step_num = 200
set ENV_NAME = string CartPole-v0
set env = call make ENV_NAME
print string 入力の次元 observation_space
print string 出力の次元 action_space
print string 報酬の範囲 reward_range
for episode in range episode_num
begin
comment 初期化
call reset
comment 描画
call rende... | """
OpenGymのテスト
"""
import gym
episode_num = 5
max_step_num = 200
ENV_NAME = "CartPole-v0"
env = gym.make(ENV_NAME)
print("入力の次元", env.observation_space)
print("出力の次元", env.action_space)
print("報酬の範囲", env.reward_range)
for episode in range(episode_num):
env.reset() # 初期化
env.render() # 描画
for step i... | Python | zaydzuhri_stack_edu_python |
function get_synthetic_data_and_answer_v1 num_rows num_columns num_preds corr random_seed data_cache_file print_details=false min_meta=false
begin
if exists path data_cache_file
begin
with open data_cache_file as f
begin
set tuple df preds meta = load pickle f
end
end
else
begin
set start = call timer
set np_random = c... | def get_synthetic_data_and_answer_v1(num_rows, num_columns, num_preds, corr, random_seed,
data_cache_file, print_details=False,
min_meta=False):
if os.path.exists(data_cache_file):
with open(data_cache_file) as f:
df, pred... | Python | nomic_cornstack_python_v1 |
for tuple n line in enumerate f start=1
begin
print string { n } : { line at slice : - 1 : }
end
close f | for n, line in enumerate(f, start=1):
print(f"{n}: {line[:-1]}")
f.close()
| Python | zaydzuhri_stack_edu_python |
function _delete_audio audio_filename must_delete=true
begin
call _check_filename audio_filename
if must_delete
begin
remove os audio_filename
end
end function | def _delete_audio(audio_filename: str, must_delete: bool = True) -> None:
_check_filename(audio_filename)
if must_delete:
os.remove(audio_filename) | Python | nomic_cornstack_python_v1 |
function copy_to_local fn
begin
class Block
begin
string Data block to return from SrcIter
function __init__ self data
begin
set data = data
end function
end class
class SrcIter
begin
string Iterate over source and return Block of data.
function __init__ self fileobj
begin
set fileobj = fileobj
end function
function ne... | def copy_to_local(fn):
class Block:
"""
Data block to return from SrcIter
"""
def __init__(self, data):
self.data = data
class SrcIter:
"""
Iterate over source and return Block of data.
"""
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
print string ... read() 方法一次性读取整个文件,read(size) 有一个可选的参数 size,用于指定字符串长度。如果没有指定 size 或者指定为负数,就会读取并返回整个文件。当文件大小为当前机器内存两倍时,就会产生问题。反之,会尽可能按比较大的 size 读取和返回数据 ... readline() 能帮助你每次读取文件的一行 ... readlines() 方法读取所有行到一个列表中 ... fobj = open('sample.txt') ... for x in fobj: ... print(x, end = '') ... 在实际... | #!/usr/bin/env python3
print("""\
... read() 方法一次性读取整个文件,read(size) 有一个可选的参数 size,用于指定字符串长度。如果没有指定 size 或者指定为负数,就会读取并返回整个文件。当文件大小为当前机器内存两倍时,就会产生问题。反之,会尽可能按比较大的 size 读取和返回数据
... readline() 能帮助你每次读取文件的一行
... readlines() 方法读取所有行到一个列表中
... fobj = open('sample.txt')
... for x in fobj:
... print(x, end = '')
... 在实际情况中,我... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode id=11 lang=python3
comment [11] Container With Most Water
comment @lc code=start
class Solution
begin
function maxArea self height
begin
set start = 0
set end = length height - 1
set maxWater = 0
while start < end
begin
set water = end - start * min height at start height at end
set maxWater = ... | #
# @lc app=leetcode id=11 lang=python3
#
# [11] Container With Most Water
#
# @lc code=start
class Solution:
def maxArea(self, height: List[int]) -> int:
start = 0
end = len(height) - 1
maxWater = 0
while start < end:
water = (end-start) * min(height[start], height[end]... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from django.shortcuts import render , redirect
import random
function index request
begin
if string gold not in keys session
begin
set session at string gold = 0
end
if string history not in keys session
begin
set sessio... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime
from django.shortcuts import render, redirect
import random
def index(request):
if 'gold' not in request.session.keys():
request.session['gold'] = 0
if 'history' not in request.session.keys():
request.... | Python | zaydzuhri_stack_edu_python |
async function source ctx command
begin
set source_url = string https://github.com/Pycord-Development/robocord
set branch = string main
set view = view ui
if command is none
begin
set url = source_url
set label = string Source code for entire bot
end
else
begin
set command_split = split command
set index = 0
set obj = ... | async def source(ctx, command: Option(str, "The command to view the source code for", required=False)):
source_url = 'https://github.com/Pycord-Development/robocord'
branch = 'main'
view = discord.ui.View()
if command is None:
url = source_url
label = "Source code for entire bot"
els... | Python | nomic_cornstack_python_v1 |
comment Task
comment Read two integers and print two lines. The first line should contain integer division, aa//bb. The second line should contain float division, aa/bb.
comment You don't need to perform any rounding or formatting operations.
comment Input Format
comment The first line contains the first integer, aa. T... | # Task
# Read two integers and print two lines. The first line should contain integer division, aa//bb. The second line should contain float division, aa/bb.
# You don't need to perform any rounding or formatting operations.
# Input Format
# The first line contains the first integer, aa. The second line contains the ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment !/usr/bin/python3
string GUI (frontend) a Demo robot vezérléshez. Ez a modul tartalmazza a főképernyő grafikus interface elemeit. ---- Libs ---- * Tkinter * Threading ---- Help ---- * https://effbot.org/tkinterbook/tkinter-events-and-bindings.htm * https://pythonprogramming.net/tki... | # -*- coding: utf-8 -*-
#!/usr/bin/python3
""" GUI (frontend) a Demo robot vezérléshez. Ez a modul tartalmazza a
főképernyő grafikus interface elemeit.
---- Libs ----
* Tkinter
* Threading
---- Help ----
* https://effbot.org/tkinterbook/tkinter-events-and-bindings.htm
* https://pythonprogramming.net/tkinter-tutorial... | Python | zaydzuhri_stack_edu_python |
if media >= 6.0
begin
print string Sua nota foi boa!
end
else
begin
print string Estuda mais!
end | if media >= 6.0:
print('Sua nota foi boa!')
else:
print('Estuda mais!') | Python | zaydzuhri_stack_edu_python |
function create_spec_from_sys_environ cls sys_environ
begin
set spec = dict
set host = get sys_environ string DOCKER_HOST
if host
begin
set spec at string host = host
end
set cert_path = get sys_environ string DOCKER_CERT_PATH or none
if cert_path
begin
set spec at string cert_path = cert_path
end
comment empty string... | def create_spec_from_sys_environ(cls, sys_environ):
spec = {}
host = sys_environ.get("DOCKER_HOST")
if host:
spec["host"] = host
cert_path = sys_environ.get("DOCKER_CERT_PATH") or None
if cert_path:
spec["cert_path"] = cert_path
# empty string for... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Fri May 22 18:33:03 2020 @author: Omkar
import bs4 as bs
import urllib.request
import re
import nltk
call download string stopwords
set src = read url open string https://en.wikipedia.org/wiki/Global_Warming
set soup = call BeautifulSoup src string lxml
set text = string ... | # -*- coding: utf-8 -*-
"""
Created on Fri May 22 18:33:03 2020
@author: Omkar
"""
import bs4 as bs
import urllib.request
import re
import nltk
nltk.download('stopwords')
src = urllib.request.urlopen('https://en.wikipedia.org/wiki/Global_Warming').read()
soup = bs.BeautifulSoup(src,'lxml')
text = ""
for para in s... | Python | zaydzuhri_stack_edu_python |
function get_level self
begin
return level
end function | def get_level(self):
return self.level | Python | nomic_cornstack_python_v1 |
string В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами. Сами минимальный и максимальный элементы в сумму не включать.
from random import random
set N = 15
set a = list 0 * N
for i in range N
begin
set a at i = integer random * 30
print string %3d % a at i end=string
e... | '''
В одномерном массиве найти сумму элементов, находящихся между минимальным и
максимальным элементами. Сами минимальный и максимальный элементы в сумму не включать.
'''
from random import random
N = 15
a = [0]*N
for i in range(N):
a[i] = int(random()*30)
print('%3d' % a[i], end='')
print()
min_id = 0
max_i... | Python | zaydzuhri_stack_edu_python |
import turtle
import random
set t = call Pen
call speed 0
call bgcolor string black
set x = 1
while x < 800
begin
set r = random integer 0 255
set g = random integer 0 255
set b = random integer 0 255
call colormode 255
call pencolor r g b
call forward x
call right 90.911
set x = x + 1
end
call done | import turtle
import random
t = turtle.Pen()
t.speed(0)
turtle.bgcolor('black')
x = 1
while x < 800:
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
t.colormode(255)
t.pencolor(r, g, b)
t.forward(x)
t.right(90.911)
x = x + 1
turtle.done()
| Python | zaydzuhri_stack_edu_python |
function update self data *args **kwargs
begin
call setData *args x=setpoint_x y=call ensure_ndarray data keyword kwargs
end function | def update(self, data, *args, **kwargs):
self.setData(x=self.setpoint_x, y=ensure_ndarray(data), *args, **kwargs) | Python | nomic_cornstack_python_v1 |
import numpy as np
from autograd import Tensor , Parameter , Module
from autograd.optim import SGD
class LinearModel extends Module
begin
function __init__ self
begin
set w = call Parameter 3
set b = call Parameter
end function
function predict self inputs
begin
string Learned function: y = Ax + b
return inputs @ w + b... | import numpy as np
from autograd import Tensor, Parameter, Module
from autograd.optim import SGD
class LinearModel(Module):
def __init__(self) -> None:
self.w = Parameter(3)
self.b = Parameter()
def predict(self, inputs: Tensor) -> Tensor:
"""Learned function: y = Ax + b"""
... | Python | zaydzuhri_stack_edu_python |
for i in range 1 n
begin
set arr at i = min num2 num3 num5
if arr at i == num2
begin
set idx2 = idx2 + 1
set num2 = arr at idx2 * 2
end
if arr at i == num3
begin
set idx3 = idx3 + 1
set num3 = arr at idx3 * 3
end
if arr at i == num5
begin
set idx5 = idx5 + 1
set num5 = arr at idx5 * 5
end
end
print arr at - 1 | for i in range(1, n):
arr[i] = min(num2, num3, num5)
if arr[i] == num2:
idx2 += 1
num2 = arr[idx2] * 2
if arr[i] == num3:
idx3 += 1
num3 = arr[idx3] * 3
if arr[i] == num5:
idx5 += 1
num5 = arr[idx5] * 5
print(arr[-1])
| Python | zaydzuhri_stack_edu_python |
string 48. Rotate Image Link: https://leetcode.com/problems/rotate-image/ # C L O C K W I S E You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D... | '''
48. Rotate Image
Link: https://leetcode.com/problems/rotate-image/
# C L O C K W I S E
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you
have to modify the input 2D matrix directly.
DO NOT allocate another 2D ... | Python | zaydzuhri_stack_edu_python |
import os
set dirs_list = list string dir1 string dir2 string dir3
for d in dirs_list
begin
make directories d
end | import os
dirs_list = ["dir1", "dir2", "dir3"]
for d in dirs_list:
os.makedirs(d)
| Python | flytech_python_25k |
function main argv=none
begin
comment Create an ArgumentParser--a special object that keeps track of all the
comment arguments we want our script to be able to handle, and then implements parsing
comment them from sys.argv
set parser = call ArgumentParser description=string Generates simulated images of clusters
commen... | def main(argv=None):
# Create an ArgumentParser--a special object that keeps track of all the
# arguments we want our script to be able to handle, and then implements parsing
# them from sys.argv
parser = argparse.ArgumentParser(description="Generates simulated images of clusters")
# Add an option... | Python | nomic_cornstack_python_v1 |
function fake_metta matrix_dict metadata
begin
set matrix = set index call from_dict matrix_dict string entity_id
with named temporary file as matrix_file
begin
with named temporary file string w as metadata_file
begin
set hdf = call HDFStore name
put string title matrix data_columns=true
seek matrix_file 0
dump metada... | def fake_metta(matrix_dict, metadata):
matrix = pandas.DataFrame.from_dict(matrix_dict).set_index('entity_id')
with tempfile.NamedTemporaryFile() as matrix_file:
with tempfile.NamedTemporaryFile('w') as metadata_file:
hdf = pandas.HDFStore(matrix_file.name)
hdf.put('title', matri... | Python | nomic_cornstack_python_v1 |
function replace_apps_openshift_io_v1_namespaced_scale_scale_with_http_info self name namespace body **kwargs
begin
set all_params = list string name string namespace string body string pretty
append all_params string callback
append all_params string _return_http_data_only
append all_params string _preload_content
app... | def replace_apps_openshift_io_v1_namespaced_scale_scale_with_http_info(self, name, namespace, body, **kwargs):
all_params = ['name', 'namespace', 'body', 'pretty']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all... | Python | nomic_cornstack_python_v1 |
async function _outgoing_tcp self pid writer
begin
set character = players at pid
comment This coroutine just loops forever, and will eventually be
comment broken once the client disconnects.
while true
begin
comment Try to get a message from the Character's queue.
comment This will block until the character receives a... | async def _outgoing_tcp(self, pid, writer):
character = self.players[pid]
# This coroutine just loops forever, and will eventually be
# broken once the client disconnects.
while True:
# Try to get a message from the Character's queue.
# This will block until the ... | Python | nomic_cornstack_python_v1 |
comment This python script aims to prepare the data for our model inputs and outputs, including cropping the data
comment and saving the data to memory in order to speed up data fetch.
comment The time coverage of GRACE is from 2002-04 to 2017-06 while GFO is from 2018-06 to 2021-12, with a spatial
comment resolution o... | # This python script aims to prepare the data for our model inputs and outputs, including cropping the data
# and saving the data to memory in order to speed up data fetch.
# The time coverage of GRACE is from 2002-04 to 2017-06 while GFO is from 2018-06 to 2021-12, with a spatial
# resolution of 0.5deg
# we used t... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf8 -*-
import logging
from menuItem import MenuItem
from conf import conf
from Graphx import graphx
from containerBehaviour import ContainerBehaviour
from containerView import ContainerView
from containerModel import ContainerModel
class Container extends MenuItem
begin
string Represent any contai... | # -*- coding: utf8 -*-
import logging
from menuItem import MenuItem
from conf import conf
from Graphx import graphx
from containerBehaviour import ContainerBehaviour
from containerView import ContainerView
from containerModel import ContainerModel
class Container(MenuItem):
"""
Represent any container of the menu... | Python | zaydzuhri_stack_edu_python |
function main_loop self
begin
call read_entity
set tpool = list
for tuple key entity in items dictOfEntities
begin
set myThreadOb1 = call TuyaMQTTEntity key entity self
call setName key
start myThreadOb1
append tpool myThreadOb1
end
set time_run_save = 0
while true
begin
if not mqtt_connected
begin
call mqtt_connect
s... | def main_loop(self):
self.read_entity()
tpool = []
for key,entity in self.dictOfEntities.items():
myThreadOb1 = TuyaMQTTEntity(key, entity, self)
myThreadOb1.setName(key)
myThreadOb1.start()
tpool.append(myThreadOb1)
time_r... | Python | nomic_cornstack_python_v1 |
function _find_groups self
begin
string Returns a tuple (reverse string, group count) for a url. For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method would return ('/%s/%s/', 2).
set pattern = pattern
if starts with pattern string ^
begin
set pattern = pattern at slice 1 : :
end
if ends with pattern... | def _find_groups(self) -> Tuple[Optional[str], Optional[int]]:
"""Returns a tuple (reverse string, group count) for a url.
For example: Given the url pattern /([0-9]{4})/([a-z-]+)/, this method
would return ('/%s/%s/', 2).
"""
pattern = self.regex.pattern
if pattern.star... | Python | jtatman_500k |
function xa self x_surface geom
begin
return array init
end function | def xa(self, x_surface, geom):
return np.array(self.init) | Python | nomic_cornstack_python_v1 |
function copy_best_model_data_to_final_dir final_dir best_model_run_dir trait
begin
set trait_cols_file_path = join path best_model_run_dir string trait_cols_names_info.pkl
set model_file_path = join path best_model_run_dir string traits_models string { trait } _model.pkl
set description_text = string linear_regression... | def copy_best_model_data_to_final_dir(final_dir, best_model_run_dir, trait):
trait_cols_file_path = os.path.join(best_model_run_dir, 'trait_cols_names_info.pkl')
model_file_path = os.path.join(best_model_run_dir, 'traits_models', f'{trait}_model.pkl')
description_text = 'linear_regression_random_forest_md_4... | Python | nomic_cornstack_python_v1 |
function retEvenStr str
begin
set str = split str string
comment print(temp)
for i in str
begin
if length i % 2 == 0
begin
print i end=string
end
end
end function
set str = string My name is Pranav rrr ppppp pppp
call retEvenStr str | def retEvenStr(str):
str = str.split(' ')
#print(temp)
for i in str:
if (len(i) % 2 == 0):
print(i, end=' ')
str = "My name is Pranav rrr ppppp pppp"
retEvenStr(str)
| Python | zaydzuhri_stack_edu_python |
function send_events sock
begin
set i = 0
while i < 10
begin
info string Sending message from publisher..
call send string even - hai i am publisher
sleep 0.2
set i = i + 1
end
end function | def send_events(sock):
i=0
while i<10:
log.info('Sending message from publisher..')
sock.send("even - hai i am publisher")
time.sleep(0.2)
i += 1 | Python | nomic_cornstack_python_v1 |
while input_password != exp_password
begin
print string Wrong password!!!
set wrong_password_count = wrong_password_count + 1
if wrong_password_count == wrong_password_limit
begin
break
end
else
begin
set input_password = input string Enter password:
end
end
if wrong_password_count != wrong_password_limit
begin
print s... | while input_password != exp_password:
print("Wrong password!!!")
wrong_password_count+=1
if wrong_password_count == wrong_password_limit:
break
else:
input_password = input("Enter password: ")
if wrong_password_count != wrong_password_limit:
print("Correct password") | Python | zaydzuhri_stack_edu_python |
function handle_message bot update
begin
with call get_connection as conn
begin
call insert_inbound_msg conn chat_id text
end
end function | def handle_message(bot, update):
with db.get_connection() as conn:
db.insert_inbound_msg(conn, update.message.chat_id, update.message.text) | Python | nomic_cornstack_python_v1 |
function test_v1_catalogue_confirm_match_iaa_edition_catalog_to_text_fragment_id_post self
begin
pass
end function | def test_v1_catalogue_confirm_match_iaa_edition_catalog_to_text_fragment_id_post(self):
pass | Python | nomic_cornstack_python_v1 |
function discretize self obstacle_collection drone_poses goal_poses
begin
set cyl_c1_list = list
set cyl_c2_list = list
set cyl_r_list = list
set cyl_dir_list = list
for obs in obstacles
begin
if is instance obs Cylinder
begin
if axis == string x
begin
append cyl_dir_list 0
append cyl_c1_list y + absolute MIN_Y
app... | def discretize(self, obstacle_collection, drone_poses, goal_poses):
cyl_c1_list = []
cyl_c2_list = []
cyl_r_list = []
cyl_dir_list = []
for obs in obstacle_collection.obstacles:
if isinstance(obs, Cylinder):
if obs.axis == 'x':
cyl_... | Python | nomic_cornstack_python_v1 |
function _ff_calc_hidden_layer self
begin
for hidden_neuron in hiddens
begin
comment value from Bias
set sum = value * weight
comment summation of input node values and their corresponding weights
for input_neuron in inputs
begin
set sum = sum + value * weight
end
comment set the hidden neuron's value
set value = call ... | def _ff_calc_hidden_layer(self):
for hidden_neuron in self.hiddens:
# value from Bias
sum = (self.hidden_bias_neuron.value
* self.hidden_bias_links[hidden_neuron.index].weight)
# summation of input node values and their corresponding weights
fo... | Python | nomic_cornstack_python_v1 |
function start_loop self
begin
call MainLoop
end function | def start_loop(self):
self.MainLoop() | Python | nomic_cornstack_python_v1 |
from transaction import Transaction
from tools import gen_keys , sign , get_hash , logger
import random
class User
begin
function __init__ self
begin
set tuple __private_key public_key = call gen_keys
set id = public_key
set coins = list
end function
function create_transaction self receiver scrooge
begin
set list_coi... | from transaction import Transaction
from tools import gen_keys, sign, get_hash, logger
import random
class User():
def __init__(self):
self.__private_key, self.public_key = gen_keys()
self.id = self.public_key
self.coins = []
def create_transaction(self, receiver, scrooge):
lis... | Python | zaydzuhri_stack_edu_python |
function product_requests_button page page_perms is_parent=false
begin
string Renders a 'requests' button on the page index showing the number of times the product has been requested. Attempts to only show such a button for valid product/variant pages
comment Is this page the 'product' model?
comment It is generally sa... | def product_requests_button(page, page_perms, is_parent=False):
"""Renders a 'requests' button on the page index showing the number
of times the product has been requested.
Attempts to only show such a button for valid product/variant pages
"""
# Is this page the 'product' model?
# It is genera... | Python | jtatman_500k |
string Properly implemented ResNet-s for CIFAR10 as described in paper [1]. The implementation and structure of this file is hugely influenced by [2] which is implemented for ImageNet and doesn't have option A for identity. Moreover, most of the implementations on the web is copy-paste from torchvision's resnet and has... | '''
Properly implemented ResNet-s for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the implementations on the web is copy-paste from
torchvision's resnet and has w... | Python | zaydzuhri_stack_edu_python |
from urllib import request
import re
set url = string https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=0&limit=20
set header = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36
set req = call R... | from urllib import request
import re
url = "https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=0&limit=20"
header = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/74.0.3729.157 Safari/537.36"
}
req = request.R... | Python | zaydzuhri_stack_edu_python |
function teardown_request self f
begin
insert set default teardown_request_funcs none list 0 f
return f
end function | def teardown_request(self, f):
self.teardown_request_funcs.setdefault(None, []).insert(0, f)
return f | Python | nomic_cornstack_python_v1 |
function _CompareFilesPerSubdirectory self expected gotten
begin
set expected_directory_to_files = dictionary comprehension result at 0 : list result at 1 for result in expected
set gotten_directory_to_files = dictionary comprehension result at 0 : list result at 2 for result in gotten
comment Note we ignore subdirecto... | def _CompareFilesPerSubdirectory(self, expected, gotten):
expected_directory_to_files = {
result[0]: list(result[1]) for result in expected
}
gotten_directory_to_files = {
# Note we ignore subdirectories and just compare files
result[0]: list(result[2])
... | Python | nomic_cornstack_python_v1 |
function data_level self
begin
return _data_level
end function | def data_level(self) -> int:
return self._data_level | Python | nomic_cornstack_python_v1 |
function is_cuda self
begin
return is_cuda
end function | def is_cuda(self):
return next(self.parameters()).is_cuda | Python | nomic_cornstack_python_v1 |
function test_installed_unknown_builder_version mock_tools builder_version capsys
begin
set side_effect = list string Flatpak 1.12.7 builder_version
call verify mock_tools
call assert_has_calls list call list string flatpak string --version call list string flatpak-builder string --version any_order=false
set output = ... | def test_installed_unknown_builder_version(mock_tools, builder_version, capsys):
mock_tools.subprocess.check_output.side_effect = [
"Flatpak 1.12.7",
builder_version,
]
Flatpak.verify(mock_tools)
mock_tools.subprocess.check_output.assert_has_calls(
[
mock.call(["fla... | Python | nomic_cornstack_python_v1 |
function predict self x
begin
assert is instance x ndarray
set output = x
for layer in _layers
begin
set output = call feed_forward output
end
return output
end function | def predict(self, x):
assert isinstance(x, np.ndarray)
output = x
for layer in self._layers:
output = layer.feed_forward(output)
return output | Python | nomic_cornstack_python_v1 |
class Node
begin
function __init__ self value
begin
set value = value
set left = none
set right = none
end function
end class
function insert_node root value
begin
if value < value
begin
if left == none
begin
set left = call Node value
end
else
begin
call insert_node left value
end
end
else
if right == none
begin
set r... | class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert_node(root, value):
if value < root.value:
if root.left == None:
root.left = Node(value)
else:
insert_node(root.left, value)
else:
i... | Python | zaydzuhri_stack_edu_python |
function _calcAvgDisplacement self prev_kp kp
begin
comment TODO: If values differ too much:
comment * filter out such values
comment * abort and detect KP
set ds_x = list
set ds_y = list
for i in range length kp
begin
append ds_x pt at 0 - pt at 0
append ds_y pt at 1 - pt at 1
end
return tuple sum ds_y / length ds_y... | def _calcAvgDisplacement(self, prev_kp, kp):
# TODO: If values differ too much:
# * filter out such values
# * abort and detect KP
ds_x = []
ds_y = []
for i in range(len(kp)):
ds_x.append(prev_kp[i].pt[0] - kp[i].pt[0])
ds_y.append... | Python | nomic_cornstack_python_v1 |
function union self *others **kwargs
begin
string Returns the union of variants in a several VariantCollection objects.
return call _combine_variant_collections combine_fn=union variant_collections=tuple self + others kwargs=kwargs
end function | def union(self, *others, **kwargs):
"""
Returns the union of variants in a several VariantCollection objects.
"""
return self._combine_variant_collections(
combine_fn=set.union,
variant_collections=(self,) + others,
kwargs=kwargs) | Python | jtatman_500k |
function textile text head_offset=0 html_type=string xhtml auto_link=false encoding=none output=none
begin
return call textile text head_offset=head_offset html_type=html_type
end function | def textile(text, head_offset=0, html_type='xhtml', auto_link=False,
encoding=None, output=None):
return Textile(auto_link=auto_link).textile(text, head_offset=head_offset,
html_type=html_type) | Python | nomic_cornstack_python_v1 |
async function test_id_missing hass controller
begin
set device = call setup_mock_accessory controller
set discovery_info = call get_device_discovery_info device
comment Remove id from device
del properties at ATTR_PROPERTIES_ID
comment Device is discovered
set result = await call async_init string homekit_controller c... | async def test_id_missing(hass: HomeAssistant, controller) -> None:
device = setup_mock_accessory(controller)
discovery_info = get_device_discovery_info(device)
# Remove id from device
del discovery_info.properties[zeroconf.ATTR_PROPERTIES_ID]
# Device is discovered
result = await hass.config_... | Python | nomic_cornstack_python_v1 |
function lvar inlist
begin
set n = length inlist
set mn = mean inlist
set deviations = list 0 * length inlist
for i in range length inlist
begin
set deviations at i = inlist at i - mn
end
return call ss deviations / decimal n - 1
end function | def lvar (inlist):
n = len(inlist)
mn = mean(inlist)
deviations = [0]*len(inlist)
for i in range(len(inlist)):
deviations[i] = inlist[i] - mn
return ss(deviations)/float(n-1) | Python | nomic_cornstack_python_v1 |
function register method event
begin
call subscribe method event
end function | def register (method, event):
Publisher.subscribe (method, event) | Python | nomic_cornstack_python_v1 |
import numpy as np
import math
function cross a b
begin
return list a at 1 * b at 2 - a at 2 * b at 1 a at 2 * b at 0 - a at 0 * b at 2 a at 0 * b at 1 - a at 1 * b at 0
end function
function raytraceSphere
begin
set sphereList = list
set rayList = list
set rayDirection = list
for i in range 0 3
begin
set element = ... | import numpy as np
import math
def cross(a, b):
return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
def raytraceSphere():
sphereList = []
rayList = []
rayDirection = []
for i in range(0,3):
element = float(input("Enter sphere center vector(3 numbers): "... | Python | zaydzuhri_stack_edu_python |
from math import floor
set SIGNIFICANT_DEZ = 3
set EPSILON = 1e-05
function my_round x significant_dez=SIGNIFICANT_DEZ
begin
return round x significant_dez
end function
function my_round_complex x d=SIGNIFICANT_DEZ
begin
return call complex call my_round real d call my_round imag d
end function
function my_complex_to_s... | from math import floor
SIGNIFICANT_DEZ = 3
EPSILON = 0.00001
def my_round(x, significant_dez = SIGNIFICANT_DEZ):
return round(x, significant_dez)
def my_round_complex(x, d = SIGNIFICANT_DEZ):
return complex(my_round(x.real, d), my_round(x.imag, d))
def my_complex_to_str(x):
real = str(int(x.real)) if in... | Python | zaydzuhri_stack_edu_python |
string @author lferiani @date June 04th, 2019 OpenTrons Pipette rack in 1 Pick up tip, return tip
from opentrons import labware , instruments , robot
comment user intuitive parameters
set tiprack_slot = string 1
comment first nonempty tip in the tip rack
set tip_start_from = string A1
comment full tiprack
set tips_left... | """
@author lferiani
@date June 04th, 2019
OpenTrons Pipette rack in 1
Pick up tip, return tip
"""
from opentrons import labware, instruments, robot
####################### user intuitive parameters
tiprack_slot = '1'
tip_start_from = 'A1' # first nonempty tip in the tip rack
tips_left = 96 # full tiprack
####... | Python | zaydzuhri_stack_edu_python |
comment Importing Necessary Functions from Files
from path import *
from sss_generation_functions import sss
from sss_detection_functions import *
from mapping_dictonary import *
import random
set errors = 10
set N_ID1 = call randrange 168
set N_ID2 = call randrange 3 | #Importing Necessary Functions from Files
from path import *
from sss_generation_functions import sss
from sss_detection_functions import *
from mapping_dictonary import *
import random
errors = 10
N_ID1 = random.randrange(168)
N_ID2 = random.randrange(3)
| Python | zaydzuhri_stack_edu_python |
string print('Python {r}'.format(r='rules!'))
string print(1>2)
string my_file= ( "C:\Users\dp\Documents\my_file.txt" ) my_file=open('my_file.txt') my_file.seek(0) my_file.readlines()
string s='hello' a=s[4]+s[3]+s[2]+s[1]+s[0] print(a) print(s[::-1])
string n=int(input("Enter any number:")) n=str(n) print(n[::-1])
str... | '''print('Python {r}'.format(r='rules!'))'''
'''print(1>2)'''
'''my_file= ( "C:\\Users\\dp\\Documents\\my_file.txt" )
my_file=open('my_file.txt')
my_file.seek(0)
my_file.readlines()'''
'''s='hello'
a=s[4]+s[3]+s[2]+s[1]+s[0]
print(a)
print(s[::-1])'''
'''n=int(input("Enter any number:"))
n=str(n)
... | Python | zaydzuhri_stack_edu_python |
function GetPublicKey self
begin
set ret = call createemptypublickey
set key = call import_key _key
call FromRSAKey call exportKey ret
return ret
end function | def GetPublicKey(self):
ret = self.createemptypublickey()
key = Crypto.PublicKey.RSA.import_key(self._key)
fiepipelib.encryption.public.publickey.FromRSAKey(key.publickey().exportKey(), ret)
return ret | Python | nomic_cornstack_python_v1 |
function get self
begin
set type = decode query_arguments at string type at 0 string utf-8
set unique_path = yield from call validate_path format string /export/{}.{} unique_key type
set local_cache_path = yield from call validate_path format string /export/{}.{} unique_key type
try
begin
set cached_stream = yield from... | def get(self):
type = self.request.query_arguments['type'][0].decode('utf-8')
unique_path = yield from self.cache_provider.validate_path('/export/{}.{}'.format(self.unique_key, type))
local_cache_path = yield from self.local_cache_provider.validate_path('/export/{}.{}'.format(self.unique_key, ty... | Python | nomic_cornstack_python_v1 |
function test_a2dp_streaming_slave_role_with_tcp_ul self
begin
if not call music_streaming_with_iperf
begin
return false
end
return true
end function | def test_a2dp_streaming_slave_role_with_tcp_ul(self):
if not self.music_streaming_with_iperf():
return False
return True | Python | nomic_cornstack_python_v1 |
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import numpy as np
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from minepy import MINE
import matplotlib.pyplot as plt
set x_raw = call loadtxt string ./data/feature_selection_X.txt
set y = call loadtxt string... | from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import numpy as np
from sklearn import linear_model
from sklearn.model_selection import train_test_split
from minepy import MINE
import matplotlib.pyplot as plt
x_raw=np.loadtxt('./data/feature_selection_X.txt')
y=np.loadtxt('./data/feature_selectio... | Python | zaydzuhri_stack_edu_python |
from string import ascii_lowercase
set chars = list ascii_lowercase
set chars = chars + list comprehension string i for i in range 10
comment print(c)
set count = dictionary
for c in chars
begin
with open string token_split_into_prefix/ { c } .txt string r as file
begin
set tokens = read lines file
set unique = set tok... | from string import ascii_lowercase
chars = list(ascii_lowercase)
chars = chars + [str(i) for i in range(10)]
# print(c)
count = dict()
for c in chars:
with open(f"token_split_into_prefix/{c}.txt", "r") as file:
tokens = file.readlines()
unique = set(tokens)
count[c] = len(unique)
for k, ... | Python | zaydzuhri_stack_edu_python |
function _K_computations self X X2
begin
comment First extract times and indices.
call _extract_t_indices X X2
call _K_compute_eq
call _K_compute_ode_eq
if X2 is none
begin
set _K_eq_ode = T
end
else
begin
call _K_compute_ode_eq transpose=true
end
call _K_compute_ode
if X2 is none
begin
set _K_dvar = zeros tuple shape ... | def _K_computations(self, X, X2):
# First extract times and indices.
self._extract_t_indices(X, X2)
self._K_compute_eq()
self._K_compute_ode_eq()
if X2 is None:
self._K_eq_ode = self._K_ode_eq.T
else:
self._K_compute_ode_eq(transpose=True... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split
set SEED = 2000
set x = text
set y = target
set tuple x_train x_v_t y_train y_v_t = train test split x y test_size=0.02 random_state=SEED
set tuple x_validation x_test y_validation y_test = train... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split
SEED = 2000
x = my_df.text
y = my_df.target
x_train, x_v_t, y_train, y_v_t = train_test_split(x, y, test_size=.02, random_state=SEED)
x_validation, x_test, y_validation, y_test = train_test_spli... | Python | zaydzuhri_stack_edu_python |
function test_Mercury self
begin
set expected_links = list string https://en.wikipedia.org/wiki/Chemical_element string https://en.wikipedia.org/wiki/Atomic_number string https://en.wikipedia.org/wiki/Heavy_metal_(chemistry) string https://en.wikipedia.org/wiki/D-block string https://en.wikipedia.org/wiki/Standard_cond... | def test_Mercury(self):
expected_links = ['https://en.wikipedia.org/wiki/Chemical_element',
'https://en.wikipedia.org/wiki/Atomic_number',
'https://en.wikipedia.org/wiki/Heavy_metal_(chemistry)',
'https://en.wikipedia.org/wiki/D-block... | Python | nomic_cornstack_python_v1 |
function isotope_pattern_match images_flat theor_iso_intensities
begin
set d1 = length images_flat
if d1 != length theor_iso_intensities
begin
raise call ValueError string amount of images and theoretical intensities must be equal
end
if any generator expression call shape im != call shape images_flat at 0 for im in im... | def isotope_pattern_match(images_flat, theor_iso_intensities):
d1 = len(images_flat)
if d1 != len(theor_iso_intensities):
raise ValueError("amount of images and theoretical intensities must be equal")
if any(np.shape(im) != np.shape(images_flat[0]) for im in images_flat):
raise ValueError("i... | Python | nomic_cornstack_python_v1 |
function populate self items
begin
for tuple name uid in items
begin
append self name uid
end
end function | def populate(self, items):
for name, uid in items:
self.append(name, uid) | Python | nomic_cornstack_python_v1 |
function _shape self df
begin
set tuple row col = shape
return tuple row + nlevels col + nlevels
end function | def _shape(self, df):
row, col = df.shape
return row + df.columns.nlevels, col + df.index.nlevels | Python | nomic_cornstack_python_v1 |
function test_msg_generation self
begin
try
begin
set record_str = call generate_json_message
end
except tuple Exception ValueError as error
begin
print error
assert false
end
assert call validate_record_format record_str
end function | def test_msg_generation(self):
try:
record_str = generate_json_message()
except (Exception, ValueError) as error:
print(error)
assert(False)
assert(validate_record_format(record_str)) | Python | nomic_cornstack_python_v1 |
function _sendBit port bit
begin
string Send an individual bit to the FireCracker module usr RTS/DTR.
if bit == string 0
begin
call _setRTSDTR port 0 1
end
else
if bit == string 1
begin
call _setRTSDTR port 1 0
end
else
begin
return
end
sleep bitDelay
call _setRTSDTR port 1 1
sleep bitDelay
end function | def _sendBit(port, bit):
"""Send an individual bit to the FireCracker module usr RTS/DTR."""
if bit == '0':
_setRTSDTR(port, 0, 1)
elif bit == '1':
_setRTSDTR(port, 1, 0)
else:
return
time.sleep(bitDelay)
_setRTSDTR(port, 1, 1)
time.sleep(bitDelay) | Python | jtatman_500k |
comment imports of external packages to use in our code
from scipy.optimize import minimize
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
comment from iminuit import Minuit
comment main function
if __name__ == string __main__
begin
function fcn x
be... | # imports of external packages to use in our code
from scipy.optimize import minimize
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
#from iminuit import Minuit
# main function
if __name__ == "__main__":
def fcn(x):
return (2 -... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Mar 25 13:54:45 2019 @author: Nataliya_Pavych
import argparse
import csv
import collections
import re
set parser = call ArgumentParser
call add_argument string -i string --input_file help=string name of input file
call add_argument string -c string --pattern_file help... | # -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 13:54:45 2019
@author: Nataliya_Pavych
"""
import argparse
import csv
import collections
import re
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_file', help='name of input file')
parser.add_argument('-c', '--pattern_file', help='name of file w... | Python | zaydzuhri_stack_edu_python |
function get_vehicle_info self vehicle_id
begin
set vehicle = get stock integer vehicle_id none
if vehicle
begin
return string { vehicle at string vehicle }
end
return string No vehicle with ID { vehicle_id } found.
end function | def get_vehicle_info(self, vehicle_id: str) -> str:
vehicle = self.stock.get(int(vehicle_id), None)
if vehicle:
return f'{vehicle["vehicle"]}'
return f'No vehicle with ID {vehicle_id} found.' | Python | nomic_cornstack_python_v1 |
function getqer self
begin
call tx self string QER?
set response = string <nr1><rmt>
return call rx self response
end function | def getqer(self):
TTiBase.tx(self, "QER?")
response = "<nr1><rmt>"
return TTiBase.rx(self, response) | Python | nomic_cornstack_python_v1 |
import numpy as np
from tensorflow.keras.models import Sequential , load_model
from tensorflow.keras.layers import Dense , LSTM
comment 1. 데이터
set a = array range 1 101
set size = 5
function split_x seq size
begin
set aaa = list
for i in range length seq - size + 1
begin
set subset = seq at slice i : i + size :
comme... | import numpy as np
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense,LSTM
#1. 데이터
a = np.array(range(1,101))
size = 5
def split_x(seq, size):
aaa = []
for i in range(len(seq) - size + 1):
subset = seq[i:(i+size)]
aaa.append(subset) #[item f... | Python | zaydzuhri_stack_edu_python |
function unauthenticated_action self
begin
return get pulumi self string unauthenticated_action
end function | def unauthenticated_action(self) -> str:
return pulumi.get(self, "unauthenticated_action") | Python | nomic_cornstack_python_v1 |
function __calculate_sensitivity self
begin
set tuple num oldage = tuple 0 - decimal string inf
set ageidx = index ATTNAME string age
for record in records
begin
if record at ageidx > 25
begin
set num = num + 1
if record at ageidx > oldage
begin
set oldage = record at ageidx
end
end
end
return oldage / num
end function | def __calculate_sensitivity(self):
num, oldage = 0, -float('inf')
ageidx = ATTNAME.index('age')
for record in self.records:
if record[ageidx] > 25:
num += 1
if record[ageidx] > oldage:
oldage = record[ageidx]
return oldage ... | Python | nomic_cornstack_python_v1 |
string Eric Goodwin 09-17-2018 Python 3.7.0 PyCharm IDE CS 4500 Introduction to the Software Profession External Files created - H3goodwinOutfile.txt Program creates this file with output data. data is same as what is displayed on the screen running of the program. Resources Used: https://docs.python.org/3/library http... | '''
Eric Goodwin
09-17-2018
Python 3.7.0
PyCharm IDE
CS 4500 Introduction to the Software Profession
External Files created - H3goodwinOutfile.txt
Program creates this file with output data. data is same as what
is displayed on the screen running of the program.
Resources Used:
https://docs.python.org/3/library
htt... | Python | zaydzuhri_stack_edu_python |
function _refeed_out_as_input outputarray
begin
comment TODO: fix me
set ux_temp = outputarray at tuple slice : : 0 0
set uy_temp = outputarray at tuple slice : : 0 1
set uz_temp = outputarray at tuple slice : : 0 2
set varx_temp = outputarray at tuple slice : : 0 3
set vary_temp = outputarray at tuple slic... | def _refeed_out_as_input(outputarray):
# TODO: fix me
ux_temp = outputarray[:,0,0]
uy_temp = outputarray[:,0,1]
uz_temp = outputarray[:,0,2]
varx_temp = outputarray[:,0,3]
vary_temp = outputarray[:,0,4]
varz_temp = outputarray[:,0,5]
temp_newdata = np.stack((generate_fake_batch(ux_temp,v... | Python | nomic_cornstack_python_v1 |
function run
begin
comment Create main parsers.
set parser = call ArgumentParser
set subparsers = call add_subparsers
comment Setup 'rosaction list' command.
set list_parser = call add_parser string list
call set_defaults func=print_action_list
comment Setup 'rosaction send' command.
set send_parser = call add_parser s... | def run():
# Create main parsers.
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
# Setup 'rosaction list' command.
list_parser = subparsers.add_parser("list")
list_parser.set_defaults(func=print_action_list)
# Setup 'rosaction send' command.
send_parser = subpa... | Python | nomic_cornstack_python_v1 |
import yaml
from itertools import groupby
function main
begin
with open string short.yaml as file
begin
set yml = load yaml file Loader=BaseLoader
end
set images = yml at string MonoBehaviour at string m_Images
set good_images = list comprehension i for i in images if integer i at string Quality > 70
set sorted_good_im... | import yaml
from itertools import groupby
def main():
with open('short.yaml') as file:
yml = yaml.load(file, Loader=yaml.BaseLoader)
images = yml['MonoBehaviour']['m_Images']
good_images = [i for i in images if int(i['Quality']) > 70]
sorted_good_images = sorted(good_images, key = lambda i: i[... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.