code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string Copyright (C) 2019 Yi-Fan Shyu, Yueh-Feng Ku 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... | '''
Copyright (C) 2019 Yi-Fan Shyu, Yueh-Feng Ku
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, publ... | Python | zaydzuhri_stack_edu_python |
function BIT_b__ii_d_ self b ii d
begin
call assert_ii ii
call assert_d d
set nn = call RegisterPlusOffset ii d
call BIT_b_n b self at nn
end function | def BIT_b__ii_d_(self, b, ii, d):
assert_ii(ii)
assert_d(d)
nn = RegisterPlusOffset(ii, d)
self.BIT_b_n(b, self[nn]) | Python | nomic_cornstack_python_v1 |
function last_block self
begin
return chain at - 1
end function | def last_block(self):
return self.chain[-1] | Python | nomic_cornstack_python_v1 |
string # --------------------------------------------------------------------------- # File for performing MCS # --------------------------------------------------------------------------- # Created by: # Matthias Willer (matthias.willer@tum.de) # Engineering Risk Analysis Group # Technische Universitat Munchen # www.e... | """
# ---------------------------------------------------------------------------
# File for performing MCS
# ---------------------------------------------------------------------------
# Created by:
# Matthias Willer (matthias.willer@tum.de)
# Engineering Risk Analysis Group
# Technische Universitat Munchen
# www.era.... | Python | zaydzuhri_stack_edu_python |
comment _*_ coding:utf-8 _*_
function print_two *args
begin
set tuple arg1 arg2 = args
print string 실행인자1: %r, 실행인자2: %r % tuple arg1 arg2
end function
function print_two_again arg1 arg2
begin
print string 실행인자1: %r, 실행인자2: %r % tuple arg1 arg2
end function
function print_one arg1
begin
print string 실행인자1:%r % arg1
end... | # _*_ coding:utf-8 _*_
def print_two(*args):
arg1, arg2 = args
print("실행인자1: %r, 실행인자2: %r"%(arg1, arg2))
def print_two_again(arg1, arg2):
print("실행인자1: %r, 실행인자2: %r" % (arg1, arg2))
def print_one(arg1):
print("실행인자1:%r"%arg1)
def print_none():
print("아무것도 받지 않음")
print_two("Zed","Shaw")
print... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
set __appname__ = string [functions_cleaned.py]
set __author__ = string Pablo Lechon (plechon@ucm.es)
set __version__ = string 0.0.1
comment IMPORTS ##
import sys
import numpy as np
from model import equations
from scipy.integrate import solve_ivp
comment CONSTANTS ##
comment FUNCTIONS ##
... | #!/usr/bin/env python3
__appname__ = '[functions_cleaned.py]'
__author__ = 'Pablo Lechon (plechon@ucm.es)'
__version__ = '0.0.1'
## IMPORTS ##
import sys
import numpy as np
from model import equations
from scipy.integrate import solve_ivp
## CONSTANTS ##
## FUNCTIONS ##
def joint_system(c_1, D_1, N_1, l1, x1, c_... | Python | zaydzuhri_stack_edu_python |
function delete_message self msg_id claim_id=none
begin
string Deletes the message whose ID matches the supplied msg_id from the specified queue. If the message has been claimed, the ID of that claim must be passed as the 'claim_id' parameter.
return delete msg_id claim_id=claim_id
end function | def delete_message(self, msg_id, claim_id=None):
"""
Deletes the message whose ID matches the supplied msg_id from the
specified queue. If the message has been claimed, the ID of that claim
must be passed as the 'claim_id' parameter.
"""
return self._message_manager.delet... | Python | jtatman_500k |
from Flask import Flask , render_template , request
set app = call Flask __name__
decorator call route string /
function hello_world
begin
set usergreet = get args string greet
set username = get args string name
if usergreet is none or usergreet == string
begin
set usergreet = string Hello
end
if username is none or ... | from Flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def hello_world():
usergreet = request.args.get('greet')
username = request.args.get('name')
if usergreet is None or usergreet == "":
usergreet = "Hello"
if username is None or username == "":
usern... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from scipy import stats
from scipy.spatial import distance
from tqdm import tqdm
from model import Model
from inout import *
class DBScan extends Model
begin
function __init__ self distance=0.12 min_neighbors=2
begin
set distance = distance
set min_neighbors = min_neighbors
set summed_dist = list
en... | import numpy as np
from scipy import stats
from scipy.spatial import distance
from tqdm import tqdm
from model import Model
from inout import *
class DBScan(Model):
def __init__(self, distance=0.12, min_neighbors=2):
self.distance = distance
self.min_neighbors = min_neighbors
... | Python | zaydzuhri_stack_edu_python |
function account_id
begin
return call get_caller_identity at string Account
end function | def account_id():
return client.get_caller_identity()['Account'] | Python | nomic_cornstack_python_v1 |
function rotate axis angle
begin
if axis not in list range 1 4
begin
raise call ValueError string Axis must be in range 1 to 3
end
set r = zeros tuple 3 3
comment Allow for zero offset numbering
set ax0 = axis - 1
set theta = call deg2rad angle
set r at tuple ax0 ax0 = 1.0
set ax1 = ax0 + 1 % 3
set ax2 = ax0 + 2 % 3
se... | def rotate(axis, angle):
if axis not in list(range(1, 4)):
raise ValueError('Axis must be in range 1 to 3')
r = np.zeros((3, 3))
ax0 = axis-1 #Allow for zero offset numbering
theta = np.deg2rad(angle)
r[ax0, ax0] = 1.0
ax1 = (ax0+1) % 3
ax2 = (ax0+2) % 3
r[ax1, ax1] = np.cos(the... | Python | nomic_cornstack_python_v1 |
function ask_message message caption
begin
set msg = call MessageDialog none message=message caption=caption style=YES_NO ? NO_DEFAULT
if call ShowModal == ID_YES
begin
return true
end
else
begin
return false
end
end function | def ask_message(message, caption):
msg = wx.MessageDialog(None, message=message, caption=caption,
style=wx.YES_NO | wx.NO_DEFAULT)
if msg.ShowModal() == wx.ID_YES:
return True
else:
return False | Python | nomic_cornstack_python_v1 |
class bytes extends object
begin
string Bytes object.
function __init__ self source=string encoding=string utf8 errors=string strict
begin
string Construct an immutable array of bytes. :type source: object :type encoding: str :type errors: str
pass
end function
function __add__ self y
begin
string The concatenation of... | class bytes(object):
"""Bytes object."""
def __init__(self, source='', encoding='utf8', errors='strict'):
"""Construct an immutable array of bytes.
:type source: object
:type encoding: str
:type errors: str
"""
pass
def __add__(self, y):
... | Python | zaydzuhri_stack_edu_python |
function is_multiple self
begin
return _mode == MULTIPLE
end function | def is_multiple(self):
return self._mode == self.Mode.MULTIPLE | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment Exercise 33. While Loops
comment Study Drill 1/2
function number_loop max incr=1
begin
string use a while loop up to number max, use incr to set the increment
set i = 0
set numbers = list
while i < max
begin
print string At the top i is { i }
append numbers i
set i = i + incr
prin... | #!/usr/bin/env python3
# Exercise 33. While Loops
# Study Drill 1/2
def number_loop(max, incr = 1):
"""
use a while loop up to number max, use incr to set the increment
"""
i = 0
numbers = []
while i < max:
print(f"At the top i is {i}")
numbers.append(i)
i = i + in... | Python | zaydzuhri_stack_edu_python |
async function set_chat_permissions self chat_id permissions request_id=none request_timeout=none skip_validation=false
begin
set _constructor = if expression skip_validation then construct else SetChatPermissions
return await call request call _constructor chat_id=chat_id permissions=permissions request_id=request_id ... | async def set_chat_permissions(
self,
chat_id: int,
permissions: ChatPermissions,
*,
request_id: str = None,
request_timeout: int = None,
skip_validation: bool = False
) -> Ok:
_constructor = SetChatPermissions.construct if ... | Python | nomic_cornstack_python_v1 |
from datetime import datetime , date , timedelta
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db_setup import Base , Association , Bus , Paradas
import random
import string
import time
import os
from colorama import *
call init
set engine = call create_engine string sqlite:///busCon... | from datetime import datetime, date, timedelta
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db_setup import Base, Association, Bus, Paradas
import random
import string
import time
import os
from colorama import *
init()
engine = create_engine('sqlite:///busControlApp.db?check_s... | Python | zaydzuhri_stack_edu_python |
print string Hello World
set x = string Raymond
print string Hello x
set y = string Raymond
print string Hello + y
set z = 4
print string Hello z
set i = 4
print string Hello + string i
set txt = format string I love to eat {food1} and {food2}. food1=string sushi food2=string fried chicken
print txt
set food3 = string ... | print("Hello World")
x = "Raymond"
print("Hello", x)
y = "Raymond"
print("Hello " + y)
z = 4
print("Hello", z)
i = 4
print("Hello " + str(i))
txt = "I love to eat {food1} and {food2}.".format(food1="sushi", food2="fried chicken")
print(txt)
food3 = "sushi"
food4 = "fried chicken"
print(f"I love to eat {food3} and... | Python | zaydzuhri_stack_edu_python |
function update_counts self new_alpha new_beta decay
begin
set _alpha = _alpha / decay + new_alpha
set _beta = _beta / decay + new_beta
set _n_updates = _n_updates + 1
end function | def update_counts(self, new_alpha, new_beta, decay):
self._alpha = self._alpha / decay + new_alpha
self._beta = self._beta / decay + new_beta
self._n_updates += 1 | Python | nomic_cornstack_python_v1 |
comment lengh=len(data)
comment print(lenght)
print length data
print max data
print min data
comment iterete in list
for i in range length data
begin
print data at i
end
comment Enhanced for loop/For-Each loop
for elm in data
begin
print elm
end
print string --------------
print list comprehension x ^ 2 for x in data
... | #lengh=len(data)
#print(lenght)
print(len(data))
print(max(data))
print(min(data))
#iterete in list
for i in range(len(data)):
print(data[i])
#Enhanced for loop/For-Each loop
for elm in data:
print(elm)
print("--------------")
print([x**2 for x in data])
print("--------------------")
numbers=list(range(1,101,... | Python | zaydzuhri_stack_edu_python |
comment 7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below.
comment when you are testing below enter words.txt as the file name.
set file = input string Enter the file nam... | # 7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below.
# when you are testing below enter words.txt as the file name.
file = input('Enter the file name: ')
fhandle =... | Python | zaydzuhri_stack_edu_python |
function join_forest self choose=none
begin
import Graphs
set result = call maximum_cardinality_search choose true
if result
begin
set receiver = result at 1
set join_forest = call UForest copy _hyperedges
for tuple sender recipient in items receiver
begin
call put_line sender recipient
end
end
else
begin
raise call De... | def join_forest(self,choose=None):
import Graphs
result = self.maximum_cardinality_search(choose,True)
if result:
receiver = result[1]
join_forest = Graphs.UForest(self._hyperedges.copy())
for sender, recipient in receiver.items():
join_forest... | Python | nomic_cornstack_python_v1 |
function change_image self product_id image_id add_namespace=false **kwargs
begin
call check_deprecated_kwargs kwargs dict string bpp string bits_per_pixel
if add_namespace
begin
call check_deprecated_kwargs locals dict string add_namespace none
set product_id = call namespace_product product_id
end
set r = patch forma... | def change_image(self, product_id, image_id, add_namespace=False, **kwargs):
check_deprecated_kwargs(kwargs, {"bpp": "bits_per_pixel"})
if add_namespace:
check_deprecated_kwargs(locals(), {"add_namespace": None})
product_id = self.namespace_product(product_id)
r = self.se... | Python | nomic_cornstack_python_v1 |
function cum_returns returns starting_value=0 out=none
begin
string Compute cumulative returns from simple returns. Parameters ---------- returns : pd.Series, np.ndarray, or pd.DataFrame Returns of the strategy as a percentage, noncumulative. - Time series with decimal returns. - Example:: 2015-07-16 -0.012143 2015-07-... | def cum_returns(returns, starting_value=0, out=None):
"""
Compute cumulative returns from simple returns.
Parameters
----------
returns : pd.Series, np.ndarray, or pd.DataFrame
Returns of the strategy as a percentage, noncumulative.
- Time series with decimal returns.
- Ex... | Python | jtatman_500k |
string Input: arr1[] = {11, 1, 13, 21, 3, 7}, arr2[] = {11, 3, 7, 1} Output: arr2[] is a subset of arr1[]
function isSubSet arr1 arr2
begin
set hashset = dict
for num in arr1
begin
if num in hashset
begin
set hashset at num = hashset at num + 1
end
else
begin
set hashset at num = 1
end
end
for num in arr2
begin
if num... | """
Input: arr1[] = {11, 1, 13, 21, 3, 7}, arr2[] = {11, 3, 7, 1}
Output: arr2[] is a subset of arr1[]
"""
def isSubSet(arr1, arr2):
hashset = {}
for num in arr1:
if num in hashset:
hashset[num] += 1
else:
hashset[num] = 1
for num in arr2:
if num in hashset:
continue
else:
... | Python | zaydzuhri_stack_edu_python |
function __len__ self
begin
return length xdata
end function | def __len__(self):
return len(self.xdata) | Python | nomic_cornstack_python_v1 |
function addVertex self x
begin
set _dict at x = list
end function | def addVertex(self,x):
self._dict[x] = [] | Python | nomic_cornstack_python_v1 |
import os
class DeviceFinder
begin
string Collects info about connected devices
function __init__ self
begin
pass
end function
function get_usb_table self
begin
string Return list of connected devices Each line contains: <field> -- <example> device name -- /dev/sdX device label -- MyAwesomeDrive device mount point -- /... | import os
class DeviceFinder:
"""Collects info about connected devices"""
def __init__(self):
pass
def get_usb_table(self):
"""Return list of connected devices
Each line contains:
<field> -- <example>
device name -- /dev/sdX
device label -- MyAwesomeDrive... | Python | zaydzuhri_stack_edu_python |
function _determine_item_type definition
begin
set data_type = definition at string DATA_TYPE_NAME
set ARRAY_ITEM = false
set PACKED_ITEM = false
if definition at string ARRAY_NAME
begin
set ARRAY_ITEM = true
end
else
if string BitUInt in data_type
begin
set PACKED_ITEM = true
end
return tuple ARRAY_ITEM PACKED_ITEM
en... | def _determine_item_type(definition):
data_type = definition['DATA_TYPE_NAME']
ARRAY_ITEM = False
PACKED_ITEM = False
if definition['ARRAY_NAME']:
ARRAY_ITEM = True
elif 'BitUInt' in data_type:
PACKED_ITEM = True
return ARRAY_ITEM, PACKED_ITEM | Python | nomic_cornstack_python_v1 |
function test_01_list_aff_grps_for_vm self
begin
call create_aff_grp aff_grp=services at string host_anti_affinity acc=name domainid=id
set list_aff_grps = list api_client
set tuple vm hostid = call create_vm_in_aff_grps list name account_name=name domain_id=id
set list_aff_grps = list api_client virtualmachineid=id
as... | def test_01_list_aff_grps_for_vm(self):
self.create_aff_grp(aff_grp=self.services["host_anti_affinity"], acc=self.account.name, domainid=self.domain.id)
list_aff_grps = AffinityGroup.list(self.api_client)
vm, hostid = self.create_vm_in_aff_grps([self.aff_grp[0].name], account_name=self.account... | Python | nomic_cornstack_python_v1 |
import os
import argparse
import json
comment remove folders
import shutil
comment Parsing arguments
set parser = call ArgumentParser add_help=true
call add_argument string -u help=string username
call add_argument string -p help=string password
set args = call parse_args
if not u or not p
begin
exit 0
end
comment Chan... | import os
import argparse
import json
import shutil # remove folders
# Parsing arguments
parser = argparse.ArgumentParser(add_help=True)
parser.add_argument('-u', help="username")
parser.add_argument('-p', help="password")
args = parser.parse_args()
if not args.u or not args.p:
exit(0)
# Chanding directory to ... | Python | zaydzuhri_stack_edu_python |
comment !/opt/python27/bin/python
import argparse
import os , sys
class Field
begin
function __init__ self
begin
set len = 0
set n_vocab = 0
set terms = list
end function
decorator staticmethod
function to_string field
begin
set s = string n_vocab
set s = s + string + string len
set s = s + string + join string ter... | #!/opt/python27/bin/python
import argparse
import os, sys
class Field:
def __init__(self):
self.len = 0
self.n_vocab = 0
self.terms = []
@staticmethod
def to_string(field):
s = str(field.n_vocab)
s += ' ' + str(field.len)
s += ' ' + ' '.join(field.terms)
... | Python | zaydzuhri_stack_edu_python |
function find_multitype_systems system_desc_dir=string systems
begin
set all_system_jsons = glob glob join path system_desc_dir string *.json
set multitype_systems = list
for sys_json in all_system_jsons
begin
set sys_id = base name path sys_json at slice : - length string .json :
set sys_type = call get_system_type... | def find_multitype_systems(system_desc_dir="systems"):
all_system_jsons = glob.glob(os.path.join(system_desc_dir, "*.json"))
multitype_systems = []
for sys_json in all_system_jsons:
sys_id = os.path.basename(sys_json)[:-len(".json")]
sys_type = get_system_type(sys_id)
if sys_type == ... | Python | nomic_cornstack_python_v1 |
function addBoldTag s words
begin
set n = length s
set marked = list false * n
for word in words
begin
set pos = find s word
while pos != - 1
begin
for i in range pos pos + length word
begin
set marked at i = true
end
set pos = find s word pos + 1
end
end
set result = list
set i = 0
while i < n
begin
if marked at i
be... | def addBoldTag(s: str, words: list) -> str:
n = len(s)
marked = [False] * n
for word in words:
pos = s.find(word)
while pos != -1:
for i in range(pos, pos + len(word)):
marked[i] = True
pos = s.find(word, pos + 1)
result = []
i = 0
while i ... | Python | jtatman_500k |
import sys
set stdin = open string 4828.txt
for tc in range 1 integer input + 1
begin
set arr = list
set N = integer input
set arr = list map int split input
sort arr
set result = arr at - 1 - arr at 0
print format string #{} {} tc result
end | import sys
sys.stdin = open("4828.txt")
for tc in range(1, int(input())+1):
arr = []
N = int(input())
arr = list(map(int, input().split()))
arr.sort()
result = arr[-1] - arr[0]
print('#{} {}'.format(tc, result)) | Python | zaydzuhri_stack_edu_python |
function __eq__ self obj
begin
if not is instance obj Matrix
begin
return false
end
if not m == m and n == n
begin
return false
end
if not type self == type obj
begin
return false
end
for i in range m
begin
for j in range n
begin
if self at tuple i j != obj at tuple i j
begin
return false
end
end
end
return true
end fu... | def __eq__(self, obj):
if not isinstance(obj, Matrix):
return False
if not (self.m == obj.m and self.n == obj.n):
return False
if not type(self) == type(obj):
return False
for i in range(self.m):
for j in range(self.n):
if s... | Python | nomic_cornstack_python_v1 |
function grade m f r
begin
if m == - 1 or f == - 1
begin
return string F
end
if m + f >= 80
begin
return string A
end
if m + f >= 65
begin
return string B
end
if m + f >= 50
begin
return string C
end
if m + f >= 30
begin
if r >= 50
begin
return string C
end
else
begin
return string D
end
end
return string F
end functio... | def grade(m, f, r):
if m == -1 or f == -1:
return 'F'
if m + f >= 80:
return 'A'
if m + f >= 65:
return 'B'
if m + f >= 50:
return 'C'
if m + f >= 30:
if r >= 50:
return 'C'
else:
return 'D'
return 'F'
while True:
m, f,... | Python | zaydzuhri_stack_edu_python |
function test_case_for_key_generation key_type bits dependencies *args result=string
begin
call hack_dependencies_not_implemented dependencies
set tc = test case
set short_key_type = call short_expression key_type
call set_description format string PSA {} {}-bit short_key_type bits
call set_dependencies dependencies
ca... | def test_case_for_key_generation(
key_type: str, bits: int,
dependencies: List[str],
*args: str,
result: str = ''
) -> test_case.TestCase:
hack_dependencies_not_implemented(dependencies)
tc = test_case.TestCase()
short_key_type = crypto_knowledge.short_expression(key_type)
... | Python | nomic_cornstack_python_v1 |
from Product import Product
from Wear import Wear
from Appliance import Appliance
function main
begin
set products = list product string 101 string 消しゴム 50 call Wear string 402 string Yシャツ 6000 string L call Appliance string 901 string 冷蔵庫(2ドア) 32000 200
for product in products
begin
print string ----------------
call ... | from Product import Product
from Wear import Wear
from Appliance import Appliance
def main():
products = [Product('101', '消しゴム', 50),
Wear('402', 'Yシャツ', 6000, 'L'),
Appliance('901', '冷蔵庫(2ドア)', 32000, 200)]
for product in products:
print('----------------')
pro... | Python | zaydzuhri_stack_edu_python |
function set_nombre self value
begin
set __nombre = value
end function | def set_nombre(self, value):
self.__nombre = value | Python | nomic_cornstack_python_v1 |
function triangular_gmap_split_edge gmap dart
begin
comment Compute the position of the edge center
comment Split the edge and get the new vertex dart
comment Update the position of the new vertex to the edge center
comment Split the face(s) incident to the new vertex
set d0 = dart
set d1 = call alpha_composed list 0 d... | def triangular_gmap_split_edge(gmap, dart):
# Compute the position of the edge center
# Split the edge and get the new vertex dart
# Update the position of the new vertex to the edge center
# Split the face(s) incident to the new vertex
d0 = dart
d1 = gmap.alpha_composed([0],dart)
d2 ... | Python | nomic_cornstack_python_v1 |
import sys
import json
import stim_bundle
from abcd_text import *
from psychopy import visual , core , monitors , iohub
comment TODO: Verify this converstion by comparing images
comment TODO: Verify that aliasing matches original E-Prime stimulus
function points_to_pixels points
begin
set pixels_per_inch = 96.0
set poi... | import sys
import json
import stim_bundle
from abcd_text import *
from psychopy import visual, core, monitors, iohub
# TODO: Verify this converstion by comparing images
# TODO: Verify that aliasing matches original E-Prime stimulus
def points_to_pixels(points):
pixels_per_inch = 96.0
points_per_inch = 72.0
... | Python | zaydzuhri_stack_edu_python |
import os
import torch as tr
import torch.nn as nn
import numpy as np
import sklearn.metrics as metricas
comment librosa ->
from torch.utils.data import Dataset , DataLoader , random_split
from scipy.io import wavfile as wv
import torchvision.models as models
import torchvision.transforms as transforms
class FeaturesDa... | import os
import torch as tr
import torch.nn as nn
import numpy as np
import sklearn.metrics as metricas
#librosa ->
from torch.utils.data import Dataset, DataLoader, random_split
from scipy.io import wavfile as wv
import torchvision.models as models
import torchvision.transforms as transforms
class FeaturesDatase... | Python | zaydzuhri_stack_edu_python |
function test_float_int self
begin
assert equal call max_integer list - 5 4.5 4 9.66 9.66
end function | def test_float_int(self):
self.assertEqual(max_integer([-5, 4.5, 4, 9.66]), 9.66) | Python | nomic_cornstack_python_v1 |
function leaky_relu x negative_slope=0.01
begin
return where x >= 0 x negative_slope * x
end function | def leaky_relu(x, negative_slope=1e-2):
return T.where(x >= 0, x, negative_slope * x) | Python | nomic_cornstack_python_v1 |
if age >= 18
begin
print string your age is age
print string adult
end
else
begin
print string your age is age
print string teenager
end
if age >= 18
begin
print string adult
end
else
comment elif is else if abbreviation
if age >= 6
begin
print string teenager
end
else
begin
print string kid
end
set height = input stri... | if age >= 18:
print('your age is',age)
print('adult')
else:
print('your age is',age)
print('teenager')
if age >= 18:
print('adult')
elif age >= 6: #elif is else if abbreviation
print('teenager')
else:
print('kid')
height = input("Please input your height:")
if int(height) >= 180:
print('tall,high')
... | Python | zaydzuhri_stack_edu_python |
function test_cal self DATA_FILE
begin
set result = 0
if line_rest_frequency != line_rest_frequency
begin
print string Warning: Line Rest Frequency of Cal observation does not match map
set result = result + 1
end
if nchan != nchan
begin
print string Warning: number of channels for Cal observation does not match map
se... | def test_cal(self, DATA_FILE):
result = 0
if DATA_FILE.line_rest_frequency != self.line_rest_frequency:
print('Warning: Line Rest Frequency of Cal observation does not \
match map')
result = result + 1
if DATA_FILE.nchan != self.nchan:
print... | Python | nomic_cornstack_python_v1 |
function _test_graphzip_subgen self fin_graphzip fin_insts n=none
begin
print string Running compression on %s... % fin_graphzip
set start = performance counter
comment run compression to get pattern dictionary
call compress_file fin_graphzip
set elapsed = performance counter - start
print string Compression took:
prin... | def _test_graphzip_subgen(self, fin_graphzip, fin_insts, n=None):
print('Running compression on %s...' % fin_graphzip)
start = time.perf_counter()
# run compression to get pattern dictionary
self.c.compress_file(fin_graphzip)
elapsed = time.perf_counter()-start
print('Com... | Python | nomic_cornstack_python_v1 |
function findTryExec self
begin
set tryexec = get self string TryExec strict=true
return which tryexec
end function | def findTryExec(self):
tryexec = self.get('TryExec', strict=True)
return which(tryexec) | Python | nomic_cornstack_python_v1 |
import MySQLdb
from nltk.tokenize import sent_tokenize
import sys
from main.writeFile import write_file
call reload sys
call setdefaultencoding string utf8
function calling_table data
begin
if data == string facebook
begin
set sql = string select post from facebook_2015_Entity where (CRF like '%1%') or (CRF like '%3%')... | import MySQLdb
from nltk.tokenize import sent_tokenize
import sys
from main.writeFile import write_file
reload(sys)
sys.setdefaultencoding('utf8')
def calling_table(data):
if data == 'facebook':
sql = "select post from facebook_2015_Entity where (CRF like '%1%') or (CRF like '%3%') or (CRF like '%2%') o... | Python | zaydzuhri_stack_edu_python |
comment Python sys System-specific parameters and functions.
comment This module provides access to some variables used or maintained by the interpreter and to functions that interact
comment strongly with the interpreter.
comment contextlib Utilities for with-statement contexts.
comment This module provides utilities ... | # Python sys System-specific parameters and functions.
# This module provides access to some variables used or maintained by the interpreter and to functions that interact
# strongly with the interpreter.
# contextlib Utilities for with-statement contexts.
# This module provides utilities for common tasks involving t... | Python | zaydzuhri_stack_edu_python |
async function test_thermostat_dry_and_fan_both_hvac_mode_and_preset hass client climate_airzone_aidoo_control_hvac_unit integration
begin
set state = get states CLIMATE_AIDOO_HVAC_UNIT_ENTITY
assert state
assert attributes at ATTR_HVAC_MODES == list OFF HEAT COOL FAN_ONLY DRY HEAT_COOL
assert attributes at ATTR_PRESET... | async def test_thermostat_dry_and_fan_both_hvac_mode_and_preset(
hass: HomeAssistant,
client,
climate_airzone_aidoo_control_hvac_unit,
integration,
) -> None:
state = hass.states.get(CLIMATE_AIDOO_HVAC_UNIT_ENTITY)
assert state
assert state.attributes[ATTR_HVAC_MODES] == [
HVACMode.O... | Python | nomic_cornstack_python_v1 |
function clTbt_sp val
begin
return list comprehension integer bt for bt in call pack string >f val
end function | def clTbt_sp(val: Union[int, float]) -> list:
return [int(bt) for bt in struct.pack(">f", val)] | Python | nomic_cornstack_python_v1 |
function to_dict self
begin
string Save this message sending object into a dictionary.
set targets = list
for cond in _targets
begin
append targets call to_dict
end
if targets
begin
return dict string targets targets
end
else
begin
return dict
end
end function | def to_dict(self):
'''Save this message sending object into a dictionary.'''
targets = []
for cond in self._targets:
targets.append(cond.to_dict())
if targets:
return {'targets': targets}
else:
return {} | Python | jtatman_500k |
for i in range num1 num2 + 1 1
begin
if i != 0
begin
if i == 2
begin
comment το 2 ειναι πρώτος
append primes i
end
else
begin
set x = string true
comment ψαχνω για διαιρέτη μεχρι την ριζα του αριθμού
set n = integer absolute i ^ 1 / 2
for j in range 2 n + 1 1
begin
comment ο αριθμος έχει διαιρέτη
if absolute i % j == 0... | for i in range(num1,num2+1,1):
if i!=0:
if i==2:
primes.append(i) #το 2 ειναι πρώτος
else:
x="true"
n=int(abs(i)**(1/2)) #ψαχνω για διαιρέτη μεχρι την ριζα του αριθμού
for j in range(2,n+1,1):
if abs(i)%j==0: #ο αριθμος έχει διαιρέτη
x="false"
... | Python | zaydzuhri_stack_edu_python |
comment Two Dice Simulation
from random import randrange
set rolls = 1000
function two_dice
begin
set d1 = call randrange 1 7
set d2 = call randrange 1 7
return d1 + d2
end function
function main
begin
set expected = dict 2 1 / 36 ; 3 2 / 36 ; 4 3 / 36 ; 5 4 / 36 ; 6 5 / 36 ; 7 6 / 36 ; 8 5 / 36 ; 9 4 / 36 ; 10 3 / 36 ... | # Two Dice Simulation
from random import randrange
rolls = 1000
def two_dice():
d1 = randrange(1, 7)
d2 = randrange(1, 7)
return d1 + d2
def main():
expected = {2: 1 / 36, 3: 2 / 36, 4: 3 / 36, 5: 4 / 36, 6: 5 / 36, 7: 6 / 36,
8: 5 / 36, 9: 4 / 36, 10: 3 / 36, 11: 2 / 36, 12: 1 / 36... | Python | zaydzuhri_stack_edu_python |
function change_station self new_station_index
begin
if not suspended
begin
set was_playing = playing
if was_playing
begin
call stop
end
set current_station_index = new_station_index % length STATIONS
if was_playing
begin
call play
end
end
else
begin
call set_cursor 0 2
call tick_message string Cannot operate whist sus... | def change_station(self, new_station_index):
if not self.suspended:
was_playing = self.playing
if was_playing:
self.stop()
self.current_station_index = new_station_index % len(STATIONS)
if was_playing:
self.play()
else:
... | Python | nomic_cornstack_python_v1 |
function get_record_for_doi label_file doi
begin
with open label_file string r as infile
begin
set records = load json infile
end
if string data in records
begin
comment Strip off the stuff we don't care about
set records = records at string data
end
comment May have been handed a single record, if so wrap in a list so... | def get_record_for_doi(label_file, doi):
with open(label_file, "r") as infile:
records = json.load(infile)
if "data" in records:
# Strip off the stuff we don't care about
records = records["data"]
# May have been handed a single record, if so wrap in a list ... | Python | nomic_cornstack_python_v1 |
comment Astro Ohnuma
comment 10/18/17
comment printsquares.py - printing squares with a function
function printsquares num1 num2
begin
for i in range num1
begin
print string +-- * num2 + string +
print string | * num2 + string |
end
print string +-- * num2 + string +
end function
call printsquares 2 4 | #Astro Ohnuma
#10/18/17
#printsquares.py - printing squares with a function
def printsquares(num1,num2):
for i in range(num1):
print(('+--'*num2)+('+'))
print(('| '*num2)+('|'))
print(('+--'*num2)+('+'))
printsquares(2,4) | Python | zaydzuhri_stack_edu_python |
comment 13.3Python库之文本处理.py
import PyPDF2
import nltk
import docx
comment PyPDF2库:
comment 用来处理pdf文件的工具集
comment 提供了一批处理PDF文件的计算功能
comment 支持获取信息、分隔/整合文件、加密解密等
comment 完全Python语言实现,不需要额外依赖,功能稳定
comment http://mstamy2.github.io/PyPDF2
comment nltk库:
comment 自然语言文本处理第三方库
comment 提供了一批简单易用的自然语言文本处理功能
comment 支持语言文本分类、标记、语... | # 13.3Python库之文本处理.py
import PyPDF2
import nltk
import docx
# PyPDF2库:
# 用来处理pdf文件的工具集
# 提供了一批处理PDF文件的计算功能
# 支持获取信息、分隔/整合文件、加密解密等
# 完全Python语言实现,不需要额外依赖,功能稳定
# http://mstamy2.github.io/PyPDF2
# nltk库:
# 自然语言文本处理第三方库
# 提供了一批简单易用的自然语言文本处理功能
# 支持语言文本分类、标记、语法句法、语义分析等
# Python中最优秀的自然语言处理
# http://www.nl... | Python | zaydzuhri_stack_edu_python |
import RPi.GPIO as GPIO
import time
call setmode BOARD
comment GPIO PIN SETUP
set GPIO_SONAR_TRIGGER = 3
set GPIO_SONAR_ECHO = 5
set GPIO_SERVO_CONTROL = 15
set GPIO_WEIGHT_DT = 29
set GPIO_WEIGHT_SDK = 31
set GPIO_LED_SERVO = 37
set GPIO_LED_SONAR = 23
comment GPIO I/O SETUP
setup GPIO GPIO_SONAR_TRIGGER OUT
setup GPI... | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
# GPIO PIN SETUP
GPIO_SONAR_TRIGGER = 3
GPIO_SONAR_ECHO = 5
GPIO_SERVO_CONTROL = 15
GPIO_WEIGHT_DT = 29
GPIO_WEIGHT_SDK = 31
GPIO_LED_SERVO = 37
GPIO_LED_SONAR = 23
# GPIO I/O SETUP
GPIO.setup(GPIO_SONAR_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_SONAR_ECHO, GPIO.... | Python | zaydzuhri_stack_edu_python |
function _get_opener self
begin
if opener
begin
return opener
end
else
if _opener is none
begin
set handlers = list
set need_keepalive_handler = have_keepalive and keepalive
set need_range_handler = range_handlers and range or reget
comment if you specify a ProxyHandler when creating the opener
comment it _must_ come ... | def _get_opener(self):
if self.opts.opener:
return self.opts.opener
elif self._opener is None:
handlers = []
need_keepalive_handler = (have_keepalive and self.opts.keepalive)
need_range_handler = (range_handlers and \
... | Python | nomic_cornstack_python_v1 |
function callback_property getter
begin
set cb = call CallbackProperty getter=getter
set __doc__ = __doc__
return cb
end function | def callback_property(getter):
cb = CallbackProperty(getter=getter)
cb.__doc__ = getter.__doc__
return cb | Python | nomic_cornstack_python_v1 |
function find_biggest_difference range_string_1 range_string_2
begin
return if expression call _calculate_difference range_string_1 > call _calculate_difference range_string_2 then 0 else 1
end function | def find_biggest_difference(range_string_1: str, range_string_2: str):
return 0 if _calculate_difference(range_string_1) > _calculate_difference(range_string_2) else 1 | Python | nomic_cornstack_python_v1 |
function testBadRequestOne self
begin
set r = get requests base_url + string -1
assert equal status_code 404
end function | def testBadRequestOne(self):
r = requests.get(base_url + "-1")
self.assertEqual(r.status_code, 404) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import re
import sys
from game import Game
from collections import defaultdict
import urllib
function game_iterator handle parse_moves=true
begin
set tag_pattern = compile string \[(\S*) "(.*)"\]
set separate_moves_pattern = compile string (?P<number>\d+) (?P<dots>\.+) \ # There is a space here... | #!/usr/bin/python
import re
import sys
from game import Game
from collections import defaultdict
import urllib
def game_iterator(handle, parse_moves=True):
tag_pattern = re.compile(r'\[(\S*) "(.*)"\]')
separate_moves_pattern = re.compile(r"""
(?P<number>\d+)
... | Python | zaydzuhri_stack_edu_python |
function find_strings_with_char string_list char
begin
set output = list
for string in string_list
begin
if char in string
begin
append output string
end
end
return output
end function
set string_list = list string apple string banana string pear
set char = string a
set output = call find_strings_with_char string_list... | def find_strings_with_char(string_list, char):
output = []
for string in string_list:
if char in string:
output.append(string)
return output
string_list = ["apple", "banana", "pear"]
char = 'a'
output = find_strings_with_char(string_list, char)
print(output) # ["apple", "banana"] | Python | jtatman_500k |
function generate_thumb_filename instance filename
begin
return call _generate_filename instance filename string thumbs
end function | def generate_thumb_filename(instance, filename):
return _generate_filename(instance, filename, 'thumbs') | Python | nomic_cornstack_python_v1 |
function output_confusion_matrix X_test results_path test_results model **kwargs
begin
set tuple loss accu_test prob_list auglbl_list pred_list conf_list = test_results
comment Output confusion matrix
set mapping_fn = none
if model is not none
begin
set mapping_fn = get attribute model string label_order_mapping none
e... | def output_confusion_matrix(X_test, results_path, test_results, model,
**kwargs):
loss, accu_test, prob_list, auglbl_list, pred_list, conf_list = test_results
# Output confusion matrix
mapping_fn = None
if model is not None:
mapping_fn = getattr(model, 'label_order_ma... | Python | nomic_cornstack_python_v1 |
function test_multiplication_matrix self tol classes
begin
set tuple c1 c2 = classes
with call warns UserWarning match=string acts on overlapping wires
begin
set O = call c1 0 @ call c2 0
end
set res = call matrix
set expected = call compute_matrix @ call compute_matrix
assert call allclose res expected atol=tol rtol=0... | def test_multiplication_matrix(self, tol, classes):
c1, c2 = classes
with pytest.warns(UserWarning, match="acts on overlapping wires"):
O = c1(0) @ c2(0)
res = O.matrix()
expected = c1.compute_matrix() @ c2.compute_matrix()
assert np.allclose(res, expected, atol=tol... | Python | nomic_cornstack_python_v1 |
function bin_to_dec binary_str
begin
comment Initialize the result
set result = 0
comment Iterate through the string and add each digit to the result
for d in binary_str
begin
comment Multiply the result by 2 for each digit of the string
set result = result * 2
comment Add the current digit to the result
set result = r... | def bin_to_dec(binary_str):
# Initialize the result
result = 0
# Iterate through the string and add each digit to the result
for d in binary_str:
# Multiply the result by 2 for each digit of the string
result = result * 2
# Add the current digit to the result
result += int(d)
# Return the result
retur... | Python | iamtarun_python_18k_alpaca |
import RPi.GPIO as GPIO
class Relay
begin
function __init__ self **kwargs
begin
set GPIO = GPIO
set pins = list
if string pins in kwargs
begin
pins == get kwargs string pins
end
call setmode BCM
setup GPIO pins OUT
call output pins 1
end function
function status self pin
begin
if input pin == 0
begin
return true
end
r... | import RPi.GPIO as GPIO
class Relay():
def __init__(self, **kwargs):
self.GPIO = GPIO
self.pins = []
if "pins" in kwargs:
self.pins == kwargs.get("pins")
self.GPIO.setmode(GPIO.BCM)
self.GPIO.setup(self.pins, GPIO.OUT)
self.GPIO.output(sel... | Python | zaydzuhri_stack_edu_python |
function _split_file self filename base ext encoder
begin
set wav = base + string .wav
set cuefile = none
for tmp in tuple base + string .cue base + string .wav.cue base + string .flac.cue base + string .wv.cue base + string .ape.cue
begin
if exists path tmp
begin
set cuefile = tmp
print string *** cuefile: %s % cuefil... | def _split_file(self, filename, base, ext, encoder):
wav = base + ".wav"
cuefile = None
for tmp in (base + ".cue", base + ".wav.cue", base + ".flac.cue",
base + ".wv.cue", base + ".ape.cue"):
if os.path.exists(tmp):
cuefile = tmp
... | Python | nomic_cornstack_python_v1 |
import abc
import numpy as np
from scipy.special import erf
from scipy.stats import norm
import matplotlib.pyplot as plt
from pybasicbayes.abstractions import GibbsSampling , MeanField
import pypolyagamma as ppg
from graphistician.internals.utils import sample_truncnorm , expected_truncnorm , normal_cdf , logistic
from... | import abc
import numpy as np
from scipy.special import erf
from scipy.stats import norm
import matplotlib.pyplot as plt
from pybasicbayes.abstractions import GibbsSampling, MeanField
import pypolyagamma as ppg
from graphistician.internals.utils import sample_truncnorm, expected_truncnorm, normal_cdf, logistic
from gr... | Python | zaydzuhri_stack_edu_python |
function rt_is_equiv_dense rt
begin
return call reduce_all list comprehension call equal call reduce_variance call cast row_lens call floatx call constant list 0.0 for row_lens in call nested_row_lengths
end function | def rt_is_equiv_dense(rt):
return math_ops.reduce_all([
math_ops.equal(
math_ops.reduce_variance(math_ops.cast(row_lens, backend.floatx())),
constant_op.constant([0.])) for row_lens in rt.nested_row_lengths()
]) | Python | nomic_cornstack_python_v1 |
function test__validate_status__0
begin
for tuple input_value expected_output in tuple tuple pending pending tuple value pending
begin
set output = call validate_status input_value
call assert_is output expected_output
end
end function | def test__validate_status__0():
for input_value, expected_output in (
(GuildJoinRequestStatus.pending, GuildJoinRequestStatus.pending),
(GuildJoinRequestStatus.pending.value, GuildJoinRequestStatus.pending)
):
output = validate_status(input_value)
vampytest.assert_is(output, expe... | Python | nomic_cornstack_python_v1 |
function store_drag self
begin
set Re_f = rho * V_cruise * l_fueltank / mu_37
set Re_f0 = rho_0 * V_TO * l_fueltank / mu_sl
comment RE at service ceiling results in (same for all configurations)
comment Figure 4.1
set Rwf = 0.95
comment Figure 4.3
set Cf_fueltank = 0.003
set ratio = l_fueltank / d_fueltank
set Swet_fue... | def store_drag(self):
Re_f = self.rho * self.V_cruise * self.l_fueltank / self.mu_37
Re_f0 = self.rho_0 * self.V_TO * self.l_fueltank / self.mu_sl
#RE at service ceiling results in (same for all configurations)
Rwf = 0.95 #Figure 4.1
Cf_fueltank = 0.003 #F... | Python | nomic_cornstack_python_v1 |
function ScrollTo self item
begin
if not item
begin
return
end
comment We have to call this here because the label in
comment question might just have been added and no screen
comment update taken place.
if _dirty
begin
if Platform in list string __WXMSW__ string __WXMAC__
begin
update self
end
end
else
begin
call Yiel... | def ScrollTo(self, item):
if not item:
return
# We have to call this here because the label in
# question might just have been added and no screen
# update taken place.
if self._dirty:
if wx.Platform in ["__WXMSW__", "__WXMAC__"]:
... | Python | nomic_cornstack_python_v1 |
function fisher pvalues
begin
return - 2 * log call prod pvalues
end function | def fisher(pvalues):
return -2 * np.log(np.prod(pvalues)) | Python | nomic_cornstack_python_v1 |
function to_camel_case string
begin
if any generator expression is upper char for char in string and any generator expression is digit char for char in string
begin
set words = split string string _
set camel_case_words = list words at 0
for word in words at slice 1 : :
begin
append camel_case_words capitalize word
e... | def to_camel_case(string):
if any(char.isupper() for char in string) and any(char.isdigit() for char in string):
words = string.split('_')
camel_case_words = [words[0]]
for word in words[1:]:
camel_case_words.append(word.capitalize())
return ''.join(camel_case_words)
... | Python | jtatman_500k |
from sys import stdin , stdout
set num_list = list read line stdin
sort num_list reverse=true
write stdout join string num_list | from sys import stdin, stdout
num_list = list(stdin.readline())
num_list.sort(reverse=True)
stdout.write("".join(num_list))
| Python | zaydzuhri_stack_edu_python |
function MichaelisMentenVMax substrate enzmldoc vmax=dict string ontology V_MAX k_m=dict string ontology K_M
begin
comment Check if the given IDs are part of the EnzymeML document already
if substrate not in call getSpeciesIDs
begin
raise call SpeciesNotFoundError species_id=substrate enzymeml_part=string Reactants/Pro... | def MichaelisMentenVMax(
substrate: str,
enzmldoc,
vmax: Dict[str, Any] = {"ontology": SBOTerm.V_MAX},
k_m: Dict[str, Any] = {"ontology": SBOTerm.K_M},
):
# Check if the given IDs are part of the EnzymeML document already
if substrate not in enzmldoc.getSpeciesIDs():
raise SpeciesNotFou... | Python | nomic_cornstack_python_v1 |
function test_percent_dewpoint_from_relative_humidity
begin
set td = call dewpoint_from_relative_humidity 10.6 * degC 37 * percent
call assert_almost_equal td 26.0 * degF 0
end function | def test_percent_dewpoint_from_relative_humidity():
td = dewpoint_from_relative_humidity(10.6 * units.degC, 37 * units.percent)
assert_almost_equal(td, 26. * units.degF, 0) | Python | nomic_cornstack_python_v1 |
function levenshtein_distance s t
begin
set tuple m n = tuple length s length t
set d = list comprehension list 0 * n + 1 for _ in range m + 1
for i in range m + 1
begin
set d at i at 0 = i
end
for j in range n + 1
begin
set d at 0 at j = j
end
for j in range 1 n + 1
begin
for i in range 1 m + 1
begin
if s at i - 1 == ... | def levenshtein_distance(s, t):
m, n = len(s), len(t)
d = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
d[i][0] = i
for j in range(n + 1):
d[0][j] = j
for j in range(1, n + 1):
for i in range(1, m + 1):
if s[i - 1] == t[j - 1]:
d[i][... | Python | jtatman_500k |
function uid self
begin
return get pulumi self string uid
end function | def uid(self) -> pulumi.Output[str]:
return pulumi.get(self, "uid") | Python | nomic_cornstack_python_v1 |
function prepare self
begin
return call BufferedPortProperty_prepare self
end function | def prepare(self):
return _yarp.BufferedPortProperty_prepare(self) | Python | nomic_cornstack_python_v1 |
import numpy as np
from colormath.color_objects import LabColor , XYZColor , sRGBColor
from colormath.color_conversions import convert_color
from Spectrum_Functions import spec_to_xyz
from Spectrum_Functions import delta_E_CIE2000
from Spectrum_Functions import gen_spectrum_1dip
from Spectrum_Functions import gen_spect... | import numpy as np
from colormath.color_objects import LabColor, XYZColor, sRGBColor
from colormath.color_conversions import convert_color
from Spectrum_Functions import spec_to_xyz
from Spectrum_Functions import delta_E_CIE2000
from Spectrum_Functions import gen_spectrum_1dip
from Spectrum_Functions import gen_s... | Python | zaydzuhri_stack_edu_python |
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
function partition self head x
begin
set dummy1 = call ListNode - 1
set dummy2 = call ListNode - 1
set node1 = dummy1
set node2 = dummy2
while head
begin
i... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
dummy1 = ListNode(-1)
dummy2 = ListNode(-1)
node1 = dummy1
node2 = dummy2
... | Python | zaydzuhri_stack_edu_python |
for _ in range T
begin
set N = integer input
set l = list comprehension integer i for i in split input
sort l
set L = list comprehension l at i + 1 - l at i for i in range N - 1
print min L
end | for _ in range(T):
N = int(input())
l = [int(i) for i in input().split()]
l.sort()
L = [l[i+1] - l[i] for i in range(N - 1)]
print(min(L)) | Python | zaydzuhri_stack_edu_python |
function get_descriptions self
begin
return _descriptions
end function | def get_descriptions(self) -> dict[str, str]:
return self._descriptions | Python | nomic_cornstack_python_v1 |
function normalize_sentence self input_sentence
begin
warn string This function can imply in data loss and reverts all lemmatization and pos tagging process. Also, it creates a standalone sentence in relation to parent Document. It is recomended that any text is normalized prior to tokenization.
if not is instance inpu... | def normalize_sentence(self, input_sentence):
warnings.warn(
"This function can imply in data loss and reverts all lemmatization and pos tagging process. Also, it creates a standalone sentence in relation to parent Document. It is recomended that any text is normalized prior to tokenization.")
... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
from flask_restful import Resource
from models.store import Store as StoreModel
class Store extends Resource
begin
function get self name
begin
set store = call find_by_name name
if store
begin
return tuple json store 200
end
return tuple dict string message string Store not found 404
end function... | # coding: utf-8
from flask_restful import Resource
from models.store import Store as StoreModel
class Store(Resource):
def get(self, name):
store = StoreModel.find_by_name(name)
if store:
return store.json(), 200
return {'message': 'Store not found'}, 404
def post(self, n... | Python | zaydzuhri_stack_edu_python |
function scale ctx
begin
info format string Successfully scaled "{}" environment. call get_current_env
end function | def scale(ctx):
ctx.info('Successfully scaled "{}" environment.'.format(self.get_current_env())) | Python | nomic_cornstack_python_v1 |
from pywinauto.application import Application
class TextNotFound extends Exception
begin
pass
end class
class NotePage
begin
function __init__ self
begin
set app = call Application
set x = list
set z = list
end function
function start_app self app
begin
start app app
end function
function write_text self
begin
call t... | from pywinauto.application import Application
class TextNotFound(Exception):
pass
class NotePage:
def __init__(self):
self.app = Application()
self.x = []
self.z = []
def start_app(self, app):
self.app.start(app)
def write_text(self):
self... | Python | zaydzuhri_stack_edu_python |
function test_array_as_buffer_ndim parser
begin
set doc = parse parser b'[[\n [1.0, 2.0],\n [3.0, 4.0]\n ]]'
set view = call memoryview call as_buffer of_type=string d
assert length view == 32
end function | def test_array_as_buffer_ndim(parser):
doc = parser.parse(b'''[[
[1.0, 2.0],
[3.0, 4.0]
]]''')
view = memoryview(doc.as_buffer(of_type='d'))
assert len(view) == 32 | Python | nomic_cornstack_python_v1 |
function calcLodSize finestLodSize lod
begin
set lodDiff = call calcLodFromSize finestLodSize - lod
return tuple call divPow2RoundUp finestLodSize at 0 lodDiff call divPow2RoundUp finestLodSize at 1 lodDiff
end function | def calcLodSize(finestLodSize, lod):
lodDiff = calcLodFromSize(finestLodSize) - lod
return (divPow2RoundUp(finestLodSize[0], lodDiff), divPow2RoundUp(finestLodSize[1], lodDiff)) | Python | nomic_cornstack_python_v1 |
function conv_dimension_numbers lhs_shape rhs_shape dimension_numbers
begin
if is instance dimension_numbers ConvDimensionNumbers
begin
return dimension_numbers
end
if length lhs_shape != length rhs_shape
begin
set msg = string convolution requires lhs and rhs ndim to be equal, got {} and {}.
raise call TypeError forma... | def conv_dimension_numbers(lhs_shape, rhs_shape, dimension_numbers):
if isinstance(dimension_numbers, ConvDimensionNumbers):
return dimension_numbers
if len(lhs_shape) != len(rhs_shape):
msg = 'convolution requires lhs and rhs ndim to be equal, got {} and {}.'
raise TypeError(msg.format(len(lhs_shape), ... | Python | nomic_cornstack_python_v1 |
function calculate_obj X W F L alpha beta
begin
comment Tr(F^T L F)
set T1 = call trace dot dot transpose F L F
set T2 = norm dot X W - F string fro
set T3 = sum
set obj = T1 + alpha * T2 + beta * T3
return obj
end function | def calculate_obj(X, W, F, L, alpha, beta):
# Tr(F^T L F)
T1 = np.trace(np.dot(np.dot(F.transpose(), L), F))
T2 = np.linalg.norm(np.dot(X, W) - F, 'fro')
T3 = (np.sqrt((W*W).sum(1))).sum()
obj = T1 + alpha*(T2 + beta*T3)
return obj | Python | nomic_cornstack_python_v1 |
function product_type self
begin
return __name__
end function | def product_type(self):
return self.__class__.__name__ | Python | nomic_cornstack_python_v1 |
import time
import psycopg2.extras
import argparse
import re
import csv
import sys
import pandas as pd
import numpy as np
import csv , json
from geojson import Feature , FeatureCollection , Point
set DBname = string postgres
set DBuser = string postgres
set DBpwd = string postgres
comment connect to the database
functi... | import time
import psycopg2.extras
import argparse
import re
import csv
import sys
import pandas as pd
import numpy as np
import csv, json
from geojson import Feature, FeatureCollection, Point
DBname = "postgres"
DBuser = "postgres"
DBpwd = "postgres"
# connect to the database
def dbconnect():
connection = psyc... | 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.