code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function isleft self
begin
try
begin
return left is self
end
except AttributeError
begin
return false
end
end function | def isleft(self):
try:
return self.parent.left is self
except AttributeError:
return False | Python | nomic_cornstack_python_v1 |
async function record self ctx start=none end=none
begin
if bot
begin
return
end
if not start or not end
begin
await call send string Insufficient arguments! Arguements: <start ID> <end ID>
return
end
set tuple summary keywords clean_messages = await call convert_to_summary ctx start end
if not summary
begin
set summar... | async def record(self, ctx, start=None, end=None):
if ctx.message.author.bot:
return
if not start or not end:
await ctx.send(
"Insufficient arguments!\n Arguements: <start ID> <end ID>"
)
return
summary, keywords, clean_messages =... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
string Created on 2018-7-5 @author: dell
from selenium import webdriver
import time
function scroll n i
begin
return format string window.scrollTo(0,(document.body.scrollHeight/{0})*{1}); n i
end function
set driver = call Firefox
set url = string https://www.jd.com
get driver url
set searchbox = ... | #coding: utf-8
'''
Created on 2018-7-5
@author: dell
'''
from selenium import webdriver
import time
def scroll(n,i):
return "window.scrollTo(0,(document.body.scrollHeight/{0})*{1});".\
format(n,i)
driver = webdriver.Firefox()
url = "https://www.jd.com"
driver.get(url)
searchbox = driver.find_element_by... | Python | zaydzuhri_stack_edu_python |
string 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q 最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。” 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5] 示例 1: 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 输出: 6 解释: 节点 2 和节点 8 的最近公共祖先是 6。 示例 2: 输入: root = [6,2,8,0,4,7,9,null,null,... | '''
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q
最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
输出: 6
解释: 节点 2 和节点 8 的最近公共祖先是 6。
示例 2:
输入: root = [6,2,8,0,4,7,9,null,nu... | Python | zaydzuhri_stack_edu_python |
function snapshot self label snapshot_type=string statevector qubits=none params=none
begin
string Take a statevector snapshot of the internal simulator representation. Works on all qubits, and prevents reordering (like barrier). For other types of snapshots use the Snapshot extension directly. Args: label (str): a sna... | def snapshot(self,
label,
snapshot_type='statevector',
qubits=None,
params=None):
"""Take a statevector snapshot of the internal simulator representation.
Works on all qubits, and prevents reordering (like barrier).
For other types of snapshots use the Sn... | Python | jtatman_500k |
for day in range 1 10000000000
begin
if x <= 0
begin
print day - 1 file=open string forest.out string w
exit
end
if day % k != 0
begin
set x = x - a
end
if day % m != 0
begin
set x = x - b
end
end | for day in range(1,10000000000):
if x<=0:
print(day-1, file=open('forest.out', 'w'))
exit()
if day % k != 0:
x-=a
if day % m != 0:
x-=b
| Python | zaydzuhri_stack_edu_python |
string Created on Nov 11, 2015 @author: Sean
import sqlite3 , csv , datetime , pytz
function median aList
begin
set aList = sorted aList
if length aList == 0
begin
return none
end
else
if length aList == 1
begin
set m = aList at 0
set l1 = list
set l2 = list
end
else
if length aList % 2 == 1
begin
set middle = intege... | '''
Created on Nov 11, 2015
@author: Sean
'''
import sqlite3, csv, datetime, pytz
def median(aList):
aList = sorted(aList)
if len(aList) == 0:
return None
elif len(aList) == 1:
m = aList[0]
l1 = []
l2 = []
elif len(aList) % 2 == 1:
middle = int((len(aList)-1)/2)... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import os
import glob
import sys
import argparse
set parser = call ArgumentParser description=string Source code txt.maker
call add_argument string --e nargs=string + default=none type=str help=string Supply file extensions to add to source file
call add_argument string --i nargs=string + defau... | #!/usr/bin/python
import os
import glob
import sys
import argparse
parser = argparse.ArgumentParser(description='Source code txt.maker')
parser.add_argument("--e", nargs='+', default=None, type=str, help="Supply file extensions to add to source file")
parser.add_argument("--i", nargs='+', default=None, type=str, help... | Python | zaydzuhri_stack_edu_python |
function buildSeekTable self memoize=false
begin
set pickle_name = strip filename string .seq + string .seek
if memoize
begin
if is file path pickle_name
begin
set seek_table = load pickle open pickle_name string rb
return
end
end
comment assert self.header['numFrames']>0
set n = header at string numFrames
if n == 0
be... | def buildSeekTable(self,memoize=False):
pickle_name = self.filename.strip(".seq") + ".seek"
if memoize:
if os.path.isfile(pickle_name):
self.seek_table = pickle.load(open(pickle_name, 'rb'))
return
# assert self.header['numFrames']>0
n=self.he... | Python | nomic_cornstack_python_v1 |
from abc import ABCMeta
from abc import abstractmethod
class Sender
begin
function __init__ self to=string
begin
set to = to
decorator abstractmethod
function send self msg
begin
pass
end function
function set_to self to
begin
set to = to
end function
comment 탬플릿 : 기본양식이 정해져있고 바꿀거만 바꿔라
comment 처리절차는 정해져있으나 어떻게 처리할지는 안정... | from abc import ABCMeta
from abc import abstractmethod
class Sender(metaclass=ABCMeta):
def __init__(self,to=''):
self.to=to
@abstractmethod
def send(self,msg):
pass
def set_to(self,to):
self.to= to
## 탬플릿 : 기본양식이 정해져있고 바꿀거만 바꿔라
... | Python | zaydzuhri_stack_edu_python |
comment Expected value calculations
import math
import sys
function calculate_distance character enemy
begin
return square root power position at 0 - position at 0 2 + power position at 1 - position at 1 2
end function
class ExpectedValue extends object
begin
set evalue_none = 0
set evalue_dps = 0
set player_ehealth = ... | # Expected value calculations
import math
import sys
def calculate_distance(character, enemy):
return math.sqrt(pow(character.position[0] - enemy.position[0], 2) + pow(character.position[1] - enemy.position[1], 2))
class ExpectedValue(object):
evalue_none = 0
evalue_dps = 0
player_ehealth = 0
en... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
string task 4
from flask import Flask
if __name__ == string __main__
begin
set app = call Flask __name__
decorator call route string / strict_slashes=false
function home
begin
string the home directory displaying
return string Hello HBNB!
end function
decorator call route string /hbnb strict_s... | #!/usr/bin/python3
"""task 4"""
from flask import Flask
if __name__ == "__main__":
app = Flask(__name__)
@app.route("/", strict_slashes=False)
def home():
"""the home directory displaying"""
return "Hello HBNB!"
@app.route("/hbnb", strict_slashes=False)
def hbnb():
"""the... | Python | zaydzuhri_stack_edu_python |
import numpy as np
function is_prime n
begin
if n <= 1
begin
return false
end
for i in range 2 integer square root n + 1
begin
if n % i == 0
begin
return false
end
end
return true
end function
function is_perfect_square n
begin
set sqrt_n = integer square root n
return sqrt_n * sqrt_n == n
end function
function next_pr... | import numpy as np
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(np.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def is_perfect_square(n):
sqrt_n = int(np.sqrt(n))
return sqrt_n * sqrt_n == n
def next_prime(n):
while True:
n += 1
... | Python | greatdarklord_python_dataset |
from macro_creator import MacroCreator , CDefinition
from arithmatic_parser import *
import re
set HEX_REGEX = compile string 0[xX]([0-9a-fA-F]+)
class Define extends CDefinition
begin
string class holding name and values extracted from #define values are use to try and merge lists of Define's to minimize resulting cod... | from .macro_creator import MacroCreator, CDefinition
from .arithmatic_parser import *
import re
HEX_REGEX = re.compile(r"0[xX]([0-9a-fA-F]+)")
class Define(CDefinition):
"""
class holding name and values extracted from #define
values are use to try and merge lists of Define's to minimize resulting code
... | Python | zaydzuhri_stack_edu_python |
function apply_actuation_torques self actuator_nrs axis_nrs actuation_torques apply_zero_torques=true
begin
assert is instance actuator_nrs list msg string actuator_nrs has to be a list of ints
assert is instance axis_nrs list msg string axis_nrs has to be a list of ints
assert is instance actuation_torques list msg st... | def apply_actuation_torques(
self, actuator_nrs, axis_nrs, actuation_torques, apply_zero_torques=True
):
assert isinstance(actuator_nrs, list), f"actuator_nrs has to be a list of ints"
assert isinstance(axis_nrs, list), f"axis_nrs has to be a list of ints"
assert isinstance(
... | Python | nomic_cornstack_python_v1 |
import requests
import copy
import collections
import psycopg2
import yaml
import datetime
import time
import pandas as pd
function slack_notify_dag_error context
begin
string Slack notification when a DAG fail. This function should be used in on_failure_callback parameter of BashOperator.
set dag_id = string context a... | import requests
import copy
import collections
import psycopg2
import yaml
import datetime
import time
import pandas as pd
def slack_notify_dag_error(context):
"""
Slack notification when a DAG fail.
This function should be used in on_failure_callback parameter of BashOperator.
"""
dag_id = str(c... | Python | zaydzuhri_stack_edu_python |
function help
begin
info YELLOW + string fips clone [project] + DEF + string fetch a project directory from a git repo, project is either a direct git-url, or a project name in the fips registry
end function | def help() :
log.info(log.YELLOW + "fips clone [project]\n" + log.DEF +
" fetch a project directory from a git repo, project is either\n"
" a direct git-url, or a project name in the fips registry") | Python | nomic_cornstack_python_v1 |
for item in source
begin
append dest item
end
print dest | for item in source:
dest.append(item)
print(dest) | Python | jtatman_500k |
function GetUseReferenceImage self
begin
return call itkGenerateImageSourceIUC2_GetUseReferenceImage self
end function | def GetUseReferenceImage(self) -> "bool":
return _itkGenerateImageSourcePython.itkGenerateImageSourceIUC2_GetUseReferenceImage(self) | Python | nomic_cornstack_python_v1 |
function main
begin
comment Set your workspace to the assignment geodatabase on your computer
set workspace = string Your workspace
set mNDVI = call mapalgebraNDVI call getBands
set nNDVI = call numpyNDVI call getBands
end function
comment Save mNDVI as u'mNDVI' and nNDVI as u'nNDVI' when you are done | def main():
arcpy.env.workspace = u'Your workspace' #Set your workspace to the assignment geodatabase on your computer
mNDVI = mapalgebraNDVI(getBands())
nNDVI = numpyNDVI(getBands())
#Save mNDVI as u'mNDVI' and nNDVI as u'nNDVI' when you are done | Python | nomic_cornstack_python_v1 |
function test_segment_dat_with_restriction_to_new_data_ival_pos_pos self
begin
comment [ 0., 100., 200., 300., 400., 500., 600., 700., 800.]
comment M100 200 600
comment M200 300 700
comment M299 399 799
comment M300 400 800
comment M301 401 801
set data = ones tuple 9 3
set time = linear space 0 900 9 endpoint=false
s... | def test_segment_dat_with_restriction_to_new_data_ival_pos_pos(self):
# [ 0., 100., 200., 300., 400., 500., 600., 700., 800.]
# M100 200 600
# M200 300 700
# M299 399 ... | Python | nomic_cornstack_python_v1 |
comment Definition for singly-linked list.
comment class ListNode:
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution
begin
comment @param A : head node of linked list
comment @param B : integer
comment @return the head node in the linked list
function rotateRight self A B
begin... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param A : head node of linked list
# @param B : integer
# @return the head node in the linked list
def rotateRight(self, A, B):
n, curr = 0, A
... | Python | zaydzuhri_stack_edu_python |
function skip_bytes src off lim bsrc
begin
set blen = length bsrc
if blen > lim - off
begin
set blen = lim - off
end
set i = 0
while i < blen and bsrc at i == src at i + off
begin
set i = i + 1
end
return if expression i == length bsrc then i + off else - i + off
end function | def skip_bytes(src, off, lim, bsrc):
blen = len(bsrc)
if blen > lim - off:
blen = lim - off
i = 0
while i < blen and bsrc[i] == src[i + off]:
i += 1
return i + off if i == len(bsrc) else -(i + off) | Python | nomic_cornstack_python_v1 |
comment real signature unknown
function __subclasshook__ self *args **kwargs
begin
pass
end function | def __subclasshook__(self, *args, **kwargs): # real signature unknown
pass | Python | nomic_cornstack_python_v1 |
comment noqa: E501 # noqa: E501
function __init__ self id=none status=none trades=none commission=none currency=none payment=none price=none quantity=none figi=none instrument_type=none is_margin_call=none date=none operation_type=none local_vars_configuration=none
begin
if local_vars_configuration is none
begin
set lo... | def __init__(self, id=None, status=None, trades=None, commission=None, currency=None, payment=None, price=None, quantity=None, figi=None, instrument_type=None, is_margin_call=None, date=None, operation_type=None, local_vars_configuration=None): # noqa: E501 # noqa: E501
if local_vars_configuration is None:
... | Python | nomic_cornstack_python_v1 |
function execute_sql_report request sql_report_id
begin
set sql_report = call get_object_or_404 SQLReport pk=sql_report_id
set param_names = call get_sql_parameters
set params = none
if length param_names > 0
begin
if method == string POST
begin
set form = call SQLReportParameterForm param_names POST
if call is_valid
b... | def execute_sql_report(request, sql_report_id):
sql_report = get_object_or_404(SQLReport, pk=sql_report_id)
param_names = sql_report.get_sql_parameters()
params = None
if len(param_names) > 0:
if request.method == 'POST':
form = SQLReportParameterForm(param_names, request.POST)... | Python | nomic_cornstack_python_v1 |
function create_phage_table_insert gnm
begin
set cluster = call convert_for_sql cluster check_set=set literal string Singleton single=true
set subcluster = call convert_for_sql subcluster check_set=set literal string none single=true
comment gnm.seq is a BioPython Seq object.
comment It is coerced to string by default.... | def create_phage_table_insert(gnm):
cluster = mysqldb_basic.convert_for_sql(gnm.cluster,
check_set={"Singleton"},
single=True)
subcluster = mysqldb_basic.convert_for_sql(gnm.subcluster,
... | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template_string
set app = call Flask __name__
decorator call route string /
function hello
begin
set html = string " <html> <h2>Hello, Welcome to Jinja2</h2> <ul> {% for car in cars %} <li>{{ car }}</li> {% endfor %} </ul> </html>
set cars = list string Hyundai string Suzuki string Rena... | from flask import Flask, render_template_string
app = Flask(__name__)
@app.route('/')
def hello():
html = """"
<html>
<h2>Hello, Welcome to Jinja2</h2>
<ul>
{% for car in cars %}
<li>{{ car }}</li>
{% endfor %}
</ul>
</html>
"""
cars = ["Hyundai", "S... | Python | zaydzuhri_stack_edu_python |
string Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. https://leetcode.com/problems/two-sum/
from __future__ import annotations
class Solution extends ob... | """
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
https://leetcode.com/problems/two-sum/
"""
from __future__ import annotations
class Solution(object... | Python | zaydzuhri_stack_edu_python |
function ingest_results self results isCsv=false
begin
for r in results
begin
set image = call Image
if isCsv
begin
call parse_row r
end
else
begin
call parse_record r
end
comment print("metadata: %s" % image.metadata)
comment answer = input("Press enter...")
append img_lst image
end
end function | def ingest_results(self, results, isCsv=False):
for r in results:
image = Image()
if isCsv:
image.parse_row(r)
else:
image.parse_record(r)
# print("metadata: %s" % image.metadata)
# answer = input("Press enter..... | Python | nomic_cornstack_python_v1 |
comment David Huang
comment Computer Programming for Designers and Artists
comment Week 5 - Oct 11 2017
comment ID 0239637
comment Takes a list as argument and prints out any element that appears more than once in the list.
comment CONSTANTS
set num_list = list 60 83 90 60 19 20 21 21 20 84 83 90 60 21 60
comment This ... | # David Huang
# Computer Programming for Designers and Artists
# Week 5 - Oct 11 2017
# ID 0239637
# Takes a list as argument and prints out any element that appears more than once in the list.
# CONSTANTS
num_list = [60, 83, 90, 60, 19, 20, 21, 21, 20, 84, 83, 90, 60, 21, 60]
duplicate_list = [] # This empty list is... | Python | zaydzuhri_stack_edu_python |
function tData src sub_shp inverse=false
begin
set dest = reshape zeros size dtype=dtype shape
set typesize = itemsize
set shape = shape
set dimension = length shape
set src2 = call from_buffer src
set dest2 = call from_buffer dest
call tData src2 dest2 typesize sub_shp shape dimension inverse
return dest
end function | def tData(src, sub_shp, inverse=False):
dest = np.zeros(src.size, dtype=src.dtype).reshape(src.shape)
typesize = src.dtype.itemsize
shape = src.shape
dimension = len(shape)
src2 = ffi.from_buffer(src)
dest2 = ffi.from_buffer(dest)
lib.tData(src2, dest2, typesize, sub_shp, shape, dimensio... | Python | nomic_cornstack_python_v1 |
import numpy as np
set english_score = array list 55 89 76 65 48 70
set math_score = array list 60 85 60 68 55 60
set chinese_score = array list 65 100 82 72 66 77
set count = 0
set result = call greater english_score math_score
comment np.where(result = True,result,result)
for item in result
begin
if item == true
begi... | import numpy as np
english_score = np.array([55,89,76,65,48,70])
math_score = np.array([60,85,60,68,55,60])
chinese_score = np.array([65,100,82,72,66,77])
count = 0
result = np.greater(english_score,math_score)
#np.where(result = True,result,result)
for item in result:
if(item == True):
count += 1
#有多... | Python | zaydzuhri_stack_edu_python |
function submit self bid
begin
set bids = call collect
set startId = call get_last_id
set endId = startId + length bids
set newBidsIds = range startId endId
extend orders bids
if type == string CO
begin
extend complex_single_orders newBidsIds
end
else
if type == string PO
begin
set pun_orders_ids at bid = newBidsIds at... | def submit(self, bid):
bids = bid.collect()
startId = self.orders.get_last_id()
endId = startId + len(bids)
newBidsIds = range(startId, endId)
self.orders.extend(bids)
if bid.type == 'CO':
self.complex_single_orders.extend(newBidsIds)
elif bid.type ... | Python | nomic_cornstack_python_v1 |
function grab_debuffs source target_in
begin
set inactive = dict
set sensor_str = sensor_strength
set target = target_in
comment I'm sure there's a list comprehension thing that could be used
comment to clean this up but I have no idea what
if target_painter
begin
if get get debuffs string inactive dict string target_... | def grab_debuffs(source, target_in):
inactive = {}
sensor_str = target_in.schema.sensor_strength
target = target_in
# I'm sure there's a list comprehension thing that could be used
# to clean this up but I have no idea what
if source.target_painter:
if target.debuffs.get('inactive', {}).... | Python | nomic_cornstack_python_v1 |
function bfs graph start goal
begin
set final = list
set agenda = list list start
comment Process node queue
while agenda
begin
set path = pop agenda 0
comment Exit if a path is found which reaches the goal
if path at - 1 == goal
begin
set final = path
break
end
comment Push the new paths onto the queue
set connected ... | def bfs(graph, start, goal):
final = []
agenda = [[start]]
# Process node queue
while agenda:
path = agenda.pop(0)
# Exit if a path is found which reaches the goal
if path[-1] == goal:
final = path
break
# Push the new paths onto the queue
... | Python | nomic_cornstack_python_v1 |
function safe_exp w thresh
begin
set slope = exp thresh
with call variable_scope string safe_exponential
begin
set lin_region = call to_float w > thresh
set lin_out = slope * w - thresh + 1.0
set exp_out = exp w
set out = lin_region * lin_out + 1.0 - lin_region * exp_out
end
return out
end function | def safe_exp(w, thresh):
slope = np.exp(thresh)
with tf.variable_scope('safe_exponential'):
lin_region = tf.to_float(w > thresh)
lin_out = slope*(w - thresh + 1.)
exp_out = tf.exp(w)
out = lin_region*lin_out + (1.-lin_region)*exp_out
return out | Python | nomic_cornstack_python_v1 |
function segment_radial_dist seg pos
begin
string Return the radial distance of a tree segment to a given point The radial distance is the euclidian distance between the mid-point of the segment and the point in question. Parameters: seg: tree segment pos: origin to which distances are measured. It must have at lease 3... | def segment_radial_dist(seg, pos):
'''Return the radial distance of a tree segment to a given point
The radial distance is the euclidian distance between the mid-point of
the segment and the point in question.
Parameters:
seg: tree segment
pos: origin to which distances are measured. ... | Python | jtatman_500k |
function message_ports_in self
begin
return call atsc_equalizer_sptr_message_ports_in self
end function | def message_ports_in(self):
return _atsc_swig.atsc_equalizer_sptr_message_ports_in(self) | Python | nomic_cornstack_python_v1 |
comment 하나의 정수를 입력받아 약수를 출력하는 함수를 만드시오.
function yaksu num
begin
print string 약수:
for i in range 1 num + 1
begin
if num % i == 0
begin
print i
end
end
end function
set n = integer input string 정수입력:
call yaksu n | # 하나의 정수를 입력받아 약수를 출력하는 함수를 만드시오.
def yaksu(num):
print('약수:')
for i in range(1, num+1):
if num%i == 0:
print(i)
n = int( input('정수입력:'))
yaksu(n)
| Python | zaydzuhri_stack_edu_python |
function get_manikin_positions self datum_name=string SWRI_H_POINT veh_role=none
begin
set manikins = desired_params at string Manikin
set mani_list = list comprehension dict string name k ; string vehicle_role manikins at k at string properties at string vehicle_role ; datum_name manikins at k at string datums at datu... | def get_manikin_positions(self, datum_name="SWRI_H_POINT", veh_role=None):
manikins = self.desired_params['Manikin']
mani_list = [{'name': k,
'vehicle_role': manikins[k]['properties']['vehicle_role'],
datum_name: manikins[k]['datums'][datum_name]['global'... | Python | nomic_cornstack_python_v1 |
comment based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa
import math
from enum import Enum
from typing import Callable , Dict , List , Optional , Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from k... | # based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa
import math
from enum import Enum
from typing import Callable, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.g... | Python | jtatman_500k |
function update_device device
begin
set payload = call get_json
if string name in payload and payload at string name != device
begin
raise call BadRequest string Device name does not match between URL and JSON payload
end
try
begin
set properties = show device
for k in payload
begin
set properties at k = payload at k
e... | def update_device(device):
payload = request.get_json()
if ('name' in payload) and (payload['name'] != device):
raise BadRequest(
'Device name does not match between URL and JSON payload')
try:
properties = devices.show(device)
for k in payload:
properties[k] ... | Python | nomic_cornstack_python_v1 |
from tkinter import *
class InterfaceGrafica
begin
function __init__ self titulo=string Interface Gráfica dimensoes=string 300x500
begin
set __container = call Tk
title __container titulo
call geometry dimensoes
set __body = call createFrame __container
set __listaElementos = list
end function
function start self
begi... | from tkinter import *
class InterfaceGrafica:
def __init__(self, titulo = 'Interface Gráfica', dimensoes = '300x500'):
self.__container = Tk()
self.__container.title(titulo)
self.__container.geometry(dimensoes)
self.__body = self.createFrame(self.__container)
self.__listaEl... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as pth
set x = linear space - pi pi 256
set tuple S C = tuple sin x cos x
plot x S
show
call six
call suptitle t k
call switch_backend
scatter plt 1 2
plot x y
scatter plt 2
class some_class extends object
begin
string This is the docstring of th... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.path as pth
x = np.linspace(-np.pi, np.pi, 256)
S, C = np.sin(x), np.cos(x)
plt.plot(x, S)
plt.show()
plt.six()
plt.suptitle(t, k)
plt.switch_backend()
plt.scatter(1, 2)
plt.plot(x, y)
plt.scatter(2)
class some_class(object):
"""
This is t... | Python | zaydzuhri_stack_edu_python |
function get_probabilities self sequence_input smoothing_type
begin
set sequence_total_count : Optional at int = none
set current_counts : Optional at List at Tuple at tuple str int = none
if sequence_input not in model
begin
comment handle unknown input
set sequence_total_count = 1
set current_counts = list tuple unse... | def get_probabilities(self, sequence_input: str,
smoothing_type: SmoothingType) -> List[Tuple[str, float]]:
sequence_total_count: Optional[int] = None
current_counts: Optional[List[Tuple[str, int]]] = None
if sequence_input not in self.model:
# handle unkno... | Python | nomic_cornstack_python_v1 |
class account
begin
function __init__ self accountno balance
begin
set accountno = accountno
set balance = balance
end function
function deposit self amount
begin
set balance = balance + amount
end function
function __str__ self
begin
return string account number + string accountno + string + string balance: + string ... | class account:
def __init__(self, accountno, balance):
self.accountno = accountno
self.balance = balance
def deposit(self,amount):
self.balance += amount
def __str__(self):
return "account number" + str(self.accountno)+"\n"+ \
"balance:"+ str(self.balance)
... | Python | zaydzuhri_stack_edu_python |
comment clone repos given in all_repos.json, extract commit log, and clean up unwanted (non-py) files as we go
import os.path
import subprocess
import sys
import urllib2
import file_utils as utils
import re
comment appends repo name to fail log file for later
function log_fail root_dir repo_name
begin
with open root_di... | #clone repos given in all_repos.json, extract commit log, and clean up unwanted (non-py) files as we go
import os.path
import subprocess
import sys
import urllib2
import file_utils as utils
import re
#appends repo name to fail log file for later
def log_fail(root_dir, repo_name):
with open(root_dir + "/github_files/... | Python | zaydzuhri_stack_edu_python |
function take_damage self damage
begin
set damage_after_defense = damage - call defend
set current_health = current_health - damage_after_defense
end function | def take_damage(self, damage):
damage_after_defense = damage - self.defend()
self.current_health -= damage_after_defense | Python | nomic_cornstack_python_v1 |
comment import tkinter as tk
from tkinter import ttk
comment root = tk.Tk()
comment root.title("Tab Widget")
comment tabControl = ttk.Notebook(root)
comment tab1 = ttk.Frame(tabControl)
comment tab2 = ttk.Frame(tabControl)
comment tabControl.add(tab1, text ='Tab 1')
comment tabControl.add(tab2, text ='Tab 2')
comment t... | # import tkinter as tk
from tkinter import ttk
# root = tk.Tk()
# root.title("Tab Widget")
# tabControl = ttk.Notebook(root)
# tab1 = ttk.Frame(tabControl)
# tab2 = ttk.Frame(tabControl)
# tabControl.add(tab1, text ='Tab 1')
# tabControl.add(tab2, text ='Tab 2')
# tabControl.pack(expand = 1, fill ="bo... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @Project : curve_fit
comment @Time : 2019-05-27 14:51
comment @Author : Samuel Chan
comment @Email : samuelchan1205@gmail.com
comment @File : continuous.py
import pickle
import numpy as np
from patsy import dmatrix
import statsmodels.api as sm
class Continuous
begin
function __init... | # -*- coding: utf-8 -*-
# @Project : curve_fit
# @Time : 2019-05-27 14:51
# @Author : Samuel Chan
# @Email : samuelchan1205@gmail.com
# @File : continuous.py
import pickle
import numpy as np
from patsy import dmatrix
import statsmodels.api as sm
class Continuous:
def __init__(self, k=3):
self.m... | Python | zaydzuhri_stack_edu_python |
import random
class Producto
begin
function __init__ self nombre precio
begin
set nombre = nombre
set precio = precio
set referencia = string REF + string random integer 1000 10000
set inventario = random integer 0 100
end function
end class | import random
class Producto:
def __init__(self, nombre, precio):
self.nombre = nombre
self.precio = precio
self.referencia = 'REF'+str(random.randint(1000, 10000))
self.inventario = random.randint(0, 100)
| Python | zaydzuhri_stack_edu_python |
comment copyright sebohacker computer entertaiment 2013
import random
set number1 = 2
print string Ahoooj
print string 1 + 1 = number1
print string
print string 10 nahodnych cisel od 1 do 100...
random integer 1 100 | #copyright sebohacker computer entertaiment 2013
import random
number1 = 2
print("Ahoooj\n")
print("1 + 1 =", number1)
print("\n")
print("\n10 nahodnych cisel od 1 do 100...")
random.randint(1,100)
| Python | zaydzuhri_stack_edu_python |
import sys
set times = 0
comment 初始化一个字母表
set alphabet = list string a string b string c string d string e string f string g string h string i string j string k string l string m string n string o string p string q string r string s string t string u string v string w string x string y string z
set alphabet_upper = lis... | import sys
times = 0
# 初始化一个字母表
alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z']
alphabet_upper = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: iso-8859-1 -*-
from time import sleep , time
from contextlib import contextmanager
class chrono
begin
function __enter__ self
begin
set debut = time
end function
end class | # !/usr/bin/env python
# -*- coding: iso-8859-1 -*-
from time import sleep, time
from contextlib import contextmanager
class chrono :
def __enter__(self):
self.debut = time()
| Python | zaydzuhri_stack_edu_python |
function delete_api self
begin
return call DeleteApiAsync self
end function | def delete_api(self) -> DeleteApiAsync:
return DeleteApiAsync(self) | Python | nomic_cornstack_python_v1 |
function list self path
begin
set req = get session url + path + string /list verify=false
set jdata = json req
if jdata at string status != string ok
begin
raise exception string Failed to query list: + text
end
return jdata at string data
end function | def list(self, path):
req = self.session.get(self.url + path + '/list',
verify=False)
jdata = req.json()
if jdata['status'] != 'ok':
raise Exception("Failed to query list: \n" + req.text)
return jdata['data'] | Python | nomic_cornstack_python_v1 |
comment Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
comment Each letter in the magazine string can only be used once in your ransom n... | #Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
#Each letter in the magazine string can only be used once in your ransom note.
#Example... | Python | zaydzuhri_stack_edu_python |
function supports_journal_branching self
begin
comment Perhaps someday I will support journaling!!!
return false
end function | def supports_journal_branching(self):
# Perhaps someday I will support journaling!!!
return False | Python | nomic_cornstack_python_v1 |
string Задание 22 (№677). Укажите минимальное натуральное число, при вводе которого этот алгоритм напечатает число, сумма цифр которого равна 15.
set x = integer input
set L = 0
set M = 1
while x > 0
begin
set L = x % 10 * M + L
set x = x // 10
set M = M * 10
end
comment Сумма цифр L будет 15
print L
set sum_of_L = 0
s... | """
Задание 22 (№677).
Укажите минимальное натуральное число,
при вводе которого этот алгоритм напечатает число, сумма цифр которого равна 15.
"""
x = int(input())
L = 0
M = 1
while x > 0:
L = x % 10 * M + L
x = x // 10
M = M * 10
print(L) # Сумма цифр L будет 15
sum_of_L = 0
answer_sum_of_L = 15
number ... | Python | zaydzuhri_stack_edu_python |
comment how the web works
comment type in url to browser, sends request to computers network interface (software/hardware responsible for data packages over network)
comment request in global network, eventually routed to remote computer, where another server receives request
comment once request data is received and a... | #how the web works
#type in url to browser, sends request to computers network interface (software/hardware responsible for data packages over network)
#request in global network, eventually routed to remote computer, where another server receives request
#once request data is received and accepted, gets digested by e... | Python | zaydzuhri_stack_edu_python |
function test_median
begin
set arr = zeros tuple 5 5
comment a 3x3 patch
set arr at tuple slice 1 : 2 : slice 1 : 4 : = 1
set arr at tuple slice 2 : 3 : slice 1 : 4 : = 2
set arr at tuple slice 3 : 4 : slice 1 : 4 : = 3
set parameters = dict string data list arr ; string size list 3 3
set result = median paramete... | def test_median():
arr = numpy.zeros((5, 5))
# a 3x3 patch
arr[1:2, 1:4] = 1
arr[2:3, 1:4] = 2
arr[3:4, 1:4] = 3
parameters = {'data': [arr], 'size': [3, 3]}
result = statistics.median(parameters)
assert_equal(result[2, 2], 2) | Python | nomic_cornstack_python_v1 |
function romanToInt s
begin
comment We have a string as the input
comment Our output is an integer
comment s is in the range of 1 and 3999
comment Input the values into a dictionary
comment loop through string and input values of s into an array
comment loop through array and check whether value of i is lower than the ... | def romanToInt(s):
# We have a string as the input
# Our output is an integer
# s is in the range of 1 and 3999
# Input the values into a dictionary
# loop through string and input values of s into an array
# loop through array and check whether value of i is lower than t... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import random
function rand
begin
comment something
set key = random sample range 256 256
set seeds = call _RC4PRGA call _RC4keySchedule key
return seeds at 0 ? 24 ? seeds at 1 ? 16 ? seeds at 2 ? 8 ? seeds at 3
end function
function randrange x y=none
begin
if y
begin
return call rand % y ... | #!/usr/bin/env python
import random
def rand():
key = random.sample(range(256), 256) # something
seeds = _RC4PRGA(_RC4keySchedule(key))
return (seeds[0]<<24)|(seeds[1]<<16)|(seeds[2]<<8)|seeds[3]
def randrange(x, y=None):
if y:
return (rand()%((y-x)+1))+x
else:
return rand()%(x+1)
def randsa... | Python | zaydzuhri_stack_edu_python |
comment An approximation of pi
comment Daniel Graham
comment This method should give an approximation of pi due to the ratio of circle to rectangle.
comment Since the area of the circle = pi and the area of the rectangle will = 4 by multiplying by 4,
comment the function returns an approximation of pi
import math
impor... | #
# An approximation of pi
#Daniel Graham
#This method should give an approximation of pi due to the ratio of circle to rectangle.
#Since the area of the circle = pi and the area of the rectangle will = 4 by multiplying by 4,
#the function returns an approximation of pi
import math
import random
from graphics... | Python | zaydzuhri_stack_edu_python |
function count_chars
begin
set chars = string
while chars == string
begin
set chars = input string What is the input string?
end
print string { chars } has { length chars } characters.
end function | def count_chars():
chars = ""
while chars == "":
chars = input("What is the input string? ")
print(f"{chars} has {len(chars)} characters.") | Python | nomic_cornstack_python_v1 |
function bzpull request target
begin
if starts with target string sha1:
begin
set target = target at slice 5 : :
end
set url = string http://bitzi.com/lookup/%s?v=tventtxt % target
set tventtxt = url open url
set tventdict = dict
set targets_to_update = set
set count = 0
set text = string
try
begin
for line in tven... | def bzpull(request, target):
if target.startswith("sha1:"):
target = target[5:]
url = "http://bitzi.com/lookup/%s?v=tventtxt" % target
tventtxt = urllib.urlopen(url)
tventdict = {}
targets_to_update = set()
count = 0
text = ""
try:
for line in tventtxt:
text +... | Python | nomic_cornstack_python_v1 |
comment Example 003: Tuples
comment Tuples are immutable objects
comment Print tuple documentation
print __doc__
print string
comment Create a tuple.
comment Tuples are like list but you can not change them
comment So, operations on tuples are way faster than lists
comment If you are sure that your values would not cha... | # Example 003: Tuples
# Tuples are immutable objects
# Print tuple documentation
print(tuple.__doc__)
print('\n\n\n')
# Create a tuple.
# Tuples are like list but you can not change them
# So, operations on tuples are way faster than lists
# If you are sure that your values would not change, then
# you should defini... | Python | zaydzuhri_stack_edu_python |
function reverse_list nums
begin
comment Using two pointers approach
set left = 0
set right = length nums - 1
comment Swap the elements from both ends until the pointers meet
while left < right
begin
comment Swap the elements
set tuple nums at left nums at right = tuple nums at right nums at left
comment Move the point... | def reverse_list(nums):
# Using two pointers approach
left = 0
right = len(nums) - 1
# Swap the elements from both ends until the pointers meet
while left < right:
# Swap the elements
nums[left], nums[right] = nums[right], nums[left]
# Move the pointers towards ... | Python | greatdarklord_python_dataset |
from dataclasses import dataclass
from typing import Tuple , cast , Iterator , TypeVar , Generic
from hw5.comparable import Comparable
set K = call TypeVar string K bound=Comparable
set V = call TypeVar string V bound=Comparable
set Entry = Tuple at tuple K V
class Node extends Generic at tuple K V
begin
string The bas... | from dataclasses import dataclass
from typing import Tuple, cast, Iterator, TypeVar, Generic
from hw5.comparable import Comparable
K = TypeVar("K", bound=Comparable)
V = TypeVar("V", bound=Comparable)
Entry = Tuple[K, V]
class Node(Generic[K, V]):
"""
The base class for all treap nodes. Should have only 2 ... | Python | zaydzuhri_stack_edu_python |
string The current code given is for the Assignment 2. > Classification > Regression
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from metrics import *
from ensemble.bagging import BaggingClassifier
from tree.base import DecisionTree
comment Or use sklearn decision tree
comment from linearRegr... | """
The current code given is for the Assignment 2.
> Classification
> Regression
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from metrics import *
from ensemble.bagging import BaggingClassifier
from tree.base import DecisionTree
# Or use sklearn decision tree
# from linearRegression.l... | Python | zaydzuhri_stack_edu_python |
comment Bad Way
class Employee
begin
pass
end class
set emp1 = call Employee
set emp2 = call Employee
set first = string Yuvansh
set last = string Bhardwaj
set email = string Yuvansh.Bhardwaj@gmail.com
set pay = 50000
set first = string Rahul
set last = string Sharma
set email = string Rahul.Sharma@gmail.com
set pay = ... | #Bad Way
class Employee:
pass
emp1 = Employee()
emp2 = Employee()
emp1.first = 'Yuvansh'
emp1.last = 'Bhardwaj'
emp1.email = 'Yuvansh.Bhardwaj@gmail.com'
emp1.pay = 50000
emp2.first = 'Rahul'
emp2.last = 'Sharma'
emp2.email = 'Rahul.Sharma@gmail.com'
emp2.pay = 40000
print(emp1.first)
print(emp1.last)
print(e... | Python | zaydzuhri_stack_edu_python |
function _getDataMessage self channel method properties body
begin
call basic_ack delivery_tag=delivery_tag
set messages_received = messages_received + 1
call callbackDataMessage body
end function | def _getDataMessage(self, channel, method, properties, body):
self.channel.basic_ack(delivery_tag=method.delivery_tag)
self.messages_received += 1
self.callbackDataMessage(body) | Python | nomic_cornstack_python_v1 |
function not_a_num val
begin
if call isnan val
begin
return false
end
else
begin
return true
end
end function | def not_a_num(val):
if math.isnan(val):
return False
else:
return True | Python | nomic_cornstack_python_v1 |
function get_encrypted_database
begin
if fernet is none
begin
raise call RuntimeError string encryption requested, but no cryptography available
end
with open database_name string rb as f
begin
set plain = read f
end
set key = call urlsafe_b64encode secret_key
set cipher = call encrypt plain
return call urlsafe_b64deco... | def get_encrypted_database():
if fernet is None:
raise RuntimeError('encryption requested, but no cryptography available')
with open(config.core.database_name, 'rb') as f:
plain = f.read()
key = base64.urlsafe_b64encode(config.utils.tasks.secret_key)
cipher = fernet.Fernet(key).encrypt(p... | Python | nomic_cornstack_python_v1 |
string Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ]
from collections import deque
class Solution
begin
function le... | """
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
"""
from collections import de... | Python | zaydzuhri_stack_edu_python |
function check_validity_of_chosen_players user username1 username2
begin
set co_player1 = first filter by query username=username1
set co_player2 = first filter by query username=username2
set error = none
if co_player1 == user or co_player2 == user
begin
set error = string Ne moreš igrati sam s seboj!
end
if co_player... | def check_validity_of_chosen_players(user: User, username1: str, username2: str):
co_player1 = User.query.filter_by(username=username1).first()
co_player2 = User.query.filter_by(username=username2).first()
error = None
if co_player1 == user or co_player2 == user:
error = 'Ne moreš igrati sam s ... | Python | nomic_cornstack_python_v1 |
function root_index request
begin
if call is_authenticated
begin
return call HttpResponseRedirect reverse string home_index
end
return call HttpResponseRedirect reverse string landing args=tuple
end function | def root_index(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse("home_index"))
return HttpResponseRedirect(reverse("landing", args=())) | Python | nomic_cornstack_python_v1 |
comment This script takes an image file as input and conducts an unsupervised k-means clustering.
comment Needs 2 arguments.
comment argument 1: input image file
comment argument 2: number of classes
comment Import sys.argv to enable command line arguments for setting parameters in the script
from sys import argv
comme... | # This script takes an image file as input and conducts an unsupervised k-means clustering.
# Needs 2 arguments.
# argument 1: input image file
# argument 2: number of classes
# Import sys.argv to enable command line arguments for setting parameters in the script
from sys import argv
# Import the otbApplicati... | Python | zaydzuhri_stack_edu_python |
function validate_otp self otp password=none
begin
set prefix = otp at slice : - 32 :
set otp_valid = call validate_otp otp
if settings at string use_ldap and settings at string ldap_yubikey_attr
begin
return otp_valid and call validate_yubikey self password prefix settings at string ldap_yubikey_attr
end
else
if pre... | def validate_otp(self, otp, password=None):
prefix = otp[:-32]
otp_valid = validate_otp(otp)
if settings['use_ldap'] and settings['ldap_yubikey_attr']:
return otp_valid and ldapauth.validate_yubikey(
self, password, prefix, settings['ldap_yubikey_attr'])
elif ... | Python | nomic_cornstack_python_v1 |
function _get_function_name self
begin
string Get function name of calling method :return: The name of the calling function (expected to be called in self.error/debug/..) :rtype: str | unicode
set fname = function
if fname == string <module>
begin
return string
end
else
begin
return fname
end
end function | def _get_function_name(self):
"""
Get function name of calling method
:return: The name of the calling function
(expected to be called in self.error/debug/..)
:rtype: str | unicode
"""
fname = inspect.getframeinfo(inspect.stack()[2][0]).function
if fn... | Python | jtatman_500k |
function f h
begin
set step = list
for i in range 0 h // 2 + 1
begin
set spaces = string * h // 2 - i
set stars = string * * 1 + i * 2
print spaces + stars
append step spaces + stars
end
pop step
for i in reversed step
begin
print i
end
end function
f dist 1
f dist 3
f dist 5
f dist 7
f dist 9 | def f(h):
step = []
for i in range(0, h//2+1):
spaces = ' '*(h//2-i)
stars = '*'*(1+(i*2))
print(spaces+stars)
step.append(spaces+stars)
step.pop()
for i in reversed(step):
print(i)
f(1)
f(3)
f(5)
f(7)
f(9)
| Python | zaydzuhri_stack_edu_python |
function is_folder_content_displayed_in_folder_content self folder_path folder_name
begin
return call is_folder_content_displayed_in_folder_content folder_path folder_name
end function | def is_folder_content_displayed_in_folder_content(self, folder_path, folder_name):
return self._folder_content.is_folder_content_displayed_in_folder_content(folder_path, folder_name) | Python | nomic_cornstack_python_v1 |
while proba != haslo and licznik != 0
begin
set proba = input string Zgadnij hasło
if proba != haslo
begin
set licznik = licznik - 1
end
end
comment licznik=0
comment while licznik<100:
comment print("JEDEN. hej")
comment while licznik>100:
comment print("DWA. hej")
comment while licznik!=10:
comment print("TRZY. hej")... | while proba!=haslo and licznik!=0:
proba=input("Zgadnij hasło\n")
if proba!=haslo:
licznik-=1
##licznik=0
####while licznik<100:
#### print("JEDEN. hej")
##
##while licznik>100:
## print("DWA. hej")
##
##while licznik!=10:
## print("TRZY. hej")
## licznik+=1
... | Python | zaydzuhri_stack_edu_python |
import torch
class Optimizer extends object
begin
string Optimization super-class Optimizers update parameter gradients after each forward+backward pass through gradient descent functions
function step self *args
begin
string Gradient-based parameter update
raise NotImplementedError
end function
end class
class SGD ext... | import torch
class Optimizer(object):
'''
Optimization super-class
Optimizers update parameter gradients after each forward+backward pass
through gradient descent functions
'''
def step(self, *args):
'''
Gradient-based parameter update
'''
raise NotImplementedE... | Python | zaydzuhri_stack_edu_python |
function is_valid_consonant isConsonants
begin
if length isConsonants > 1
begin
return false
end
else
begin
for tempCons in CONSONANTS
begin
if tempCons == lower isConsonants
begin
return true
end
end
for else
begin
return false
end
end
end function
function is_valid_vowel isVowels
begin
if length isVowels > 1
begin
re... | def is_valid_consonant(isConsonants):
if(len(isConsonants) > 1):
return False
else:
for tempCons in CONSONANTS:
if(tempCons == isConsonants.lower()):
return True
else:
return False
def is_valid_vowel(isVowels):
if(len(isVowels) > 1)... | Python | zaydzuhri_stack_edu_python |
function visit_call call_node stats rel_file_path
begin
set callable_as_attribute = has attribute func string attrname
if callable_as_attribute
begin
set callable_name = attrname
end
else
begin
if not has attribute func string name
begin
return call_node
end
set callable_name = name
end
comment Optimization: Start with... | def visit_call(call_node, stats, rel_file_path):
callable_as_attribute = hasattr(call_node.func, "attrname")
if callable_as_attribute:
callable_name = call_node.func.attrname
else:
if not hasattr(call_node.func, "name"):
return call_node
callab... | Python | nomic_cornstack_python_v1 |
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from sklearn.model_selection import train_test_split
import os , pickle , pandas as pd
comment Vectorizer Function
function vectorizer_by_tfidf dataset_train dataset_test
begin
set v = call TfidfVectorizer
set vectors_train = fit tr... | from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import metrics
from sklearn.model_selection import train_test_split
import os, pickle, pandas as pd
###
# Vectorizer Function
###
def vectorizer_by_tfidf(dataset_train, dataset_test):
v = TfidfVectorizer()
vectors_train = v.fit_transform... | Python | zaydzuhri_stack_edu_python |
from utilities import *
from niceSierpinskiUtilities import *
from numpy import *
import pygame
call init
set clock = call MyClock
set tuple width height = tuple 1200 600
set size = tuple width height
set screen = call set_mode tuple width height
call fill white
set screenMatrix = zeros tuple width height | from utilities import *
from niceSierpinskiUtilities import *
from numpy import *
import pygame
pygame.init()
clock = MyClock()
width, height = 1200, 600
size = (width, height)
screen = pygame.display.set_mode((width, height))
screen.fill(white)
screenMatrix = zeros((width, height)) | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_diabetes
import matplotlib.pyplot as plt
set d = call load_diabetes
set df = call DataFrame data=data columns=feature_names
set X = df at list s... | import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_diabetes
import matplotlib.pyplot as plt
d=load_diabetes()
df=pd.DataFrame(data=d.data,columns=d.feature_names)
X=df[['age']]
y=df['s... | Python | zaydzuhri_stack_edu_python |
function global_lppooling attrs inputs proto_obj
begin
string Performs global lp pooling on the input.
set p_value = get attrs string p 2
set new_attrs = call _add_extra_attributes attrs dict string global_pool true ; string kernel tuple 1 1 ; string pool_type string lp ; string p_value p_value
set new_attrs = call _re... | def global_lppooling(attrs, inputs, proto_obj):
"""Performs global lp pooling on the input."""
p_value = attrs.get('p', 2)
new_attrs = translation_utils._add_extra_attributes(attrs, {'global_pool': True,
'kernel': (1, 1),
... | Python | jtatman_500k |
function covenant_url self covenant_url
begin
set _covenant_url = covenant_url
end function | def covenant_url(self, covenant_url):
self._covenant_url = covenant_url | Python | nomic_cornstack_python_v1 |
set clr = call CyclicLR base_lr=0.001 max_lr=0.006 step_size=2000.0 mode=string triangular
fit model X_train Y_train callbacks=list clr
set clr_fn = lambda x -> 0.5 * 1 + sin x * pi / 2.0
set clr = call CyclicLR base_lr=0.001 max_lr=0.006 step_size=2000.0 scale_fn=clr_fn scale_mode=string cycle
fit model X_train Y_trai... | clr = CyclicLR(base_lr=0.001, max_lr=0.006,
step_size=2000., mode='triangular')
model.fit(X_train, Y_train, callbacks=[clr])
clr_fn = lambda x: 0.5*(1+np.sin(x*np.pi/2.))
clr = CyclicLR(base_lr=0.001, max_lr=0.006,
step_size=2000., scale_fn=clr_fn,
scale_mod... | Python | zaydzuhri_stack_edu_python |
import Combo.Combo as Combo
import Deck.Deck as Deck
import Field.Field as Field
import Common.Common as Common
import Deck.Card as Card
from Common.Common import bcolors
from itertools import combinations
import cPickle as pickle
class ComboTest
begin
function __init__ self name folder
begin
set combo = call Combo
loa... | import Combo.Combo as Combo
import Deck.Deck as Deck
import Field.Field as Field
import Common.Common as Common
import Deck.Card as Card
from Common.Common import bcolors
from itertools import combinations
import cPickle as pickle
class ComboTest:
def __init__(self, name, folder):
self.combo = Combo.Combo... | Python | zaydzuhri_stack_edu_python |
function edit self **data
begin
set modification_date = now
call applyData context keyword data
call flash call _ string Changes saved. type=string message
return call redirect call url context
end function | def edit(self, **data):
self.context.modification_date = datetime.datetime.now()
self.applyData(self.context, **data)
self.flash(_(u'Changes saved.'), type=u'message')
return self.redirect(self.url(self.context)) | Python | nomic_cornstack_python_v1 |
function parse_simpleflake flake
begin
set timestamp = SIMPLEFLAKE_EPOCH + call extract_bits flake SIMPLEFLAKE_TIMESTAMP_SHIFT SIMPLEFLAKE_TIMESTAMP_LENGTH / 1000.0
set random = call extract_bits flake SIMPLEFLAKE_RANDOM_SHIFT SIMPLEFLAKE_RANDOM_LENGTH
return call simpleflake_struct timestamp random
end function | def parse_simpleflake(flake):
timestamp = SIMPLEFLAKE_EPOCH\
+ extract_bits(flake,
SIMPLEFLAKE_TIMESTAMP_SHIFT,
SIMPLEFLAKE_TIMESTAMP_LENGTH) / 1000.0
random = extract_bits(flake,
SIMPLEFLAKE_RANDOM_SHIFT,
... | Python | nomic_cornstack_python_v1 |
function cancel control_address **kwargs
begin
try
begin
call send_ctrl_msg control_address string TERMINATE
end
except RpcError
begin
comment TERMINATE can fail if the the runtime dies before sending the return value
pass
end
end function | def cancel(
control_address: str,
**kwargs,
):
try:
Grpclet.send_ctrl_msg(control_address, 'TERMINATE')
except RpcError:
# TERMINATE can fail if the the runtime dies before sending the return value
pass | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Wed Nov 7 21:13:06 2018 @author: justinowen
import numpy
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
comment torch.manual_seed(1) # reproducible
comment x data (tensor), shape=(100, 1)
set x = unsqueeze torch ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 7 21:13:06 2018
@author: justinowen
"""
import numpy
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
# torch.manual_seed(1) # reproducible
x = torch.unsqueeze(torch.linspace(-1, 1, 300), dim=1) # x data (tensor), ... | Python | zaydzuhri_stack_edu_python |
function save_frame image directory frame_number
begin
if not exists path directory
begin
make directories directory
end
save directory + string / + string frame_number + string .png string PNG
end function | def save_frame(image, directory, frame_number):
if not os.path.exists(directory):
os.makedirs(directory)
image.save(directory + "/" + str(frame_number) + ".png", "PNG") | Python | nomic_cornstack_python_v1 |
function get self request device_id
begin
set device = call get_object_or_404 Device pk=device_id
set serializer = call DeviceReadingSerializer device
return call Response data
end function | def get(self, request, device_id):
device = get_object_or_404(Device, pk=device_id)
serializer = DeviceReadingSerializer(device)
return Response(serializer.data) | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.