code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function func_greater self left right
begin
comment Evaluate the expressions numerically.
set left = evaluate self left
set right = evaluate self right
set tuple x y = tuple call num left call num right
comment Return 1 or 0 depending on their relative size.
if x > y
begin
return string ace
end
else
begin
return string... | def func_greater(self, left, right):
# Evaluate the expressions numerically.
left = self.evaluate(left)
right = self.evaluate(right)
x, y = self.lexicon.num(left), self.lexicon.num(right)
# Return 1 or 0 depending on their relative size.
if x > y:
return 'ace'
else:
return 'bozo' | Python | nomic_cornstack_python_v1 |
set a = integer input string determine uma quantidade de dias
set b = integer input string determine uma quantidade de horas
set c = integer input string determine uma quantidade de minutos
set d = integer input string determine uma quantidade de segundos
set x = a * 86400 + b * 3600 + c * 60 + d
print x | a=int(input("determine uma quantidade de dias"))
b=int(input("determine uma quantidade de horas"))
c=int(input("determine uma quantidade de minutos"))
d=int(input("determine uma quantidade de segundos"))
x=a*86400+b*3600+c*60+d
print(x)
| Python | zaydzuhri_stack_edu_python |
comment tools function
function createLetters word
begin
set letterList = list
for iLetter in range 0 length word - 1
begin
if word at iLetter not in letterList
begin
append letterList word at iLetter
end
end
return letterList
end function
function getOccurences word letterList
begin
set letterOccurence = list
for iL... | #tools function
def createLetters(word):
letterList=[]
for iLetter in range(0,len(word)-1):
if word[iLetter] not in letterList:
letterList.append(word[iLetter])
return letterList
def getOccurences(word,letterList):
letterOccurence=[]
for iLetter in range(0,len(letterList)):
letterOccurence.append(word.co... | Python | zaydzuhri_stack_edu_python |
function DP n k
begin
if k == 0
begin
return 1
end
else
if n < 10 and k == 1
begin
return n
end
else
if n < 10 and k != 0
begin
return 0
end
else
begin
set tuple q r = tuple n // 10 n % 10
return call DP q k + r * call DP q k - 1 + 9 - r * call DP q - 1 k - 1
end
end function
set n = integer input
set k = integer input... | def DP(n, k):
if k == 0:
return 1
elif n < 10 and k == 1:
return n
elif n < 10 and k != 0:
return 0
else:
q, r = n//10, n % 10
return DP(q, k)+r*DP(q, k-1)+(9-r)*DP(q-1, k-1)
n = int(input())
k = int(input())
print(DP(n, k))
| Python | zaydzuhri_stack_edu_python |
comment untuk membuat comment, bisa diblok terus ctrl+/(slash)
set decimal = 90.8
print type decimal
set decimalToInt = integer decimal
print type decimalToInt
print decimalToInt
set bilanganBulat = 98
print bilanganBulat
set integerToDecimal = decimal bilanganBulat
print type integerToDecimal
print integerToDecimal
se... | #untuk membuat comment, bisa diblok terus ctrl+/(slash)
decimal=90.8
print(type(decimal))
decimalToInt = int(decimal)
print(type(decimalToInt))
print(decimalToInt)
bilanganBulat = 98
print(bilanganBulat)
integerToDecimal = float(bilanganBulat)
print(type(integerToDecimal))
print(integerToDecimal)
number=10
print(n... | Python | zaydzuhri_stack_edu_python |
function format_link link
begin
set p = compile string (\/web\/[0-9]+\/)
for m in call finditer link
begin
set to_rep = link at slice start m : call end : at slice : - 1 : + string if_/
set new_str = link at slice : start m : + to_rep + link at slice call end : :
comment only need first occurrence
return new_str... | def format_link(link):
p = re.compile('(\/web\/[0-9]+\/)')
for m in p.finditer(link):
to_rep = link[m.start():m.end()][:-1] + "if_/"
new_str = link[:m.start()] + to_rep + link[m.end():]
# only need first occurrence
return new_str
# return original if already formatted
ret... | Python | nomic_cornstack_python_v1 |
function virtual_networks self
begin
return get pulumi self string virtual_networks
end function | def virtual_networks(self) -> Optional[pulumi.Input['AzureIntegrationsVirtualNetworksArgs']]:
return pulumi.get(self, "virtual_networks") | Python | nomic_cornstack_python_v1 |
async function on_message self message
begin
if string purge in content
begin
return
end
if call mentioned_in message
begin
set lang = call getLang id
with open string serverconfig/prefixes.json string r as f
begin
set prefix = load json f at string id
end
with open string embeds/ { lang } /mentionPrefix.json string r ... | async def on_message(self, message: discord.Message):
if "purge" in message.content:
return
if self.client.user.mentioned_in(message):
lang = functions.getLang.getLang(message.guild.id)
with open("serverconfig/prefixes.json", "r") as f:
prefix = json.l... | Python | nomic_cornstack_python_v1 |
function plot_vector_field vtk_data vector_solution_component=0 axes=none **kwargs
begin
set point_data = call vtk_to_numpy call GetData
set x = point_data at tuple slice : : 0
set y = point_data at tuple slice : : 1
set u = call vtk_to_numpy call GetArray vector_solution_component
if axes is none
begin
set tuple... | def plot_vector_field(vtk_data, vector_solution_component = 0, axes = None,
**kwargs):
point_data = vtk_to_numpy(vtk_data.GetPoints().GetData())
x = point_data[:,0]
y = point_data[:,1]
u = vtk_to_numpy(vtk_data.GetPointData().GetArray(
vector_solution_component))
... | Python | nomic_cornstack_python_v1 |
from getting_information import get_params
from getting_field import get_field
import numpy
import copy
set field = list list string . string . string . string . string # string . string . string . string . list string . string . string . string . string . string . string . string . string . list string . string . stri... | from getting_information import get_params
from getting_field import get_field
import numpy
import copy
field = [[".", ".", ".", ".", "#", ".", ".", ".", "."],
[".", ".", ".", ".", ".", ".", ".", ".", "."],
[".", ".", ".", ".", "#", ".", "#", "#", "#"],
[".", ".", ".", ".", "#", ".... | Python | zaydzuhri_stack_edu_python |
function build_xanthos_configs model_list scenario_list output_dir n_configs xanthos_root_dir xanthos_output_dir drought_thresholds_dir xanthos_output_variables=string q pet_model_abbrev=none runoff_model_abbrev=none router_model_abbrev=none template=none generate_drought_stats=0
begin
comment use default configuration... | def build_xanthos_configs(model_list, scenario_list, output_dir, n_configs, xanthos_root_dir, xanthos_output_dir,
drought_thresholds_dir, xanthos_output_variables='q', pet_model_abbrev=None,
runoff_model_abbrev=None, router_model_abbrev=None, template=None,
... | Python | nomic_cornstack_python_v1 |
function add_dynamic_constraint self var des
begin
for i in range length var
begin
call AddConstraint var at i <= des at i + slack
call AddConstraint var at i >= des at i - slack
end
end function | def add_dynamic_constraint(
self, var: Union[np.ndarray, object], des: Union[np.ndarray, object]
) -> None:
for i in range(len(var)):
self.program.AddConstraint(var[i] <= des[i] + self.slack)
self.program.AddConstraint(var[i] >= des[i] - self.slack) | Python | nomic_cornstack_python_v1 |
import torch
from accuracy import calculate_accuracy
comment check if CUDA is available
set train_on_gpu = call is_available
comment define our training loop.
function train model iterator optimizer criterion
begin
set epoch_loss = 0
set epoch_acc = 0
train model
for tuple data target in iterator
begin
comment move ten... | import torch
from accuracy import calculate_accuracy
# check if CUDA is available
train_on_gpu = torch.cuda.is_available()
#define our training loop.
def train(model, iterator, optimizer, criterion):
epoch_loss = 0
epoch_acc = 0
model.train()
for (data, target) in iterator:
... | Python | zaydzuhri_stack_edu_python |
function __init__ self data_protocols=none ip_address=none name=none
begin
comment Initialize members of the class
set data_protocols = data_protocols
set ip_address = ip_address
set name = name
end function | def __init__(self,
data_protocols=None,
ip_address=None,
name=None,
):
# Initialize members of the class
self.data_protocols = data_protocols
self.ip_address = ip_address
self.name = name | Python | nomic_cornstack_python_v1 |
for i in range 3 N + 1
begin
set dp at i = dp at i - 1 + dp at i - 2
end
print dp at - 1 % 10007 | for i in range(3,N+1):
dp[i] = dp[i-1] + dp[i-2]
print(dp[-1] % 10007) | Python | zaydzuhri_stack_edu_python |
import json
import numpy as np
import networkx as nx
from core.apiWeightedGraph import apiGraph
class NodeKeyset
begin
function __init__ self graph keywords api_categories
begin
set graph = graph
set keywords = keywords
set api_categories = api_categories
end function
function calcKeySet self v keywords num_of_keywords... | import json
import numpy as np
import networkx as nx
from core.apiWeightedGraph import apiGraph
class NodeKeyset:
def __init__(self, graph, keywords, api_categories):
self.graph = graph
self.keywords = keywords
self.api_categories = api_categories
def calcKeySet(self, v, key... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as pyplot
import matplotlib.backends.backend_pdf as backend_pdf
import numpy
import json
from enum import Enum
from common_plots import *
set TITLE_FONTSIZE = 9
comment Plots a histogram of a json attribute.
function plot_histogram_priorities data
begin
set f = figure
set x = list comprehension... | import matplotlib.pyplot as pyplot
import matplotlib.backends.backend_pdf as backend_pdf
import numpy
import json
from enum import Enum
from common_plots import *
TITLE_FONTSIZE = 9
# Plots a histogram of a json attribute.
def plot_histogram_priorities(data):
f = pyplot.figure()
x = [point['priorities'] for... | Python | zaydzuhri_stack_edu_python |
function _make_item message translation sources comment status
begin
set entry = none
if message is not none and message != string and translation is not none
begin
comment both the message and its translation are escaped in the PO file;
comment we need to undo this before storing the strings in the
comment translatio... | def _make_item(message, translation, sources, comment, status):
entry = None
if (message is not None) and (message != "") and (translation is not None):
# both the message and its translation are escaped in the PO file;
# we need to undo this before storing the strings in the
# translat... | Python | nomic_cornstack_python_v1 |
function set_training_data self inputs outputs
begin
set _output_column = columns at 0
set _label_encoder = call LabelEncoder
set labels = fit transform _label_encoder call ravel
set _value_counts = value counts outputs at _output_column
set _nclasses = shape at 0
if _nclasses == 2
begin
set _nclasses = 1
end
set tuple... | def set_training_data(self, *, inputs: Inputs, outputs: Outputs) -> None:
self._output_column = outputs.columns[0]
self._label_encoder = LabelEncoder()
labels = self._label_encoder.fit_transform(outputs.values.ravel())
self._value_counts = outputs[self._output_column].value_counts()
... | Python | nomic_cornstack_python_v1 |
function prepare_puzzle puzzle
begin
return list comprehension integer n for n in puzzle at 0
end function
function move_cups puzzle moves
begin
set cups = dictionary comprehension n : if expression i + 1 < length puzzle then puzzle at i + 1 else puzzle at 0 for tuple i n in enumerate puzzle
set current_cup = puzzle at... | def prepare_puzzle(puzzle):
return [int(n) for n in puzzle[0]]
def move_cups(puzzle, moves):
cups = {n: puzzle[i+1] if i+1 < len(puzzle) else puzzle[0] for i, n in enumerate(puzzle)}
current_cup = puzzle[0]
for _ in range(moves):
cup1 = cups[current_cup]
cup2 = cups[cup1]
cup3 =... | Python | zaydzuhri_stack_edu_python |
import sys
import pygame
class Ship
begin
function __init__ self screen
begin
set screen = screen
set image = load image string images/ship.bmp
set rect = call get_rect
set screen_rect = call get_rect
set centerx = centerx
set bottom = bottom
end function
function blitme self
begin
call blit image rect
end function
end... | import sys
import pygame
class Ship():
def __init__(self, screen):
self.screen = screen
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.rect.centerx = self.screen_rect.centerx
self.rect.bott... | Python | zaydzuhri_stack_edu_python |
function read_md5sum param
begin
set DEFAULT_PARAM = dict string in_file none
comment File in which we want to read the md5sum
set in_file = call get_value string in_file param DEFAULT_PARAM
with open in_file string r as fin
begin
set md5sum = read fin
end
return md5sum
end function | def read_md5sum(param):
DEFAULT_PARAM = {
# File in which we want to read the md5sum
'in_file': None,
}
in_file = get_value('in_file', param, DEFAULT_PARAM)
with open(in_file, 'r') as fin:
md5sum = fin.read()
return md5sum | Python | nomic_cornstack_python_v1 |
function check_files_exist self is_subclass_calling=true
begin
comment NB: Should all be files, not directories
comment List of lists. Passes if any of the files in the sublist are found.
set files_fail = list list string Dockerfile list string cookietemple.cfg list string Makefile list string README.rst list string LI... | def check_files_exist(self, is_subclass_calling=True):
# NB: Should all be files, not directories
# List of lists. Passes if any of the files in the sublist are found.
files_fail = [
['Dockerfile'],
['cookietemple.cfg'],
['Makefile'],
['README.rst... | Python | nomic_cornstack_python_v1 |
for i in range c
begin
set tuple a b = map str split input
if a > b
begin
set n = n + 3
end
else
if a < b
begin
set m = m + 3
end
else
begin
set n = n + 1
set m = m + 1
end
end
print n m | for i in range(c):
a,b=map(str,input().split())
if a>b:
n+=3
elif a<b:
m+=3
else:
n+=1
m+=1
print(n,m)
| Python | zaydzuhri_stack_edu_python |
string Your task is to create a function - basic_op(). The function should take three arguments operation(string/char), value1(number), value2(number). The function should return result of numbers after applying the chosen operation.
comment %%
function basic_op operator value1 value2
begin
set d = dict string + value1... | """
Your task is to create a function - basic_op().
The function should take three arguments
operation(string/char), value1(number), value2(number).
The function should return result of numbers after applying
the chosen operation.
"""
# %%
def basic_op(operator, value1, value2):
d = {
'+':value1+value2,
... | Python | zaydzuhri_stack_edu_python |
function downward_api self
begin
return get pulumi self string downward_api
end function | def downward_api(self) -> Optional['outputs.DownwardAPIVolumeSource']:
return pulumi.get(self, "downward_api") | Python | nomic_cornstack_python_v1 |
function get_fields file_lines
begin
set fields = dict
set fields at string content_type_tag = file_lines at 1
set law_name = file_lines at 2
set fields at string law_name = law_name
comment Get law number & exact date from the name
set law_num = split law_name at 1
set law_exact_date = split law_name at 3
set law_num... | def get_fields(file_lines):
fields = {}
fields["content_type_tag"] = file_lines[1]
law_name = file_lines[2]
fields["law_name"] = law_name
# Get law number & exact date from the name
law_num = law_name.split()[1]
law_exact_date = law_name.split()[3]
law_num_date = law_num + '_' + law_exact_date
fi... | Python | nomic_cornstack_python_v1 |
function preprocess_adj adj
begin
comment A_~
set adj_normalized = call normalize_adj adj + call eye shape at 0
return call sparse_to_tensor adj_normalized
end function | def preprocess_adj(adj):
adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0])) # A_~
return sparse_to_tensor(adj_normalized) | Python | nomic_cornstack_python_v1 |
async function help_command ctx *args
begin
if args
begin
await call specific_help ctx *args
end
else
begin
await call general_help ctx
end
end function | async def help_command(ctx, *args):
if args:
await specific_help(ctx, *args)
else:
await general_help(ctx) | Python | nomic_cornstack_python_v1 |
from random import randint
from random import randrange
import winsound
import time
while true
begin
call Beep call randrange 300 2000 random integer 100 500
sleep call randrange 0 500 / 1000
end | from random import randint
from random import randrange
import winsound
import time
while True:
winsound.Beep(randrange(300, 2000), randint(100, 500))
time.sleep((randrange(0, 500)/1000))
| Python | zaydzuhri_stack_edu_python |
function average_orientation orientations
begin
raise call NotImplementedError
end function | def average_orientation(orientations):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function load_from_json_word_list self json_file_name
begin
assert exists path json_file_name
comment load dictionary from json
with open json_file_name string r as fp
begin
set word_list = load json fp
end
comment set of all words
set word_set = set word_list
for tuple nb_words word in enumerate word_set
begin
call _a... | def load_from_json_word_list(self, json_file_name: str):
assert os.path.exists(json_file_name)
# load dictionary from json
with open(json_file_name, 'r') as fp:
word_list = json.load(fp)
word_set = set(word_list) # set of all words
for nb_words, word in enumerate(w... | Python | nomic_cornstack_python_v1 |
string Title : 271. Encode and Decode Strings ($$$) (XXX) Problem : https://leetcode.com/problems/remove-duplicate-letters/ : https://www.lintcode.com/problem/encode-and-decode-strings/description
string Reference: https://baihuqian.github.io/2018-07-28-encode-and-decode-strings/
class Solution
begin
function encode se... | '''
Title : 271. Encode and Decode Strings ($$$) (XXX)
Problem : https://leetcode.com/problems/remove-duplicate-letters/
: https://www.lintcode.com/problem/encode-and-decode-strings/description
'''
''' Reference: https://baihuqian.github.io/2018-07-28-encode-and-decode-strings/ '''
class Solution:
d... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Mon Apr 23 13:13:54 2018 @author: vinit.shah1ibm.com
comment Load Libraries and Data ######################
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import *
import seaborn as sns
from matplotlib impo... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 23 13:13:54 2018
@author: vinit.shah1ibm.com
"""
###################### Load Libraries and Data ######################
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import *
import seaborn as sns
from matplotlib ... | Python | zaydzuhri_stack_edu_python |
import pygame
import sys
import random
call init
class Coin extends Sprite
begin
function __init__ self
begin
call __init__ self
set coins = call OrderedUpdates
for i in range 20
begin
set image = load image string final_images/coin62.png
end
end function
end class | import pygame
import sys
import random
pygame.init()
class Coin(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
coins = pygame.sprite.OrderedUpdates()
for i in range(20):
self.image = pygame.image.load('final_images/coin62.png') | Python | zaydzuhri_stack_edu_python |
function email_integrations self
begin
return get pulumi self string email_integrations
end function | def email_integrations(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['NotificationPolicyEmailIntegrationArgs']]]]:
return pulumi.get(self, "email_integrations") | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup
function scrape_website url
begin
set response = get requests url
set soup = call BeautifulSoup text string html.parser
set links = find all soup string a
set url_counts = dict
for link in links
begin
set url = get link string href
if starts with url string http:// or star... | import requests
from bs4 import BeautifulSoup
def scrape_website(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
links = soup.find_all('a')
url_counts = {}
for link in links:
url = link.get('href')
if url.startswith('http://') or url.startswith... | Python | greatdarklord_python_dataset |
comment INSTALLATION/PREP ################
comment This is a DEMO to demonstrate the classifiers we learned about
comment in CSI 431 @ UAlbany Fall'18
comment Might need to install the latest scikit-learn
comment On linux or Mac: sudo pip install -U scikit-learn
comment Codebase with more classifiers here:
comment http... | ############################### INSTALLATION/PREP ################
# This is a DEMO to demonstrate the classifiers we learned about
# in CSI 431 @ UAlbany Fall'18
#
# Might need to install the latest scikit-learn
# On linux or Mac: sudo pip install -U scikit-learn
#
# Codebase with more classifiers here:
# http... | Python | zaydzuhri_stack_edu_python |
import string
import logging
import re
set logger = call getLogger __name__
call basicConfig format=string %(asctime)-15s: %(message)s level=INFO
info string Start
with open string input5.txt as f
begin
set polymer = strip read f
end
function scan accum cur
begin
if accum
begin
set prev = accum at - 1
if upper prev == ... | import string
import logging
import re
logger = logging.getLogger(__name__)
logging.basicConfig(format='%(asctime)-15s: %(message)s', level=logging.INFO)
logger.info("Start")
with open('input5.txt') as f:
polymer = f.read().strip()
def scan(accum, cur):
if accum:
prev = accum[-1]
if prev.upper... | Python | zaydzuhri_stack_edu_python |
function _getBaselineValue self name
begin
set obj = call _CS_getObjectByName settings name
if call isscalar obj
begin
return obj
end
else
begin
raise call ConvergenceScanException format string Unrecognized type of input parameter '{}': {}. name type obj
end
end function | def _getBaselineValue(self, name):
obj = _CS_getObjectByName(self.settings, name)
if np.isscalar(obj):
return obj
else:
raise ConvergenceScanException("Unrecognized type of input parameter '{}': {}.".format(name, type(obj))) | Python | nomic_cornstack_python_v1 |
function check_int x
begin
if is instance x int
begin
return x
end
if not call isdecimal
begin
raise call RuntimeError format string {} is not a decimal number x
end
return integer x
end function | def check_int(x):
if isinstance(x, int):
return x
if not x.isdecimal():
raise RuntimeError("{} is not a decimal number".format(x))
return int(x) | Python | nomic_cornstack_python_v1 |
function _Renew self client
begin
function _OnException type value tb
begin
string If failure occurs during renewal, just abandon the lock.
error string failure trying to renew lock "%s" exc_info=tuple type value tb
end function
function _OnRenewalTimeout
begin
set _timeout = none
if not _renewing
begin
return
end
info... | def _Renew(self, client):
def _OnException(type, value, tb):
"""If failure occurs during renewal, just abandon the lock."""
logging.error('failure trying to renew lock "%s"', exc_info=(type, value, tb))
def _OnRenewalTimeout():
self._timeout = None
if not self._renewing:
... | Python | nomic_cornstack_python_v1 |
try
begin
write fh string I love Python Programming!
end
finally
begin
close fh
end
comment Sample code(2) Write using with statement
with open string sample_log.txt string w as fh
begin
write fh string I love Python even more!!
end | try:
fh.write("I love Python Programming!")
finally:
fh.close()
# Sample code(2) Write using with statement
with open("sample_log.txt", "w") as fh:
fh.write("I love Python even more!!")
| Python | zaydzuhri_stack_edu_python |
function extract_source source_archive target
begin
with open source_archive as tar_file
begin
call safetar_extractall tar_file target
end
end function | def extract_source(source_archive, target):
with tarfile.open(source_archive) as tar_file:
safetar_extractall(tar_file, target) | Python | nomic_cornstack_python_v1 |
function initialize self
begin
set currState = startState
end function | def initialize(self):
self.currState = self.startState | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sun May 2 20:08:59 2021 @author: Admin
print string hello world
print string pranay abhi
print string hello world
print string hello double backflash\\
print string helllo
print string hello'bay
print string hello"pranay'hm
comment this is commentanay
print string hello\... | # -*- coding: utf-8 -*-
"""
Created on Sun May 2 20:08:59 2021
@author: Admin
"""
print("hello world")
print("pranay \n abhi")
print("hello\tworld")
print("hello double backflash\\\\")
print("hel\bllo")
print("hello'bay")
print('''hello"pranay'hm''')
#this is commentanay
print("hello\\npr")
... | Python | zaydzuhri_stack_edu_python |
function merge_tbl tbl1 tbl2 outpath=string
begin
set tbl = list
for i in range length tbl1
begin
if i < length tbl2
begin
set c = tbl2 at i at 1
end
else
begin
set c = string ・
end
append tbl tuple tbl1 at i at 0 c
end
if outpath != string
begin
call dump_tbl tbl outpath
end
print string tbl1 + string length tbl1 + ... | def merge_tbl(tbl1: List[Tuple[bytes, str]],
tbl2: List[Tuple[bytes, str]], outpath=r"")\
-> List[Tuple[bytes, str]]:
tbl = []
for i in range(len(tbl1)):
if i < len(tbl2): c= tbl2[i][1]
else: c='・'
tbl.append((tbl1[i][0], c))
if outpath!="": dump_tbl(tbl, outpath... | Python | nomic_cornstack_python_v1 |
function map_feature x1 x2 degree
begin
set mapped = ones tuple length x1 1
for i in range 1 degree + 1
begin
for j in range i + 1
begin
set mapped = concatenate tuple mapped x1 ^ i - j * x2 ^ j axis=1
end
end
return mapped
end function | def map_feature(x1, x2, degree):
mapped = np.ones((len(x1), 1))
for i in range(1,degree+1):
for j in range(i+1):
mapped = np.concatenate((mapped, (x1**(i-j)*x2**j)),axis = 1)
return mapped | Python | nomic_cornstack_python_v1 |
comment HackerRank. Python Challenge, also Day 3 of 30 day coding challenge.
comment if n is odd, it's weird. if it is even and (6 >= N >= 20), it's weird.
comment !/bin/python3
import math
import os
import random
import re
import sys
if __name__ == string __main__
begin
set N = integer input
comment odd
if N % 2 == 1
... | #HackerRank. Python Challenge, also Day 3 of 30 day coding challenge.
#if n is odd, it's weird. if it is even and (6 >= N >= 20), it's weird.
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
N = int(input())
if (N % 2 == 1): #odd
print("Weird")
el... | Python | zaydzuhri_stack_edu_python |
function poly2lsf a
begin
comment Line spectral frequencies are not defined for complex polynomials.
comment Normalize the polynomial
set a = array a
if a at 0 != 1
begin
set a = a / a at 0
end
if max absolute call roots a >= 1.0
begin
error string The polynomial must have all roots inside of the unit circle.
end
comme... | def poly2lsf(a):
#Line spectral frequencies are not defined for complex polynomials.
# Normalize the polynomial
a = np.array(a)
if a[0] != 1:
a/=a[0]
if max(np.abs(np.roots(a))) >= 1.0:
error('The polynomial must have all roots inside of the unit circle.');
# Form the sum a... | Python | nomic_cornstack_python_v1 |
function load_json_settings filename
begin
set filepath = call joinpath filename
if exists filepath
begin
with open filepath mode=string r as f
begin
set data = load json f
end
return data
end
else
begin
call save_json_settings filename dict
return dict
end
end function | def load_json_settings(filename: str):
filepath = TEMP_DIR.joinpath(filename)
if filepath.exists():
with open(filepath, mode='r') as f:
data = json.load(f)
return data
else:
save_json_settings(filename, {})
return {} | Python | nomic_cornstack_python_v1 |
function sumAll start end
begin
set sum = 0
for start in range end + 1
begin
set sum = sum + start
end
print string %d부터 %d까지의 합은 %d 입니다. % tuple 1 10 sum
end function
call sumAll 1 10 | def sumAll(start, end):
sum=0
for start in range(end+1):
sum+=start
print("%d부터 %d까지의 합은 %d 입니다."%(1,10,sum))
sumAll(1,10)
| Python | zaydzuhri_stack_edu_python |
function is_index_valid string_line current_index
begin
if 0 <= current_index < length string_line
begin
return true
end
end function
function add_stop_command string_line get_info
begin
set tuple index string_to_insert = get_info
set index = integer index
if call is_index_valid string_line index
begin
set string_line ... | def is_index_valid(string_line, current_index):
if 0 <= current_index < len(string_line):
return True
def add_stop_command(string_line, get_info):
index, string_to_insert = get_info
index = int(index)
if is_index_valid(string_line, index):
string_line = string_line[:index] + string_to_... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from optimal_control_framework.costs.obstacle import SphericalObstacle
import numpy as np
class BufferedSphericalObstacle extends SphericalObstacle
begin
comment Principal axes (R.T), semi_major_axes
set buffer_ellipsoid = none
comment Inflate ellipsoids
set sigma_inflation = 1
set n = none... | #!/usr/bin/env python
from optimal_control_framework.costs.obstacle import SphericalObstacle
import numpy as np
class BufferedSphericalObstacle(SphericalObstacle):
buffer_ellipsoid = None # Principal axes (R.T), semi_major_axes
sigma_inflation = 1 # Inflate ellipsoids
n = None
def __init__(self, cen... | Python | zaydzuhri_stack_edu_python |
import time
from multiprocessing import Queue
from multiprocessing.managers import BaseManager
comment 从机类
class Slave
begin
function __init__ self
begin
comment 派发出去的任务队列
set dispatched_task_queue = queue
comment 完成的任务队列
set finished_task_queue = queue
end function
function start self
begin
comment 把派发任务队列和完成任务队列注册到网络... | import time
from multiprocessing import Queue
from multiprocessing.managers import BaseManager
#从机类
class Slave:
def __init__(self):
# 派发出去的任务队列
self.dispatched_task_queue = Queue()
# 完成的任务队列
self.finished_task_queue = Queue()
def start(self):
# 把派发任务队列和完成任务队列注册到网络上
... | Python | zaydzuhri_stack_edu_python |
from funkcje import suuma_cyfr
set plik = open string /Users/jakubchudon/Desktop/matury/2012_podstawa/cyfry.txt
set min = 90
set maks = 0
for linia in plik
begin
set linia = integer strip linia
set x = call suuma_cyfr linia
if x > call suuma_cyfr maks
begin
set maks = linia
end
if x < call suuma_cyfr min
begin
set min ... | from funkcje import suuma_cyfr
plik=open('/Users/jakubchudon/Desktop/matury/2012_podstawa/cyfry.txt')
min=90
maks=0
for linia in plik:
linia=int(linia.strip())
x=suuma_cyfr(linia)
if x>suuma_cyfr(maks):
maks=linia
if x<suuma_cyfr(min):
min=linia
print(min,maks)
| Python | zaydzuhri_stack_edu_python |
function _args_for_gen_ode_func self
begin
set args = tuple forcing_full coordinates speeds constants_symbols
return args
end function | def _args_for_gen_ode_func(self):
args = (self.eom_method.forcing_full,
self.coordinates,
self.speeds,
self.constants_symbols)
return args | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string Implementation of Fast Fourier Transform method for European call options. This module provides: 1. Classes for the Geometric Brownian Motion and Variance Gamma processes 2. Call option pricing functions for Monte Carlo, Fourier Inversion and Fast Fourier transform methods 3. Price a... | #!/usr/bin/env python
"""Implementation of Fast Fourier Transform method for European call options.
This module provides:
1. Classes for the Geometric Brownian Motion and Variance Gamma processes
2. Call option pricing functions for Monte Carlo, Fourier Inversion and
Fast Fourier transform method... | Python | zaydzuhri_stack_edu_python |
function test_search_seminar self
begin
set response = get client string /api/search.json?q=example
assert equal status_code HTTP_200_OK
assert equal data at string count 2
end function | def test_search_seminar(self):
response = self.client.get('/api/search.json?q=example')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data['count'], 2) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import random
function generate_code code_len=4
begin
string Generate verification code of specified length :param code_len: Verification code length (default 4 characters) :return: Random verification code composed of uppercase and lowercase English letters and numbers
set all_chars = str... | #!/usr/bin/env python3
import random
def generate_code(code_len=4):
'''
Generate verification code of specified length
:param code_len: Verification code length (default 4 characters)
:return: Random verification code composed of uppercase and lowercase \
English letters and numbers
... | Python | zaydzuhri_stack_edu_python |
function _set_fflags target fc=string gfortran argv=true osname=none verbose=false
begin
set fflags = none
if fc is not none
begin
set fflags = list
comment get lower case OS string
if osname is none
begin
set osname = call _get_osname
end
comment remove target .exe extension, if necessary
set target = call _get_base_... | def _set_fflags(target, fc="gfortran", argv=True, osname=None, verbose=False):
fflags = None
if fc is not None:
fflags = []
# get lower case OS string
if osname is None:
osname = _get_osname()
# remove target .exe extension, if necessary
target = _get_base_a... | Python | nomic_cornstack_python_v1 |
function rollback self
begin
comment TODO needs a unit test
rollback conn
end function | def rollback(self):
# TODO needs a unit test
self.conn.rollback() | Python | nomic_cornstack_python_v1 |
function combine_feature target_body tool_bodies operation
begin
comment Get Combine Features
set combine_features = combineFeatures
comment Define a collection and add all tool bodies to it
set combine_tools = call create
for tool in tool_bodies
begin
comment todo add error checking
add combine_tools tool
end
comment ... | def combine_feature(target_body: adsk.fusion.BRepBody, tool_bodies: List[adsk.fusion.BRepBody],
operation: adsk.fusion.FeatureOperations):
# Get Combine Features
combine_features = target_body.parentComponent.features.combineFeatures
# Define a collection and add all tool bodies to it
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1: 输入: ["flower","flow","flight"] 输出: "fl" 示例 2: 输入: ["dog","racecar","car"] 输出: "" 解释: 输入不存在公共前缀。 说明: 所有输入只包含小写字母 a-z 。 链接:https://leetcode-cn.com/problems/longest-common-prefix
class Solution extends object
begin
function longestComm... | # -*- coding: utf-8 -*-
'''
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""。
示例 1:
输入: ["flower","flow","flight"]
输出: "fl"
示例 2:
输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。
说明:
所有输入只包含小写字母 a-z 。
链接:https://leetcode-cn.com/problems/longest-common-prefix
'''
class Solution(object):
def longestCommonPrefix(... | Python | zaydzuhri_stack_edu_python |
function _OctaveFromString cls notestring
begin
if notestring == none
begin
return string
end
set notestring = strip notestring
set index = - 1
if length notestring <= 1
begin
comment No octave specified
return _DEFAULT_OCTAVE
end
else
begin
set n = 1
while n < length notestring
begin
set c = notestring at n
if call _... | def _OctaveFromString(cls, notestring):
if notestring == None:
return ""
notestring = notestring.strip()
index = -1
if len(notestring) <= 1:
# No octave specified
return _DEFAULT_OCTAVE
else:
n = 1
while n < len(notestri... | Python | nomic_cornstack_python_v1 |
import numpy as np
import random
comment одномерный массив из 12 случайных чисел от 1 до 1000
set mat = array random sample range 1000 12
comment превратим w в трёхмерную матрицу
set mat = reshape mat tuple 2 2 3
set mat = reshape mat tuple 12 1
print mat | import numpy as np
import random
mat = np.array(random.sample(range(1000), 12)) # одномерный массив из 12 случайных чисел от 1 до 1000
mat = mat.reshape((2, 2, 3)) # превратим w в трёхмерную матрицу
mat = mat.reshape((12, 1))
print(mat)
| Python | zaydzuhri_stack_edu_python |
function _transform_pandas self df
begin
raise call NotImplementedError
end function | def _transform_pandas(self, df: "pd.DataFrame") -> "pd.DataFrame":
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function get_rect self sz_type=none enlarge=false
begin
if sz_type is none
begin
set sz_type = SZ_DISPLAY
end
set c1x = coord at 0 at 0
set c1y = coord at 0 at 1
set c3x = coord at 1 at 0
set c3y = coord at 1 at 1
set tuple c1x c1y c3x c3y = call order_ul_lr c1x c1y c3x c3y
string Leave room at each end for corner
set ... | def get_rect(self, sz_type=None, enlarge=False):
if sz_type is None:
sz_type=SelectPart.SZ_DISPLAY
c1x = self.loc.coord[0][0]
c1y = self.loc.coord[0][1]
c3x = self.loc.coord[1][0]
c3y = self.loc.coord[1][1]
c1x,c1y,c3x,c3y = SelectLoc.order_ul_lr(c1x,c1... | Python | nomic_cornstack_python_v1 |
from tkinter.messagebox import showinfo
from Sello_Carta import *
from Baraja import *
set baraja = call Baraja CartaBlackJack
set dealer = list
set jugador = list
set dgana_puntaje = 0
set pgana_puntaje = 0
function reiniciar
begin
global dealer jugador
call rebarajar dealer
set dealer = list
call rebarajar jugador... | from tkinter.messagebox import showinfo
from Sello_Carta import *
from Baraja import *
baraja = Baraja(CartaBlackJack)
dealer = []
jugador = []
dgana_puntaje = 0
pgana_puntaje = 0
def reiniciar():
global dealer, jugador
baraja.rebarajar(dealer)
dealer = []
baraja.rebarajar(jugador)
jugador... | Python | zaydzuhri_stack_edu_python |
function load self load_address=none load_parameter=none clear_indicator=true store_status_indicator=false wait_for_completion=true operation_timeout=none status_timeout=none allow_status_exceptions=false force=false
begin
string Load (boot) this LPAR from a load address (boot device), using the HMC operation "Load Log... | def load(self, load_address=None, load_parameter=None,
clear_indicator=True, store_status_indicator=False,
wait_for_completion=True, operation_timeout=None,
status_timeout=None, allow_status_exceptions=False,
force=False):
"""
Load (boot) this LPAR fro... | Python | jtatman_500k |
from datamuse import datamuse
set datamuse = call Datamuse
function related_words word
begin
comment if related words from NYT api are more than one word
if string in word
begin
set words = split word string
for word in words
begin
set related = call words rel_jja=word
print word
set word_list = list
end
print string... | from datamuse import datamuse
datamuse = datamuse.Datamuse()
def related_words(word):
#if related words from NYT api are more than one word
if ' ' in word:
words = word.split(' ')
for word in words:
related = datamuse.words(rel_jja=word)
print(word)
word... | Python | zaydzuhri_stack_edu_python |
comment 时间:20190515
comment Example:
comment Input: [2,1,5,6,2,3]
comment Output: 10
comment 难度:Hard(1.0)
comment 递增栈:栈中只放递增序列
comment 思路:1.我们首先将2加入到栈中,我们接着访问1,我们发现1比栈顶元素2小,所以我们将栈顶元素2弹出,并且记录此时的面积2。我们发现栈已经空了,所以我们要接着压栈。
comment 2.接着我们通过不断遍历找到第二个递增栈。
comment 3.我们接着访问2,我们发现此时2比栈顶元素6小,所以我们弹出栈顶元素6,并且记录此时的面积6*1=6。
comment 4.此... | # 时间:20190515
# Example:
# Input: [2,1,5,6,2,3]
# Output: 10
# 难度:Hard(1.0)
#递增栈:栈中只放递增序列
#思路:1.我们首先将2加入到栈中,我们接着访问1,我们发现1比栈顶元素2小,所以我们将栈顶元素2弹出,并且记录此时的面积2。我们发现栈已经空了,所以我们要接着压栈。
#2.接着我们通过不断遍历找到第二个递增栈。
#3.我们接着访问2,我们发现此时2比栈顶元素6小,所以我们弹出栈顶元素6,并且记录此时的面积6*1=6。
#4.此时栈中还有元素,我们发现此时2依旧比栈顶元素5大,所以我们需要将栈顶元素5弹出,并且我们记录此时出栈元素构成的最大面积5*2=1... | Python | zaydzuhri_stack_edu_python |
function __parse_list self
begin
set idx = idx + 1
set l = list
while data at slice idx : idx + 1 : != b'e'
begin
append l call __parse
end
set idx = idx + 1
return l
end function | def __parse_list(self) -> list:
self.idx += 1
l = []
while self.data[self.idx: self.idx + 1] != b'e':
l.append(self.__parse())
self.idx += 1
return l | Python | nomic_cornstack_python_v1 |
import physics
import pyglet
import graphics
import math
class Spritey extends Polygon
begin
function __init__ self texture_filename body size
begin
set vertices = list tuple - size - size tuple size - size tuple size size tuple - size size
set size = size
set body = body
set angle = none
set texture = call texture tex... | import physics
import pyglet
import graphics
import math
class Spritey(physics.Polygon):
def __init__(self, texture_filename, body, size):
self.vertices = [(-size, -size),
(size, -size),
(size, size),
(-size, size)]
... | Python | zaydzuhri_stack_edu_python |
import poplib
import email
import getpass
set pop_conn = call POP3_SSL string pop.gmail.com 995
comment pop_conn.user(input("insert Email : "))
comment pop_conn.pass_(getpass.getpass("password : "))
call user string tst9928@gmail.com
call pass_ string testing1;
print call stat
print list
print string
if call stat at 1 ... | import poplib
import email
import getpass
pop_conn = poplib.POP3_SSL('pop.gmail.com', 995)
#pop_conn.user(input("insert Email : "))
#pop_conn.pass_(getpass.getpass("password : "))
pop_conn.user('tst9928@gmail.com')
pop_conn.pass_('testing1;')
print(pop_conn.stat())
print(pop_conn.list())
print ("")
if pop_conn.stat(... | Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
class TreeNode extends object
begin
function __init__ self val=0 left=none right=none
begin
set val = val
set left = left
set right = right
end function
end class
class Solution extends object
begin
function inorderTraversal self root
begin
string :type root: TreeNode :rtype: ... | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
... | Python | zaydzuhri_stack_edu_python |
function convert_ms n
begin
set Secs = integer n / 1000 % 60
set Mins = integer n / 1000 * 60 % 60
set Hr = integer n / 1000 * 60 * 60
return format string {}:{}:{} Hr Mins Secs
end function
print call convert_ms Time | def convert_ms(n):
Secs = int((n / 1000) % 60)
Mins = int((n / (1000*60)) % 60)
Hr = int((n / (1000*60*60)))
return("{}:{}:{}".format(Hr, Mins, Secs))
print(convert_ms(Time))
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import csv
import random
import time
import copy
import matplotlib.pyplot as plt
set start = time
comment initialize distance matrix
set cities = list
comment initialize counter
set t = 0
comment import data
with open string TSP29.csv as f
begin
set reader = reader f
for row in reader
beg... | # -*- coding: utf-8 -*-
import csv
import random
import time
import copy
import matplotlib.pyplot as plt
start = time.time()
#initialize distance matrix
cities = []
#initialize counter
t = 0
#import data
with open("TSP29.csv") as f:
reader = csv.reader(f)
for row in reader:
#variable generator
... | Python | zaydzuhri_stack_edu_python |
function ex_authorize_security_group_permissive self name
begin
set results = list
set params = dict string Action string AuthorizeSecurityGroupIngress ; string GroupName name ; string IpProtocol string tcp ; string FromPort string 0 ; string ToPort string 65535 ; string CidrIp string 0.0.0.0/0
end function | def ex_authorize_security_group_permissive(self, name):
results = []
params = {'Action': 'AuthorizeSecurityGroupIngress',
'GroupName': name,
'IpProtocol': 'tcp',
'FromPort': '0',
'ToPort': '65535',
'CidrIp': '0.0.... | Python | nomic_cornstack_python_v1 |
function download_file service file_id file_name=none
begin
comment Setup request for the file
set request = call get_media fileId=file_id supportsAllDrives=true
comment setup the file handler to recieve the byte stream
set fh = call BytesIO
comment the download utility
set downloader = call MediaIoBaseDownload fh requ... | def download_file(service, file_id, file_name=None):
# Setup request for the file
request = service.files().get_media(fileId=file_id, supportsAllDrives=True)
# setup the file handler to recieve the byte stream
fh = io.BytesIO()
# the download utility
downloader = MediaIoBaseDownload(fh, reques... | Python | nomic_cornstack_python_v1 |
class Debug
begin
set COMBAT = 2
set MATH = 1
set SHIP_STATUS = 3
function __init__ self
begin
set active = false
set active_categories = list COMBAT
end function
function log self msg category
begin
if active and category in active_categories
begin
print msg
end
end function
function is_active self
begin
return active... | class Debug:
COMBAT = 2
MATH = 1
SHIP_STATUS = 3
def __init__(self):
self.active = False
self.active_categories = [Debug.COMBAT]
def log(self, msg, category):
if self.active and category in self.active_categories:
print(msg)
def is_active(self) -> bool:
... | Python | zaydzuhri_stack_edu_python |
comment function with parameter and without return
function add no1 no2
begin
print no1
print no2
print no1 + no2
end function
add 100 200
print string ------------------------------------
comment lambda function with parameter and without return
set x = lambda no1 no2 -> print string sum no1 + no2
call x 2 3 | #function with parameter and without return
def add(no1,no2):
print(no1)
print(no2)
print(no1+no2)
add(100,200)
print("------------------------------------")
#lambda function with parameter and without return
x = lambda no1,no2:print("sum",no1+no2)
x(2,3) | Python | zaydzuhri_stack_edu_python |
function process self
begin
call bike_arrival
pop active_rides index active_rides ride
comment Returns an empty list of events so that the output from process is
comment consistent
return list
end function | def process(self) -> List['Event']:
self.ride.end.bike_arrival()
self.simulation.active_rides.pop(
self.simulation.active_rides.index(self.ride))
# Returns an empty list of events so that the output from process is
# consistent
return [] | Python | nomic_cornstack_python_v1 |
import pandas as pd
comment 言語基礎
comment 真偽値
comment 真偽値の逆転
comment !ではなくnotで記述 | import pandas as pd
# 言語基礎
## 真偽値
### 真偽値の逆転
# !ではなくnotで記述 | Python | zaydzuhri_stack_edu_python |
function show_fits_image file imscale image_element contr=1.0 show=true
begin
set tuple imbw header = call get_fits_image file
if length shape == 2
begin
set im = call rescale imbw imscale multichannel=false
end
else
begin
set im = call rescale imbw imscale multichannel=true
end
set im = im / max im * 255 * contr
set i... | def show_fits_image(file, imscale, image_element, contr=1.0, show=True):
imbw, header = get_fits_image(file)
if len(imbw.shape) == 2:
im = tf.rescale(imbw, imscale, multichannel=False)
else:
im = tf.rescale(imbw, imscale, multichannel=True)
im = im / np.max(im) * 255 * contr
i... | Python | nomic_cornstack_python_v1 |
function fusion_api_get_ipv4_range_allocated_fragments self uri api=none headers=none
begin
return get ipv4range uri=uri api=api headers=headers param=string /allocated-fragments
end function | def fusion_api_get_ipv4_range_allocated_fragments(self, uri, api=None, headers=None):
return self.ipv4range.get(uri=uri, api=api, headers=headers, param='/allocated-fragments') | Python | nomic_cornstack_python_v1 |
from gpiozero import LED , Button , LightSensor
from time import sleep
set led = call LED 23
set button = call Button 26
comment Change threshold to lower sensitivity
set sensor = call LightSensor 4 threshold=0.9
while true
begin
comment print(sensor.light_detected)
if not light_detected and is_pressed
begin
call on
en... | from gpiozero import LED, Button, LightSensor
from time import sleep
led = LED(23)
button = Button(26)
sensor = LightSensor(4, threshold=0.9) # Change threshold to lower sensitivity
while True:
# print(sensor.light_detected)
if not sensor.light_detected and button.is_pressed:
led.on()
else:
... | Python | zaydzuhri_stack_edu_python |
function set_use_desktop self bEnabled
begin
call call_sdk_function string PrlVmCfg_SetUseDesktop handle bEnabled
end function | def set_use_desktop(self, bEnabled):
call_sdk_function('PrlVmCfg_SetUseDesktop', self.handle, bEnabled) | Python | nomic_cornstack_python_v1 |
import sys
import bpy
function looop start_frame end_frame location
begin
print string Came in looop
for step in range start_frame end_frame + 1
begin
call frame_set step
set filepath = location + string /V.png_%d.png % step
call render write_still=true
end
end function
set argv = argv
comment get all args after "--"
s... | import sys
import bpy
def looop(start_frame, end_frame, location):
print('Came in looop')
for step in range(start_frame, end_frame + 1):
bpy.context.scene.frame_set(step)
bpy.data.scenes["Scene"].render.filepath = location + '/V.png_%d.png' % step
bpy.ops.render.rend... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from revop import *
import sys
import argparse
set DATA_PATH = string ../data/evaluation/data/
function read_file prebuild skip
begin
set f = open prebuild string r
set lines = list comprehension line at slice : - 1 : for line in read lines f
set lines = lines at slice skip : :
close f
return lin... | import numpy as np
from revop import *
import sys
import argparse
DATA_PATH = '../data/evaluation/data/'
def read_file(prebuild, skip):
f = open(prebuild, "r")
lines = [line[:-1] for line in f.readlines()]
lines = lines[skip:]
f.close()
return lines
def get_order(index_hashes):
name2order =... | Python | zaydzuhri_stack_edu_python |
import pytz
from datetime import datetime
import sys
import context
import os
function export symbol dt output_dir
begin
set eastern = call timezone string US/Eastern
set start = string { dt } 09:30:00
set end = string { dt } 16:00:00
set start_date = call localize string parse time start string %Y-%m-%d %H:%M:%S
set e... | import pytz
from datetime import datetime
import sys
import context
import os
def export(symbol: str, dt: str, output_dir: str):
eastern = pytz.timezone('US/Eastern')
start = f'{dt} 09:30:00'
end = f'{dt} 16:00:00'
start_date = eastern.localize(datetime.strptime(start, '%Y-%m-%d %H:%M:%S'))
end_... | Python | zaydzuhri_stack_edu_python |
comment will print all numbers in range between 1 and 11 but not 11 itself
for value in range 1 11
begin
print value
end | for value in range(1,11): #will print all numbers in range between 1 and 11 but not 11 itself
print(value)
| Python | zaydzuhri_stack_edu_python |
comment User will be given 6 guesses to guess a randomly chosen number.
import random , inputValidator
set nGuess = 6
set nGuessLeft = nGuess
set correctGuess = random integer 1 20
print string I am thinking of a number between 1 and 20.
print string You have 6 tries to guess the number correctly.
for numTry in range n... | # User will be given 6 guesses to guess a randomly chosen number.
import random, inputValidator
nGuess = 6
nGuessLeft = nGuess
correctGuess = random.randint(1,20)
print("I am thinking of a number between 1 and 20.")
print("You have 6 tries to guess the number correctly.")
for numTry in range(nGuess):
guess = input... | Python | zaydzuhri_stack_edu_python |
if S at 0 > 2019
begin
set ans = string TBD
end
else
if S at 0 < 2019
begin
set ans = string Heisei
end
else
if S at 1 > 4
begin
set ans = string TBD
end
else
if S at 1 <= 4
begin
set ans = string Heisei
end
print ans | if S[0] > 2019:
ans = 'TBD'
elif S[0] < 2019:
ans = 'Heisei'
else:
if S[1] > 4:
ans = 'TBD'
elif S[1] <= 4:
ans = 'Heisei'
print(ans) | Python | zaydzuhri_stack_edu_python |
function proj_linf v radius=1
begin
set vmod = absolute v
set projmult = call minimum radius / vmod 1
return projmult * v
end function | def proj_linf(v, radius=1):
vmod = np.abs(v)
projmult = np.minimum(radius/vmod, 1)
return projmult*v | Python | nomic_cornstack_python_v1 |
function rotate_to_run m avp
begin
comment First rotate to align x-axis with mean wind direction in sonic's
comment reference frame
comment Split into single runs (of length avp minutes)
set m_g = group by m call Grouper freq=string %sMin % avp
set m_out = call DataFrame columns=list string x string y string z string T... | def rotate_to_run(m,avp):
# First rotate to align x-axis with mean wind direction in sonic's
# reference frame
m_g = m.groupby(pd.Grouper(freq='%sMin'%avp)) # Split into single runs (of length avp minutes)
m_out = pd.DataFrame(columns=['x','y','z','T','u','v','w','theta','phi'])
... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from matplotlib.colors import ListedColormap
comment 集成方法分类器
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import BaggingClassifi... | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from matplotlib.colors import ListedColormap
#集成方法分类器
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import BaggingClassifier
fro... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
set root = call Tk
set label = call Label root text=string Hello World
set field = call Entry root
set label1 = call Label root text=string in column1
set label2 = call Label root text=string another text
grid row=0 column=0
grid row=0 column=1
grid row=1 columnspan=3
grid row=0 column=2
call main... | from tkinter import *
root = Tk()
label = Label(root, text="Hello World")
field = Entry(root)
label1 = Label(root, text="in column1")
label2 = Label(root, text="another text")
label.grid(row=0, column=0)
field.grid(row=0, column=1)
label1.grid(row=1, columnspan=3)
label2.grid(row=0, column=2)
mainloop() | Python | zaydzuhri_stack_edu_python |
from linked_list import *
comment assumptions: Keys are case insinsitive letters only. numbers are not allowed as keys
comment h(key) = key mod m, m is prime number
comment some prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 1... | from linked_list import *
# assumptions: Keys are case insinsitive letters only. numbers are not allowed as keys
# h(key) = key mod m, m is prime number
# some prime numbers: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149... | Python | zaydzuhri_stack_edu_python |
function _select chromosomes data count_clusters select_coeff
begin
string ! @brief Performs selection procedure where new chromosomes are calculated. @param[in] chromosomes (numpy.array): Chromosomes
comment Calc centers
set centres = call get_centres chromosomes data count_clusters
comment Calc fitness functions
set ... | def _select(chromosomes, data, count_clusters, select_coeff):
"""!
@brief Performs selection procedure where new chromosomes are calculated.
@param[in] chromosomes (numpy.array): Chromosomes
"""
# Calc centers
centres = ga_math.get_centres(chromosomes,... | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.