code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from math import floor
set tuple A B N = list map int split input
if N < B
begin
print floor A * N / B - A * floor N / B
end
else
begin
print floor A * B - 1 / B - A * floor B - 1 / B
end | from math import floor
A, B, N = list(map(int, input().split()))
if N < B:
print(floor(A*N/B)-A*floor(N/B))
else:
print(floor(A*(B-1)/B)-A*floor((B-1)/B)) | Python | zaydzuhri_stack_edu_python |
string Created on May 11, 2015 @author: TDARSEY
import os.path
import json
import fnmatch
from settings import Settings
class Project extends object
begin
string classdocs
function __init__ self **kwargs
begin
string Constructor
set other_attributes = dict
set name = string
set inventory_code = string
set program_na... | '''
Created on May 11, 2015
@author: TDARSEY
'''
import os.path
import json
import fnmatch
from settings import Settings
class Project(object):
'''classdocs
'''
def __init__(self, **kwargs):
'''Constructor
'''
self.other_attributes = {}
self.name = ""
self.in... | Python | zaydzuhri_stack_edu_python |
function setCompartmentType self *args
begin
return call Compartment_setCompartmentType self *args
end function | def setCompartmentType(self, *args):
return _libsbml.Compartment_setCompartmentType(self, *args) | Python | nomic_cornstack_python_v1 |
function _product l
begin
return reduce mul l 1
end function | def _product(l):
return reduce(mul, l, 1) | Python | nomic_cornstack_python_v1 |
import pygame
from pygame.locals import *
from function import *
import os
import platform
from math import *
comment on importe les modules
import sys , glob
comment taille de la fenêtre
comment hauteur
set h = 600
comment largeur
set l = 1200
set screen = call set_mode tuple l h
comment controle le framerate du jeu
s... | import pygame
from pygame.locals import *
from function import *
import os
import platform
from math import *
import sys, glob #on importe les modules
# taille de la fenêtre
h=600 #hauteur
l=1200 # largeur
screen = pygame.display.set_mode((l,h))
clock = pygame.time.Clock() # controle le framerate du jeu
# --------... | Python | zaydzuhri_stack_edu_python |
function consolidate_matches
begin
set infile = string Files/inter_group_matches_positives.txt
with open infile encoding=string utf8 as f
begin
set inter_group_matches_positives = read lines f
set lg = length inter_group_matches_positives
comment p(inter_group_matches_positives)
set fields = split inter_group_matches_p... | def consolidate_matches():
infile = "Files/inter_group_matches_positives.txt"
with open(infile, encoding="utf8") as f:
inter_group_matches_positives = f.readlines()
lg = len(inter_group_matches_positives)
# p(inter_group_matches_positives)
fields = inter_group_matches_positives[1... | Python | nomic_cornstack_python_v1 |
function remove self key columns=none super_column=none timestamp=none
begin
return remove Mutator self _column_family key columns super_column timestamp
end function | def remove(self, key, columns=None, super_column=None, timestamp=None):
return Mutator.remove(self, self._column_family, key,
columns, super_column, timestamp) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import geopandas as gpd
from geopandas.tools import sjoin
from shapely.geometry import Point
function clean_data df
begin
string Fill in missing observation types based on the information given about specific obstructions. Arguments: df : a pandas DataFrame A DataFrame containing the sidewalk obstru... | import pandas as pd
import geopandas as gpd
from geopandas.tools import sjoin
from shapely.geometry import Point
def clean_data(df):
""" Fill in missing observation types based on the information given about
specific obstructions.
Arguments:
df : a pandas DataFrame
A DataFrame contain... | Python | zaydzuhri_stack_edu_python |
function init
begin
comment initialize pygame
call init
comment setup the screen
set screen = call set_mode tuple 640 480 DOUBLEBUF 32
call set_caption string Connect4X
end function | def init():
# initialize pygame
pygame.init()
# setup the screen
screen = pygame.display.set_mode((640, 480), pygame.DOUBLEBUF, 32)
pygame.display.set_caption("Connect4X") | Python | nomic_cornstack_python_v1 |
comment 09/09/2020 Kristin Kim, SSW 567 HW 01: Testing triangle classification
import unittest
function classifyTriangle a b c
begin
if a + b < c or a + c < b or c + b < a
begin
return string NotATriangle
end
else
if a == b == c
begin
return string Equilateral
end
else
if a == b or a == c or b == c
begin
return string ... | # 09/09/2020 Kristin Kim, SSW 567 HW 01: Testing triangle classification
import unittest
def classifyTriangle(a,b,c):
if a+b<c or a+c<b or c+b<a:
return "NotATriangle"
elif a==b==c:
return "Equilateral"
elif a==b or a==c or b==c:
return "Isosceles"
elif a^2+b^2==c^2:... | Python | zaydzuhri_stack_edu_python |
string #***************************************************************************** # Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>, # # Distributed under the terms of the GNU General Public License (GPL) # # This code is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even th... | """
#*****************************************************************************
# Copyright (C) 2007 Mike Hansen <mhansen@gmail.com>,
#
# Distributed under the terms of the GNU General Public License (GPL)
#
# This code is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; witho... | Python | zaydzuhri_stack_edu_python |
from abc import ABC , abstractmethod
import pydantic
from pydantic import BaseModel
from enum import Enum
from typing import List , Tuple , Optional , Dict
import math
from termcolor import colored
from colorama import init , Fore , Back , Style
class Rank extends Enum
begin
set ONE = 1
set TWO = 2
set THREE = 3
set FO... | from abc import ABC, abstractmethod
import pydantic
from pydantic import BaseModel
from enum import Enum
from typing import List, Tuple, Optional, Dict
import math
from termcolor import colored
from colorama import init, Fore, Back, Style
class Rank(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 4
FIVE ... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
from temp_views import Temporary_views
call set_option string display.width 100000
call set_option string display.max_columns 1000000
call set_option string display.max_rows 10000000
string Este arquivo contem a classe Relatorios2 que corresponde à geracao de relatorio incluindo-se as simulacoes fei... | import pandas as pd
from temp_views import Temporary_views
pd.set_option('display.width', 100000)
pd.set_option('display.max_columns', 1000000)
pd.set_option('display.max_rows', 10000000)
'''
Este arquivo contem a classe Relatorios2 que corresponde à geracao de relatorio incluindo-se as simulacoes feitas pe... | Python | zaydzuhri_stack_edu_python |
function raise_to_top self
begin
call wlr_scene_node_raise_to_top _ptr
end function | def raise_to_top(self) -> None:
lib.wlr_scene_node_raise_to_top(self._ptr) | Python | nomic_cornstack_python_v1 |
import socket
import logging
import time
import sys
call basicConfig format=string [LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s level=NOTSET
set port = 10020
set adresa = string 198.10.0.2
set server_address = tuple adresa port
set mesaj = string merea
info string Handshake cu %s string server_address
s... | import socket
import logging
import time
import sys
logging.basicConfig(format = u'[LINE:%(lineno)d]# %(levelname)-8s [%(asctime)s] %(message)s', level = logging.NOTSET)
port = 10020
adresa = '198.10.0.2'
server_address = (adresa, port)
mesaj = "merea"
logging.info('Handshake cu %s', str(server_address))
sock = socke... | Python | zaydzuhri_stack_edu_python |
function get_index_relative_to_object_for_ts obj timestamp timestamp_list
begin
set nearest_timestamp = call find_nearest timestamp_list timestamp
end function | def get_index_relative_to_object_for_ts(obj, timestamp, timestamp_list):
nearest_timestamp = find_nearest(timestamp_list, timestamp) | Python | nomic_cornstack_python_v1 |
function list_images self repository_name registry_id=none
begin
set repository = none
set found = false
if repository_name in repositories
begin
set repository = repositories at repository_name
if registry_id
begin
if registry_id == registry_id
begin
set found = true
end
end
else
begin
set found = true
end
end
if not ... | def list_images(self, repository_name, registry_id=None):
repository = None
found = False
if repository_name in self.repositories:
repository = self.repositories[repository_name]
if registry_id:
if repository.registry_id == registry_id:
... | Python | nomic_cornstack_python_v1 |
function _get_new_words self current_text index
begin
raise call NotImplementedError
end function | def _get_new_words(self, current_text, index):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
comment author: Daniel Lozano
comment source: HackerRank ( https://www.hackerrank.com )
comment problem name: Algorithms: Implementation: Counting Valleys
comment problem url: https://www.hackerrank.com/challenges/counting-valleys/problem
set n = integer input
set hike = input
set sea_level = 0
set valley = 0
for step ... | # author: Daniel Lozano
# source: HackerRank ( https://www.hackerrank.com )
# problem name: Algorithms: Implementation: Counting Valleys
# problem url: https://www.hackerrank.com/challenges/counting-valleys/problem
n = int(input())
hike = input()
sea_level = 0
valley = 0
for step in hike:
if step == "U":
... | Python | zaydzuhri_stack_edu_python |
function latitude self latitude
begin
set _latitude = latitude
end function | def latitude(self, latitude):
self._latitude = latitude | Python | nomic_cornstack_python_v1 |
function add a b
begin
set sum = a + b
return sum
end function
function sub a b
begin
set difference = a - b
return difference
end function
function mult a b
begin
set product = a * b
return product
end function
function div a b
begin
set quotient = a / b
return quotient
end function | def add(a, b):
sum = a + b
return(sum)
def sub(a, b):
difference = a - b
return(difference)
def mult(a, b):
product = a * b
return(product)
def div(a, b):
quotient = a / b
return(quotient)
| Python | zaydzuhri_stack_edu_python |
from all_persist_ops.employee import Employee
function get_input_from_user idwant=false
begin
set eid = 0
if idwant
begin
print string Enter Values for Add Operations
set eid = integer input string Enter Emp Id :
end
else
begin
print string Enter Values for update Operations
end
set name = input string Enter Emp Name :... | from all_persist_ops.employee import Employee
def get_input_from_user(idwant=False):
eid = 0
if idwant:
print('Enter Values for Add Operations')
eid = int(input('Enter Emp Id : '))
else:
print('Enter Values for update Operations')
name = input('Enter Emp Name : ')
eage = int... | Python | zaydzuhri_stack_edu_python |
function fieldset_end self
begin
return call Markup string </fieldset>
end function | def fieldset_end(self):
return Markup(u'</fieldset>\n') | Python | nomic_cornstack_python_v1 |
import os
function populate
begin
call add_title title=string Some text about Burger content=string A hamburger (also called a beef burger, hamburger sandwich, burger or hamburg) is a sandwich consisting of one or more cooked patties of ground meat, usually beef, placed inside a sliced bun. Hamburgers are often served ... | import os
def populate():
add_title(title="Some text about Burger",
content=""" A hamburger (also called a beef burger, hamburger sandwich, burger or hamburg) is a sandwich consisting of one or more cooked patties of ground meat, usually beef, placed inside a sliced bun.
Hamburgers are often served with lettuce,... | Python | zaydzuhri_stack_edu_python |
function login_success request
begin
if not has attribute user string profile
begin
return call redirect string index
end
else
begin
return call redirect string registration_process
end
end function | def login_success(request):
if not hasattr(request.user, 'profile'):
return redirect('index')
else:
return redirect('registration_process') | Python | nomic_cornstack_python_v1 |
function remove_node self node
begin
set prev = prev
set new = next
set next = new
set prev = prev
end function | def remove_node(self, node):
prev = node.prev
new = node.next
prev.next = new
new.prev = prev | Python | nomic_cornstack_python_v1 |
function pre_process_item_filter self
begin
comment TODO: Maybe someone has a custom location for their item filters, so this search path probably shouldn't be hard coded like this
comment self.main_filter_path = os.path.join(os.environ['USERPROFILE'], "Documents", "My Games", "Path of Exile", self.config['Config']['fi... | def pre_process_item_filter(self):
#TODO: Maybe someone has a custom location for their item filters, so this search path probably shouldn't be hard coded like this
# self.main_filter_path = os.path.join(os.environ['USERPROFILE'], "Documents", "My Games", "Path of Exile", self.config['Config']['filter']... | Python | nomic_cornstack_python_v1 |
import sys
import os
from skeleton import *
import numpy as np
import pandas as pd
import statsmodels.tsa.stattools as ts
import kalman as ka
import johansen as jn
import datetime
class BasicMR extends Strategy
begin
string Mean Reversion Strategy for one security with Bollinger Bands. If many securities supplied, it a... | import sys
import os
from skeleton import *
import numpy as np
import pandas as pd
import statsmodels.tsa.stattools as ts
import kalman as ka
import johansen as jn
import datetime
class BasicMR(Strategy):
"""Mean Reversion Strategy for one security with Bollinger Bands.
If many securities supplied, it analyze... | Python | zaydzuhri_stack_edu_python |
for line in read lines open string 5-input.txt
begin
append l integer line
end
comment l = [0,3,0,1,-3]
set escape = false
set idx = 0
set numSteps = 0
while not escape
begin
try
begin
set jmp = l at idx
if jmp >= 3
begin
set l at idx = l at idx - 1
end
else
begin
set l at idx = l at idx + 1
end
set idx = idx + jmp
set... | for line in open('5-input.txt').readlines():
l.append(int(line))
# l = [0,3,0,1,-3]
escape = False
idx = 0
numSteps = 0
while not escape:
try:
jmp = l[idx]
if jmp >= 3:
l[idx] -= 1
else:
l[idx] += 1
idx += jmp
numSteps += 1
except IndexError:
escape = True
| Python | zaydzuhri_stack_edu_python |
function max_sum_from_start array
begin
set array_sum = 0
set max_sum = decimal string -inf
for num in array
begin
set array_sum = array_sum + num
if array_sum > max_sum
begin
set max_sum = array_sum
end
end
return max_sum
end function | def max_sum_from_start(array):
array_sum = 0
max_sum = float("-inf")
for num in array:
array_sum += num
if array_sum > max_sum:
max_sum = array_sum
return max_sum | Python | nomic_cornstack_python_v1 |
function test_image_utf8 self
begin
set request = call blank string /image.gif?cur= + call quote_plus encode string http://www.mysite.com/page string utf8 + string &ref= + call quote_plus encode string http://www.google.com?q=café string utf8 + string &title=Google
set response = call get_response app
assert equal stri... | def test_image_utf8(self):
request = Request.blank('/image.gif?cur='
+ quote_plus(u'http://www.mysite.com/page'.encode('utf8'))
+ '&ref='
+ quote_plus(u'http://www.google.com?q=café'.encode('utf8'))
+ '&title=Google'
)
response... | Python | nomic_cornstack_python_v1 |
function run self scheduler_schedule_id **kwargs
begin
string Deactivates the schedule specified by the ID `scheduler_schedule_id` in the scheduler service. Arguments: scheduler_schedule_id {str} -- The ID of the schedule to deactivate
set log = call get_logger keyword kwargs
call update_schedule scheduler_schedule_id ... | def run(self, scheduler_schedule_id, **kwargs):
"""
Deactivates the schedule specified by the ID `scheduler_schedule_id` in
the scheduler service.
Arguments:
scheduler_schedule_id {str} -- The ID of the schedule to deactivate
"""
log = self.get_logger(**kwarg... | Python | jtatman_500k |
function amplify_noise noise
begin
set tuple min max = tuple min max
set amplification = 255.0 / max - min
return as type noise * amplification string uint8
end function | def amplify_noise(noise):
min, max = noise.min(), noise.max()
amplification = 255.0 / (max - min)
return (noise * amplification).astype("uint8") | Python | nomic_cornstack_python_v1 |
function get_output_vp x vpID
begin
set trials = 0
set file = open x + string /output_vp + string vpID string r
try
begin
while 1
begin
set zeile = read line file
set _ = zeile at 0
set trials = trials + 1
end
end
except any
begin
close file
end
set file = open x + string /output_vp + string vpID string r
set correct =... | def get_output_vp(x, vpID):
trials = 0
file = open(x + "/output_vp" + str(vpID), "r")
try:
while 1:
zeile = file.readline()
_ = zeile[0]
trials += 1
except:
file.close()
file = open(x + "/output_vp" + str(vpID), "r")
correct = np.zeros(trials)... | Python | nomic_cornstack_python_v1 |
function test_config celery_app
begin
set result = call send_task string tests.tasks.mul args=tuple 4 4
assert get result == 16
end function | def test_config(celery_app):
result = celery_app.send_task('tests.tasks.mul', args=(4, 4))
assert result.get() == 16 | Python | nomic_cornstack_python_v1 |
function getCrossingAngleEC self
begin
set Axes = list
set Axes = list comprehension list ECAxis_X ECAxis_Y ECAxis_Z for tmhelix in tmhelixmodel_set
set CrossingAngleEC = call AngleDEG
return
end function | def getCrossingAngleEC (self):
Axes = []
Axes = [[tmhelix.ECAxis_X,tmhelix.ECAxis_Y,tmhelix.ECAxis_Z] for tmhelix in self.tmhelixmodel_set]
CrossingAngleEC = SetOfVectors([Axes[0], Axes[1] ]) .AngleDEG ()
return | Python | nomic_cornstack_python_v1 |
function enable self delay=false
begin
set enabled = true
if delayed == false
begin
set delayed = delay
end
end function | def enable(self, delay=False) -> None:
self.enabled = True
if self.delayed == False:
self.delayed = delay | Python | nomic_cornstack_python_v1 |
function _load_data name
begin
set filename = join path absolute path path directory name path __file__ string data name
with load np filename as f
begin
return dictionary items f
end
end function | def _load_data(name):
filename = os.path.join(os.path.abspath(os.path.dirname(__file__)),
'data', name)
with np.load(filename) as f:
return dict(f.items()) | Python | nomic_cornstack_python_v1 |
function test_user_cannot_register_with_invalid_username self
begin
set response = post SIGNUP_URL data=dumps dict string username string #_danny ; string email string danny@gmail.com ; string password string pass12345 content_type=string application/json
assert equal status_code 400
set result = loads decode data
asse... | def test_user_cannot_register_with_invalid_username(self):
response = self.client.post(SIGNUP_URL,
data=json.dumps(
{'username': '#_danny', 'email': 'danny@gmail.com', 'password': 'pass12345'}),
conte... | Python | nomic_cornstack_python_v1 |
while true
begin
set l = input
if l == string fin
begin
break
end
append inpt l
end
print inpt
set i = 0
set t1 = list
set t2 = list
set t3 = list
for l in inpt
begin
set i = i + 1
set list = list
for s in split strip l string
begin
set m = strip s
if m != string
begin
append list integer m
end
end
append t1 list ... | while True:
l= input()
if l=='fin':
break
inpt.append(l)
print(inpt)
i =0
t1 =[]
t2=[]
t3=[]
for l in inpt:
i +=1
list = []
for s in l.strip().split(" "):
m = s.strip()
if (m != ''):
list.append(int(m))
t1.append(list[0])
t2.append(list[1])
t3.... | Python | zaydzuhri_stack_edu_python |
function make_entry isbn
begin
set ecs = call import_pyaws_ecs
import bibfile
set entry = call BibEntry
set entry_type = string book
end function | def make_entry(isbn):
ecs = import_pyaws_ecs()
import bibfile
entry = bibfile.BibEntry()
entry.entry_type = 'book' | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import math
set i = 1
set a = integer input string digite um numero:
set b = integer input string digite um numero:
set c = integer input string digite um numero:
set d = integer input string digite um numero: | # -*- coding: utf-8 -*-
import math
i = 1
a = int(input('digite um numero:'))
b= int(input('digite um numero:'))
c = int(input('digite um numero:'))
d= int(input('digite um numero:')) | Python | zaydzuhri_stack_edu_python |
import os
import shutil
import zipfile
from flask import flash
function flashmsg msg
begin
try
begin
call flash msg
end
except RuntimeError
begin
pass
end
end function
function request_files_empty request_result filetype
begin
if filename == string or filename is none
begin
call flashmsg string Empty in submission: + ... | import os
import shutil
import zipfile
from flask import flash
def flashmsg(msg):
try:
flash(msg)
except RuntimeError:
pass
def request_files_empty(request_result, filetype):
if request_result.filename == '' or request_result.filename is None:
flashmsg('Empty in submission: ' + ... | Python | zaydzuhri_stack_edu_python |
class GroceryItem
begin
function __init__ self name price quantity
begin
set name = name
set price = price
set quantity = quantity
end function
end class | class GroceryItem:
def __init__(self, name, price, quantity):
self.name = name
self.price = price
self.quantity = quantity | Python | jtatman_500k |
import math
set tuple N D = map int split input
set xd = list comprehension list map int split input for _ in range N
set ans = 0
for i in range N - 1
begin
for j in range i + 1 N
begin
set t = 0
for k in range D
begin
set t = t + power xd at i at k - xd at j at k 2
end
set t = square root t
if t == decimal integer t
b... | import math
N, D = map(int, input().split())
xd = [list(map(int, input().split())) for _ in range(N)]
ans = 0
for i in range(N-1):
for j in range(i+1, N):
t = 0
for k in range(D):
t += pow(xd[i][k]-xd[j][k], 2)
t = math.sqrt(t)
if t == float(int(t)):
ans += 1
... | Python | zaydzuhri_stack_edu_python |
function resolve_bypred predicate minimum=1 timeout=FOREVER
begin
string Resolve all streams that match a given predicate. Advanced query that allows to impose more conditions on the retrieved streams; the given string is an XPath 1.0 predicate for the <description> node (omitting the surrounding []'s), see also http:/... | def resolve_bypred(predicate, minimum=1, timeout=FOREVER):
"""Resolve all streams that match a given predicate.
Advanced query that allows to impose more conditions on the retrieved
streams; the given string is an XPath 1.0 predicate for the <description>
node (omitting the surrounding []'s), see also... | Python | jtatman_500k |
comment _*_ coding:utf-8 _*_
import time
import datetime
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.cross_validation import KFold
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
comment 误差计算公式
functi... | # _*_ coding:utf-8 _*_
import time
import datetime
import numpy as np
import pandas as pd
import lightgbm as lgb
from sklearn.cross_validation import KFold
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import train_test_split
from sklearn.externals import joblib
# 误差计算公式
def evalerror(pre... | Python | zaydzuhri_stack_edu_python |
from characters import Character
from dialogue import Dialogue
import locations
import time
class Player extends Character
begin
function __init__ self name location attr=none
begin
call __init__ name location attr
set _isPlayer = true
end function
function getAction self
begin
while call isAlive
begin
set act = split ... | from characters import Character
from dialogue import Dialogue
import locations
import time
class Player(Character):
def __init__(self, name, location, attr = None):
super().__init__(name, location, attr)
self._isPlayer = True
def getAction(self):
while self.isAlive():
act ... | Python | zaydzuhri_stack_edu_python |
comment ds -> (date / datetime / timestamp)
comment y -> is numeric value that we will try to forecast / predict
comment * Which growth that we will use (linear or logistics)
comment * Which model that we will use (additive or multiplicative)
comment * Changepoint (Automatatic and Manual approach)
comment * Trend Flexi... | # ds -> (date / datetime / timestamp)
# y -> is numeric value that we will try to forecast / predict
#
# * Which growth that we will use (linear or logistics)
# * Which model that we will use (additive or multiplicative)
# * Changepoint (Automatatic and Manual approach)
# * Trend Flexibility (How to adjust t... | Python | zaydzuhri_stack_edu_python |
import motors
import sensors
from time import time
from timeit import default_timer
set leftMotor = call MotorWithEncoder DIR_pin=22 PWM_pin=17 ENC_pin=4
set rightMotor = call MotorWithEncoder DIR_pin=23 PWM_pin=18 ENC_pin=26
set transducer = call Transducer
set last_time = time
try
begin
while true
begin
run speed=20 ... | import motors
import sensors
from time import time
from timeit import default_timer
leftMotor = motors.MotorWithEncoder(DIR_pin=22, PWM_pin=17, ENC_pin=4)
rightMotor = motors.MotorWithEncoder(DIR_pin=23, PWM_pin=18, ENC_pin=26)
transducer = sensors.Transducer()
last_time = time()
try:
while True:
leftM... | Python | zaydzuhri_stack_edu_python |
import sys
import os
import json
import records
import psycopg2
import logging
import datetime
import psycopg2.extras
from jsonschema import validate
from typing import List , Dict , Any
from db_initialise import DatabaseInitialLogin
call basicConfig format=string %(name)s - %(asctime)s - %(message)s datefmt=string %d-... | import sys
import os
import json
import records
import psycopg2
import logging
import datetime
import psycopg2.extras
from jsonschema import validate
from typing import List, Dict, Any
from db_initialise import DatabaseInitialLogin
logging.basicConfig(format='%(name)s - %(asctime)s - %(message)s',
datefmt='%d-... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
comment DFS version.
function solve self board
begin
string :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead.
if length board > 0 and length board at 0 > 0
begin
set N = length board
set M = length board at 0
set directions = list tuple ... | class Solution(object):
# DFS version.
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if len(board) > 0 and len(board[0]) > 0:
N = len(board)
M = len(board[0])
... | Python | zaydzuhri_stack_edu_python |
function add_fixed_parameters_from_config_file self config_file
begin
call _add_fixed_parameters_from_config_file config_file _add_fixed_parameters
end function | def add_fixed_parameters_from_config_file(self, config_file):
self._add_fixed_parameters_from_config_file(
config_file, self._add_fixed_parameters) | Python | nomic_cornstack_python_v1 |
function ScriptSymbols script include_script_code=false
begin
set script_chars = call UnicodeSet string [\p{%s}\u200C\u200D] % call getName
set script_name = replace call getName string _ string
write stderr string Found %d characters specific to %s (%s) % tuple length script_chars script_name call getShortName
set pre... | def ScriptSymbols(script, include_script_code=False):
script_chars = icu.UnicodeSet(r'[\p{%s}\u200C\u200D]' % script.getName())
script_name = script.getName().replace('_', ' ')
utf8.stderr.write('Found %d characters specific to %s (%s)\n' %
(len(script_chars), script_name, script.getShortName(... | Python | nomic_cornstack_python_v1 |
class Employee
begin
function __init__ self name age salary
begin
set name = name
set age = age
set salary = salary
end function
function get_info self
begin
return format string Employee({}, {}, {}) name age salary
end function
end class | class Employee:
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def get_info(self):
return 'Employee({}, {}, {})'.format(self.name, self.age, self.salary) | Python | iamtarun_python_18k_alpaca |
import sys , PIL.Image
set imageName = replace call rsplit string . 1 at 0 string - string _
set img = call convert string L
set threshold = 128 * list 0 + 128 * list 255
for y in range size at 1
begin
for x in range size at 0
begin
set old = call getpixel tuple x y
set new = threshold at old
end
end
comment err = (old... | import sys, PIL.Image
imageName = sys.argv[-1].rsplit( ".", 1 )[ 0 ].replace("-","_")
img = PIL.Image.open(sys.argv[-1]).convert('L')
threshold = 128*[0] + 128*[255]
for y in range(img.size[1]):
for x in range(img.size[0]):
old = img.getpixel((x, y))
new = threshold[old]
#err = (old - new... | Python | zaydzuhri_stack_edu_python |
function write_to_coupon_collection self data
begin
try
begin
comment print data
set result = insert collection_coupon data
end
except Exception as e
begin
raise e
end
return result
end function | def write_to_coupon_collection(self, data):
try:
#print data
result = db.collection_coupon.insert(data)
except Exception as e:
raise e
return result | Python | nomic_cornstack_python_v1 |
function rollback_ldif self
begin
return get pulumi self string rollback_ldif
end function | def rollback_ldif(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "rollback_ldif") | Python | nomic_cornstack_python_v1 |
function returnInstance cls name
begin
if name not in __repairs
begin
call raiseAnError IOError format string {} MECHANISM NOT IMPLEMENTED!!!!! name
end
return __repairs at name
end function | def returnInstance(cls, name):
if name not in __repairs:
cls.raiseAnError (IOError, "{} MECHANISM NOT IMPLEMENTED!!!!!".format(name))
return __repairs[name] | Python | nomic_cornstack_python_v1 |
async function approve self ctx user
begin
set server = server
if id in norole at id
begin
if norole at id at id at string Role == true
begin
set norole at id at id = dict string Role false
call save_json warninglist norole
set nobnl = get utils roles name=string NoBNL
await call remove_roles user nobnl
set msg = await... | async def approve(self, ctx, user: discord.Member):
server = ctx.message.server
if user.id in self.norole[server.id]:
if self.norole[server.id][user.id]['Role'] == True:
self.norole[server.id][user.id] = {'Role': False}
dataIO.save_json(self.warninglist, self.... | Python | nomic_cornstack_python_v1 |
function getJitterRadius self **kwargs
begin
pass
end function | def getJitterRadius(self, **kwargs):
pass | Python | nomic_cornstack_python_v1 |
function encode a b c
begin
set strabc = list string a string b string c
set output = string
for x in strabc
begin
set diff = 3 - length x
if diff > 0
begin
set x = string 0 * diff + x
set output = output + x
end
end
comment str(a)+str(b)+str(c)
return output
end function | def encode(a,b,c):
strabc = [str(a),str(b),str(c)]
output = ''
for x in strabc:
diff = 3 - len(x)
if diff > 0:
x = '0'*diff + x
output += x
return output #str(a)+str(b)+str(c)
| Python | nomic_cornstack_python_v1 |
function ContainsLabel self row_asm
begin
for label in labels
begin
if label in row_asm
begin
return label
end
end
return none
end function | def ContainsLabel(self, row_asm):
for label in self.labels:
if label in row_asm:
return label
return None | Python | nomic_cornstack_python_v1 |
function ip_to_int ip
begin
set match = match string ^(\d+).(\d+).(\d+).(\d+)$ ip
if not match
begin
raise call ValueError format string Malformed IPv4 address '{}' ip
end
set ip_int = 0
for group in map int call groups
begin
if group ? ? 255
begin
raise call ValueError format string Malformed IPv4 address '{}' ip
end
... | def ip_to_int(ip):
match = re.match(r"^(\d+).(\d+).(\d+).(\d+)$", ip)
if not match:
raise ValueError("Malformed IPv4 address '{}'".format(ip))
ip_int = 0
for group in map(int, match.groups()):
if group & ~0xFF:
raise Va... | Python | nomic_cornstack_python_v1 |
function scaffold_fn
begin
call init_from_checkpoint params at string resnet_checkpoint dict string / string resnet%s/ % RESNET_DEPTH
return call Scaffold
end function | def scaffold_fn():
tf.train.init_from_checkpoint(params['resnet_checkpoint'], {
'/': 'resnet%s/' % ssd_constants.RESNET_DEPTH,
})
return tf.train.Scaffold() | Python | nomic_cornstack_python_v1 |
function aumentar preço=0 taxa=0 formato=false
begin
set res = preço + preço * taxa / 100
return if expression formato is false then res else call moeda res
end function
function diminuir preço=0 taxa=0 formato=false
begin
set res = preço - preço * taxa / 100
return if expression formato is false then res else call moe... | def aumentar(preço=0, taxa=0, formato=False):
res = preço + (preço * (taxa / 100))
return res if formato is False else moeda(res)
def diminuir(preço=0, taxa=0, formato=False):
res = preço - (preço * (taxa / 100))
return res if formato is False else moeda(res)
def dobro(preço=0, formato=False):
r... | Python | zaydzuhri_stack_edu_python |
async function _notes self ctx
begin
pass
end function | async def _notes(self, ctx: Context):
pass | Python | nomic_cornstack_python_v1 |
function distance_alt v1 v2
begin
set x1 = v1 at 0
set y1 = v1 at 1
set z1 = v1 at 2
set x2 = v2 at 0
set y2 = v2 at 1
set z2 = v2 at 2
return square root x2 - x1 * pi / 180 * 6356.752 * cos y1 + y2 * pi / 360 ^ 2 + y2 - y1 * pi / 180 * 6356.752 ^ 2 + z1 - z2 / 1000.0 ^ 2
end function | def distance_alt(v1,v2):
x1=v1[0]
y1=v1[1]
z1=v1[2]
x2=v2[0]
y2=v2[1]
z2=v2[2]
return np.sqrt(((x2-x1)*np.pi/180*6356.752*np.cos((y1+y2)*np.pi/360))**2+((y2-y1)*np.pi/180*6356.752)**2 + ((z1-z2)/1000.)**2) | Python | nomic_cornstack_python_v1 |
function SetFace self *args
begin
return call ShapeUpgrade_EdgeDivide_SetFace self *args
end function | def SetFace(self, *args):
return _ShapeUpgrade.ShapeUpgrade_EdgeDivide_SetFace(self, *args) | Python | nomic_cornstack_python_v1 |
function is_expired self key now=none remove=false
begin
with _lock
begin
if now is none
begin
set now = time
end
comment pylint: disable=unused-variable
set tuple expire _value = _values at key
if expire is none
begin
return false
end
set expired = expire < now
if expired and remove
begin
call __delitem__ key
end
retu... | def is_expired(self, key, now=None, remove=False):
with self._lock:
if now is None:
now = time.time()
# pylint: disable=unused-variable
expire, _value = self._values[key]
if expire is None:
return False
expired = expire ... | Python | nomic_cornstack_python_v1 |
function Factors no1
begin
set fact = 0
for i in range 1 no1 // 2 + 1
begin
if no1 % i == 0
begin
set fact = fact + i
end
end
return fact
end function
function main
begin
set no1 = integer input string Enter The Number:
print string Addition of no1 string Factor is call Factors no1 string !
end function
if __name__ == ... | def Factors(no1):
fact = 0;
for i in range(1,(no1//2)+1):
if no1%i == 0:
fact = fact + i;
return fact;
def main():
no1 = int(input("Enter The Number:"));
print("Addition of ",no1," Factor is ",Factors(no1),"!");
if __name__ == "__main__":
main(); | Python | zaydzuhri_stack_edu_python |
function iot_list_devices client args
begin
set offset = get args string offset string 0
set pagelength = get args string limit max_fetch
set result = call list_devices offset pagelength
if not result
begin
return call CommandResults readable_output=string ### No devices found
end
return call CommandResults outputs_pre... | def iot_list_devices(client, args):
offset = args.get('offset', '0')
pagelength = args.get('limit', client.max_fetch)
result = client.list_devices(offset, pagelength)
if not result:
return CommandResults(
readable_output='### No devices found'
)
return CommandResults(
... | Python | nomic_cornstack_python_v1 |
import pygame
import os
from pygame.sprite import Sprite
class Wall extends Sprite
begin
function __init__ self game x y settings type
begin
call __init__
set settings = settings
set g = game
set type = type
set image = call Surface tuple tileSize tileSize
set rect = call get_rect
set x = x * tileSize
set y = y * tileS... | import pygame
import os
from pygame.sprite import Sprite
class Wall(Sprite):
def __init__(self, game, x, y, settings, type):
super(Wall, self).__init__()
self.settings = settings
self.g = game
self.type = type
self.image = pygame.Surface((settings.tileSize, settings.tileSize... | Python | zaydzuhri_stack_edu_python |
function show self
begin
function display_info event
begin
string On click, display node/arc information.
set ind = call arr call get_gid at ind at 0
if event_id == ind
begin
call set_visible false
set event_id = string
call draw_idle
return
end
else
begin
set event_id = ind
end
if string bus in ind
begin
comment bus ... | def show(self):
def display_info(event):
""" On click, display node/arc information. """
ind = arr(event.artist.get_gid())[event.ind[0]]
if self.event_id == ind:
annot.set_visible(False)
self.event_id = ''
self.fig.canvas.dra... | Python | nomic_cornstack_python_v1 |
function test_delete_recipe_category self
begin
call signup string Bo string Theo string Bo_theo5@example.com string Bo1995 string Bo1995
call login string Bo_theo5@example.com string Bo1995
call dashboard
call category string JunkFood
call dashboard
call recipe_dashboard
call create_recipe string cakes string blah, bl... | def test_delete_recipe_category(self):
self.signup('Bo', 'Theo', 'Bo_theo5@example.com', 'Bo1995', 'Bo1995')
self.login('Bo_theo5@example.com', 'Bo1995')
self.dashboard()
self.category('JunkFood')
self.dashboard()
self.recipe_dashboard()
self.create_recipe('cakes'... | Python | nomic_cornstack_python_v1 |
from math import *
set ab = integer input
set bc = integer input
print round call degrees call atan ab / bc string ° sep=string | from math import *
ab=int(input())
bc=int(input())
print(round(degrees(atan(ab/bc))),'°',sep='') | Python | zaydzuhri_stack_edu_python |
function test_file_types accelize_drm conf_json cred_json async_handler
begin
set driver = pytest_fpga_driver at 0
set async_cb = call create
set log_path = real path string ./drmlib-%d.log % call getpid
set msg = string This is a message
set verbosity = 2
set rotating_size = 1024
set rotating_num = 5
set size = rotati... | def test_file_types(accelize_drm, conf_json, cred_json, async_handler):
driver = accelize_drm.pytest_fpga_driver[0]
async_cb = async_handler.create()
log_path = realpath("./drmlib-%d.log" % getpid())
msg = 'This is a message'
verbosity = 2
rotating_size = 1024
rotating_num = 5
size = ro... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import json
import re
import requests
set champions = list
set items = list
set other = list
set alltips = list
set enem = list
set ta = list
set reco = list
function readFile
begin
with open string ../datasets/champions/Ezreal.json encoding=string utf-8 as f
begin
set data = loads ... | # -*- coding: utf-8 -*-
import json
import re
import requests
champions = []
items = []
other = []
alltips = []
enem = []
ta = []
reco = []
def readFile():
with open('../datasets/champions/Ezreal.json', encoding='utf-8') as f:
data = json.loads(f.read())
champion = ""
nome = ""
abi = ""
ski... | Python | zaydzuhri_stack_edu_python |
function push_left grid
begin
set merge = list true true true true
for r in range 4
begin
for c in range 1 4
begin
set x = 1
set y = 0
while x <= c
begin
comment move values left if position to the left is empty
if grid at r at c - x == 0
begin
set grid at r at c - x = grid at r at c - y
set grid at r at c - y = 0
end
... | def push_left(grid):
merge = [True,True,True,True]
for r in range(4):
for c in range(1,4):
x = 1
y = 0
while (x<=c):
# move values left if position to the left is empty
if grid[r][c-x] == 0:
grid[r][c-x] = g... | Python | nomic_cornstack_python_v1 |
function add_evaluations e1 e2
begin
set true_positive = e1 at 0 + e2 at 0
set false_positive = e1 at 1 + e2 at 1
set distance = e1 at 2 + e2 at 2
if e1 at 2 < 0 and e2 at 2 < 0
begin
set distance = - 1
end
else
if e1 at 2 < 0
begin
set distance = e2 at 2
end
else
if e2 at 2 < 0
begin
set distance = e1 at 2
end
return ... | def add_evaluations(e1, e2):
true_positive = e1[0] + e2[0]
false_positive = e1[1] + e2[1]
distance = e1[2] + e2[2]
if e1[2] < 0 and e2[2] < 0:
distance = -1
elif e1[2] < 0:
distance = e2[2]
elif e2[2] < 0:
... | Python | nomic_cornstack_python_v1 |
from java.lang import Runnable
from javax.swing import JFrame
from javax.swing import SwingUtilities
class ToBeDetermined extends Runnable
begin
function __init__ self
begin
set frame = call JFrame string ToBeDetermined defaultCloseOperation=EXIT_ON_CLOSE
end function
function run self
begin
comment Have the applicatio... | from java.lang import Runnable;
from javax.swing import JFrame;
from javax.swing import SwingUtilities;
class ToBeDetermined( Runnable ) :
def __init__( self ) :
self.frame = JFrame( 'ToBeDetermined' , defaultCloseOperation = JFrame.EXIT_ON_CLOSE );
def run( self ) :
sel... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
string Created on Sat Oct 15 15:12:15 2016 @author: zxl
import numpy as np
from scipy import stats
function fillTrainDataNA_withGroupMode data_train
begin
comment 所有Distance的中位数
set distance_mode = mode at 0
for tuple user_id group in group by data_train at st... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 15 15:12:15 2016
@author: zxl
"""
import numpy as np
from scipy import stats
def fillTrainDataNA_withGroupMode(data_train):
distance_mode = stats.mode(data_train['Distance']).mode[0] # 所有Distance的中位数
for user_id, group in data_train['D... | Python | zaydzuhri_stack_edu_python |
import re
set myString = string The length of the tree is 25 meters, and the height of the tree is 15 meters
comment Use regex to find all numeric values in the string
set numeric_values = find all string \d+ myString
comment Convert the numeric values to integers and calculate the sum
set total_sum = sum generator exp... | import re
myString = "The length of the tree is 25 meters, and the height of the tree is 15 meters"
# Use regex to find all numeric values in the string
numeric_values = re.findall(r'\d+', myString)
# Convert the numeric values to integers and calculate the sum
total_sum = sum(int(value) for value in numeric_values)... | Python | jtatman_500k |
comment a = [0, 0, 0, 0]
set a = list
set hap = 0
comment print(a[0]) - 길이가 0
print length a
for i in range 0 4
begin
append a integer input string i + 1 + string 번째 숫자:
end
comment a[i] = int(input(str(i+1) + "번째 숫자:"))
string a[0] = int(input("1번째 숫자 : ")) a[1] = int(input("2번째 숫자 : ")) a[2] = int(input("3번째 숫자 : ")... | # a = [0, 0, 0, 0]
a = []
hap = 0
# print(a[0]) - 길이가 0
print(len(a))
for i in range(0,4):
a.append(int(input(str(i + 1) + "번째 숫자:")))
# a[i] = int(input(str(i+1) + "번째 숫자:"))
'''
a[0] = int(input("1번째 숫자 : "))
a[1] = int(input("2번째 숫자 : "))
a[2] = int(input("3번째 숫자 : "))
a[3] = int(input("4번째 숫자 : "))
'''
# 인... | Python | zaydzuhri_stack_edu_python |
for i in range 0 inp + 1
begin
if inp % 2 == 0
begin
set c = 0
end
else
begin
set c = inp % 2
end
end
print c | for i in range(0,inp+1):
if inp%2==0:
c=0
else:
c=inp%2
print(c)
| Python | zaydzuhri_stack_edu_python |
import os , sys
import win32print
function imprime impressora texto
begin
if version_info >= tuple 3
begin
set raw_data = bytes texto + string string utf-8
end
else
begin
set raw_data = texto + string
end
call WritePrinter impressora raw_data
end function | import os, sys
import win32print
def imprime(impressora, texto):
if sys.version_info >= (3,):
raw_data = bytes (texto+"\n", "utf-8")
else:
raw_data = texto+"\n"
win32print.WritePrinter(impressora,raw_data)
| Python | zaydzuhri_stack_edu_python |
function _stephash _file _hash stepfunc=none
begin
if stepfunc is none
begin
set stepfunc = exponential
end
set stepping = call stepfunc
set step = next stepping
with open _file string rb as fileh
begin
set iteration = 0
for chunk in iterate lambda -> read fileh 4096 b''
begin
update _hash chunk
set iteration = iterat... | def _stephash(_file, _hash, stepfunc=None):
if stepfunc is None:
stepfunc = exponential
stepping = stepfunc()
step = next(stepping)
with open(_file, 'rb') as fileh:
iteration = 0
for chunk in iter(lambda: fileh.read(4096), b''):
_hash.update(chunk)
itera... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import scrapy
import re
import sys
comment import time
comment 东方财富网 http://quote.eastmoney.com/stocklist.html
comment 百度股票 http://gupiao.baidu.com/stock/
class StocksSpider extends Spider
begin
comment 这只爬虫的名字
set name = string stocks
comment 爬虫要爬的网址---起始网址
set start_urls = list string ht... | # -*- coding: utf-8 -*-
import scrapy
import re
import sys
# import time
# 东方财富网 http://quote.eastmoney.com/stocklist.html
# 百度股票 http://gupiao.baidu.com/stock/
class StocksSpider(scrapy.Spider):
# 这只爬虫的名字
name = 'stocks'
# 爬虫要爬的网址---起始网址
start_urls = ['http://quote.eastmoney.com/stocklist.html... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment encoding: utf-8
comment Encapsulates key distances from a file with triplets:
comment key1_id key2_id distance
comment It considers reverse order pair with same distance
comment Those pair of keys not appearing in the file are supposed 0 distant
import sys , os
class KeyDistance
be... | #! /usr/bin/env python
# encoding: utf-8
#
# Encapsulates key distances from a file with triplets:
# key1_id key2_id distance
# It considers reverse order pair with same distance
# Those pair of keys not appearing in the file are supposed 0 distant
#
import sys, os
#
class KeyDistance:
def __init__(self, filenam... | Python | zaydzuhri_stack_edu_python |
comment print([len(word) for word in words if word != "the"]) | #print([len(word) for word in words if word != "the"])
| Python | zaydzuhri_stack_edu_python |
function on_launch launch_request session
begin
print string on_launch requestId= + launch_request at string requestId + string , sessionId= + session at string sessionId
comment Dispatch to your skill's launch
return call get_welcome_response
end function | def on_launch(launch_request, session):
print("on_launch requestId=" + launch_request['requestId'] +
", sessionId=" + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response() | Python | nomic_cornstack_python_v1 |
comment Aylon Ben Dvora class 8a
print string Aylon Ben Dvora
comment ex1
print string ex1 with elif
comment ask the user for an input of a year variable
set year_elif = integer input string Please enter a year:
comment if the year is a leap year the system prints that it is a leap year
if year_elif % 4 == 0 and year_e... | # Aylon Ben Dvora class 8a
print ("Aylon Ben Dvora")
# ex1
print ("ex1 \nwith elif")
# ask the user for an input of a year variable
year_elif = int(input("Please enter a year: "))
# if the year is a leap year the system prints that it is a leap year
if (year_elif % 4 == 0 and year_elif % 100 != 0):
print (f"{ye... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
from selenium import webdriver
import unittest
import time
import sys
append path string \Public
from Public import logon , logout
class Logon extends TestCase
begin
decorator classmethod
function setUpClass cls
begin
comment cls.driver = webdriver.Firefox() # 不开启静默模式
set options = call Chr... | # -*- coding:utf-8 -*-
from selenium import webdriver
import unittest
import time
import sys
sys.path.append("\Public")
from Public import logon, logout
class Logon(unittest.TestCase):
@classmethod
def setUpClass(cls):
# cls.driver = webdriver.Firefox() # 不开启静默模式
options = webdriver.ChromeOpt... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Sun Jan 5 18:57:43 2020 @author: Sena-2
comment name = input('What is your name: ')
comment age = int(input('What is your age? '))
comment bday = 2020-age
comment print(f'{name}, you are going to turn 100 in {bday+100}.')
comment num = int(in... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 5 18:57:43 2020
@author: Sena-2
"""
#name = input('What is your name: ')
#age = int(input('What is your age? '))
#
#bday = 2020-age
#
#print(f'{name}, you are going to turn 100 in {bday+100}.')
#num = int(input('Please enter a number: '))
#c... | Python | zaydzuhri_stack_edu_python |
function apply_dataarray_vfunc func *args signature join=string inner exclude_dims=call frozenset keep_attrs=false
begin
string Apply a variable level function over DataArray, Variable and/or ndarray objects.
from dataarray import DataArray
if length args > 1
begin
set args = call deep_align args join=join copy=false e... | def apply_dataarray_vfunc(
func,
*args,
signature,
join='inner',
exclude_dims=frozenset(),
keep_attrs=False
):
"""Apply a variable level function over DataArray, Variable and/or ndarray
objects.
"""
from .dataarray import DataArray
if len(args) > 1:
args = deep_align... | Python | jtatman_500k |
function check_template_variables subject vars
begin
for var in vars
begin
to call expect subject match string \{\{cookiecutter\. + var + string \}\}
end
end function | def check_template_variables(subject, vars):
for var in vars:
expect(subject).to(match(r'\{\{cookiecutter\.' + var + '\}\}')) | Python | nomic_cornstack_python_v1 |
function calculate_discount price
begin
if price < 10
begin
raise call ValueError string Invalid price: price must be greater than or equal to 10
end
set discount = price * 0.2
set discounted_price = round price - discount
return discounted_price
end function
set discounted_price = call calculate_discount 50
print disc... | def calculate_discount(price):
if price < 10:
raise ValueError("Invalid price: price must be greater than or equal to 10")
discount = price * 0.2
discounted_price = round(price - discount)
return discounted_price
discounted_price = calculate_discount(50)
print(discounted_price)
| Python | jtatman_500k |
function untangle_circles circles ocr_groups
begin
set new_circles = list
set rejects = list
for c in circles
begin
set tuple center r = c at string circle
set r = r - 1
set coff = c at string offset
set ctl = tuple center at 0 - r + coff at 0 center at 1 - r + coff at 1
set ctr = tuple center at 0 + r + coff at 0 ce... | def untangle_circles(circles, ocr_groups):
new_circles = []
rejects = []
for c in circles:
center,r = c['circle']
r -= 1
coff = c['offset']
ctl = (center[0] - r + coff[0], center[1] - r + coff[1])
ctr = (center[0] + r + coff[0], center[1] - r + coff[1])
cbl =... | Python | nomic_cornstack_python_v1 |
import json
comment f = open("test.txt", "r")
comment data = eval(f.read())
comment f.close()
comment print(data["age"])
set f = open string test.txt string r
comment data = json.loads(f.read())
set data = load json f
print data
close f | import json
# f = open("test.txt", "r")
# data = eval(f.read())
#
# f.close()
#
# print(data["age"])
f = open("test.txt", "r")
# data = json.loads(f.read())
data = json.load(f)
print(data)
f.close() | Python | zaydzuhri_stack_edu_python |
string 1439. Hard You are given an m * n matrix, mat, and an integer k, which has its rows sorted in non-decreasing order. You are allowed to choose exactly 1 element from each row to form an array. Return the Kth smallest array sum among all possible arrays. Example 1: Input: mat = [[1,3,11],[2,4,6]], k = 5 Output: 7 ... | """
1439.
Hard
You are given an m * n matrix, mat, and an integer k, which has its rows sorted in non-decreasing order.
You are allowed to choose exactly 1 element from each row to form an array.
Return the Kth smallest array sum among all possible arrays.
Example 1:
Input: mat = [[1,3,11],[2,4,6]], k = 5
Out... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.