code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function user request id
begin
comment Get user data by id:
set user = dict string user get objects id=id ; string total_reviews count all ; string reviewed_books call distinct
return call render request string reviewer/show_user.html user
end function | def user(request, id):
# Get user data by id:
user = {
"user": User.objects.get(id=id),
"total_reviews": User.objects.get(id=id).review_set.all().count(),
"reviewed_books": Book.objects.filter(review__user__id=id).distinct(),
}
return render(request, "reviewer/show_user.html", ... | Python | nomic_cornstack_python_v1 |
comment /usr/bin/env python3
function sum_common_prefix_length s
begin
set sum_of_lengths = 0
for i in range length s
begin
set prefix = s at slice : i :
set suffix = s at slice i : :
set sum_of_lengths = sum_of_lengths + length call find_longest_common_prefix suffix s
end
return sum_of_lengths
end function
functio... | #/usr/bin/env python3
def sum_common_prefix_length(s):
sum_of_lengths = 0
for i in range(len(s)):
prefix = s[:i]
suffix = s[i:]
sum_of_lengths += len(find_longest_common_prefix(suffix, s))
return sum_of_lengths
def find_longest_common_prefix(s1, s2):
i = j = 0
while i < ... | Python | zaydzuhri_stack_edu_python |
import unittest
from parser import Parser , Events
class ParserTest extends TestCase
begin
function test_scopes_end self
begin
set p = call Parser string function() { if (1) { } else { } }
assert equal FUNCTION_START call _next_token
assert equal OTHER_KEYWORD call _next_token
assert equal OTHER_KEYWORD call _next_toke... | import unittest
from parser import Parser, Events
class ParserTest(unittest.TestCase):
def test_scopes_end(self):
p = Parser(' function() { if (1) { } else { } }')
self.assertEqual(Events.FUNCTION_START, p._next_token())
self.assertEqual(Events.OTHER_KEYWORD, p._next_token())
self.assertEqual(Event... | Python | zaydzuhri_stack_edu_python |
function setUpClass cls
begin
call setUpClass
set acl_active_table = string
end function | def setUpClass(cls):
super(TestClassifier, cls).setUpClass()
cls.acl_active_table = '' | Python | nomic_cornstack_python_v1 |
try
begin
set stream = open string C:\Users\Humanitroy\Desktop\file.txt string rt
comment aqui se procesa el archivo
comment se imprime el contenido del archivo
print read stream
close stream
end
except Exception as exc
begin
print string No se puede abrir el archivo: exc
end | try:
stream = open("C:\\Users\\Humanitroy\\Desktop\\file.txt", "rt")
# aqui se procesa el archivo
print(stream.read()) # se imprime el contenido del archivo
stream.close()
except Exception as exc:
print("No se puede abrir el archivo:", exc) | Python | zaydzuhri_stack_edu_python |
function get_type self
begin
return _col_type
end function | def get_type(self):
return self._col_type | Python | nomic_cornstack_python_v1 |
from itertools import count , imap
function ispandigital seed
begin
set digits = string seed
for i in count 2
begin
set ndig = length digits
if ndig < 9
begin
set digits = digits + string seed * i
end
else
if ndig == 9 and set digits == set string 123456789
begin
return integer digits
end
else
begin
return false
end
en... | from itertools import count, imap
def ispandigital( seed):
digits = str( seed)
for i in count(2):
ndig = len( digits)
if ndig < 9: digits += str( seed * i)
elif ndig == 9 and set( digits) == set( '123456789'):
return int( digits)
else: return False | Python | zaydzuhri_stack_edu_python |
function can_contain_aggregation self aggregation
begin
return false
end function | def can_contain_aggregation(self, aggregation):
return False | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[3]:
comment stuff to import
call magic string matplotlib inline
import matplotlib.pyplot as plt
import statsmodels.api as sm
import pandas as pd
import numpy as np
import statsmodels.api as sm
import pylab as pl
from sklearn import datasets
from sklearn import metrics
comment In[4]:
com... | # coding: utf-8
# In[3]:
# stuff to import
get_ipython().magic('matplotlib inline')
import matplotlib.pyplot as plt
import statsmodels.api as sm
import pandas as pd
import numpy as np
import statsmodels.api as sm
import pylab as pl
from sklearn import datasets
from sklearn import metrics
# In[4]:
# read in the fil... | Python | zaydzuhri_stack_edu_python |
function update self
begin
update data
set sensor_type = key
if sensor_type == string light
begin
set _attr_native_value = light
end
else
if sensor_type == string light_red
begin
set _attr_native_value = light_red
end
else
if sensor_type == string light_green
begin
set _attr_native_value = light_green
end
else
if senso... | def update(self):
self.data.update()
sensor_type = self.entity_description.key
if sensor_type == "light":
self._attr_native_value = self.data.light
elif sensor_type == "light_red":
self._attr_native_value = self.data.light_red
elif sensor_type == "light_g... | Python | nomic_cornstack_python_v1 |
function block_size self
begin
return _block_size
end function | def block_size(self) -> int:
return self._block_size | Python | nomic_cornstack_python_v1 |
import math
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 get_max_prime_with_pattern arr
begin
set max_prime = - 1
for num in arr
begin
if call is_prime num
begin
set digit_sum = sum ... | import math
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def get_max_prime_with_pattern(arr):
max_prime = -1
for num in arr:
if is_prime(num):
digit_sum = sum(int(digit) fo... | Python | jtatman_500k |
function dgTimerOff self
begin
pass
end function | def dgTimerOff(self):
pass | Python | nomic_cornstack_python_v1 |
function next self
begin
string Returns the next attribute from the Instances object. :return: the next Attribute object :rtype: Attribute
if col < num_attributes
begin
set index = col
set col = col + 1
return call attribute index
end
else
begin
raise call StopIteration
end
end function | def next(self):
"""
Returns the next attribute from the Instances object.
:return: the next Attribute object
:rtype: Attribute
"""
if self.col < self.data.num_attributes:
index = self.col
self.col += 1
return self.data.attribute(index)... | Python | jtatman_500k |
import datetime
import enum
import math
import config
from pydantic import BaseModel , EmailStr
class AcceptanceStatusEnum extends Enum
begin
set none = string none
set waitlist_queue = string waitlist_queue
set waitlisted = string waitlisted
set rejected = string rejected
set queue = string queue
set accepted = string... | import datetime
import enum
import math
import config
from pydantic import BaseModel, EmailStr
class AcceptanceStatusEnum(enum.Enum):
none = "none"
waitlist_queue = "waitlist_queue"
waitlisted = "waitlisted"
rejected = "rejected"
queue = "queue"
accepted = "accepted"
class ShirtSize(enum.En... | Python | zaydzuhri_stack_edu_python |
import random
class Player
begin
function __init__ self letter
begin
set letter = letter
end function
end class
class ComputerPlayer extends Player
begin
function __init__ self letter
begin
call __init__ letter
end function
function get_move self board available_moves
begin
comment selecting random key
set rand_choice ... | import random
class Player:
def __init__(self, letter):
self.letter = letter
class ComputerPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, board, available_moves):
rand_choice = random.choice([k for k in available_moves.keys()]) #selecting r... | Python | zaydzuhri_stack_edu_python |
function __hash__ self
begin
return call hash tuple host port
end function | def __hash__(self):
return hash((self.host, self.port)) | Python | nomic_cornstack_python_v1 |
function _computeViscousFactor self maxwellTime
begin
set timeFrac = 1e-05
set numTerms = 5
set dq = 0.0
if maxwellTime < timeFrac * dt
begin
set fSign = 1.0
set factorial = 1.0
set fraction = 1.0
set dq = 1.0
for iTerm in range 2 numTerms + 1
begin
set factorial = factorial * iTerm
set fSign = fSign * - 1.0
set fracti... | def _computeViscousFactor(self, maxwellTime):
timeFrac = 1.0e-5
numTerms = 5
dq = 0.0
if maxwellTime < timeFrac*self.dt:
fSign = 1.0
factorial = 1.0
fraction = 1.0
dq = 1.0
for iTerm in range(2, numTerms + 1):
factorial *= iTerm
fSign *= -1.0
fr... | Python | nomic_cornstack_python_v1 |
function calculate_metrics self
begin
comment arrays initialization
set number_of_models = length models
set train_set_size = shape at 0
set test_set_size = shape at 0
set tmp_predict_classes_train = call ndarray tuple train_set_size number_of_models
set tmp_predict_classes_test = call ndarray tuple test_set_size numbe... | def calculate_metrics(self):
# arrays initialization
number_of_models = len(self.models)
train_set_size = self.x_train.shape[0]
test_set_size = self.x_test.shape[0]
tmp_predict_classes_train = numpy.ndarray(
(train_set_size, number_of_models))
tmp_predict_cla... | Python | nomic_cornstack_python_v1 |
comment 640. Solve the Equation - https://leetcode.com/problems/solve-the-equation
comment Credits to https://discuss.leetcode.com/topic/95283/python-regex-solution-explained
class Solution
begin
function solveEquation self equation
begin
string :type equation: str :rtype: str
comment Coefficients are defined by the fo... | # 640. Solve the Equation - https://leetcode.com/problems/solve-the-equation
# Credits to https://discuss.leetcode.com/topic/95283/python-regex-solution-explained
class Solution:
def solveEquation(self, equation):
"""
:type equation: str
:rtype: str
"""
# Coefficients are d... | Python | zaydzuhri_stack_edu_python |
string Algorithm: Feature space: (L,u,v,x,y) Intensity + (u,v) color channels + Position in image (x,y) • Apply meanshift in the 5-dimensional space • For each pixel (xi,yi) of intensity Li and color (ui,vi), find the corresponding mode ck • All of the pixel (xi,yi) corresponding to the same mode ck are grouped into a ... | '''
Algorithm:
Feature space: (L,u,v,x,y) Intensity + (u,v)
color channels + Position in image (x,y)
• Apply meanshift in the 5-dimensional space
• For each pixel (xi,yi) of intensity Li and color
(ui,vi), find the corresponding mode ck
• All of the pixel (xi,yi) corresponding to the same
mode ck are grouped into a sin... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Feb 18 16:53:07 2019 @author: Matt creating a more efficient computation of fibonacci sequence using a dictionary computes and stores each fibonacci sequence number to be called when needed, instead of computing each value over and over again.
comment Original, ineffi... | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 18 16:53:07 2019
@author: Matt
creating a more efficient computation of fibonacci sequence using a dictionary
computes and stores each fibonacci sequence number to be called when needed, instead
of computing each value over and over again.
"""
# Original, inefficient ... | Python | zaydzuhri_stack_edu_python |
comment vim: fileencoding=utf-8
function fib x
begin
print string fib():
set tuple a b = tuple 0 1
while b < x
begin
print b end=string
set tuple a b = tuple b a + b
end
print
end function
function fib_range x
begin
print string fib_range():
set tuple a b = tuple 0 1
for i in range x
begin
print b end=string
set tuple ... | # vim: fileencoding=utf-8
def fib(x):
print('fib():')
a, b = 0, 1
while b < x:
print(b, end=' ')
a, b = b, a+b
print()
def fib_range(x):
print('fib_range():')
a, b = 0, 1
for i in range(x):
print(b, end=' ')
a, b = b, a+b
print()
def check_the_none():
... | 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
comment @param {ListNode} head
comment @return {boolean}
function isPalindrome self head
begin
comment typical way to find the middle node, must remember!
... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @return {boolean}
def isPalindrome(self, head):
#typical way to find the middle node, must remember!
#there are n ... | Python | zaydzuhri_stack_edu_python |
function __getitem__ self key
begin
set data = call exec_one get key
try
begin
set result = loads data
end
except EOFError
begin
raise call KeyError key
end
return result
end function | def __getitem__(self, key):
data = self._conn.exec_one(self._sql.get, key)
try:
result = pickle.loads(data)
except EOFError:
raise KeyError(key)
return result | Python | nomic_cornstack_python_v1 |
comment We say a number is sparse if there are no adjacent ones in its binary representation.
comment For example, 21 (10101) is sparse, but 22 (10110) is not. For a given input N,
comment find the smallest sparse number greater than or equal to N.
function solution number
begin
set binary = string binary number at sli... | # We say a number is sparse if there are no adjacent ones in its binary representation.
# For example, 21 (10101) is sparse, but 22 (10110) is not. For a given input N,
# find the smallest sparse number greater than or equal to N.
def solution(number):
binary = str(bin(number)[2:])
to_return = ''
previo... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
string This program execute Run: $ python JsonQueryParser.py qald-file.json
import sys
import json
import os
import unicodedata
import re
from collections import defaultdict
set pattern = string http://dbpedia.org/ontology
set pattern2 = string dbo:
class QueryDataBase extends object
begin
... | #!/usr/bin/env python
"""This program execute
Run:
$ python JsonQueryParser.py qald-file.json
"""
import sys
import json
import os
import unicodedata
import re
from collections import defaultdict
pattern = "http://dbpedia.org/ontology"
pattern2 = "dbo:"
class QueryDataBase(object):
def __init__(self, inputf... | Python | zaydzuhri_stack_edu_python |
function reload_systemd_unit bus unit timeout=100
begin
debug string Instructing systemd to reload unit %s unit
try
begin
set systemd = get bus string org.freedesktop.systemd1 timeout=timeout
set manager_interface = systemd at string org.freedesktop.systemd1.Manager
call ReloadUnit unit string fail timeout=timeout
end
... | def reload_systemd_unit(bus: Bus, unit: str, timeout: int = 100) -> None:
logger.debug("Instructing systemd to reload unit %s", unit)
try:
systemd = bus.get('org.freedesktop.systemd1', timeout=timeout)
manager_interface = systemd['org.freedesktop.systemd1.Manager']
manager_interface.Relo... | Python | nomic_cornstack_python_v1 |
function filter_re_replace val pattern repl
begin
return sub pattern repl string val
end function | def filter_re_replace(val: AnyStr, pattern: str, repl: str) -> str:
return re.sub(pattern, repl, str(val)) | Python | nomic_cornstack_python_v1 |
function fixture_causative_output causatives_file
begin
with open causatives_file string r as infile
begin
set content = read infile
end
return content
end function | def fixture_causative_output(causatives_file: Path) -> str:
with open(causatives_file, "r") as infile:
content = infile.read()
return content | Python | nomic_cornstack_python_v1 |
function q self
begin
return _q
end function | def q(self):
return self._q | Python | nomic_cornstack_python_v1 |
for i in range 0 p - 1
begin
for j in range i + 1 p
begin
if absolute l at i + l at j < large
begin
set tuple u v = tuple l at i l at j
set large = absolute u + v
end
end
end
print u v | for i in range(0,p-1):
for j in range(i+1,p):
if abs(l[i]+l[j])<large:
u,v=l[i],l[j]
large=abs(u+v)
print(u,v)
| Python | zaydzuhri_stack_edu_python |
comment bc strings are a bitch in cpp
set list a b = list comprehension integer x for x in split input
if a == 0
begin
set a = 1
end
if b == 0
begin
set b = 1
end
comment want to compute b!/a!
set diff = b - a
set bigNum = 1
while diff > 0
begin
set bigNum = bigNum * b % 10
set b = b - 1
set diff = diff - 1
set bigNum ... | # bc strings are a bitch in cpp
[a,b] = [int(x) for x in input().split()]
if a == 0:
a = 1
if b == 0:
b = 1
# want to compute b!/a!
diff = b-a
bigNum = 1
while diff > 0:
bigNum = (bigNum*b)%10
b -= 1
diff -= 1
bigNum = int(str(bigNum)[-1])
if (bigNum == 0):
break
print(bigNum)
| Python | zaydzuhri_stack_edu_python |
import sys
class Graph
begin
function __init__ self vertices
begin
set V = vertices
set graph = list
end function
function add_edge self u v w
begin
append graph list u v w
end function
function find_min_key self key mst_set
begin
set min_key = maxsize
set min_index = none
for v in range V
begin
if key at v < min_key ... | import sys
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []
def add_edge(self, u, v, w):
self.graph.append([u, v, w])
def find_min_key(self, key, mst_set):
min_key = sys.maxsize
min_index = None
for v in range(self.V):
... | Python | greatdarklord_python_dataset |
function getUserInfo user_id
begin
set user = call one
return user
end function | def getUserInfo(user_id):
user = session.query(User).filter_by(id=user_id).one()
return user | Python | nomic_cornstack_python_v1 |
function GetObjectCount self
begin
return call itkConnectedComponentImageFilterIUS3IUL3_GetObjectCount self
end function | def GetObjectCount(self) -> "unsigned long long const &":
return _itkConnectedComponentImageFilterPython.itkConnectedComponentImageFilterIUS3IUL3_GetObjectCount(self) | Python | nomic_cornstack_python_v1 |
function move_west self
begin
move dx=- 1 dy=0
set prev_tile = string east
end function | def move_west(self):
self.move(dx=-1, dy=0)
self.prev_tile = "east" | Python | nomic_cornstack_python_v1 |
function print_flow self starts=none
begin
if starts is none
begin
set starts = _start_steps
end
else
begin
set starts = call steps_by_name starts
end
print string start_steps
call pprint _start_steps
print string steps
call pprint _steps
print string steps-flow
call pprint _step_flow
print string steps-index
call ppri... | def print_flow(self, starts = None ):
if starts is None:
starts = self._start_steps
else:
starts = self.steps_by_name( starts )
print("start_steps")
pp.pprint( self._start_steps )
print("steps")
pp.pprint( self._steps )
print("steps-flow"... | Python | nomic_cornstack_python_v1 |
from time import sleep
import pyautogui
function click x y
begin
call click x y
end function
function check_screen
begin
set button = call locateOnScreen string en.png confidence=0.7
set buttonPt = call locateOnScreen string pt.png confidence=0.7
print string Waiting...
if button != none
begin
call click left top
retur... | from time import sleep
import pyautogui
def click(x, y):
pyautogui.click(x, y)
def check_screen():
button = pyautogui.locateOnScreen('en.png', confidence=0.7)
buttonPt = pyautogui.locateOnScreen('pt.png', confidence=0.7)
print('Waiting...')
if button != None:
click(button.left, but... | Python | zaydzuhri_stack_edu_python |
function countFullBrowser self data docID
begin
for entry in call genData
begin
if string visitor_useragent in entry and string event_type in entry
begin
if entry at string event_type == string read
begin
if string entry at string subject_doc_id == docID
begin
if entry at string visitor_useragent in browserCounts
begin... | def countFullBrowser(self, data, docID):
for entry in data.genData():
if 'visitor_useragent' in entry and 'event_type' in entry:
if entry['event_type'] == 'read':
if str(entry['subject_doc_id']) == docID:
if entry['visitor_useragent'] in se... | Python | nomic_cornstack_python_v1 |
string @author : saitejasedate Write a python program to read multiple lines of text input and store the input into a string.
function main
begin
string program to read multiple lines of text input and store the input into a string.
set str_output = string
set input_num_lines = integer input
for line_num in range inpu... | '''
@author : saitejasedate
Write a python program to read multiple lines of text input and store the input into a string.
'''
def main():
'''
program to read multiple lines of text input and store the input into a string.
'''
str_output = ""
input_num_lines = int(input())
for line_num in range... | Python | zaydzuhri_stack_edu_python |
function IGOU_Model coeffs t
begin
set tuple a b gamma lambda0 = coeffs
set k = 2 * b ^ - 2 / gamma
set A = 1 - square root 1 + k * 1 - exp - gamma * t / k + 1 / square root 1 + k * call atanh square root 1 + k * 1 - exp - gamma * t / square root 1 + k - call atanh 1 / square root 1 + k
set survival = exp - lambda0 / g... | def IGOU_Model(coeffs,t):
a, b, gamma,lambda0 = coeffs
k = 2 * b ** (-2) / gamma
A = (1 - sqrt(1 + k * (1 - exp(-gamma * t)))) \
/ k + 1 / sqrt(1 + k) \
* (atanh(sqrt(1 + k * (1 - exp(-gamma * t))) /
sqrt(1 + k)) - atanh(1 / sqrt(1 + k)))
survival = exp((... | Python | nomic_cornstack_python_v1 |
function random_array_fill array k
begin
for i in range k
begin
set array at tuple call alea shape at 0 - 1 call alea shape at 1 - 1 = string X
end
return array
end function | def random_array_fill(array,k):
for i in range(k):
array[alea(array.shape[0]-1),alea(array.shape[1]-1)] = 'X'
return array | Python | nomic_cornstack_python_v1 |
function find_node_by_op_type self op_type
begin
return list __op_type_list at op_type
end function | def find_node_by_op_type(self, op_type: str) -> List[Operator]:
return list(self.__op_type_list[op_type]) | Python | nomic_cornstack_python_v1 |
function is_valid_email email
begin
if match regex email
begin
return true
end
end function | def is_valid_email(email):
if re.match(regex, email):
return True | Python | greatdarklord_python_dataset |
function has_data self
begin
return list 0 != __contexts and list 0 != __weights
end function | def has_data(self):
return ([0] != self.__contexts) and ([0] != self.__weights) | Python | nomic_cornstack_python_v1 |
comment emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
comment ex: set sts=4 ts=4 sw=4 noet:
string COPYRIGHT: Yaroslav Halchenko 2014 LICENSE: MIT Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files... | #emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
#ex: set sts=4 ts=4 sw=4 noet:
"""
COPYRIGHT: Yaroslav Halchenko 2014
LICENSE: MIT
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "... | Python | zaydzuhri_stack_edu_python |
function test_page_serve self
begin
get driver url_ + USA_URL
comment Using implicit wait here to wait for loading page.
call implicitly_wait 5
set req = call Request current_url
with url open req as response
begin
assert equal call getcode 200
end
comment Assert the js files are generated successfully.
set req = call ... | def test_page_serve(self):
self.driver.get(self.url_ + USA_URL)
# Using implicit wait here to wait for loading page.
self.driver.implicitly_wait(5)
req = urllib.request.Request(self.driver.current_url)
with urllib.request.urlopen(req) as response:
self.assertEqual(res... | Python | nomic_cornstack_python_v1 |
function read_in_data f_txt
begin
set wd_list = list
comment read and igmore 20 lines in the file
try
begin
with open f_txt as f_in
begin
comment for line in range (20):
comment f_in.readline()
for line in f_in
begin
extend wd_list split line
end
end
close f_in
end
except IOError
begin
print format string Cannot find ... | def read_in_data(f_txt):
wd_list = []
#read and igmore 20 lines in the file
try:
with open (f_txt) as f_in:
# for line in range (20):
#f_in.readline()
for line in f_in:
wd_list.extend(line.split())
f_in.close()
except IOError:
print("Cannot find file {}".format(f_txt))
return wd_list | Python | nomic_cornstack_python_v1 |
function get_management_certificate self thumbprint
begin
string The Get Management Certificate operation retrieves information about the management certificate with the specified thumbprint. Management certificates, which are also known as subscription certificates, authenticate clients attempting to connect to resour... | def get_management_certificate(self, thumbprint):
'''
The Get Management Certificate operation retrieves information about
the management certificate with the specified thumbprint. Management
certificates, which are also known as subscription certificates,
authenticate clients at... | Python | jtatman_500k |
function remove_transaction self transaction
begin
set i = 0
while i < length transactions
begin
if hash == hash
begin
debug string Removing transaction %s % hash
del transactions at i
set i = i - 1
end
set i = i + 1
end
end function | def remove_transaction(self, transaction):
i = 0
while i < len(self.transactions):
if transaction.hash == self.transactions[i].hash:
logger.debug("Removing transaction %s" % self.transactions[i].hash)
del self.transactions[i]
... | Python | nomic_cornstack_python_v1 |
from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
import time
function init_browser
begin
set executable_path = dict string executable_path string chromedriver.exe
return call Browser string chrome keyword executable_path headless=false
end function
function scrape
begin
set browser = call ... | from splinter import Browser
from bs4 import BeautifulSoup
import pandas as pd
import time
def init_browser():
executable_path = {'executable_path': 'chromedriver.exe'}
return Browser("chrome", **executable_path, headless=False)
def scrape():
browser = init_browser()
# create mars_data dict that we ca... | Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ self value
begin
string OBJECTIVE: Input Parameter
set data = value
set next = none
end function
end class
class LinkedList
begin
function __init__ self
begin
string
set head = none
end function
function insertAtBegin self value
begin
string
if head == none
begin
set nod = call Node... | class Node:
def __init__(self,value):
'''
OBJECTIVE:
Input Parameter
'''
self.data=value
self.next=None
class LinkedList:
def __init__(self):
'''
'''
self.head=None
def insertAtBegin(self,value):
'''
'''... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set t = integer input
for i in range t
begin
set n = integer input
set num = list map int split input
set and_list = list comprehension list 0 * n for _ in range n
set or_list = list comprehension list 0 * n for _ in range n
set ans = 0
for a in range n
begin
for b in range n
begin
set and_list at a ... | import numpy as np
t = int(input())
for i in range(t):
n = int(input())
num = list(map(int,input().split()))
and_list = [[0]*n for _ in range(n)]
or_list = [[0]*n for _ in range(n)]
ans = 0
for a in range(n):
for b in range(n):
and_list[a][b]=num[a]&num[b]
or_list[a][b]=num[a]|num[b]
and_list = np.... | Python | zaydzuhri_stack_edu_python |
set a = 4
set b = 5
set c = a + b
print string c= c | a=4
b=5
c=a+b
print("c=",c) | Python | zaydzuhri_stack_edu_python |
from data_access import *
if __name__ == string __main__
begin
set whitelist_jda = call JsonDataAccess string whitelist.json
set username = string
print string Whitelist Creator ---------------------------------
while true
begin
set username = input string Type username to add to whitelist or exit to exit:
if string e... | from data_access import *
if __name__ == "__main__":
whitelist_jda = JsonDataAccess("whitelist.json")
username = ""
print("""
Whitelist Creator
---------------------------------
""")
while True:
username = input("Type username to add to whitelist or exit to exit: ")
if 'exit... | Python | zaydzuhri_stack_edu_python |
comment http://acm.timus.ru/problem.aspx?space=1&num=1991&locale=en
set tuple blocks droids = split input
set tuple blocks droids = tuple integer blocks integer droids
set tot_explosion = split input
set survived_droids = 0
set untouched_explosion = 0
for block in tot_explosion
begin
set calc = droids - integer block
i... | # http://acm.timus.ru/problem.aspx?space=1&num=1991&locale=en
blocks, droids = input().split()
blocks, droids = int(blocks), int(droids)
tot_explosion = input().split()
survived_droids = 0
untouched_explosion = 0
for block in tot_explosion:
calc = droids - int(block)
if calc > 0:
survived_droids += ca... | Python | zaydzuhri_stack_edu_python |
function get_messages self
begin
try
begin
set _msg_buffer = _msg_buffer + call recv 4096
while length _msg_buffer >= 4
begin
set message = call _pop_from_buffer
if message
begin
yield message
end
else
begin
return
end
end
end
except error
begin
return
end
end function | def get_messages(self):
try:
self._msg_buffer += self._socket.recv(4096)
while len(self._msg_buffer) >= 4:
message = self._pop_from_buffer()
if message:
yield message
else:
return
except socket.error:
return | Python | nomic_cornstack_python_v1 |
function print_tree node depth=1
begin
for child in node
begin
print string * depth + call get_name
call print_tree child depth + 1
end
end function | def print_tree(node, depth=1):
for child in node:
print(" " * depth + child.get_name())
print_tree(child, depth+1) | Python | nomic_cornstack_python_v1 |
function memorize_prior_distribution self y_train
begin
for y in y_train
begin
for i in range length y - 1
begin
set apriori_probability at string y at i + string y at i + 1 = apriori_probability at string y at i + string y at i + 1 + 1
end
end
end function | def memorize_prior_distribution(self, y_train: List[str]):
for y in y_train:
for i in range(len(y) - 1):
self.apriori_probability[str(y[i]) + str(y[i + 1])] += 1 | Python | nomic_cornstack_python_v1 |
function clone self *args
begin
return call CompositeDragger_clone self *args
end function | def clone(self, *args):
return _osgManipulator.CompositeDragger_clone(self, *args) | Python | nomic_cornstack_python_v1 |
function update self outputs targets
begin
set tuple tn fp fn tp support num_classes = update call super outputs=outputs targets=targets
set tuple per_class micro macro weighted = call get_aggregated_metrics tp=tp fp=fp fn=fn support=support zero_division=zero_division
if num_classes is none
begin
set num_classes = num... | def update(
self, outputs: torch.Tensor, targets: torch.Tensor
) -> Tuple[Any, Any, Any, Any]:
tn, fp, fn, tp, support, num_classes = super().update(
outputs=outputs, targets=targets
)
per_class, micro, macro, weighted = get_aggregated_metrics(
tp=tp, fp=fp, f... | Python | nomic_cornstack_python_v1 |
import unittest
from datetime import date , timedelta
from chore import *
from server import Scheduler
from dummydata import *
class ChoreTestMethods extends TestCase
begin
set test_no_history = call Chore string Test Empty string weekly
set test = call Chore string Test string weekly
append history call Completion str... | import unittest
from datetime import date, timedelta
from chore import *
from server import Scheduler
from dummydata import *
class ChoreTestMethods(unittest.TestCase):
test_no_history = Chore("Test Empty", "weekly")
test = Chore("Test", "weekly")
test.history.append(Completion("Alice", "2019-11-25"... | Python | zaydzuhri_stack_edu_python |
from funcionalidad import LectorCursos , LectorEvaluaciones , LectorPersonas , LectorRequisitos
from sistema import Bummer , Pacmatico , Permisos
from universidad import Universidad
from curso import Curso
set dir_cur = string cursos.txt
set dir_eval = string evaluaciones.txt
set dir_req = string requisitos.txt
set dir... | from funcionalidad import LectorCursos, LectorEvaluaciones, LectorPersonas, LectorRequisitos
from sistema import Bummer, Pacmatico, Permisos
from universidad import Universidad
from curso import Curso
dir_cur = "cursos.txt"
dir_eval = "evaluaciones.txt"
dir_req = "requisitos.txt"
dir_per = "personas.txt"
def leer(me... | Python | zaydzuhri_stack_edu_python |
function testSearchWithHasNoneValue self
begin
set objectID = uuid 4
yield update index dict objectID dict string test/tag1 none ; uuid 4 dict string test/tag2 none
yield commit index
set query = call parseQuery string has test/tag1
set result = yield search query
assert equal set list objectID result
end function | def testSearchWithHasNoneValue(self):
objectID = uuid4()
yield self.index.update({objectID: {u'test/tag1': None},
uuid4(): {u'test/tag2': None}})
yield self.index.commit()
query = parseQuery(u'has test/tag1')
result = yield self.index.search(query... | Python | nomic_cornstack_python_v1 |
function testLimitBenchmarksToRunToMultipleBenchmarks self
begin
call _RunLimitBenchmarksToRun set list string StarRandomAccess string SingleRandomAccess
call _ValidateRunLimitBenchmarksToRun list string MPI_Init( &argc, &argv ); string if (redacted) string goto hpcc_end; string // MPI RandomAccess line 1 redacted. str... | def testLimitBenchmarksToRunToMultipleBenchmarks(self):
self._RunLimitBenchmarksToRun(
set(['StarRandomAccess', 'SingleRandomAccess']))
self._ValidateRunLimitBenchmarksToRun([
' MPI_Init( &argc, &argv );',
' if (redacted)',
' goto hpcc_end;',
'// MPI RandomAccess l... | Python | nomic_cornstack_python_v1 |
function get_vulnerabilities_hr vulnerability_list
begin
return list comprehension dict string Name get vuln_info_dict string cve string ; string V2/Score get vuln_info_dict string baseScore string ; string Attack Vector get vuln_info_dict string attackVector string ; string Attack Complexity get vuln_info_dict string ... | def get_vulnerabilities_hr(vulnerability_list):
return [{'Name': vuln_info_dict.get('cve', ''),
'V2/Score': vuln_info_dict.get('baseScore', ''),
'Attack Vector': vuln_info_dict.get('attackVector', ''),
'Attack Complexity': vuln_info_dict.get('accessComplexity', ''),
... | Python | nomic_cornstack_python_v1 |
function ship_to_country self
begin
return _ship_to_country
end function | def ship_to_country(self):
return self._ship_to_country | Python | nomic_cornstack_python_v1 |
function insert k res
begin
set k = k - 1
if k == 0
begin
set res = string ABC
end
else
begin
comment res = "(A " + insert(k) + " B " + insert(k) + " C)"
set res = string A + insert k res + string B + insert k res + string C
end
return res
end function
set res = string
set res = insert k res
comment print(res)
print r... | def insert(k, res):
k -= 1
if k == 0:
res = "ABC"
else:
# res = "(A " + insert(k) + " B " + insert(k) + " C)"
res = "A" + insert(k, res) + "B" + insert(k, res) + "C"
return res
res = ""
res = insert(k, res)
# print(res)
print(res[s-1:t])
| Python | zaydzuhri_stack_edu_python |
function fact n
begin
if n <= 1
begin
return 1
end
else
begin
return n * call fact n - 1
end
end function
set a = call fact 100
set s = string a
set total = 0
for i in range length s
begin
set total = total + integer s at i
end
print total | def fact(n):
if n <= 1:
return 1
else:
return n * fact(n-1)
a = fact(100)
s = str(a)
total = 0
for i in range(len(s)):
total += int(s[i])
print(total) | Python | zaydzuhri_stack_edu_python |
function read_png filename
begin
set image_raw = call read_file filename
set image = call decode_image image_raw channels=3
set image = call cast image float32
set image = image / 255.0
set basename = call py_function lambda s -> base name path decode call numpy string utf-8 inp=list filename Tout=string
return tuple b... | def read_png(filename):
image_raw = tf.io.read_file(filename)
image = tf.image.decode_image(image_raw, channels=3)
image = tf.cast(image, tf.float32)
image = image / 255.
basename = tf.py_function(lambda s: os.path.basename(s.numpy().decode('utf-8')),
inp=[filename],
... | Python | nomic_cornstack_python_v1 |
string Write a program to find the largest possible rectangle of letters such that every row forms a word (reading left to right) and every column forms a word (reading top to bottom). Words should appear in this dictionary: WORD.LST (1.66MB). Heuristic solutions that may not always produce a provably optimal rectangle... | """
Write a program to find the largest possible rectangle of letters such that every row forms a word (reading left to right) and every column forms a word (reading top to bottom).
Words should appear in this dictionary: WORD.LST (1.66MB).
Heuristic solutions that may not always produce a provably optimal rectangle wi... | Python | zaydzuhri_stack_edu_python |
function mock_device device_id name is_online=true device_type_name=none
begin
set device = call MagicMock
set device_id = call PropertyMock return_value=device_id
set name = call PropertyMock return_value=name
set is_online = call PropertyMock return_value=is_online
set device_type = call PropertyMock return_value=dic... | def mock_device(device_id, name, is_online=True, device_type_name=None):
device = MagicMock()
type(device).device_id = PropertyMock(return_value=device_id)
type(device).name = PropertyMock(return_value=name)
type(device).is_online = PropertyMock(return_value=is_online)
type(device).device_type = Pro... | Python | nomic_cornstack_python_v1 |
function handleCommunications self
begin
call callAllCallbacks connection
try
begin
while true
begin
set message = call recv 2048
if message == b''
begin
close socket
break
end
call callAllCallbacks message message
end
end
except Exception as e
begin
close socket
call callAllCallbacks error e
end
finally
begin
call cal... | def handleCommunications(self):
self.connection.callAllCallbacks(HandlerType.connection)
try:
while True:
message = self.socket.recv(2048)
if message == b'':
self.socket.close()
break
self.connection.call... | Python | nomic_cornstack_python_v1 |
function get_page self page_id
begin
return call Page page_id user_id site_id
end function | def get_page(self, page_id):
return Page(page_id, self.user_id, self.site_id) | Python | nomic_cornstack_python_v1 |
import discord
from random import randint , shuffle
from scenes import scenes , images
from discord.ext import commands
import config
set bot = call Bot command_prefix=prefix
set players_list = list
set gameinfo = dict string started false ; string map none ; string spy none
decorator call command
async function ping ... | import discord
from random import randint, shuffle
from scenes import scenes, images
from discord.ext import commands
import config
bot = commands.Bot(command_prefix=config.prefix)
players_list = []
gameinfo = {"started":False, "map":None, 'spy':None}
@bot.command()
async def ping(ctx):
await ctx.send('Pong! {0... | Python | zaydzuhri_stack_edu_python |
function validate_price_precision value currency=none
begin
comment check no needed when there is no value
if not value
begin
return
end
set currency_fraction = call get_currency_fraction currency or DEFAULT_CURRENCY
set value = call normalize
if absolute exponent > currency_fraction
begin
raise call ValidationError st... | def validate_price_precision(value: Optional["Decimal"], currency: str = None):
# check no needed when there is no value
if not value:
return
currency_fraction = get_currency_fraction(currency or settings.DEFAULT_CURRENCY)
value = value.normalize()
if abs(value.as_tuple().exponent) > curre... | Python | nomic_cornstack_python_v1 |
class Settings
begin
string main game settings class
function __init__ self
begin
string init static game settings
comment screen params
set screen_width = 900
set screen_height = 700
set bg_color = tuple 230 230 230
comment ship params
set ship_limit = 3
comment bullet params
set bullet_width = 3
set bullet_height = 1... | class Settings:
""" main game settings class """
def __init__(self):
""" init static game settings """
# screen params
self.screen_width = 900
self.screen_height = 700
self.bg_color = (230, 230, 230)
# ship params
self.ship_limit = 3
# bullet pa... | Python | zaydzuhri_stack_edu_python |
string batch_real.py - converting and batching our data for the real numbered angles author : Benjamin Blundell email : me@benjamin.computer
import os , math , pickle
import numpy as np
import tensorflow as tf
from random import randint
comment Import common items
set parentdir = directory name path directory name path... | """
batch_real.py - converting and batching our data for the real numbered angles
author : Benjamin Blundell
email : me@benjamin.computer
"""
import os, math, pickle
import numpy as np
import tensorflow as tf
from random import randint
# Import common items
parentdir = os.path.dirname(os.path.dirname(os.path.abspath... | Python | zaydzuhri_stack_edu_python |
function write
begin
title st string All about me..!!
call markdown string :large_blue_diamond: **Data Engineer** The current role revolves around working with database management(AWS Redshift), automation of tasks (using Python), and helping out other teams at work with required data for BI reports. This involves me w... | def write():
st.title("All about me..!!")
st.markdown(
"""
:large_blue_diamond: **Data Engineer**\n
The current role revolves around working with database management(AWS Redshift), automation of tasks (using Python), and helping out other teams at work with required data for BI reports. Th... | Python | nomic_cornstack_python_v1 |
function elastic_data_sync from_ts to_ts conn_obj idx type
begin
if from_ts
begin
set query = dict string _id dict string $gt from_ts ; string $lte to_ts
end
else
begin
set query = dict string _id dict string $lte to_ts
end
set pkg_meta = find conn_obj query
comment Call elasticsearch bulk insert with mongo cursor
set ... | def elastic_data_sync(from_ts, to_ts, conn_obj, idx, type):
if from_ts:
query = {"_id": {"$gt": from_ts, "$lte": to_ts}}
else:
query = {"_id": {"$lte": to_ts}}
pkg_meta = conn_obj.find(query)
#Call elasticsearch bulk insert with mongo cursor
data = {"data_iter": pkg_meta, "index": id... | Python | nomic_cornstack_python_v1 |
function test_parlour_two
begin
set response = get call test_client string /show-menu
assert status_code == 200
end function | def test_parlour_two():
response = PizzaParlour.app.test_client().get('/show-menu')
assert response.status_code == 200 | Python | nomic_cornstack_python_v1 |
while x < length frase
begin
if frase at x == string a
begin
set a = a + 1
end
else
if frase at x == string
begin
set branco = branco + 1
end
set x = x + 1
end
string for x in range(len(frase)): if frase[x]=='a': a=a+1 elif frase==' ': branco=branco+1 x=x+1
string for car in frase: if car =='a': a = a+1 elif car == ' ... | while x<len(frase):
if frase[x] == 'a':
a=a+1
elif frase[x]==' ':
branco = branco+1
x=x+1
'''
for x in range(len(frase)):
if frase[x]=='a':
a=a+1
elif frase==' ':
branco=branco+1
x=x+1
'''
'''
for car in frase:
if car =='a':
a = a+1
elif car == ' ':
branco =branco+1
'''
prin... | Python | zaydzuhri_stack_edu_python |
function plot_arrow x y z=none col=string r width=2 arrow_size=40
begin
comment 2D Arrow
if z is none or not has attribute call gca string get_zlim
begin
set x0 = x at 0
set y0 = y at 0
set dx = x at 1 - x at 0
set dy = y at 1 - y at 0
call arrow x0 y0 dx dy width=arrow_size / 4000.0 color=col length_includes_head=true... | def plot_arrow(x, y, z=None, col='r', width=2, arrow_size=40):
# 2D Arrow
if z is None or not hasattr(plt.gca(), 'get_zlim'):
x0 = x[0]
y0 = y[0]
dx = x[1] - x[0]
dy = y[1] - y[0]
plt.arrow(x0, y0, dx, dy, width=arrow_size / 4000.0, color=col, length_includes_head=True)... | Python | nomic_cornstack_python_v1 |
import socket
set HOST = string pi1
set PORT = 8888
set ADDR = tuple HOST PORT
set BUF_SIZE = 1024
set server = call socket AF_INET SOCK_STREAM
call bind ADDR
call listen 1
set tuple conn addr = call accept | import socket
HOST='pi1'
PORT=8888
ADDR=(HOST,PORT)
BUF_SIZE=1024
server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(ADDR)
server.listen(1)
conn,addr = server.accept() | Python | zaydzuhri_stack_edu_python |
string Modulo de integracao com a API do Genius.
import requests
comment env
set TOKEN = string 15wkAF8IJKq621Qrvjr8zXIjBx_1Qs5rdUCiC5nvJpTA_QAcShPhymvusPGV6vKD
set API = string https://api.genius.com
set RESOURCE_SEARCH = string /search?q=
set AUTH = dict string Authorization string Bearer { TOKEN }
function search q
... | """
Modulo de integracao com a API do Genius.
"""
import requests
TOKEN = '15wkAF8IJKq621Qrvjr8zXIjBx_1Qs5rdUCiC5nvJpTA_QAcShPhymvusPGV6vKD' # env
API = 'https://api.genius.com'
RESOURCE_SEARCH = '/search?q='
AUTH = {'Authorization': f'Bearer {TOKEN}'}
def search(q):
"""
Faz uma busca para o endpoint /sear... | Python | zaydzuhri_stack_edu_python |
import ftplib
import os
import json
import datetime
from datetime import datetime , date
import time
import shutil
function main
begin
global arquivo
set conf = read open string config.json
set configuracao = loads conf
set host = string configuracao at string host
set user = configuracao at string user
set passw = con... | import ftplib
import os
import json
import datetime
from datetime import datetime, date
import time
import shutil
def main():
global arquivo
conf=open('config.json').read()
configuracao=json.loads(conf)
host=str(configuracao['host'])
user=configuracao['user']
passw=configuracao['passw']
or... | Python | zaydzuhri_stack_edu_python |
function make_scatterplot filename analysis base_id reference=string terms_full outfile=none n_voxels=none x_lab=string Uploaded Image y_lab=none gene_masks=false
begin
try
begin
comment Get the data
set x = call load_image masker filename
comment y = get_decoder_analysis_data(make_scatterplot.dd, analysis)
set ref = r... | def make_scatterplot(filename, analysis, base_id, reference='terms_full',
outfile=None, n_voxels=None,
x_lab="Uploaded Image", y_lab=None, gene_masks=False):
try:
# Get the data
x = load_image(make_scatterplot.masker, filename)
# y = get_decoder_anal... | Python | nomic_cornstack_python_v1 |
import numpy as np
function calculate list
begin
if length list != 9
begin
raise call ValueError string List must contain nine numbers.
end
set nplist = array list
set nplist = reshape np list tuple 3 3
set calculations = call fromkeys list string mean string variance string standard deviation string max string min str... | import numpy as np
def calculate(list):
if len(list) != 9:
raise ValueError("List must contain nine numbers.")
nplist = np.array(list)
nplist = np.reshape(list, (3, 3))
calculations = dict.fromkeys(["mean", "variance", "standard deviation", "max", "min", "sum"])
means = [np.mean(nplist... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
comment Parameters are stored in config
set host = get config string METASPLOIT string host fallback=string 127.0.0.1
set port = get config string METASPLOIT string port fallback=55552
set uri = get config string METASPLOIT string uri fallback=string /api/
set username = get config string M... | def __init__(self):
# Parameters are stored in config
host = config.get('METASPLOIT', 'host', fallback='127.0.0.1')
port = config.get('METASPLOIT', 'port', fallback=55552)
uri = config.get('METASPLOIT', 'uri', fallback="/api/")
self.username = config.get('METASPLOIT', 'user', fa... | Python | nomic_cornstack_python_v1 |
function _test_equivalence self r1 aa1
begin
set resname = call get_resname
set resname = protein_letters_3to1 at resname
assert aa1 == resname
end function | def _test_equivalence(self, r1, aa1):
resname = r1.get_resname()
resname = SCOPData.protein_letters_3to1[resname]
assert aa1 == resname | Python | nomic_cornstack_python_v1 |
function addAtHead self val
begin
set node = call ListNode val
if head == none
begin
set head = node
end
else
begin
set next = head
set head = node
end
end function | def addAtHead(self, val):
node = ListNode(val)
if self.head == None:
self.head = node
else:
node.next = self.head
self.head = node | Python | nomic_cornstack_python_v1 |
function get_labels user
begin
set status_labels = filter super_organization__in=all
set labels = list
for label in status_labels
begin
append labels dict string name name ; string color color ; string id pk
end
return labels
end function | def get_labels(user):
status_labels = StatusLabel.objects.filter(
super_organization__in=user.orgs.all()
)
labels = []
for label in status_labels:
labels.append({
'name': label.name,
'color': label.color,
'id': label.pk,
})
return labels | Python | nomic_cornstack_python_v1 |
function call self method **params
begin
if method == string info
begin
set url = format string /api/3/{} method
end
else
begin
comment method: ticker, depth, trades
set url = format string /api/3/{}/{} method pairs
end
return call apirequest url keyword params
end function | def call(self, method, **params):
if method == 'info':
url = '/api/3/{}'.format(method)
else: # method: ticker, depth, trades
url = '/api/3/{}/{}'.format(method, self.pairs)
return self.apirequest(url, **params) | Python | nomic_cornstack_python_v1 |
function dice_move_import self pathway_matrix
begin
for i in range nodes
begin
for k in range 1 7
begin
if i + k < nodes
begin
set pathway_matrix at i at i + k = 1
end
end
end
end function | def dice_move_import(self, pathway_matrix):
for i in range(self.nodes):
for k in range(1,7):
if i + k < self.nodes:
pathway_matrix[i][i+k] = 1 | Python | nomic_cornstack_python_v1 |
async function addship self ctx user1 user2=none percentage=0
begin
set user2 = user2 or author
set percentage = max list min list percentage * 100 10000 - 10000
async_with call Database as db
begin
await call db string INSERT INTO ship_percentages (user_id_1, user_id_2, percentage) VALUES ($1, $2, $3) ON CONFLICT (use... | async def addship(self, ctx: vbu.Context, user1: discord.Member, user2: discord.Member = None, percentage: float = 0):
user2 = user2 or ctx.author
percentage = max([min([percentage * 100, 10_000]), -10_000])
async with vbu.Database() as db:
await db(
"""INSERT INTO s... | Python | nomic_cornstack_python_v1 |
function test_invalid_fps_init_raises self get_patch
begin
try
begin
set cf = call ImageRefreshCamFeeder rdb string wilsat string archimedes string http://fake.com/image.jpg 0 0
end
except any
begin
pass
end
try else
begin
call fail string Exception was expected
end
end function | def test_invalid_fps_init_raises(self, get_patch):
try:
self.cf = ImageRefreshCamFeeder(self.rdb, 'wilsat', 'archimedes', 'http://fake.com/image.jpg', 0,
0)
except:
pass
else:
self.fail("Exception was expected") | Python | nomic_cornstack_python_v1 |
print string Example 1::
set dictionary = dict string basket list 1 2 3 ; string name string Ayush ; string Hii string Hello
print string basket in dictionary
print string age in dictionary
print string Example 2::
print string basket in keys dictionary
print string Ayush in values dictionary
print items dictionary
pri... | print('Example 1::')
dictionary = {
'basket' : [1,2,3],
'name' : 'Ayush',
'Hii' : 'Hello'
}
print('basket' in dictionary)
print('age' in dictionary)
print('Example 2::')
print('basket' in dictionary.keys())
print('Ayush' in dictionary.values())
print(dictionary.items())
print('Example 3::')
... | Python | zaydzuhri_stack_edu_python |
import time
import json
import requests
import MySQLdb
import threading
import sqlalchemy
import glob
import sys
import tables
import queue
import os
import pandas as pd
from sqlalchemy import create_engine
from datetime import datetime , timedelta
from pandas.io.json import json_normalize
string This program takes rec... | import time
import json
import requests
import MySQLdb
import threading
import sqlalchemy
import glob
import sys
import tables
import queue
import os
import pandas as pd
from sqlalchemy import create_engine
from datetime import datetime, timedelta
from pandas.io.json import json_normalize
"""
This program takes record... | Python | zaydzuhri_stack_edu_python |
function get_attr_wrapped_model model attr allow_none=true
begin
if is instance model list
begin
raise call RuntimeError string _get_attr_wrapped_model given a list of models
end
if allow_none
begin
function condition model attr
begin
return not has attribute model attr
end function
end
else
begin
function condition mo... | def get_attr_wrapped_model(model, attr, allow_none=True):
if isinstance(model, list):
raise RuntimeError("_get_attr_wrapped_model given a list of models")
if allow_none:
def condition(model, attr):
return not hasattr(model, attr)
else:
def condition(model, attr):
... | 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.