code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_hospitals_current
begin
set hospitals = all
return tuple call jsonify call __as_feature_collection hospitals 200
end function | def get_hospitals_current():
hospitals = db.session.query(HospitalDevelopment).all()
return jsonify(__as_feature_collection(hospitals)), 200 | Python | nomic_cornstack_python_v1 |
string Simple 2d world where the player can interact with the items in the world.
set __author__ = string
set __date__ = string
set __version__ = string 1.1.0
set __copyright__ = string The University of Queensland, 2019
import math
import sys
import tkinter as tk
from typing import Tuple , List
from tkinter import f... | """
Simple 2d world where the player can interact with the items in the world.
"""
__author__ = ""
__date__ = ""
__version__ = "1.1.0"
__copyright__ = "The University of Queensland, 2019"
import math
import sys
import tkinter as tk
from typing import Tuple, List
from tkinter import filedialog
from tkinter import me... | Python | zaydzuhri_stack_edu_python |
function _strip_leading_comma descr
begin
if length descr > 0 and strip descr at 0 == string ,
begin
set descr = strip descr at slice 1 : :
end
return strip descr
end function | def _strip_leading_comma(descr):
if len(descr) > 0 and descr.strip()[0] == ",":
descr = descr.strip()[1:]
return descr.strip() | Python | nomic_cornstack_python_v1 |
function get_genre_for_current_song track_metadata genre_metadata song
begin
comment Formatting file name to leave out the file path and extension, as well as remove leading 0's
comment eg. path\to\000002.mp3 becomes 2
set song_name = base name song
set song_name = call splitext song_name at 0
set song_name = left stri... | def get_genre_for_current_song(track_metadata, genre_metadata, song):
# Formatting file name to leave out the file path and extension, as well as remove leading 0's
# eg. path\to\000002.mp3 becomes 2
song_name = basename(song)
song_name = splitext(song_name)[0]
song_name = song_name.lstrip('0')
... | Python | nomic_cornstack_python_v1 |
function find_suggestions filelist
begin
set suggestions = set
set unknowns = list
for filename in filelist
begin
if is directory path filename
begin
comment it's impossible to add empty directories via MANIFEST.in anyway,
comment and non-empty directories will be added automatically when we
comment specify patterns f... | def find_suggestions(filelist):
suggestions = set()
unknowns = []
for filename in filelist:
if os.path.isdir(filename):
# it's impossible to add empty directories via MANIFEST.in anyway,
# and non-empty directories will be added automatically when we
# specify pat... | Python | nomic_cornstack_python_v1 |
import time
import Adafruit_SSD1306
import Adafruit_LSM303
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
comment Raspberry Pi pin configuration:
set RST = 24
set lsm303 = call LSM303
set disp = call SSD1306_128_64 rst=RST i2c_address=61
comment Initialize library.
call begin
comment Clear di... | import time
import Adafruit_SSD1306
import Adafruit_LSM303
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
# Raspberry Pi pin configuration:
RST = 24
lsm303 = Adafruit_LSM303.LSM303()
disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3D)
# Initialize library.
disp.begin()
# C... | Python | zaydzuhri_stack_edu_python |
function __init__ self src_entity=none src_event=none role=string new **kwargs
begin
call __init__ src_entity=src_entity keyword kwargs
comment pylint: disable=locally-disabled, line-too-long
if src_event is not none
begin
if role == string new
begin
set ProcessId = if expression string NewProcessId in src_event then s... | def __init__(
self,
src_entity: Mapping[str, Any] = None,
src_event: Mapping[str, Any] = None,
role="new",
**kwargs,
):
super().__init__(src_entity=src_entity, **kwargs)
# pylint: disable=locally-disabled, line-too-long
if src_event is not None:
... | Python | nomic_cornstack_python_v1 |
comment noqa: PLR0913
function __init__ self url key secret log_console=false log_file=false log_file_rotate=false certpath=none certverify=false certwarn=true proxy=none headers=none cookies=none credentials=false timeout_connect=CONNECT_TIMEOUT timeout_response=RESPONSE_TIMEOUT cert_client_key=none cert_client_cert=n... | def __init__( # noqa: PLR0913
self,
url: str,
key: str,
secret: str,
log_console: bool = False,
log_file: bool = False,
log_file_rotate: bool = False,
certpath: t.Optional[PathLike] = None,
certverify: bool = False,
certwarn: bool = True,
... | Python | nomic_cornstack_python_v1 |
function gen_class_module spec lib klasses **module_settings
begin
update module_settings call get_module_settings
set _settings = call ModuleSettings keyword module_settings
comment convert input/output specs into VT port objects
set input_ports = list comprehension call CIPort name call get_port_type keyword call get... | def gen_class_module(spec, lib, klasses, **module_settings):
module_settings.update(spec.get_module_settings())
_settings = ModuleSettings(**module_settings)
# convert input/output specs into VT port objects
input_ports = [CIPort(ispec.name, ispec.get_port_type(), **ispec.get_port_attrs())
... | Python | nomic_cornstack_python_v1 |
function get_default cls
begin
return ALL
end function | def get_default(cls):
return cls.ALL | Python | nomic_cornstack_python_v1 |
import face_recognition
import cv2
import numpy as np
import os
import pyttsx3
set tts = call init
set voices = call getProperty string voices
call setProperty string voice string ru
call say string Привет! Меня зовут Рома. Я очень рад вас видеть!
call runAndWait
if string DISPLAY in environ
begin
print environ at stri... | import face_recognition
import cv2
import numpy as np
import os
import pyttsx3
tts = pyttsx3.init()
voices = tts.getProperty('voices')
tts.setProperty('voice', 'ru')
tts.say('Привет! Меня зовут Рома. Я очень рад вас видеть!')
tts.runAndWait()
if 'DISPLAY' in os.environ:
print(os.environ['DISPLAY'])
else:
prin... | Python | zaydzuhri_stack_edu_python |
function test_hypergeometric_conf_badinput7
begin
raises ValueError hypergeom_conf_interval 101 5 100 0.95 string two-sided none string sterne
end function | def test_hypergeometric_conf_badinput7():
pytest.raises(ValueError, hypergeom_conf_interval,
101, 5, 100, 0.95, 'two-sided', None, 'sterne') | Python | nomic_cornstack_python_v1 |
function parse_toplevel_subterms_and_connector cls compound_term_string
begin
set compound_term_string = replace compound_term_string string string
set subterms = list
set intervals = list
comment string with no outer parentheses () or set brackets [], {}
set internal_string = compound_term_string at slice 1 : - 1 :... | def parse_toplevel_subterms_and_connector(cls, compound_term_string):
compound_term_string = compound_term_string.replace(" ","")
subterms = []
intervals = []
internal_string = compound_term_string[1:-1] # string with no outer parentheses () or set brackets [], {}
# check for in... | Python | nomic_cornstack_python_v1 |
function get_followers_url self
begin
return call _get_url string followers
end function | def get_followers_url(self):
return self._get_url('followers') | Python | nomic_cornstack_python_v1 |
function Close self codingParams
begin
comment determine if encoding or encoding and, if encoding, do last block
comment we are writing to the PACFile, must be encode
if mode == string wb
begin
comment we are writing the coded file -- pass a block of zeros to move last data block to other side of MDCT block
set data = ... | def Close(self,codingParams):
# determine if encoding or encoding and, if encoding, do last block
if self.fp.mode == "wb": # we are writing to the PACFile, must be encode
# we are writing the coded file -- pass a block of zeros to move last data block to other side of MDCT block
... | Python | nomic_cornstack_python_v1 |
from square_board.board import Board as NormalBoard
from square_board.data import piece_shape_set
class BoardFactory
begin
decorator staticmethod
function createBoard boardType
begin
if boardType == string square_standard
begin
return call NormalBoard piece_shape_set
end
return format string board type {} is not define... | from .square_board.board import Board as NormalBoard
from .square_board.data import piece_shape_set
class BoardFactory:
@staticmethod
def createBoard(boardType):
if boardType == "square_standard":
return NormalBoard(piece_shape_set)
return "board type {} is not defined!".format... | Python | zaydzuhri_stack_edu_python |
async function authenticate_client_secret_basic query_client request
begin
set tuple client_id client_secret = call extract_basic_authorization headers
if client_id and client_secret
begin
set client = await call _validate_client query_client client_id state 401
if call check_token_endpoint_auth_method string client_se... | async def authenticate_client_secret_basic(query_client, request):
client_id, client_secret = extract_basic_authorization(request.headers)
if client_id and client_secret:
client = await _validate_client(query_client, client_id, request.state, 401)
if client.check_token_endpoint_auth_method(
... | Python | nomic_cornstack_python_v1 |
function process_write self target_file **kwargs
begin
set flow = call generate keyword kwargs
for markup in call serialize
begin
write target_file markup
yield true
end
end function | def process_write(self, target_file, **kwargs):
flow = self.generate(**kwargs)
for markup in flow.serialize():
target_file.write(markup)
yield True | Python | nomic_cornstack_python_v1 |
function make_top_words_list job_dir
begin
set credentials = call get_application_default
set storage = call build string storage string v1 credentials=credentials
set objects = call objects
set subpaths = match string gs://(monorail-.*)-mlengine/(component_trainer_\d+) job_dir
if subpaths
begin
set project_id = call g... | def make_top_words_list(job_dir):
credentials = GoogleCredentials.get_application_default()
storage = discovery.build('storage', 'v1', credentials=credentials)
objects = storage.objects()
subpaths = re.match('gs://(monorail-.*)-mlengine/(component_trainer_\d+)',
job_dir)
if subpaths:
... | Python | nomic_cornstack_python_v1 |
from math import radians , sin , cos , tan
set n = decimal input string Qual o ângulo você deseja saber os valores:
set c = cos call radians n
set s = sin call radians n
set t = tan call radians n
print format string [31mO ângulo de {} tem COSSENO {:.2f} n c
print format string [34mO ângulo de {} tem SENO {:.2f} n s
... | from math import radians, sin, cos, tan
n = float(input("Qual o ângulo você deseja saber os valores: "))
c = cos(radians(n))
s = sin(radians(n))
t = tan(radians(n))
print("\033[31mO ângulo de {} tem COSSENO {:.2f}".format(n, c))
print("\033[34mO ângulo de {} tem SENO {:.2f}".format(n, s))
print("\033[35mO ângulo... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
from tensorflow.keras import layers , models
comment Define the CNN model
function create_model
begin
set model = sequential
add model conv 2d 32 tuple 3 3 activation=string relu input_shape=tuple 28 28 1
add model max pooling 2d tuple 2 2
add model conv 2d 64 tuple 3 3 activation=string relu
ad... | import tensorflow as tf
from tensorflow.keras import layers, models
# Define the CNN model
def create_model():
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activati... | Python | jtatman_500k |
from findplaces import find_places
from telebot import *
set token = string
with open string token.txt as f
begin
set token = read f
end
import telebot
set bot = call TeleBot token
decorator call message_handler content_types=list string text
function get_text_messages message
begin
if text == string /start
begin
call... | from findplaces import find_places
from telebot import *
token = ""
with open("token.txt") as f:
token = f.read()
import telebot;
bot = telebot.TeleBot(token)
@bot.message_handler(content_types=["text"])
def get_text_messages(message):
if message.text == "/start":
bot.send_message(messag... | Python | zaydzuhri_stack_edu_python |
async function remove self ctx trigger
begin
if type trigger is Trigger
begin
await call remove_trigger guild name
await call remove_trigger_from_cache guild trigger
await call send call _ string Trigger ` + name + call _ string ` removed.
end
else
begin
await call send call _ string Trigger ` + trigger + call _ string... | async def remove(self, ctx: commands.Context, trigger: TriggerExists):
if type(trigger) is Trigger:
await self.remove_trigger(ctx.guild, trigger.name)
await self.remove_trigger_from_cache(ctx.guild, trigger)
await ctx.send(_("Trigger `") + trigger.name + _("` removed."))
... | Python | nomic_cornstack_python_v1 |
function neighbor_k self obj k in_model=true
begin
if in_model
begin
set i = call neighbor_k call as_index obj k
if call isstring obj
begin
return strings at i
end
try
begin
integer obj
return i
end
except any
begin
return space at i
end
end
else
begin
comment Note that if not in_model, we require obj to be a vector.
s... | def neighbor_k(self, obj, k, in_model=True):
if in_model:
i = self.D.neighbor_k(self.as_index(obj), k)
if isstring(obj):
return self.strings[i]
try:
int(obj)
return i
except: return self.space[i]
else:
... | Python | nomic_cornstack_python_v1 |
comment -------------------------------------------------------------------------------
comment Iteratively estimates a trajectory by using gradient descent to try and
comment minimise the error between predicted and observed landmark bearings
comment --------------------------------------------------------------------... | #-------------------------------------------------------------------------------
# Iteratively estimates a trajectory by using gradient descent to try and
# minimise the error between predicted and observed landmark bearings
#-------------------------------------------------------------------------------
import random... | Python | zaydzuhri_stack_edu_python |
string A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and... | """
A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters
can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency.
For example, bacdc and ... | Python | zaydzuhri_stack_edu_python |
function load_vocabulary self
begin
set vocab_file = open vocabulary_path string r
set vocab_list = split read vocab_file string
close vocab_file
print string [INFO] Reading vocabulary...
print vocab_list at slice 0 : 15 :
end function | def load_vocabulary(self):
vocab_file = open(vocabulary_path, "r")
self.vocab_list = vocab_file.read().split("\n")
vocab_file.close()
print("[INFO] Reading vocabulary...")
print(self.vocab_list[0:15]) | Python | nomic_cornstack_python_v1 |
function __init__ self *database_args **database_kwargs
begin
set database_args = database_args
set database_kwargs = database_kwargs
call __init__
end function | def __init__(self, *database_args, **database_kwargs):
self.database_args = database_args
self.database_kwargs = database_kwargs
super(CommonCallback, self).__init__() | Python | nomic_cornstack_python_v1 |
import Ejemplo_2
import mi_paquete
import datetime
call saludar
call help Ejemplo_2
call help saludar
print string ==========================================
print directory Ejemplo_2
print string ==========================================
call help mi_paquete
call help datetime | import Ejemplo_2
import mi_paquete
import datetime
Ejemplo_2.saludar()
help(Ejemplo_2)
help(Ejemplo_2.saludar)
print("==========================================")
print(dir(Ejemplo_2))
print("==========================================")
help(mi_paquete)
help(datetime) | Python | zaydzuhri_stack_edu_python |
function merge_experiments_scans_reading experiments scans reading
begin
set experiments_df = call experiments_to_dataframe experiments
set scans_df = call scans_to_dataframe scans
set reading_df = call reading_to_dataframe reading
set exp_scan = merge experiments_df scans_df how=string inner
set merged = merge exp_sca... | def merge_experiments_scans_reading(experiments, scans, reading):
experiments_df = experiments_to_dataframe(experiments)
scans_df = scans_to_dataframe(scans)
reading_df = reading_to_dataframe(reading)
exp_scan = pd.merge(experiments_df, scans_df, how='inner')
merged = pd.merge(exp_scan, reading_df, ... | Python | nomic_cornstack_python_v1 |
function generate_from ast include_paths
begin
set includes = set usertype_includes
for include in includes
begin
comment Not generating type casters for the builtin types.
comment Not scanning headers generated by pybind11 code generator because the
comment `// CLIF USE` in those headers do not have associated `Clif_P... | def generate_from(ast: ast_pb2.AST,
include_paths: List[str]) -> Generator[str, None, None]:
includes = set(ast.usertype_includes)
for include in includes:
# Not generating type casters for the builtin types.
# Not scanning headers generated by pybind11 code generator because the
# `/... | Python | nomic_cornstack_python_v1 |
function initial_solution self a b
begin
return binary integer a base=2 + integer b base=2 at slice 2 : :
end function | def initial_solution(self, a: str, b: str) -> str:
return bin(int(a, base=2) + int(b, base=2))[2:] | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
function ignnbn n p
begin
comment *****************************************************************************80
comment IGNNBN generates a negative binomial random deviate.
comment Discussion:
comment This procedure generates a single random deviate from a negative binomial
comment distr... | #! /usr/bin/env python
#
def ignnbn ( n, p ):
#*****************************************************************************80
#
## IGNNBN generates a negative binomial random deviate.
#
# Discussion:
#
# This procedure generates a single random deviate from a negative binomial
# distribution.
#
# Licensing:
#... | Python | zaydzuhri_stack_edu_python |
function drawdown pnl how=string high
begin
set mark = if expression how == string high then maximum else minimum
set watermark = accumulate fill missing pnl min
set dd = 1 - pnl / call shift 1
set ix at dd < 0 = 0
return dd
end function | def drawdown(pnl, how='high'):
mark = np.maximum if how == 'high' else np.minimum
watermark = mark.accumulate(pnl.fillna(pnl.min()))
dd = 1 - (pnl / watermark.shift(1))
dd.ix[dd < 0] = 0
return dd | Python | nomic_cornstack_python_v1 |
function remove_useless_file rootPath
begin
set all_file_paddle_list = call get_all_paddle_file rootPath
set ut_file_map_new = dict
set ut_file_map = string %s/build/ut_file_map.json % rootPath
with open ut_file_map string r as load_f
begin
set load_dict = load json load_f
end
for key in load_dict
begin
if key in all_... | def remove_useless_file(rootPath):
all_file_paddle_list = get_all_paddle_file(rootPath)
ut_file_map_new = {}
ut_file_map = "%s/build/ut_file_map.json" % rootPath
with open(ut_file_map, 'r') as load_f:
load_dict = json.load(load_f)
for key in load_dict:
if key in all_file_paddle_list:... | Python | nomic_cornstack_python_v1 |
function convert_upsample node **kwargs
begin
set tuple name input_nodes attrs = call get_inputs node kwargs
set sample_type = get attrs string sample_type string nearest
set sample_type = if expression sample_type == string bilinear then string linear else sample_type
set scale = call convert_string_to_list get attrs ... | def convert_upsample(node, **kwargs):
name, input_nodes, attrs = get_inputs(node, kwargs)
sample_type = attrs.get('sample_type', 'nearest')
sample_type = 'linear' if sample_type == 'bilinear' else sample_type
scale = convert_string_to_list(attrs.get('scale'))
scaleh = scalew = float(scale[0])
... | Python | nomic_cornstack_python_v1 |
from __future__ import unicode_literals
from django.contrib import messages
from django.db import models
import datetime
import re
import bcrypt
set EMAIL_REGEX = compile string ^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$
comment Create your models here.
class UserManager extends Manager
begin
comment isValidLogin ta... | from __future__ import unicode_literals
from django.contrib import messages
from django.db import models
import datetime
import re
import bcrypt
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
# Create your models here.
class UserManager(models.Manager):
# isValidLogin takes in the u... | Python | zaydzuhri_stack_edu_python |
comment Taken from Python 2.7's functools
function cmp_to_key mycmp
begin
class K extends object
begin
set __slots__ = list string obj
function __init__ self obj *args
begin
set obj = obj
end function
function __lt__ self other
begin
return call mycmp obj obj < 0
end function
function __gt__ self other
begin
return cal... | def cmp_to_key(mycmp): # Taken from Python 2.7's functools
class K(object):
__slots__ = ['obj']
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other... | Python | nomic_cornstack_python_v1 |
function run_tests
begin
set environ at string WORKDIR = CONFIG at string workdir
set environ at string REPORTDIR = CONFIG at string reportFolder
set stdout = DEVNULL
if CONFIG at string verbose
begin
set stdout = none
end
comment cycle throught version
set total = 0
set valid = 0
set start = time
for version in call g... | def run_tests():
os.environ['WORKDIR'] = CONFIG['workdir']
os.environ['REPORTDIR'] = CONFIG['reportFolder']
stdout = subprocess.DEVNULL
if CONFIG['verbose']:
stdout = None
# cycle throught version
total = 0
valid = 0
start = time.time()
for version in utils.get_dirs(CONFIG['v... | Python | nomic_cornstack_python_v1 |
function api_put self uri **kwargs
begin
return call api_request string PUT uri json=kwargs
end function | def api_put(self, uri, **kwargs):
return self.api_request("PUT", uri, json=kwargs) | Python | nomic_cornstack_python_v1 |
function addAttribute self attr
begin
pass
end function | def addAttribute(self, attr):
pass | Python | nomic_cornstack_python_v1 |
function iterator self
begin
return call Floats_iterator self
end function | def iterator(self):
return _RMF_HDF5.Floats_iterator(self) | Python | nomic_cornstack_python_v1 |
async function async_setup_entry hass config_entry
begin
set default data DOMAIN dict
set coordinator = call QnapCoordinator hass config_entry
comment Fetch initial data so we have data when entities subscribe
await call async_config_entry_first_refresh
set data at DOMAIN at entry_id = coordinator
await call async_forw... | async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
hass.data.setdefault(DOMAIN, {})
coordinator = QnapCoordinator(hass, config_entry)
# Fetch initial data so we have data when entities subscribe
await coordinator.async_config_entry_first_refresh()
hass.data[DOMAIN][... | Python | nomic_cornstack_python_v1 |
function test_load_from_env_unset
begin
set a = load ExampleConfig number=3 floaty_number=5 flag=false word=string hello _lookup_config_envvar=string config
assert number == 3
assert floaty_number == 5.0
assert flag is false
assert word == string hello
end function | def test_load_from_env_unset():
a = ExampleConfig.load(
number=3,
floaty_number=5,
flag=False,
word='hello',
_lookup_config_envvar='config',
)
assert a.number == 3
assert a.floaty_number == 5.0
assert a.flag is False
assert a.word == 'hello' | Python | nomic_cornstack_python_v1 |
import jieba.posseg as pseg
from pyltp import SentenceSplitter , Segmentor , Postagger , Parser , SementicRoleLabeller
set model_dir = string ../pyltp_models
comment 分词
set segmentor = call Segmentor
load segmentor model_dir + string /cws.model
comment 词性标注
set postagger = call Postagger
load postagger model_dir + stri... | import jieba.posseg as pseg
from pyltp import SentenceSplitter, Segmentor, Postagger, Parser, SementicRoleLabeller
model_dir = '../pyltp_models'
segmentor = Segmentor() # 分词
segmentor.load(model_dir + '/cws.model')
postagger = Postagger() # 词性标注
postagger.load(model_dir + '/pos.model')
parser = Parser() # 依存句法分析
p... | Python | zaydzuhri_stack_edu_python |
function _connect_to_target self host
begin
set port = 80
if string : in host
begin
set tuple host _ port = call partition string :
end
set tuple socket_family _ _ _ address = call getaddrinfo host port at 0
set target = call socket socket_family
call connect address
end function | def _connect_to_target(self, host):
port = 80
if ':' in host:
host, _, port = host.partition(':')
(socket_family, _, _, _, address) = socket.getaddrinfo(host, port)[0]
self.target = socket.socket(socket_family)
self.target.connect(address) | Python | nomic_cornstack_python_v1 |
import json
function loadDeviceList *args
begin
comment Because the main.py file that calls this method is located in the root directory,
comment the relative path of the file needs to behave as though this method is also at the
comment root of the directory. In this file's internal test, a single integer is passed to ... | import json
def loadDeviceList(*args):
#Because the main.py file that calls this method is located in the root directory,
#the relative path of the file needs to behave as though this method is also at the
#root of the directory. In this file's internal test, a single integer is passed to the function
#to give th... | Python | zaydzuhri_stack_edu_python |
function is_exponential character
begin
return character in exponentials
end function | def is_exponential(character: str) -> bool:
return character in exponentials | Python | nomic_cornstack_python_v1 |
function can_be_viewed_by self player
begin
if call check_permstring string builders
begin
return true
end
return call access player string withdraw or call access player string viewassets
end function | def can_be_viewed_by(self, player):
if player.check_permstring("builders"):
return True
return self.access(player, "withdraw") or self.access(player, "viewassets") | Python | nomic_cornstack_python_v1 |
comment AUTHOR: Sutharsan Rajaratnam
comment DATE: December, 24, 2019
comment PURPOSE: Test suite (TS) 'runner' file
comment tests/.../classesTC_un/run_un_ts_main.py
import unittest
comment Import test case module: 'TC_ComputePayroll
comment from classesTC_un import ComputePayroll
from payroll.tests.un.classesTC_un imp... | #########################################
###AUTHOR: Sutharsan Rajaratnam
###DATE: December, 24, 2019
###PURPOSE: Test suite (TS) 'runner' file
### tests/.../classesTC_un/run_un_ts_main.py
#########################################
import unittest
# Import test case module: 'TC_ComputePayroll
# from classesT... | Python | zaydzuhri_stack_edu_python |
for w in text
begin
set counts at w = get counts w 0 + 1
end
for tuple k v in items counts
begin
if v > 1000
begin
print k v
end
end | for w in text:
counts[w] = counts.get(w,0) + 1
for k,v in counts.items():
if v > 1000:
print(k,v)
| Python | zaydzuhri_stack_edu_python |
function process_request self msg
begin
set avail_id = call get_best_vlan_id msg
if avail_id != NOTFOUND
begin
call assign avail_id msg
if req_type == RED
begin
call assign avail_id msg
end
end
return avail_id
end function | def process_request(self, msg: RequestMsg):
avail_id = self.get_best_vlan_id(msg)
if avail_id != NOTFOUND:
self._primary_port.assign(avail_id, msg)
if msg.req_type == RequestType.RED:
self._secondary_port.assign(avail_id, msg)
return avail_id | Python | nomic_cornstack_python_v1 |
from django.core.exceptions import ValidationError
from django.db.models import Avg , Count , Sum
from django.utils import timezone
from app.libs.constants import ERROR_MESSAGES , THRESHOLD_VALUES
from app.stores.models import Box
from datetime import timedelta
class CheckConstraintsUtil extends object
begin
function _... | from django.core.exceptions import ValidationError
from django.db.models import Avg, Count, Sum
from django.utils import timezone
from app.libs.constants import ERROR_MESSAGES, THRESHOLD_VALUES
from app.stores.models import Box
from datetime import timedelta
class CheckConstraintsUtil(object):
def __init__(self, u... | Python | zaydzuhri_stack_edu_python |
function lower_case
begin
set count_lower = 0
for char in user_input
begin
if is lower char == true
begin
set count_lower = count_lower + 1
end
end
return count_lower
end function
function upper_case
begin
set count_upper = 0
for char in user_input
begin
if is upper char == true
begin
set count_upper = count_upper + 1
... | def lower_case():
count_lower = 0
for char in user_input:
if (char.islower()) == True:
count_lower += 1
return count_lower
def upper_case():
count_upper = 0
for char in user_input:
if (char.isupper()) == True:
count_upper += 1
return count_upp... | Python | zaydzuhri_stack_edu_python |
comment Create your models here.
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse
import markdown
from django.utils.html import strip_tags
class Category extends Model
begin
set name = call CharField max_length=100
class Meta
begi... | # Create your models here.
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from django.urls import reverse
import markdown
from django.utils.html import strip_tags
class Category(models.Model):
name = models.CharField(max_length=100)
clas... | Python | zaydzuhri_stack_edu_python |
from circle import Circle
from box import Box
class ShapeFactory
begin
set shapes = dict string circle call Circle ; string box call Box
function __init__ self
begin
pass
end function
function createShape self _type
begin
return get shapes _type
end function
end class | from circle import Circle
from box import Box
class ShapeFactory:
shapes = {
'circle': Circle(),
'box' : Box()
}
def __init__(self):
pass
def createShape(self, _type):
return self.shapes.get(_type)
| Python | zaydzuhri_stack_edu_python |
function get_value key dictionary
begin
try
begin
comment We're using 2 regular expressions, the first one to try to cast the value as int if
comment possible, the second one to convert the key using dot and bracket notation into a list
comment of ordered keys to access the value in the dictionary.
set keys = list comp... | def get_value(key, dictionary):
try:
# We're using 2 regular expressions, the first one to try to cast the value as int if
# possible, the second one to convert the key using dot and bracket notation into a list
# of ordered keys to access the value in the dictionary.
keys = [int(k) ... | Python | nomic_cornstack_python_v1 |
function fill_crafting_table self
begin
for tuple i slot in enumerate crafting
begin
set crafting_table at divide mod i crafting_stride = slot
end
end function | def fill_crafting_table(self):
for i, slot in enumerate(self.crafting):
self.crafting_table[divmod(i, self.crafting_stride)] = slot | Python | nomic_cornstack_python_v1 |
function get_mass_ratio_EggletonBook mass_primary
begin
comment Define the period distribution
set X_2 = uniform 0 1
set alpha_prime = 0.1 * mass_primary ^ 1.5
set alpha = 3.5 + 1.3 * alpha_prime / 1 + alpha_prime
set P = 50000.0 / mass_primary ^ 2 * X_2 / 1 - X_2 ^ alpha
comment Now define the inverse mass-ratio distr... | def get_mass_ratio_EggletonBook(mass_primary):
# Define the period distribution
X_2 = np.random.uniform(0,1)
alpha_prime = 0.1 * mass_primary**1.5
alpha = (3.5 + 1.3*alpha_prime)/(1 + alpha_prime)
P = (5e4/mass_primary**2)*(X_2/(1-X_2))**alpha
# Now define the inverse mass-ratio distribution
... | Python | nomic_cornstack_python_v1 |
set tuple a b = map int split input
print string { a // b }
print string { a % b }
print string { a / b } | a, b = map(int, input().split())
print(f'{a//b}')
print(f'{a%b}')
print(f'{a/b:.8f}')
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Aug 16 15:12:50 2019 @author: Thunderson-RJ
import numpy as np
class LMS
begin
function __init__ self FilterOrder InitialValue=0
begin
set NoCoef = FilterOrder + 1
if InitialValue == 0
begin
set coef = zeros NoCoef dtype=complex
end
else
begin
assert length InitialVal... | # -*- coding: utf-8 -*-
"""
Created on Fri Aug 16 15:12:50 2019
@author: Thunderson-RJ
"""
import numpy as np
class LMS:
def __init__(self, FilterOrder, InitialValue = 0):
NoCoef = FilterOrder + 1
if (InitialValue == 0):
self.coef = np.zeros(NoCoef, dtype=complex)
... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set _debug = false
end function | def __init__(self):
self._debug = False | Python | nomic_cornstack_python_v1 |
comment -*- coding:utf-8 -*-
import csv
set headers = list string 成语 string 长度 string 拼音 string 成语解释 string 出自 string 去调拼音 string 首字拼音 string 末字拼音
set data = list
set data_sum = 30957
set mydata = list
comment 已经处理的成语数
set now_sum = 0
set every = list
function init
begin
with open string cyyy.csv mode=string r encod... | # -*- coding:utf-8 -*-
import csv
headers = ["成语","长度","拼音","成语解释","出自","去调拼音","首字拼音","末字拼音"]
data = []
data_sum = 30957
mydata = []
now_sum = 0 #已经处理的成语数
every = []
def init():
with open('cyyy.csv',mode = 'r',encoding = 'utf-8')as f:
global data
data = csv.DictReader(f)
#print(type(data))
i ... | Python | zaydzuhri_stack_edu_python |
function main
begin
import os , sys , getopt , ConfigParser , time
end function
comment parse command line arguments | def main():
import os, sys, getopt, ConfigParser, time
# parse command line arguments | Python | nomic_cornstack_python_v1 |
import discord
from discord.ext import commands
from youtube_dl import YoutubeDL
from utils import embed_send
from base_logger import logger
from asyncio import sleep
comment dictionary that holds music sessions across multiple servers. key - server id, value - music queue
set queue = dict
class Music extends Cog
begi... | import discord
from discord.ext import commands
from youtube_dl import YoutubeDL
from utils import embed_send
from base_logger import logger
from asyncio import sleep
# dictionary that holds music sessions across multiple servers. key - server id, value - music queue
queue = {}
class Music(commands.Cog):
def __... | Python | zaydzuhri_stack_edu_python |
comment noqa: C901
function build_logical_line_tokens self
begin
set logical = list
set comments = list
set mapping : _LogicalMapping = list
set length = 0
set previous_row = none
set previous_column = none
for tuple token_type text start end line in tokens
begin
if token_type in SKIP_TOKENS
begin
continue
end
if no... | def build_logical_line_tokens(self) -> _Logical: # noqa: C901
logical = []
comments = []
mapping: _LogicalMapping = []
length = 0
previous_row = previous_column = None
for token_type, text, start, end, line in self.tokens:
if token_type in SKIP_TOKENS:
... | Python | nomic_cornstack_python_v1 |
function wheel pos
begin
if pos < 85
begin
return call Color pos * 3 255 - pos * 3 0
end
else
if pos < 170
begin
set pos = pos - 85
return call Color 255 - pos * 3 0 pos * 3
end
else
begin
set pos = pos - 170
return call Color 0 pos * 3 255 - pos * 3
end
end function | def wheel(pos):
if pos < 85:
return Color(pos * 3, 255 - pos * 3, 0)
elif pos < 170:
pos -= 85
return Color(255 - pos * 3, 0, pos * 3)
else:
pos -= 170
return Color(0, pos * 3, 255 - pos * 3) | Python | nomic_cornstack_python_v1 |
import dates
import nose.tools as n
function check_is_date tokens expectation
begin
call assert_equal call is_date tokens expectation
end function
function check_token_is_month token expectation
begin
call assert_equal call _token_is_month token expectation
end function
function check_token_is_day_of_month token expect... | import dates
import nose.tools as n
def check_is_date(tokens, expectation):
n.assert_equal(dates.is_date(tokens), expectation)
def check_token_is_month(token, expectation):
n.assert_equal(dates._token_is_month(token), expectation)
def check_token_is_day_of_month(token, expectation):
n.assert_equal(dates.... | Python | zaydzuhri_stack_edu_python |
comment https://leetcode.com/problems/add-two-numbers/description/
class ListNode
begin
function __init__ self x
begin
set val = x
set next = none
end function
function __eq__ self other
begin
if is instance other ListNode
begin
set this_pointer = next
set other_pointer = next
if val != val
begin
return false
end
else
... | # https://leetcode.com/problems/add-two-numbers/description/
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __eq__(self, other):
if isinstance(other, ListNode):
this_pointer = self.next
other_pointer = other.next
if other.v... | Python | zaydzuhri_stack_edu_python |
function send_reminder self
begin
pass
end function | def send_reminder(self):
pass | Python | nomic_cornstack_python_v1 |
function add_player inp_to_add type_to_add host root password
begin
set detail_dict = dict
if type_to_add == string url
begin
set player_soup = call BeautifulSoup text string html.parser
set player_site = inp_to_add
end
else
begin
set tuple player_soup player_site = call get_first_search_result SOCCER_URL + string /se... | def add_player(inp_to_add, type_to_add, host, root, password):
detail_dict = {}
if type_to_add == "url":
player_soup = BeautifulSoup(requests.get(inp_to_add).text, 'html.parser')
player_site = inp_to_add
else:
player_soup, player_site = get_first_search_result(
S... | Python | nomic_cornstack_python_v1 |
function fix_post_relative_url rel_url
begin
string Fix post relative url to a standard, uniform format. Possible input: - 2016/7/8/my-post - 2016/07/08/my-post.html - 2016/8/09/my-post/ - 2016/8/09/my-post/index - 2016/8/09/my-post/index.htm - 2016/8/09/my-post/index.html :param rel_url: relative url to fix :return: f... | def fix_post_relative_url(rel_url):
"""
Fix post relative url to a standard, uniform format.
Possible input:
- 2016/7/8/my-post
- 2016/07/08/my-post.html
- 2016/8/09/my-post/
- 2016/8/09/my-post/index
- 2016/8/09/my-post/index.htm
- 2016/8/09/my-p... | Python | jtatman_500k |
comment Filtering out strings without letter 'a'
set filtered_words = list comprehension word for word in words if string a in word
comment Print the filtered list
print filtered_words
comment Output: ['apple', 'banana', 'grape'] | # Filtering out strings without letter 'a'
filtered_words = [word for word in words if 'a' in word]
# Print the filtered list
print(filtered_words)
# Output: ['apple', 'banana', 'grape'] | Python | iamtarun_python_18k_alpaca |
string attributes.py module For Haxby's dataset: get the attributes of all merged runs for one subject. 1452 volumens have all merged runs for one subject. Generate file containing 1452 lines - one for each volumen.
import numpy as np
comment attributes.txt generation
function get_conditions directory
begin
set runs = ... | '''
attributes.py
module
For Haxby's dataset: get the attributes of all merged runs for one subject.
1452 volumens have all merged runs for one subject.
Generate file containing 1452 lines - one for each volumen.
'''
import numpy as np
###############################################################################... | Python | zaydzuhri_stack_edu_python |
import pygame
import math
class GameOverSpinnerAnimation
begin
function __init__ self screen text_color_start
begin
set wait_icon_path_radius = 25
set wait_icon_counter = 0
set wait_icon_radius = screen at 0 * 0.01
set numIconCircles = 4
set text_color = text_color_start
set wait_icon_center = tuple screen at 0 * 0.71 ... | import pygame
import math
class GameOverSpinnerAnimation():
def __init__(self, screen, text_color_start):
self.wait_icon_path_radius = 25
self.wait_icon_counter = 0
self.wait_icon_radius = screen[0] * 0.01
self.numIconCircles = 4
self.text_color = text_color_start
... | Python | zaydzuhri_stack_edu_python |
function release_buffer self d_id
begin
if d_id is none
begin
print string Warning: release_buffer(): attempted to release already freed buffer
end
else
begin
if d_id in keys book
begin
set _ = pop book d_id
end
try
begin
release d_id
end
comment ~ d_id = None
except LogicError
begin
raise call RuntimeError string Erro... | def release_buffer(self, d_id):
if d_id is None:
print("Warning: release_buffer(): attempted to release already freed buffer")
else:
if d_id in self.book.keys():
_ = self.book.pop(d_id)
try:
d_id.release()
#~ d_id = Non... | Python | nomic_cornstack_python_v1 |
function test_notallow_any_dict
begin
with raises ValueError as __
begin
set value = dictionary
set __ = call String value=value
end
end function | def test_notallow_any_dict():
with pytest.raises(ValueError) as __:
value = dict()
__ = param.String(value=value) | Python | nomic_cornstack_python_v1 |
comment 5/21/2020
comment Perform the necessary imports
from scipy.cluster.hierarchy import linkage , dendrogram
import matplotlib.pyplot as plt
comment Calculate the linkage: mergings
set mergings = call linkage samples method=string complete
comment Plot the dendrogram, using varieties as labels
call dendrogram mergi... | # 5/21/2020
# Perform the necessary imports
from scipy.cluster.hierarchy import linkage, dendrogram
import matplotlib.pyplot as plt
# Calculate the linkage: mergings
mergings = linkage(samples, method = 'complete')
# Plot the dendrogram, using varieties as labels
dendrogram(mergings,
labels= varieties,
... | Python | zaydzuhri_stack_edu_python |
function __init__ self task context_features sequence_features batch_size eval_batch_size feature_engineering_fn seed
begin
set _train_dataset = none
set _train_eval_dataset = none
set _val_dataset = none
set _test_dataset = none
set batch_size = batch_size
set eval_batch_size = eval_batch_size
set _create_dataset = pa... | def __init__(self, task, context_features, sequence_features, batch_size,
eval_batch_size, feature_engineering_fn, seed):
self._train_dataset = None
self._train_eval_dataset = None
self._val_dataset = None
self._test_dataset = None
self.batch_size = batch_size
self.eval_batch_size... | Python | nomic_cornstack_python_v1 |
function to_json self names
begin
raise exception string Cannot run abstract method.
end function | def to_json(self, names):
raise Exception('Cannot run abstract method.') | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Author : Rock Wayne
comment @Created : 2020-07-29 18:14:52
comment @Last Modified : 2020-07-29 18:14:52
comment @Mail : lostlorder@gmail.com
comment @Version : alpha-1.0
comment 给定一棵二叉树,以逆时针顺序从根开始返回其边界。边界按顺序包括左边界、叶子结点和右边界而不包括重复的结点。 (结点的值可能重复)
comment 左... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : Rock Wayne
# @Created : 2020-07-29 18:14:52
# @Last Modified : 2020-07-29 18:14:52
# @Mail : lostlorder@gmail.com
# @Version : alpha-1.0
# 给定一棵二叉树,以逆时针顺序从根开始返回其边界。边界按顺序包括左边界、叶子结点和右边界而不包括重复的结点。 (结点的值可能重复)
#
# 左边界的定义是从根到最左侧结点的路径。右边界... | Python | zaydzuhri_stack_edu_python |
function insert_ecoproblem ecoproblem newId modified ecoproblems_counter
begin
set delete_ecoproblem_query = format string DELETE FROM forest.ecoproblem WHERE standestimation_id = {} newId
string insert a values into the ecoproblem table
set ecoproblemquery = string INSERT INTO forest.ecoproblem ( ecoproblemtype_id, ec... | def insert_ecoproblem(ecoproblem, newId, modified, ecoproblems_counter):
delete_ecoproblem_query = """DELETE FROM forest.ecoproblem WHERE standestimation_id = {}""".format(
newId)
""" insert a values into the ecoproblem table """
ecoproblemquery = """INSERT INTO forest.ecoproblem (
ecoprobl... | Python | nomic_cornstack_python_v1 |
function test_preprocessor_re3repos test_config temp_preprocessor
begin
set DATACITE_API_REPO = test_config at string EXTERNAL at string datacite_api_repo
set RE3DATA_API = test_config at string EXTERNAL at string re3data_api
comment this is initialized why?
assert length keys re3repositories == 0
call retrieve_datacit... | def test_preprocessor_re3repos(test_config, temp_preprocessor):
DATACITE_API_REPO = test_config['EXTERNAL']['datacite_api_repo']
RE3DATA_API = test_config['EXTERNAL']['re3data_api']
assert len(temp_preprocessor.re3repositories.keys()) == 0 # this is initialized why?
temp_preprocessor.retrieve_dataci... | Python | nomic_cornstack_python_v1 |
function get resource_name id opts=none
begin
set opts = merge opts call ResourceOptions id=id
set __props__ = call __new__ IntegrationAccountSchemaArgs
set __dict__ at string changed_time = none
set __dict__ at string content = none
set __dict__ at string content_link = none
set __dict__ at string content_type = none
... | def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'IntegrationAccountSchema':
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = IntegrationAccountSchemaArgs.__new__(IntegrationAccountSchemaArgs... | Python | nomic_cornstack_python_v1 |
import numpy
import scipy.misc as smp
from PIL import Image
set file1 = string C:/Users/Aidan/Documents/Eager/Data/201805250700/PerthB01_201805250700_data.csv
set file2 = string C:/Users/Aidan/Documents/Eager/Data/201805250700/PerthB02_201805250700_data.csv
set file3 = string C:/Users/Aidan/Documents/Eager/Data/2018052... | import numpy
import scipy.misc as smp
from PIL import Image
file1 = "C:/Users/Aidan/Documents/Eager/Data/201805250700/PerthB01_201805250700_data.csv"
file2 = "C:/Users/Aidan/Documents/Eager/Data/201805250700/PerthB02_201805250700_data.csv"
file3 = "C:/Users/Aidan/Documents/Eager/Data/201805250700/PerthB03_201805250700... | Python | zaydzuhri_stack_edu_python |
import requests
import pandas as pd
set client_id = string kV9KBToXgWIqyXY3CGjB
set client_secret = string tcQXerzca7
set url = string https://openapi.naver.com/v1/search/book.json?query=파이썬
set headers = dict string X-Naver-Client-id client_id ; string X-Naver-Client-Secret client_secret
set resp = get requests url he... | import requests
import pandas as pd
client_id = "kV9KBToXgWIqyXY3CGjB"
client_secret = "tcQXerzca7"
url = "https://openapi.naver.com/v1/search/book.json?query=파이썬"
headers = {
"X-Naver-Client-id": client_id,
"X-Naver-Client-Secret": client_secret,
}
resp = requests.get(url, headers=headers)
resp = resp.json(... | Python | zaydzuhri_stack_edu_python |
function logreg_loss Y class_sign
begin
set loss = sum call softplus_actfun - class_sign * Y
return loss
end function | def logreg_loss(Y, class_sign):
loss = T.sum(softplus_actfun(-class_sign * Y))
return loss | Python | nomic_cornstack_python_v1 |
function read_integer self
begin
return call _read 4
end function | def read_integer(self):
return self._read(4) | Python | nomic_cornstack_python_v1 |
function median numbers
begin
sort numbers
if length numbers % 2 == 0
begin
return numbers at length numbers // 2 + numbers at length numbers // 2 - 1 / 2.0
end
else
begin
return numbers at length numbers // 2
end
end function | def median(numbers):
numbers.sort()
if len(numbers) % 2 == 0:
return (numbers[len(numbers)//2] + numbers[(len(numbers)//2)-1]) / 2.0
else:
return numbers[len(numbers)//2]
| Python | flytech_python_25k |
for i in range 0 10 ^ 10 + 1
begin
set n = string i
if not string 4 in n
begin
set a = integer n
set b = 0
end
else
begin
set m = string
for digit in map int n
begin
if digit == 4
begin
set m = m + string 1
end
else
begin
set m = m + string 0
end
end
set a = integer m
set b = integer n - a
end
if string 4 in string a ... | for i in range(0, 10**10+1):
n = str(i)
if not ("4" in n):
a = int(n)
b = 0
else:
m = ""
for digit in map(int, n):
if digit == 4:
m += "1"
else:
m += "0"
a = int(m)
b = int(n) - a
if (("4" in str(a)) ... | Python | zaydzuhri_stack_edu_python |
function printlist x width=70 indent=4 file=none
begin
set blanks = string * indent
comment Print the sorted list: 'x' may be a '--random' list or a set()
print call fill join string generator expression string elt for elt in sorted x width initial_indent=blanks subsequent_indent=blanks file=file
end function | def printlist(x, width=70, indent=4, file=None):
blanks = ' ' * indent
# Print the sorted list: 'x' may be a '--random' list or a set()
print(textwrap.fill(' '.join(str(elt) for elt in sorted(x)), width,
initial_indent=blanks, subsequent_indent=blanks),
file=file) | Python | nomic_cornstack_python_v1 |
function termlists_are_equal terms1 terms2
begin
return length terms1 == length terms2 and all generator expression call is_syntactically_equal y for tuple x y in zip terms1 terms2
end function | def termlists_are_equal(terms1, terms2):
return len(terms1) == len(terms2) and all(x.is_syntactically_equal(y) for x, y in zip(terms1, terms2)) | Python | nomic_cornstack_python_v1 |
string Usage: python change_line_value.py config/simu.conf.boom2 test_simu.conf.boom2 88 -l 393 -n busWidth
function make_change input_path output_path value line_number=none name=none
begin
with open input_path as f
begin
set lines = read lines f
end
assert not line_number is none or name is none
set line_number = lin... | """
Usage:
python change_line_value.py config/simu.conf.boom2 test_simu.conf.boom2 88 -l 393 -n busWidth
"""
def make_change(input_path, output_path, value, line_number=None, name=None):
with open(input_path) as f:
lines = f.readlines()
assert not (line_number is None or name is None)
line_number -= ... | Python | zaydzuhri_stack_edu_python |
comment get the python version i'm using
comment system specif parameters and function
import sys
print version
comment display current date and time
import datetime
print today
comment circle area
import math
set r = integer input string insert radius:
print string The area is: string r ^ 2 * pi
comment converto strin... | #get the python version i'm using
import sys #system specif parameters and function
print(sys.version)
#display current date and time
import datetime
print(datetime.datetime.today())
#circle area
import math
r = int(input("insert radius: "))
print("The area is: ", str(r**2*math.pi))
#converto stringa in input con va... | Python | zaydzuhri_stack_edu_python |
function get_partlists page=none page_size=none user_token=none api_key=none
begin
set parameters = dict string page page ; string page_size page_size ; string key api_key
set user_token = call assert_user_token user_token
set path = API_USERS_URL + string %s/partlists/ % user_token
return call request path parameters
... | def get_partlists(page=None, page_size=None, user_token=None, api_key=None):
parameters = {
'page': page,
'page_size': page_size,
'key': api_key}
user_token = assert_user_token(user_token)
path = config.API_USERS_URL + "%s/partlists/" % user_token
return request(pa... | Python | nomic_cornstack_python_v1 |
from builtins import range
import numpy as np
from robust.linearize_twoterm_posynomials import LinearizeTwoTermPosynomials
import os
function construct_linearization_data max_num_of_linear_sections the_file_path
begin
set the_file = open the_file_path string w
for i in range 2 max_num_of_linear_sections
begin
set a = c... | from builtins import range
import numpy as np
from robust.linearize_twoterm_posynomials import LinearizeTwoTermPosynomials
import os
def construct_linearization_data(max_num_of_linear_sections, the_file_path):
the_file = open(the_file_path, "w")
for i in range(2, max_num_of_linear_sections):
a = Linea... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri May 7 16:19:19 2021 @author: ingma
import pandas as pd
from datetime import datetime , timedelta
comment Récupération des données
set data = read csv string data.csv
set time = read csv string timetables.csv
set analyse_date = call datetime 2021 5 6 16 0 0
comment réc... | # -*- coding: utf-8 -*-
"""
Created on Fri May 7 16:19:19 2021
@author: ingma
"""
import pandas as pd
from datetime import datetime, timedelta
#Récupération des données
data = pd.read_csv("data.csv")
time = pd.read_csv("timetables.csv")
analyse_date = datetime(2021, 5, 6, 16,0,0)
#récupération d... | Python | zaydzuhri_stack_edu_python |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other):
return not self == other | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[29]:
import plotly
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.colors import n_colors
function plt_tab4
begin
set df4 = read csv string D:\insight_project\tabs\refined_tab\tab1_4.csv error_... | #!/usr/bin/env python
# coding: utf-8
# In[29]:
import plotly
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.colors import n_colors
def plt_tab4():
df4 = pd.read_csv("D:\\insight_project\\tabs\\refined_tab\\tab1_4.csv", error_bad_lines=False)
... | Python | zaydzuhri_stack_edu_python |
function solve self
begin
while path at - 1 != 88
begin
set n = call next_move
if n is none
begin
set path = path + list string Error: Could not find full path (budget does not suffice or unreachable).
break
end
set path = path + list n
call updated_occupied_locations
set currentTurn = currentTurn + 1
end
end function | def solve(self):
while self.character.path[-1] != 88:
n = self.next_move()
if n is None:
self.character.path += ['Error: Could not find full path (budget does not suffice or unreachable).']
break
self.character.path += [n]
self.upda... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.