code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Problem 28
comment Number spiral diagonals
set s = 1
set curnum = 1
set inc = 2
for i in range 500
begin
for j in range 4
begin
set curnum = curnum + inc
set s = s + curnum
end
set inc = inc + 2
end | # Problem 28
# Number spiral diagonals
#
s = 1
curnum = 1
inc = 2
for i in range(500):
for j in range(4):
curnum = curnum + inc
s = s + curnum
inc = inc + 2
| Python | zaydzuhri_stack_edu_python |
import os , sys
import datetime
from config import get_config
function next_friday d
begin
if call weekday <= 4
begin
set time_delta = time delta 4 - call weekday
end
else
begin
set time_delta = time delta 11 - call weekday
end
return d + time_delta
end function
set START_DATE = call date 2015 6 16
set END_DATE = call ... | import os, sys
import datetime
from config import get_config
def next_friday( d ):
if d.weekday() <= 4:
time_delta = datetime.timedelta( 4 - d.weekday() )
else:
time_delta = datetime.timedelta( 11 - d.weekday())
return d + time_delta
START_DATE = datetime.date(2015,6,16);
END_DATE = datet... | Python | zaydzuhri_stack_edu_python |
async function send_request self connection payment_handle
begin
if not has attribute send_request string cb
begin
debug string vcx_credential_send_request: Creating callback
set cb = call create_cb call CFUNCTYPE none c_uint32 c_uint32
end
set c_credential_handle = call c_uint32 handle
set c_connection_handle = call c... | async def send_request(self, connection: Connection, payment_handle: int):
if not hasattr(Credential.send_request, "cb"):
self.logger.debug("vcx_credential_send_request: Creating callback")
Credential.send_request.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32))
c_credential_... | Python | nomic_cornstack_python_v1 |
function write self fileW
begin
call wFloat x
call wFloat y
call wFloat z
end function | def write(self, fileW):
fileW.wFloat(self.x)
fileW.wFloat(self.y)
fileW.wFloat(self.z) | Python | nomic_cornstack_python_v1 |
function get_stir_mass_grid tracer_ids model verbose=true
begin
call printv string Loading mass grid verbose=verbose
set tracer_ids = call expand_sequence tracer_ids
set mass_grid = list
for tracer_id in tracer_ids
begin
set mass = call get_stir_mass_element tracer_id model
set mass_grid = mass_grid + list mass
end
re... | def get_stir_mass_grid(tracer_ids, model, verbose=True):
printv('Loading mass grid', verbose=verbose)
tracer_ids = tools.expand_sequence(tracer_ids)
mass_grid = []
for tracer_id in tracer_ids:
mass = get_stir_mass_element(tracer_id, model)
mass_grid += [mass]
return np.array(mass_g... | Python | nomic_cornstack_python_v1 |
function split_lines s
begin
return list comprehension strip line for line in split s string if strip line
end function
function count_start_comma s
begin
set count = 0
while starts with s string ,
begin
set count = count + 1
set s = s at slice 1 : :
end
return count
end function
function restore lst
begin
set restor... | def split_lines(s: str):
return [line.strip() for line in s.split('\n') if line.strip()]
def count_start_comma(s: str):
count = 0
while s.startswith(','):
count += 1
s = s[1:]
return count
def restore(lst: list):
restore_list = []
for index, line in enumerate(lst):
co... | Python | zaydzuhri_stack_edu_python |
function _claim_master_member_sequence_number self community meta
begin
assert is instance distribution FullSyncDistribution msg string currently only FullSyncDistribution allows sequence numbers
set tuple sequence_number = next
return sequence_number + 1
end function | def _claim_master_member_sequence_number(self, community, meta):
assert isinstance(meta.distribution, FullSyncDistribution), "currently only FullSyncDistribution allows sequence numbers"
sequence_number, = self._database.execute(u"SELECT COUNT(*) FROM sync WHERE member = ? AND sync.meta_message = ?",
... | Python | nomic_cornstack_python_v1 |
function iteration self
begin
comment get from class
comment return
return none
end function | def iteration(self):
# get from class
# return
return None | Python | nomic_cornstack_python_v1 |
function do self **args
begin
with call allure_step string Do upgrade { name }
begin
set data = call _subcall string do string create keyword args
end
set task = none
if get data string task_id is not none
begin
set task = call Task _api id=data at string task_id
end
return task
end function | def do(self, **args) -> Optional['Task']:
with allure_step(f"Do upgrade {self.name}"):
data = self._subcall("do", "create", **args)
task = None
if data.get('task_id') is not None:
task = Task(self._api, id=data['task_id'])
return task | Python | nomic_cornstack_python_v1 |
for i in range 0 length a 1
begin
if decimal a at i != decimal max a
begin
append A decimal a at i
end
end
set kostil = A at 1
set A at 1 = decimal max a
append A kostil
for i in range 0 length b 1
begin
if decimal b at i != decimal max b
begin
append B decimal b at i
end
end
set kostil = B at 1
set B at 1 = decimal ma... | for i in range(0, len(a), 1):
if float(a[i]) != float(max(a)):
A.append(float(a[i]))
kostil = A[1]
A[1] = float(max(a))
A.append(kostil)
for i in range(0, len(b), 1):
if float(b[i]) != float(max(b)):
B.append(float(b[i]))
kostil = B[1]
B[1] = float(max(b))
B.append(kostil)
C ... | Python | zaydzuhri_stack_edu_python |
function clicks_ignored self
begin
set result = _ignore_count > 0
set _ignore_count = max 0 _ignore_count - 1
return result
end function | def clicks_ignored(self):
result = self._ignore_count > 0
self._ignore_count = max(0, self._ignore_count - 1)
return result | Python | nomic_cornstack_python_v1 |
import copy
from obstacle import obstacle_fields
function get_type obstacle
begin
return obstacle at TYPE
end function
function get_position obstacle
begin
return obstacle at POSITION
end function
function set_type obstacle obstacle_type
begin
set obstacle at TYPE = obstacle_type
end function
function set_position obst... | import copy
from obstacle import obstacle_fields
def get_type(obstacle):
return obstacle[obstacle_fields.TYPE]
def get_position(obstacle):
return obstacle[obstacle_fields.POSITION]
def set_type(obstacle, obstacle_type):
obstacle[obstacle_fields.TYPE] = obstacle_type
def set_position(obstacle, posit... | Python | zaydzuhri_stack_edu_python |
function problem2
begin
set k = 4
set total_draws = 20
set total_balls = 50
figure
for _ in range 50
begin
for num_samples in list 10000
begin
set experiment_results = list
for samples in range num_samples
begin
set N = random integer 1 k total_balls - 1
set N = append np N k
set N = flatten array N
shuffle random N
s... | def problem2():
k = 4
total_draws = 20
total_balls = 50
plt.figure()
for _ in range(50):
for num_samples in [10000]:
experiment_results = []
for samples in range(num_samples):
N = np.random.randint(1, k, total_balls - 1)
N = np.append(... | Python | nomic_cornstack_python_v1 |
function __init__ self std_cwid std_name major
begin
set _std_cwid = std_cwid
set _std_name = std_name
set _major = major
set _courses = dictionary
end function | def __init__(self, std_cwid, std_name, major):
self._std_cwid = std_cwid
self._std_name = std_name
self._major = major
self._courses = dict() | Python | nomic_cornstack_python_v1 |
set color = list string red string blue string green string pink
print *color sep=string ,
set add = input string Your new color :
append color add
print string New list: end=string
print *color sep=string , | color = ['red', 'blue', 'green', 'pink']
print(*color, sep=', ')
add = input("Your new color : ")
color.append(add)
print("New list: ",end="")
print(*color, sep=', ')
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string @author: Liran CHEN 220040071
import pandas as pd
import numpy as np
from sklearn import svm
from sklearn import model_selection
import tushare as ts
comment get the stock data from tushare
comment use your own tushare token
set TOKEN = string
call set_token TOKEN
set pro = call pr... | # -*- coding: utf-8 -*-
"""
@author: Liran CHEN 220040071
"""
import pandas as pd
import numpy as np
from sklearn import svm
from sklearn import model_selection
import tushare as ts
#get the stock data from tushare
#use your own tushare token
TOKEN = ''
ts.set_token(TOKEN)
pro = ts.pro_api()
#get the da... | Python | zaydzuhri_stack_edu_python |
function mean_and_max arr
begin
set sum = 0
set count = 0
set max_num = 0
for num in arr
begin
if num > 4 and num < 10 and num % 2 == 0
begin
set sum = sum + num
set count = count + 1
if num > max_num
begin
set max_num = num
end
end
end
set mean = sum / count
if max_num > 7
begin
set max_num = max_num / 2
end
return tu... | def mean_and_max(arr):
sum = 0
count = 0
max_num = 0
for num in arr:
if num > 4 and num < 10 and num % 2 == 0:
sum += num
count += 1
if num > max_num:
max_num = num
mean = sum / count
if max_num > 7:
max_num /= 2
return ... | Python | jtatman_500k |
function toKML self domImpl
begin
set doc = call createDocument string http://earth.google.com/kml/2.0 string kml none
set kml = documentElement
call setAttribute string xmlns string http://earth.google.com/kml/2.0
comment create Document tag
set document = call createElement string Document
call appendChild document
c... | def toKML (self, domImpl):
doc = domImpl.createDocument ("http://earth.google.com/kml/2.0","kml",None)
kml = doc.documentElement
kml.setAttribute ("xmlns","http://earth.google.com/kml/2.0")
# create Document tag
document = doc.createElement("Document")
kml.appendC... | Python | nomic_cornstack_python_v1 |
function gcd a b
begin
return if expression b == 0 then a else call gcd b a % b
end function
function lcm a b
begin
set m = a * b
while a != 0 and b != 0
begin
if a > b
begin
set a = a % b
end
else
begin
set b = b % a
end
end
return m // a + b
end function
set n = integer input
set numerator = integer input
set denomin... | def gcd(a: int, b: int):
return a if b == 0 else gcd(b, a % b)
def lcm(a, b):
m = a * b
while a != 0 and b != 0:
if a > b:
a %= b
else:
b %= a
return m // (a + b)
n = int(input())
numerator = int(input())
denominator = int(input())
for i in range(n - 1):
... | Python | zaydzuhri_stack_edu_python |
function is_closed self
begin
return all start == end
end function | def is_closed(self):
return np.all(self.start == self.end) | Python | nomic_cornstack_python_v1 |
function setUp self
begin
setup call super WsgiLimiterTest self
set app = call WsgiLimiter TEST_LIMITS
end function | def setUp(self):
super(WsgiLimiterTest, self).setUp()
self.app = limits.WsgiLimiter(TEST_LIMITS) | Python | nomic_cornstack_python_v1 |
import unittest
from xde.encoder import EnumStrictEncoder
class TestEnumStrictEncoder extends TestCase
begin
function test_encode self
begin
set encoder = call EnumStrictEncoder
set possible_values = list string one string two string three string four string five
set target = string one
set one_hot = encode encoder tar... | import unittest
from xde.encoder import EnumStrictEncoder
class TestEnumStrictEncoder(unittest.TestCase):
def test_encode(self):
encoder = EnumStrictEncoder()
possible_values = ["one", "two", "three", "four", "five"]
target = "one"
one_hot = encoder.encode(target, possible_values... | Python | zaydzuhri_stack_edu_python |
import sqlite3
set a = input string name
set b = input string species
set c = input string iq
set rosterData = tuple a b c
set connection = call connect string :memory:
set c = call cursor
call executescript string CREATE TABLE Roster(Name TEXT, Species TEXT, IQ INT) rosterValues =( ('Jean-Baptiste Zorg', 'Human', 122)... | import sqlite3
a = input("name")
b = input("species")
c = input("iq")
rosterData = (a,b,c)
connection = sqlite3.connect(':memory:')
c = connection.cursor()
c.executescript("""
CREATE TABLE Roster(Name TEXT, Species TEXT, IQ INT)
rosterValues =(
('Jean-Baptiste Zorg', 'Human', 122),
('Korben Dallas', 'Meat Popsic... | Python | zaydzuhri_stack_edu_python |
string Copyright (c) 2014 Edgar A. Margffoy T. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis... | """
Copyright (c) 2014 Edgar A. Margffoy T.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, dist... | Python | zaydzuhri_stack_edu_python |
function get_propagated_names self
begin
return call get_names
end function | def get_propagated_names(self):
return self.get_names() | Python | nomic_cornstack_python_v1 |
comment User function Template for python3
class Solution
begin
function UncommonChars self A B
begin
set alpha_array = list 0 * 26
set output = string
for i in A
begin
set alpha_array at ordinal i - 97 = 1
end
for i in B
begin
if alpha_array at ordinal i - 97 == 1 or alpha_array at ordinal i - 97 == - 1
begin
set alp... | #User function Template for python3
class Solution:
def UncommonChars(self,A, B):
alpha_array = [0]*26
output = ""
for i in A:
alpha_array[ord(i)-97] = 1
for i in B:
if alpha_array[ord(i)-97] == 1 or alpha_array[ord(i)-97] == -1:
alpha_array[o... | Python | zaydzuhri_stack_edu_python |
comment ----------------------------------------------
comment Project: SengokushiAI
comment Author: huang ying
comment Date: 2018.10.31
comment ----------------------------------------------
import threading
import time
import json
import queue
import os
from pynput.mouse import Button , Controller
from pynput import ... | # ----------------------------------------------
# Project: SengokushiAI
# Author: huang ying
# Date: 2018.10.31
# ----------------------------------------------
import threading
import time
import json
import queue
import os
from pynput.mouse import Button, Controller
from pynput import keyboard
EVENT_INVALID ... | Python | zaydzuhri_stack_edu_python |
function test_multiple_states self
begin
comment Prepare.
set app = call factory
set request = call getRequest app
set context = call factory
comment Create a dummy event and get it back.
set event_id = call createEvent context
set event = call call LookupActivityEvent event_id
comment Cancel when created.
set state_ch... | def test_multiple_states(self):
# Prepare.
app = self.factory()
request = self.getRequest(app)
context = model.factory()
# Create a dummy event and get it back.
event_id = boilerplate.createEvent(context)
event = repo.LookupActivityEvent()(event_id)
# C... | Python | nomic_cornstack_python_v1 |
from gpiozero import Motor
class ControlledCar
begin
function __init__ self left_motor=call Motor 27 22 right_motor=call Motor 26 17 right_motor_correction_speed=1 left_motor_correction_speed=1
begin
set left_motor = left_motor
set right_motor = right_motor
set right_motor_correction_speed = right_motor_correction_spee... | from gpiozero import Motor
class ControlledCar:
def __init__(self, left_motor = Motor(27, 22), right_motor = Motor(26, 17), right_motor_correction_speed=1, left_motor_correction_speed=1):
self.left_motor = left_motor
self.right_motor = right_motor
self.right_motor_correction_speed = right... | Python | zaydzuhri_stack_edu_python |
function __sub__ self b
begin
return call Vector2D x - x y - y
end function | def __sub__(self, b):
return Vector2D(self.x - b.x, self.y - b.y) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import logging
from numpy import *
from pylab import norm
from scipy import optimize
comment what coordinates should I use????????????????
comment +x = east: about x = attitude (pitch)
comment +y = north: about y = bank (roll)
comment +z = up: about z = heading (yaw)
comment vector = matrix... | #!/usr/bin/env python
import logging
from numpy import *
from pylab import norm
from scipy import optimize
# what coordinates should I use????????????????
# +x = east: about x = attitude (pitch)
# +y = north: about y = bank (roll)
# +z = up: about z = heading (yaw)
# vector = matrix([[x,y,z,1]])
# rotation_matrix =... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment crb331 - Collin Barnwell and npy259 - Nathan Yeazel
import struct , string , math , copy
set globalcount = 0
class SudokuBoard
begin
string This will be the sudoku board game object your player will manipulate.
function __init__ self size board
begin
string the constructor for the S... | #!/usr/bin/env python
# crb331 - Collin Barnwell and npy259 - Nathan Yeazel
import struct, string, math, copy
globalcount = 0
class SudokuBoard:
"""This will be the sudoku board game object your player will manipulate."""
def __init__(self, size, board):
"""the constructor for the SudokuBoard"""
... | Python | zaydzuhri_stack_edu_python |
for num in range 0 101
begin
if num > 1
begin
for i in range 2 integer num / 2 + 1
begin
if num % i == 0
begin
break
end
end
for else
begin
print num
end
end
end | for num in range(0, 101):
if num > 1:
for i in range(2, int(num/2) + 1):
if (num % i) == 0:
break
else:
print(num)
| Python | jtatman_500k |
string 標準ライブラリ os "OS"はOSに依存した機能を扱うためのライブラリです。 カレントディレクトリを調べたり、ファイルパスを分割したりする場合などに利用します。
import sys
import os
comment カレントディレクトリの取得
print get current directory string
comment パス区切り文字の取得
print sep string
comment パスを親ディレクトリとファイルに分割
print split path argv at 0 string
comment パスを連結
print join path get current directory stri... | """
標準ライブラリ os
"OS"はOSに依存した機能を扱うためのライブラリです。
カレントディレクトリを調べたり、ファイルパスを分割したりする場合などに利用します。
"""
import sys
import os
# カレントディレクトリの取得
print(os.getcwd(), '\n')
# パス区切り文字の取得
print(os.sep, '\n')
# パスを親ディレクトリとファイルに分割
print(os.path.split(sys.argv[0]), '\n')
# パスを連結
print(os.path.join(os.getcwd(), 'hoge.py'), '\n')
# ファイル名を名前... | Python | zaydzuhri_stack_edu_python |
function rescaleSigma self arg0
begin
return call PhaseSpace_rescaleSigma self arg0
end function | def rescaleSigma(self, arg0):
return _pythia8.PhaseSpace_rescaleSigma(self, arg0) | Python | nomic_cornstack_python_v1 |
function save_zip self
begin
comment enable zipfile compression
set compression = ZIP_DEFLATED
set zip_path = join path test_data_dir string dbwebexport.zip
try
begin
set zf = zip file zip_path string w compression allowZip64=true
end
except RuntimeError
begin
error string Zip file cannot be compressed (check zlib modu... | def save_zip(self):
# enable zipfile compression
compression = ZIP_DEFLATED
zip_path = os.path.join(self.test_data_dir, 'dbwebexport.zip')
try:
zf = ZipFile(zip_path, 'w', compression, allowZip64=True)
except RuntimeError:
logger.error('Zip file cannot be... | Python | nomic_cornstack_python_v1 |
import Queue
function r2i
begin
set l = split call raw_input string
return tuple integer l at 0 integer l at 1
end function
function r3i
begin
set l = split call raw_input string
return tuple integer l at 0 integer l at 1 integer l at 2
end function
set tuple nn ne = call r2i
set lt = dict
set mx = 100000000
for k in ... | import Queue
def r2i():
l = raw_input().split(' ')
return (int(l[0]),int(l[1]))
def r3i():
l = raw_input().split(' ')
return (int(l[0]),int(l[1]), int(l[2]))
nn, ne = r2i()
lt = {}
mx = 100000000
for k in range(nn):
lt[k] = []
for k in range(ne):
i, j, r = r3i()
lt[i-1].append((r... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string author: mabin date : 2018-05-25 =================== [15. 3Sum](https://leetcode.com/problems/3sum/description/) | Medium =================== problem description =================== Given an array nums of n integers, are there elements a, b, c in nums suc... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
author: mabin
date : 2018-05-25
===================
[15. 3Sum](https://leetcode.com/problems/3sum/description/) | Medium
===================
problem description
===================
Given an array nums of n integers, are there elements a, b, c in nums
such that a + b + ... | Python | zaydzuhri_stack_edu_python |
function interactive
begin
while true
begin
set fn = call rel_path absolute path input string Enter Photo Name or Folder Name:
print
if exists fn
begin
break
end
print format string {} is not a valid path fn
end
comment Start Single Mode
if is file fn
begin
call main fn MIN_PLANT_SIZE
end
else
begin
comment Start Multi... | def interactive():
while True:
fn = rel_path(abspath(input('Enter Photo Name or Folder Name: \n')))
print()
if exists(fn):
break
print('{} is not a valid path \n'.format(fn))
# Start Single Mode
if isfile(fn):
main(fn, MIN_PLANT_SI... | Python | nomic_cornstack_python_v1 |
function forward self img target=none target_weight=none img_metas=none return_loss=true **kwargs
begin
if return_loss
begin
return call forward_train img target target_weight img_metas keyword kwargs
end
return call forward_test img img_metas keyword kwargs
end function | def forward(self,
img,
target=None,
target_weight=None,
img_metas=None,
return_loss=True,
**kwargs):
if return_loss:
return self.forward_train(img, target, target_weight, img_metas,
... | Python | nomic_cornstack_python_v1 |
function list_pnums self
begin
return sorted list comprehension key for key in catalog
end function | def list_pnums(self):
return sorted([key for key in self.catalog]) | Python | nomic_cornstack_python_v1 |
function fillter_segments self save_flag=false
begin
set filtered_segments = call segmentor
set seg_sum = sum filtered_segments axis=tuple 1 2
comment bin_mask = self.binary_mask > 150 # some masks where created strangely,
comment not only 255 or 0
set segment_activation = filtered_segments * as type binary_mask bool
s... | def fillter_segments(self, save_flag=False):
filtered_segments = self.segmentor()
seg_sum = np.sum(filtered_segments, axis=(1, 2))
#bin_mask = self.binary_mask > 150 # some masks where created strangely,
# not only 255 or 0
segment_activation = filtered_segments * self.binary... | Python | nomic_cornstack_python_v1 |
import torch
from torch.autograd import Variable
import numpy as np
from sklearn.metrics import mean_squared_error
function compute_rmse model data_set batch_size=1000 cuda=false
begin
set dtype = FloatTensor
if cuda
begin
set dtype = FloatTensor
end
comment --- sequential loader
set data_loader = call DataLoader data_... | import torch
from torch.autograd import Variable
import numpy as np
from sklearn.metrics import mean_squared_error
def compute_rmse(model, data_set, batch_size=1000, cuda=False):
dtype=torch.FloatTensor
if cuda:
dtype = torch.cuda.FloatTensor
# --- sequential loader
data_loader = torch.utils.data.DataLoad... | Python | zaydzuhri_stack_edu_python |
function identity_func x=call cast Any Undefined *_args
begin
return x
end function | def identity_func(x: T = cast(Any, Undefined), *_args: Any) -> T:
return x | Python | nomic_cornstack_python_v1 |
import sqlite3
function insert_customer_record id name age address
begin
comment Connect to the database
set conn = call connect string database.db
set cursor = call cursor
comment Query the 'customers' table to check if the ID already exists
execute cursor string SELECT * FROM customers WHERE ID = ? tuple id
if call f... | import sqlite3
def insert_customer_record(id, name, age, address):
# Connect to the database
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
# Query the 'customers' table to check if the ID already exists
cursor.execute("SELECT * FROM customers WHERE ID = ?", (id,))
if cursor.fetc... | Python | greatdarklord_python_dataset |
comment -*- coding: utf-8 -*-
import fizzbuzz
import unittest
class TestFizzBuzz extends TestCase
begin
function test_three self
begin
assert equal process 6 string Fizz
end function
function test_five self
begin
assert equal process 10 string Buzz
end function
function test_three_and_five self
begin
assert equal proce... | # -*- coding: utf-8 -*-
import fizzbuzz
import unittest
class TestFizzBuzz(unittest.TestCase):
def test_three(self):
self.assertEqual(fizzbuzz.process(6), 'Fizz')
def test_five(self):
self.assertEqual(fizzbuzz.process(10), 'Buzz')
def test_three_and_five(self):
self.... | Python | zaydzuhri_stack_edu_python |
function excel_date_and_time_string value
begin
set format = string %-m/%-d/%y %-I:%M %p
return call date_to_string value format
end function | def excel_date_and_time_string(value):
format='%-m/%-d/%y %-I:%M %p'
return date_to_string(value,format) | Python | nomic_cornstack_python_v1 |
import csv
import matplotlib.pyplot as plt
import numpy
class Population extends object
begin
set data : list = list
function read_data self
begin
set data = reader open string ./data/202106_202106_연령별인구현황_월간.csv encoding=string utf-8
next data
set data = data
end function
function pop_per_dong self dong
begin
call re... | import csv
import matplotlib.pyplot as plt
import numpy
class Population(object):
data: [] = list()
def read_data(self):
data = csv.reader(open('./data/202106_202106_연령별인구현황_월간.csv', encoding='utf-8'))
next(data)
self.data = data
def pop_per_dong(self, dong: str) -> []:
s... | Python | zaydzuhri_stack_edu_python |
from django.conf.urls.defaults import *
set urlpatterns = call patterns string call url string ^$ string idios.views.profiles name=string profile_list call url string ^profile/(?P<username>[\w\._-]+)/$ string idios.views.profile name=string profile_detail call url string ^edit/$ string idios.views.profile_edit name=st... | from django.conf.urls.defaults import *
urlpatterns = patterns("",
url(r"^$", "idios.views.profiles", name="profile_list"),
url(r"^profile/(?P<username>[\w\._-]+)/$", "idios.views.profile", name="profile_detail"),
url(r"^edit/$", "idios.views.profile_edit", name="profile_edit"),
)
| Python | jtatman_500k |
class MyClass
begin
function __init__ self param1 param2
begin
set param1 = param1
set param2 = param2
end function
function print_parameters self
begin
print string param1 + string , + string param2
end function
end class | class MyClass:
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
def print_parameters(self):
print(str(self.param1) + ", " + str(self.param2)) | Python | jtatman_500k |
if score > 15
begin
print string Gefeliciteerd, je bent geslaagd
end
if score < 15
begin
print string Helaas heb je het niet gehaald
end | if score >15:
print ('Gefeliciteerd, je bent geslaagd')
if score <15:
print ('Helaas heb je het niet gehaald') | Python | zaydzuhri_stack_edu_python |
function test_create_virtual_account_beneficiary self
begin
pass
end function | def test_create_virtual_account_beneficiary(self):
pass | Python | nomic_cornstack_python_v1 |
set my_list = list 1 2 3 4 5 8 6 7
set list_two = list string A string 23 100.232 string o
print my_list
print length list_two
print my_list at 0
print my_list + list string four
print pop my_list
print my_list
sort my_list
print my_list
reverse my_list
print my_list
set lst_1 = list 1 2 3
set lst_2 = list 4 5 6
set ls... | my_list=[1,2,3,4,5,8,6,7]
list_two = ['A string',23,100.232,'o']
print(my_list)
print(len(list_two))
print(my_list[0])
print(my_list + ["four"])
print(my_list.pop())
print(my_list)
my_list.sort()
print(my_list)
my_list.reverse()
print(my_list)
lst_1=[1,2,3]
lst_2=[4,5,6]
lst_3=[7,8,9]
matrix = [l... | Python | zaydzuhri_stack_edu_python |
import json
import random
import urllib.request
import requests
set SUBJECT_CODE_FILE = string ./data/subject_data2.csv
set ROOMS_DATA_FILE = string ./data/rooms_data.csv
set CLASS_LIST = string classList
set DAY = string day
set START = string start
set END = string end
set LOCATIONS = string locations
set SUBJ_CODE =... | import json
import random
import urllib.request
import requests
SUBJECT_CODE_FILE = './data/subject_data2.csv'
ROOMS_DATA_FILE = './data/rooms_data.csv'
CLASS_LIST = 'classList'
DAY = "day"
START = "start"
END = "end"
LOCATIONS = "locations"
SUBJ_CODE = "subjectCode"
URL = "https://uom-semester-planner.azurewebsites.... | Python | zaydzuhri_stack_edu_python |
function contains_4_letters word
begin
set count = 0
for letter in word
begin
if is alpha letter
begin
set count = count + 1
end
end
if count == 4
begin
return true
end
return false
end function
function censor word
begin
for i in range length word
begin
if is alpha word at i
begin
set word = word at slice : i : + st... | def contains_4_letters(word):
count = 0
for letter in word:
if letter.isalpha():
count += 1
if count == 4:
return True
return False
def censor(word):
for i in range(len(word)):
if word[i].isalpha():
word = word[:i] + '*' + word[i+1:]
return word
# get filename from user: filename
# open file in read... | Python | zaydzuhri_stack_edu_python |
function Scala As a
begin
if call IsEmpty As
begin
return As
end
return call MakeList a * head As call Scala tail As a
end function | def Scala(As, a):
if IsEmpty(As):
return As
return MakeList(a*Head(As), Scala(Tail(As), a)) | Python | nomic_cornstack_python_v1 |
comment -*-coding : UTF-8-*-
import getopt
import sys | #-*-coding : UTF-8-*-
import getopt
import sys | Python | zaydzuhri_stack_edu_python |
function device_locked self device
begin
string Show lock notification for specified device object.
if not call is_handleable device
begin
return
end
call _show_notification string device_locked call _ string Device locked call _ string {0.device_presentation} locked device icon_name
end function | def device_locked(self, device):
"""Show lock notification for specified device object."""
if not self._mounter.is_handleable(device):
return
self._show_notification(
'device_locked',
_('Device locked'),
_('{0.device_presentation} locked', device),... | Python | jtatman_500k |
import torch
import math
from torch.autograd import Variable
import numpy as np
from PIL import Image
import numpy as np
function error_map A B
begin
set error_map = sum 1 keepdim=true / size A 1
return power 0.5
end function
function patch_distance A B average=true
begin
set error = sum
if average == false
begin
retur... | import torch
import math
from torch.autograd import Variable
import numpy as np
from PIL import Image
import numpy as np
def error_map(A, B):
error_map = (A - B).pow(2).sum(1, keepdim=True) / A.size(1)
return error_map.pow(0.5)
def patch_distance(A, B, average=True):
error = (A - B).pow(2).sum()
if ... | Python | zaydzuhri_stack_edu_python |
set message = string Hello World
print message
print find message string World
comment case sensitive
print count message string l
print lower message
print upper message
print replace message string string --
print directory message
print call help str
print call help maketrans |
message = "Hello World"
print(message)
print(message.find("World"))
print(message.count("l")) #case sensitive
print(message.lower())
print(message.upper())
print(message.replace(" ", "--"))
print(dir(message))
print(help(str))
print(help(str.maketrans)) | Python | zaydzuhri_stack_edu_python |
function CoinFromRef coin_ref tx_output state=Unconfirmed transaction=none
begin
string Get a Coin object using a CoinReference. Args: coin_ref (neo.Core.CoinReference): an object representing a single UTXO / transaction input. tx_output (neo.Core.Transaction.TransactionOutput): an object representing a transaction out... | def CoinFromRef(coin_ref, tx_output, state=CoinState.Unconfirmed, transaction=None):
"""
Get a Coin object using a CoinReference.
Args:
coin_ref (neo.Core.CoinReference): an object representing a single UTXO / transaction input.
tx_output (neo.Core.Transaction.Transactio... | Python | jtatman_500k |
import sublime
import datetime
import re
comment GENERIC CHECKS
function is_anime_list view
begin
set full_name = call file_name
comment in case no file is open
if full_name == none
begin
return false
end
set res = search string ([^\/\\]+)$ full_name
return res and call group 1 == string anilist.anl or false
end functi... | import sublime
import datetime
import re
### GENERIC CHECKS
def is_anime_list(view):
full_name = view.file_name()
if full_name == None: #in case no file is open
return False
res = re.search(r'([^\/\\]+)$', full_name)
return res and res.group(1) == 'anilist.anl' or False
### CURSOR UTILS
def get_cursor(vie... | Python | zaydzuhri_stack_edu_python |
import turtle
call bgcolor string grey
call pensize 3
call speed 0
for i in range 8
begin
for colours in list string orange string pink string violet string red string cyan string violet string gold
begin
call color colours
call circle 100
call left 15
end
end
call hideturtle | import turtle
turtle.bgcolor("grey")
turtle.pensize(3)
turtle.speed(0)
for i in range(8):
for colours in ['orange','pink','violet','red','cyan','violet','gold']:
turtle.color(colours)
turtle.circle(100)
turtle.left(15)
turtle.hideturtle()
| Python | zaydzuhri_stack_edu_python |
string Keras based assignment Modified code from https://github.com/keras-team/keras/tree/master/examples to answer questions Train a simple deep CNN on the CIFAR10 small images dataset. It gets to 75% validation accuracy in 25 epochs, and 79% after 50 epochs.
from __future__ import print_function
import keras
from ker... | """
Keras based assignment
Modified code from https://github.com/keras-team/keras/tree/master/examples to answer questions
Train a simple deep CNN on the CIFAR10 small images dataset.
It gets to 75% validation accuracy in 25 epochs, and 79% after 50 epochs.
"""
from __future__ import print_function
import keras
from ... | Python | zaydzuhri_stack_edu_python |
function sentence_spelling_correction test_data_line
begin
comment split the test_data_line according to the metadata
set test_data_line = split test_data_line string
comment sentence id
set sentence_id = test_data_line at 0
comment the error number in this sentence
set n_error = integer test_data_line at 1
comment the... | def sentence_spelling_correction(test_data_line):
test_data_line = test_data_line.split("\t") # split the test_data_line according to the metadata
sentence_id = test_data_line[0] # sentence id
n_error = int(test_data_line[1]) # the error number in this sentence
sentence = test_data_line[2] # the tes... | Python | nomic_cornstack_python_v1 |
function fulfilled_by self
begin
if not call is_fulfilled
begin
return none
end
return filter passengers__user=user
end function | def fulfilled_by(self):
if not self.is_fulfilled():
return None
return self.recommended(ignore_full=True).filter(passengers__user=self.template.user) | Python | nomic_cornstack_python_v1 |
function divide A B u
begin
return integer u / A / B
end function
function encode2 str
begin
set s = list
for i in set str
begin
if count str i > 1
begin
append s count str i
end
append s i
end
return s
end function
function encode str
begin
set s = dict
for i in str
begin
set default s i 0
set s at i = s at i + 1
en... | def divide(A,B,u):
return int(u/(A/B))
def encode2(str):
s = []
for i in set(str):
if str.count(i)>1:
s.append(str.count(i))
s.append(i)
return s
def encode(str):
s = {}
for i in str:
s.setdefault(i,0)
s[i]+=1
a = []
for c in s.keys():
if s[c]>1:
a... | Python | zaydzuhri_stack_edu_python |
function user_iflags_first *args
begin
return call user_iflags_first *args
end function | def user_iflags_first(*args):
return _ida_hexrays.user_iflags_first(*args) | Python | nomic_cornstack_python_v1 |
function CenterOfMass self
begin
set TM_COM_Set = list comprehension call CenterOfMass for i in Content
return call CenterOfMass
end function | def CenterOfMass ( self ):
TM_COM_Set = [i. CenterOfMass ( ) for i in self.Content]
return SetOfPoints ( TM_COM_Set ). CenterOfMass ( ) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string The 4-print-square module Has a function that prints a square
function print_square size
begin
string Prints a square of 'size' size with the caracter '#'
if type size is not int
begin
raise call TypeError string size must be an integer
end
if size < 0
begin
raise call ValueError string... | #!/usr/bin/python3
"""
The 4-print-square module
Has a function that prints a square
"""
def print_square(size):
"""
Prints a square of 'size' size with the caracter '#'
"""
if type(size) is not int:
raise TypeError('size must be an integer')
if size < 0:
raise ValueError('size mu... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import scipy as sp
import scipy.linalg as la
import matplotlib.pyplot as plt
import math
import cmath
import numpy.random as random
from numpy.random import choice , sample , randint
from scipy import optimize
from scipy.optimize import curve_fit
import statistics
import os
import pandas as pd
import... | import numpy as np
import scipy as sp
import scipy.linalg as la
import matplotlib.pyplot as plt
import math
import cmath
import numpy.random as random
from numpy.random import choice, sample, randint
from scipy import optimize
from scipy.optimize import curve_fit
import statistics
import os
import pandas as pd
import q... | Python | zaydzuhri_stack_edu_python |
function test_login_server_error self logging_mock connection_mock connection_enter
begin
set return_value = none
assert equal login_nok call login database
call assert_not_called
call assert_not_called
call assert_log logging_mock LDAPServerPoolError USERNAME
end function | def test_login_server_error(self, logging_mock, connection_mock, connection_enter):
connection_mock.return_value = None
self.assertEqual(self.login_nok, auth.login(self.database))
connection_mock.assert_not_called()
connection_enter.assert_not_called()
self.assert_log(logging_moc... | Python | nomic_cornstack_python_v1 |
function update_steps self delta
begin
set polyline_steps = polyline_steps + delta
if polyline_steps < 1
begin
set polyline_steps = 1
end
end function | def update_steps(self, delta):
self.polyline_steps += delta
if self.polyline_steps < 1:
self.polyline_steps = 1 | Python | nomic_cornstack_python_v1 |
function dgTimer self timerMetric timerType
begin
pass
end function | def dgTimer(self, timerMetric, timerType):
pass | Python | nomic_cornstack_python_v1 |
function test_login_valid self
begin
call create_user name=string Michael email=string michael.tcoelho@gmail.com password=string 123
set data = dictionary email=string michael.tcoelho@gmail.com password=string 123
set form = call AuthenticationForm data
assert true call is_valid
assert equal call non_field_errors list
... | def test_login_valid(self):
User.objects.create_user(name='Michael', email='michael.tcoelho@gmail.com', password='123')
data = dict(email='michael.tcoelho@gmail.com', password='123')
form = AuthenticationForm(data)
self.assertTrue(form.is_valid())
self.assertEqual(form.non_fie... | Python | nomic_cornstack_python_v1 |
function _sortCalls self
begin
sort calls key=lambda a -> call getTime
end function | def _sortCalls(self):
self.calls.sort(key=lambda a: a.getTime()) | Python | nomic_cornstack_python_v1 |
import requests
import re
set headers = dict string Authorization string Bearer 5uVEBGiZ40XPkmlPEw-fb478unHY3MG2j2KvwVNcQF61OUjLs1lwjWTDIZfHgRwzcf3aWC7McbdWqs4qz-Z3XB0HGR7rOsxD-sbQsbbOeMfl8c8xNoGW3Sbv4NvUWnYx
function find_all_rests zip_code
begin
set search_url = string https://api.yelp.com/v3/businesses/search?locati... | import requests
import re
headers = {"Authorization":"Bearer 5uVEBGiZ40XPkmlPEw-fb478unHY3MG2j2KvwVNcQF61OUjLs1lwjWTDIZfHgRwzcf3aWC7McbdWqs4qz-Z3XB0HGR7rOsxD-sbQsbbOeMfl8c8xNoGW3Sbv4NvUWnYx"}
def find_all_rests(zip_code):
search_url = "https://api.yelp.com/v3/businesses/search?location=" + str(zip_code) + "&term=... | Python | zaydzuhri_stack_edu_python |
function test_invalid_tokens self
begin
assert true 1 + 1
end function | def test_invalid_tokens(self):
self.assertTrue(1 + 1) | Python | nomic_cornstack_python_v1 |
import re
from tool.android.android_studio_translator import Segment
from tool.android.android_studio_translator import TestSql
from tool.android.android_studio_translator.web.util import SegmentUtil
from tool.android.android_studio_translator.web.util import TimeLogger
from xx.database.mysql_helper import MySqlHelper
... | import re
from tool.android.android_studio_translator import Segment
from tool.android.android_studio_translator import TestSql
from tool.android.android_studio_translator.web.util import SegmentUtil
from tool.android.android_studio_translator.web.util import TimeLogger
from xx.database.mysql_helper import MySqlHelper... | Python | zaydzuhri_stack_edu_python |
string DetailsParser.py this is the file that allows us to quickly query the data source: classes.uoregon.edu specifically the detailed view for any specific subject and crn combination Authors: (RegTools) Joseph Goh Mason Sayyadi Owen McEvoy Ryan Gurnick Samuel Lundquist Priority credit to: Ryan Gurnick - 2/27/20 Crea... | """
DetailsParser.py this is the file that allows us to quickly query the data source:
classes.uoregon.edu specifically the detailed view for any specific subject and crn
combination
Authors:
(RegTools)
Joseph Goh
Mason Sayyadi
Owen McEvoy
Ryan Gurnick
Samuel Lundquist
Priority credit to:
Ryan Gurnick - 2/27/20 Crea... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string COMBINATION METHODS module This module contains definitions of forecast combinations methods, which are used to produce the combine forecasts. The first input should be a DataFrame with the training data of the following form: the first column contains the realized values, the other... | # -*- coding: utf-8 -*-
"""
COMBINATION METHODS module
This module contains definitions of forecast combinations methods, which are
used to produce the combine forecasts.
The first input should be a DataFrame with the training data of the following
form: the first column contains the realized values, the other column... | Python | zaydzuhri_stack_edu_python |
function readFile self fileName
begin
set contents = list
set f = open fileName
for line in f
begin
append contents line
end
close f
set result = call segmentWords join string contents
return result
end function | def readFile(self, fileName):
contents = []
f = open(fileName)
for line in f:
contents.append(line)
f.close()
result = self.segmentWords('\n'.join(contents))
return result | Python | nomic_cornstack_python_v1 |
comment # Recursion
comment Time complexity --> o(n)
comment space complexity --> o(n)
string # Definition for a Node. class Node(object): def __init__(self, val=0, left=None, right=None, next=None): self.val = val self.left = left self.right = right self.next = next
class Solution extends object
begin
function connect... | # # Recursion
# Time complexity --> o(n)
# space complexity --> o(n)
"""
# Definition for a Node.
class Node(object):
def __init__(self, val=0, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution(object):
def c... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set model_name = string ARDroneCarre
comment Publishers
set pub_cmd_vel = call Publisher string cmd_vel_RHC Twist queue_size=300
comment Subscribers
set sub_vicon_data = call Subscriber format string /vicon/{0}/{0} model_name TransformStamped process_vicon_data
set sub_des_pos = call Subscr... | def __init__(self):
self.model_name = 'ARDroneCarre'
# Publishers
self.pub_cmd_vel = rospy.Publisher('cmd_vel_RHC',
Twist,
queue_size = 300)
# Subscribers
self.sub_vicon_data = rospy.Subscr... | Python | nomic_cornstack_python_v1 |
function print_menu menu
begin
for tuple name price in items menu
begin
print name string :$ format price string .2f sep=string
end
end function
function get_order menu
begin
set orders = list
set order = input string what would you like to order?(Q to Quit)
while upper order != string Q
begin
set found = get menu ord... | def print_menu(menu):
for name, price in menu.items():
print(name, ':$', format(price, '.2f'), sep='')
def get_order(menu):
orders=[]
order= input("what would you like to order?(Q to Quit)")
while (order.upper() != 'Q'):
found = menu.get(order)
if found:
orders.appe... | Python | zaydzuhri_stack_edu_python |
function add_test_user self name email
begin
call until call visibility_of_element_located ADD_MANUALLY_FORM
set add_manually_form = call find_element *UfOPageLayout.ADD_MANUALLY_FORM
set name_paper_input = call find_element *UfOPageLayout.ADD_MANUALLY_INPUT_NAME
set name_input = call find_element ID string input
call ... | def add_test_user(self, name, email):
WebDriverWait(self.driver, UfOPageLayout.DEFAULT_TIMEOUT).until(
EC.visibility_of_element_located(((UfOPageLayout.ADD_MANUALLY_FORM))))
add_manually_form = self.driver.find_element(
*UfOPageLayout.ADD_MANUALLY_FORM)
name_paper_input = add_manually_form.f... | Python | nomic_cornstack_python_v1 |
function output_height_2d layer height
begin
assert is instance layer tuple Conv2d MaxPool2d
set padding = call _value_at_axis padding 0
set dilation = call _value_at_axis dilation 0
set kernel_size = call _value_at_axis kernel_size 0
set stride = call _value_at_axis stride 0
return floor height + 2 * padding - dilatio... | def output_height_2d(layer, height):
assert isinstance(layer, (torch.nn.Conv2d, torch.nn.MaxPool2d))
padding = _value_at_axis(layer.padding, 0)
dilation = _value_at_axis(layer.dilation, 0)
kernel_size = _value_at_axis(layer.kernel_size, 0)
stride = _value_at_axis(layer.stride, 0)
return math.flo... | Python | nomic_cornstack_python_v1 |
comment {{{
function SendEmail_on_finish jobid base_www_url finish_status name_server from_email to_email contact_email logfile=string errfile=string
begin
set err_msg = string
if exists path errfile
begin
set err_msg = call ReadFile errfile
end
set subject = string Your result for %s JOBID=%s % tuple name_server job... | def SendEmail_on_finish(jobid, base_www_url, finish_status, name_server, from_email, to_email, contact_email, logfile="", errfile=""):# {{{
err_msg = ""
if os.path.exists(errfile):
err_msg = myfunc.ReadFile(errfile)
subject = "Your result for %s JOBID=%s"%(name_server, jobid)
if finish_status =... | Python | nomic_cornstack_python_v1 |
comment !/env/python3
set text_file = open string Day_03/input string r
set lines = list comprehension strip x for x in read lines text_file
comment Part 01
set traverse = dict string x 3 ; string y 1
set pos = dict string x 0 ; string y 0
set trees = 0
while pos at string y < length lines - 1
begin
set pos at string x... | #!/env/python3
text_file = open("Day_03/input", "r")
lines = [x.strip() for x in text_file.readlines()]
# Part 01
traverse = {"x": 3, "y": 1}
pos = {"x": 0, "y": 0}
trees = 0
while pos["y"] < (len(lines) - 1):
pos["x"] += traverse["x"]
pos["y"] += traverse["y"]
line = lines[pos["y"]]
mod_x = pos["x"] ... | Python | zaydzuhri_stack_edu_python |
string O(N**3 * log(4*10**9)) Python 3.8.2: TLE PyPy3 (7.3.0): AC (1846 ms)
import math
import sys
function main
begin
set readline = readline
set n = integer read line
set x = list
set y = list
set p = list
for i in range n
begin
set tuple xi yi pi = map int split read line
append x xi
append y yi
append p pi
end
s... | """
O(N**3 * log(4*10**9))
Python 3.8.2: TLE
PyPy3 (7.3.0): AC (1846 ms)
"""
import math
import sys
def main():
readline = sys.stdin.readline
n = int(readline())
x = []
y = []
p = []
for i in range(n):
xi, yi, pi = map(int, readline().split())
x.append(xi)
y.append(yi... | Python | zaydzuhri_stack_edu_python |
function mixup_numerical x1 x2
begin
assert type x1 == type x2 msg string x1 and x2 should have the same numerical type.
if is instance x1 int
begin
return call mixup_integer x1 x2
end
else
if is instance x1 float
begin
return call mixup_float x1 x2
end
else
begin
raise call TypeError string Unsupported data type.
end
... | def mixup_numerical(
x1: Union[float, int],
x2: Union[float, int]
) -> Tuple[Union[float, int]]:
assert type(x1) == type(x2), "x1 and x2 should have the same numerical type."
if isinstance(x1, int):
return mixup_integer(x1, x2)
elif isi... | Python | nomic_cornstack_python_v1 |
function getWeight self
begin
pass
end function | def getWeight(self):
pass | Python | nomic_cornstack_python_v1 |
import torch
class Checkpoint
begin
string Class that saves a model whenever a designated metric is improved.
function __init__ self path monitor mode=string max verbose=true
begin
string path: str Path to save the model. monitor: str Name of the metric we want to monitor. Has to be the same name as in the History obje... | import torch
class Checkpoint():
"""Class that saves a model whenever a designated metric is improved."""
def __init__(self, path, monitor, mode='max', verbose=True):
"""
path: str
Path to save the model.
monitor: str
Name of the metric we want to monitor.
... | Python | zaydzuhri_stack_edu_python |
from functools import lru_cache
import sys
call setrecursionlimit 10 ^ 9
set test_mat = list list 1 2 0 list 2 4 5 list 7 0 1
string def maks_neumn(matrika,i,j): #To mogoce ni cist prou, loh da je treba nekje i pa j zamenat visina = len(matrika) - i sirina = len(matrika[0]) - j if visina == 1: return sum(matrika[0]) el... | from functools import lru_cache
import sys
sys.setrecursionlimit(10**9)
test_mat = [
[1,2,0],
[2,4,5],
[7,0,1]
]
'''
def maks_neumn(matrika,i,j):
#To mogoce ni cist prou, loh da je treba nekje i pa j zamenat
visina = len(matrika) - i
sirina = len(matrika[0]) - j
if visina == 1:
re... | Python | zaydzuhri_stack_edu_python |
function two_sum_dict a sum
begin
set dict = dict
for i in range length a
begin
if sum - a at i in dict
begin
return true
end
set dict at a at i = 1
end
return false
end function
function two_sum_two_pointer a sum
begin
sort a
set tuple l r = tuple 0 length a - 1
while l < r
begin
if a at l + a at r == sum
begin
retur... | def two_sum_dict(a,sum):
dict={}
for i in range(len(a)):
if ((sum-a[i]) in dict):
return True
dict[a[i]]=1
return False
def two_sum_two_pointer(a,sum):
a.sort()
l,r=0,len(a)-1
while(l<r):
if(a[l]+a[r]==sum):
return True
elif(a[l]+a[r]<sum)... | Python | zaydzuhri_stack_edu_python |
function run self
begin
pass
end function | def run(self):
pass | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Apr 14 08:07:36 2020 Classes representing different kind of Ordinary Differential Equations (ODEs). @author: Carollo Andrea - Tomasi Matteo
import numpy as np
import pinocchio as pin
from numpy.linalg import norm
class ContactPoint_ODE
begin
string A point on the robo... | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 08:07:36 2020
Classes representing different kind of Ordinary Differential Equations (ODEs).
@author: Carollo Andrea - Tomasi Matteo
"""
import numpy as np
import pinocchio as pin
from numpy.linalg import norm
class ContactPoint_ODE:
''' A point on the robot su... | Python | zaydzuhri_stack_edu_python |
function getCondition self symbol
begin
return call getCondition symbol
end function | def getCondition(self, symbol):
return self.__boolCombiner.getCondition(symbol) | Python | nomic_cornstack_python_v1 |
function _get_threshold self graph benchmark entry_name
begin
if get params string branch
begin
set branch_suffix = string @ + get params string branch
end
else
begin
set branch_suffix = string
end
set max_threshold = none
for tuple regex threshold in items regressions_thresholds
begin
if match regex entry_name + bran... | def _get_threshold(self, graph, benchmark, entry_name):
if graph.params.get('branch'):
branch_suffix = '@' + graph.params.get('branch')
else:
branch_suffix = ''
max_threshold = None
for regex, threshold in self.conf.regressions_thresholds.items():
if... | Python | nomic_cornstack_python_v1 |
import math
function getArea radius
begin
set pi = pi
set area = pi * radius * radius
return area
end function
function getFirstAndLast list
begin
set length = length list
return list list at 0 list at length - 1
end function
function getNumDays date1 date2
begin
set d1 = 0
set d2 = 0
set diff = 0
if date1 == string Mo... | import math
def getArea(radius):
pi = math.pi
area = pi * radius * radius
return area
def getFirstAndLast(list):
length = len(list)
return [list[0], list[length - 1]]
def getNumDays(date1, date2):
d1 = 0
d2 = 0
diff = 0
if date1 == "Monday":
d1 = 1
if date1 == "Tues... | 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.